PackageManagerService.java revision cd251fa382e887f59c278d4d7cd0a858812c6114
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.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 147import android.os.RemoteCallbackList; 148import android.os.RemoteException; 149import android.os.SELinux; 150import android.os.ServiceManager; 151import android.os.SystemClock; 152import android.os.SystemProperties; 153import android.os.UserHandle; 154import android.os.UserManager; 155import android.os.storage.IMountService; 156import android.os.storage.StorageEventListener; 157import android.os.storage.StorageManager; 158import android.os.storage.VolumeInfo; 159import android.os.storage.VolumeRecord; 160import android.security.KeyStore; 161import android.security.SystemKeyStore; 162import android.system.ErrnoException; 163import android.system.Os; 164import android.system.StructStat; 165import android.text.TextUtils; 166import android.text.format.DateUtils; 167import android.util.ArrayMap; 168import android.util.ArraySet; 169import android.util.AtomicFile; 170import android.util.DisplayMetrics; 171import android.util.EventLog; 172import android.util.ExceptionUtils; 173import android.util.Log; 174import android.util.LogPrinter; 175import android.util.MathUtils; 176import android.util.PrintStreamPrinter; 177import android.util.Slog; 178import android.util.SparseArray; 179import android.util.SparseBooleanArray; 180import android.util.SparseIntArray; 181import android.util.Xml; 182import android.view.Display; 183 184import dalvik.system.DexFile; 185import dalvik.system.VMRuntime; 186 187import libcore.io.IoUtils; 188import libcore.util.EmptyArray; 189 190import com.android.internal.R; 191import com.android.internal.app.IMediaContainerService; 192import com.android.internal.app.ResolverActivity; 193import com.android.internal.content.NativeLibraryHelper; 194import com.android.internal.content.PackageHelper; 195import com.android.internal.os.IParcelFileDescriptorFactory; 196import com.android.internal.os.SomeArgs; 197import com.android.internal.util.ArrayUtils; 198import com.android.internal.util.FastPrintWriter; 199import com.android.internal.util.FastXmlSerializer; 200import com.android.internal.util.IndentingPrintWriter; 201import com.android.internal.util.Preconditions; 202import com.android.server.EventLogTags; 203import com.android.server.FgThread; 204import com.android.server.IntentResolver; 205import com.android.server.LocalServices; 206import com.android.server.ServiceThread; 207import com.android.server.SystemConfig; 208import com.android.server.Watchdog; 209import com.android.server.pm.Settings.DatabaseVersion; 210import com.android.server.pm.PermissionsState.PermissionState; 211import com.android.server.storage.DeviceStorageMonitorInternal; 212 213import org.xmlpull.v1.XmlPullParser; 214import org.xmlpull.v1.XmlSerializer; 215 216import java.io.BufferedInputStream; 217import java.io.BufferedOutputStream; 218import java.io.BufferedReader; 219import java.io.ByteArrayInputStream; 220import java.io.ByteArrayOutputStream; 221import java.io.File; 222import java.io.FileDescriptor; 223import java.io.FileNotFoundException; 224import java.io.FileOutputStream; 225import java.io.FileReader; 226import java.io.FilenameFilter; 227import java.io.IOException; 228import java.io.InputStream; 229import java.io.PrintWriter; 230import java.nio.charset.StandardCharsets; 231import java.security.NoSuchAlgorithmException; 232import java.security.PublicKey; 233import java.security.cert.CertificateEncodingException; 234import java.security.cert.CertificateException; 235import java.text.SimpleDateFormat; 236import java.util.ArrayList; 237import java.util.Arrays; 238import java.util.Collection; 239import java.util.Collections; 240import java.util.Comparator; 241import java.util.Date; 242import java.util.Iterator; 243import java.util.List; 244import java.util.Map; 245import java.util.Objects; 246import java.util.Set; 247import java.util.concurrent.CountDownLatch; 248import java.util.concurrent.TimeUnit; 249import java.util.concurrent.atomic.AtomicBoolean; 250import java.util.concurrent.atomic.AtomicInteger; 251import java.util.concurrent.atomic.AtomicLong; 252 253/** 254 * Keep track of all those .apks everywhere. 255 * 256 * This is very central to the platform's security; please run the unit 257 * tests whenever making modifications here: 258 * 259mmm frameworks/base/tests/AndroidTests 260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 262 * 263 * {@hide} 264 */ 265public class PackageManagerService extends IPackageManager.Stub { 266 static final String TAG = "PackageManager"; 267 static final boolean DEBUG_SETTINGS = false; 268 static final boolean DEBUG_PREFERRED = false; 269 static final boolean DEBUG_UPGRADE = false; 270 private static final boolean DEBUG_BACKUP = true; 271 private static final boolean DEBUG_INSTALL = false; 272 private static final boolean DEBUG_REMOVE = false; 273 private static final boolean DEBUG_BROADCASTS = false; 274 private static final boolean DEBUG_SHOW_INFO = false; 275 private static final boolean DEBUG_PACKAGE_INFO = false; 276 private static final boolean DEBUG_INTENT_MATCHING = false; 277 private static final boolean DEBUG_PACKAGE_SCANNING = false; 278 private static final boolean DEBUG_VERIFY = false; 279 private static final boolean DEBUG_DEXOPT = false; 280 private static final boolean DEBUG_ABI_SELECTION = false; 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 private static final int[] EMPTY_INT_ARRAY = new int[0]; 310 311 /** 312 * Timeout (in milliseconds) after which the watchdog should declare that 313 * our handler thread is wedged. The usual default for such things is one 314 * minute but we sometimes do very lengthy I/O operations on this thread, 315 * such as installing multi-gigabyte applications, so ours needs to be longer. 316 */ 317 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 318 319 /** 320 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 321 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 322 * settings entry if available, otherwise we use the hardcoded default. If it's been 323 * more than this long since the last fstrim, we force one during the boot sequence. 324 * 325 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 326 * one gets run at the next available charging+idle time. This final mandatory 327 * no-fstrim check kicks in only of the other scheduling criteria is never met. 328 */ 329 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 330 331 /** 332 * Whether verification is enabled by default. 333 */ 334 private static final boolean DEFAULT_VERIFY_ENABLE = true; 335 336 /** 337 * The default maximum time to wait for the verification agent to return in 338 * milliseconds. 339 */ 340 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 341 342 /** 343 * The default response for package verification timeout. 344 * 345 * This can be either PackageManager.VERIFICATION_ALLOW or 346 * PackageManager.VERIFICATION_REJECT. 347 */ 348 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 349 350 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 351 352 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 353 DEFAULT_CONTAINER_PACKAGE, 354 "com.android.defcontainer.DefaultContainerService"); 355 356 private static final String KILL_APP_REASON_GIDS_CHANGED = 357 "permission grant or revoke changed gids"; 358 359 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 360 "permissions revoked"; 361 362 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 363 364 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 365 366 /** Permission grant: not grant the permission. */ 367 private static final int GRANT_DENIED = 1; 368 369 /** Permission grant: grant the permission as an install permission. */ 370 private static final int GRANT_INSTALL = 2; 371 372 /** Permission grant: grant the permission as an install permission for a legacy app. */ 373 private static final int GRANT_INSTALL_LEGACY = 3; 374 375 /** Permission grant: grant the permission as a runtime one. */ 376 private static final int GRANT_RUNTIME = 4; 377 378 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 379 private static final int GRANT_UPGRADE = 5; 380 381 final ServiceThread mHandlerThread; 382 383 final PackageHandler mHandler; 384 385 /** 386 * Messages for {@link #mHandler} that need to wait for system ready before 387 * being dispatched. 388 */ 389 private ArrayList<Message> mPostSystemReadyMessages; 390 391 final int mSdkVersion = Build.VERSION.SDK_INT; 392 393 final Context mContext; 394 final boolean mFactoryTest; 395 final boolean mOnlyCore; 396 final boolean mLazyDexOpt; 397 final long mDexOptLRUThresholdInMills; 398 final DisplayMetrics mMetrics; 399 final int mDefParseFlags; 400 final String[] mSeparateProcesses; 401 final boolean mIsUpgrade; 402 403 // This is where all application persistent data goes. 404 final File mAppDataDir; 405 406 // This is where all application persistent data goes for secondary users. 407 final File mUserAppDataDir; 408 409 /** The location for ASEC container files on internal storage. */ 410 final String mAsecInternalPath; 411 412 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 413 // LOCK HELD. Can be called with mInstallLock held. 414 final Installer mInstaller; 415 416 /** Directory where installed third-party apps stored */ 417 final File mAppInstallDir; 418 419 /** 420 * Directory to which applications installed internally have their 421 * 32 bit native libraries copied. 422 */ 423 private File mAppLib32InstallDir; 424 425 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 426 // apps. 427 final File mDrmAppPrivateInstallDir; 428 429 // ---------------------------------------------------------------- 430 431 // Lock for state used when installing and doing other long running 432 // operations. Methods that must be called with this lock held have 433 // the suffix "LI". 434 final Object mInstallLock = new Object(); 435 436 // ---------------------------------------------------------------- 437 438 // Keys are String (package name), values are Package. This also serves 439 // as the lock for the global state. Methods that must be called with 440 // this lock held have the prefix "LP". 441 final ArrayMap<String, PackageParser.Package> mPackages = 442 new ArrayMap<String, PackageParser.Package>(); 443 444 // Tracks available target package names -> overlay package paths. 445 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 446 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 447 448 final Settings mSettings; 449 boolean mRestoredSettings; 450 451 // System configuration read by SystemConfig. 452 final int[] mGlobalGids; 453 final SparseArray<ArraySet<String>> mSystemPermissions; 454 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 455 456 // If mac_permissions.xml was found for seinfo labeling. 457 boolean mFoundPolicyFile; 458 459 // If a recursive restorecon of /data/data/<pkg> is needed. 460 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 461 462 public static final class SharedLibraryEntry { 463 public final String path; 464 public final String apk; 465 466 SharedLibraryEntry(String _path, String _apk) { 467 path = _path; 468 apk = _apk; 469 } 470 } 471 472 // Currently known shared libraries. 473 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 474 new ArrayMap<String, SharedLibraryEntry>(); 475 476 // All available activities, for your resolving pleasure. 477 final ActivityIntentResolver mActivities = 478 new ActivityIntentResolver(); 479 480 // All available receivers, for your resolving pleasure. 481 final ActivityIntentResolver mReceivers = 482 new ActivityIntentResolver(); 483 484 // All available services, for your resolving pleasure. 485 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 486 487 // All available providers, for your resolving pleasure. 488 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 489 490 // Mapping from provider base names (first directory in content URI codePath) 491 // to the provider information. 492 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 493 new ArrayMap<String, PackageParser.Provider>(); 494 495 // Mapping from instrumentation class names to info about them. 496 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 497 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 498 499 // Mapping from permission names to info about them. 500 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 501 new ArrayMap<String, PackageParser.PermissionGroup>(); 502 503 // Packages whose data we have transfered into another package, thus 504 // should no longer exist. 505 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 506 507 // Broadcast actions that are only available to the system. 508 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 509 510 /** List of packages waiting for verification. */ 511 final SparseArray<PackageVerificationState> mPendingVerification 512 = new SparseArray<PackageVerificationState>(); 513 514 /** Set of packages associated with each app op permission. */ 515 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 516 517 final PackageInstallerService mInstallerService; 518 519 private final PackageDexOptimizer mPackageDexOptimizer; 520 521 private AtomicInteger mNextMoveId = new AtomicInteger(); 522 private final MoveCallbacks mMoveCallbacks; 523 524 // Cache of users who need badging. 525 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 526 527 /** Token for keys in mPendingVerification. */ 528 private int mPendingVerificationToken = 0; 529 530 volatile boolean mSystemReady; 531 volatile boolean mSafeMode; 532 volatile boolean mHasSystemUidErrors; 533 534 ApplicationInfo mAndroidApplication; 535 final ActivityInfo mResolveActivity = new ActivityInfo(); 536 final ResolveInfo mResolveInfo = new ResolveInfo(); 537 ComponentName mResolveComponentName; 538 PackageParser.Package mPlatformPackage; 539 ComponentName mCustomResolverComponentName; 540 541 boolean mResolverReplaced = false; 542 543 private final ComponentName mIntentFilterVerifierComponent; 544 private int mIntentFilterVerificationToken = 0; 545 546 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 547 = new SparseArray<IntentFilterVerificationState>(); 548 549 private interface IntentFilterVerifier<T extends IntentFilter> { 550 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 551 T filter, String packageName); 552 void startVerifications(int userId); 553 void receiveVerificationResponse(int verificationId); 554 } 555 556 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 557 private Context mContext; 558 private ComponentName mIntentFilterVerifierComponent; 559 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 560 561 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 562 mContext = context; 563 mIntentFilterVerifierComponent = verifierComponent; 564 } 565 566 private String getDefaultScheme() { 567 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 568 return IntentFilter.SCHEME_HTTP; 569 } 570 571 @Override 572 public void startVerifications(int userId) { 573 // Launch verifications requests 574 int count = mCurrentIntentFilterVerifications.size(); 575 for (int n=0; n<count; n++) { 576 int verificationId = mCurrentIntentFilterVerifications.get(n); 577 final IntentFilterVerificationState ivs = 578 mIntentFilterVerificationStates.get(verificationId); 579 580 String packageName = ivs.getPackageName(); 581 582 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 583 final int filterCount = filters.size(); 584 ArraySet<String> domainsSet = new ArraySet<>(); 585 for (int m=0; m<filterCount; m++) { 586 PackageParser.ActivityIntentInfo filter = filters.get(m); 587 domainsSet.addAll(filter.getHostsList()); 588 } 589 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 590 synchronized (mPackages) { 591 if (mSettings.createIntentFilterVerificationIfNeededLPw( 592 packageName, domainsList) != null) { 593 scheduleWriteSettingsLocked(); 594 } 595 } 596 sendVerificationRequest(userId, verificationId, ivs); 597 } 598 mCurrentIntentFilterVerifications.clear(); 599 } 600 601 private void sendVerificationRequest(int userId, int verificationId, 602 IntentFilterVerificationState ivs) { 603 604 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 605 verificationIntent.putExtra( 606 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 607 verificationId); 608 verificationIntent.putExtra( 609 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 610 getDefaultScheme()); 611 verificationIntent.putExtra( 612 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 613 ivs.getHostsString()); 614 verificationIntent.putExtra( 615 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 616 ivs.getPackageName()); 617 verificationIntent.setComponent(mIntentFilterVerifierComponent); 618 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 619 620 UserHandle user = new UserHandle(userId); 621 mContext.sendBroadcastAsUser(verificationIntent, user); 622 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 623 } 624 625 public void receiveVerificationResponse(int verificationId) { 626 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 627 628 final boolean verified = ivs.isVerified(); 629 630 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 631 final int count = filters.size(); 632 for (int n=0; n<count; n++) { 633 PackageParser.ActivityIntentInfo filter = filters.get(n); 634 filter.setVerified(verified); 635 636 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 637 + verified + " and hosts:" + ivs.getHostsString()); 638 } 639 640 mIntentFilterVerificationStates.remove(verificationId); 641 642 final String packageName = ivs.getPackageName(); 643 IntentFilterVerificationInfo ivi = null; 644 645 synchronized (mPackages) { 646 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 647 } 648 if (ivi == null) { 649 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 650 + verificationId + " packageName:" + packageName); 651 return; 652 } 653 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 654 + verificationId); 655 656 synchronized (mPackages) { 657 if (verified) { 658 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 659 } else { 660 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 661 } 662 scheduleWriteSettingsLocked(); 663 664 final int userId = ivs.getUserId(); 665 if (userId != UserHandle.USER_ALL) { 666 final int userStatus = 667 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 668 669 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 670 boolean needUpdate = false; 671 672 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 673 // already been set by the User thru the Disambiguation dialog 674 switch (userStatus) { 675 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 676 if (verified) { 677 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 678 } else { 679 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 680 } 681 needUpdate = true; 682 break; 683 684 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 685 if (verified) { 686 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 687 needUpdate = true; 688 } 689 break; 690 691 default: 692 // Nothing to do 693 } 694 695 if (needUpdate) { 696 mSettings.updateIntentFilterVerificationStatusLPw( 697 packageName, updatedStatus, userId); 698 scheduleWritePackageRestrictionsLocked(userId); 699 } 700 } 701 } 702 } 703 704 @Override 705 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 706 ActivityIntentInfo filter, String packageName) { 707 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 708 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 709 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 710 return false; 711 } 712 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 713 if (ivs == null) { 714 ivs = createDomainVerificationState(verifierId, userId, verificationId, 715 packageName); 716 } 717 if (!hasValidDomains(filter)) { 718 return false; 719 } 720 ivs.addFilter(filter); 721 return true; 722 } 723 724 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 725 int userId, int verificationId, String packageName) { 726 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 727 verifierId, userId, packageName); 728 ivs.setPendingState(); 729 synchronized (mPackages) { 730 mIntentFilterVerificationStates.append(verificationId, ivs); 731 mCurrentIntentFilterVerifications.add(verificationId); 732 } 733 return ivs; 734 } 735 } 736 737 private static boolean hasValidDomains(ActivityIntentInfo filter) { 738 return hasValidDomains(filter, true); 739 } 740 741 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 742 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 743 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 744 if (!hasHTTPorHTTPS) { 745 if (logging) { 746 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 747 } 748 return false; 749 } 750 return true; 751 } 752 753 private IntentFilterVerifier mIntentFilterVerifier; 754 755 // Set of pending broadcasts for aggregating enable/disable of components. 756 static class PendingPackageBroadcasts { 757 // for each user id, a map of <package name -> components within that package> 758 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 759 760 public PendingPackageBroadcasts() { 761 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 762 } 763 764 public ArrayList<String> get(int userId, String packageName) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 return packages.get(packageName); 767 } 768 769 public void put(int userId, String packageName, ArrayList<String> components) { 770 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 771 packages.put(packageName, components); 772 } 773 774 public void remove(int userId, String packageName) { 775 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 776 if (packages != null) { 777 packages.remove(packageName); 778 } 779 } 780 781 public void remove(int userId) { 782 mUidMap.remove(userId); 783 } 784 785 public int userIdCount() { 786 return mUidMap.size(); 787 } 788 789 public int userIdAt(int n) { 790 return mUidMap.keyAt(n); 791 } 792 793 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 794 return mUidMap.get(userId); 795 } 796 797 public int size() { 798 // total number of pending broadcast entries across all userIds 799 int num = 0; 800 for (int i = 0; i< mUidMap.size(); i++) { 801 num += mUidMap.valueAt(i).size(); 802 } 803 return num; 804 } 805 806 public void clear() { 807 mUidMap.clear(); 808 } 809 810 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 811 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 812 if (map == null) { 813 map = new ArrayMap<String, ArrayList<String>>(); 814 mUidMap.put(userId, map); 815 } 816 return map; 817 } 818 } 819 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 820 821 // Service Connection to remote media container service to copy 822 // package uri's from external media onto secure containers 823 // or internal storage. 824 private IMediaContainerService mContainerService = null; 825 826 static final int SEND_PENDING_BROADCAST = 1; 827 static final int MCS_BOUND = 3; 828 static final int END_COPY = 4; 829 static final int INIT_COPY = 5; 830 static final int MCS_UNBIND = 6; 831 static final int START_CLEANING_PACKAGE = 7; 832 static final int FIND_INSTALL_LOC = 8; 833 static final int POST_INSTALL = 9; 834 static final int MCS_RECONNECT = 10; 835 static final int MCS_GIVE_UP = 11; 836 static final int UPDATED_MEDIA_STATUS = 12; 837 static final int WRITE_SETTINGS = 13; 838 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 839 static final int PACKAGE_VERIFIED = 15; 840 static final int CHECK_PENDING_VERIFICATION = 16; 841 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 842 static final int INTENT_FILTER_VERIFIED = 18; 843 844 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 845 846 // Delay time in millisecs 847 static final int BROADCAST_DELAY = 10 * 1000; 848 849 static UserManagerService sUserManager; 850 851 // Stores a list of users whose package restrictions file needs to be updated 852 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 853 854 final private DefaultContainerConnection mDefContainerConn = 855 new DefaultContainerConnection(); 856 class DefaultContainerConnection implements ServiceConnection { 857 public void onServiceConnected(ComponentName name, IBinder service) { 858 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 859 IMediaContainerService imcs = 860 IMediaContainerService.Stub.asInterface(service); 861 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 862 } 863 864 public void onServiceDisconnected(ComponentName name) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 866 } 867 }; 868 869 // Recordkeeping of restore-after-install operations that are currently in flight 870 // between the Package Manager and the Backup Manager 871 class PostInstallData { 872 public InstallArgs args; 873 public PackageInstalledInfo res; 874 875 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 876 args = _a; 877 res = _r; 878 } 879 }; 880 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 881 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 882 883 // backup/restore of preferred activity state 884 private static final String TAG_PREFERRED_BACKUP = "pa"; 885 886 private final String mRequiredVerifierPackage; 887 888 private final PackageUsage mPackageUsage = new PackageUsage(); 889 890 private class PackageUsage { 891 private static final int WRITE_INTERVAL 892 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 893 894 private final Object mFileLock = new Object(); 895 private final AtomicLong mLastWritten = new AtomicLong(0); 896 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 897 898 private boolean mIsHistoricalPackageUsageAvailable = true; 899 900 boolean isHistoricalPackageUsageAvailable() { 901 return mIsHistoricalPackageUsageAvailable; 902 } 903 904 void write(boolean force) { 905 if (force) { 906 writeInternal(); 907 return; 908 } 909 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 910 && !DEBUG_DEXOPT) { 911 return; 912 } 913 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 914 new Thread("PackageUsage_DiskWriter") { 915 @Override 916 public void run() { 917 try { 918 writeInternal(); 919 } finally { 920 mBackgroundWriteRunning.set(false); 921 } 922 } 923 }.start(); 924 } 925 } 926 927 private void writeInternal() { 928 synchronized (mPackages) { 929 synchronized (mFileLock) { 930 AtomicFile file = getFile(); 931 FileOutputStream f = null; 932 try { 933 f = file.startWrite(); 934 BufferedOutputStream out = new BufferedOutputStream(f); 935 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 936 StringBuilder sb = new StringBuilder(); 937 for (PackageParser.Package pkg : mPackages.values()) { 938 if (pkg.mLastPackageUsageTimeInMills == 0) { 939 continue; 940 } 941 sb.setLength(0); 942 sb.append(pkg.packageName); 943 sb.append(' '); 944 sb.append((long)pkg.mLastPackageUsageTimeInMills); 945 sb.append('\n'); 946 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 947 } 948 out.flush(); 949 file.finishWrite(f); 950 } catch (IOException e) { 951 if (f != null) { 952 file.failWrite(f); 953 } 954 Log.e(TAG, "Failed to write package usage times", e); 955 } 956 } 957 } 958 mLastWritten.set(SystemClock.elapsedRealtime()); 959 } 960 961 void readLP() { 962 synchronized (mFileLock) { 963 AtomicFile file = getFile(); 964 BufferedInputStream in = null; 965 try { 966 in = new BufferedInputStream(file.openRead()); 967 StringBuffer sb = new StringBuffer(); 968 while (true) { 969 String packageName = readToken(in, sb, ' '); 970 if (packageName == null) { 971 break; 972 } 973 String timeInMillisString = readToken(in, sb, '\n'); 974 if (timeInMillisString == null) { 975 throw new IOException("Failed to find last usage time for package " 976 + packageName); 977 } 978 PackageParser.Package pkg = mPackages.get(packageName); 979 if (pkg == null) { 980 continue; 981 } 982 long timeInMillis; 983 try { 984 timeInMillis = Long.parseLong(timeInMillisString.toString()); 985 } catch (NumberFormatException e) { 986 throw new IOException("Failed to parse " + timeInMillisString 987 + " as a long.", e); 988 } 989 pkg.mLastPackageUsageTimeInMills = timeInMillis; 990 } 991 } catch (FileNotFoundException expected) { 992 mIsHistoricalPackageUsageAvailable = false; 993 } catch (IOException e) { 994 Log.w(TAG, "Failed to read package usage times", e); 995 } finally { 996 IoUtils.closeQuietly(in); 997 } 998 } 999 mLastWritten.set(SystemClock.elapsedRealtime()); 1000 } 1001 1002 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1003 throws IOException { 1004 sb.setLength(0); 1005 while (true) { 1006 int ch = in.read(); 1007 if (ch == -1) { 1008 if (sb.length() == 0) { 1009 return null; 1010 } 1011 throw new IOException("Unexpected EOF"); 1012 } 1013 if (ch == endOfToken) { 1014 return sb.toString(); 1015 } 1016 sb.append((char)ch); 1017 } 1018 } 1019 1020 private AtomicFile getFile() { 1021 File dataDir = Environment.getDataDirectory(); 1022 File systemDir = new File(dataDir, "system"); 1023 File fname = new File(systemDir, "package-usage.list"); 1024 return new AtomicFile(fname); 1025 } 1026 } 1027 1028 class PackageHandler extends Handler { 1029 private boolean mBound = false; 1030 final ArrayList<HandlerParams> mPendingInstalls = 1031 new ArrayList<HandlerParams>(); 1032 1033 private boolean connectToService() { 1034 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1035 " DefaultContainerService"); 1036 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1038 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1039 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 mBound = true; 1042 return true; 1043 } 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 return false; 1046 } 1047 1048 private void disconnectService() { 1049 mContainerService = null; 1050 mBound = false; 1051 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1052 mContext.unbindService(mDefContainerConn); 1053 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1054 } 1055 1056 PackageHandler(Looper looper) { 1057 super(looper); 1058 } 1059 1060 public void handleMessage(Message msg) { 1061 try { 1062 doHandleMessage(msg); 1063 } finally { 1064 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1065 } 1066 } 1067 1068 void doHandleMessage(Message msg) { 1069 switch (msg.what) { 1070 case INIT_COPY: { 1071 HandlerParams params = (HandlerParams) msg.obj; 1072 int idx = mPendingInstalls.size(); 1073 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1074 // If a bind was already initiated we dont really 1075 // need to do anything. The pending install 1076 // will be processed later on. 1077 if (!mBound) { 1078 // If this is the only one pending we might 1079 // have to bind to the service again. 1080 if (!connectToService()) { 1081 Slog.e(TAG, "Failed to bind to media container service"); 1082 params.serviceError(); 1083 return; 1084 } else { 1085 // Once we bind to the service, the first 1086 // pending request will be processed. 1087 mPendingInstalls.add(idx, params); 1088 } 1089 } else { 1090 mPendingInstalls.add(idx, params); 1091 // Already bound to the service. Just make 1092 // sure we trigger off processing the first request. 1093 if (idx == 0) { 1094 mHandler.sendEmptyMessage(MCS_BOUND); 1095 } 1096 } 1097 break; 1098 } 1099 case MCS_BOUND: { 1100 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1101 if (msg.obj != null) { 1102 mContainerService = (IMediaContainerService) msg.obj; 1103 } 1104 if (mContainerService == null) { 1105 // Something seriously wrong. Bail out 1106 Slog.e(TAG, "Cannot bind to media container service"); 1107 for (HandlerParams params : mPendingInstalls) { 1108 // Indicate service bind error 1109 params.serviceError(); 1110 } 1111 mPendingInstalls.clear(); 1112 } else if (mPendingInstalls.size() > 0) { 1113 HandlerParams params = mPendingInstalls.get(0); 1114 if (params != null) { 1115 if (params.startCopy()) { 1116 // We are done... look for more work or to 1117 // go idle. 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Checking for more work or unbind..."); 1120 // Delete pending install 1121 if (mPendingInstalls.size() > 0) { 1122 mPendingInstalls.remove(0); 1123 } 1124 if (mPendingInstalls.size() == 0) { 1125 if (mBound) { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, 1127 "Posting delayed MCS_UNBIND"); 1128 removeMessages(MCS_UNBIND); 1129 Message ubmsg = obtainMessage(MCS_UNBIND); 1130 // Unbind after a little delay, to avoid 1131 // continual thrashing. 1132 sendMessageDelayed(ubmsg, 10000); 1133 } 1134 } else { 1135 // There are more pending requests in queue. 1136 // Just post MCS_BOUND message to trigger processing 1137 // of next pending install. 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, 1139 "Posting MCS_BOUND for next work"); 1140 mHandler.sendEmptyMessage(MCS_BOUND); 1141 } 1142 } 1143 } 1144 } else { 1145 // Should never happen ideally. 1146 Slog.w(TAG, "Empty queue"); 1147 } 1148 break; 1149 } 1150 case MCS_RECONNECT: { 1151 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1152 if (mPendingInstalls.size() > 0) { 1153 if (mBound) { 1154 disconnectService(); 1155 } 1156 if (!connectToService()) { 1157 Slog.e(TAG, "Failed to bind to media container service"); 1158 for (HandlerParams params : mPendingInstalls) { 1159 // Indicate service bind error 1160 params.serviceError(); 1161 } 1162 mPendingInstalls.clear(); 1163 } 1164 } 1165 break; 1166 } 1167 case MCS_UNBIND: { 1168 // If there is no actual work left, then time to unbind. 1169 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1170 1171 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1172 if (mBound) { 1173 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1174 1175 disconnectService(); 1176 } 1177 } else if (mPendingInstalls.size() > 0) { 1178 // There are more pending requests in queue. 1179 // Just post MCS_BOUND message to trigger processing 1180 // of next pending install. 1181 mHandler.sendEmptyMessage(MCS_BOUND); 1182 } 1183 1184 break; 1185 } 1186 case MCS_GIVE_UP: { 1187 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1188 mPendingInstalls.remove(0); 1189 break; 1190 } 1191 case SEND_PENDING_BROADCAST: { 1192 String packages[]; 1193 ArrayList<String> components[]; 1194 int size = 0; 1195 int uids[]; 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1197 synchronized (mPackages) { 1198 if (mPendingBroadcasts == null) { 1199 return; 1200 } 1201 size = mPendingBroadcasts.size(); 1202 if (size <= 0) { 1203 // Nothing to be done. Just return 1204 return; 1205 } 1206 packages = new String[size]; 1207 components = new ArrayList[size]; 1208 uids = new int[size]; 1209 int i = 0; // filling out the above arrays 1210 1211 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1212 int packageUserId = mPendingBroadcasts.userIdAt(n); 1213 Iterator<Map.Entry<String, ArrayList<String>>> it 1214 = mPendingBroadcasts.packagesForUserId(packageUserId) 1215 .entrySet().iterator(); 1216 while (it.hasNext() && i < size) { 1217 Map.Entry<String, ArrayList<String>> ent = it.next(); 1218 packages[i] = ent.getKey(); 1219 components[i] = ent.getValue(); 1220 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1221 uids[i] = (ps != null) 1222 ? UserHandle.getUid(packageUserId, ps.appId) 1223 : -1; 1224 i++; 1225 } 1226 } 1227 size = i; 1228 mPendingBroadcasts.clear(); 1229 } 1230 // Send broadcasts 1231 for (int i = 0; i < size; i++) { 1232 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1233 } 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1235 break; 1236 } 1237 case START_CLEANING_PACKAGE: { 1238 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1239 final String packageName = (String)msg.obj; 1240 final int userId = msg.arg1; 1241 final boolean andCode = msg.arg2 != 0; 1242 synchronized (mPackages) { 1243 if (userId == UserHandle.USER_ALL) { 1244 int[] users = sUserManager.getUserIds(); 1245 for (int user : users) { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(user, packageName, andCode)); 1248 } 1249 } else { 1250 mSettings.addPackageToCleanLPw( 1251 new PackageCleanItem(userId, packageName, andCode)); 1252 } 1253 } 1254 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1255 startCleaningPackages(); 1256 } break; 1257 case POST_INSTALL: { 1258 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1259 PostInstallData data = mRunningInstalls.get(msg.arg1); 1260 mRunningInstalls.delete(msg.arg1); 1261 boolean deleteOld = false; 1262 1263 if (data != null) { 1264 InstallArgs args = data.args; 1265 PackageInstalledInfo res = data.res; 1266 1267 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1268 res.removedInfo.sendBroadcast(false, true, false); 1269 Bundle extras = new Bundle(1); 1270 extras.putInt(Intent.EXTRA_UID, res.uid); 1271 1272 // Now that we successfully installed the package, grant runtime 1273 // permissions if requested before broadcasting the install. 1274 if ((args.installFlags 1275 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1276 grantRequestedRuntimePermissions(res.pkg, 1277 args.user.getIdentifier()); 1278 } 1279 1280 // Determine the set of users who are adding this 1281 // package for the first time vs. those who are seeing 1282 // an update. 1283 int[] firstUsers; 1284 int[] updateUsers = new int[0]; 1285 if (res.origUsers == null || res.origUsers.length == 0) { 1286 firstUsers = res.newUsers; 1287 } else { 1288 firstUsers = new int[0]; 1289 for (int i=0; i<res.newUsers.length; i++) { 1290 int user = res.newUsers[i]; 1291 boolean isNew = true; 1292 for (int j=0; j<res.origUsers.length; j++) { 1293 if (res.origUsers[j] == user) { 1294 isNew = false; 1295 break; 1296 } 1297 } 1298 if (isNew) { 1299 int[] newFirst = new int[firstUsers.length+1]; 1300 System.arraycopy(firstUsers, 0, newFirst, 0, 1301 firstUsers.length); 1302 newFirst[firstUsers.length] = user; 1303 firstUsers = newFirst; 1304 } else { 1305 int[] newUpdate = new int[updateUsers.length+1]; 1306 System.arraycopy(updateUsers, 0, newUpdate, 0, 1307 updateUsers.length); 1308 newUpdate[updateUsers.length] = user; 1309 updateUsers = newUpdate; 1310 } 1311 } 1312 } 1313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1314 res.pkg.applicationInfo.packageName, 1315 extras, null, null, firstUsers); 1316 final boolean update = res.removedInfo.removedPackage != null; 1317 if (update) { 1318 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1319 } 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 if (update) { 1324 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1325 res.pkg.applicationInfo.packageName, 1326 extras, null, null, updateUsers); 1327 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1328 null, null, 1329 res.pkg.applicationInfo.packageName, null, updateUsers); 1330 1331 // treat asec-hosted packages like removable media on upgrade 1332 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1333 if (DEBUG_INSTALL) { 1334 Slog.i(TAG, "upgrading pkg " + res.pkg 1335 + " is ASEC-hosted -> AVAILABLE"); 1336 } 1337 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1338 ArrayList<String> pkgList = new ArrayList<String>(1); 1339 pkgList.add(res.pkg.applicationInfo.packageName); 1340 sendResourcesChangedBroadcast(true, true, 1341 pkgList,uidArray, null); 1342 } 1343 } 1344 if (res.removedInfo.args != null) { 1345 // Remove the replaced package's older resources safely now 1346 deleteOld = true; 1347 } 1348 1349 // Log current value of "unknown sources" setting 1350 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1351 getUnknownSourcesSettings()); 1352 } 1353 // Force a gc to clear up things 1354 Runtime.getRuntime().gc(); 1355 // We delete after a gc for applications on sdcard. 1356 if (deleteOld) { 1357 synchronized (mInstallLock) { 1358 res.removedInfo.args.doPostDeleteLI(true); 1359 } 1360 } 1361 if (args.observer != null) { 1362 try { 1363 Bundle extras = extrasForInstallResult(res); 1364 args.observer.onPackageInstalled(res.name, res.returnCode, 1365 res.returnMsg, extras); 1366 } catch (RemoteException e) { 1367 Slog.i(TAG, "Observer no longer exists."); 1368 } 1369 } 1370 } else { 1371 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1372 } 1373 } break; 1374 case UPDATED_MEDIA_STATUS: { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1376 boolean reportStatus = msg.arg1 == 1; 1377 boolean doGc = msg.arg2 == 1; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1379 if (doGc) { 1380 // Force a gc to clear up stale containers. 1381 Runtime.getRuntime().gc(); 1382 } 1383 if (msg.obj != null) { 1384 @SuppressWarnings("unchecked") 1385 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1387 // Unload containers 1388 unloadAllContainers(args); 1389 } 1390 if (reportStatus) { 1391 try { 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1393 PackageHelper.getMountService().finishMediaUpdate(); 1394 } catch (RemoteException e) { 1395 Log.e(TAG, "MountService not running?"); 1396 } 1397 } 1398 } break; 1399 case WRITE_SETTINGS: { 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1401 synchronized (mPackages) { 1402 removeMessages(WRITE_SETTINGS); 1403 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1404 mSettings.writeLPr(); 1405 mDirtyUsers.clear(); 1406 } 1407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1408 } break; 1409 case WRITE_PACKAGE_RESTRICTIONS: { 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1411 synchronized (mPackages) { 1412 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1413 for (int userId : mDirtyUsers) { 1414 mSettings.writePackageRestrictionsLPr(userId); 1415 } 1416 mDirtyUsers.clear(); 1417 } 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1419 } break; 1420 case CHECK_PENDING_VERIFICATION: { 1421 final int verificationId = msg.arg1; 1422 final PackageVerificationState state = mPendingVerification.get(verificationId); 1423 1424 if ((state != null) && !state.timeoutExtended()) { 1425 final InstallArgs args = state.getInstallArgs(); 1426 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1427 1428 Slog.i(TAG, "Verification timed out for " + originUri); 1429 mPendingVerification.remove(verificationId); 1430 1431 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1432 1433 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1434 Slog.i(TAG, "Continuing with installation of " + originUri); 1435 state.setVerifierResponse(Binder.getCallingUid(), 1436 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1437 broadcastPackageVerified(verificationId, originUri, 1438 PackageManager.VERIFICATION_ALLOW, 1439 state.getInstallArgs().getUser()); 1440 try { 1441 ret = args.copyApk(mContainerService, true); 1442 } catch (RemoteException e) { 1443 Slog.e(TAG, "Could not contact the ContainerService"); 1444 } 1445 } else { 1446 broadcastPackageVerified(verificationId, originUri, 1447 PackageManager.VERIFICATION_REJECT, 1448 state.getInstallArgs().getUser()); 1449 } 1450 1451 processPendingInstall(args, ret); 1452 mHandler.sendEmptyMessage(MCS_UNBIND); 1453 } 1454 break; 1455 } 1456 case PACKAGE_VERIFIED: { 1457 final int verificationId = msg.arg1; 1458 1459 final PackageVerificationState state = mPendingVerification.get(verificationId); 1460 if (state == null) { 1461 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1462 break; 1463 } 1464 1465 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1466 1467 state.setVerifierResponse(response.callerUid, response.code); 1468 1469 if (state.isVerificationComplete()) { 1470 mPendingVerification.remove(verificationId); 1471 1472 final InstallArgs args = state.getInstallArgs(); 1473 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1474 1475 int ret; 1476 if (state.isInstallAllowed()) { 1477 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1478 broadcastPackageVerified(verificationId, originUri, 1479 response.code, state.getInstallArgs().getUser()); 1480 try { 1481 ret = args.copyApk(mContainerService, true); 1482 } catch (RemoteException e) { 1483 Slog.e(TAG, "Could not contact the ContainerService"); 1484 } 1485 } else { 1486 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1487 } 1488 1489 processPendingInstall(args, ret); 1490 1491 mHandler.sendEmptyMessage(MCS_UNBIND); 1492 } 1493 1494 break; 1495 } 1496 case START_INTENT_FILTER_VERIFICATIONS: { 1497 int userId = msg.arg1; 1498 int verifierUid = msg.arg2; 1499 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1500 1501 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1502 break; 1503 } 1504 case INTENT_FILTER_VERIFIED: { 1505 final int verificationId = msg.arg1; 1506 1507 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1508 verificationId); 1509 if (state == null) { 1510 Slog.w(TAG, "Invalid IntentFilter verification token " 1511 + verificationId + " received"); 1512 break; 1513 } 1514 1515 final int userId = state.getUserId(); 1516 1517 Slog.d(TAG, "Processing IntentFilter verification with token:" 1518 + verificationId + " and userId:" + userId); 1519 1520 final IntentFilterVerificationResponse response = 1521 (IntentFilterVerificationResponse) msg.obj; 1522 1523 state.setVerifierResponse(response.callerUid, response.code); 1524 1525 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1526 + " and userId:" + userId 1527 + " is settings verifier response with response code:" 1528 + response.code); 1529 1530 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1531 Slog.d(TAG, "Domains failing verification: " 1532 + response.getFailedDomainsString()); 1533 } 1534 1535 if (state.isVerificationComplete()) { 1536 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1537 } else { 1538 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1539 + " was not said to be complete"); 1540 } 1541 1542 break; 1543 } 1544 } 1545 } 1546 } 1547 1548 private StorageEventListener mStorageListener = new StorageEventListener() { 1549 @Override 1550 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1551 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1552 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1553 // TODO: ensure that private directories exist for all active users 1554 // TODO: remove user data whose serial number doesn't match 1555 loadPrivatePackages(vol); 1556 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1557 unloadPrivatePackages(vol); 1558 } 1559 } 1560 1561 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1562 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1563 updateExternalMediaStatus(true, false); 1564 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1565 updateExternalMediaStatus(false, false); 1566 } 1567 } 1568 } 1569 1570 @Override 1571 public void onVolumeForgotten(String fsUuid) { 1572 // TODO: remove all packages hosted on this uuid 1573 } 1574 }; 1575 1576 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1577 if (userId >= UserHandle.USER_OWNER) { 1578 grantRequestedRuntimePermissionsForUser(pkg, userId); 1579 } else if (userId == UserHandle.USER_ALL) { 1580 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1581 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1582 } 1583 } 1584 } 1585 1586 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1587 SettingBase sb = (SettingBase) pkg.mExtras; 1588 if (sb == null) { 1589 return; 1590 } 1591 1592 PermissionsState permissionsState = sb.getPermissionsState(); 1593 1594 for (String permission : pkg.requestedPermissions) { 1595 BasePermission bp = mSettings.mPermissions.get(permission); 1596 if (bp != null && bp.isRuntime()) { 1597 permissionsState.grantRuntimePermission(bp, userId); 1598 } 1599 } 1600 } 1601 1602 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1603 Bundle extras = null; 1604 switch (res.returnCode) { 1605 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1606 extras = new Bundle(); 1607 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1608 res.origPermission); 1609 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1610 res.origPackage); 1611 break; 1612 } 1613 case PackageManager.INSTALL_SUCCEEDED: { 1614 extras = new Bundle(); 1615 extras.putBoolean(Intent.EXTRA_REPLACING, 1616 res.removedInfo != null && res.removedInfo.removedPackage != null); 1617 break; 1618 } 1619 } 1620 return extras; 1621 } 1622 1623 void scheduleWriteSettingsLocked() { 1624 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1625 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1626 } 1627 } 1628 1629 void scheduleWritePackageRestrictionsLocked(int userId) { 1630 if (!sUserManager.exists(userId)) return; 1631 mDirtyUsers.add(userId); 1632 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1633 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1634 } 1635 } 1636 1637 public static PackageManagerService main(Context context, Installer installer, 1638 boolean factoryTest, boolean onlyCore) { 1639 PackageManagerService m = new PackageManagerService(context, installer, 1640 factoryTest, onlyCore); 1641 ServiceManager.addService("package", m); 1642 return m; 1643 } 1644 1645 static String[] splitString(String str, char sep) { 1646 int count = 1; 1647 int i = 0; 1648 while ((i=str.indexOf(sep, i)) >= 0) { 1649 count++; 1650 i++; 1651 } 1652 1653 String[] res = new String[count]; 1654 i=0; 1655 count = 0; 1656 int lastI=0; 1657 while ((i=str.indexOf(sep, i)) >= 0) { 1658 res[count] = str.substring(lastI, i); 1659 count++; 1660 i++; 1661 lastI = i; 1662 } 1663 res[count] = str.substring(lastI, str.length()); 1664 return res; 1665 } 1666 1667 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1668 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1669 Context.DISPLAY_SERVICE); 1670 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1671 } 1672 1673 public PackageManagerService(Context context, Installer installer, 1674 boolean factoryTest, boolean onlyCore) { 1675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1676 SystemClock.uptimeMillis()); 1677 1678 if (mSdkVersion <= 0) { 1679 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1680 } 1681 1682 mContext = context; 1683 mFactoryTest = factoryTest; 1684 mOnlyCore = onlyCore; 1685 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1686 mMetrics = new DisplayMetrics(); 1687 mSettings = new Settings(mPackages); 1688 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1689 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1690 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1691 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1692 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1693 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1694 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 1701 // TODO: add a property to control this? 1702 long dexOptLRUThresholdInMinutes; 1703 if (mLazyDexOpt) { 1704 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1705 } else { 1706 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1707 } 1708 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1709 1710 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1711 if (separateProcesses != null && separateProcesses.length() > 0) { 1712 if ("*".equals(separateProcesses)) { 1713 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1714 mSeparateProcesses = null; 1715 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1716 } else { 1717 mDefParseFlags = 0; 1718 mSeparateProcesses = separateProcesses.split(","); 1719 Slog.w(TAG, "Running with debug.separate_processes: " 1720 + separateProcesses); 1721 } 1722 } else { 1723 mDefParseFlags = 0; 1724 mSeparateProcesses = null; 1725 } 1726 1727 mInstaller = installer; 1728 mPackageDexOptimizer = new PackageDexOptimizer(this); 1729 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1730 1731 getDefaultDisplayMetrics(context, mMetrics); 1732 1733 SystemConfig systemConfig = SystemConfig.getInstance(); 1734 mGlobalGids = systemConfig.getGlobalGids(); 1735 mSystemPermissions = systemConfig.getSystemPermissions(); 1736 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1737 1738 synchronized (mInstallLock) { 1739 // writer 1740 synchronized (mPackages) { 1741 mHandlerThread = new ServiceThread(TAG, 1742 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1743 mHandlerThread.start(); 1744 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1745 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1746 1747 File dataDir = Environment.getDataDirectory(); 1748 mAppDataDir = new File(dataDir, "data"); 1749 mAppInstallDir = new File(dataDir, "app"); 1750 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1751 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1752 mUserAppDataDir = new File(dataDir, "user"); 1753 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1754 1755 sUserManager = new UserManagerService(context, this, 1756 mInstallLock, mPackages); 1757 1758 // Propagate permission configuration in to package manager. 1759 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1760 = systemConfig.getPermissions(); 1761 for (int i=0; i<permConfig.size(); i++) { 1762 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1763 BasePermission bp = mSettings.mPermissions.get(perm.name); 1764 if (bp == null) { 1765 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1766 mSettings.mPermissions.put(perm.name, bp); 1767 } 1768 if (perm.gids != null) { 1769 bp.setGids(perm.gids, perm.perUser); 1770 } 1771 } 1772 1773 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1774 for (int i=0; i<libConfig.size(); i++) { 1775 mSharedLibraries.put(libConfig.keyAt(i), 1776 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1777 } 1778 1779 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1780 1781 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1782 mSdkVersion, mOnlyCore); 1783 1784 String customResolverActivity = Resources.getSystem().getString( 1785 R.string.config_customResolverActivity); 1786 if (TextUtils.isEmpty(customResolverActivity)) { 1787 customResolverActivity = null; 1788 } else { 1789 mCustomResolverComponentName = ComponentName.unflattenFromString( 1790 customResolverActivity); 1791 } 1792 1793 long startTime = SystemClock.uptimeMillis(); 1794 1795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1796 startTime); 1797 1798 // Set flag to monitor and not change apk file paths when 1799 // scanning install directories. 1800 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1801 1802 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1803 1804 /** 1805 * Add everything in the in the boot class path to the 1806 * list of process files because dexopt will have been run 1807 * if necessary during zygote startup. 1808 */ 1809 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1810 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1811 1812 if (bootClassPath != null) { 1813 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1814 for (String element : bootClassPathElements) { 1815 alreadyDexOpted.add(element); 1816 } 1817 } else { 1818 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1819 } 1820 1821 if (systemServerClassPath != null) { 1822 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1823 for (String element : systemServerClassPathElements) { 1824 alreadyDexOpted.add(element); 1825 } 1826 } else { 1827 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1828 } 1829 1830 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1831 final String[] dexCodeInstructionSets = 1832 getDexCodeInstructionSets( 1833 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1834 1835 /** 1836 * Ensure all external libraries have had dexopt run on them. 1837 */ 1838 if (mSharedLibraries.size() > 0) { 1839 // NOTE: For now, we're compiling these system "shared libraries" 1840 // (and framework jars) into all available architectures. It's possible 1841 // to compile them only when we come across an app that uses them (there's 1842 // already logic for that in scanPackageLI) but that adds some complexity. 1843 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1844 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1845 final String lib = libEntry.path; 1846 if (lib == null) { 1847 continue; 1848 } 1849 1850 try { 1851 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1852 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1853 alreadyDexOpted.add(lib); 1854 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1855 } 1856 } catch (FileNotFoundException e) { 1857 Slog.w(TAG, "Library not found: " + lib); 1858 } catch (IOException e) { 1859 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1860 + e.getMessage()); 1861 } 1862 } 1863 } 1864 } 1865 1866 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1867 1868 // Gross hack for now: we know this file doesn't contain any 1869 // code, so don't dexopt it to avoid the resulting log spew. 1870 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1871 1872 // Gross hack for now: we know this file is only part of 1873 // the boot class path for art, so don't dexopt it to 1874 // avoid the resulting log spew. 1875 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1876 1877 /** 1878 * And there are a number of commands implemented in Java, which 1879 * we currently need to do the dexopt on so that they can be 1880 * run from a non-root shell. 1881 */ 1882 String[] frameworkFiles = frameworkDir.list(); 1883 if (frameworkFiles != null) { 1884 // TODO: We could compile these only for the most preferred ABI. We should 1885 // first double check that the dex files for these commands are not referenced 1886 // by other system apps. 1887 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1888 for (int i=0; i<frameworkFiles.length; i++) { 1889 File libPath = new File(frameworkDir, frameworkFiles[i]); 1890 String path = libPath.getPath(); 1891 // Skip the file if we already did it. 1892 if (alreadyDexOpted.contains(path)) { 1893 continue; 1894 } 1895 // Skip the file if it is not a type we want to dexopt. 1896 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1897 continue; 1898 } 1899 try { 1900 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1901 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1902 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1903 } 1904 } catch (FileNotFoundException e) { 1905 Slog.w(TAG, "Jar not found: " + path); 1906 } catch (IOException e) { 1907 Slog.w(TAG, "Exception reading jar: " + path, e); 1908 } 1909 } 1910 } 1911 } 1912 1913 // Collect vendor overlay packages. 1914 // (Do this before scanning any apps.) 1915 // For security and version matching reason, only consider 1916 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1917 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1918 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1919 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1920 1921 // Find base frameworks (resource packages without code). 1922 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1923 | PackageParser.PARSE_IS_SYSTEM_DIR 1924 | PackageParser.PARSE_IS_PRIVILEGED, 1925 scanFlags | SCAN_NO_DEX, 0); 1926 1927 // Collected privileged system packages. 1928 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1929 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR 1931 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1932 1933 // Collect ordinary system packages. 1934 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1935 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1936 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1937 1938 // Collect all vendor packages. 1939 File vendorAppDir = new File("/vendor/app"); 1940 try { 1941 vendorAppDir = vendorAppDir.getCanonicalFile(); 1942 } catch (IOException e) { 1943 // failed to look up canonical path, continue with original one 1944 } 1945 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1946 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1947 1948 // Collect all OEM packages. 1949 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1950 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1951 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1952 1953 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1954 mInstaller.moveFiles(); 1955 1956 // Prune any system packages that no longer exist. 1957 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1958 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1959 if (!mOnlyCore) { 1960 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1961 while (psit.hasNext()) { 1962 PackageSetting ps = psit.next(); 1963 1964 /* 1965 * If this is not a system app, it can't be a 1966 * disable system app. 1967 */ 1968 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1969 continue; 1970 } 1971 1972 /* 1973 * If the package is scanned, it's not erased. 1974 */ 1975 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1976 if (scannedPkg != null) { 1977 /* 1978 * If the system app is both scanned and in the 1979 * disabled packages list, then it must have been 1980 * added via OTA. Remove it from the currently 1981 * scanned package so the previously user-installed 1982 * application can be scanned. 1983 */ 1984 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1985 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1986 + ps.name + "; removing system app. Last known codePath=" 1987 + ps.codePathString + ", installStatus=" + ps.installStatus 1988 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1989 + scannedPkg.mVersionCode); 1990 removePackageLI(ps, true); 1991 expectingBetter.put(ps.name, ps.codePath); 1992 } 1993 1994 continue; 1995 } 1996 1997 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1998 psit.remove(); 1999 logCriticalInfo(Log.WARN, "System package " + ps.name 2000 + " no longer exists; wiping its data"); 2001 removeDataDirsLI(null, ps.name); 2002 } else { 2003 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2004 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2005 possiblyDeletedUpdatedSystemApps.add(ps.name); 2006 } 2007 } 2008 } 2009 } 2010 2011 //look for any incomplete package installations 2012 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2013 //clean up list 2014 for(int i = 0; i < deletePkgsList.size(); i++) { 2015 //clean up here 2016 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2017 } 2018 //delete tmp files 2019 deleteTempPackageFiles(); 2020 2021 // Remove any shared userIDs that have no associated packages 2022 mSettings.pruneSharedUsersLPw(); 2023 2024 if (!mOnlyCore) { 2025 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2026 SystemClock.uptimeMillis()); 2027 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2028 2029 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2030 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2031 2032 /** 2033 * Remove disable package settings for any updated system 2034 * apps that were removed via an OTA. If they're not a 2035 * previously-updated app, remove them completely. 2036 * Otherwise, just revoke their system-level permissions. 2037 */ 2038 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2039 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2040 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2041 2042 String msg; 2043 if (deletedPkg == null) { 2044 msg = "Updated system package " + deletedAppName 2045 + " no longer exists; wiping its data"; 2046 removeDataDirsLI(null, deletedAppName); 2047 } else { 2048 msg = "Updated system app + " + deletedAppName 2049 + " no longer present; removing system privileges for " 2050 + deletedAppName; 2051 2052 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2053 2054 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2055 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2056 } 2057 logCriticalInfo(Log.WARN, msg); 2058 } 2059 2060 /** 2061 * Make sure all system apps that we expected to appear on 2062 * the userdata partition actually showed up. If they never 2063 * appeared, crawl back and revive the system version. 2064 */ 2065 for (int i = 0; i < expectingBetter.size(); i++) { 2066 final String packageName = expectingBetter.keyAt(i); 2067 if (!mPackages.containsKey(packageName)) { 2068 final File scanFile = expectingBetter.valueAt(i); 2069 2070 logCriticalInfo(Log.WARN, "Expected better " + packageName 2071 + " but never showed up; reverting to system"); 2072 2073 final int reparseFlags; 2074 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR 2077 | PackageParser.PARSE_IS_PRIVILEGED; 2078 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2079 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR; 2081 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2082 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR; 2084 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2085 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR; 2087 } else { 2088 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2089 continue; 2090 } 2091 2092 mSettings.enableSystemPackageLPw(packageName); 2093 2094 try { 2095 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2096 } catch (PackageManagerException e) { 2097 Slog.e(TAG, "Failed to parse original system package: " 2098 + e.getMessage()); 2099 } 2100 } 2101 } 2102 } 2103 2104 // Now that we know all of the shared libraries, update all clients to have 2105 // the correct library paths. 2106 updateAllSharedLibrariesLPw(); 2107 2108 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2109 // NOTE: We ignore potential failures here during a system scan (like 2110 // the rest of the commands above) because there's precious little we 2111 // can do about it. A settings error is reported, though. 2112 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2113 false /* force dexopt */, false /* defer dexopt */); 2114 } 2115 2116 // Now that we know all the packages we are keeping, 2117 // read and update their last usage times. 2118 mPackageUsage.readLP(); 2119 2120 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2121 SystemClock.uptimeMillis()); 2122 Slog.i(TAG, "Time to scan packages: " 2123 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2124 + " seconds"); 2125 2126 // If the platform SDK has changed since the last time we booted, 2127 // we need to re-grant app permission to catch any new ones that 2128 // appear. This is really a hack, and means that apps can in some 2129 // cases get permissions that the user didn't initially explicitly 2130 // allow... it would be nice to have some better way to handle 2131 // this situation. 2132 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2133 != mSdkVersion; 2134 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2135 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2136 + "; regranting permissions for internal storage"); 2137 mSettings.mInternalSdkPlatform = mSdkVersion; 2138 2139 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2140 | (regrantPermissions 2141 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2142 : 0)); 2143 2144 // If this is the first boot, and it is a normal boot, then 2145 // we need to initialize the default preferred apps. 2146 if (!mRestoredSettings && !onlyCore) { 2147 mSettings.readDefaultPreferredAppsLPw(this, 0); 2148 } 2149 2150 // If this is first boot after an OTA, and a normal boot, then 2151 // we need to clear code cache directories. 2152 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2153 if (mIsUpgrade && !onlyCore) { 2154 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2155 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2156 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2157 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2158 } 2159 mSettings.mFingerprint = Build.FINGERPRINT; 2160 } 2161 2162 primeDomainVerificationsLPw(false); 2163 checkDefaultBrowser(); 2164 2165 // All the changes are done during package scanning. 2166 mSettings.updateInternalDatabaseVersion(); 2167 2168 // can downgrade to reader 2169 mSettings.writeLPr(); 2170 2171 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2172 SystemClock.uptimeMillis()); 2173 2174 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2175 2176 mInstallerService = new PackageInstallerService(context, this); 2177 2178 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2179 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2180 mIntentFilterVerifierComponent); 2181 2182 } // synchronized (mPackages) 2183 } // synchronized (mInstallLock) 2184 2185 // Now after opening every single application zip, make sure they 2186 // are all flushed. Not really needed, but keeps things nice and 2187 // tidy. 2188 Runtime.getRuntime().gc(); 2189 } 2190 2191 @Override 2192 public boolean isFirstBoot() { 2193 return !mRestoredSettings; 2194 } 2195 2196 @Override 2197 public boolean isOnlyCoreApps() { 2198 return mOnlyCore; 2199 } 2200 2201 @Override 2202 public boolean isUpgrade() { 2203 return mIsUpgrade; 2204 } 2205 2206 private String getRequiredVerifierLPr() { 2207 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2208 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2209 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2210 2211 String requiredVerifier = null; 2212 2213 final int N = receivers.size(); 2214 for (int i = 0; i < N; i++) { 2215 final ResolveInfo info = receivers.get(i); 2216 2217 if (info.activityInfo == null) { 2218 continue; 2219 } 2220 2221 final String packageName = info.activityInfo.packageName; 2222 2223 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2224 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2225 continue; 2226 } 2227 2228 if (requiredVerifier != null) { 2229 throw new RuntimeException("There can be only one required verifier"); 2230 } 2231 2232 requiredVerifier = packageName; 2233 } 2234 2235 return requiredVerifier; 2236 } 2237 2238 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2239 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2240 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2241 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2242 2243 ComponentName verifierComponentName = null; 2244 2245 int priority = -1000; 2246 final int N = receivers.size(); 2247 for (int i = 0; i < N; i++) { 2248 final ResolveInfo info = receivers.get(i); 2249 2250 if (info.activityInfo == null) { 2251 continue; 2252 } 2253 2254 final String packageName = info.activityInfo.packageName; 2255 2256 final PackageSetting ps = mSettings.mPackages.get(packageName); 2257 if (ps == null) { 2258 continue; 2259 } 2260 2261 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2262 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2263 continue; 2264 } 2265 2266 // Select the IntentFilterVerifier with the highest priority 2267 if (priority < info.priority) { 2268 priority = info.priority; 2269 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2270 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2271 " with priority: " + info.priority); 2272 } 2273 } 2274 2275 return verifierComponentName; 2276 } 2277 2278 private void primeDomainVerificationsLPw(boolean logging) { 2279 Slog.d(TAG, "Start priming domain verifications"); 2280 boolean updated = false; 2281 ArraySet<String> allHostsSet = new ArraySet<>(); 2282 for (PackageParser.Package pkg : mPackages.values()) { 2283 final String packageName = pkg.packageName; 2284 if (!hasDomainURLs(pkg)) { 2285 if (logging) { 2286 Slog.d(TAG, "No priming domain verifications for " + 2287 "package with no domain URLs: " + packageName); 2288 } 2289 continue; 2290 } 2291 if (!pkg.isSystemApp()) { 2292 if (logging) { 2293 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2294 packageName); 2295 } 2296 continue; 2297 } 2298 for (PackageParser.Activity a : pkg.activities) { 2299 for (ActivityIntentInfo filter : a.intents) { 2300 if (hasValidDomains(filter, false)) { 2301 allHostsSet.addAll(filter.getHostsList()); 2302 } 2303 } 2304 } 2305 if (allHostsSet.size() == 0) { 2306 allHostsSet.add("*"); 2307 } 2308 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2309 IntentFilterVerificationInfo ivi = 2310 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2311 if (ivi != null) { 2312 // We will always log this 2313 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2314 " with hosts:" + ivi.getDomainsString()); 2315 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2316 updated = true; 2317 } 2318 else { 2319 if (logging) { 2320 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2321 } 2322 } 2323 allHostsSet.clear(); 2324 } 2325 if (updated) { 2326 if (logging) { 2327 Slog.d(TAG, "Will need to write primed domain verifications"); 2328 } 2329 } 2330 Slog.d(TAG, "End priming domain verifications"); 2331 } 2332 2333 private void checkDefaultBrowser() { 2334 final int myUserId = UserHandle.myUserId(); 2335 final String packageName = getDefaultBrowserPackageName(myUserId); 2336 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2337 if (info == null) { 2338 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2339 packageName); 2340 setDefaultBrowserPackageName(null, myUserId); 2341 } 2342 } 2343 2344 @Override 2345 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2346 throws RemoteException { 2347 try { 2348 return super.onTransact(code, data, reply, flags); 2349 } catch (RuntimeException e) { 2350 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2351 Slog.wtf(TAG, "Package Manager Crash", e); 2352 } 2353 throw e; 2354 } 2355 } 2356 2357 void cleanupInstallFailedPackage(PackageSetting ps) { 2358 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2359 2360 removeDataDirsLI(ps.volumeUuid, ps.name); 2361 if (ps.codePath != null) { 2362 if (ps.codePath.isDirectory()) { 2363 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2364 } else { 2365 ps.codePath.delete(); 2366 } 2367 } 2368 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2369 if (ps.resourcePath.isDirectory()) { 2370 FileUtils.deleteContents(ps.resourcePath); 2371 } 2372 ps.resourcePath.delete(); 2373 } 2374 mSettings.removePackageLPw(ps.name); 2375 } 2376 2377 static int[] appendInts(int[] cur, int[] add) { 2378 if (add == null) return cur; 2379 if (cur == null) return add; 2380 final int N = add.length; 2381 for (int i=0; i<N; i++) { 2382 cur = appendInt(cur, add[i]); 2383 } 2384 return cur; 2385 } 2386 2387 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2388 if (!sUserManager.exists(userId)) return null; 2389 final PackageSetting ps = (PackageSetting) p.mExtras; 2390 if (ps == null) { 2391 return null; 2392 } 2393 2394 final PermissionsState permissionsState = ps.getPermissionsState(); 2395 2396 final int[] gids = permissionsState.computeGids(userId); 2397 final Set<String> permissions = permissionsState.getPermissions(userId); 2398 final PackageUserState state = ps.readUserState(userId); 2399 2400 return PackageParser.generatePackageInfo(p, gids, flags, 2401 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2402 } 2403 2404 @Override 2405 public boolean isPackageFrozen(String packageName) { 2406 synchronized (mPackages) { 2407 final PackageSetting ps = mSettings.mPackages.get(packageName); 2408 if (ps != null) { 2409 return ps.frozen; 2410 } 2411 } 2412 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2413 return true; 2414 } 2415 2416 @Override 2417 public boolean isPackageAvailable(String packageName, int userId) { 2418 if (!sUserManager.exists(userId)) return false; 2419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2420 synchronized (mPackages) { 2421 PackageParser.Package p = mPackages.get(packageName); 2422 if (p != null) { 2423 final PackageSetting ps = (PackageSetting) p.mExtras; 2424 if (ps != null) { 2425 final PackageUserState state = ps.readUserState(userId); 2426 if (state != null) { 2427 return PackageParser.isAvailable(state); 2428 } 2429 } 2430 } 2431 } 2432 return false; 2433 } 2434 2435 @Override 2436 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2437 if (!sUserManager.exists(userId)) return null; 2438 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2439 // reader 2440 synchronized (mPackages) { 2441 PackageParser.Package p = mPackages.get(packageName); 2442 if (DEBUG_PACKAGE_INFO) 2443 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2444 if (p != null) { 2445 return generatePackageInfo(p, flags, userId); 2446 } 2447 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2448 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2449 } 2450 } 2451 return null; 2452 } 2453 2454 @Override 2455 public String[] currentToCanonicalPackageNames(String[] names) { 2456 String[] out = new String[names.length]; 2457 // reader 2458 synchronized (mPackages) { 2459 for (int i=names.length-1; i>=0; i--) { 2460 PackageSetting ps = mSettings.mPackages.get(names[i]); 2461 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2462 } 2463 } 2464 return out; 2465 } 2466 2467 @Override 2468 public String[] canonicalToCurrentPackageNames(String[] names) { 2469 String[] out = new String[names.length]; 2470 // reader 2471 synchronized (mPackages) { 2472 for (int i=names.length-1; i>=0; i--) { 2473 String cur = mSettings.mRenamedPackages.get(names[i]); 2474 out[i] = cur != null ? cur : names[i]; 2475 } 2476 } 2477 return out; 2478 } 2479 2480 @Override 2481 public int getPackageUid(String packageName, int userId) { 2482 if (!sUserManager.exists(userId)) return -1; 2483 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2484 2485 // reader 2486 synchronized (mPackages) { 2487 PackageParser.Package p = mPackages.get(packageName); 2488 if(p != null) { 2489 return UserHandle.getUid(userId, p.applicationInfo.uid); 2490 } 2491 PackageSetting ps = mSettings.mPackages.get(packageName); 2492 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2493 return -1; 2494 } 2495 p = ps.pkg; 2496 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2497 } 2498 } 2499 2500 @Override 2501 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2502 if (!sUserManager.exists(userId)) { 2503 return null; 2504 } 2505 2506 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2507 "getPackageGids"); 2508 2509 // reader 2510 synchronized (mPackages) { 2511 PackageParser.Package p = mPackages.get(packageName); 2512 if (DEBUG_PACKAGE_INFO) { 2513 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2514 } 2515 if (p != null) { 2516 PackageSetting ps = (PackageSetting) p.mExtras; 2517 return ps.getPermissionsState().computeGids(userId); 2518 } 2519 } 2520 2521 return null; 2522 } 2523 2524 static PermissionInfo generatePermissionInfo( 2525 BasePermission bp, int flags) { 2526 if (bp.perm != null) { 2527 return PackageParser.generatePermissionInfo(bp.perm, flags); 2528 } 2529 PermissionInfo pi = new PermissionInfo(); 2530 pi.name = bp.name; 2531 pi.packageName = bp.sourcePackage; 2532 pi.nonLocalizedLabel = bp.name; 2533 pi.protectionLevel = bp.protectionLevel; 2534 return pi; 2535 } 2536 2537 @Override 2538 public PermissionInfo getPermissionInfo(String name, int flags) { 2539 // reader 2540 synchronized (mPackages) { 2541 final BasePermission p = mSettings.mPermissions.get(name); 2542 if (p != null) { 2543 return generatePermissionInfo(p, flags); 2544 } 2545 return null; 2546 } 2547 } 2548 2549 @Override 2550 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2551 // reader 2552 synchronized (mPackages) { 2553 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2554 for (BasePermission p : mSettings.mPermissions.values()) { 2555 if (group == null) { 2556 if (p.perm == null || p.perm.info.group == null) { 2557 out.add(generatePermissionInfo(p, flags)); 2558 } 2559 } else { 2560 if (p.perm != null && group.equals(p.perm.info.group)) { 2561 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2562 } 2563 } 2564 } 2565 2566 if (out.size() > 0) { 2567 return out; 2568 } 2569 return mPermissionGroups.containsKey(group) ? out : null; 2570 } 2571 } 2572 2573 @Override 2574 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2575 // reader 2576 synchronized (mPackages) { 2577 return PackageParser.generatePermissionGroupInfo( 2578 mPermissionGroups.get(name), flags); 2579 } 2580 } 2581 2582 @Override 2583 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2584 // reader 2585 synchronized (mPackages) { 2586 final int N = mPermissionGroups.size(); 2587 ArrayList<PermissionGroupInfo> out 2588 = new ArrayList<PermissionGroupInfo>(N); 2589 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2590 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2591 } 2592 return out; 2593 } 2594 } 2595 2596 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2597 int userId) { 2598 if (!sUserManager.exists(userId)) return null; 2599 PackageSetting ps = mSettings.mPackages.get(packageName); 2600 if (ps != null) { 2601 if (ps.pkg == null) { 2602 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2603 flags, userId); 2604 if (pInfo != null) { 2605 return pInfo.applicationInfo; 2606 } 2607 return null; 2608 } 2609 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2610 ps.readUserState(userId), userId); 2611 } 2612 return null; 2613 } 2614 2615 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2616 int userId) { 2617 if (!sUserManager.exists(userId)) return null; 2618 PackageSetting ps = mSettings.mPackages.get(packageName); 2619 if (ps != null) { 2620 PackageParser.Package pkg = ps.pkg; 2621 if (pkg == null) { 2622 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2623 return null; 2624 } 2625 // Only data remains, so we aren't worried about code paths 2626 pkg = new PackageParser.Package(packageName); 2627 pkg.applicationInfo.packageName = packageName; 2628 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2629 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2630 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2631 packageName, userId).getAbsolutePath(); 2632 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2633 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2634 } 2635 return generatePackageInfo(pkg, flags, userId); 2636 } 2637 return null; 2638 } 2639 2640 @Override 2641 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2642 if (!sUserManager.exists(userId)) return null; 2643 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2644 // writer 2645 synchronized (mPackages) { 2646 PackageParser.Package p = mPackages.get(packageName); 2647 if (DEBUG_PACKAGE_INFO) Log.v( 2648 TAG, "getApplicationInfo " + packageName 2649 + ": " + p); 2650 if (p != null) { 2651 PackageSetting ps = mSettings.mPackages.get(packageName); 2652 if (ps == null) return null; 2653 // Note: isEnabledLP() does not apply here - always return info 2654 return PackageParser.generateApplicationInfo( 2655 p, flags, ps.readUserState(userId), userId); 2656 } 2657 if ("android".equals(packageName)||"system".equals(packageName)) { 2658 return mAndroidApplication; 2659 } 2660 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2661 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2662 } 2663 } 2664 return null; 2665 } 2666 2667 @Override 2668 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2669 final IPackageDataObserver observer) { 2670 mContext.enforceCallingOrSelfPermission( 2671 android.Manifest.permission.CLEAR_APP_CACHE, null); 2672 // Queue up an async operation since clearing cache may take a little while. 2673 mHandler.post(new Runnable() { 2674 public void run() { 2675 mHandler.removeCallbacks(this); 2676 int retCode = -1; 2677 synchronized (mInstallLock) { 2678 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2679 if (retCode < 0) { 2680 Slog.w(TAG, "Couldn't clear application caches"); 2681 } 2682 } 2683 if (observer != null) { 2684 try { 2685 observer.onRemoveCompleted(null, (retCode >= 0)); 2686 } catch (RemoteException e) { 2687 Slog.w(TAG, "RemoveException when invoking call back"); 2688 } 2689 } 2690 } 2691 }); 2692 } 2693 2694 @Override 2695 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2696 final IntentSender pi) { 2697 mContext.enforceCallingOrSelfPermission( 2698 android.Manifest.permission.CLEAR_APP_CACHE, null); 2699 // Queue up an async operation since clearing cache may take a little while. 2700 mHandler.post(new Runnable() { 2701 public void run() { 2702 mHandler.removeCallbacks(this); 2703 int retCode = -1; 2704 synchronized (mInstallLock) { 2705 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2706 if (retCode < 0) { 2707 Slog.w(TAG, "Couldn't clear application caches"); 2708 } 2709 } 2710 if(pi != null) { 2711 try { 2712 // Callback via pending intent 2713 int code = (retCode >= 0) ? 1 : 0; 2714 pi.sendIntent(null, code, null, 2715 null, null); 2716 } catch (SendIntentException e1) { 2717 Slog.i(TAG, "Failed to send pending intent"); 2718 } 2719 } 2720 } 2721 }); 2722 } 2723 2724 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2725 synchronized (mInstallLock) { 2726 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2727 throw new IOException("Failed to free enough space"); 2728 } 2729 } 2730 } 2731 2732 @Override 2733 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2734 if (!sUserManager.exists(userId)) return null; 2735 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2736 synchronized (mPackages) { 2737 PackageParser.Activity a = mActivities.mActivities.get(component); 2738 2739 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2740 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2741 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2742 if (ps == null) return null; 2743 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2744 userId); 2745 } 2746 if (mResolveComponentName.equals(component)) { 2747 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2748 new PackageUserState(), userId); 2749 } 2750 } 2751 return null; 2752 } 2753 2754 @Override 2755 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2756 String resolvedType) { 2757 synchronized (mPackages) { 2758 PackageParser.Activity a = mActivities.mActivities.get(component); 2759 if (a == null) { 2760 return false; 2761 } 2762 for (int i=0; i<a.intents.size(); i++) { 2763 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2764 intent.getData(), intent.getCategories(), TAG) >= 0) { 2765 return true; 2766 } 2767 } 2768 return false; 2769 } 2770 } 2771 2772 @Override 2773 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2774 if (!sUserManager.exists(userId)) return null; 2775 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2776 synchronized (mPackages) { 2777 PackageParser.Activity a = mReceivers.mActivities.get(component); 2778 if (DEBUG_PACKAGE_INFO) Log.v( 2779 TAG, "getReceiverInfo " + component + ": " + a); 2780 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2781 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2782 if (ps == null) return null; 2783 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2784 userId); 2785 } 2786 } 2787 return null; 2788 } 2789 2790 @Override 2791 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2792 if (!sUserManager.exists(userId)) return null; 2793 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2794 synchronized (mPackages) { 2795 PackageParser.Service s = mServices.mServices.get(component); 2796 if (DEBUG_PACKAGE_INFO) Log.v( 2797 TAG, "getServiceInfo " + component + ": " + s); 2798 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2799 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2800 if (ps == null) return null; 2801 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2802 userId); 2803 } 2804 } 2805 return null; 2806 } 2807 2808 @Override 2809 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2810 if (!sUserManager.exists(userId)) return null; 2811 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2812 synchronized (mPackages) { 2813 PackageParser.Provider p = mProviders.mProviders.get(component); 2814 if (DEBUG_PACKAGE_INFO) Log.v( 2815 TAG, "getProviderInfo " + component + ": " + p); 2816 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2817 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2818 if (ps == null) return null; 2819 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2820 userId); 2821 } 2822 } 2823 return null; 2824 } 2825 2826 @Override 2827 public String[] getSystemSharedLibraryNames() { 2828 Set<String> libSet; 2829 synchronized (mPackages) { 2830 libSet = mSharedLibraries.keySet(); 2831 int size = libSet.size(); 2832 if (size > 0) { 2833 String[] libs = new String[size]; 2834 libSet.toArray(libs); 2835 return libs; 2836 } 2837 } 2838 return null; 2839 } 2840 2841 /** 2842 * @hide 2843 */ 2844 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2845 synchronized (mPackages) { 2846 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2847 if (lib != null && lib.apk != null) { 2848 return mPackages.get(lib.apk); 2849 } 2850 } 2851 return null; 2852 } 2853 2854 @Override 2855 public FeatureInfo[] getSystemAvailableFeatures() { 2856 Collection<FeatureInfo> featSet; 2857 synchronized (mPackages) { 2858 featSet = mAvailableFeatures.values(); 2859 int size = featSet.size(); 2860 if (size > 0) { 2861 FeatureInfo[] features = new FeatureInfo[size+1]; 2862 featSet.toArray(features); 2863 FeatureInfo fi = new FeatureInfo(); 2864 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2865 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2866 features[size] = fi; 2867 return features; 2868 } 2869 } 2870 return null; 2871 } 2872 2873 @Override 2874 public boolean hasSystemFeature(String name) { 2875 synchronized (mPackages) { 2876 return mAvailableFeatures.containsKey(name); 2877 } 2878 } 2879 2880 private void checkValidCaller(int uid, int userId) { 2881 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2882 return; 2883 2884 throw new SecurityException("Caller uid=" + uid 2885 + " is not privileged to communicate with user=" + userId); 2886 } 2887 2888 @Override 2889 public int checkPermission(String permName, String pkgName, int userId) { 2890 if (!sUserManager.exists(userId)) { 2891 return PackageManager.PERMISSION_DENIED; 2892 } 2893 2894 synchronized (mPackages) { 2895 final PackageParser.Package p = mPackages.get(pkgName); 2896 if (p != null && p.mExtras != null) { 2897 final PackageSetting ps = (PackageSetting) p.mExtras; 2898 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2899 return PackageManager.PERMISSION_GRANTED; 2900 } 2901 } 2902 } 2903 2904 return PackageManager.PERMISSION_DENIED; 2905 } 2906 2907 @Override 2908 public int checkUidPermission(String permName, int uid) { 2909 final int userId = UserHandle.getUserId(uid); 2910 2911 if (!sUserManager.exists(userId)) { 2912 return PackageManager.PERMISSION_DENIED; 2913 } 2914 2915 synchronized (mPackages) { 2916 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2917 if (obj != null) { 2918 final SettingBase ps = (SettingBase) obj; 2919 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2920 return PackageManager.PERMISSION_GRANTED; 2921 } 2922 } else { 2923 ArraySet<String> perms = mSystemPermissions.get(uid); 2924 if (perms != null && perms.contains(permName)) { 2925 return PackageManager.PERMISSION_GRANTED; 2926 } 2927 } 2928 } 2929 2930 return PackageManager.PERMISSION_DENIED; 2931 } 2932 2933 /** 2934 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2935 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2936 * @param checkShell TODO(yamasani): 2937 * @param message the message to log on security exception 2938 */ 2939 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2940 boolean checkShell, String message) { 2941 if (userId < 0) { 2942 throw new IllegalArgumentException("Invalid userId " + userId); 2943 } 2944 if (checkShell) { 2945 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2946 } 2947 if (userId == UserHandle.getUserId(callingUid)) return; 2948 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2949 if (requireFullPermission) { 2950 mContext.enforceCallingOrSelfPermission( 2951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2952 } else { 2953 try { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2956 } catch (SecurityException se) { 2957 mContext.enforceCallingOrSelfPermission( 2958 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2959 } 2960 } 2961 } 2962 } 2963 2964 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2965 if (callingUid == Process.SHELL_UID) { 2966 if (userHandle >= 0 2967 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2968 throw new SecurityException("Shell does not have permission to access user " 2969 + userHandle); 2970 } else if (userHandle < 0) { 2971 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2972 + Debug.getCallers(3)); 2973 } 2974 } 2975 } 2976 2977 private BasePermission findPermissionTreeLP(String permName) { 2978 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2979 if (permName.startsWith(bp.name) && 2980 permName.length() > bp.name.length() && 2981 permName.charAt(bp.name.length()) == '.') { 2982 return bp; 2983 } 2984 } 2985 return null; 2986 } 2987 2988 private BasePermission checkPermissionTreeLP(String permName) { 2989 if (permName != null) { 2990 BasePermission bp = findPermissionTreeLP(permName); 2991 if (bp != null) { 2992 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2993 return bp; 2994 } 2995 throw new SecurityException("Calling uid " 2996 + Binder.getCallingUid() 2997 + " is not allowed to add to permission tree " 2998 + bp.name + " owned by uid " + bp.uid); 2999 } 3000 } 3001 throw new SecurityException("No permission tree found for " + permName); 3002 } 3003 3004 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3005 if (s1 == null) { 3006 return s2 == null; 3007 } 3008 if (s2 == null) { 3009 return false; 3010 } 3011 if (s1.getClass() != s2.getClass()) { 3012 return false; 3013 } 3014 return s1.equals(s2); 3015 } 3016 3017 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3018 if (pi1.icon != pi2.icon) return false; 3019 if (pi1.logo != pi2.logo) return false; 3020 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3021 if (!compareStrings(pi1.name, pi2.name)) return false; 3022 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3023 // We'll take care of setting this one. 3024 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3025 // These are not currently stored in settings. 3026 //if (!compareStrings(pi1.group, pi2.group)) return false; 3027 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3028 //if (pi1.labelRes != pi2.labelRes) return false; 3029 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3030 return true; 3031 } 3032 3033 int permissionInfoFootprint(PermissionInfo info) { 3034 int size = info.name.length(); 3035 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3036 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3037 return size; 3038 } 3039 3040 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3041 int size = 0; 3042 for (BasePermission perm : mSettings.mPermissions.values()) { 3043 if (perm.uid == tree.uid) { 3044 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3045 } 3046 } 3047 return size; 3048 } 3049 3050 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3051 // We calculate the max size of permissions defined by this uid and throw 3052 // if that plus the size of 'info' would exceed our stated maximum. 3053 if (tree.uid != Process.SYSTEM_UID) { 3054 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3055 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3056 throw new SecurityException("Permission tree size cap exceeded"); 3057 } 3058 } 3059 } 3060 3061 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3062 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3063 throw new SecurityException("Label must be specified in permission"); 3064 } 3065 BasePermission tree = checkPermissionTreeLP(info.name); 3066 BasePermission bp = mSettings.mPermissions.get(info.name); 3067 boolean added = bp == null; 3068 boolean changed = true; 3069 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3070 if (added) { 3071 enforcePermissionCapLocked(info, tree); 3072 bp = new BasePermission(info.name, tree.sourcePackage, 3073 BasePermission.TYPE_DYNAMIC); 3074 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3075 throw new SecurityException( 3076 "Not allowed to modify non-dynamic permission " 3077 + info.name); 3078 } else { 3079 if (bp.protectionLevel == fixedLevel 3080 && bp.perm.owner.equals(tree.perm.owner) 3081 && bp.uid == tree.uid 3082 && comparePermissionInfos(bp.perm.info, info)) { 3083 changed = false; 3084 } 3085 } 3086 bp.protectionLevel = fixedLevel; 3087 info = new PermissionInfo(info); 3088 info.protectionLevel = fixedLevel; 3089 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3090 bp.perm.info.packageName = tree.perm.info.packageName; 3091 bp.uid = tree.uid; 3092 if (added) { 3093 mSettings.mPermissions.put(info.name, bp); 3094 } 3095 if (changed) { 3096 if (!async) { 3097 mSettings.writeLPr(); 3098 } else { 3099 scheduleWriteSettingsLocked(); 3100 } 3101 } 3102 return added; 3103 } 3104 3105 @Override 3106 public boolean addPermission(PermissionInfo info) { 3107 synchronized (mPackages) { 3108 return addPermissionLocked(info, false); 3109 } 3110 } 3111 3112 @Override 3113 public boolean addPermissionAsync(PermissionInfo info) { 3114 synchronized (mPackages) { 3115 return addPermissionLocked(info, true); 3116 } 3117 } 3118 3119 @Override 3120 public void removePermission(String name) { 3121 synchronized (mPackages) { 3122 checkPermissionTreeLP(name); 3123 BasePermission bp = mSettings.mPermissions.get(name); 3124 if (bp != null) { 3125 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3126 throw new SecurityException( 3127 "Not allowed to modify non-dynamic permission " 3128 + name); 3129 } 3130 mSettings.mPermissions.remove(name); 3131 mSettings.writeLPr(); 3132 } 3133 } 3134 } 3135 3136 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3137 BasePermission bp) { 3138 int index = pkg.requestedPermissions.indexOf(bp.name); 3139 if (index == -1) { 3140 throw new SecurityException("Package " + pkg.packageName 3141 + " has not requested permission " + bp.name); 3142 } 3143 if (!bp.isRuntime()) { 3144 throw new SecurityException("Permission " + bp.name 3145 + " is not a changeable permission type"); 3146 } 3147 } 3148 3149 @Override 3150 public void grantRuntimePermission(String packageName, String name, int userId) { 3151 if (!sUserManager.exists(userId)) { 3152 Log.e(TAG, "No such user:" + userId); 3153 return; 3154 } 3155 3156 mContext.enforceCallingOrSelfPermission( 3157 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3158 "grantRuntimePermission"); 3159 3160 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3161 "grantRuntimePermission"); 3162 3163 boolean gidsChanged = false; 3164 final SettingBase sb; 3165 3166 synchronized (mPackages) { 3167 final PackageParser.Package pkg = mPackages.get(packageName); 3168 if (pkg == null) { 3169 throw new IllegalArgumentException("Unknown package: " + packageName); 3170 } 3171 3172 final BasePermission bp = mSettings.mPermissions.get(name); 3173 if (bp == null) { 3174 throw new IllegalArgumentException("Unknown permission: " + name); 3175 } 3176 3177 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3178 3179 sb = (SettingBase) pkg.mExtras; 3180 if (sb == null) { 3181 throw new IllegalArgumentException("Unknown package: " + packageName); 3182 } 3183 3184 final PermissionsState permissionsState = sb.getPermissionsState(); 3185 3186 final int flags = permissionsState.getPermissionFlags(name, userId); 3187 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3188 throw new SecurityException("Cannot grant system fixed permission: " 3189 + name + " for package: " + packageName); 3190 } 3191 3192 final int result = permissionsState.grantRuntimePermission(bp, userId); 3193 switch (result) { 3194 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3195 return; 3196 } 3197 3198 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3199 gidsChanged = true; 3200 } 3201 break; 3202 } 3203 3204 // Not critical if that is lost - app has to request again. 3205 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3206 } 3207 3208 if (gidsChanged) { 3209 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3210 } 3211 } 3212 3213 @Override 3214 public void revokeRuntimePermission(String packageName, String name, int userId) { 3215 if (!sUserManager.exists(userId)) { 3216 Log.e(TAG, "No such user:" + userId); 3217 return; 3218 } 3219 3220 mContext.enforceCallingOrSelfPermission( 3221 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3222 "revokeRuntimePermission"); 3223 3224 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3225 "revokeRuntimePermission"); 3226 3227 final SettingBase sb; 3228 3229 synchronized (mPackages) { 3230 final PackageParser.Package pkg = mPackages.get(packageName); 3231 if (pkg == null) { 3232 throw new IllegalArgumentException("Unknown package: " + packageName); 3233 } 3234 3235 final BasePermission bp = mSettings.mPermissions.get(name); 3236 if (bp == null) { 3237 throw new IllegalArgumentException("Unknown permission: " + name); 3238 } 3239 3240 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3241 3242 sb = (SettingBase) pkg.mExtras; 3243 if (sb == null) { 3244 throw new IllegalArgumentException("Unknown package: " + packageName); 3245 } 3246 3247 final PermissionsState permissionsState = sb.getPermissionsState(); 3248 3249 final int flags = permissionsState.getPermissionFlags(name, userId); 3250 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3251 throw new SecurityException("Cannot revoke system fixed permission: " 3252 + name + " for package: " + packageName); 3253 } 3254 3255 if (permissionsState.revokeRuntimePermission(bp, userId) == 3256 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3257 return; 3258 } 3259 3260 // Critical, after this call app should never have the permission. 3261 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3262 } 3263 3264 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3265 } 3266 3267 @Override 3268 public int getPermissionFlags(String name, String packageName, int userId) { 3269 if (!sUserManager.exists(userId)) { 3270 return 0; 3271 } 3272 3273 mContext.enforceCallingOrSelfPermission( 3274 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3275 "getPermissionFlags"); 3276 3277 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3278 "getPermissionFlags"); 3279 3280 synchronized (mPackages) { 3281 final PackageParser.Package pkg = mPackages.get(packageName); 3282 if (pkg == null) { 3283 throw new IllegalArgumentException("Unknown package: " + packageName); 3284 } 3285 3286 final BasePermission bp = mSettings.mPermissions.get(name); 3287 if (bp == null) { 3288 throw new IllegalArgumentException("Unknown permission: " + name); 3289 } 3290 3291 SettingBase sb = (SettingBase) pkg.mExtras; 3292 if (sb == null) { 3293 throw new IllegalArgumentException("Unknown package: " + packageName); 3294 } 3295 3296 PermissionsState permissionsState = sb.getPermissionsState(); 3297 return permissionsState.getPermissionFlags(name, userId); 3298 } 3299 } 3300 3301 @Override 3302 public void updatePermissionFlags(String name, String packageName, int flagMask, 3303 int flagValues, int userId) { 3304 if (!sUserManager.exists(userId)) { 3305 return; 3306 } 3307 3308 mContext.enforceCallingOrSelfPermission( 3309 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3310 "updatePermissionFlags"); 3311 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3313 "updatePermissionFlags"); 3314 3315 // Only the system can change policy flags. 3316 if (getCallingUid() != Process.SYSTEM_UID) { 3317 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3318 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3319 } 3320 3321 // Only the package manager can change system flags. 3322 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3323 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3324 3325 synchronized (mPackages) { 3326 final PackageParser.Package pkg = mPackages.get(packageName); 3327 if (pkg == null) { 3328 throw new IllegalArgumentException("Unknown package: " + packageName); 3329 } 3330 3331 final BasePermission bp = mSettings.mPermissions.get(name); 3332 if (bp == null) { 3333 throw new IllegalArgumentException("Unknown permission: " + name); 3334 } 3335 3336 SettingBase sb = (SettingBase) pkg.mExtras; 3337 if (sb == null) { 3338 throw new IllegalArgumentException("Unknown package: " + packageName); 3339 } 3340 3341 PermissionsState permissionsState = sb.getPermissionsState(); 3342 3343 // Only the package manager can change flags for system component permissions. 3344 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3345 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3346 return; 3347 } 3348 3349 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3350 // Install and runtime permissions are stored in different places, 3351 // so figure out what permission changed and persist the change. 3352 if (permissionsState.getInstallPermissionState(name) != null) { 3353 scheduleWriteSettingsLocked(); 3354 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3355 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3356 } 3357 } 3358 } 3359 } 3360 3361 @Override 3362 public boolean isProtectedBroadcast(String actionName) { 3363 synchronized (mPackages) { 3364 return mProtectedBroadcasts.contains(actionName); 3365 } 3366 } 3367 3368 @Override 3369 public int checkSignatures(String pkg1, String pkg2) { 3370 synchronized (mPackages) { 3371 final PackageParser.Package p1 = mPackages.get(pkg1); 3372 final PackageParser.Package p2 = mPackages.get(pkg2); 3373 if (p1 == null || p1.mExtras == null 3374 || p2 == null || p2.mExtras == null) { 3375 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3376 } 3377 return compareSignatures(p1.mSignatures, p2.mSignatures); 3378 } 3379 } 3380 3381 @Override 3382 public int checkUidSignatures(int uid1, int uid2) { 3383 // Map to base uids. 3384 uid1 = UserHandle.getAppId(uid1); 3385 uid2 = UserHandle.getAppId(uid2); 3386 // reader 3387 synchronized (mPackages) { 3388 Signature[] s1; 3389 Signature[] s2; 3390 Object obj = mSettings.getUserIdLPr(uid1); 3391 if (obj != null) { 3392 if (obj instanceof SharedUserSetting) { 3393 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3394 } else if (obj instanceof PackageSetting) { 3395 s1 = ((PackageSetting)obj).signatures.mSignatures; 3396 } else { 3397 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3398 } 3399 } else { 3400 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3401 } 3402 obj = mSettings.getUserIdLPr(uid2); 3403 if (obj != null) { 3404 if (obj instanceof SharedUserSetting) { 3405 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3406 } else if (obj instanceof PackageSetting) { 3407 s2 = ((PackageSetting)obj).signatures.mSignatures; 3408 } else { 3409 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3410 } 3411 } else { 3412 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3413 } 3414 return compareSignatures(s1, s2); 3415 } 3416 } 3417 3418 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3419 final long identity = Binder.clearCallingIdentity(); 3420 try { 3421 if (sb instanceof SharedUserSetting) { 3422 SharedUserSetting sus = (SharedUserSetting) sb; 3423 final int packageCount = sus.packages.size(); 3424 for (int i = 0; i < packageCount; i++) { 3425 PackageSetting susPs = sus.packages.valueAt(i); 3426 if (userId == UserHandle.USER_ALL) { 3427 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3428 } else { 3429 final int uid = UserHandle.getUid(userId, susPs.appId); 3430 killUid(uid, reason); 3431 } 3432 } 3433 } else if (sb instanceof PackageSetting) { 3434 PackageSetting ps = (PackageSetting) sb; 3435 if (userId == UserHandle.USER_ALL) { 3436 killApplication(ps.pkg.packageName, ps.appId, reason); 3437 } else { 3438 final int uid = UserHandle.getUid(userId, ps.appId); 3439 killUid(uid, reason); 3440 } 3441 } 3442 } finally { 3443 Binder.restoreCallingIdentity(identity); 3444 } 3445 } 3446 3447 private static void killUid(int uid, String reason) { 3448 IActivityManager am = ActivityManagerNative.getDefault(); 3449 if (am != null) { 3450 try { 3451 am.killUid(uid, reason); 3452 } catch (RemoteException e) { 3453 /* ignore - same process */ 3454 } 3455 } 3456 } 3457 3458 /** 3459 * Compares two sets of signatures. Returns: 3460 * <br /> 3461 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3462 * <br /> 3463 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3464 * <br /> 3465 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3466 * <br /> 3467 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3468 * <br /> 3469 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3470 */ 3471 static int compareSignatures(Signature[] s1, Signature[] s2) { 3472 if (s1 == null) { 3473 return s2 == null 3474 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3475 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3476 } 3477 3478 if (s2 == null) { 3479 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3480 } 3481 3482 if (s1.length != s2.length) { 3483 return PackageManager.SIGNATURE_NO_MATCH; 3484 } 3485 3486 // Since both signature sets are of size 1, we can compare without HashSets. 3487 if (s1.length == 1) { 3488 return s1[0].equals(s2[0]) ? 3489 PackageManager.SIGNATURE_MATCH : 3490 PackageManager.SIGNATURE_NO_MATCH; 3491 } 3492 3493 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3494 for (Signature sig : s1) { 3495 set1.add(sig); 3496 } 3497 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3498 for (Signature sig : s2) { 3499 set2.add(sig); 3500 } 3501 // Make sure s2 contains all signatures in s1. 3502 if (set1.equals(set2)) { 3503 return PackageManager.SIGNATURE_MATCH; 3504 } 3505 return PackageManager.SIGNATURE_NO_MATCH; 3506 } 3507 3508 /** 3509 * If the database version for this type of package (internal storage or 3510 * external storage) is less than the version where package signatures 3511 * were updated, return true. 3512 */ 3513 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3514 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3515 DatabaseVersion.SIGNATURE_END_ENTITY)) 3516 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3517 DatabaseVersion.SIGNATURE_END_ENTITY)); 3518 } 3519 3520 /** 3521 * Used for backward compatibility to make sure any packages with 3522 * certificate chains get upgraded to the new style. {@code existingSigs} 3523 * will be in the old format (since they were stored on disk from before the 3524 * system upgrade) and {@code scannedSigs} will be in the newer format. 3525 */ 3526 private int compareSignaturesCompat(PackageSignatures existingSigs, 3527 PackageParser.Package scannedPkg) { 3528 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3529 return PackageManager.SIGNATURE_NO_MATCH; 3530 } 3531 3532 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3533 for (Signature sig : existingSigs.mSignatures) { 3534 existingSet.add(sig); 3535 } 3536 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3537 for (Signature sig : scannedPkg.mSignatures) { 3538 try { 3539 Signature[] chainSignatures = sig.getChainSignatures(); 3540 for (Signature chainSig : chainSignatures) { 3541 scannedCompatSet.add(chainSig); 3542 } 3543 } catch (CertificateEncodingException e) { 3544 scannedCompatSet.add(sig); 3545 } 3546 } 3547 /* 3548 * Make sure the expanded scanned set contains all signatures in the 3549 * existing one. 3550 */ 3551 if (scannedCompatSet.equals(existingSet)) { 3552 // Migrate the old signatures to the new scheme. 3553 existingSigs.assignSignatures(scannedPkg.mSignatures); 3554 // The new KeySets will be re-added later in the scanning process. 3555 synchronized (mPackages) { 3556 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3557 } 3558 return PackageManager.SIGNATURE_MATCH; 3559 } 3560 return PackageManager.SIGNATURE_NO_MATCH; 3561 } 3562 3563 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3564 if (isExternal(scannedPkg)) { 3565 return mSettings.isExternalDatabaseVersionOlderThan( 3566 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3567 } else { 3568 return mSettings.isInternalDatabaseVersionOlderThan( 3569 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3570 } 3571 } 3572 3573 private int compareSignaturesRecover(PackageSignatures existingSigs, 3574 PackageParser.Package scannedPkg) { 3575 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3576 return PackageManager.SIGNATURE_NO_MATCH; 3577 } 3578 3579 String msg = null; 3580 try { 3581 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3582 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3583 + scannedPkg.packageName); 3584 return PackageManager.SIGNATURE_MATCH; 3585 } 3586 } catch (CertificateException e) { 3587 msg = e.getMessage(); 3588 } 3589 3590 logCriticalInfo(Log.INFO, 3591 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3592 return PackageManager.SIGNATURE_NO_MATCH; 3593 } 3594 3595 @Override 3596 public String[] getPackagesForUid(int uid) { 3597 uid = UserHandle.getAppId(uid); 3598 // reader 3599 synchronized (mPackages) { 3600 Object obj = mSettings.getUserIdLPr(uid); 3601 if (obj instanceof SharedUserSetting) { 3602 final SharedUserSetting sus = (SharedUserSetting) obj; 3603 final int N = sus.packages.size(); 3604 final String[] res = new String[N]; 3605 final Iterator<PackageSetting> it = sus.packages.iterator(); 3606 int i = 0; 3607 while (it.hasNext()) { 3608 res[i++] = it.next().name; 3609 } 3610 return res; 3611 } else if (obj instanceof PackageSetting) { 3612 final PackageSetting ps = (PackageSetting) obj; 3613 return new String[] { ps.name }; 3614 } 3615 } 3616 return null; 3617 } 3618 3619 @Override 3620 public String getNameForUid(int uid) { 3621 // reader 3622 synchronized (mPackages) { 3623 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3624 if (obj instanceof SharedUserSetting) { 3625 final SharedUserSetting sus = (SharedUserSetting) obj; 3626 return sus.name + ":" + sus.userId; 3627 } else if (obj instanceof PackageSetting) { 3628 final PackageSetting ps = (PackageSetting) obj; 3629 return ps.name; 3630 } 3631 } 3632 return null; 3633 } 3634 3635 @Override 3636 public int getUidForSharedUser(String sharedUserName) { 3637 if(sharedUserName == null) { 3638 return -1; 3639 } 3640 // reader 3641 synchronized (mPackages) { 3642 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3643 if (suid == null) { 3644 return -1; 3645 } 3646 return suid.userId; 3647 } 3648 } 3649 3650 @Override 3651 public int getFlagsForUid(int uid) { 3652 synchronized (mPackages) { 3653 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3654 if (obj instanceof SharedUserSetting) { 3655 final SharedUserSetting sus = (SharedUserSetting) obj; 3656 return sus.pkgFlags; 3657 } else if (obj instanceof PackageSetting) { 3658 final PackageSetting ps = (PackageSetting) obj; 3659 return ps.pkgFlags; 3660 } 3661 } 3662 return 0; 3663 } 3664 3665 @Override 3666 public int getPrivateFlagsForUid(int uid) { 3667 synchronized (mPackages) { 3668 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3669 if (obj instanceof SharedUserSetting) { 3670 final SharedUserSetting sus = (SharedUserSetting) obj; 3671 return sus.pkgPrivateFlags; 3672 } else if (obj instanceof PackageSetting) { 3673 final PackageSetting ps = (PackageSetting) obj; 3674 return ps.pkgPrivateFlags; 3675 } 3676 } 3677 return 0; 3678 } 3679 3680 @Override 3681 public boolean isUidPrivileged(int uid) { 3682 uid = UserHandle.getAppId(uid); 3683 // reader 3684 synchronized (mPackages) { 3685 Object obj = mSettings.getUserIdLPr(uid); 3686 if (obj instanceof SharedUserSetting) { 3687 final SharedUserSetting sus = (SharedUserSetting) obj; 3688 final Iterator<PackageSetting> it = sus.packages.iterator(); 3689 while (it.hasNext()) { 3690 if (it.next().isPrivileged()) { 3691 return true; 3692 } 3693 } 3694 } else if (obj instanceof PackageSetting) { 3695 final PackageSetting ps = (PackageSetting) obj; 3696 return ps.isPrivileged(); 3697 } 3698 } 3699 return false; 3700 } 3701 3702 @Override 3703 public String[] getAppOpPermissionPackages(String permissionName) { 3704 synchronized (mPackages) { 3705 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3706 if (pkgs == null) { 3707 return null; 3708 } 3709 return pkgs.toArray(new String[pkgs.size()]); 3710 } 3711 } 3712 3713 @Override 3714 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3715 int flags, int userId) { 3716 if (!sUserManager.exists(userId)) return null; 3717 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3718 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3719 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3720 } 3721 3722 @Override 3723 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3724 IntentFilter filter, int match, ComponentName activity) { 3725 final int userId = UserHandle.getCallingUserId(); 3726 if (DEBUG_PREFERRED) { 3727 Log.v(TAG, "setLastChosenActivity intent=" + intent 3728 + " resolvedType=" + resolvedType 3729 + " flags=" + flags 3730 + " filter=" + filter 3731 + " match=" + match 3732 + " activity=" + activity); 3733 filter.dump(new PrintStreamPrinter(System.out), " "); 3734 } 3735 intent.setComponent(null); 3736 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3737 // Find any earlier preferred or last chosen entries and nuke them 3738 findPreferredActivity(intent, resolvedType, 3739 flags, query, 0, false, true, false, userId); 3740 // Add the new activity as the last chosen for this filter 3741 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3742 "Setting last chosen"); 3743 } 3744 3745 @Override 3746 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3747 final int userId = UserHandle.getCallingUserId(); 3748 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3749 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3750 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3751 false, false, false, userId); 3752 } 3753 3754 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3755 int flags, List<ResolveInfo> query, int userId) { 3756 if (query != null) { 3757 final int N = query.size(); 3758 if (N == 1) { 3759 return query.get(0); 3760 } else if (N > 1) { 3761 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3762 // If there is more than one activity with the same priority, 3763 // then let the user decide between them. 3764 ResolveInfo r0 = query.get(0); 3765 ResolveInfo r1 = query.get(1); 3766 if (DEBUG_INTENT_MATCHING || debug) { 3767 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3768 + r1.activityInfo.name + "=" + r1.priority); 3769 } 3770 // If the first activity has a higher priority, or a different 3771 // default, then it is always desireable to pick it. 3772 if (r0.priority != r1.priority 3773 || r0.preferredOrder != r1.preferredOrder 3774 || r0.isDefault != r1.isDefault) { 3775 return query.get(0); 3776 } 3777 // If we have saved a preference for a preferred activity for 3778 // this Intent, use that. 3779 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3780 flags, query, r0.priority, true, false, debug, userId); 3781 if (ri != null) { 3782 return ri; 3783 } 3784 if (userId != 0) { 3785 ri = new ResolveInfo(mResolveInfo); 3786 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3787 ri.activityInfo.applicationInfo = new ApplicationInfo( 3788 ri.activityInfo.applicationInfo); 3789 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3790 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3791 return ri; 3792 } 3793 return mResolveInfo; 3794 } 3795 } 3796 return null; 3797 } 3798 3799 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3800 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3801 final int N = query.size(); 3802 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3803 .get(userId); 3804 // Get the list of persistent preferred activities that handle the intent 3805 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3806 List<PersistentPreferredActivity> pprefs = ppir != null 3807 ? ppir.queryIntent(intent, resolvedType, 3808 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3809 : null; 3810 if (pprefs != null && pprefs.size() > 0) { 3811 final int M = pprefs.size(); 3812 for (int i=0; i<M; i++) { 3813 final PersistentPreferredActivity ppa = pprefs.get(i); 3814 if (DEBUG_PREFERRED || debug) { 3815 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3816 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3817 + "\n component=" + ppa.mComponent); 3818 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3819 } 3820 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3821 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3822 if (DEBUG_PREFERRED || debug) { 3823 Slog.v(TAG, "Found persistent preferred activity:"); 3824 if (ai != null) { 3825 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3826 } else { 3827 Slog.v(TAG, " null"); 3828 } 3829 } 3830 if (ai == null) { 3831 // This previously registered persistent preferred activity 3832 // component is no longer known. Ignore it and do NOT remove it. 3833 continue; 3834 } 3835 for (int j=0; j<N; j++) { 3836 final ResolveInfo ri = query.get(j); 3837 if (!ri.activityInfo.applicationInfo.packageName 3838 .equals(ai.applicationInfo.packageName)) { 3839 continue; 3840 } 3841 if (!ri.activityInfo.name.equals(ai.name)) { 3842 continue; 3843 } 3844 // Found a persistent preference that can handle the intent. 3845 if (DEBUG_PREFERRED || debug) { 3846 Slog.v(TAG, "Returning persistent preferred activity: " + 3847 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3848 } 3849 return ri; 3850 } 3851 } 3852 } 3853 return null; 3854 } 3855 3856 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3857 List<ResolveInfo> query, int priority, boolean always, 3858 boolean removeMatches, boolean debug, int userId) { 3859 if (!sUserManager.exists(userId)) return null; 3860 // writer 3861 synchronized (mPackages) { 3862 if (intent.getSelector() != null) { 3863 intent = intent.getSelector(); 3864 } 3865 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3866 3867 // Try to find a matching persistent preferred activity. 3868 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3869 debug, userId); 3870 3871 // If a persistent preferred activity matched, use it. 3872 if (pri != null) { 3873 return pri; 3874 } 3875 3876 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3877 // Get the list of preferred activities that handle the intent 3878 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3879 List<PreferredActivity> prefs = pir != null 3880 ? pir.queryIntent(intent, resolvedType, 3881 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3882 : null; 3883 if (prefs != null && prefs.size() > 0) { 3884 boolean changed = false; 3885 try { 3886 // First figure out how good the original match set is. 3887 // We will only allow preferred activities that came 3888 // from the same match quality. 3889 int match = 0; 3890 3891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3892 3893 final int N = query.size(); 3894 for (int j=0; j<N; j++) { 3895 final ResolveInfo ri = query.get(j); 3896 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3897 + ": 0x" + Integer.toHexString(match)); 3898 if (ri.match > match) { 3899 match = ri.match; 3900 } 3901 } 3902 3903 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3904 + Integer.toHexString(match)); 3905 3906 match &= IntentFilter.MATCH_CATEGORY_MASK; 3907 final int M = prefs.size(); 3908 for (int i=0; i<M; i++) { 3909 final PreferredActivity pa = prefs.get(i); 3910 if (DEBUG_PREFERRED || debug) { 3911 Slog.v(TAG, "Checking PreferredActivity ds=" 3912 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3913 + "\n component=" + pa.mPref.mComponent); 3914 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3915 } 3916 if (pa.mPref.mMatch != match) { 3917 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3918 + Integer.toHexString(pa.mPref.mMatch)); 3919 continue; 3920 } 3921 // If it's not an "always" type preferred activity and that's what we're 3922 // looking for, skip it. 3923 if (always && !pa.mPref.mAlways) { 3924 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3925 continue; 3926 } 3927 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3928 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3929 if (DEBUG_PREFERRED || debug) { 3930 Slog.v(TAG, "Found preferred activity:"); 3931 if (ai != null) { 3932 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3933 } else { 3934 Slog.v(TAG, " null"); 3935 } 3936 } 3937 if (ai == null) { 3938 // This previously registered preferred activity 3939 // component is no longer known. Most likely an update 3940 // to the app was installed and in the new version this 3941 // component no longer exists. Clean it up by removing 3942 // it from the preferred activities list, and skip it. 3943 Slog.w(TAG, "Removing dangling preferred activity: " 3944 + pa.mPref.mComponent); 3945 pir.removeFilter(pa); 3946 changed = true; 3947 continue; 3948 } 3949 for (int j=0; j<N; j++) { 3950 final ResolveInfo ri = query.get(j); 3951 if (!ri.activityInfo.applicationInfo.packageName 3952 .equals(ai.applicationInfo.packageName)) { 3953 continue; 3954 } 3955 if (!ri.activityInfo.name.equals(ai.name)) { 3956 continue; 3957 } 3958 3959 if (removeMatches) { 3960 pir.removeFilter(pa); 3961 changed = true; 3962 if (DEBUG_PREFERRED) { 3963 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3964 } 3965 break; 3966 } 3967 3968 // Okay we found a previously set preferred or last chosen app. 3969 // If the result set is different from when this 3970 // was created, we need to clear it and re-ask the 3971 // user their preference, if we're looking for an "always" type entry. 3972 if (always && !pa.mPref.sameSet(query)) { 3973 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3974 + intent + " type " + resolvedType); 3975 if (DEBUG_PREFERRED) { 3976 Slog.v(TAG, "Removing preferred activity since set changed " 3977 + pa.mPref.mComponent); 3978 } 3979 pir.removeFilter(pa); 3980 // Re-add the filter as a "last chosen" entry (!always) 3981 PreferredActivity lastChosen = new PreferredActivity( 3982 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3983 pir.addFilter(lastChosen); 3984 changed = true; 3985 return null; 3986 } 3987 3988 // Yay! Either the set matched or we're looking for the last chosen 3989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3990 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3991 return ri; 3992 } 3993 } 3994 } finally { 3995 if (changed) { 3996 if (DEBUG_PREFERRED) { 3997 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3998 } 3999 scheduleWritePackageRestrictionsLocked(userId); 4000 } 4001 } 4002 } 4003 } 4004 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4005 return null; 4006 } 4007 4008 /* 4009 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4010 */ 4011 @Override 4012 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4013 int targetUserId) { 4014 mContext.enforceCallingOrSelfPermission( 4015 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4016 List<CrossProfileIntentFilter> matches = 4017 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4018 if (matches != null) { 4019 int size = matches.size(); 4020 for (int i = 0; i < size; i++) { 4021 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4022 } 4023 } 4024 return false; 4025 } 4026 4027 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4028 String resolvedType, int userId) { 4029 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4030 if (resolver != null) { 4031 return resolver.queryIntent(intent, resolvedType, false, userId); 4032 } 4033 return null; 4034 } 4035 4036 @Override 4037 public List<ResolveInfo> queryIntentActivities(Intent intent, 4038 String resolvedType, int flags, int userId) { 4039 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4040 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4041 ComponentName comp = intent.getComponent(); 4042 if (comp == null) { 4043 if (intent.getSelector() != null) { 4044 intent = intent.getSelector(); 4045 comp = intent.getComponent(); 4046 } 4047 } 4048 4049 if (comp != null) { 4050 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4051 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4052 if (ai != null) { 4053 final ResolveInfo ri = new ResolveInfo(); 4054 ri.activityInfo = ai; 4055 list.add(ri); 4056 } 4057 return list; 4058 } 4059 4060 // reader 4061 synchronized (mPackages) { 4062 final String pkgName = intent.getPackage(); 4063 if (pkgName == null) { 4064 List<CrossProfileIntentFilter> matchingFilters = 4065 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4066 // Check for results that need to skip the current profile. 4067 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4068 resolvedType, flags, userId); 4069 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4070 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4071 result.add(resolveInfo); 4072 return filterIfNotPrimaryUser(result, userId); 4073 } 4074 4075 // Check for results in the current profile. 4076 List<ResolveInfo> result = mActivities.queryIntent( 4077 intent, resolvedType, flags, userId); 4078 4079 // Check for cross profile results. 4080 resolveInfo = queryCrossProfileIntents( 4081 matchingFilters, intent, resolvedType, flags, userId); 4082 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4083 result.add(resolveInfo); 4084 Collections.sort(result, mResolvePrioritySorter); 4085 } 4086 result = filterIfNotPrimaryUser(result, userId); 4087 if (result.size() > 1 && hasWebURI(intent)) { 4088 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4089 } 4090 return result; 4091 } 4092 final PackageParser.Package pkg = mPackages.get(pkgName); 4093 if (pkg != null) { 4094 return filterIfNotPrimaryUser( 4095 mActivities.queryIntentForPackage( 4096 intent, resolvedType, flags, pkg.activities, userId), 4097 userId); 4098 } 4099 return new ArrayList<ResolveInfo>(); 4100 } 4101 } 4102 4103 private boolean isUserEnabled(int userId) { 4104 long callingId = Binder.clearCallingIdentity(); 4105 try { 4106 UserInfo userInfo = sUserManager.getUserInfo(userId); 4107 return userInfo != null && userInfo.isEnabled(); 4108 } finally { 4109 Binder.restoreCallingIdentity(callingId); 4110 } 4111 } 4112 4113 /** 4114 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4115 * 4116 * @return filtered list 4117 */ 4118 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4119 if (userId == UserHandle.USER_OWNER) { 4120 return resolveInfos; 4121 } 4122 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4123 ResolveInfo info = resolveInfos.get(i); 4124 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4125 resolveInfos.remove(i); 4126 } 4127 } 4128 return resolveInfos; 4129 } 4130 4131 private static boolean hasWebURI(Intent intent) { 4132 if (intent.getData() == null) { 4133 return false; 4134 } 4135 final String scheme = intent.getScheme(); 4136 if (TextUtils.isEmpty(scheme)) { 4137 return false; 4138 } 4139 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4140 } 4141 4142 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4143 int flags, List<ResolveInfo> candidates) { 4144 if (DEBUG_PREFERRED) { 4145 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4146 candidates.size()); 4147 } 4148 4149 final int userId = UserHandle.getCallingUserId(); 4150 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4151 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4152 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4153 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4154 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4155 4156 synchronized (mPackages) { 4157 final int count = candidates.size(); 4158 // First, try to use the domain prefered App. Partition the candidates into four lists: 4159 // one for the final results, one for the "do not use ever", one for "undefined status" 4160 // and finally one for "Browser App type". 4161 for (int n=0; n<count; n++) { 4162 ResolveInfo info = candidates.get(n); 4163 String packageName = info.activityInfo.packageName; 4164 PackageSetting ps = mSettings.mPackages.get(packageName); 4165 if (ps != null) { 4166 // Add to the special match all list (Browser use case) 4167 if (info.handleAllWebDataURI) { 4168 matchAllList.add(info); 4169 continue; 4170 } 4171 // Try to get the status from User settings first 4172 int status = getDomainVerificationStatusLPr(ps, userId); 4173 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4174 alwaysList.add(info); 4175 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4176 neverList.add(info); 4177 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4178 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4179 undefinedList.add(info); 4180 } 4181 } 4182 } 4183 // First try to add the "always" if there is any 4184 if (alwaysList.size() > 0) { 4185 result.addAll(alwaysList); 4186 } else { 4187 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4188 result.addAll(undefinedList); 4189 // Also add Browsers (all of them or only the default one) 4190 if ((flags & MATCH_ALL) != 0) { 4191 result.addAll(matchAllList); 4192 } else { 4193 // Try to add the Default Browser if we can 4194 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4195 UserHandle.myUserId()); 4196 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4197 boolean defaultBrowserFound = false; 4198 final int browserCount = matchAllList.size(); 4199 for (int n=0; n<browserCount; n++) { 4200 ResolveInfo browser = matchAllList.get(n); 4201 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4202 result.add(browser); 4203 defaultBrowserFound = true; 4204 break; 4205 } 4206 } 4207 if (!defaultBrowserFound) { 4208 result.addAll(matchAllList); 4209 } 4210 } else { 4211 result.addAll(matchAllList); 4212 } 4213 } 4214 4215 // If there is nothing selected, add all candidates and remove the ones that the User 4216 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4217 if (result.size() == 0) { 4218 result.addAll(candidates); 4219 result.removeAll(neverList); 4220 } 4221 } 4222 } 4223 if (DEBUG_PREFERRED) { 4224 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4225 result.size()); 4226 } 4227 return result; 4228 } 4229 4230 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4231 int status = ps.getDomainVerificationStatusForUser(userId); 4232 // if none available, get the master status 4233 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4234 if (ps.getIntentFilterVerificationInfo() != null) { 4235 status = ps.getIntentFilterVerificationInfo().getStatus(); 4236 } 4237 } 4238 return status; 4239 } 4240 4241 private ResolveInfo querySkipCurrentProfileIntents( 4242 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4243 int flags, int sourceUserId) { 4244 if (matchingFilters != null) { 4245 int size = matchingFilters.size(); 4246 for (int i = 0; i < size; i ++) { 4247 CrossProfileIntentFilter filter = matchingFilters.get(i); 4248 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4249 // Checking if there are activities in the target user that can handle the 4250 // intent. 4251 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4252 flags, sourceUserId); 4253 if (resolveInfo != null) { 4254 return resolveInfo; 4255 } 4256 } 4257 } 4258 } 4259 return null; 4260 } 4261 4262 // Return matching ResolveInfo if any for skip current profile intent filters. 4263 private ResolveInfo queryCrossProfileIntents( 4264 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4265 int flags, int sourceUserId) { 4266 if (matchingFilters != null) { 4267 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4268 // match the same intent. For performance reasons, it is better not to 4269 // run queryIntent twice for the same userId 4270 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4271 int size = matchingFilters.size(); 4272 for (int i = 0; i < size; i++) { 4273 CrossProfileIntentFilter filter = matchingFilters.get(i); 4274 int targetUserId = filter.getTargetUserId(); 4275 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4276 && !alreadyTriedUserIds.get(targetUserId)) { 4277 // Checking if there are activities in the target user that can handle the 4278 // intent. 4279 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4280 flags, sourceUserId); 4281 if (resolveInfo != null) return resolveInfo; 4282 alreadyTriedUserIds.put(targetUserId, true); 4283 } 4284 } 4285 } 4286 return null; 4287 } 4288 4289 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4290 String resolvedType, int flags, int sourceUserId) { 4291 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4292 resolvedType, flags, filter.getTargetUserId()); 4293 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4294 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4295 } 4296 return null; 4297 } 4298 4299 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4300 int sourceUserId, int targetUserId) { 4301 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4302 String className; 4303 if (targetUserId == UserHandle.USER_OWNER) { 4304 className = FORWARD_INTENT_TO_USER_OWNER; 4305 } else { 4306 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4307 } 4308 ComponentName forwardingActivityComponentName = new ComponentName( 4309 mAndroidApplication.packageName, className); 4310 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4311 sourceUserId); 4312 if (targetUserId == UserHandle.USER_OWNER) { 4313 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4314 forwardingResolveInfo.noResourceId = true; 4315 } 4316 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4317 forwardingResolveInfo.priority = 0; 4318 forwardingResolveInfo.preferredOrder = 0; 4319 forwardingResolveInfo.match = 0; 4320 forwardingResolveInfo.isDefault = true; 4321 forwardingResolveInfo.filter = filter; 4322 forwardingResolveInfo.targetUserId = targetUserId; 4323 return forwardingResolveInfo; 4324 } 4325 4326 @Override 4327 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4328 Intent[] specifics, String[] specificTypes, Intent intent, 4329 String resolvedType, int flags, int userId) { 4330 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4331 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4332 false, "query intent activity options"); 4333 final String resultsAction = intent.getAction(); 4334 4335 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4336 | PackageManager.GET_RESOLVED_FILTER, userId); 4337 4338 if (DEBUG_INTENT_MATCHING) { 4339 Log.v(TAG, "Query " + intent + ": " + results); 4340 } 4341 4342 int specificsPos = 0; 4343 int N; 4344 4345 // todo: note that the algorithm used here is O(N^2). This 4346 // isn't a problem in our current environment, but if we start running 4347 // into situations where we have more than 5 or 10 matches then this 4348 // should probably be changed to something smarter... 4349 4350 // First we go through and resolve each of the specific items 4351 // that were supplied, taking care of removing any corresponding 4352 // duplicate items in the generic resolve list. 4353 if (specifics != null) { 4354 for (int i=0; i<specifics.length; i++) { 4355 final Intent sintent = specifics[i]; 4356 if (sintent == null) { 4357 continue; 4358 } 4359 4360 if (DEBUG_INTENT_MATCHING) { 4361 Log.v(TAG, "Specific #" + i + ": " + sintent); 4362 } 4363 4364 String action = sintent.getAction(); 4365 if (resultsAction != null && resultsAction.equals(action)) { 4366 // If this action was explicitly requested, then don't 4367 // remove things that have it. 4368 action = null; 4369 } 4370 4371 ResolveInfo ri = null; 4372 ActivityInfo ai = null; 4373 4374 ComponentName comp = sintent.getComponent(); 4375 if (comp == null) { 4376 ri = resolveIntent( 4377 sintent, 4378 specificTypes != null ? specificTypes[i] : null, 4379 flags, userId); 4380 if (ri == null) { 4381 continue; 4382 } 4383 if (ri == mResolveInfo) { 4384 // ACK! Must do something better with this. 4385 } 4386 ai = ri.activityInfo; 4387 comp = new ComponentName(ai.applicationInfo.packageName, 4388 ai.name); 4389 } else { 4390 ai = getActivityInfo(comp, flags, userId); 4391 if (ai == null) { 4392 continue; 4393 } 4394 } 4395 4396 // Look for any generic query activities that are duplicates 4397 // of this specific one, and remove them from the results. 4398 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4399 N = results.size(); 4400 int j; 4401 for (j=specificsPos; j<N; j++) { 4402 ResolveInfo sri = results.get(j); 4403 if ((sri.activityInfo.name.equals(comp.getClassName()) 4404 && sri.activityInfo.applicationInfo.packageName.equals( 4405 comp.getPackageName())) 4406 || (action != null && sri.filter.matchAction(action))) { 4407 results.remove(j); 4408 if (DEBUG_INTENT_MATCHING) Log.v( 4409 TAG, "Removing duplicate item from " + j 4410 + " due to specific " + specificsPos); 4411 if (ri == null) { 4412 ri = sri; 4413 } 4414 j--; 4415 N--; 4416 } 4417 } 4418 4419 // Add this specific item to its proper place. 4420 if (ri == null) { 4421 ri = new ResolveInfo(); 4422 ri.activityInfo = ai; 4423 } 4424 results.add(specificsPos, ri); 4425 ri.specificIndex = i; 4426 specificsPos++; 4427 } 4428 } 4429 4430 // Now we go through the remaining generic results and remove any 4431 // duplicate actions that are found here. 4432 N = results.size(); 4433 for (int i=specificsPos; i<N-1; i++) { 4434 final ResolveInfo rii = results.get(i); 4435 if (rii.filter == null) { 4436 continue; 4437 } 4438 4439 // Iterate over all of the actions of this result's intent 4440 // filter... typically this should be just one. 4441 final Iterator<String> it = rii.filter.actionsIterator(); 4442 if (it == null) { 4443 continue; 4444 } 4445 while (it.hasNext()) { 4446 final String action = it.next(); 4447 if (resultsAction != null && resultsAction.equals(action)) { 4448 // If this action was explicitly requested, then don't 4449 // remove things that have it. 4450 continue; 4451 } 4452 for (int j=i+1; j<N; j++) { 4453 final ResolveInfo rij = results.get(j); 4454 if (rij.filter != null && rij.filter.hasAction(action)) { 4455 results.remove(j); 4456 if (DEBUG_INTENT_MATCHING) Log.v( 4457 TAG, "Removing duplicate item from " + j 4458 + " due to action " + action + " at " + i); 4459 j--; 4460 N--; 4461 } 4462 } 4463 } 4464 4465 // If the caller didn't request filter information, drop it now 4466 // so we don't have to marshall/unmarshall it. 4467 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4468 rii.filter = null; 4469 } 4470 } 4471 4472 // Filter out the caller activity if so requested. 4473 if (caller != null) { 4474 N = results.size(); 4475 for (int i=0; i<N; i++) { 4476 ActivityInfo ainfo = results.get(i).activityInfo; 4477 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4478 && caller.getClassName().equals(ainfo.name)) { 4479 results.remove(i); 4480 break; 4481 } 4482 } 4483 } 4484 4485 // If the caller didn't request filter information, 4486 // drop them now so we don't have to 4487 // marshall/unmarshall it. 4488 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4489 N = results.size(); 4490 for (int i=0; i<N; i++) { 4491 results.get(i).filter = null; 4492 } 4493 } 4494 4495 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4496 return results; 4497 } 4498 4499 @Override 4500 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4501 int userId) { 4502 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4503 ComponentName comp = intent.getComponent(); 4504 if (comp == null) { 4505 if (intent.getSelector() != null) { 4506 intent = intent.getSelector(); 4507 comp = intent.getComponent(); 4508 } 4509 } 4510 if (comp != null) { 4511 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4512 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4513 if (ai != null) { 4514 ResolveInfo ri = new ResolveInfo(); 4515 ri.activityInfo = ai; 4516 list.add(ri); 4517 } 4518 return list; 4519 } 4520 4521 // reader 4522 synchronized (mPackages) { 4523 String pkgName = intent.getPackage(); 4524 if (pkgName == null) { 4525 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4526 } 4527 final PackageParser.Package pkg = mPackages.get(pkgName); 4528 if (pkg != null) { 4529 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4530 userId); 4531 } 4532 return null; 4533 } 4534 } 4535 4536 @Override 4537 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4538 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4539 if (!sUserManager.exists(userId)) return null; 4540 if (query != null) { 4541 if (query.size() >= 1) { 4542 // If there is more than one service with the same priority, 4543 // just arbitrarily pick the first one. 4544 return query.get(0); 4545 } 4546 } 4547 return null; 4548 } 4549 4550 @Override 4551 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4552 int userId) { 4553 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4554 ComponentName comp = intent.getComponent(); 4555 if (comp == null) { 4556 if (intent.getSelector() != null) { 4557 intent = intent.getSelector(); 4558 comp = intent.getComponent(); 4559 } 4560 } 4561 if (comp != null) { 4562 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4563 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4564 if (si != null) { 4565 final ResolveInfo ri = new ResolveInfo(); 4566 ri.serviceInfo = si; 4567 list.add(ri); 4568 } 4569 return list; 4570 } 4571 4572 // reader 4573 synchronized (mPackages) { 4574 String pkgName = intent.getPackage(); 4575 if (pkgName == null) { 4576 return mServices.queryIntent(intent, resolvedType, flags, userId); 4577 } 4578 final PackageParser.Package pkg = mPackages.get(pkgName); 4579 if (pkg != null) { 4580 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4581 userId); 4582 } 4583 return null; 4584 } 4585 } 4586 4587 @Override 4588 public List<ResolveInfo> queryIntentContentProviders( 4589 Intent intent, String resolvedType, int flags, int userId) { 4590 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4591 ComponentName comp = intent.getComponent(); 4592 if (comp == null) { 4593 if (intent.getSelector() != null) { 4594 intent = intent.getSelector(); 4595 comp = intent.getComponent(); 4596 } 4597 } 4598 if (comp != null) { 4599 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4600 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4601 if (pi != null) { 4602 final ResolveInfo ri = new ResolveInfo(); 4603 ri.providerInfo = pi; 4604 list.add(ri); 4605 } 4606 return list; 4607 } 4608 4609 // reader 4610 synchronized (mPackages) { 4611 String pkgName = intent.getPackage(); 4612 if (pkgName == null) { 4613 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4614 } 4615 final PackageParser.Package pkg = mPackages.get(pkgName); 4616 if (pkg != null) { 4617 return mProviders.queryIntentForPackage( 4618 intent, resolvedType, flags, pkg.providers, userId); 4619 } 4620 return null; 4621 } 4622 } 4623 4624 @Override 4625 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4626 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4627 4628 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4629 4630 // writer 4631 synchronized (mPackages) { 4632 ArrayList<PackageInfo> list; 4633 if (listUninstalled) { 4634 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4635 for (PackageSetting ps : mSettings.mPackages.values()) { 4636 PackageInfo pi; 4637 if (ps.pkg != null) { 4638 pi = generatePackageInfo(ps.pkg, flags, userId); 4639 } else { 4640 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4641 } 4642 if (pi != null) { 4643 list.add(pi); 4644 } 4645 } 4646 } else { 4647 list = new ArrayList<PackageInfo>(mPackages.size()); 4648 for (PackageParser.Package p : mPackages.values()) { 4649 PackageInfo pi = generatePackageInfo(p, flags, userId); 4650 if (pi != null) { 4651 list.add(pi); 4652 } 4653 } 4654 } 4655 4656 return new ParceledListSlice<PackageInfo>(list); 4657 } 4658 } 4659 4660 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4661 String[] permissions, boolean[] tmp, int flags, int userId) { 4662 int numMatch = 0; 4663 final PermissionsState permissionsState = ps.getPermissionsState(); 4664 for (int i=0; i<permissions.length; i++) { 4665 final String permission = permissions[i]; 4666 if (permissionsState.hasPermission(permission, userId)) { 4667 tmp[i] = true; 4668 numMatch++; 4669 } else { 4670 tmp[i] = false; 4671 } 4672 } 4673 if (numMatch == 0) { 4674 return; 4675 } 4676 PackageInfo pi; 4677 if (ps.pkg != null) { 4678 pi = generatePackageInfo(ps.pkg, flags, userId); 4679 } else { 4680 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4681 } 4682 // The above might return null in cases of uninstalled apps or install-state 4683 // skew across users/profiles. 4684 if (pi != null) { 4685 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4686 if (numMatch == permissions.length) { 4687 pi.requestedPermissions = permissions; 4688 } else { 4689 pi.requestedPermissions = new String[numMatch]; 4690 numMatch = 0; 4691 for (int i=0; i<permissions.length; i++) { 4692 if (tmp[i]) { 4693 pi.requestedPermissions[numMatch] = permissions[i]; 4694 numMatch++; 4695 } 4696 } 4697 } 4698 } 4699 list.add(pi); 4700 } 4701 } 4702 4703 @Override 4704 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4705 String[] permissions, int flags, int userId) { 4706 if (!sUserManager.exists(userId)) return null; 4707 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4708 4709 // writer 4710 synchronized (mPackages) { 4711 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4712 boolean[] tmpBools = new boolean[permissions.length]; 4713 if (listUninstalled) { 4714 for (PackageSetting ps : mSettings.mPackages.values()) { 4715 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4716 } 4717 } else { 4718 for (PackageParser.Package pkg : mPackages.values()) { 4719 PackageSetting ps = (PackageSetting)pkg.mExtras; 4720 if (ps != null) { 4721 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4722 userId); 4723 } 4724 } 4725 } 4726 4727 return new ParceledListSlice<PackageInfo>(list); 4728 } 4729 } 4730 4731 @Override 4732 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4733 if (!sUserManager.exists(userId)) return null; 4734 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4735 4736 // writer 4737 synchronized (mPackages) { 4738 ArrayList<ApplicationInfo> list; 4739 if (listUninstalled) { 4740 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4741 for (PackageSetting ps : mSettings.mPackages.values()) { 4742 ApplicationInfo ai; 4743 if (ps.pkg != null) { 4744 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4745 ps.readUserState(userId), userId); 4746 } else { 4747 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4748 } 4749 if (ai != null) { 4750 list.add(ai); 4751 } 4752 } 4753 } else { 4754 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4755 for (PackageParser.Package p : mPackages.values()) { 4756 if (p.mExtras != null) { 4757 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4758 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4759 if (ai != null) { 4760 list.add(ai); 4761 } 4762 } 4763 } 4764 } 4765 4766 return new ParceledListSlice<ApplicationInfo>(list); 4767 } 4768 } 4769 4770 public List<ApplicationInfo> getPersistentApplications(int flags) { 4771 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4772 4773 // reader 4774 synchronized (mPackages) { 4775 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4776 final int userId = UserHandle.getCallingUserId(); 4777 while (i.hasNext()) { 4778 final PackageParser.Package p = i.next(); 4779 if (p.applicationInfo != null 4780 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4781 && (!mSafeMode || isSystemApp(p))) { 4782 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4783 if (ps != null) { 4784 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4785 ps.readUserState(userId), userId); 4786 if (ai != null) { 4787 finalList.add(ai); 4788 } 4789 } 4790 } 4791 } 4792 } 4793 4794 return finalList; 4795 } 4796 4797 @Override 4798 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4799 if (!sUserManager.exists(userId)) return null; 4800 // reader 4801 synchronized (mPackages) { 4802 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4803 PackageSetting ps = provider != null 4804 ? mSettings.mPackages.get(provider.owner.packageName) 4805 : null; 4806 return ps != null 4807 && mSettings.isEnabledLPr(provider.info, flags, userId) 4808 && (!mSafeMode || (provider.info.applicationInfo.flags 4809 &ApplicationInfo.FLAG_SYSTEM) != 0) 4810 ? PackageParser.generateProviderInfo(provider, flags, 4811 ps.readUserState(userId), userId) 4812 : null; 4813 } 4814 } 4815 4816 /** 4817 * @deprecated 4818 */ 4819 @Deprecated 4820 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4821 // reader 4822 synchronized (mPackages) { 4823 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4824 .entrySet().iterator(); 4825 final int userId = UserHandle.getCallingUserId(); 4826 while (i.hasNext()) { 4827 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4828 PackageParser.Provider p = entry.getValue(); 4829 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4830 4831 if (ps != null && p.syncable 4832 && (!mSafeMode || (p.info.applicationInfo.flags 4833 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4834 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4835 ps.readUserState(userId), userId); 4836 if (info != null) { 4837 outNames.add(entry.getKey()); 4838 outInfo.add(info); 4839 } 4840 } 4841 } 4842 } 4843 } 4844 4845 @Override 4846 public List<ProviderInfo> queryContentProviders(String processName, 4847 int uid, int flags) { 4848 ArrayList<ProviderInfo> finalList = null; 4849 // reader 4850 synchronized (mPackages) { 4851 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4852 final int userId = processName != null ? 4853 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4854 while (i.hasNext()) { 4855 final PackageParser.Provider p = i.next(); 4856 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4857 if (ps != null && p.info.authority != null 4858 && (processName == null 4859 || (p.info.processName.equals(processName) 4860 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4861 && mSettings.isEnabledLPr(p.info, flags, userId) 4862 && (!mSafeMode 4863 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4864 if (finalList == null) { 4865 finalList = new ArrayList<ProviderInfo>(3); 4866 } 4867 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4868 ps.readUserState(userId), userId); 4869 if (info != null) { 4870 finalList.add(info); 4871 } 4872 } 4873 } 4874 } 4875 4876 if (finalList != null) { 4877 Collections.sort(finalList, mProviderInitOrderSorter); 4878 } 4879 4880 return finalList; 4881 } 4882 4883 @Override 4884 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4885 int flags) { 4886 // reader 4887 synchronized (mPackages) { 4888 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4889 return PackageParser.generateInstrumentationInfo(i, flags); 4890 } 4891 } 4892 4893 @Override 4894 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4895 int flags) { 4896 ArrayList<InstrumentationInfo> finalList = 4897 new ArrayList<InstrumentationInfo>(); 4898 4899 // reader 4900 synchronized (mPackages) { 4901 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4902 while (i.hasNext()) { 4903 final PackageParser.Instrumentation p = i.next(); 4904 if (targetPackage == null 4905 || targetPackage.equals(p.info.targetPackage)) { 4906 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4907 flags); 4908 if (ii != null) { 4909 finalList.add(ii); 4910 } 4911 } 4912 } 4913 } 4914 4915 return finalList; 4916 } 4917 4918 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4919 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4920 if (overlays == null) { 4921 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4922 return; 4923 } 4924 for (PackageParser.Package opkg : overlays.values()) { 4925 // Not much to do if idmap fails: we already logged the error 4926 // and we certainly don't want to abort installation of pkg simply 4927 // because an overlay didn't fit properly. For these reasons, 4928 // ignore the return value of createIdmapForPackagePairLI. 4929 createIdmapForPackagePairLI(pkg, opkg); 4930 } 4931 } 4932 4933 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4934 PackageParser.Package opkg) { 4935 if (!opkg.mTrustedOverlay) { 4936 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4937 opkg.baseCodePath + ": overlay not trusted"); 4938 return false; 4939 } 4940 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4941 if (overlaySet == null) { 4942 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4943 opkg.baseCodePath + " but target package has no known overlays"); 4944 return false; 4945 } 4946 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4947 // TODO: generate idmap for split APKs 4948 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4949 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4950 + opkg.baseCodePath); 4951 return false; 4952 } 4953 PackageParser.Package[] overlayArray = 4954 overlaySet.values().toArray(new PackageParser.Package[0]); 4955 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4956 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4957 return p1.mOverlayPriority - p2.mOverlayPriority; 4958 } 4959 }; 4960 Arrays.sort(overlayArray, cmp); 4961 4962 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4963 int i = 0; 4964 for (PackageParser.Package p : overlayArray) { 4965 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4966 } 4967 return true; 4968 } 4969 4970 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4971 final File[] files = dir.listFiles(); 4972 if (ArrayUtils.isEmpty(files)) { 4973 Log.d(TAG, "No files in app dir " + dir); 4974 return; 4975 } 4976 4977 if (DEBUG_PACKAGE_SCANNING) { 4978 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4979 + " flags=0x" + Integer.toHexString(parseFlags)); 4980 } 4981 4982 for (File file : files) { 4983 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4984 && !PackageInstallerService.isStageName(file.getName()); 4985 if (!isPackage) { 4986 // Ignore entries which are not packages 4987 continue; 4988 } 4989 try { 4990 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4991 scanFlags, currentTime, null); 4992 } catch (PackageManagerException e) { 4993 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4994 4995 // Delete invalid userdata apps 4996 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4997 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4998 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4999 if (file.isDirectory()) { 5000 mInstaller.rmPackageDir(file.getAbsolutePath()); 5001 } else { 5002 file.delete(); 5003 } 5004 } 5005 } 5006 } 5007 } 5008 5009 private static File getSettingsProblemFile() { 5010 File dataDir = Environment.getDataDirectory(); 5011 File systemDir = new File(dataDir, "system"); 5012 File fname = new File(systemDir, "uiderrors.txt"); 5013 return fname; 5014 } 5015 5016 static void reportSettingsProblem(int priority, String msg) { 5017 logCriticalInfo(priority, msg); 5018 } 5019 5020 static void logCriticalInfo(int priority, String msg) { 5021 Slog.println(priority, TAG, msg); 5022 EventLogTags.writePmCriticalInfo(msg); 5023 try { 5024 File fname = getSettingsProblemFile(); 5025 FileOutputStream out = new FileOutputStream(fname, true); 5026 PrintWriter pw = new FastPrintWriter(out); 5027 SimpleDateFormat formatter = new SimpleDateFormat(); 5028 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5029 pw.println(dateString + ": " + msg); 5030 pw.close(); 5031 FileUtils.setPermissions( 5032 fname.toString(), 5033 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5034 -1, -1); 5035 } catch (java.io.IOException e) { 5036 } 5037 } 5038 5039 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5040 PackageParser.Package pkg, File srcFile, int parseFlags) 5041 throws PackageManagerException { 5042 if (ps != null 5043 && ps.codePath.equals(srcFile) 5044 && ps.timeStamp == srcFile.lastModified() 5045 && !isCompatSignatureUpdateNeeded(pkg) 5046 && !isRecoverSignatureUpdateNeeded(pkg)) { 5047 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5048 if (ps.signatures.mSignatures != null 5049 && ps.signatures.mSignatures.length != 0 5050 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5051 // Optimization: reuse the existing cached certificates 5052 // if the package appears to be unchanged. 5053 pkg.mSignatures = ps.signatures.mSignatures; 5054 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5055 synchronized (mPackages) { 5056 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5057 } 5058 return; 5059 } 5060 5061 Slog.w(TAG, "PackageSetting for " + ps.name 5062 + " is missing signatures. Collecting certs again to recover them."); 5063 } else { 5064 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5065 } 5066 5067 try { 5068 pp.collectCertificates(pkg, parseFlags); 5069 pp.collectManifestDigest(pkg); 5070 } catch (PackageParserException e) { 5071 throw PackageManagerException.from(e); 5072 } 5073 } 5074 5075 /* 5076 * Scan a package and return the newly parsed package. 5077 * Returns null in case of errors and the error code is stored in mLastScanError 5078 */ 5079 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5080 long currentTime, UserHandle user) throws PackageManagerException { 5081 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5082 parseFlags |= mDefParseFlags; 5083 PackageParser pp = new PackageParser(); 5084 pp.setSeparateProcesses(mSeparateProcesses); 5085 pp.setOnlyCoreApps(mOnlyCore); 5086 pp.setDisplayMetrics(mMetrics); 5087 5088 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5089 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5090 } 5091 5092 final PackageParser.Package pkg; 5093 try { 5094 pkg = pp.parsePackage(scanFile, parseFlags); 5095 } catch (PackageParserException e) { 5096 throw PackageManagerException.from(e); 5097 } 5098 5099 PackageSetting ps = null; 5100 PackageSetting updatedPkg; 5101 // reader 5102 synchronized (mPackages) { 5103 // Look to see if we already know about this package. 5104 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5105 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5106 // This package has been renamed to its original name. Let's 5107 // use that. 5108 ps = mSettings.peekPackageLPr(oldName); 5109 } 5110 // If there was no original package, see one for the real package name. 5111 if (ps == null) { 5112 ps = mSettings.peekPackageLPr(pkg.packageName); 5113 } 5114 // Check to see if this package could be hiding/updating a system 5115 // package. Must look for it either under the original or real 5116 // package name depending on our state. 5117 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5118 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5119 } 5120 boolean updatedPkgBetter = false; 5121 // First check if this is a system package that may involve an update 5122 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5123 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5124 // it needs to drop FLAG_PRIVILEGED. 5125 if (locationIsPrivileged(scanFile)) { 5126 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5127 } else { 5128 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5129 } 5130 5131 if (ps != null && !ps.codePath.equals(scanFile)) { 5132 // The path has changed from what was last scanned... check the 5133 // version of the new path against what we have stored to determine 5134 // what to do. 5135 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5136 if (pkg.mVersionCode <= ps.versionCode) { 5137 // The system package has been updated and the code path does not match 5138 // Ignore entry. Skip it. 5139 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5140 + " ignored: updated version " + ps.versionCode 5141 + " better than this " + pkg.mVersionCode); 5142 if (!updatedPkg.codePath.equals(scanFile)) { 5143 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5144 + ps.name + " changing from " + updatedPkg.codePathString 5145 + " to " + scanFile); 5146 updatedPkg.codePath = scanFile; 5147 updatedPkg.codePathString = scanFile.toString(); 5148 updatedPkg.resourcePath = scanFile; 5149 updatedPkg.resourcePathString = scanFile.toString(); 5150 } 5151 updatedPkg.pkg = pkg; 5152 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5153 } else { 5154 // The current app on the system partition is better than 5155 // what we have updated to on the data partition; switch 5156 // back to the system partition version. 5157 // At this point, its safely assumed that package installation for 5158 // apps in system partition will go through. If not there won't be a working 5159 // version of the app 5160 // writer 5161 synchronized (mPackages) { 5162 // Just remove the loaded entries from package lists. 5163 mPackages.remove(ps.name); 5164 } 5165 5166 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5167 + " reverting from " + ps.codePathString 5168 + ": new version " + pkg.mVersionCode 5169 + " better than installed " + ps.versionCode); 5170 5171 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5172 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5173 synchronized (mInstallLock) { 5174 args.cleanUpResourcesLI(); 5175 } 5176 synchronized (mPackages) { 5177 mSettings.enableSystemPackageLPw(ps.name); 5178 } 5179 updatedPkgBetter = true; 5180 } 5181 } 5182 } 5183 5184 if (updatedPkg != null) { 5185 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5186 // initially 5187 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5188 5189 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5190 // flag set initially 5191 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5192 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5193 } 5194 } 5195 5196 // Verify certificates against what was last scanned 5197 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5198 5199 /* 5200 * A new system app appeared, but we already had a non-system one of the 5201 * same name installed earlier. 5202 */ 5203 boolean shouldHideSystemApp = false; 5204 if (updatedPkg == null && ps != null 5205 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5206 /* 5207 * Check to make sure the signatures match first. If they don't, 5208 * wipe the installed application and its data. 5209 */ 5210 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5211 != PackageManager.SIGNATURE_MATCH) { 5212 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5213 + " signatures don't match existing userdata copy; removing"); 5214 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5215 ps = null; 5216 } else { 5217 /* 5218 * If the newly-added system app is an older version than the 5219 * already installed version, hide it. It will be scanned later 5220 * and re-added like an update. 5221 */ 5222 if (pkg.mVersionCode <= ps.versionCode) { 5223 shouldHideSystemApp = true; 5224 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5225 + " but new version " + pkg.mVersionCode + " better than installed " 5226 + ps.versionCode + "; hiding system"); 5227 } else { 5228 /* 5229 * The newly found system app is a newer version that the 5230 * one previously installed. Simply remove the 5231 * already-installed application and replace it with our own 5232 * while keeping the application data. 5233 */ 5234 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5235 + " reverting from " + ps.codePathString + ": new version " 5236 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5237 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5238 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5239 synchronized (mInstallLock) { 5240 args.cleanUpResourcesLI(); 5241 } 5242 } 5243 } 5244 } 5245 5246 // The apk is forward locked (not public) if its code and resources 5247 // are kept in different files. (except for app in either system or 5248 // vendor path). 5249 // TODO grab this value from PackageSettings 5250 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5251 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5252 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5253 } 5254 } 5255 5256 // TODO: extend to support forward-locked splits 5257 String resourcePath = null; 5258 String baseResourcePath = null; 5259 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5260 if (ps != null && ps.resourcePathString != null) { 5261 resourcePath = ps.resourcePathString; 5262 baseResourcePath = ps.resourcePathString; 5263 } else { 5264 // Should not happen at all. Just log an error. 5265 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5266 } 5267 } else { 5268 resourcePath = pkg.codePath; 5269 baseResourcePath = pkg.baseCodePath; 5270 } 5271 5272 // Set application objects path explicitly. 5273 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5274 pkg.applicationInfo.setCodePath(pkg.codePath); 5275 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5276 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5277 pkg.applicationInfo.setResourcePath(resourcePath); 5278 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5279 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5280 5281 // Note that we invoke the following method only if we are about to unpack an application 5282 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5283 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5284 5285 /* 5286 * If the system app should be overridden by a previously installed 5287 * data, hide the system app now and let the /data/app scan pick it up 5288 * again. 5289 */ 5290 if (shouldHideSystemApp) { 5291 synchronized (mPackages) { 5292 /* 5293 * We have to grant systems permissions before we hide, because 5294 * grantPermissions will assume the package update is trying to 5295 * expand its permissions. 5296 */ 5297 grantPermissionsLPw(pkg, true, pkg.packageName); 5298 mSettings.disableSystemPackageLPw(pkg.packageName); 5299 } 5300 } 5301 5302 return scannedPkg; 5303 } 5304 5305 private static String fixProcessName(String defProcessName, 5306 String processName, int uid) { 5307 if (processName == null) { 5308 return defProcessName; 5309 } 5310 return processName; 5311 } 5312 5313 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5314 throws PackageManagerException { 5315 if (pkgSetting.signatures.mSignatures != null) { 5316 // Already existing package. Make sure signatures match 5317 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5318 == PackageManager.SIGNATURE_MATCH; 5319 if (!match) { 5320 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5321 == PackageManager.SIGNATURE_MATCH; 5322 } 5323 if (!match) { 5324 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5325 == PackageManager.SIGNATURE_MATCH; 5326 } 5327 if (!match) { 5328 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5329 + pkg.packageName + " signatures do not match the " 5330 + "previously installed version; ignoring!"); 5331 } 5332 } 5333 5334 // Check for shared user signatures 5335 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5336 // Already existing package. Make sure signatures match 5337 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5338 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5339 if (!match) { 5340 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5341 == PackageManager.SIGNATURE_MATCH; 5342 } 5343 if (!match) { 5344 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5345 == PackageManager.SIGNATURE_MATCH; 5346 } 5347 if (!match) { 5348 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5349 "Package " + pkg.packageName 5350 + " has no signatures that match those in shared user " 5351 + pkgSetting.sharedUser.name + "; ignoring!"); 5352 } 5353 } 5354 } 5355 5356 /** 5357 * Enforces that only the system UID or root's UID can call a method exposed 5358 * via Binder. 5359 * 5360 * @param message used as message if SecurityException is thrown 5361 * @throws SecurityException if the caller is not system or root 5362 */ 5363 private static final void enforceSystemOrRoot(String message) { 5364 final int uid = Binder.getCallingUid(); 5365 if (uid != Process.SYSTEM_UID && uid != 0) { 5366 throw new SecurityException(message); 5367 } 5368 } 5369 5370 @Override 5371 public void performBootDexOpt() { 5372 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5373 5374 // Before everything else, see whether we need to fstrim. 5375 try { 5376 IMountService ms = PackageHelper.getMountService(); 5377 if (ms != null) { 5378 final boolean isUpgrade = isUpgrade(); 5379 boolean doTrim = isUpgrade; 5380 if (doTrim) { 5381 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5382 } else { 5383 final long interval = android.provider.Settings.Global.getLong( 5384 mContext.getContentResolver(), 5385 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5386 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5387 if (interval > 0) { 5388 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5389 if (timeSinceLast > interval) { 5390 doTrim = true; 5391 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5392 + "; running immediately"); 5393 } 5394 } 5395 } 5396 if (doTrim) { 5397 if (!isFirstBoot()) { 5398 try { 5399 ActivityManagerNative.getDefault().showBootMessage( 5400 mContext.getResources().getString( 5401 R.string.android_upgrading_fstrim), true); 5402 } catch (RemoteException e) { 5403 } 5404 } 5405 ms.runMaintenance(); 5406 } 5407 } else { 5408 Slog.e(TAG, "Mount service unavailable!"); 5409 } 5410 } catch (RemoteException e) { 5411 // Can't happen; MountService is local 5412 } 5413 5414 final ArraySet<PackageParser.Package> pkgs; 5415 synchronized (mPackages) { 5416 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5417 } 5418 5419 if (pkgs != null) { 5420 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5421 // in case the device runs out of space. 5422 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5423 // Give priority to core apps. 5424 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5425 PackageParser.Package pkg = it.next(); 5426 if (pkg.coreApp) { 5427 if (DEBUG_DEXOPT) { 5428 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5429 } 5430 sortedPkgs.add(pkg); 5431 it.remove(); 5432 } 5433 } 5434 // Give priority to system apps that listen for pre boot complete. 5435 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5436 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5437 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5438 PackageParser.Package pkg = it.next(); 5439 if (pkgNames.contains(pkg.packageName)) { 5440 if (DEBUG_DEXOPT) { 5441 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5442 } 5443 sortedPkgs.add(pkg); 5444 it.remove(); 5445 } 5446 } 5447 // Give priority to system apps. 5448 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5449 PackageParser.Package pkg = it.next(); 5450 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5451 if (DEBUG_DEXOPT) { 5452 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5453 } 5454 sortedPkgs.add(pkg); 5455 it.remove(); 5456 } 5457 } 5458 // Give priority to updated system apps. 5459 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5460 PackageParser.Package pkg = it.next(); 5461 if (pkg.isUpdatedSystemApp()) { 5462 if (DEBUG_DEXOPT) { 5463 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5464 } 5465 sortedPkgs.add(pkg); 5466 it.remove(); 5467 } 5468 } 5469 // Give priority to apps that listen for boot complete. 5470 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5471 pkgNames = getPackageNamesForIntent(intent); 5472 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5473 PackageParser.Package pkg = it.next(); 5474 if (pkgNames.contains(pkg.packageName)) { 5475 if (DEBUG_DEXOPT) { 5476 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5477 } 5478 sortedPkgs.add(pkg); 5479 it.remove(); 5480 } 5481 } 5482 // Filter out packages that aren't recently used. 5483 filterRecentlyUsedApps(pkgs); 5484 // Add all remaining apps. 5485 for (PackageParser.Package pkg : pkgs) { 5486 if (DEBUG_DEXOPT) { 5487 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5488 } 5489 sortedPkgs.add(pkg); 5490 } 5491 5492 // If we want to be lazy, filter everything that wasn't recently used. 5493 if (mLazyDexOpt) { 5494 filterRecentlyUsedApps(sortedPkgs); 5495 } 5496 5497 int i = 0; 5498 int total = sortedPkgs.size(); 5499 File dataDir = Environment.getDataDirectory(); 5500 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5501 if (lowThreshold == 0) { 5502 throw new IllegalStateException("Invalid low memory threshold"); 5503 } 5504 for (PackageParser.Package pkg : sortedPkgs) { 5505 long usableSpace = dataDir.getUsableSpace(); 5506 if (usableSpace < lowThreshold) { 5507 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5508 break; 5509 } 5510 performBootDexOpt(pkg, ++i, total); 5511 } 5512 } 5513 } 5514 5515 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5516 // Filter out packages that aren't recently used. 5517 // 5518 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5519 // should do a full dexopt. 5520 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5521 int total = pkgs.size(); 5522 int skipped = 0; 5523 long now = System.currentTimeMillis(); 5524 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5525 PackageParser.Package pkg = i.next(); 5526 long then = pkg.mLastPackageUsageTimeInMills; 5527 if (then + mDexOptLRUThresholdInMills < now) { 5528 if (DEBUG_DEXOPT) { 5529 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5530 ((then == 0) ? "never" : new Date(then))); 5531 } 5532 i.remove(); 5533 skipped++; 5534 } 5535 } 5536 if (DEBUG_DEXOPT) { 5537 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5538 } 5539 } 5540 } 5541 5542 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5543 List<ResolveInfo> ris = null; 5544 try { 5545 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5546 intent, null, 0, UserHandle.USER_OWNER); 5547 } catch (RemoteException e) { 5548 } 5549 ArraySet<String> pkgNames = new ArraySet<String>(); 5550 if (ris != null) { 5551 for (ResolveInfo ri : ris) { 5552 pkgNames.add(ri.activityInfo.packageName); 5553 } 5554 } 5555 return pkgNames; 5556 } 5557 5558 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5559 if (DEBUG_DEXOPT) { 5560 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5561 } 5562 if (!isFirstBoot()) { 5563 try { 5564 ActivityManagerNative.getDefault().showBootMessage( 5565 mContext.getResources().getString(R.string.android_upgrading_apk, 5566 curr, total), true); 5567 } catch (RemoteException e) { 5568 } 5569 } 5570 PackageParser.Package p = pkg; 5571 synchronized (mInstallLock) { 5572 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5573 false /* force dex */, false /* defer */, true /* include dependencies */); 5574 } 5575 } 5576 5577 @Override 5578 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5579 return performDexOpt(packageName, instructionSet, false); 5580 } 5581 5582 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5583 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5584 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5585 if (!dexopt && !updateUsage) { 5586 // We aren't going to dexopt or update usage, so bail early. 5587 return false; 5588 } 5589 PackageParser.Package p; 5590 final String targetInstructionSet; 5591 synchronized (mPackages) { 5592 p = mPackages.get(packageName); 5593 if (p == null) { 5594 return false; 5595 } 5596 if (updateUsage) { 5597 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5598 } 5599 mPackageUsage.write(false); 5600 if (!dexopt) { 5601 // We aren't going to dexopt, so bail early. 5602 return false; 5603 } 5604 5605 targetInstructionSet = instructionSet != null ? instructionSet : 5606 getPrimaryInstructionSet(p.applicationInfo); 5607 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5608 return false; 5609 } 5610 } 5611 5612 synchronized (mInstallLock) { 5613 final String[] instructionSets = new String[] { targetInstructionSet }; 5614 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5615 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5616 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5617 } 5618 } 5619 5620 public ArraySet<String> getPackagesThatNeedDexOpt() { 5621 ArraySet<String> pkgs = null; 5622 synchronized (mPackages) { 5623 for (PackageParser.Package p : mPackages.values()) { 5624 if (DEBUG_DEXOPT) { 5625 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5626 } 5627 if (!p.mDexOptPerformed.isEmpty()) { 5628 continue; 5629 } 5630 if (pkgs == null) { 5631 pkgs = new ArraySet<String>(); 5632 } 5633 pkgs.add(p.packageName); 5634 } 5635 } 5636 return pkgs; 5637 } 5638 5639 public void shutdown() { 5640 mPackageUsage.write(true); 5641 } 5642 5643 @Override 5644 public void forceDexOpt(String packageName) { 5645 enforceSystemOrRoot("forceDexOpt"); 5646 5647 PackageParser.Package pkg; 5648 synchronized (mPackages) { 5649 pkg = mPackages.get(packageName); 5650 if (pkg == null) { 5651 throw new IllegalArgumentException("Missing package: " + packageName); 5652 } 5653 } 5654 5655 synchronized (mInstallLock) { 5656 final String[] instructionSets = new String[] { 5657 getPrimaryInstructionSet(pkg.applicationInfo) }; 5658 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5659 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5660 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5661 throw new IllegalStateException("Failed to dexopt: " + res); 5662 } 5663 } 5664 } 5665 5666 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5667 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5668 Slog.w(TAG, "Unable to update from " + oldPkg.name 5669 + " to " + newPkg.packageName 5670 + ": old package not in system partition"); 5671 return false; 5672 } else if (mPackages.get(oldPkg.name) != null) { 5673 Slog.w(TAG, "Unable to update from " + oldPkg.name 5674 + " to " + newPkg.packageName 5675 + ": old package still exists"); 5676 return false; 5677 } 5678 return true; 5679 } 5680 5681 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5682 int[] users = sUserManager.getUserIds(); 5683 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5684 if (res < 0) { 5685 return res; 5686 } 5687 for (int user : users) { 5688 if (user != 0) { 5689 res = mInstaller.createUserData(volumeUuid, packageName, 5690 UserHandle.getUid(user, uid), user, seinfo); 5691 if (res < 0) { 5692 return res; 5693 } 5694 } 5695 } 5696 return res; 5697 } 5698 5699 private int removeDataDirsLI(String volumeUuid, String packageName) { 5700 int[] users = sUserManager.getUserIds(); 5701 int res = 0; 5702 for (int user : users) { 5703 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5704 if (resInner < 0) { 5705 res = resInner; 5706 } 5707 } 5708 5709 return res; 5710 } 5711 5712 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5713 int[] users = sUserManager.getUserIds(); 5714 int res = 0; 5715 for (int user : users) { 5716 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5717 if (resInner < 0) { 5718 res = resInner; 5719 } 5720 } 5721 return res; 5722 } 5723 5724 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5725 PackageParser.Package changingLib) { 5726 if (file.path != null) { 5727 usesLibraryFiles.add(file.path); 5728 return; 5729 } 5730 PackageParser.Package p = mPackages.get(file.apk); 5731 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5732 // If we are doing this while in the middle of updating a library apk, 5733 // then we need to make sure to use that new apk for determining the 5734 // dependencies here. (We haven't yet finished committing the new apk 5735 // to the package manager state.) 5736 if (p == null || p.packageName.equals(changingLib.packageName)) { 5737 p = changingLib; 5738 } 5739 } 5740 if (p != null) { 5741 usesLibraryFiles.addAll(p.getAllCodePaths()); 5742 } 5743 } 5744 5745 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5746 PackageParser.Package changingLib) throws PackageManagerException { 5747 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5748 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5749 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5750 for (int i=0; i<N; i++) { 5751 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5752 if (file == null) { 5753 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5754 "Package " + pkg.packageName + " requires unavailable shared library " 5755 + pkg.usesLibraries.get(i) + "; failing!"); 5756 } 5757 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5758 } 5759 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5760 for (int i=0; i<N; i++) { 5761 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5762 if (file == null) { 5763 Slog.w(TAG, "Package " + pkg.packageName 5764 + " desires unavailable shared library " 5765 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5766 } else { 5767 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5768 } 5769 } 5770 N = usesLibraryFiles.size(); 5771 if (N > 0) { 5772 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5773 } else { 5774 pkg.usesLibraryFiles = null; 5775 } 5776 } 5777 } 5778 5779 private static boolean hasString(List<String> list, List<String> which) { 5780 if (list == null) { 5781 return false; 5782 } 5783 for (int i=list.size()-1; i>=0; i--) { 5784 for (int j=which.size()-1; j>=0; j--) { 5785 if (which.get(j).equals(list.get(i))) { 5786 return true; 5787 } 5788 } 5789 } 5790 return false; 5791 } 5792 5793 private void updateAllSharedLibrariesLPw() { 5794 for (PackageParser.Package pkg : mPackages.values()) { 5795 try { 5796 updateSharedLibrariesLPw(pkg, null); 5797 } catch (PackageManagerException e) { 5798 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5799 } 5800 } 5801 } 5802 5803 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5804 PackageParser.Package changingPkg) { 5805 ArrayList<PackageParser.Package> res = null; 5806 for (PackageParser.Package pkg : mPackages.values()) { 5807 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5808 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5809 if (res == null) { 5810 res = new ArrayList<PackageParser.Package>(); 5811 } 5812 res.add(pkg); 5813 try { 5814 updateSharedLibrariesLPw(pkg, changingPkg); 5815 } catch (PackageManagerException e) { 5816 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5817 } 5818 } 5819 } 5820 return res; 5821 } 5822 5823 /** 5824 * Derive the value of the {@code cpuAbiOverride} based on the provided 5825 * value and an optional stored value from the package settings. 5826 */ 5827 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5828 String cpuAbiOverride = null; 5829 5830 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5831 cpuAbiOverride = null; 5832 } else if (abiOverride != null) { 5833 cpuAbiOverride = abiOverride; 5834 } else if (settings != null) { 5835 cpuAbiOverride = settings.cpuAbiOverrideString; 5836 } 5837 5838 return cpuAbiOverride; 5839 } 5840 5841 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5842 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5843 boolean success = false; 5844 try { 5845 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5846 currentTime, user); 5847 success = true; 5848 return res; 5849 } finally { 5850 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5851 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5852 } 5853 } 5854 } 5855 5856 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5857 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5858 final File scanFile = new File(pkg.codePath); 5859 if (pkg.applicationInfo.getCodePath() == null || 5860 pkg.applicationInfo.getResourcePath() == null) { 5861 // Bail out. The resource and code paths haven't been set. 5862 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5863 "Code and resource paths haven't been set correctly"); 5864 } 5865 5866 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5867 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5868 } else { 5869 // Only allow system apps to be flagged as core apps. 5870 pkg.coreApp = false; 5871 } 5872 5873 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5874 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5875 } 5876 5877 if (mCustomResolverComponentName != null && 5878 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5879 setUpCustomResolverActivity(pkg); 5880 } 5881 5882 if (pkg.packageName.equals("android")) { 5883 synchronized (mPackages) { 5884 if (mAndroidApplication != null) { 5885 Slog.w(TAG, "*************************************************"); 5886 Slog.w(TAG, "Core android package being redefined. Skipping."); 5887 Slog.w(TAG, " file=" + scanFile); 5888 Slog.w(TAG, "*************************************************"); 5889 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5890 "Core android package being redefined. Skipping."); 5891 } 5892 5893 // Set up information for our fall-back user intent resolution activity. 5894 mPlatformPackage = pkg; 5895 pkg.mVersionCode = mSdkVersion; 5896 mAndroidApplication = pkg.applicationInfo; 5897 5898 if (!mResolverReplaced) { 5899 mResolveActivity.applicationInfo = mAndroidApplication; 5900 mResolveActivity.name = ResolverActivity.class.getName(); 5901 mResolveActivity.packageName = mAndroidApplication.packageName; 5902 mResolveActivity.processName = "system:ui"; 5903 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5904 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5905 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5906 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5907 mResolveActivity.exported = true; 5908 mResolveActivity.enabled = true; 5909 mResolveInfo.activityInfo = mResolveActivity; 5910 mResolveInfo.priority = 0; 5911 mResolveInfo.preferredOrder = 0; 5912 mResolveInfo.match = 0; 5913 mResolveComponentName = new ComponentName( 5914 mAndroidApplication.packageName, mResolveActivity.name); 5915 } 5916 } 5917 } 5918 5919 if (DEBUG_PACKAGE_SCANNING) { 5920 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5921 Log.d(TAG, "Scanning package " + pkg.packageName); 5922 } 5923 5924 if (mPackages.containsKey(pkg.packageName) 5925 || mSharedLibraries.containsKey(pkg.packageName)) { 5926 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5927 "Application package " + pkg.packageName 5928 + " already installed. Skipping duplicate."); 5929 } 5930 5931 // If we're only installing presumed-existing packages, require that the 5932 // scanned APK is both already known and at the path previously established 5933 // for it. Previously unknown packages we pick up normally, but if we have an 5934 // a priori expectation about this package's install presence, enforce it. 5935 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5936 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5937 if (known != null) { 5938 if (DEBUG_PACKAGE_SCANNING) { 5939 Log.d(TAG, "Examining " + pkg.codePath 5940 + " and requiring known paths " + known.codePathString 5941 + " & " + known.resourcePathString); 5942 } 5943 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5944 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5945 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5946 "Application package " + pkg.packageName 5947 + " found at " + pkg.applicationInfo.getCodePath() 5948 + " but expected at " + known.codePathString + "; ignoring."); 5949 } 5950 } 5951 } 5952 5953 // Initialize package source and resource directories 5954 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5955 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5956 5957 SharedUserSetting suid = null; 5958 PackageSetting pkgSetting = null; 5959 5960 if (!isSystemApp(pkg)) { 5961 // Only system apps can use these features. 5962 pkg.mOriginalPackages = null; 5963 pkg.mRealPackage = null; 5964 pkg.mAdoptPermissions = null; 5965 } 5966 5967 // writer 5968 synchronized (mPackages) { 5969 if (pkg.mSharedUserId != null) { 5970 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5971 if (suid == null) { 5972 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5973 "Creating application package " + pkg.packageName 5974 + " for shared user failed"); 5975 } 5976 if (DEBUG_PACKAGE_SCANNING) { 5977 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5978 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5979 + "): packages=" + suid.packages); 5980 } 5981 } 5982 5983 // Check if we are renaming from an original package name. 5984 PackageSetting origPackage = null; 5985 String realName = null; 5986 if (pkg.mOriginalPackages != null) { 5987 // This package may need to be renamed to a previously 5988 // installed name. Let's check on that... 5989 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5990 if (pkg.mOriginalPackages.contains(renamed)) { 5991 // This package had originally been installed as the 5992 // original name, and we have already taken care of 5993 // transitioning to the new one. Just update the new 5994 // one to continue using the old name. 5995 realName = pkg.mRealPackage; 5996 if (!pkg.packageName.equals(renamed)) { 5997 // Callers into this function may have already taken 5998 // care of renaming the package; only do it here if 5999 // it is not already done. 6000 pkg.setPackageName(renamed); 6001 } 6002 6003 } else { 6004 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6005 if ((origPackage = mSettings.peekPackageLPr( 6006 pkg.mOriginalPackages.get(i))) != null) { 6007 // We do have the package already installed under its 6008 // original name... should we use it? 6009 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6010 // New package is not compatible with original. 6011 origPackage = null; 6012 continue; 6013 } else if (origPackage.sharedUser != null) { 6014 // Make sure uid is compatible between packages. 6015 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6016 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6017 + " to " + pkg.packageName + ": old uid " 6018 + origPackage.sharedUser.name 6019 + " differs from " + pkg.mSharedUserId); 6020 origPackage = null; 6021 continue; 6022 } 6023 } else { 6024 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6025 + pkg.packageName + " to old name " + origPackage.name); 6026 } 6027 break; 6028 } 6029 } 6030 } 6031 } 6032 6033 if (mTransferedPackages.contains(pkg.packageName)) { 6034 Slog.w(TAG, "Package " + pkg.packageName 6035 + " was transferred to another, but its .apk remains"); 6036 } 6037 6038 // Just create the setting, don't add it yet. For already existing packages 6039 // the PkgSetting exists already and doesn't have to be created. 6040 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6041 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6042 pkg.applicationInfo.primaryCpuAbi, 6043 pkg.applicationInfo.secondaryCpuAbi, 6044 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6045 user, false); 6046 if (pkgSetting == null) { 6047 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6048 "Creating application package " + pkg.packageName + " failed"); 6049 } 6050 6051 if (pkgSetting.origPackage != null) { 6052 // If we are first transitioning from an original package, 6053 // fix up the new package's name now. We need to do this after 6054 // looking up the package under its new name, so getPackageLP 6055 // can take care of fiddling things correctly. 6056 pkg.setPackageName(origPackage.name); 6057 6058 // File a report about this. 6059 String msg = "New package " + pkgSetting.realName 6060 + " renamed to replace old package " + pkgSetting.name; 6061 reportSettingsProblem(Log.WARN, msg); 6062 6063 // Make a note of it. 6064 mTransferedPackages.add(origPackage.name); 6065 6066 // No longer need to retain this. 6067 pkgSetting.origPackage = null; 6068 } 6069 6070 if (realName != null) { 6071 // Make a note of it. 6072 mTransferedPackages.add(pkg.packageName); 6073 } 6074 6075 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6076 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6077 } 6078 6079 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6080 // Check all shared libraries and map to their actual file path. 6081 // We only do this here for apps not on a system dir, because those 6082 // are the only ones that can fail an install due to this. We 6083 // will take care of the system apps by updating all of their 6084 // library paths after the scan is done. 6085 updateSharedLibrariesLPw(pkg, null); 6086 } 6087 6088 if (mFoundPolicyFile) { 6089 SELinuxMMAC.assignSeinfoValue(pkg); 6090 } 6091 6092 pkg.applicationInfo.uid = pkgSetting.appId; 6093 pkg.mExtras = pkgSetting; 6094 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6095 try { 6096 verifySignaturesLP(pkgSetting, pkg); 6097 // We just determined the app is signed correctly, so bring 6098 // over the latest parsed certs. 6099 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6100 } catch (PackageManagerException e) { 6101 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6102 throw e; 6103 } 6104 // The signature has changed, but this package is in the system 6105 // image... let's recover! 6106 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6107 // However... if this package is part of a shared user, but it 6108 // doesn't match the signature of the shared user, let's fail. 6109 // What this means is that you can't change the signatures 6110 // associated with an overall shared user, which doesn't seem all 6111 // that unreasonable. 6112 if (pkgSetting.sharedUser != null) { 6113 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6114 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6115 throw new PackageManagerException( 6116 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6117 "Signature mismatch for shared user : " 6118 + pkgSetting.sharedUser); 6119 } 6120 } 6121 // File a report about this. 6122 String msg = "System package " + pkg.packageName 6123 + " signature changed; retaining data."; 6124 reportSettingsProblem(Log.WARN, msg); 6125 } 6126 } else { 6127 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6128 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6129 + pkg.packageName + " upgrade keys do not match the " 6130 + "previously installed version"); 6131 } else { 6132 // We just determined the app is signed correctly, so bring 6133 // over the latest parsed certs. 6134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6135 } 6136 } 6137 // Verify that this new package doesn't have any content providers 6138 // that conflict with existing packages. Only do this if the 6139 // package isn't already installed, since we don't want to break 6140 // things that are installed. 6141 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6142 final int N = pkg.providers.size(); 6143 int i; 6144 for (i=0; i<N; i++) { 6145 PackageParser.Provider p = pkg.providers.get(i); 6146 if (p.info.authority != null) { 6147 String names[] = p.info.authority.split(";"); 6148 for (int j = 0; j < names.length; j++) { 6149 if (mProvidersByAuthority.containsKey(names[j])) { 6150 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6151 final String otherPackageName = 6152 ((other != null && other.getComponentName() != null) ? 6153 other.getComponentName().getPackageName() : "?"); 6154 throw new PackageManagerException( 6155 INSTALL_FAILED_CONFLICTING_PROVIDER, 6156 "Can't install because provider name " + names[j] 6157 + " (in package " + pkg.applicationInfo.packageName 6158 + ") is already used by " + otherPackageName); 6159 } 6160 } 6161 } 6162 } 6163 } 6164 6165 if (pkg.mAdoptPermissions != null) { 6166 // This package wants to adopt ownership of permissions from 6167 // another package. 6168 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6169 final String origName = pkg.mAdoptPermissions.get(i); 6170 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6171 if (orig != null) { 6172 if (verifyPackageUpdateLPr(orig, pkg)) { 6173 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6174 + pkg.packageName); 6175 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6176 } 6177 } 6178 } 6179 } 6180 } 6181 6182 final String pkgName = pkg.packageName; 6183 6184 final long scanFileTime = scanFile.lastModified(); 6185 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6186 pkg.applicationInfo.processName = fixProcessName( 6187 pkg.applicationInfo.packageName, 6188 pkg.applicationInfo.processName, 6189 pkg.applicationInfo.uid); 6190 6191 File dataPath; 6192 if (mPlatformPackage == pkg) { 6193 // The system package is special. 6194 dataPath = new File(Environment.getDataDirectory(), "system"); 6195 6196 pkg.applicationInfo.dataDir = dataPath.getPath(); 6197 6198 } else { 6199 // This is a normal package, need to make its data directory. 6200 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6201 UserHandle.USER_OWNER); 6202 6203 boolean uidError = false; 6204 if (dataPath.exists()) { 6205 int currentUid = 0; 6206 try { 6207 StructStat stat = Os.stat(dataPath.getPath()); 6208 currentUid = stat.st_uid; 6209 } catch (ErrnoException e) { 6210 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6211 } 6212 6213 // If we have mismatched owners for the data path, we have a problem. 6214 if (currentUid != pkg.applicationInfo.uid) { 6215 boolean recovered = false; 6216 if (currentUid == 0) { 6217 // The directory somehow became owned by root. Wow. 6218 // This is probably because the system was stopped while 6219 // installd was in the middle of messing with its libs 6220 // directory. Ask installd to fix that. 6221 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6222 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6223 if (ret >= 0) { 6224 recovered = true; 6225 String msg = "Package " + pkg.packageName 6226 + " unexpectedly changed to uid 0; recovered to " + 6227 + pkg.applicationInfo.uid; 6228 reportSettingsProblem(Log.WARN, msg); 6229 } 6230 } 6231 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6232 || (scanFlags&SCAN_BOOTING) != 0)) { 6233 // If this is a system app, we can at least delete its 6234 // current data so the application will still work. 6235 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6236 if (ret >= 0) { 6237 // TODO: Kill the processes first 6238 // Old data gone! 6239 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6240 ? "System package " : "Third party package "; 6241 String msg = prefix + pkg.packageName 6242 + " has changed from uid: " 6243 + currentUid + " to " 6244 + pkg.applicationInfo.uid + "; old data erased"; 6245 reportSettingsProblem(Log.WARN, msg); 6246 recovered = true; 6247 6248 // And now re-install the app. 6249 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6250 pkg.applicationInfo.seinfo); 6251 if (ret == -1) { 6252 // Ack should not happen! 6253 msg = prefix + pkg.packageName 6254 + " could not have data directory re-created after delete."; 6255 reportSettingsProblem(Log.WARN, msg); 6256 throw new PackageManagerException( 6257 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6258 } 6259 } 6260 if (!recovered) { 6261 mHasSystemUidErrors = true; 6262 } 6263 } else if (!recovered) { 6264 // If we allow this install to proceed, we will be broken. 6265 // Abort, abort! 6266 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6267 "scanPackageLI"); 6268 } 6269 if (!recovered) { 6270 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6271 + pkg.applicationInfo.uid + "/fs_" 6272 + currentUid; 6273 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6274 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6275 String msg = "Package " + pkg.packageName 6276 + " has mismatched uid: " 6277 + currentUid + " on disk, " 6278 + pkg.applicationInfo.uid + " in settings"; 6279 // writer 6280 synchronized (mPackages) { 6281 mSettings.mReadMessages.append(msg); 6282 mSettings.mReadMessages.append('\n'); 6283 uidError = true; 6284 if (!pkgSetting.uidError) { 6285 reportSettingsProblem(Log.ERROR, msg); 6286 } 6287 } 6288 } 6289 } 6290 pkg.applicationInfo.dataDir = dataPath.getPath(); 6291 if (mShouldRestoreconData) { 6292 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6293 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6294 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6295 } 6296 } else { 6297 if (DEBUG_PACKAGE_SCANNING) { 6298 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6299 Log.v(TAG, "Want this data dir: " + dataPath); 6300 } 6301 //invoke installer to do the actual installation 6302 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6303 pkg.applicationInfo.seinfo); 6304 if (ret < 0) { 6305 // Error from installer 6306 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6307 "Unable to create data dirs [errorCode=" + ret + "]"); 6308 } 6309 6310 if (dataPath.exists()) { 6311 pkg.applicationInfo.dataDir = dataPath.getPath(); 6312 } else { 6313 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6314 pkg.applicationInfo.dataDir = null; 6315 } 6316 } 6317 6318 pkgSetting.uidError = uidError; 6319 } 6320 6321 final String path = scanFile.getPath(); 6322 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6323 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6324 setBundledAppAbisAndRoots(pkg, pkgSetting); 6325 6326 // If we haven't found any native libraries for the app, check if it has 6327 // renderscript code. We'll need to force the app to 32 bit if it has 6328 // renderscript bitcode. 6329 if (pkg.applicationInfo.primaryCpuAbi == null 6330 && pkg.applicationInfo.secondaryCpuAbi == null 6331 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6332 NativeLibraryHelper.Handle handle = null; 6333 try { 6334 handle = NativeLibraryHelper.Handle.create(scanFile); 6335 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6336 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6337 } 6338 } catch (IOException ioe) { 6339 Slog.w(TAG, "Error scanning system app : " + ioe); 6340 } finally { 6341 IoUtils.closeQuietly(handle); 6342 } 6343 } 6344 6345 setNativeLibraryPaths(pkg); 6346 } else { 6347 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6348 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6349 } else { 6350 // TODO: We need this second call to derive in two cases : 6351 // 6352 // - To update the native library paths based on the final install location. 6353 // - We don't call dexopt when moving packages, and so we have to scan again. 6354 // 6355 // We can simplify this and avoid having to scan the package again by letting 6356 // scanPackageLI know if the current install was a move (and deriving things only 6357 // in that case) and by "reparenting" the native lib directory in the case of 6358 // a normal (non-move) install. 6359 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */); 6360 } 6361 6362 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6363 final int[] userIds = sUserManager.getUserIds(); 6364 synchronized (mInstallLock) { 6365 // Create a native library symlink only if we have native libraries 6366 // and if the native libraries are 32 bit libraries. We do not provide 6367 // this symlink for 64 bit libraries. 6368 if (pkg.applicationInfo.primaryCpuAbi != null && 6369 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6370 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6371 for (int userId : userIds) { 6372 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6373 nativeLibPath, userId) < 0) { 6374 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6375 "Failed linking native library dir (user=" + userId + ")"); 6376 } 6377 } 6378 } 6379 } 6380 } 6381 6382 // This is a special case for the "system" package, where the ABI is 6383 // dictated by the zygote configuration (and init.rc). We should keep track 6384 // of this ABI so that we can deal with "normal" applications that run under 6385 // the same UID correctly. 6386 if (mPlatformPackage == pkg) { 6387 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6388 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6389 } 6390 6391 // If there's a mismatch between the abi-override in the package setting 6392 // and the abiOverride specified for the install. Warn about this because we 6393 // would've already compiled the app without taking the package setting into 6394 // account. 6395 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6396 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6397 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6398 " for package: " + pkg.packageName); 6399 } 6400 } 6401 6402 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6403 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6404 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6405 6406 // Copy the derived override back to the parsed package, so that we can 6407 // update the package settings accordingly. 6408 pkg.cpuAbiOverride = cpuAbiOverride; 6409 6410 if (DEBUG_ABI_SELECTION) { 6411 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6412 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6413 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6414 } 6415 6416 // Push the derived path down into PackageSettings so we know what to 6417 // clean up at uninstall time. 6418 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6419 6420 if (DEBUG_ABI_SELECTION) { 6421 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6422 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6423 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6424 } 6425 6426 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6427 // We don't do this here during boot because we can do it all 6428 // at once after scanning all existing packages. 6429 // 6430 // We also do this *before* we perform dexopt on this package, so that 6431 // we can avoid redundant dexopts, and also to make sure we've got the 6432 // code and package path correct. 6433 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6434 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6435 } 6436 6437 if ((scanFlags & SCAN_NO_DEX) == 0) { 6438 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6439 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6440 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6441 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6442 } 6443 } 6444 if (mFactoryTest && pkg.requestedPermissions.contains( 6445 android.Manifest.permission.FACTORY_TEST)) { 6446 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6447 } 6448 6449 ArrayList<PackageParser.Package> clientLibPkgs = null; 6450 6451 // writer 6452 synchronized (mPackages) { 6453 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6454 // Only system apps can add new shared libraries. 6455 if (pkg.libraryNames != null) { 6456 for (int i=0; i<pkg.libraryNames.size(); i++) { 6457 String name = pkg.libraryNames.get(i); 6458 boolean allowed = false; 6459 if (pkg.isUpdatedSystemApp()) { 6460 // New library entries can only be added through the 6461 // system image. This is important to get rid of a lot 6462 // of nasty edge cases: for example if we allowed a non- 6463 // system update of the app to add a library, then uninstalling 6464 // the update would make the library go away, and assumptions 6465 // we made such as through app install filtering would now 6466 // have allowed apps on the device which aren't compatible 6467 // with it. Better to just have the restriction here, be 6468 // conservative, and create many fewer cases that can negatively 6469 // impact the user experience. 6470 final PackageSetting sysPs = mSettings 6471 .getDisabledSystemPkgLPr(pkg.packageName); 6472 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6473 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6474 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6475 allowed = true; 6476 allowed = true; 6477 break; 6478 } 6479 } 6480 } 6481 } else { 6482 allowed = true; 6483 } 6484 if (allowed) { 6485 if (!mSharedLibraries.containsKey(name)) { 6486 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6487 } else if (!name.equals(pkg.packageName)) { 6488 Slog.w(TAG, "Package " + pkg.packageName + " library " 6489 + name + " already exists; skipping"); 6490 } 6491 } else { 6492 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6493 + name + " that is not declared on system image; skipping"); 6494 } 6495 } 6496 if ((scanFlags&SCAN_BOOTING) == 0) { 6497 // If we are not booting, we need to update any applications 6498 // that are clients of our shared library. If we are booting, 6499 // this will all be done once the scan is complete. 6500 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6501 } 6502 } 6503 } 6504 } 6505 6506 // We also need to dexopt any apps that are dependent on this library. Note that 6507 // if these fail, we should abort the install since installing the library will 6508 // result in some apps being broken. 6509 if (clientLibPkgs != null) { 6510 if ((scanFlags & SCAN_NO_DEX) == 0) { 6511 for (int i = 0; i < clientLibPkgs.size(); i++) { 6512 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6513 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6514 null /* instruction sets */, forceDex, 6515 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6516 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6517 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6518 "scanPackageLI failed to dexopt clientLibPkgs"); 6519 } 6520 } 6521 } 6522 } 6523 6524 // Also need to kill any apps that are dependent on the library. 6525 if (clientLibPkgs != null) { 6526 for (int i=0; i<clientLibPkgs.size(); i++) { 6527 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6528 killApplication(clientPkg.applicationInfo.packageName, 6529 clientPkg.applicationInfo.uid, "update lib"); 6530 } 6531 } 6532 6533 // writer 6534 synchronized (mPackages) { 6535 // We don't expect installation to fail beyond this point 6536 6537 // Add the new setting to mSettings 6538 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6539 // Add the new setting to mPackages 6540 mPackages.put(pkg.applicationInfo.packageName, pkg); 6541 // Make sure we don't accidentally delete its data. 6542 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6543 while (iter.hasNext()) { 6544 PackageCleanItem item = iter.next(); 6545 if (pkgName.equals(item.packageName)) { 6546 iter.remove(); 6547 } 6548 } 6549 6550 // Take care of first install / last update times. 6551 if (currentTime != 0) { 6552 if (pkgSetting.firstInstallTime == 0) { 6553 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6554 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6555 pkgSetting.lastUpdateTime = currentTime; 6556 } 6557 } else if (pkgSetting.firstInstallTime == 0) { 6558 // We need *something*. Take time time stamp of the file. 6559 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6560 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6561 if (scanFileTime != pkgSetting.timeStamp) { 6562 // A package on the system image has changed; consider this 6563 // to be an update. 6564 pkgSetting.lastUpdateTime = scanFileTime; 6565 } 6566 } 6567 6568 // Add the package's KeySets to the global KeySetManagerService 6569 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6570 try { 6571 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6572 if (pkg.mKeySetMapping != null) { 6573 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6574 if (pkg.mUpgradeKeySets != null) { 6575 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6576 } 6577 } 6578 } catch (NullPointerException e) { 6579 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6580 } catch (IllegalArgumentException e) { 6581 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6582 } 6583 6584 int N = pkg.providers.size(); 6585 StringBuilder r = null; 6586 int i; 6587 for (i=0; i<N; i++) { 6588 PackageParser.Provider p = pkg.providers.get(i); 6589 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6590 p.info.processName, pkg.applicationInfo.uid); 6591 mProviders.addProvider(p); 6592 p.syncable = p.info.isSyncable; 6593 if (p.info.authority != null) { 6594 String names[] = p.info.authority.split(";"); 6595 p.info.authority = null; 6596 for (int j = 0; j < names.length; j++) { 6597 if (j == 1 && p.syncable) { 6598 // We only want the first authority for a provider to possibly be 6599 // syncable, so if we already added this provider using a different 6600 // authority clear the syncable flag. We copy the provider before 6601 // changing it because the mProviders object contains a reference 6602 // to a provider that we don't want to change. 6603 // Only do this for the second authority since the resulting provider 6604 // object can be the same for all future authorities for this provider. 6605 p = new PackageParser.Provider(p); 6606 p.syncable = false; 6607 } 6608 if (!mProvidersByAuthority.containsKey(names[j])) { 6609 mProvidersByAuthority.put(names[j], p); 6610 if (p.info.authority == null) { 6611 p.info.authority = names[j]; 6612 } else { 6613 p.info.authority = p.info.authority + ";" + names[j]; 6614 } 6615 if (DEBUG_PACKAGE_SCANNING) { 6616 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6617 Log.d(TAG, "Registered content provider: " + names[j] 6618 + ", className = " + p.info.name + ", isSyncable = " 6619 + p.info.isSyncable); 6620 } 6621 } else { 6622 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6623 Slog.w(TAG, "Skipping provider name " + names[j] + 6624 " (in package " + pkg.applicationInfo.packageName + 6625 "): name already used by " 6626 + ((other != null && other.getComponentName() != null) 6627 ? other.getComponentName().getPackageName() : "?")); 6628 } 6629 } 6630 } 6631 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6632 if (r == null) { 6633 r = new StringBuilder(256); 6634 } else { 6635 r.append(' '); 6636 } 6637 r.append(p.info.name); 6638 } 6639 } 6640 if (r != null) { 6641 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6642 } 6643 6644 N = pkg.services.size(); 6645 r = null; 6646 for (i=0; i<N; i++) { 6647 PackageParser.Service s = pkg.services.get(i); 6648 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6649 s.info.processName, pkg.applicationInfo.uid); 6650 mServices.addService(s); 6651 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6652 if (r == null) { 6653 r = new StringBuilder(256); 6654 } else { 6655 r.append(' '); 6656 } 6657 r.append(s.info.name); 6658 } 6659 } 6660 if (r != null) { 6661 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6662 } 6663 6664 N = pkg.receivers.size(); 6665 r = null; 6666 for (i=0; i<N; i++) { 6667 PackageParser.Activity a = pkg.receivers.get(i); 6668 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6669 a.info.processName, pkg.applicationInfo.uid); 6670 mReceivers.addActivity(a, "receiver"); 6671 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6672 if (r == null) { 6673 r = new StringBuilder(256); 6674 } else { 6675 r.append(' '); 6676 } 6677 r.append(a.info.name); 6678 } 6679 } 6680 if (r != null) { 6681 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6682 } 6683 6684 N = pkg.activities.size(); 6685 r = null; 6686 for (i=0; i<N; i++) { 6687 PackageParser.Activity a = pkg.activities.get(i); 6688 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6689 a.info.processName, pkg.applicationInfo.uid); 6690 mActivities.addActivity(a, "activity"); 6691 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6692 if (r == null) { 6693 r = new StringBuilder(256); 6694 } else { 6695 r.append(' '); 6696 } 6697 r.append(a.info.name); 6698 } 6699 } 6700 if (r != null) { 6701 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6702 } 6703 6704 N = pkg.permissionGroups.size(); 6705 r = null; 6706 for (i=0; i<N; i++) { 6707 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6708 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6709 if (cur == null) { 6710 mPermissionGroups.put(pg.info.name, pg); 6711 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6712 if (r == null) { 6713 r = new StringBuilder(256); 6714 } else { 6715 r.append(' '); 6716 } 6717 r.append(pg.info.name); 6718 } 6719 } else { 6720 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6721 + pg.info.packageName + " ignored: original from " 6722 + cur.info.packageName); 6723 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6724 if (r == null) { 6725 r = new StringBuilder(256); 6726 } else { 6727 r.append(' '); 6728 } 6729 r.append("DUP:"); 6730 r.append(pg.info.name); 6731 } 6732 } 6733 } 6734 if (r != null) { 6735 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6736 } 6737 6738 N = pkg.permissions.size(); 6739 r = null; 6740 for (i=0; i<N; i++) { 6741 PackageParser.Permission p = pkg.permissions.get(i); 6742 6743 // Now that permission groups have a special meaning, we ignore permission 6744 // groups for legacy apps to prevent unexpected behavior. In particular, 6745 // permissions for one app being granted to someone just becuase they happen 6746 // to be in a group defined by another app (before this had no implications). 6747 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6748 p.group = mPermissionGroups.get(p.info.group); 6749 // Warn for a permission in an unknown group. 6750 if (p.info.group != null && p.group == null) { 6751 Slog.w(TAG, "Permission " + p.info.name + " from package " 6752 + p.info.packageName + " in an unknown group " + p.info.group); 6753 } 6754 } 6755 6756 ArrayMap<String, BasePermission> permissionMap = 6757 p.tree ? mSettings.mPermissionTrees 6758 : mSettings.mPermissions; 6759 BasePermission bp = permissionMap.get(p.info.name); 6760 6761 // Allow system apps to redefine non-system permissions 6762 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6763 final boolean currentOwnerIsSystem = (bp.perm != null 6764 && isSystemApp(bp.perm.owner)); 6765 if (isSystemApp(p.owner)) { 6766 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6767 // It's a built-in permission and no owner, take ownership now 6768 bp.packageSetting = pkgSetting; 6769 bp.perm = p; 6770 bp.uid = pkg.applicationInfo.uid; 6771 bp.sourcePackage = p.info.packageName; 6772 } else if (!currentOwnerIsSystem) { 6773 String msg = "New decl " + p.owner + " of permission " 6774 + p.info.name + " is system; overriding " + bp.sourcePackage; 6775 reportSettingsProblem(Log.WARN, msg); 6776 bp = null; 6777 } 6778 } 6779 } 6780 6781 if (bp == null) { 6782 bp = new BasePermission(p.info.name, p.info.packageName, 6783 BasePermission.TYPE_NORMAL); 6784 permissionMap.put(p.info.name, bp); 6785 } 6786 6787 if (bp.perm == null) { 6788 if (bp.sourcePackage == null 6789 || bp.sourcePackage.equals(p.info.packageName)) { 6790 BasePermission tree = findPermissionTreeLP(p.info.name); 6791 if (tree == null 6792 || tree.sourcePackage.equals(p.info.packageName)) { 6793 bp.packageSetting = pkgSetting; 6794 bp.perm = p; 6795 bp.uid = pkg.applicationInfo.uid; 6796 bp.sourcePackage = p.info.packageName; 6797 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6798 if (r == null) { 6799 r = new StringBuilder(256); 6800 } else { 6801 r.append(' '); 6802 } 6803 r.append(p.info.name); 6804 } 6805 } else { 6806 Slog.w(TAG, "Permission " + p.info.name + " from package " 6807 + p.info.packageName + " ignored: base tree " 6808 + tree.name + " is from package " 6809 + tree.sourcePackage); 6810 } 6811 } else { 6812 Slog.w(TAG, "Permission " + p.info.name + " from package " 6813 + p.info.packageName + " ignored: original from " 6814 + bp.sourcePackage); 6815 } 6816 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6817 if (r == null) { 6818 r = new StringBuilder(256); 6819 } else { 6820 r.append(' '); 6821 } 6822 r.append("DUP:"); 6823 r.append(p.info.name); 6824 } 6825 if (bp.perm == p) { 6826 bp.protectionLevel = p.info.protectionLevel; 6827 } 6828 } 6829 6830 if (r != null) { 6831 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6832 } 6833 6834 N = pkg.instrumentation.size(); 6835 r = null; 6836 for (i=0; i<N; i++) { 6837 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6838 a.info.packageName = pkg.applicationInfo.packageName; 6839 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6840 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6841 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6842 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6843 a.info.dataDir = pkg.applicationInfo.dataDir; 6844 6845 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6846 // need other information about the application, like the ABI and what not ? 6847 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6848 mInstrumentation.put(a.getComponentName(), a); 6849 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6850 if (r == null) { 6851 r = new StringBuilder(256); 6852 } else { 6853 r.append(' '); 6854 } 6855 r.append(a.info.name); 6856 } 6857 } 6858 if (r != null) { 6859 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6860 } 6861 6862 if (pkg.protectedBroadcasts != null) { 6863 N = pkg.protectedBroadcasts.size(); 6864 for (i=0; i<N; i++) { 6865 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6866 } 6867 } 6868 6869 pkgSetting.setTimeStamp(scanFileTime); 6870 6871 // Create idmap files for pairs of (packages, overlay packages). 6872 // Note: "android", ie framework-res.apk, is handled by native layers. 6873 if (pkg.mOverlayTarget != null) { 6874 // This is an overlay package. 6875 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6876 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6877 mOverlays.put(pkg.mOverlayTarget, 6878 new ArrayMap<String, PackageParser.Package>()); 6879 } 6880 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6881 map.put(pkg.packageName, pkg); 6882 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6883 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6884 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6885 "scanPackageLI failed to createIdmap"); 6886 } 6887 } 6888 } else if (mOverlays.containsKey(pkg.packageName) && 6889 !pkg.packageName.equals("android")) { 6890 // This is a regular package, with one or more known overlay packages. 6891 createIdmapsForPackageLI(pkg); 6892 } 6893 } 6894 6895 return pkg; 6896 } 6897 6898 /** 6899 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6900 * is derived purely on the basis of the contents of {@code scanFile} and 6901 * {@code cpuAbiOverride}. 6902 * 6903 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6904 */ 6905 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6906 String cpuAbiOverride, boolean extractLibs) 6907 throws PackageManagerException { 6908 // TODO: We can probably be smarter about this stuff. For installed apps, 6909 // we can calculate this information at install time once and for all. For 6910 // system apps, we can probably assume that this information doesn't change 6911 // after the first boot scan. As things stand, we do lots of unnecessary work. 6912 6913 // Give ourselves some initial paths; we'll come back for another 6914 // pass once we've determined ABI below. 6915 setNativeLibraryPaths(pkg); 6916 6917 // We would never need to extract libs for forward-locked and external packages, 6918 // since the container service will do it for us. 6919 if (pkg.isForwardLocked() || isExternal(pkg)) { 6920 extractLibs = false; 6921 } 6922 6923 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6924 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6925 6926 NativeLibraryHelper.Handle handle = null; 6927 try { 6928 handle = NativeLibraryHelper.Handle.create(scanFile); 6929 // TODO(multiArch): This can be null for apps that didn't go through the 6930 // usual installation process. We can calculate it again, like we 6931 // do during install time. 6932 // 6933 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6934 // unnecessary. 6935 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6936 6937 // Null out the abis so that they can be recalculated. 6938 pkg.applicationInfo.primaryCpuAbi = null; 6939 pkg.applicationInfo.secondaryCpuAbi = null; 6940 if (isMultiArch(pkg.applicationInfo)) { 6941 // Warn if we've set an abiOverride for multi-lib packages.. 6942 // By definition, we need to copy both 32 and 64 bit libraries for 6943 // such packages. 6944 if (pkg.cpuAbiOverride != null 6945 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6946 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6947 } 6948 6949 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6950 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6951 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6952 if (extractLibs) { 6953 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6954 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6955 useIsaSpecificSubdirs); 6956 } else { 6957 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6958 } 6959 } 6960 6961 maybeThrowExceptionForMultiArchCopy( 6962 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6963 6964 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6965 if (extractLibs) { 6966 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6967 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6968 useIsaSpecificSubdirs); 6969 } else { 6970 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6971 } 6972 } 6973 6974 maybeThrowExceptionForMultiArchCopy( 6975 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6976 6977 if (abi64 >= 0) { 6978 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6979 } 6980 6981 if (abi32 >= 0) { 6982 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6983 if (abi64 >= 0) { 6984 pkg.applicationInfo.secondaryCpuAbi = abi; 6985 } else { 6986 pkg.applicationInfo.primaryCpuAbi = abi; 6987 } 6988 } 6989 } else { 6990 String[] abiList = (cpuAbiOverride != null) ? 6991 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6992 6993 // Enable gross and lame hacks for apps that are built with old 6994 // SDK tools. We must scan their APKs for renderscript bitcode and 6995 // not launch them if it's present. Don't bother checking on devices 6996 // that don't have 64 bit support. 6997 boolean needsRenderScriptOverride = false; 6998 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6999 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7000 abiList = Build.SUPPORTED_32_BIT_ABIS; 7001 needsRenderScriptOverride = true; 7002 } 7003 7004 final int copyRet; 7005 if (extractLibs) { 7006 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7007 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7008 } else { 7009 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7010 } 7011 7012 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7013 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7014 "Error unpackaging native libs for app, errorCode=" + copyRet); 7015 } 7016 7017 if (copyRet >= 0) { 7018 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7019 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7020 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7021 } else if (needsRenderScriptOverride) { 7022 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7023 } 7024 } 7025 } catch (IOException ioe) { 7026 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7027 } finally { 7028 IoUtils.closeQuietly(handle); 7029 } 7030 7031 // Now that we've calculated the ABIs and determined if it's an internal app, 7032 // we will go ahead and populate the nativeLibraryPath. 7033 setNativeLibraryPaths(pkg); 7034 } 7035 7036 /** 7037 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7038 * i.e, so that all packages can be run inside a single process if required. 7039 * 7040 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7041 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7042 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7043 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7044 * updating a package that belongs to a shared user. 7045 * 7046 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7047 * adds unnecessary complexity. 7048 */ 7049 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7050 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7051 String requiredInstructionSet = null; 7052 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7053 requiredInstructionSet = VMRuntime.getInstructionSet( 7054 scannedPackage.applicationInfo.primaryCpuAbi); 7055 } 7056 7057 PackageSetting requirer = null; 7058 for (PackageSetting ps : packagesForUser) { 7059 // If packagesForUser contains scannedPackage, we skip it. This will happen 7060 // when scannedPackage is an update of an existing package. Without this check, 7061 // we will never be able to change the ABI of any package belonging to a shared 7062 // user, even if it's compatible with other packages. 7063 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7064 if (ps.primaryCpuAbiString == null) { 7065 continue; 7066 } 7067 7068 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7069 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7070 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7071 // this but there's not much we can do. 7072 String errorMessage = "Instruction set mismatch, " 7073 + ((requirer == null) ? "[caller]" : requirer) 7074 + " requires " + requiredInstructionSet + " whereas " + ps 7075 + " requires " + instructionSet; 7076 Slog.w(TAG, errorMessage); 7077 } 7078 7079 if (requiredInstructionSet == null) { 7080 requiredInstructionSet = instructionSet; 7081 requirer = ps; 7082 } 7083 } 7084 } 7085 7086 if (requiredInstructionSet != null) { 7087 String adjustedAbi; 7088 if (requirer != null) { 7089 // requirer != null implies that either scannedPackage was null or that scannedPackage 7090 // did not require an ABI, in which case we have to adjust scannedPackage to match 7091 // the ABI of the set (which is the same as requirer's ABI) 7092 adjustedAbi = requirer.primaryCpuAbiString; 7093 if (scannedPackage != null) { 7094 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7095 } 7096 } else { 7097 // requirer == null implies that we're updating all ABIs in the set to 7098 // match scannedPackage. 7099 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7100 } 7101 7102 for (PackageSetting ps : packagesForUser) { 7103 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7104 if (ps.primaryCpuAbiString != null) { 7105 continue; 7106 } 7107 7108 ps.primaryCpuAbiString = adjustedAbi; 7109 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7110 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7111 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7112 7113 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7114 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7115 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7116 ps.primaryCpuAbiString = null; 7117 ps.pkg.applicationInfo.primaryCpuAbi = null; 7118 return; 7119 } else { 7120 mInstaller.rmdex(ps.codePathString, 7121 getDexCodeInstructionSet(getPreferredInstructionSet())); 7122 } 7123 } 7124 } 7125 } 7126 } 7127 } 7128 7129 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7130 synchronized (mPackages) { 7131 mResolverReplaced = true; 7132 // Set up information for custom user intent resolution activity. 7133 mResolveActivity.applicationInfo = pkg.applicationInfo; 7134 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7135 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7136 mResolveActivity.processName = pkg.applicationInfo.packageName; 7137 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7138 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7139 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7140 mResolveActivity.theme = 0; 7141 mResolveActivity.exported = true; 7142 mResolveActivity.enabled = true; 7143 mResolveInfo.activityInfo = mResolveActivity; 7144 mResolveInfo.priority = 0; 7145 mResolveInfo.preferredOrder = 0; 7146 mResolveInfo.match = 0; 7147 mResolveComponentName = mCustomResolverComponentName; 7148 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7149 mResolveComponentName); 7150 } 7151 } 7152 7153 private static String calculateBundledApkRoot(final String codePathString) { 7154 final File codePath = new File(codePathString); 7155 final File codeRoot; 7156 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7157 codeRoot = Environment.getRootDirectory(); 7158 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7159 codeRoot = Environment.getOemDirectory(); 7160 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7161 codeRoot = Environment.getVendorDirectory(); 7162 } else { 7163 // Unrecognized code path; take its top real segment as the apk root: 7164 // e.g. /something/app/blah.apk => /something 7165 try { 7166 File f = codePath.getCanonicalFile(); 7167 File parent = f.getParentFile(); // non-null because codePath is a file 7168 File tmp; 7169 while ((tmp = parent.getParentFile()) != null) { 7170 f = parent; 7171 parent = tmp; 7172 } 7173 codeRoot = f; 7174 Slog.w(TAG, "Unrecognized code path " 7175 + codePath + " - using " + codeRoot); 7176 } catch (IOException e) { 7177 // Can't canonicalize the code path -- shenanigans? 7178 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7179 return Environment.getRootDirectory().getPath(); 7180 } 7181 } 7182 return codeRoot.getPath(); 7183 } 7184 7185 /** 7186 * Derive and set the location of native libraries for the given package, 7187 * which varies depending on where and how the package was installed. 7188 */ 7189 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7190 final ApplicationInfo info = pkg.applicationInfo; 7191 final String codePath = pkg.codePath; 7192 final File codeFile = new File(codePath); 7193 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7194 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7195 7196 info.nativeLibraryRootDir = null; 7197 info.nativeLibraryRootRequiresIsa = false; 7198 info.nativeLibraryDir = null; 7199 info.secondaryNativeLibraryDir = null; 7200 7201 if (isApkFile(codeFile)) { 7202 // Monolithic install 7203 if (bundledApp) { 7204 // If "/system/lib64/apkname" exists, assume that is the per-package 7205 // native library directory to use; otherwise use "/system/lib/apkname". 7206 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7207 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7208 getPrimaryInstructionSet(info)); 7209 7210 // This is a bundled system app so choose the path based on the ABI. 7211 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7212 // is just the default path. 7213 final String apkName = deriveCodePathName(codePath); 7214 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7215 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7216 apkName).getAbsolutePath(); 7217 7218 if (info.secondaryCpuAbi != null) { 7219 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7220 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7221 secondaryLibDir, apkName).getAbsolutePath(); 7222 } 7223 } else if (asecApp) { 7224 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7225 .getAbsolutePath(); 7226 } else { 7227 final String apkName = deriveCodePathName(codePath); 7228 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7229 .getAbsolutePath(); 7230 } 7231 7232 info.nativeLibraryRootRequiresIsa = false; 7233 info.nativeLibraryDir = info.nativeLibraryRootDir; 7234 } else { 7235 // Cluster install 7236 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7237 info.nativeLibraryRootRequiresIsa = true; 7238 7239 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7240 getPrimaryInstructionSet(info)).getAbsolutePath(); 7241 7242 if (info.secondaryCpuAbi != null) { 7243 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7244 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7245 } 7246 } 7247 } 7248 7249 /** 7250 * Calculate the abis and roots for a bundled app. These can uniquely 7251 * be determined from the contents of the system partition, i.e whether 7252 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7253 * of this information, and instead assume that the system was built 7254 * sensibly. 7255 */ 7256 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7257 PackageSetting pkgSetting) { 7258 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7259 7260 // If "/system/lib64/apkname" exists, assume that is the per-package 7261 // native library directory to use; otherwise use "/system/lib/apkname". 7262 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7263 setBundledAppAbi(pkg, apkRoot, apkName); 7264 // pkgSetting might be null during rescan following uninstall of updates 7265 // to a bundled app, so accommodate that possibility. The settings in 7266 // that case will be established later from the parsed package. 7267 // 7268 // If the settings aren't null, sync them up with what we've just derived. 7269 // note that apkRoot isn't stored in the package settings. 7270 if (pkgSetting != null) { 7271 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7272 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7273 } 7274 } 7275 7276 /** 7277 * Deduces the ABI of a bundled app and sets the relevant fields on the 7278 * parsed pkg object. 7279 * 7280 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7281 * under which system libraries are installed. 7282 * @param apkName the name of the installed package. 7283 */ 7284 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7285 final File codeFile = new File(pkg.codePath); 7286 7287 final boolean has64BitLibs; 7288 final boolean has32BitLibs; 7289 if (isApkFile(codeFile)) { 7290 // Monolithic install 7291 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7292 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7293 } else { 7294 // Cluster install 7295 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7296 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7297 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7298 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7299 has64BitLibs = (new File(rootDir, isa)).exists(); 7300 } else { 7301 has64BitLibs = false; 7302 } 7303 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7304 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7305 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7306 has32BitLibs = (new File(rootDir, isa)).exists(); 7307 } else { 7308 has32BitLibs = false; 7309 } 7310 } 7311 7312 if (has64BitLibs && !has32BitLibs) { 7313 // The package has 64 bit libs, but not 32 bit libs. Its primary 7314 // ABI should be 64 bit. We can safely assume here that the bundled 7315 // native libraries correspond to the most preferred ABI in the list. 7316 7317 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7318 pkg.applicationInfo.secondaryCpuAbi = null; 7319 } else if (has32BitLibs && !has64BitLibs) { 7320 // The package has 32 bit libs but not 64 bit libs. Its primary 7321 // ABI should be 32 bit. 7322 7323 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7324 pkg.applicationInfo.secondaryCpuAbi = null; 7325 } else if (has32BitLibs && has64BitLibs) { 7326 // The application has both 64 and 32 bit bundled libraries. We check 7327 // here that the app declares multiArch support, and warn if it doesn't. 7328 // 7329 // We will be lenient here and record both ABIs. The primary will be the 7330 // ABI that's higher on the list, i.e, a device that's configured to prefer 7331 // 64 bit apps will see a 64 bit primary ABI, 7332 7333 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7334 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7335 } 7336 7337 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7338 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7339 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7340 } else { 7341 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7342 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7343 } 7344 } else { 7345 pkg.applicationInfo.primaryCpuAbi = null; 7346 pkg.applicationInfo.secondaryCpuAbi = null; 7347 } 7348 } 7349 7350 private void killApplication(String pkgName, int appId, String reason) { 7351 // Request the ActivityManager to kill the process(only for existing packages) 7352 // so that we do not end up in a confused state while the user is still using the older 7353 // version of the application while the new one gets installed. 7354 IActivityManager am = ActivityManagerNative.getDefault(); 7355 if (am != null) { 7356 try { 7357 am.killApplicationWithAppId(pkgName, appId, reason); 7358 } catch (RemoteException e) { 7359 } 7360 } 7361 } 7362 7363 void removePackageLI(PackageSetting ps, boolean chatty) { 7364 if (DEBUG_INSTALL) { 7365 if (chatty) 7366 Log.d(TAG, "Removing package " + ps.name); 7367 } 7368 7369 // writer 7370 synchronized (mPackages) { 7371 mPackages.remove(ps.name); 7372 final PackageParser.Package pkg = ps.pkg; 7373 if (pkg != null) { 7374 cleanPackageDataStructuresLILPw(pkg, chatty); 7375 } 7376 } 7377 } 7378 7379 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7380 if (DEBUG_INSTALL) { 7381 if (chatty) 7382 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7383 } 7384 7385 // writer 7386 synchronized (mPackages) { 7387 mPackages.remove(pkg.applicationInfo.packageName); 7388 cleanPackageDataStructuresLILPw(pkg, chatty); 7389 } 7390 } 7391 7392 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7393 int N = pkg.providers.size(); 7394 StringBuilder r = null; 7395 int i; 7396 for (i=0; i<N; i++) { 7397 PackageParser.Provider p = pkg.providers.get(i); 7398 mProviders.removeProvider(p); 7399 if (p.info.authority == null) { 7400 7401 /* There was another ContentProvider with this authority when 7402 * this app was installed so this authority is null, 7403 * Ignore it as we don't have to unregister the provider. 7404 */ 7405 continue; 7406 } 7407 String names[] = p.info.authority.split(";"); 7408 for (int j = 0; j < names.length; j++) { 7409 if (mProvidersByAuthority.get(names[j]) == p) { 7410 mProvidersByAuthority.remove(names[j]); 7411 if (DEBUG_REMOVE) { 7412 if (chatty) 7413 Log.d(TAG, "Unregistered content provider: " + names[j] 7414 + ", className = " + p.info.name + ", isSyncable = " 7415 + p.info.isSyncable); 7416 } 7417 } 7418 } 7419 if (DEBUG_REMOVE && chatty) { 7420 if (r == null) { 7421 r = new StringBuilder(256); 7422 } else { 7423 r.append(' '); 7424 } 7425 r.append(p.info.name); 7426 } 7427 } 7428 if (r != null) { 7429 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7430 } 7431 7432 N = pkg.services.size(); 7433 r = null; 7434 for (i=0; i<N; i++) { 7435 PackageParser.Service s = pkg.services.get(i); 7436 mServices.removeService(s); 7437 if (chatty) { 7438 if (r == null) { 7439 r = new StringBuilder(256); 7440 } else { 7441 r.append(' '); 7442 } 7443 r.append(s.info.name); 7444 } 7445 } 7446 if (r != null) { 7447 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7448 } 7449 7450 N = pkg.receivers.size(); 7451 r = null; 7452 for (i=0; i<N; i++) { 7453 PackageParser.Activity a = pkg.receivers.get(i); 7454 mReceivers.removeActivity(a, "receiver"); 7455 if (DEBUG_REMOVE && chatty) { 7456 if (r == null) { 7457 r = new StringBuilder(256); 7458 } else { 7459 r.append(' '); 7460 } 7461 r.append(a.info.name); 7462 } 7463 } 7464 if (r != null) { 7465 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7466 } 7467 7468 N = pkg.activities.size(); 7469 r = null; 7470 for (i=0; i<N; i++) { 7471 PackageParser.Activity a = pkg.activities.get(i); 7472 mActivities.removeActivity(a, "activity"); 7473 if (DEBUG_REMOVE && chatty) { 7474 if (r == null) { 7475 r = new StringBuilder(256); 7476 } else { 7477 r.append(' '); 7478 } 7479 r.append(a.info.name); 7480 } 7481 } 7482 if (r != null) { 7483 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7484 } 7485 7486 N = pkg.permissions.size(); 7487 r = null; 7488 for (i=0; i<N; i++) { 7489 PackageParser.Permission p = pkg.permissions.get(i); 7490 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7491 if (bp == null) { 7492 bp = mSettings.mPermissionTrees.get(p.info.name); 7493 } 7494 if (bp != null && bp.perm == p) { 7495 bp.perm = null; 7496 if (DEBUG_REMOVE && chatty) { 7497 if (r == null) { 7498 r = new StringBuilder(256); 7499 } else { 7500 r.append(' '); 7501 } 7502 r.append(p.info.name); 7503 } 7504 } 7505 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7506 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7507 if (appOpPerms != null) { 7508 appOpPerms.remove(pkg.packageName); 7509 } 7510 } 7511 } 7512 if (r != null) { 7513 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7514 } 7515 7516 N = pkg.requestedPermissions.size(); 7517 r = null; 7518 for (i=0; i<N; i++) { 7519 String perm = pkg.requestedPermissions.get(i); 7520 BasePermission bp = mSettings.mPermissions.get(perm); 7521 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7522 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7523 if (appOpPerms != null) { 7524 appOpPerms.remove(pkg.packageName); 7525 if (appOpPerms.isEmpty()) { 7526 mAppOpPermissionPackages.remove(perm); 7527 } 7528 } 7529 } 7530 } 7531 if (r != null) { 7532 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7533 } 7534 7535 N = pkg.instrumentation.size(); 7536 r = null; 7537 for (i=0; i<N; i++) { 7538 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7539 mInstrumentation.remove(a.getComponentName()); 7540 if (DEBUG_REMOVE && chatty) { 7541 if (r == null) { 7542 r = new StringBuilder(256); 7543 } else { 7544 r.append(' '); 7545 } 7546 r.append(a.info.name); 7547 } 7548 } 7549 if (r != null) { 7550 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7551 } 7552 7553 r = null; 7554 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7555 // Only system apps can hold shared libraries. 7556 if (pkg.libraryNames != null) { 7557 for (i=0; i<pkg.libraryNames.size(); i++) { 7558 String name = pkg.libraryNames.get(i); 7559 SharedLibraryEntry cur = mSharedLibraries.get(name); 7560 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7561 mSharedLibraries.remove(name); 7562 if (DEBUG_REMOVE && chatty) { 7563 if (r == null) { 7564 r = new StringBuilder(256); 7565 } else { 7566 r.append(' '); 7567 } 7568 r.append(name); 7569 } 7570 } 7571 } 7572 } 7573 } 7574 if (r != null) { 7575 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7576 } 7577 } 7578 7579 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7580 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7581 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7582 return true; 7583 } 7584 } 7585 return false; 7586 } 7587 7588 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7589 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7590 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7591 7592 private void updatePermissionsLPw(String changingPkg, 7593 PackageParser.Package pkgInfo, int flags) { 7594 // Make sure there are no dangling permission trees. 7595 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7596 while (it.hasNext()) { 7597 final BasePermission bp = it.next(); 7598 if (bp.packageSetting == null) { 7599 // We may not yet have parsed the package, so just see if 7600 // we still know about its settings. 7601 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7602 } 7603 if (bp.packageSetting == null) { 7604 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7605 + " from package " + bp.sourcePackage); 7606 it.remove(); 7607 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7608 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7609 Slog.i(TAG, "Removing old permission tree: " + bp.name 7610 + " from package " + bp.sourcePackage); 7611 flags |= UPDATE_PERMISSIONS_ALL; 7612 it.remove(); 7613 } 7614 } 7615 } 7616 7617 // Make sure all dynamic permissions have been assigned to a package, 7618 // and make sure there are no dangling permissions. 7619 it = mSettings.mPermissions.values().iterator(); 7620 while (it.hasNext()) { 7621 final BasePermission bp = it.next(); 7622 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7623 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7624 + bp.name + " pkg=" + bp.sourcePackage 7625 + " info=" + bp.pendingInfo); 7626 if (bp.packageSetting == null && bp.pendingInfo != null) { 7627 final BasePermission tree = findPermissionTreeLP(bp.name); 7628 if (tree != null && tree.perm != null) { 7629 bp.packageSetting = tree.packageSetting; 7630 bp.perm = new PackageParser.Permission(tree.perm.owner, 7631 new PermissionInfo(bp.pendingInfo)); 7632 bp.perm.info.packageName = tree.perm.info.packageName; 7633 bp.perm.info.name = bp.name; 7634 bp.uid = tree.uid; 7635 } 7636 } 7637 } 7638 if (bp.packageSetting == null) { 7639 // We may not yet have parsed the package, so just see if 7640 // we still know about its settings. 7641 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7642 } 7643 if (bp.packageSetting == null) { 7644 Slog.w(TAG, "Removing dangling permission: " + bp.name 7645 + " from package " + bp.sourcePackage); 7646 it.remove(); 7647 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7648 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7649 Slog.i(TAG, "Removing old permission: " + bp.name 7650 + " from package " + bp.sourcePackage); 7651 flags |= UPDATE_PERMISSIONS_ALL; 7652 it.remove(); 7653 } 7654 } 7655 } 7656 7657 // Now update the permissions for all packages, in particular 7658 // replace the granted permissions of the system packages. 7659 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7660 for (PackageParser.Package pkg : mPackages.values()) { 7661 if (pkg != pkgInfo) { 7662 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7663 changingPkg); 7664 } 7665 } 7666 } 7667 7668 if (pkgInfo != null) { 7669 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7670 } 7671 } 7672 7673 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7674 String packageOfInterest) { 7675 // IMPORTANT: There are two types of permissions: install and runtime. 7676 // Install time permissions are granted when the app is installed to 7677 // all device users and users added in the future. Runtime permissions 7678 // are granted at runtime explicitly to specific users. Normal and signature 7679 // protected permissions are install time permissions. Dangerous permissions 7680 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7681 // otherwise they are runtime permissions. This function does not manage 7682 // runtime permissions except for the case an app targeting Lollipop MR1 7683 // being upgraded to target a newer SDK, in which case dangerous permissions 7684 // are transformed from install time to runtime ones. 7685 7686 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7687 if (ps == null) { 7688 return; 7689 } 7690 7691 PermissionsState permissionsState = ps.getPermissionsState(); 7692 PermissionsState origPermissions = permissionsState; 7693 7694 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7695 7696 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7697 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7698 7699 boolean changedInstallPermission = false; 7700 7701 if (replace) { 7702 ps.installPermissionsFixed = false; 7703 if (!ps.isSharedUser()) { 7704 origPermissions = new PermissionsState(permissionsState); 7705 permissionsState.reset(); 7706 } 7707 } 7708 7709 permissionsState.setGlobalGids(mGlobalGids); 7710 7711 final int N = pkg.requestedPermissions.size(); 7712 for (int i=0; i<N; i++) { 7713 final String name = pkg.requestedPermissions.get(i); 7714 final BasePermission bp = mSettings.mPermissions.get(name); 7715 7716 if (DEBUG_INSTALL) { 7717 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7718 } 7719 7720 if (bp == null || bp.packageSetting == null) { 7721 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7722 Slog.w(TAG, "Unknown permission " + name 7723 + " in package " + pkg.packageName); 7724 } 7725 continue; 7726 } 7727 7728 final String perm = bp.name; 7729 boolean allowedSig = false; 7730 int grant = GRANT_DENIED; 7731 7732 // Keep track of app op permissions. 7733 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7734 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7735 if (pkgs == null) { 7736 pkgs = new ArraySet<>(); 7737 mAppOpPermissionPackages.put(bp.name, pkgs); 7738 } 7739 pkgs.add(pkg.packageName); 7740 } 7741 7742 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7743 switch (level) { 7744 case PermissionInfo.PROTECTION_NORMAL: { 7745 // For all apps normal permissions are install time ones. 7746 grant = GRANT_INSTALL; 7747 } break; 7748 7749 case PermissionInfo.PROTECTION_DANGEROUS: { 7750 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7751 // For legacy apps dangerous permissions are install time ones. 7752 grant = GRANT_INSTALL_LEGACY; 7753 } else if (ps.isSystem()) { 7754 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7755 if (origPermissions.hasInstallPermission(bp.name)) { 7756 // If a system app had an install permission, then the app was 7757 // upgraded and we grant the permissions as runtime to all users. 7758 grant = GRANT_UPGRADE; 7759 upgradeUserIds = currentUserIds; 7760 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7761 // If users changed since the last permissions update for a 7762 // system app, we grant the permission as runtime to the new users. 7763 grant = GRANT_UPGRADE; 7764 upgradeUserIds = currentUserIds; 7765 for (int userId : updatedUserIds) { 7766 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7767 } 7768 } else { 7769 // Otherwise, we grant the permission as runtime if the app 7770 // already had it, i.e. we preserve runtime permissions. 7771 grant = GRANT_RUNTIME; 7772 } 7773 } else if (origPermissions.hasInstallPermission(bp.name)) { 7774 // For legacy apps that became modern, install becomes runtime. 7775 grant = GRANT_UPGRADE; 7776 upgradeUserIds = currentUserIds; 7777 } else if (replace) { 7778 // For upgraded modern apps keep runtime permissions unchanged. 7779 grant = GRANT_RUNTIME; 7780 } 7781 } break; 7782 7783 case PermissionInfo.PROTECTION_SIGNATURE: { 7784 // For all apps signature permissions are install time ones. 7785 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7786 if (allowedSig) { 7787 grant = GRANT_INSTALL; 7788 } 7789 } break; 7790 } 7791 7792 if (DEBUG_INSTALL) { 7793 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7794 } 7795 7796 if (grant != GRANT_DENIED) { 7797 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7798 // If this is an existing, non-system package, then 7799 // we can't add any new permissions to it. 7800 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7801 // Except... if this is a permission that was added 7802 // to the platform (note: need to only do this when 7803 // updating the platform). 7804 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7805 grant = GRANT_DENIED; 7806 } 7807 } 7808 } 7809 7810 switch (grant) { 7811 case GRANT_INSTALL: { 7812 // Revoke this as runtime permission to handle the case of 7813 // a runtime permssion being downgraded to an install one. 7814 for (int userId : UserManagerService.getInstance().getUserIds()) { 7815 if (origPermissions.getRuntimePermissionState( 7816 bp.name, userId) != null) { 7817 // Revoke the runtime permission and clear the flags. 7818 origPermissions.revokeRuntimePermission(bp, userId); 7819 origPermissions.updatePermissionFlags(bp, userId, 7820 PackageManager.MASK_PERMISSION_FLAGS, 0); 7821 // If we revoked a permission permission, we have to write. 7822 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7823 changedRuntimePermissionUserIds, userId); 7824 } 7825 } 7826 // Grant an install permission. 7827 if (permissionsState.grantInstallPermission(bp) != 7828 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7829 changedInstallPermission = true; 7830 } 7831 } break; 7832 7833 case GRANT_INSTALL_LEGACY: { 7834 // Grant an install permission. 7835 if (permissionsState.grantInstallPermission(bp) != 7836 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7837 changedInstallPermission = true; 7838 } 7839 } break; 7840 7841 case GRANT_RUNTIME: { 7842 // Grant previously granted runtime permissions. 7843 for (int userId : UserManagerService.getInstance().getUserIds()) { 7844 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7845 PermissionState permissionState = origPermissions 7846 .getRuntimePermissionState(bp.name, userId); 7847 final int flags = permissionState.getFlags(); 7848 if (permissionsState.grantRuntimePermission(bp, userId) == 7849 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7850 // If we cannot put the permission as it was, we have to write. 7851 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7852 changedRuntimePermissionUserIds, userId); 7853 } else { 7854 // System components not only get the permissions but 7855 // they are also fixed, so nothing can change that. 7856 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7857 ? flags 7858 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7859 // Propagate the permission flags. 7860 permissionsState.updatePermissionFlags(bp, userId, 7861 newFlags, newFlags); 7862 } 7863 } 7864 } 7865 } break; 7866 7867 case GRANT_UPGRADE: { 7868 // Grant runtime permissions for a previously held install permission. 7869 PermissionState permissionState = origPermissions 7870 .getInstallPermissionState(bp.name); 7871 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7872 7873 origPermissions.revokeInstallPermission(bp); 7874 // We will be transferring the permission flags, so clear them. 7875 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7876 PackageManager.MASK_PERMISSION_FLAGS, 0); 7877 7878 // If the permission is not to be promoted to runtime we ignore it and 7879 // also its other flags as they are not applicable to install permissions. 7880 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7881 for (int userId : upgradeUserIds) { 7882 if (permissionsState.grantRuntimePermission(bp, userId) != 7883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7884 // System components not only get the permissions but 7885 // they are also fixed so nothing can change that. 7886 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7887 ? flags 7888 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7889 // Transfer the permission flags. 7890 permissionsState.updatePermissionFlags(bp, userId, 7891 newFlags, newFlags); 7892 // If we granted the permission, we have to write. 7893 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7894 changedRuntimePermissionUserIds, userId); 7895 } 7896 } 7897 } 7898 } break; 7899 7900 default: { 7901 if (packageOfInterest == null 7902 || packageOfInterest.equals(pkg.packageName)) { 7903 Slog.w(TAG, "Not granting permission " + perm 7904 + " to package " + pkg.packageName 7905 + " because it was previously installed without"); 7906 } 7907 } break; 7908 } 7909 } else { 7910 if (permissionsState.revokeInstallPermission(bp) != 7911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7912 // Also drop the permission flags. 7913 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7914 PackageManager.MASK_PERMISSION_FLAGS, 0); 7915 changedInstallPermission = true; 7916 Slog.i(TAG, "Un-granting permission " + perm 7917 + " from package " + pkg.packageName 7918 + " (protectionLevel=" + bp.protectionLevel 7919 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7920 + ")"); 7921 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7922 // Don't print warning for app op permissions, since it is fine for them 7923 // not to be granted, there is a UI for the user to decide. 7924 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7925 Slog.w(TAG, "Not granting permission " + perm 7926 + " to package " + pkg.packageName 7927 + " (protectionLevel=" + bp.protectionLevel 7928 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7929 + ")"); 7930 } 7931 } 7932 } 7933 } 7934 7935 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7936 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7937 // This is the first that we have heard about this package, so the 7938 // permissions we have now selected are fixed until explicitly 7939 // changed. 7940 ps.installPermissionsFixed = true; 7941 } 7942 7943 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7944 7945 // Persist the runtime permissions state for users with changes. 7946 for (int userId : changedRuntimePermissionUserIds) { 7947 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7948 } 7949 } 7950 7951 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7952 boolean allowed = false; 7953 final int NP = PackageParser.NEW_PERMISSIONS.length; 7954 for (int ip=0; ip<NP; ip++) { 7955 final PackageParser.NewPermissionInfo npi 7956 = PackageParser.NEW_PERMISSIONS[ip]; 7957 if (npi.name.equals(perm) 7958 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7959 allowed = true; 7960 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7961 + pkg.packageName); 7962 break; 7963 } 7964 } 7965 return allowed; 7966 } 7967 7968 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7969 BasePermission bp, PermissionsState origPermissions) { 7970 boolean allowed; 7971 allowed = (compareSignatures( 7972 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7973 == PackageManager.SIGNATURE_MATCH) 7974 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7975 == PackageManager.SIGNATURE_MATCH); 7976 if (!allowed && (bp.protectionLevel 7977 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7978 if (isSystemApp(pkg)) { 7979 // For updated system applications, a system permission 7980 // is granted only if it had been defined by the original application. 7981 if (pkg.isUpdatedSystemApp()) { 7982 final PackageSetting sysPs = mSettings 7983 .getDisabledSystemPkgLPr(pkg.packageName); 7984 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7985 // If the original was granted this permission, we take 7986 // that grant decision as read and propagate it to the 7987 // update. 7988 if (sysPs.isPrivileged()) { 7989 allowed = true; 7990 } 7991 } else { 7992 // The system apk may have been updated with an older 7993 // version of the one on the data partition, but which 7994 // granted a new system permission that it didn't have 7995 // before. In this case we do want to allow the app to 7996 // now get the new permission if the ancestral apk is 7997 // privileged to get it. 7998 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7999 for (int j=0; 8000 j<sysPs.pkg.requestedPermissions.size(); j++) { 8001 if (perm.equals( 8002 sysPs.pkg.requestedPermissions.get(j))) { 8003 allowed = true; 8004 break; 8005 } 8006 } 8007 } 8008 } 8009 } else { 8010 allowed = isPrivilegedApp(pkg); 8011 } 8012 } 8013 } 8014 if (!allowed && (bp.protectionLevel 8015 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8016 // For development permissions, a development permission 8017 // is granted only if it was already granted. 8018 allowed = origPermissions.hasInstallPermission(perm); 8019 } 8020 return allowed; 8021 } 8022 8023 final class ActivityIntentResolver 8024 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8026 boolean defaultOnly, int userId) { 8027 if (!sUserManager.exists(userId)) return null; 8028 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8029 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8030 } 8031 8032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8033 int userId) { 8034 if (!sUserManager.exists(userId)) return null; 8035 mFlags = flags; 8036 return super.queryIntent(intent, resolvedType, 8037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8038 } 8039 8040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8041 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8042 if (!sUserManager.exists(userId)) return null; 8043 if (packageActivities == null) { 8044 return null; 8045 } 8046 mFlags = flags; 8047 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8048 final int N = packageActivities.size(); 8049 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8050 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8051 8052 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8053 for (int i = 0; i < N; ++i) { 8054 intentFilters = packageActivities.get(i).intents; 8055 if (intentFilters != null && intentFilters.size() > 0) { 8056 PackageParser.ActivityIntentInfo[] array = 8057 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8058 intentFilters.toArray(array); 8059 listCut.add(array); 8060 } 8061 } 8062 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8063 } 8064 8065 public final void addActivity(PackageParser.Activity a, String type) { 8066 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8067 mActivities.put(a.getComponentName(), a); 8068 if (DEBUG_SHOW_INFO) 8069 Log.v( 8070 TAG, " " + type + " " + 8071 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8072 if (DEBUG_SHOW_INFO) 8073 Log.v(TAG, " Class=" + a.info.name); 8074 final int NI = a.intents.size(); 8075 for (int j=0; j<NI; j++) { 8076 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8077 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8078 intent.setPriority(0); 8079 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8080 + a.className + " with priority > 0, forcing to 0"); 8081 } 8082 if (DEBUG_SHOW_INFO) { 8083 Log.v(TAG, " IntentFilter:"); 8084 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8085 } 8086 if (!intent.debugCheck()) { 8087 Log.w(TAG, "==> For Activity " + a.info.name); 8088 } 8089 addFilter(intent); 8090 } 8091 } 8092 8093 public final void removeActivity(PackageParser.Activity a, String type) { 8094 mActivities.remove(a.getComponentName()); 8095 if (DEBUG_SHOW_INFO) { 8096 Log.v(TAG, " " + type + " " 8097 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8098 : a.info.name) + ":"); 8099 Log.v(TAG, " Class=" + a.info.name); 8100 } 8101 final int NI = a.intents.size(); 8102 for (int j=0; j<NI; j++) { 8103 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8104 if (DEBUG_SHOW_INFO) { 8105 Log.v(TAG, " IntentFilter:"); 8106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8107 } 8108 removeFilter(intent); 8109 } 8110 } 8111 8112 @Override 8113 protected boolean allowFilterResult( 8114 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8115 ActivityInfo filterAi = filter.activity.info; 8116 for (int i=dest.size()-1; i>=0; i--) { 8117 ActivityInfo destAi = dest.get(i).activityInfo; 8118 if (destAi.name == filterAi.name 8119 && destAi.packageName == filterAi.packageName) { 8120 return false; 8121 } 8122 } 8123 return true; 8124 } 8125 8126 @Override 8127 protected ActivityIntentInfo[] newArray(int size) { 8128 return new ActivityIntentInfo[size]; 8129 } 8130 8131 @Override 8132 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8133 if (!sUserManager.exists(userId)) return true; 8134 PackageParser.Package p = filter.activity.owner; 8135 if (p != null) { 8136 PackageSetting ps = (PackageSetting)p.mExtras; 8137 if (ps != null) { 8138 // System apps are never considered stopped for purposes of 8139 // filtering, because there may be no way for the user to 8140 // actually re-launch them. 8141 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8142 && ps.getStopped(userId); 8143 } 8144 } 8145 return false; 8146 } 8147 8148 @Override 8149 protected boolean isPackageForFilter(String packageName, 8150 PackageParser.ActivityIntentInfo info) { 8151 return packageName.equals(info.activity.owner.packageName); 8152 } 8153 8154 @Override 8155 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8156 int match, int userId) { 8157 if (!sUserManager.exists(userId)) return null; 8158 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8159 return null; 8160 } 8161 final PackageParser.Activity activity = info.activity; 8162 if (mSafeMode && (activity.info.applicationInfo.flags 8163 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8164 return null; 8165 } 8166 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8167 if (ps == null) { 8168 return null; 8169 } 8170 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8171 ps.readUserState(userId), userId); 8172 if (ai == null) { 8173 return null; 8174 } 8175 final ResolveInfo res = new ResolveInfo(); 8176 res.activityInfo = ai; 8177 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8178 res.filter = info; 8179 } 8180 if (info != null) { 8181 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8182 } 8183 res.priority = info.getPriority(); 8184 res.preferredOrder = activity.owner.mPreferredOrder; 8185 //System.out.println("Result: " + res.activityInfo.className + 8186 // " = " + res.priority); 8187 res.match = match; 8188 res.isDefault = info.hasDefault; 8189 res.labelRes = info.labelRes; 8190 res.nonLocalizedLabel = info.nonLocalizedLabel; 8191 if (userNeedsBadging(userId)) { 8192 res.noResourceId = true; 8193 } else { 8194 res.icon = info.icon; 8195 } 8196 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8197 return res; 8198 } 8199 8200 @Override 8201 protected void sortResults(List<ResolveInfo> results) { 8202 Collections.sort(results, mResolvePrioritySorter); 8203 } 8204 8205 @Override 8206 protected void dumpFilter(PrintWriter out, String prefix, 8207 PackageParser.ActivityIntentInfo filter) { 8208 out.print(prefix); out.print( 8209 Integer.toHexString(System.identityHashCode(filter.activity))); 8210 out.print(' '); 8211 filter.activity.printComponentShortName(out); 8212 out.print(" filter "); 8213 out.println(Integer.toHexString(System.identityHashCode(filter))); 8214 } 8215 8216 @Override 8217 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8218 return filter.activity; 8219 } 8220 8221 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8222 PackageParser.Activity activity = (PackageParser.Activity)label; 8223 out.print(prefix); out.print( 8224 Integer.toHexString(System.identityHashCode(activity))); 8225 out.print(' '); 8226 activity.printComponentShortName(out); 8227 if (count > 1) { 8228 out.print(" ("); out.print(count); out.print(" filters)"); 8229 } 8230 out.println(); 8231 } 8232 8233// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8234// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8235// final List<ResolveInfo> retList = Lists.newArrayList(); 8236// while (i.hasNext()) { 8237// final ResolveInfo resolveInfo = i.next(); 8238// if (isEnabledLP(resolveInfo.activityInfo)) { 8239// retList.add(resolveInfo); 8240// } 8241// } 8242// return retList; 8243// } 8244 8245 // Keys are String (activity class name), values are Activity. 8246 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8247 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8248 private int mFlags; 8249 } 8250 8251 private final class ServiceIntentResolver 8252 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8253 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8254 boolean defaultOnly, int userId) { 8255 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8256 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8257 } 8258 8259 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8260 int userId) { 8261 if (!sUserManager.exists(userId)) return null; 8262 mFlags = flags; 8263 return super.queryIntent(intent, resolvedType, 8264 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8265 } 8266 8267 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8268 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8269 if (!sUserManager.exists(userId)) return null; 8270 if (packageServices == null) { 8271 return null; 8272 } 8273 mFlags = flags; 8274 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8275 final int N = packageServices.size(); 8276 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8277 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8278 8279 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8280 for (int i = 0; i < N; ++i) { 8281 intentFilters = packageServices.get(i).intents; 8282 if (intentFilters != null && intentFilters.size() > 0) { 8283 PackageParser.ServiceIntentInfo[] array = 8284 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8285 intentFilters.toArray(array); 8286 listCut.add(array); 8287 } 8288 } 8289 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8290 } 8291 8292 public final void addService(PackageParser.Service s) { 8293 mServices.put(s.getComponentName(), s); 8294 if (DEBUG_SHOW_INFO) { 8295 Log.v(TAG, " " 8296 + (s.info.nonLocalizedLabel != null 8297 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8298 Log.v(TAG, " Class=" + s.info.name); 8299 } 8300 final int NI = s.intents.size(); 8301 int j; 8302 for (j=0; j<NI; j++) { 8303 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8304 if (DEBUG_SHOW_INFO) { 8305 Log.v(TAG, " IntentFilter:"); 8306 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8307 } 8308 if (!intent.debugCheck()) { 8309 Log.w(TAG, "==> For Service " + s.info.name); 8310 } 8311 addFilter(intent); 8312 } 8313 } 8314 8315 public final void removeService(PackageParser.Service s) { 8316 mServices.remove(s.getComponentName()); 8317 if (DEBUG_SHOW_INFO) { 8318 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8319 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8320 Log.v(TAG, " Class=" + s.info.name); 8321 } 8322 final int NI = s.intents.size(); 8323 int j; 8324 for (j=0; j<NI; j++) { 8325 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8326 if (DEBUG_SHOW_INFO) { 8327 Log.v(TAG, " IntentFilter:"); 8328 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8329 } 8330 removeFilter(intent); 8331 } 8332 } 8333 8334 @Override 8335 protected boolean allowFilterResult( 8336 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8337 ServiceInfo filterSi = filter.service.info; 8338 for (int i=dest.size()-1; i>=0; i--) { 8339 ServiceInfo destAi = dest.get(i).serviceInfo; 8340 if (destAi.name == filterSi.name 8341 && destAi.packageName == filterSi.packageName) { 8342 return false; 8343 } 8344 } 8345 return true; 8346 } 8347 8348 @Override 8349 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8350 return new PackageParser.ServiceIntentInfo[size]; 8351 } 8352 8353 @Override 8354 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8355 if (!sUserManager.exists(userId)) return true; 8356 PackageParser.Package p = filter.service.owner; 8357 if (p != null) { 8358 PackageSetting ps = (PackageSetting)p.mExtras; 8359 if (ps != null) { 8360 // System apps are never considered stopped for purposes of 8361 // filtering, because there may be no way for the user to 8362 // actually re-launch them. 8363 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8364 && ps.getStopped(userId); 8365 } 8366 } 8367 return false; 8368 } 8369 8370 @Override 8371 protected boolean isPackageForFilter(String packageName, 8372 PackageParser.ServiceIntentInfo info) { 8373 return packageName.equals(info.service.owner.packageName); 8374 } 8375 8376 @Override 8377 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8378 int match, int userId) { 8379 if (!sUserManager.exists(userId)) return null; 8380 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8381 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8382 return null; 8383 } 8384 final PackageParser.Service service = info.service; 8385 if (mSafeMode && (service.info.applicationInfo.flags 8386 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8387 return null; 8388 } 8389 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8390 if (ps == null) { 8391 return null; 8392 } 8393 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8394 ps.readUserState(userId), userId); 8395 if (si == null) { 8396 return null; 8397 } 8398 final ResolveInfo res = new ResolveInfo(); 8399 res.serviceInfo = si; 8400 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8401 res.filter = filter; 8402 } 8403 res.priority = info.getPriority(); 8404 res.preferredOrder = service.owner.mPreferredOrder; 8405 res.match = match; 8406 res.isDefault = info.hasDefault; 8407 res.labelRes = info.labelRes; 8408 res.nonLocalizedLabel = info.nonLocalizedLabel; 8409 res.icon = info.icon; 8410 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8411 return res; 8412 } 8413 8414 @Override 8415 protected void sortResults(List<ResolveInfo> results) { 8416 Collections.sort(results, mResolvePrioritySorter); 8417 } 8418 8419 @Override 8420 protected void dumpFilter(PrintWriter out, String prefix, 8421 PackageParser.ServiceIntentInfo filter) { 8422 out.print(prefix); out.print( 8423 Integer.toHexString(System.identityHashCode(filter.service))); 8424 out.print(' '); 8425 filter.service.printComponentShortName(out); 8426 out.print(" filter "); 8427 out.println(Integer.toHexString(System.identityHashCode(filter))); 8428 } 8429 8430 @Override 8431 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8432 return filter.service; 8433 } 8434 8435 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8436 PackageParser.Service service = (PackageParser.Service)label; 8437 out.print(prefix); out.print( 8438 Integer.toHexString(System.identityHashCode(service))); 8439 out.print(' '); 8440 service.printComponentShortName(out); 8441 if (count > 1) { 8442 out.print(" ("); out.print(count); out.print(" filters)"); 8443 } 8444 out.println(); 8445 } 8446 8447// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8448// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8449// final List<ResolveInfo> retList = Lists.newArrayList(); 8450// while (i.hasNext()) { 8451// final ResolveInfo resolveInfo = (ResolveInfo) i; 8452// if (isEnabledLP(resolveInfo.serviceInfo)) { 8453// retList.add(resolveInfo); 8454// } 8455// } 8456// return retList; 8457// } 8458 8459 // Keys are String (activity class name), values are Activity. 8460 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8461 = new ArrayMap<ComponentName, PackageParser.Service>(); 8462 private int mFlags; 8463 }; 8464 8465 private final class ProviderIntentResolver 8466 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8467 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8468 boolean defaultOnly, int userId) { 8469 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8470 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8471 } 8472 8473 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8474 int userId) { 8475 if (!sUserManager.exists(userId)) 8476 return null; 8477 mFlags = flags; 8478 return super.queryIntent(intent, resolvedType, 8479 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8480 } 8481 8482 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8483 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8484 if (!sUserManager.exists(userId)) 8485 return null; 8486 if (packageProviders == null) { 8487 return null; 8488 } 8489 mFlags = flags; 8490 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8491 final int N = packageProviders.size(); 8492 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8493 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8494 8495 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8496 for (int i = 0; i < N; ++i) { 8497 intentFilters = packageProviders.get(i).intents; 8498 if (intentFilters != null && intentFilters.size() > 0) { 8499 PackageParser.ProviderIntentInfo[] array = 8500 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8501 intentFilters.toArray(array); 8502 listCut.add(array); 8503 } 8504 } 8505 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8506 } 8507 8508 public final void addProvider(PackageParser.Provider p) { 8509 if (mProviders.containsKey(p.getComponentName())) { 8510 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8511 return; 8512 } 8513 8514 mProviders.put(p.getComponentName(), p); 8515 if (DEBUG_SHOW_INFO) { 8516 Log.v(TAG, " " 8517 + (p.info.nonLocalizedLabel != null 8518 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8519 Log.v(TAG, " Class=" + p.info.name); 8520 } 8521 final int NI = p.intents.size(); 8522 int j; 8523 for (j = 0; j < NI; j++) { 8524 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8525 if (DEBUG_SHOW_INFO) { 8526 Log.v(TAG, " IntentFilter:"); 8527 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8528 } 8529 if (!intent.debugCheck()) { 8530 Log.w(TAG, "==> For Provider " + p.info.name); 8531 } 8532 addFilter(intent); 8533 } 8534 } 8535 8536 public final void removeProvider(PackageParser.Provider p) { 8537 mProviders.remove(p.getComponentName()); 8538 if (DEBUG_SHOW_INFO) { 8539 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8540 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8541 Log.v(TAG, " Class=" + p.info.name); 8542 } 8543 final int NI = p.intents.size(); 8544 int j; 8545 for (j = 0; j < NI; j++) { 8546 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8547 if (DEBUG_SHOW_INFO) { 8548 Log.v(TAG, " IntentFilter:"); 8549 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8550 } 8551 removeFilter(intent); 8552 } 8553 } 8554 8555 @Override 8556 protected boolean allowFilterResult( 8557 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8558 ProviderInfo filterPi = filter.provider.info; 8559 for (int i = dest.size() - 1; i >= 0; i--) { 8560 ProviderInfo destPi = dest.get(i).providerInfo; 8561 if (destPi.name == filterPi.name 8562 && destPi.packageName == filterPi.packageName) { 8563 return false; 8564 } 8565 } 8566 return true; 8567 } 8568 8569 @Override 8570 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8571 return new PackageParser.ProviderIntentInfo[size]; 8572 } 8573 8574 @Override 8575 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8576 if (!sUserManager.exists(userId)) 8577 return true; 8578 PackageParser.Package p = filter.provider.owner; 8579 if (p != null) { 8580 PackageSetting ps = (PackageSetting) p.mExtras; 8581 if (ps != null) { 8582 // System apps are never considered stopped for purposes of 8583 // filtering, because there may be no way for the user to 8584 // actually re-launch them. 8585 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8586 && ps.getStopped(userId); 8587 } 8588 } 8589 return false; 8590 } 8591 8592 @Override 8593 protected boolean isPackageForFilter(String packageName, 8594 PackageParser.ProviderIntentInfo info) { 8595 return packageName.equals(info.provider.owner.packageName); 8596 } 8597 8598 @Override 8599 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8600 int match, int userId) { 8601 if (!sUserManager.exists(userId)) 8602 return null; 8603 final PackageParser.ProviderIntentInfo info = filter; 8604 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8605 return null; 8606 } 8607 final PackageParser.Provider provider = info.provider; 8608 if (mSafeMode && (provider.info.applicationInfo.flags 8609 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8610 return null; 8611 } 8612 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8613 if (ps == null) { 8614 return null; 8615 } 8616 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8617 ps.readUserState(userId), userId); 8618 if (pi == null) { 8619 return null; 8620 } 8621 final ResolveInfo res = new ResolveInfo(); 8622 res.providerInfo = pi; 8623 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8624 res.filter = filter; 8625 } 8626 res.priority = info.getPriority(); 8627 res.preferredOrder = provider.owner.mPreferredOrder; 8628 res.match = match; 8629 res.isDefault = info.hasDefault; 8630 res.labelRes = info.labelRes; 8631 res.nonLocalizedLabel = info.nonLocalizedLabel; 8632 res.icon = info.icon; 8633 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8634 return res; 8635 } 8636 8637 @Override 8638 protected void sortResults(List<ResolveInfo> results) { 8639 Collections.sort(results, mResolvePrioritySorter); 8640 } 8641 8642 @Override 8643 protected void dumpFilter(PrintWriter out, String prefix, 8644 PackageParser.ProviderIntentInfo filter) { 8645 out.print(prefix); 8646 out.print( 8647 Integer.toHexString(System.identityHashCode(filter.provider))); 8648 out.print(' '); 8649 filter.provider.printComponentShortName(out); 8650 out.print(" filter "); 8651 out.println(Integer.toHexString(System.identityHashCode(filter))); 8652 } 8653 8654 @Override 8655 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8656 return filter.provider; 8657 } 8658 8659 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8660 PackageParser.Provider provider = (PackageParser.Provider)label; 8661 out.print(prefix); out.print( 8662 Integer.toHexString(System.identityHashCode(provider))); 8663 out.print(' '); 8664 provider.printComponentShortName(out); 8665 if (count > 1) { 8666 out.print(" ("); out.print(count); out.print(" filters)"); 8667 } 8668 out.println(); 8669 } 8670 8671 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8672 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8673 private int mFlags; 8674 }; 8675 8676 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8677 new Comparator<ResolveInfo>() { 8678 public int compare(ResolveInfo r1, ResolveInfo r2) { 8679 int v1 = r1.priority; 8680 int v2 = r2.priority; 8681 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8682 if (v1 != v2) { 8683 return (v1 > v2) ? -1 : 1; 8684 } 8685 v1 = r1.preferredOrder; 8686 v2 = r2.preferredOrder; 8687 if (v1 != v2) { 8688 return (v1 > v2) ? -1 : 1; 8689 } 8690 if (r1.isDefault != r2.isDefault) { 8691 return r1.isDefault ? -1 : 1; 8692 } 8693 v1 = r1.match; 8694 v2 = r2.match; 8695 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8696 if (v1 != v2) { 8697 return (v1 > v2) ? -1 : 1; 8698 } 8699 if (r1.system != r2.system) { 8700 return r1.system ? -1 : 1; 8701 } 8702 return 0; 8703 } 8704 }; 8705 8706 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8707 new Comparator<ProviderInfo>() { 8708 public int compare(ProviderInfo p1, ProviderInfo p2) { 8709 final int v1 = p1.initOrder; 8710 final int v2 = p2.initOrder; 8711 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8712 } 8713 }; 8714 8715 final void sendPackageBroadcast(final String action, final String pkg, 8716 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8717 final int[] userIds) { 8718 mHandler.post(new Runnable() { 8719 @Override 8720 public void run() { 8721 try { 8722 final IActivityManager am = ActivityManagerNative.getDefault(); 8723 if (am == null) return; 8724 final int[] resolvedUserIds; 8725 if (userIds == null) { 8726 resolvedUserIds = am.getRunningUserIds(); 8727 } else { 8728 resolvedUserIds = userIds; 8729 } 8730 for (int id : resolvedUserIds) { 8731 final Intent intent = new Intent(action, 8732 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8733 if (extras != null) { 8734 intent.putExtras(extras); 8735 } 8736 if (targetPkg != null) { 8737 intent.setPackage(targetPkg); 8738 } 8739 // Modify the UID when posting to other users 8740 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8741 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8742 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8743 intent.putExtra(Intent.EXTRA_UID, uid); 8744 } 8745 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8746 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8747 if (DEBUG_BROADCASTS) { 8748 RuntimeException here = new RuntimeException("here"); 8749 here.fillInStackTrace(); 8750 Slog.d(TAG, "Sending to user " + id + ": " 8751 + intent.toShortString(false, true, false, false) 8752 + " " + intent.getExtras(), here); 8753 } 8754 am.broadcastIntent(null, intent, null, finishedReceiver, 8755 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8756 finishedReceiver != null, false, id); 8757 } 8758 } catch (RemoteException ex) { 8759 } 8760 } 8761 }); 8762 } 8763 8764 /** 8765 * Check if the external storage media is available. This is true if there 8766 * is a mounted external storage medium or if the external storage is 8767 * emulated. 8768 */ 8769 private boolean isExternalMediaAvailable() { 8770 return mMediaMounted || Environment.isExternalStorageEmulated(); 8771 } 8772 8773 @Override 8774 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8775 // writer 8776 synchronized (mPackages) { 8777 if (!isExternalMediaAvailable()) { 8778 // If the external storage is no longer mounted at this point, 8779 // the caller may not have been able to delete all of this 8780 // packages files and can not delete any more. Bail. 8781 return null; 8782 } 8783 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8784 if (lastPackage != null) { 8785 pkgs.remove(lastPackage); 8786 } 8787 if (pkgs.size() > 0) { 8788 return pkgs.get(0); 8789 } 8790 } 8791 return null; 8792 } 8793 8794 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8795 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8796 userId, andCode ? 1 : 0, packageName); 8797 if (mSystemReady) { 8798 msg.sendToTarget(); 8799 } else { 8800 if (mPostSystemReadyMessages == null) { 8801 mPostSystemReadyMessages = new ArrayList<>(); 8802 } 8803 mPostSystemReadyMessages.add(msg); 8804 } 8805 } 8806 8807 void startCleaningPackages() { 8808 // reader 8809 synchronized (mPackages) { 8810 if (!isExternalMediaAvailable()) { 8811 return; 8812 } 8813 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8814 return; 8815 } 8816 } 8817 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8818 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8819 IActivityManager am = ActivityManagerNative.getDefault(); 8820 if (am != null) { 8821 try { 8822 am.startService(null, intent, null, UserHandle.USER_OWNER); 8823 } catch (RemoteException e) { 8824 } 8825 } 8826 } 8827 8828 @Override 8829 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8830 int installFlags, String installerPackageName, VerificationParams verificationParams, 8831 String packageAbiOverride) { 8832 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8833 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8834 } 8835 8836 @Override 8837 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8838 int installFlags, String installerPackageName, VerificationParams verificationParams, 8839 String packageAbiOverride, int userId) { 8840 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8841 8842 final int callingUid = Binder.getCallingUid(); 8843 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8844 8845 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8846 try { 8847 if (observer != null) { 8848 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8849 } 8850 } catch (RemoteException re) { 8851 } 8852 return; 8853 } 8854 8855 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8856 installFlags |= PackageManager.INSTALL_FROM_ADB; 8857 8858 } else { 8859 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8860 // about installerPackageName. 8861 8862 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8863 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8864 } 8865 8866 UserHandle user; 8867 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8868 user = UserHandle.ALL; 8869 } else { 8870 user = new UserHandle(userId); 8871 } 8872 8873 // Only system components can circumvent runtime permissions when installing. 8874 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8875 && mContext.checkCallingOrSelfPermission(Manifest.permission 8876 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8877 throw new SecurityException("You need the " 8878 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8879 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8880 } 8881 8882 verificationParams.setInstallerUid(callingUid); 8883 8884 final File originFile = new File(originPath); 8885 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8886 8887 final Message msg = mHandler.obtainMessage(INIT_COPY); 8888 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8889 null, verificationParams, user, packageAbiOverride); 8890 mHandler.sendMessage(msg); 8891 } 8892 8893 void installStage(String packageName, File stagedDir, String stagedCid, 8894 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8895 String installerPackageName, int installerUid, UserHandle user) { 8896 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8897 params.referrerUri, installerUid, null); 8898 8899 final OriginInfo origin; 8900 if (stagedDir != null) { 8901 origin = OriginInfo.fromStagedFile(stagedDir); 8902 } else { 8903 origin = OriginInfo.fromStagedContainer(stagedCid); 8904 } 8905 8906 final Message msg = mHandler.obtainMessage(INIT_COPY); 8907 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8908 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8909 mHandler.sendMessage(msg); 8910 } 8911 8912 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8913 Bundle extras = new Bundle(1); 8914 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8915 8916 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8917 packageName, extras, null, null, new int[] {userId}); 8918 try { 8919 IActivityManager am = ActivityManagerNative.getDefault(); 8920 final boolean isSystem = 8921 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8922 if (isSystem && am.isUserRunning(userId, false)) { 8923 // The just-installed/enabled app is bundled on the system, so presumed 8924 // to be able to run automatically without needing an explicit launch. 8925 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8926 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8927 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8928 .setPackage(packageName); 8929 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8930 android.app.AppOpsManager.OP_NONE, false, false, userId); 8931 } 8932 } catch (RemoteException e) { 8933 // shouldn't happen 8934 Slog.w(TAG, "Unable to bootstrap installed package", e); 8935 } 8936 } 8937 8938 @Override 8939 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8940 int userId) { 8941 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8942 PackageSetting pkgSetting; 8943 final int uid = Binder.getCallingUid(); 8944 enforceCrossUserPermission(uid, userId, true, true, 8945 "setApplicationHiddenSetting for user " + userId); 8946 8947 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8948 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8949 return false; 8950 } 8951 8952 long callingId = Binder.clearCallingIdentity(); 8953 try { 8954 boolean sendAdded = false; 8955 boolean sendRemoved = false; 8956 // writer 8957 synchronized (mPackages) { 8958 pkgSetting = mSettings.mPackages.get(packageName); 8959 if (pkgSetting == null) { 8960 return false; 8961 } 8962 if (pkgSetting.getHidden(userId) != hidden) { 8963 pkgSetting.setHidden(hidden, userId); 8964 mSettings.writePackageRestrictionsLPr(userId); 8965 if (hidden) { 8966 sendRemoved = true; 8967 } else { 8968 sendAdded = true; 8969 } 8970 } 8971 } 8972 if (sendAdded) { 8973 sendPackageAddedForUser(packageName, pkgSetting, userId); 8974 return true; 8975 } 8976 if (sendRemoved) { 8977 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8978 "hiding pkg"); 8979 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8980 } 8981 } finally { 8982 Binder.restoreCallingIdentity(callingId); 8983 } 8984 return false; 8985 } 8986 8987 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8988 int userId) { 8989 final PackageRemovedInfo info = new PackageRemovedInfo(); 8990 info.removedPackage = packageName; 8991 info.removedUsers = new int[] {userId}; 8992 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8993 info.sendBroadcast(false, false, false); 8994 } 8995 8996 /** 8997 * Returns true if application is not found or there was an error. Otherwise it returns 8998 * the hidden state of the package for the given user. 8999 */ 9000 @Override 9001 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9002 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9003 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9004 false, "getApplicationHidden for user " + userId); 9005 PackageSetting pkgSetting; 9006 long callingId = Binder.clearCallingIdentity(); 9007 try { 9008 // writer 9009 synchronized (mPackages) { 9010 pkgSetting = mSettings.mPackages.get(packageName); 9011 if (pkgSetting == null) { 9012 return true; 9013 } 9014 return pkgSetting.getHidden(userId); 9015 } 9016 } finally { 9017 Binder.restoreCallingIdentity(callingId); 9018 } 9019 } 9020 9021 /** 9022 * @hide 9023 */ 9024 @Override 9025 public int installExistingPackageAsUser(String packageName, int userId) { 9026 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9027 null); 9028 PackageSetting pkgSetting; 9029 final int uid = Binder.getCallingUid(); 9030 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9031 + userId); 9032 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9033 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9034 } 9035 9036 long callingId = Binder.clearCallingIdentity(); 9037 try { 9038 boolean sendAdded = false; 9039 9040 // writer 9041 synchronized (mPackages) { 9042 pkgSetting = mSettings.mPackages.get(packageName); 9043 if (pkgSetting == null) { 9044 return PackageManager.INSTALL_FAILED_INVALID_URI; 9045 } 9046 if (!pkgSetting.getInstalled(userId)) { 9047 pkgSetting.setInstalled(true, userId); 9048 pkgSetting.setHidden(false, userId); 9049 mSettings.writePackageRestrictionsLPr(userId); 9050 sendAdded = true; 9051 } 9052 } 9053 9054 if (sendAdded) { 9055 sendPackageAddedForUser(packageName, pkgSetting, userId); 9056 } 9057 } finally { 9058 Binder.restoreCallingIdentity(callingId); 9059 } 9060 9061 return PackageManager.INSTALL_SUCCEEDED; 9062 } 9063 9064 boolean isUserRestricted(int userId, String restrictionKey) { 9065 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9066 if (restrictions.getBoolean(restrictionKey, false)) { 9067 Log.w(TAG, "User is restricted: " + restrictionKey); 9068 return true; 9069 } 9070 return false; 9071 } 9072 9073 @Override 9074 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9075 mContext.enforceCallingOrSelfPermission( 9076 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9077 "Only package verification agents can verify applications"); 9078 9079 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9080 final PackageVerificationResponse response = new PackageVerificationResponse( 9081 verificationCode, Binder.getCallingUid()); 9082 msg.arg1 = id; 9083 msg.obj = response; 9084 mHandler.sendMessage(msg); 9085 } 9086 9087 @Override 9088 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9089 long millisecondsToDelay) { 9090 mContext.enforceCallingOrSelfPermission( 9091 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9092 "Only package verification agents can extend verification timeouts"); 9093 9094 final PackageVerificationState state = mPendingVerification.get(id); 9095 final PackageVerificationResponse response = new PackageVerificationResponse( 9096 verificationCodeAtTimeout, Binder.getCallingUid()); 9097 9098 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9099 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9100 } 9101 if (millisecondsToDelay < 0) { 9102 millisecondsToDelay = 0; 9103 } 9104 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9105 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9106 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9107 } 9108 9109 if ((state != null) && !state.timeoutExtended()) { 9110 state.extendTimeout(); 9111 9112 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9113 msg.arg1 = id; 9114 msg.obj = response; 9115 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9116 } 9117 } 9118 9119 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9120 int verificationCode, UserHandle user) { 9121 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9122 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9123 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9124 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9125 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9126 9127 mContext.sendBroadcastAsUser(intent, user, 9128 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9129 } 9130 9131 private ComponentName matchComponentForVerifier(String packageName, 9132 List<ResolveInfo> receivers) { 9133 ActivityInfo targetReceiver = null; 9134 9135 final int NR = receivers.size(); 9136 for (int i = 0; i < NR; i++) { 9137 final ResolveInfo info = receivers.get(i); 9138 if (info.activityInfo == null) { 9139 continue; 9140 } 9141 9142 if (packageName.equals(info.activityInfo.packageName)) { 9143 targetReceiver = info.activityInfo; 9144 break; 9145 } 9146 } 9147 9148 if (targetReceiver == null) { 9149 return null; 9150 } 9151 9152 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9153 } 9154 9155 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9156 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9157 if (pkgInfo.verifiers.length == 0) { 9158 return null; 9159 } 9160 9161 final int N = pkgInfo.verifiers.length; 9162 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9163 for (int i = 0; i < N; i++) { 9164 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9165 9166 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9167 receivers); 9168 if (comp == null) { 9169 continue; 9170 } 9171 9172 final int verifierUid = getUidForVerifier(verifierInfo); 9173 if (verifierUid == -1) { 9174 continue; 9175 } 9176 9177 if (DEBUG_VERIFY) { 9178 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9179 + " with the correct signature"); 9180 } 9181 sufficientVerifiers.add(comp); 9182 verificationState.addSufficientVerifier(verifierUid); 9183 } 9184 9185 return sufficientVerifiers; 9186 } 9187 9188 private int getUidForVerifier(VerifierInfo verifierInfo) { 9189 synchronized (mPackages) { 9190 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9191 if (pkg == null) { 9192 return -1; 9193 } else if (pkg.mSignatures.length != 1) { 9194 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9195 + " has more than one signature; ignoring"); 9196 return -1; 9197 } 9198 9199 /* 9200 * If the public key of the package's signature does not match 9201 * our expected public key, then this is a different package and 9202 * we should skip. 9203 */ 9204 9205 final byte[] expectedPublicKey; 9206 try { 9207 final Signature verifierSig = pkg.mSignatures[0]; 9208 final PublicKey publicKey = verifierSig.getPublicKey(); 9209 expectedPublicKey = publicKey.getEncoded(); 9210 } catch (CertificateException e) { 9211 return -1; 9212 } 9213 9214 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9215 9216 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9217 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9218 + " does not have the expected public key; ignoring"); 9219 return -1; 9220 } 9221 9222 return pkg.applicationInfo.uid; 9223 } 9224 } 9225 9226 @Override 9227 public void finishPackageInstall(int token) { 9228 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9229 9230 if (DEBUG_INSTALL) { 9231 Slog.v(TAG, "BM finishing package install for " + token); 9232 } 9233 9234 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9235 mHandler.sendMessage(msg); 9236 } 9237 9238 /** 9239 * Get the verification agent timeout. 9240 * 9241 * @return verification timeout in milliseconds 9242 */ 9243 private long getVerificationTimeout() { 9244 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9245 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9246 DEFAULT_VERIFICATION_TIMEOUT); 9247 } 9248 9249 /** 9250 * Get the default verification agent response code. 9251 * 9252 * @return default verification response code 9253 */ 9254 private int getDefaultVerificationResponse() { 9255 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9256 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9257 DEFAULT_VERIFICATION_RESPONSE); 9258 } 9259 9260 /** 9261 * Check whether or not package verification has been enabled. 9262 * 9263 * @return true if verification should be performed 9264 */ 9265 private boolean isVerificationEnabled(int userId, int installFlags) { 9266 if (!DEFAULT_VERIFY_ENABLE) { 9267 return false; 9268 } 9269 9270 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9271 9272 // Check if installing from ADB 9273 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9274 // Do not run verification in a test harness environment 9275 if (ActivityManager.isRunningInTestHarness()) { 9276 return false; 9277 } 9278 if (ensureVerifyAppsEnabled) { 9279 return true; 9280 } 9281 // Check if the developer does not want package verification for ADB installs 9282 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9283 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9284 return false; 9285 } 9286 } 9287 9288 if (ensureVerifyAppsEnabled) { 9289 return true; 9290 } 9291 9292 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9293 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9294 } 9295 9296 @Override 9297 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9298 throws RemoteException { 9299 mContext.enforceCallingOrSelfPermission( 9300 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9301 "Only intentfilter verification agents can verify applications"); 9302 9303 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9304 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9305 Binder.getCallingUid(), verificationCode, failedDomains); 9306 msg.arg1 = id; 9307 msg.obj = response; 9308 mHandler.sendMessage(msg); 9309 } 9310 9311 @Override 9312 public int getIntentVerificationStatus(String packageName, int userId) { 9313 synchronized (mPackages) { 9314 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9315 } 9316 } 9317 9318 @Override 9319 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9320 boolean result = false; 9321 synchronized (mPackages) { 9322 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9323 } 9324 if (result) { 9325 scheduleWritePackageRestrictionsLocked(userId); 9326 } 9327 return result; 9328 } 9329 9330 @Override 9331 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9332 synchronized (mPackages) { 9333 return mSettings.getIntentFilterVerificationsLPr(packageName); 9334 } 9335 } 9336 9337 @Override 9338 public List<IntentFilter> getAllIntentFilters(String packageName) { 9339 if (TextUtils.isEmpty(packageName)) { 9340 return Collections.<IntentFilter>emptyList(); 9341 } 9342 synchronized (mPackages) { 9343 PackageParser.Package pkg = mPackages.get(packageName); 9344 if (pkg == null || pkg.activities == null) { 9345 return Collections.<IntentFilter>emptyList(); 9346 } 9347 final int count = pkg.activities.size(); 9348 ArrayList<IntentFilter> result = new ArrayList<>(); 9349 for (int n=0; n<count; n++) { 9350 PackageParser.Activity activity = pkg.activities.get(n); 9351 if (activity.intents != null || activity.intents.size() > 0) { 9352 result.addAll(activity.intents); 9353 } 9354 } 9355 return result; 9356 } 9357 } 9358 9359 @Override 9360 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9361 synchronized (mPackages) { 9362 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9363 if (packageName != null) { 9364 result |= updateIntentVerificationStatus(packageName, 9365 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9366 UserHandle.myUserId()); 9367 } 9368 return result; 9369 } 9370 } 9371 9372 @Override 9373 public String getDefaultBrowserPackageName(int userId) { 9374 synchronized (mPackages) { 9375 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9376 } 9377 } 9378 9379 /** 9380 * Get the "allow unknown sources" setting. 9381 * 9382 * @return the current "allow unknown sources" setting 9383 */ 9384 private int getUnknownSourcesSettings() { 9385 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9386 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9387 -1); 9388 } 9389 9390 @Override 9391 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9392 final int uid = Binder.getCallingUid(); 9393 // writer 9394 synchronized (mPackages) { 9395 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9396 if (targetPackageSetting == null) { 9397 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9398 } 9399 9400 PackageSetting installerPackageSetting; 9401 if (installerPackageName != null) { 9402 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9403 if (installerPackageSetting == null) { 9404 throw new IllegalArgumentException("Unknown installer package: " 9405 + installerPackageName); 9406 } 9407 } else { 9408 installerPackageSetting = null; 9409 } 9410 9411 Signature[] callerSignature; 9412 Object obj = mSettings.getUserIdLPr(uid); 9413 if (obj != null) { 9414 if (obj instanceof SharedUserSetting) { 9415 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9416 } else if (obj instanceof PackageSetting) { 9417 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9418 } else { 9419 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9420 } 9421 } else { 9422 throw new SecurityException("Unknown calling uid " + uid); 9423 } 9424 9425 // Verify: can't set installerPackageName to a package that is 9426 // not signed with the same cert as the caller. 9427 if (installerPackageSetting != null) { 9428 if (compareSignatures(callerSignature, 9429 installerPackageSetting.signatures.mSignatures) 9430 != PackageManager.SIGNATURE_MATCH) { 9431 throw new SecurityException( 9432 "Caller does not have same cert as new installer package " 9433 + installerPackageName); 9434 } 9435 } 9436 9437 // Verify: if target already has an installer package, it must 9438 // be signed with the same cert as the caller. 9439 if (targetPackageSetting.installerPackageName != null) { 9440 PackageSetting setting = mSettings.mPackages.get( 9441 targetPackageSetting.installerPackageName); 9442 // If the currently set package isn't valid, then it's always 9443 // okay to change it. 9444 if (setting != null) { 9445 if (compareSignatures(callerSignature, 9446 setting.signatures.mSignatures) 9447 != PackageManager.SIGNATURE_MATCH) { 9448 throw new SecurityException( 9449 "Caller does not have same cert as old installer package " 9450 + targetPackageSetting.installerPackageName); 9451 } 9452 } 9453 } 9454 9455 // Okay! 9456 targetPackageSetting.installerPackageName = installerPackageName; 9457 scheduleWriteSettingsLocked(); 9458 } 9459 } 9460 9461 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9462 // Queue up an async operation since the package installation may take a little while. 9463 mHandler.post(new Runnable() { 9464 public void run() { 9465 mHandler.removeCallbacks(this); 9466 // Result object to be returned 9467 PackageInstalledInfo res = new PackageInstalledInfo(); 9468 res.returnCode = currentStatus; 9469 res.uid = -1; 9470 res.pkg = null; 9471 res.removedInfo = new PackageRemovedInfo(); 9472 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9473 args.doPreInstall(res.returnCode); 9474 synchronized (mInstallLock) { 9475 installPackageLI(args, res); 9476 } 9477 args.doPostInstall(res.returnCode, res.uid); 9478 } 9479 9480 // A restore should be performed at this point if (a) the install 9481 // succeeded, (b) the operation is not an update, and (c) the new 9482 // package has not opted out of backup participation. 9483 final boolean update = res.removedInfo.removedPackage != null; 9484 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9485 boolean doRestore = !update 9486 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9487 9488 // Set up the post-install work request bookkeeping. This will be used 9489 // and cleaned up by the post-install event handling regardless of whether 9490 // there's a restore pass performed. Token values are >= 1. 9491 int token; 9492 if (mNextInstallToken < 0) mNextInstallToken = 1; 9493 token = mNextInstallToken++; 9494 9495 PostInstallData data = new PostInstallData(args, res); 9496 mRunningInstalls.put(token, data); 9497 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9498 9499 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9500 // Pass responsibility to the Backup Manager. It will perform a 9501 // restore if appropriate, then pass responsibility back to the 9502 // Package Manager to run the post-install observer callbacks 9503 // and broadcasts. 9504 IBackupManager bm = IBackupManager.Stub.asInterface( 9505 ServiceManager.getService(Context.BACKUP_SERVICE)); 9506 if (bm != null) { 9507 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9508 + " to BM for possible restore"); 9509 try { 9510 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9511 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9512 } else { 9513 doRestore = false; 9514 } 9515 } catch (RemoteException e) { 9516 // can't happen; the backup manager is local 9517 } catch (Exception e) { 9518 Slog.e(TAG, "Exception trying to enqueue restore", e); 9519 doRestore = false; 9520 } 9521 } else { 9522 Slog.e(TAG, "Backup Manager not found!"); 9523 doRestore = false; 9524 } 9525 } 9526 9527 if (!doRestore) { 9528 // No restore possible, or the Backup Manager was mysteriously not 9529 // available -- just fire the post-install work request directly. 9530 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9531 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9532 mHandler.sendMessage(msg); 9533 } 9534 } 9535 }); 9536 } 9537 9538 private abstract class HandlerParams { 9539 private static final int MAX_RETRIES = 4; 9540 9541 /** 9542 * Number of times startCopy() has been attempted and had a non-fatal 9543 * error. 9544 */ 9545 private int mRetries = 0; 9546 9547 /** User handle for the user requesting the information or installation. */ 9548 private final UserHandle mUser; 9549 9550 HandlerParams(UserHandle user) { 9551 mUser = user; 9552 } 9553 9554 UserHandle getUser() { 9555 return mUser; 9556 } 9557 9558 final boolean startCopy() { 9559 boolean res; 9560 try { 9561 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9562 9563 if (++mRetries > MAX_RETRIES) { 9564 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9565 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9566 handleServiceError(); 9567 return false; 9568 } else { 9569 handleStartCopy(); 9570 res = true; 9571 } 9572 } catch (RemoteException e) { 9573 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9574 mHandler.sendEmptyMessage(MCS_RECONNECT); 9575 res = false; 9576 } 9577 handleReturnCode(); 9578 return res; 9579 } 9580 9581 final void serviceError() { 9582 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9583 handleServiceError(); 9584 handleReturnCode(); 9585 } 9586 9587 abstract void handleStartCopy() throws RemoteException; 9588 abstract void handleServiceError(); 9589 abstract void handleReturnCode(); 9590 } 9591 9592 class MeasureParams extends HandlerParams { 9593 private final PackageStats mStats; 9594 private boolean mSuccess; 9595 9596 private final IPackageStatsObserver mObserver; 9597 9598 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9599 super(new UserHandle(stats.userHandle)); 9600 mObserver = observer; 9601 mStats = stats; 9602 } 9603 9604 @Override 9605 public String toString() { 9606 return "MeasureParams{" 9607 + Integer.toHexString(System.identityHashCode(this)) 9608 + " " + mStats.packageName + "}"; 9609 } 9610 9611 @Override 9612 void handleStartCopy() throws RemoteException { 9613 synchronized (mInstallLock) { 9614 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9615 } 9616 9617 if (mSuccess) { 9618 final boolean mounted; 9619 if (Environment.isExternalStorageEmulated()) { 9620 mounted = true; 9621 } else { 9622 final String status = Environment.getExternalStorageState(); 9623 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9624 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9625 } 9626 9627 if (mounted) { 9628 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9629 9630 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9631 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9632 9633 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9634 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9635 9636 // Always subtract cache size, since it's a subdirectory 9637 mStats.externalDataSize -= mStats.externalCacheSize; 9638 9639 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9640 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9641 9642 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9643 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9644 } 9645 } 9646 } 9647 9648 @Override 9649 void handleReturnCode() { 9650 if (mObserver != null) { 9651 try { 9652 mObserver.onGetStatsCompleted(mStats, mSuccess); 9653 } catch (RemoteException e) { 9654 Slog.i(TAG, "Observer no longer exists."); 9655 } 9656 } 9657 } 9658 9659 @Override 9660 void handleServiceError() { 9661 Slog.e(TAG, "Could not measure application " + mStats.packageName 9662 + " external storage"); 9663 } 9664 } 9665 9666 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9667 throws RemoteException { 9668 long result = 0; 9669 for (File path : paths) { 9670 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9671 } 9672 return result; 9673 } 9674 9675 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9676 for (File path : paths) { 9677 try { 9678 mcs.clearDirectory(path.getAbsolutePath()); 9679 } catch (RemoteException e) { 9680 } 9681 } 9682 } 9683 9684 static class OriginInfo { 9685 /** 9686 * Location where install is coming from, before it has been 9687 * copied/renamed into place. This could be a single monolithic APK 9688 * file, or a cluster directory. This location may be untrusted. 9689 */ 9690 final File file; 9691 final String cid; 9692 9693 /** 9694 * Flag indicating that {@link #file} or {@link #cid} has already been 9695 * staged, meaning downstream users don't need to defensively copy the 9696 * contents. 9697 */ 9698 final boolean staged; 9699 9700 /** 9701 * Flag indicating that {@link #file} or {@link #cid} is an already 9702 * installed app that is being moved. 9703 */ 9704 final boolean existing; 9705 9706 final String resolvedPath; 9707 final File resolvedFile; 9708 9709 static OriginInfo fromNothing() { 9710 return new OriginInfo(null, null, false, false); 9711 } 9712 9713 static OriginInfo fromUntrustedFile(File file) { 9714 return new OriginInfo(file, null, false, false); 9715 } 9716 9717 static OriginInfo fromExistingFile(File file) { 9718 return new OriginInfo(file, null, false, true); 9719 } 9720 9721 static OriginInfo fromStagedFile(File file) { 9722 return new OriginInfo(file, null, true, false); 9723 } 9724 9725 static OriginInfo fromStagedContainer(String cid) { 9726 return new OriginInfo(null, cid, true, false); 9727 } 9728 9729 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9730 this.file = file; 9731 this.cid = cid; 9732 this.staged = staged; 9733 this.existing = existing; 9734 9735 if (cid != null) { 9736 resolvedPath = PackageHelper.getSdDir(cid); 9737 resolvedFile = new File(resolvedPath); 9738 } else if (file != null) { 9739 resolvedPath = file.getAbsolutePath(); 9740 resolvedFile = file; 9741 } else { 9742 resolvedPath = null; 9743 resolvedFile = null; 9744 } 9745 } 9746 } 9747 9748 class MoveInfo { 9749 final int moveId; 9750 final String fromUuid; 9751 final String toUuid; 9752 final String packageName; 9753 final String dataAppName; 9754 final int appId; 9755 final String seinfo; 9756 9757 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9758 String dataAppName, int appId, String seinfo) { 9759 this.moveId = moveId; 9760 this.fromUuid = fromUuid; 9761 this.toUuid = toUuid; 9762 this.packageName = packageName; 9763 this.dataAppName = dataAppName; 9764 this.appId = appId; 9765 this.seinfo = seinfo; 9766 } 9767 } 9768 9769 class InstallParams extends HandlerParams { 9770 final OriginInfo origin; 9771 final MoveInfo move; 9772 final IPackageInstallObserver2 observer; 9773 int installFlags; 9774 final String installerPackageName; 9775 final String volumeUuid; 9776 final VerificationParams verificationParams; 9777 private InstallArgs mArgs; 9778 private int mRet; 9779 final String packageAbiOverride; 9780 9781 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9782 int installFlags, String installerPackageName, String volumeUuid, 9783 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9784 super(user); 9785 this.origin = origin; 9786 this.move = move; 9787 this.observer = observer; 9788 this.installFlags = installFlags; 9789 this.installerPackageName = installerPackageName; 9790 this.volumeUuid = volumeUuid; 9791 this.verificationParams = verificationParams; 9792 this.packageAbiOverride = packageAbiOverride; 9793 } 9794 9795 @Override 9796 public String toString() { 9797 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9798 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9799 } 9800 9801 public ManifestDigest getManifestDigest() { 9802 if (verificationParams == null) { 9803 return null; 9804 } 9805 return verificationParams.getManifestDigest(); 9806 } 9807 9808 private int installLocationPolicy(PackageInfoLite pkgLite) { 9809 String packageName = pkgLite.packageName; 9810 int installLocation = pkgLite.installLocation; 9811 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9812 // reader 9813 synchronized (mPackages) { 9814 PackageParser.Package pkg = mPackages.get(packageName); 9815 if (pkg != null) { 9816 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9817 // Check for downgrading. 9818 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9819 try { 9820 checkDowngrade(pkg, pkgLite); 9821 } catch (PackageManagerException e) { 9822 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9823 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9824 } 9825 } 9826 // Check for updated system application. 9827 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9828 if (onSd) { 9829 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9830 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9831 } 9832 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9833 } else { 9834 if (onSd) { 9835 // Install flag overrides everything. 9836 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9837 } 9838 // If current upgrade specifies particular preference 9839 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9840 // Application explicitly specified internal. 9841 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9842 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9843 // App explictly prefers external. Let policy decide 9844 } else { 9845 // Prefer previous location 9846 if (isExternal(pkg)) { 9847 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9848 } 9849 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9850 } 9851 } 9852 } else { 9853 // Invalid install. Return error code 9854 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9855 } 9856 } 9857 } 9858 // All the special cases have been taken care of. 9859 // Return result based on recommended install location. 9860 if (onSd) { 9861 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9862 } 9863 return pkgLite.recommendedInstallLocation; 9864 } 9865 9866 /* 9867 * Invoke remote method to get package information and install 9868 * location values. Override install location based on default 9869 * policy if needed and then create install arguments based 9870 * on the install location. 9871 */ 9872 public void handleStartCopy() throws RemoteException { 9873 int ret = PackageManager.INSTALL_SUCCEEDED; 9874 9875 // If we're already staged, we've firmly committed to an install location 9876 if (origin.staged) { 9877 if (origin.file != null) { 9878 installFlags |= PackageManager.INSTALL_INTERNAL; 9879 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9880 } else if (origin.cid != null) { 9881 installFlags |= PackageManager.INSTALL_EXTERNAL; 9882 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9883 } else { 9884 throw new IllegalStateException("Invalid stage location"); 9885 } 9886 } 9887 9888 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9889 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9890 9891 PackageInfoLite pkgLite = null; 9892 9893 if (onInt && onSd) { 9894 // Check if both bits are set. 9895 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9896 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9897 } else { 9898 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9899 packageAbiOverride); 9900 9901 /* 9902 * If we have too little free space, try to free cache 9903 * before giving up. 9904 */ 9905 if (!origin.staged && pkgLite.recommendedInstallLocation 9906 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9907 // TODO: focus freeing disk space on the target device 9908 final StorageManager storage = StorageManager.from(mContext); 9909 final long lowThreshold = storage.getStorageLowBytes( 9910 Environment.getDataDirectory()); 9911 9912 final long sizeBytes = mContainerService.calculateInstalledSize( 9913 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9914 9915 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9916 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9917 installFlags, packageAbiOverride); 9918 } 9919 9920 /* 9921 * The cache free must have deleted the file we 9922 * downloaded to install. 9923 * 9924 * TODO: fix the "freeCache" call to not delete 9925 * the file we care about. 9926 */ 9927 if (pkgLite.recommendedInstallLocation 9928 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9929 pkgLite.recommendedInstallLocation 9930 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9931 } 9932 } 9933 } 9934 9935 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9936 int loc = pkgLite.recommendedInstallLocation; 9937 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9938 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9939 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9940 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9941 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9942 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9943 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9944 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9945 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9946 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9947 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9948 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9949 } else { 9950 // Override with defaults if needed. 9951 loc = installLocationPolicy(pkgLite); 9952 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9953 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9954 } else if (!onSd && !onInt) { 9955 // Override install location with flags 9956 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9957 // Set the flag to install on external media. 9958 installFlags |= PackageManager.INSTALL_EXTERNAL; 9959 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9960 } else { 9961 // Make sure the flag for installing on external 9962 // media is unset 9963 installFlags |= PackageManager.INSTALL_INTERNAL; 9964 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9965 } 9966 } 9967 } 9968 } 9969 9970 final InstallArgs args = createInstallArgs(this); 9971 mArgs = args; 9972 9973 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9974 /* 9975 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9976 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9977 */ 9978 int userIdentifier = getUser().getIdentifier(); 9979 if (userIdentifier == UserHandle.USER_ALL 9980 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9981 userIdentifier = UserHandle.USER_OWNER; 9982 } 9983 9984 /* 9985 * Determine if we have any installed package verifiers. If we 9986 * do, then we'll defer to them to verify the packages. 9987 */ 9988 final int requiredUid = mRequiredVerifierPackage == null ? -1 9989 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9990 if (!origin.existing && requiredUid != -1 9991 && isVerificationEnabled(userIdentifier, installFlags)) { 9992 final Intent verification = new Intent( 9993 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9994 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9995 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9996 PACKAGE_MIME_TYPE); 9997 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9998 9999 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10000 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10001 0 /* TODO: Which userId? */); 10002 10003 if (DEBUG_VERIFY) { 10004 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10005 + verification.toString() + " with " + pkgLite.verifiers.length 10006 + " optional verifiers"); 10007 } 10008 10009 final int verificationId = mPendingVerificationToken++; 10010 10011 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10012 10013 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10014 installerPackageName); 10015 10016 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10017 installFlags); 10018 10019 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10020 pkgLite.packageName); 10021 10022 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10023 pkgLite.versionCode); 10024 10025 if (verificationParams != null) { 10026 if (verificationParams.getVerificationURI() != null) { 10027 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10028 verificationParams.getVerificationURI()); 10029 } 10030 if (verificationParams.getOriginatingURI() != null) { 10031 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10032 verificationParams.getOriginatingURI()); 10033 } 10034 if (verificationParams.getReferrer() != null) { 10035 verification.putExtra(Intent.EXTRA_REFERRER, 10036 verificationParams.getReferrer()); 10037 } 10038 if (verificationParams.getOriginatingUid() >= 0) { 10039 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10040 verificationParams.getOriginatingUid()); 10041 } 10042 if (verificationParams.getInstallerUid() >= 0) { 10043 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10044 verificationParams.getInstallerUid()); 10045 } 10046 } 10047 10048 final PackageVerificationState verificationState = new PackageVerificationState( 10049 requiredUid, args); 10050 10051 mPendingVerification.append(verificationId, verificationState); 10052 10053 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10054 receivers, verificationState); 10055 10056 /* 10057 * If any sufficient verifiers were listed in the package 10058 * manifest, attempt to ask them. 10059 */ 10060 if (sufficientVerifiers != null) { 10061 final int N = sufficientVerifiers.size(); 10062 if (N == 0) { 10063 Slog.i(TAG, "Additional verifiers required, but none installed."); 10064 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10065 } else { 10066 for (int i = 0; i < N; i++) { 10067 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10068 10069 final Intent sufficientIntent = new Intent(verification); 10070 sufficientIntent.setComponent(verifierComponent); 10071 10072 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10073 } 10074 } 10075 } 10076 10077 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10078 mRequiredVerifierPackage, receivers); 10079 if (ret == PackageManager.INSTALL_SUCCEEDED 10080 && mRequiredVerifierPackage != null) { 10081 /* 10082 * Send the intent to the required verification agent, 10083 * but only start the verification timeout after the 10084 * target BroadcastReceivers have run. 10085 */ 10086 verification.setComponent(requiredVerifierComponent); 10087 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10088 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10089 new BroadcastReceiver() { 10090 @Override 10091 public void onReceive(Context context, Intent intent) { 10092 final Message msg = mHandler 10093 .obtainMessage(CHECK_PENDING_VERIFICATION); 10094 msg.arg1 = verificationId; 10095 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10096 } 10097 }, null, 0, null, null); 10098 10099 /* 10100 * We don't want the copy to proceed until verification 10101 * succeeds, so null out this field. 10102 */ 10103 mArgs = null; 10104 } 10105 } else { 10106 /* 10107 * No package verification is enabled, so immediately start 10108 * the remote call to initiate copy using temporary file. 10109 */ 10110 ret = args.copyApk(mContainerService, true); 10111 } 10112 } 10113 10114 mRet = ret; 10115 } 10116 10117 @Override 10118 void handleReturnCode() { 10119 // If mArgs is null, then MCS couldn't be reached. When it 10120 // reconnects, it will try again to install. At that point, this 10121 // will succeed. 10122 if (mArgs != null) { 10123 processPendingInstall(mArgs, mRet); 10124 } 10125 } 10126 10127 @Override 10128 void handleServiceError() { 10129 mArgs = createInstallArgs(this); 10130 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10131 } 10132 10133 public boolean isForwardLocked() { 10134 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10135 } 10136 } 10137 10138 /** 10139 * Used during creation of InstallArgs 10140 * 10141 * @param installFlags package installation flags 10142 * @return true if should be installed on external storage 10143 */ 10144 private static boolean installOnExternalAsec(int installFlags) { 10145 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10146 return false; 10147 } 10148 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10149 return true; 10150 } 10151 return false; 10152 } 10153 10154 /** 10155 * Used during creation of InstallArgs 10156 * 10157 * @param installFlags package installation flags 10158 * @return true if should be installed as forward locked 10159 */ 10160 private static boolean installForwardLocked(int installFlags) { 10161 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10162 } 10163 10164 private InstallArgs createInstallArgs(InstallParams params) { 10165 if (params.move != null) { 10166 return new MoveInstallArgs(params); 10167 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10168 return new AsecInstallArgs(params); 10169 } else { 10170 return new FileInstallArgs(params); 10171 } 10172 } 10173 10174 /** 10175 * Create args that describe an existing installed package. Typically used 10176 * when cleaning up old installs, or used as a move source. 10177 */ 10178 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10179 String resourcePath, String[] instructionSets) { 10180 final boolean isInAsec; 10181 if (installOnExternalAsec(installFlags)) { 10182 /* Apps on SD card are always in ASEC containers. */ 10183 isInAsec = true; 10184 } else if (installForwardLocked(installFlags) 10185 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10186 /* 10187 * Forward-locked apps are only in ASEC containers if they're the 10188 * new style 10189 */ 10190 isInAsec = true; 10191 } else { 10192 isInAsec = false; 10193 } 10194 10195 if (isInAsec) { 10196 return new AsecInstallArgs(codePath, instructionSets, 10197 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10198 } else { 10199 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10200 } 10201 } 10202 10203 static abstract class InstallArgs { 10204 /** @see InstallParams#origin */ 10205 final OriginInfo origin; 10206 /** @see InstallParams#move */ 10207 final MoveInfo move; 10208 10209 final IPackageInstallObserver2 observer; 10210 // Always refers to PackageManager flags only 10211 final int installFlags; 10212 final String installerPackageName; 10213 final String volumeUuid; 10214 final ManifestDigest manifestDigest; 10215 final UserHandle user; 10216 final String abiOverride; 10217 10218 // The list of instruction sets supported by this app. This is currently 10219 // only used during the rmdex() phase to clean up resources. We can get rid of this 10220 // if we move dex files under the common app path. 10221 /* nullable */ String[] instructionSets; 10222 10223 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10224 int installFlags, String installerPackageName, String volumeUuid, 10225 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10226 String abiOverride) { 10227 this.origin = origin; 10228 this.move = move; 10229 this.installFlags = installFlags; 10230 this.observer = observer; 10231 this.installerPackageName = installerPackageName; 10232 this.volumeUuid = volumeUuid; 10233 this.manifestDigest = manifestDigest; 10234 this.user = user; 10235 this.instructionSets = instructionSets; 10236 this.abiOverride = abiOverride; 10237 } 10238 10239 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10240 abstract int doPreInstall(int status); 10241 10242 /** 10243 * Rename package into final resting place. All paths on the given 10244 * scanned package should be updated to reflect the rename. 10245 */ 10246 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10247 abstract int doPostInstall(int status, int uid); 10248 10249 /** @see PackageSettingBase#codePathString */ 10250 abstract String getCodePath(); 10251 /** @see PackageSettingBase#resourcePathString */ 10252 abstract String getResourcePath(); 10253 10254 // Need installer lock especially for dex file removal. 10255 abstract void cleanUpResourcesLI(); 10256 abstract boolean doPostDeleteLI(boolean delete); 10257 10258 /** 10259 * Called before the source arguments are copied. This is used mostly 10260 * for MoveParams when it needs to read the source file to put it in the 10261 * destination. 10262 */ 10263 int doPreCopy() { 10264 return PackageManager.INSTALL_SUCCEEDED; 10265 } 10266 10267 /** 10268 * Called after the source arguments are copied. This is used mostly for 10269 * MoveParams when it needs to read the source file to put it in the 10270 * destination. 10271 * 10272 * @return 10273 */ 10274 int doPostCopy(int uid) { 10275 return PackageManager.INSTALL_SUCCEEDED; 10276 } 10277 10278 protected boolean isFwdLocked() { 10279 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10280 } 10281 10282 protected boolean isExternalAsec() { 10283 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10284 } 10285 10286 UserHandle getUser() { 10287 return user; 10288 } 10289 } 10290 10291 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10292 if (!allCodePaths.isEmpty()) { 10293 if (instructionSets == null) { 10294 throw new IllegalStateException("instructionSet == null"); 10295 } 10296 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10297 for (String codePath : allCodePaths) { 10298 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10299 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10300 if (retCode < 0) { 10301 Slog.w(TAG, "Couldn't remove dex file for package: " 10302 + " at location " + codePath + ", retcode=" + retCode); 10303 // we don't consider this to be a failure of the core package deletion 10304 } 10305 } 10306 } 10307 } 10308 } 10309 10310 /** 10311 * Logic to handle installation of non-ASEC applications, including copying 10312 * and renaming logic. 10313 */ 10314 class FileInstallArgs extends InstallArgs { 10315 private File codeFile; 10316 private File resourceFile; 10317 10318 // Example topology: 10319 // /data/app/com.example/base.apk 10320 // /data/app/com.example/split_foo.apk 10321 // /data/app/com.example/lib/arm/libfoo.so 10322 // /data/app/com.example/lib/arm64/libfoo.so 10323 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10324 10325 /** New install */ 10326 FileInstallArgs(InstallParams params) { 10327 super(params.origin, params.move, params.observer, params.installFlags, 10328 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10329 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10330 if (isFwdLocked()) { 10331 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10332 } 10333 } 10334 10335 /** Existing install */ 10336 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10337 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10338 null); 10339 this.codeFile = (codePath != null) ? new File(codePath) : null; 10340 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10341 } 10342 10343 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10344 if (origin.staged) { 10345 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10346 codeFile = origin.file; 10347 resourceFile = origin.file; 10348 return PackageManager.INSTALL_SUCCEEDED; 10349 } 10350 10351 try { 10352 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10353 codeFile = tempDir; 10354 resourceFile = tempDir; 10355 } catch (IOException e) { 10356 Slog.w(TAG, "Failed to create copy file: " + e); 10357 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10358 } 10359 10360 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10361 @Override 10362 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10363 if (!FileUtils.isValidExtFilename(name)) { 10364 throw new IllegalArgumentException("Invalid filename: " + name); 10365 } 10366 try { 10367 final File file = new File(codeFile, name); 10368 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10369 O_RDWR | O_CREAT, 0644); 10370 Os.chmod(file.getAbsolutePath(), 0644); 10371 return new ParcelFileDescriptor(fd); 10372 } catch (ErrnoException e) { 10373 throw new RemoteException("Failed to open: " + e.getMessage()); 10374 } 10375 } 10376 }; 10377 10378 int ret = PackageManager.INSTALL_SUCCEEDED; 10379 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10380 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10381 Slog.e(TAG, "Failed to copy package"); 10382 return ret; 10383 } 10384 10385 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10386 NativeLibraryHelper.Handle handle = null; 10387 try { 10388 handle = NativeLibraryHelper.Handle.create(codeFile); 10389 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10390 abiOverride); 10391 } catch (IOException e) { 10392 Slog.e(TAG, "Copying native libraries failed", e); 10393 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10394 } finally { 10395 IoUtils.closeQuietly(handle); 10396 } 10397 10398 return ret; 10399 } 10400 10401 int doPreInstall(int status) { 10402 if (status != PackageManager.INSTALL_SUCCEEDED) { 10403 cleanUp(); 10404 } 10405 return status; 10406 } 10407 10408 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10409 if (status != PackageManager.INSTALL_SUCCEEDED) { 10410 cleanUp(); 10411 return false; 10412 } 10413 10414 final File targetDir = codeFile.getParentFile(); 10415 final File beforeCodeFile = codeFile; 10416 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10417 10418 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10419 try { 10420 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10421 } catch (ErrnoException e) { 10422 Slog.d(TAG, "Failed to rename", e); 10423 return false; 10424 } 10425 10426 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10427 Slog.d(TAG, "Failed to restorecon"); 10428 return false; 10429 } 10430 10431 // Reflect the rename internally 10432 codeFile = afterCodeFile; 10433 resourceFile = afterCodeFile; 10434 10435 // Reflect the rename in scanned details 10436 pkg.codePath = afterCodeFile.getAbsolutePath(); 10437 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10438 pkg.baseCodePath); 10439 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10440 pkg.splitCodePaths); 10441 10442 // Reflect the rename in app info 10443 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10444 pkg.applicationInfo.setCodePath(pkg.codePath); 10445 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10446 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10447 pkg.applicationInfo.setResourcePath(pkg.codePath); 10448 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10449 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10450 10451 return true; 10452 } 10453 10454 int doPostInstall(int status, int uid) { 10455 if (status != PackageManager.INSTALL_SUCCEEDED) { 10456 cleanUp(); 10457 } 10458 return status; 10459 } 10460 10461 @Override 10462 String getCodePath() { 10463 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10464 } 10465 10466 @Override 10467 String getResourcePath() { 10468 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10469 } 10470 10471 private boolean cleanUp() { 10472 if (codeFile == null || !codeFile.exists()) { 10473 return false; 10474 } 10475 10476 if (codeFile.isDirectory()) { 10477 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10478 } else { 10479 codeFile.delete(); 10480 } 10481 10482 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10483 resourceFile.delete(); 10484 } 10485 10486 return true; 10487 } 10488 10489 void cleanUpResourcesLI() { 10490 // Try enumerating all code paths before deleting 10491 List<String> allCodePaths = Collections.EMPTY_LIST; 10492 if (codeFile != null && codeFile.exists()) { 10493 try { 10494 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10495 allCodePaths = pkg.getAllCodePaths(); 10496 } catch (PackageParserException e) { 10497 // Ignored; we tried our best 10498 } 10499 } 10500 10501 cleanUp(); 10502 removeDexFiles(allCodePaths, instructionSets); 10503 } 10504 10505 boolean doPostDeleteLI(boolean delete) { 10506 // XXX err, shouldn't we respect the delete flag? 10507 cleanUpResourcesLI(); 10508 return true; 10509 } 10510 } 10511 10512 private boolean isAsecExternal(String cid) { 10513 final String asecPath = PackageHelper.getSdFilesystem(cid); 10514 return !asecPath.startsWith(mAsecInternalPath); 10515 } 10516 10517 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10518 PackageManagerException { 10519 if (copyRet < 0) { 10520 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10521 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10522 throw new PackageManagerException(copyRet, message); 10523 } 10524 } 10525 } 10526 10527 /** 10528 * Extract the MountService "container ID" from the full code path of an 10529 * .apk. 10530 */ 10531 static String cidFromCodePath(String fullCodePath) { 10532 int eidx = fullCodePath.lastIndexOf("/"); 10533 String subStr1 = fullCodePath.substring(0, eidx); 10534 int sidx = subStr1.lastIndexOf("/"); 10535 return subStr1.substring(sidx+1, eidx); 10536 } 10537 10538 /** 10539 * Logic to handle installation of ASEC applications, including copying and 10540 * renaming logic. 10541 */ 10542 class AsecInstallArgs extends InstallArgs { 10543 static final String RES_FILE_NAME = "pkg.apk"; 10544 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10545 10546 String cid; 10547 String packagePath; 10548 String resourcePath; 10549 10550 /** New install */ 10551 AsecInstallArgs(InstallParams params) { 10552 super(params.origin, params.move, params.observer, params.installFlags, 10553 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10554 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10555 } 10556 10557 /** Existing install */ 10558 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10559 boolean isExternal, boolean isForwardLocked) { 10560 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10561 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10562 instructionSets, null); 10563 // Hackily pretend we're still looking at a full code path 10564 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10565 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10566 } 10567 10568 // Extract cid from fullCodePath 10569 int eidx = fullCodePath.lastIndexOf("/"); 10570 String subStr1 = fullCodePath.substring(0, eidx); 10571 int sidx = subStr1.lastIndexOf("/"); 10572 cid = subStr1.substring(sidx+1, eidx); 10573 setMountPath(subStr1); 10574 } 10575 10576 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10577 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10578 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10579 instructionSets, null); 10580 this.cid = cid; 10581 setMountPath(PackageHelper.getSdDir(cid)); 10582 } 10583 10584 void createCopyFile() { 10585 cid = mInstallerService.allocateExternalStageCidLegacy(); 10586 } 10587 10588 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10589 if (origin.staged) { 10590 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10591 cid = origin.cid; 10592 setMountPath(PackageHelper.getSdDir(cid)); 10593 return PackageManager.INSTALL_SUCCEEDED; 10594 } 10595 10596 if (temp) { 10597 createCopyFile(); 10598 } else { 10599 /* 10600 * Pre-emptively destroy the container since it's destroyed if 10601 * copying fails due to it existing anyway. 10602 */ 10603 PackageHelper.destroySdDir(cid); 10604 } 10605 10606 final String newMountPath = imcs.copyPackageToContainer( 10607 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10608 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10609 10610 if (newMountPath != null) { 10611 setMountPath(newMountPath); 10612 return PackageManager.INSTALL_SUCCEEDED; 10613 } else { 10614 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10615 } 10616 } 10617 10618 @Override 10619 String getCodePath() { 10620 return packagePath; 10621 } 10622 10623 @Override 10624 String getResourcePath() { 10625 return resourcePath; 10626 } 10627 10628 int doPreInstall(int status) { 10629 if (status != PackageManager.INSTALL_SUCCEEDED) { 10630 // Destroy container 10631 PackageHelper.destroySdDir(cid); 10632 } else { 10633 boolean mounted = PackageHelper.isContainerMounted(cid); 10634 if (!mounted) { 10635 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10636 Process.SYSTEM_UID); 10637 if (newMountPath != null) { 10638 setMountPath(newMountPath); 10639 } else { 10640 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10641 } 10642 } 10643 } 10644 return status; 10645 } 10646 10647 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10648 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10649 String newMountPath = null; 10650 if (PackageHelper.isContainerMounted(cid)) { 10651 // Unmount the container 10652 if (!PackageHelper.unMountSdDir(cid)) { 10653 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10654 return false; 10655 } 10656 } 10657 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10658 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10659 " which might be stale. Will try to clean up."); 10660 // Clean up the stale container and proceed to recreate. 10661 if (!PackageHelper.destroySdDir(newCacheId)) { 10662 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10663 return false; 10664 } 10665 // Successfully cleaned up stale container. Try to rename again. 10666 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10667 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10668 + " inspite of cleaning it up."); 10669 return false; 10670 } 10671 } 10672 if (!PackageHelper.isContainerMounted(newCacheId)) { 10673 Slog.w(TAG, "Mounting container " + newCacheId); 10674 newMountPath = PackageHelper.mountSdDir(newCacheId, 10675 getEncryptKey(), Process.SYSTEM_UID); 10676 } else { 10677 newMountPath = PackageHelper.getSdDir(newCacheId); 10678 } 10679 if (newMountPath == null) { 10680 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10681 return false; 10682 } 10683 Log.i(TAG, "Succesfully renamed " + cid + 10684 " to " + newCacheId + 10685 " at new path: " + newMountPath); 10686 cid = newCacheId; 10687 10688 final File beforeCodeFile = new File(packagePath); 10689 setMountPath(newMountPath); 10690 final File afterCodeFile = new File(packagePath); 10691 10692 // Reflect the rename in scanned details 10693 pkg.codePath = afterCodeFile.getAbsolutePath(); 10694 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10695 pkg.baseCodePath); 10696 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10697 pkg.splitCodePaths); 10698 10699 // Reflect the rename in app info 10700 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10701 pkg.applicationInfo.setCodePath(pkg.codePath); 10702 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10703 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10704 pkg.applicationInfo.setResourcePath(pkg.codePath); 10705 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10706 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10707 10708 return true; 10709 } 10710 10711 private void setMountPath(String mountPath) { 10712 final File mountFile = new File(mountPath); 10713 10714 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10715 if (monolithicFile.exists()) { 10716 packagePath = monolithicFile.getAbsolutePath(); 10717 if (isFwdLocked()) { 10718 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10719 } else { 10720 resourcePath = packagePath; 10721 } 10722 } else { 10723 packagePath = mountFile.getAbsolutePath(); 10724 resourcePath = packagePath; 10725 } 10726 } 10727 10728 int doPostInstall(int status, int uid) { 10729 if (status != PackageManager.INSTALL_SUCCEEDED) { 10730 cleanUp(); 10731 } else { 10732 final int groupOwner; 10733 final String protectedFile; 10734 if (isFwdLocked()) { 10735 groupOwner = UserHandle.getSharedAppGid(uid); 10736 protectedFile = RES_FILE_NAME; 10737 } else { 10738 groupOwner = -1; 10739 protectedFile = null; 10740 } 10741 10742 if (uid < Process.FIRST_APPLICATION_UID 10743 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10744 Slog.e(TAG, "Failed to finalize " + cid); 10745 PackageHelper.destroySdDir(cid); 10746 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10747 } 10748 10749 boolean mounted = PackageHelper.isContainerMounted(cid); 10750 if (!mounted) { 10751 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10752 } 10753 } 10754 return status; 10755 } 10756 10757 private void cleanUp() { 10758 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10759 10760 // Destroy secure container 10761 PackageHelper.destroySdDir(cid); 10762 } 10763 10764 private List<String> getAllCodePaths() { 10765 final File codeFile = new File(getCodePath()); 10766 if (codeFile != null && codeFile.exists()) { 10767 try { 10768 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10769 return pkg.getAllCodePaths(); 10770 } catch (PackageParserException e) { 10771 // Ignored; we tried our best 10772 } 10773 } 10774 return Collections.EMPTY_LIST; 10775 } 10776 10777 void cleanUpResourcesLI() { 10778 // Enumerate all code paths before deleting 10779 cleanUpResourcesLI(getAllCodePaths()); 10780 } 10781 10782 private void cleanUpResourcesLI(List<String> allCodePaths) { 10783 cleanUp(); 10784 removeDexFiles(allCodePaths, instructionSets); 10785 } 10786 10787 String getPackageName() { 10788 return getAsecPackageName(cid); 10789 } 10790 10791 boolean doPostDeleteLI(boolean delete) { 10792 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10793 final List<String> allCodePaths = getAllCodePaths(); 10794 boolean mounted = PackageHelper.isContainerMounted(cid); 10795 if (mounted) { 10796 // Unmount first 10797 if (PackageHelper.unMountSdDir(cid)) { 10798 mounted = false; 10799 } 10800 } 10801 if (!mounted && delete) { 10802 cleanUpResourcesLI(allCodePaths); 10803 } 10804 return !mounted; 10805 } 10806 10807 @Override 10808 int doPreCopy() { 10809 if (isFwdLocked()) { 10810 if (!PackageHelper.fixSdPermissions(cid, 10811 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10812 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10813 } 10814 } 10815 10816 return PackageManager.INSTALL_SUCCEEDED; 10817 } 10818 10819 @Override 10820 int doPostCopy(int uid) { 10821 if (isFwdLocked()) { 10822 if (uid < Process.FIRST_APPLICATION_UID 10823 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10824 RES_FILE_NAME)) { 10825 Slog.e(TAG, "Failed to finalize " + cid); 10826 PackageHelper.destroySdDir(cid); 10827 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10828 } 10829 } 10830 10831 return PackageManager.INSTALL_SUCCEEDED; 10832 } 10833 } 10834 10835 /** 10836 * Logic to handle movement of existing installed applications. 10837 */ 10838 class MoveInstallArgs extends InstallArgs { 10839 private File codeFile; 10840 private File resourceFile; 10841 10842 /** New install */ 10843 MoveInstallArgs(InstallParams params) { 10844 super(params.origin, params.move, params.observer, params.installFlags, 10845 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10846 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10847 } 10848 10849 int copyApk(IMediaContainerService imcs, boolean temp) { 10850 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10851 + move.toUuid); 10852 synchronized (mInstaller) { 10853 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10854 move.dataAppName, move.appId, move.seinfo) != 0) { 10855 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10856 } 10857 } 10858 10859 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10860 resourceFile = codeFile; 10861 Slog.d(TAG, "codeFile after move is " + codeFile); 10862 10863 return PackageManager.INSTALL_SUCCEEDED; 10864 } 10865 10866 int doPreInstall(int status) { 10867 if (status != PackageManager.INSTALL_SUCCEEDED) { 10868 cleanUp(); 10869 } 10870 return status; 10871 } 10872 10873 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10874 if (status != PackageManager.INSTALL_SUCCEEDED) { 10875 cleanUp(); 10876 return false; 10877 } 10878 10879 // Reflect the move in app info 10880 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10881 pkg.applicationInfo.setCodePath(pkg.codePath); 10882 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10883 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10884 pkg.applicationInfo.setResourcePath(pkg.codePath); 10885 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10886 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10887 10888 return true; 10889 } 10890 10891 int doPostInstall(int status, int uid) { 10892 if (status != PackageManager.INSTALL_SUCCEEDED) { 10893 cleanUp(); 10894 } 10895 return status; 10896 } 10897 10898 @Override 10899 String getCodePath() { 10900 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10901 } 10902 10903 @Override 10904 String getResourcePath() { 10905 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10906 } 10907 10908 private boolean cleanUp() { 10909 if (codeFile == null || !codeFile.exists()) { 10910 return false; 10911 } 10912 10913 if (codeFile.isDirectory()) { 10914 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10915 } else { 10916 codeFile.delete(); 10917 } 10918 10919 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10920 resourceFile.delete(); 10921 } 10922 10923 return true; 10924 } 10925 10926 void cleanUpResourcesLI() { 10927 cleanUp(); 10928 } 10929 10930 boolean doPostDeleteLI(boolean delete) { 10931 // XXX err, shouldn't we respect the delete flag? 10932 cleanUpResourcesLI(); 10933 return true; 10934 } 10935 } 10936 10937 static String getAsecPackageName(String packageCid) { 10938 int idx = packageCid.lastIndexOf("-"); 10939 if (idx == -1) { 10940 return packageCid; 10941 } 10942 return packageCid.substring(0, idx); 10943 } 10944 10945 // Utility method used to create code paths based on package name and available index. 10946 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10947 String idxStr = ""; 10948 int idx = 1; 10949 // Fall back to default value of idx=1 if prefix is not 10950 // part of oldCodePath 10951 if (oldCodePath != null) { 10952 String subStr = oldCodePath; 10953 // Drop the suffix right away 10954 if (suffix != null && subStr.endsWith(suffix)) { 10955 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10956 } 10957 // If oldCodePath already contains prefix find out the 10958 // ending index to either increment or decrement. 10959 int sidx = subStr.lastIndexOf(prefix); 10960 if (sidx != -1) { 10961 subStr = subStr.substring(sidx + prefix.length()); 10962 if (subStr != null) { 10963 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10964 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10965 } 10966 try { 10967 idx = Integer.parseInt(subStr); 10968 if (idx <= 1) { 10969 idx++; 10970 } else { 10971 idx--; 10972 } 10973 } catch(NumberFormatException e) { 10974 } 10975 } 10976 } 10977 } 10978 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10979 return prefix + idxStr; 10980 } 10981 10982 private File getNextCodePath(File targetDir, String packageName) { 10983 int suffix = 1; 10984 File result; 10985 do { 10986 result = new File(targetDir, packageName + "-" + suffix); 10987 suffix++; 10988 } while (result.exists()); 10989 return result; 10990 } 10991 10992 // Utility method that returns the relative package path with respect 10993 // to the installation directory. Like say for /data/data/com.test-1.apk 10994 // string com.test-1 is returned. 10995 static String deriveCodePathName(String codePath) { 10996 if (codePath == null) { 10997 return null; 10998 } 10999 final File codeFile = new File(codePath); 11000 final String name = codeFile.getName(); 11001 if (codeFile.isDirectory()) { 11002 return name; 11003 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11004 final int lastDot = name.lastIndexOf('.'); 11005 return name.substring(0, lastDot); 11006 } else { 11007 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11008 return null; 11009 } 11010 } 11011 11012 class PackageInstalledInfo { 11013 String name; 11014 int uid; 11015 // The set of users that originally had this package installed. 11016 int[] origUsers; 11017 // The set of users that now have this package installed. 11018 int[] newUsers; 11019 PackageParser.Package pkg; 11020 int returnCode; 11021 String returnMsg; 11022 PackageRemovedInfo removedInfo; 11023 11024 public void setError(int code, String msg) { 11025 returnCode = code; 11026 returnMsg = msg; 11027 Slog.w(TAG, msg); 11028 } 11029 11030 public void setError(String msg, PackageParserException e) { 11031 returnCode = e.error; 11032 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11033 Slog.w(TAG, msg, e); 11034 } 11035 11036 public void setError(String msg, PackageManagerException e) { 11037 returnCode = e.error; 11038 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11039 Slog.w(TAG, msg, e); 11040 } 11041 11042 // In some error cases we want to convey more info back to the observer 11043 String origPackage; 11044 String origPermission; 11045 } 11046 11047 /* 11048 * Install a non-existing package. 11049 */ 11050 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11051 UserHandle user, String installerPackageName, String volumeUuid, 11052 PackageInstalledInfo res) { 11053 // Remember this for later, in case we need to rollback this install 11054 String pkgName = pkg.packageName; 11055 11056 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11057 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11058 UserHandle.USER_OWNER).exists(); 11059 synchronized(mPackages) { 11060 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11061 // A package with the same name is already installed, though 11062 // it has been renamed to an older name. The package we 11063 // are trying to install should be installed as an update to 11064 // the existing one, but that has not been requested, so bail. 11065 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11066 + " without first uninstalling package running as " 11067 + mSettings.mRenamedPackages.get(pkgName)); 11068 return; 11069 } 11070 if (mPackages.containsKey(pkgName)) { 11071 // Don't allow installation over an existing package with the same name. 11072 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11073 + " without first uninstalling."); 11074 return; 11075 } 11076 } 11077 11078 try { 11079 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11080 System.currentTimeMillis(), user); 11081 11082 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11083 // delete the partially installed application. the data directory will have to be 11084 // restored if it was already existing 11085 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11086 // remove package from internal structures. Note that we want deletePackageX to 11087 // delete the package data and cache directories that it created in 11088 // scanPackageLocked, unless those directories existed before we even tried to 11089 // install. 11090 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11091 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11092 res.removedInfo, true); 11093 } 11094 11095 } catch (PackageManagerException e) { 11096 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11097 } 11098 } 11099 11100 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11101 // Upgrade keysets are being used. Determine if new package has a superset of the 11102 // required keys. 11103 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11104 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11105 for (int i = 0; i < upgradeKeySets.length; i++) { 11106 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11107 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11108 return true; 11109 } 11110 } 11111 return false; 11112 } 11113 11114 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11115 UserHandle user, String installerPackageName, String volumeUuid, 11116 PackageInstalledInfo res) { 11117 final PackageParser.Package oldPackage; 11118 final String pkgName = pkg.packageName; 11119 final int[] allUsers; 11120 final boolean[] perUserInstalled; 11121 final boolean weFroze; 11122 11123 // First find the old package info and check signatures 11124 synchronized(mPackages) { 11125 oldPackage = mPackages.get(pkgName); 11126 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11127 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11128 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11129 // default to original signature matching 11130 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11131 != PackageManager.SIGNATURE_MATCH) { 11132 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11133 "New package has a different signature: " + pkgName); 11134 return; 11135 } 11136 } else { 11137 if(!checkUpgradeKeySetLP(ps, pkg)) { 11138 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11139 "New package not signed by keys specified by upgrade-keysets: " 11140 + pkgName); 11141 return; 11142 } 11143 } 11144 11145 // In case of rollback, remember per-user/profile install state 11146 allUsers = sUserManager.getUserIds(); 11147 perUserInstalled = new boolean[allUsers.length]; 11148 for (int i = 0; i < allUsers.length; i++) { 11149 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11150 } 11151 11152 // Mark the app as frozen to prevent launching during the upgrade 11153 // process, and then kill all running instances 11154 if (!ps.frozen) { 11155 ps.frozen = true; 11156 weFroze = true; 11157 } else { 11158 weFroze = false; 11159 } 11160 } 11161 11162 // Now that we're guarded by frozen state, kill app during upgrade 11163 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11164 11165 try { 11166 boolean sysPkg = (isSystemApp(oldPackage)); 11167 if (sysPkg) { 11168 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11169 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11170 } else { 11171 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11172 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11173 } 11174 } finally { 11175 // Regardless of success or failure of upgrade steps above, always 11176 // unfreeze the package if we froze it 11177 if (weFroze) { 11178 unfreezePackage(pkgName); 11179 } 11180 } 11181 } 11182 11183 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11184 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11185 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11186 String volumeUuid, PackageInstalledInfo res) { 11187 String pkgName = deletedPackage.packageName; 11188 boolean deletedPkg = true; 11189 boolean updatedSettings = false; 11190 11191 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11192 + deletedPackage); 11193 long origUpdateTime; 11194 if (pkg.mExtras != null) { 11195 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11196 } else { 11197 origUpdateTime = 0; 11198 } 11199 11200 // First delete the existing package while retaining the data directory 11201 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11202 res.removedInfo, true)) { 11203 // If the existing package wasn't successfully deleted 11204 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11205 deletedPkg = false; 11206 } else { 11207 // Successfully deleted the old package; proceed with replace. 11208 11209 // If deleted package lived in a container, give users a chance to 11210 // relinquish resources before killing. 11211 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11212 if (DEBUG_INSTALL) { 11213 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11214 } 11215 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11216 final ArrayList<String> pkgList = new ArrayList<String>(1); 11217 pkgList.add(deletedPackage.applicationInfo.packageName); 11218 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11219 } 11220 11221 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11222 try { 11223 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11224 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11225 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11226 perUserInstalled, res, user); 11227 updatedSettings = true; 11228 } catch (PackageManagerException e) { 11229 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11230 } 11231 } 11232 11233 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11234 // remove package from internal structures. Note that we want deletePackageX to 11235 // delete the package data and cache directories that it created in 11236 // scanPackageLocked, unless those directories existed before we even tried to 11237 // install. 11238 if(updatedSettings) { 11239 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11240 deletePackageLI( 11241 pkgName, null, true, allUsers, perUserInstalled, 11242 PackageManager.DELETE_KEEP_DATA, 11243 res.removedInfo, true); 11244 } 11245 // Since we failed to install the new package we need to restore the old 11246 // package that we deleted. 11247 if (deletedPkg) { 11248 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11249 File restoreFile = new File(deletedPackage.codePath); 11250 // Parse old package 11251 boolean oldExternal = isExternal(deletedPackage); 11252 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11253 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11254 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11255 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11256 try { 11257 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11258 } catch (PackageManagerException e) { 11259 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11260 + e.getMessage()); 11261 return; 11262 } 11263 // Restore of old package succeeded. Update permissions. 11264 // writer 11265 synchronized (mPackages) { 11266 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11267 UPDATE_PERMISSIONS_ALL); 11268 // can downgrade to reader 11269 mSettings.writeLPr(); 11270 } 11271 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11272 } 11273 } 11274 } 11275 11276 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11277 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11278 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11279 String volumeUuid, PackageInstalledInfo res) { 11280 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11281 + ", old=" + deletedPackage); 11282 boolean disabledSystem = false; 11283 boolean updatedSettings = false; 11284 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11285 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11286 != 0) { 11287 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11288 } 11289 String packageName = deletedPackage.packageName; 11290 if (packageName == null) { 11291 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11292 "Attempt to delete null packageName."); 11293 return; 11294 } 11295 PackageParser.Package oldPkg; 11296 PackageSetting oldPkgSetting; 11297 // reader 11298 synchronized (mPackages) { 11299 oldPkg = mPackages.get(packageName); 11300 oldPkgSetting = mSettings.mPackages.get(packageName); 11301 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11302 (oldPkgSetting == null)) { 11303 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11304 "Couldn't find package:" + packageName + " information"); 11305 return; 11306 } 11307 } 11308 11309 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11310 res.removedInfo.removedPackage = packageName; 11311 // Remove existing system package 11312 removePackageLI(oldPkgSetting, true); 11313 // writer 11314 synchronized (mPackages) { 11315 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11316 if (!disabledSystem && deletedPackage != null) { 11317 // We didn't need to disable the .apk as a current system package, 11318 // which means we are replacing another update that is already 11319 // installed. We need to make sure to delete the older one's .apk. 11320 res.removedInfo.args = createInstallArgsForExisting(0, 11321 deletedPackage.applicationInfo.getCodePath(), 11322 deletedPackage.applicationInfo.getResourcePath(), 11323 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11324 } else { 11325 res.removedInfo.args = null; 11326 } 11327 } 11328 11329 // Successfully disabled the old package. Now proceed with re-installation 11330 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11331 11332 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11333 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11334 11335 PackageParser.Package newPackage = null; 11336 try { 11337 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11338 if (newPackage.mExtras != null) { 11339 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11340 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11341 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11342 11343 // is the update attempting to change shared user? that isn't going to work... 11344 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11345 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11346 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11347 + " to " + newPkgSetting.sharedUser); 11348 updatedSettings = true; 11349 } 11350 } 11351 11352 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11353 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11354 perUserInstalled, res, user); 11355 updatedSettings = true; 11356 } 11357 11358 } catch (PackageManagerException e) { 11359 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11360 } 11361 11362 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11363 // Re installation failed. Restore old information 11364 // Remove new pkg information 11365 if (newPackage != null) { 11366 removeInstalledPackageLI(newPackage, true); 11367 } 11368 // Add back the old system package 11369 try { 11370 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11371 } catch (PackageManagerException e) { 11372 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11373 } 11374 // Restore the old system information in Settings 11375 synchronized (mPackages) { 11376 if (disabledSystem) { 11377 mSettings.enableSystemPackageLPw(packageName); 11378 } 11379 if (updatedSettings) { 11380 mSettings.setInstallerPackageName(packageName, 11381 oldPkgSetting.installerPackageName); 11382 } 11383 mSettings.writeLPr(); 11384 } 11385 } 11386 } 11387 11388 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11389 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11390 UserHandle user) { 11391 String pkgName = newPackage.packageName; 11392 synchronized (mPackages) { 11393 //write settings. the installStatus will be incomplete at this stage. 11394 //note that the new package setting would have already been 11395 //added to mPackages. It hasn't been persisted yet. 11396 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11397 mSettings.writeLPr(); 11398 } 11399 11400 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11401 11402 synchronized (mPackages) { 11403 updatePermissionsLPw(newPackage.packageName, newPackage, 11404 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11405 ? UPDATE_PERMISSIONS_ALL : 0)); 11406 // For system-bundled packages, we assume that installing an upgraded version 11407 // of the package implies that the user actually wants to run that new code, 11408 // so we enable the package. 11409 PackageSetting ps = mSettings.mPackages.get(pkgName); 11410 if (ps != null) { 11411 if (isSystemApp(newPackage)) { 11412 // NB: implicit assumption that system package upgrades apply to all users 11413 if (DEBUG_INSTALL) { 11414 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11415 } 11416 if (res.origUsers != null) { 11417 for (int userHandle : res.origUsers) { 11418 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11419 userHandle, installerPackageName); 11420 } 11421 } 11422 // Also convey the prior install/uninstall state 11423 if (allUsers != null && perUserInstalled != null) { 11424 for (int i = 0; i < allUsers.length; i++) { 11425 if (DEBUG_INSTALL) { 11426 Slog.d(TAG, " user " + allUsers[i] 11427 + " => " + perUserInstalled[i]); 11428 } 11429 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11430 } 11431 // these install state changes will be persisted in the 11432 // upcoming call to mSettings.writeLPr(). 11433 } 11434 } 11435 // It's implied that when a user requests installation, they want the app to be 11436 // installed and enabled. 11437 int userId = user.getIdentifier(); 11438 if (userId != UserHandle.USER_ALL) { 11439 ps.setInstalled(true, userId); 11440 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11441 } 11442 } 11443 res.name = pkgName; 11444 res.uid = newPackage.applicationInfo.uid; 11445 res.pkg = newPackage; 11446 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11447 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11448 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11449 //to update install status 11450 mSettings.writeLPr(); 11451 } 11452 } 11453 11454 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11455 final int installFlags = args.installFlags; 11456 final String installerPackageName = args.installerPackageName; 11457 final String volumeUuid = args.volumeUuid; 11458 final File tmpPackageFile = new File(args.getCodePath()); 11459 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11460 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11461 || (args.volumeUuid != null)); 11462 boolean replace = false; 11463 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11464 // Result object to be returned 11465 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11466 11467 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11468 // Retrieve PackageSettings and parse package 11469 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11470 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11471 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11472 PackageParser pp = new PackageParser(); 11473 pp.setSeparateProcesses(mSeparateProcesses); 11474 pp.setDisplayMetrics(mMetrics); 11475 11476 final PackageParser.Package pkg; 11477 try { 11478 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11479 } catch (PackageParserException e) { 11480 res.setError("Failed parse during installPackageLI", e); 11481 return; 11482 } 11483 11484 // Mark that we have an install time CPU ABI override. 11485 pkg.cpuAbiOverride = args.abiOverride; 11486 11487 String pkgName = res.name = pkg.packageName; 11488 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11489 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11490 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11491 return; 11492 } 11493 } 11494 11495 try { 11496 pp.collectCertificates(pkg, parseFlags); 11497 pp.collectManifestDigest(pkg); 11498 } catch (PackageParserException e) { 11499 res.setError("Failed collect during installPackageLI", e); 11500 return; 11501 } 11502 11503 /* If the installer passed in a manifest digest, compare it now. */ 11504 if (args.manifestDigest != null) { 11505 if (DEBUG_INSTALL) { 11506 final String parsedManifest = pkg.manifestDigest == null ? "null" 11507 : pkg.manifestDigest.toString(); 11508 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11509 + parsedManifest); 11510 } 11511 11512 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11513 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11514 return; 11515 } 11516 } else if (DEBUG_INSTALL) { 11517 final String parsedManifest = pkg.manifestDigest == null 11518 ? "null" : pkg.manifestDigest.toString(); 11519 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11520 } 11521 11522 // Get rid of all references to package scan path via parser. 11523 pp = null; 11524 String oldCodePath = null; 11525 boolean systemApp = false; 11526 synchronized (mPackages) { 11527 // Check if installing already existing package 11528 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11529 String oldName = mSettings.mRenamedPackages.get(pkgName); 11530 if (pkg.mOriginalPackages != null 11531 && pkg.mOriginalPackages.contains(oldName) 11532 && mPackages.containsKey(oldName)) { 11533 // This package is derived from an original package, 11534 // and this device has been updating from that original 11535 // name. We must continue using the original name, so 11536 // rename the new package here. 11537 pkg.setPackageName(oldName); 11538 pkgName = pkg.packageName; 11539 replace = true; 11540 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11541 + oldName + " pkgName=" + pkgName); 11542 } else if (mPackages.containsKey(pkgName)) { 11543 // This package, under its official name, already exists 11544 // on the device; we should replace it. 11545 replace = true; 11546 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11547 } 11548 11549 // Prevent apps opting out from runtime permissions 11550 if (replace) { 11551 PackageParser.Package oldPackage = mPackages.get(pkgName); 11552 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11553 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11554 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11555 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11556 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11557 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11558 + " doesn't support runtime permissions but the old" 11559 + " target SDK " + oldTargetSdk + " does."); 11560 return; 11561 } 11562 } 11563 } 11564 11565 PackageSetting ps = mSettings.mPackages.get(pkgName); 11566 if (ps != null) { 11567 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11568 11569 // Quick sanity check that we're signed correctly if updating; 11570 // we'll check this again later when scanning, but we want to 11571 // bail early here before tripping over redefined permissions. 11572 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11573 try { 11574 verifySignaturesLP(ps, pkg); 11575 } catch (PackageManagerException e) { 11576 res.setError(e.error, e.getMessage()); 11577 return; 11578 } 11579 } else { 11580 if (!checkUpgradeKeySetLP(ps, pkg)) { 11581 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11582 + pkg.packageName + " upgrade keys do not match the " 11583 + "previously installed version"); 11584 return; 11585 } 11586 } 11587 11588 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11589 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11590 systemApp = (ps.pkg.applicationInfo.flags & 11591 ApplicationInfo.FLAG_SYSTEM) != 0; 11592 } 11593 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11594 } 11595 11596 // Check whether the newly-scanned package wants to define an already-defined perm 11597 int N = pkg.permissions.size(); 11598 for (int i = N-1; i >= 0; i--) { 11599 PackageParser.Permission perm = pkg.permissions.get(i); 11600 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11601 if (bp != null) { 11602 // If the defining package is signed with our cert, it's okay. This 11603 // also includes the "updating the same package" case, of course. 11604 // "updating same package" could also involve key-rotation. 11605 final boolean sigsOk; 11606 if (!bp.sourcePackage.equals(pkg.packageName) 11607 || !(bp.packageSetting instanceof PackageSetting) 11608 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11609 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11610 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11611 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11612 } else { 11613 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11614 } 11615 if (!sigsOk) { 11616 // If the owning package is the system itself, we log but allow 11617 // install to proceed; we fail the install on all other permission 11618 // redefinitions. 11619 if (!bp.sourcePackage.equals("android")) { 11620 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11621 + pkg.packageName + " attempting to redeclare permission " 11622 + perm.info.name + " already owned by " + bp.sourcePackage); 11623 res.origPermission = perm.info.name; 11624 res.origPackage = bp.sourcePackage; 11625 return; 11626 } else { 11627 Slog.w(TAG, "Package " + pkg.packageName 11628 + " attempting to redeclare system permission " 11629 + perm.info.name + "; ignoring new declaration"); 11630 pkg.permissions.remove(i); 11631 } 11632 } 11633 } 11634 } 11635 11636 } 11637 11638 if (systemApp && onExternal) { 11639 // Disable updates to system apps on sdcard 11640 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11641 "Cannot install updates to system apps on sdcard"); 11642 return; 11643 } 11644 11645 if (args.move != null) { 11646 // We did an in-place move, so dex is ready to roll 11647 scanFlags |= SCAN_NO_DEX; 11648 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11649 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11650 scanFlags |= SCAN_NO_DEX; 11651 11652 try { 11653 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11654 true /* extract libs */); 11655 } catch (PackageManagerException pme) { 11656 Slog.e(TAG, "Error deriving application ABI", pme); 11657 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11658 return; 11659 } 11660 11661 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11662 int result = mPackageDexOptimizer 11663 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11664 false /* defer */, false /* inclDependencies */); 11665 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11666 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11667 return; 11668 } 11669 } 11670 11671 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11672 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11673 return; 11674 } 11675 11676 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11677 11678 if (replace) { 11679 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11680 installerPackageName, volumeUuid, res); 11681 } else { 11682 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11683 args.user, installerPackageName, volumeUuid, res); 11684 } 11685 synchronized (mPackages) { 11686 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11687 if (ps != null) { 11688 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11689 } 11690 } 11691 } 11692 11693 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11694 if (mIntentFilterVerifierComponent == null) { 11695 Slog.d(TAG, "No IntentFilter verification will not be done as " 11696 + "there is no IntentFilterVerifier available!"); 11697 return; 11698 } 11699 11700 final int verifierUid = getPackageUid( 11701 mIntentFilterVerifierComponent.getPackageName(), 11702 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11703 11704 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11705 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11706 msg.obj = pkg; 11707 msg.arg1 = userId; 11708 msg.arg2 = verifierUid; 11709 11710 mHandler.sendMessage(msg); 11711 } 11712 11713 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11714 PackageParser.Package pkg) { 11715 int size = pkg.activities.size(); 11716 if (size == 0) { 11717 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11718 return; 11719 } 11720 11721 final boolean hasDomainURLs = hasDomainURLs(pkg); 11722 if (!hasDomainURLs) { 11723 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11724 return; 11725 } 11726 11727 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11728 + " Activities needs verification ..."); 11729 11730 final int verificationId = mIntentFilterVerificationToken++; 11731 int count = 0; 11732 final String packageName = pkg.packageName; 11733 ArrayList<String> allHosts = new ArrayList<>(); 11734 11735 synchronized (mPackages) { 11736 for (PackageParser.Activity a : pkg.activities) { 11737 for (ActivityIntentInfo filter : a.intents) { 11738 boolean needsFilterVerification = filter.needsVerification(); 11739 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11740 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11741 mIntentFilterVerifier.addOneIntentFilterVerification( 11742 verifierUid, userId, verificationId, filter, packageName); 11743 count++; 11744 } else if (!needsFilterVerification) { 11745 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11746 if (hasValidDomains(filter)) { 11747 ArrayList<String> hosts = filter.getHostsList(); 11748 if (hosts.size() > 0) { 11749 allHosts.addAll(hosts); 11750 } else { 11751 if (allHosts.isEmpty()) { 11752 allHosts.add("*"); 11753 } 11754 } 11755 } 11756 } else { 11757 Slog.d(TAG, "Verification already done for IntentFilter:" 11758 + filter.toString()); 11759 } 11760 } 11761 } 11762 } 11763 11764 if (count > 0) { 11765 mIntentFilterVerifier.startVerifications(userId); 11766 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11767 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11768 } else { 11769 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11770 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11771 packageName, allHosts) != null) { 11772 scheduleWriteSettingsLocked(); 11773 } 11774 } 11775 } 11776 11777 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11778 final ComponentName cn = filter.activity.getComponentName(); 11779 final String packageName = cn.getPackageName(); 11780 11781 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11782 packageName); 11783 if (ivi == null) { 11784 return true; 11785 } 11786 int status = ivi.getStatus(); 11787 switch (status) { 11788 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11789 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11790 return true; 11791 11792 default: 11793 // Nothing to do 11794 return false; 11795 } 11796 } 11797 11798 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11799 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11800 || ((pkg.applicationInfo.privateFlags 11801 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11802 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11803 } 11804 11805 private static boolean isMultiArch(PackageSetting ps) { 11806 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11807 } 11808 11809 private static boolean isMultiArch(ApplicationInfo info) { 11810 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11811 } 11812 11813 private static boolean isExternal(PackageParser.Package pkg) { 11814 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11815 } 11816 11817 private static boolean isExternal(PackageSetting ps) { 11818 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11819 } 11820 11821 private static boolean isExternal(ApplicationInfo info) { 11822 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11823 } 11824 11825 private static boolean isSystemApp(PackageParser.Package pkg) { 11826 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11827 } 11828 11829 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11830 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11831 } 11832 11833 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11834 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11835 } 11836 11837 private static boolean isSystemApp(PackageSetting ps) { 11838 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11839 } 11840 11841 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11842 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11843 } 11844 11845 private int packageFlagsToInstallFlags(PackageSetting ps) { 11846 int installFlags = 0; 11847 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11848 // This existing package was an external ASEC install when we have 11849 // the external flag without a UUID 11850 installFlags |= PackageManager.INSTALL_EXTERNAL; 11851 } 11852 if (ps.isForwardLocked()) { 11853 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11854 } 11855 return installFlags; 11856 } 11857 11858 private void deleteTempPackageFiles() { 11859 final FilenameFilter filter = new FilenameFilter() { 11860 public boolean accept(File dir, String name) { 11861 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11862 } 11863 }; 11864 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11865 file.delete(); 11866 } 11867 } 11868 11869 @Override 11870 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11871 int flags) { 11872 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11873 flags); 11874 } 11875 11876 @Override 11877 public void deletePackage(final String packageName, 11878 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11879 mContext.enforceCallingOrSelfPermission( 11880 android.Manifest.permission.DELETE_PACKAGES, null); 11881 final int uid = Binder.getCallingUid(); 11882 if (UserHandle.getUserId(uid) != userId) { 11883 mContext.enforceCallingPermission( 11884 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11885 "deletePackage for user " + userId); 11886 } 11887 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11888 try { 11889 observer.onPackageDeleted(packageName, 11890 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11891 } catch (RemoteException re) { 11892 } 11893 return; 11894 } 11895 11896 boolean uninstallBlocked = false; 11897 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11898 int[] users = sUserManager.getUserIds(); 11899 for (int i = 0; i < users.length; ++i) { 11900 if (getBlockUninstallForUser(packageName, users[i])) { 11901 uninstallBlocked = true; 11902 break; 11903 } 11904 } 11905 } else { 11906 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11907 } 11908 if (uninstallBlocked) { 11909 try { 11910 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11911 null); 11912 } catch (RemoteException re) { 11913 } 11914 return; 11915 } 11916 11917 if (DEBUG_REMOVE) { 11918 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11919 } 11920 // Queue up an async operation since the package deletion may take a little while. 11921 mHandler.post(new Runnable() { 11922 public void run() { 11923 mHandler.removeCallbacks(this); 11924 final int returnCode = deletePackageX(packageName, userId, flags); 11925 if (observer != null) { 11926 try { 11927 observer.onPackageDeleted(packageName, returnCode, null); 11928 } catch (RemoteException e) { 11929 Log.i(TAG, "Observer no longer exists."); 11930 } //end catch 11931 } //end if 11932 } //end run 11933 }); 11934 } 11935 11936 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11937 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11938 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11939 try { 11940 if (dpm != null) { 11941 if (dpm.isDeviceOwner(packageName)) { 11942 return true; 11943 } 11944 int[] users; 11945 if (userId == UserHandle.USER_ALL) { 11946 users = sUserManager.getUserIds(); 11947 } else { 11948 users = new int[]{userId}; 11949 } 11950 for (int i = 0; i < users.length; ++i) { 11951 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11952 return true; 11953 } 11954 } 11955 } 11956 } catch (RemoteException e) { 11957 } 11958 return false; 11959 } 11960 11961 /** 11962 * This method is an internal method that could be get invoked either 11963 * to delete an installed package or to clean up a failed installation. 11964 * After deleting an installed package, a broadcast is sent to notify any 11965 * listeners that the package has been installed. For cleaning up a failed 11966 * installation, the broadcast is not necessary since the package's 11967 * installation wouldn't have sent the initial broadcast either 11968 * The key steps in deleting a package are 11969 * deleting the package information in internal structures like mPackages, 11970 * deleting the packages base directories through installd 11971 * updating mSettings to reflect current status 11972 * persisting settings for later use 11973 * sending a broadcast if necessary 11974 */ 11975 private int deletePackageX(String packageName, int userId, int flags) { 11976 final PackageRemovedInfo info = new PackageRemovedInfo(); 11977 final boolean res; 11978 11979 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11980 ? UserHandle.ALL : new UserHandle(userId); 11981 11982 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11983 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11984 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11985 } 11986 11987 boolean removedForAllUsers = false; 11988 boolean systemUpdate = false; 11989 11990 // for the uninstall-updates case and restricted profiles, remember the per- 11991 // userhandle installed state 11992 int[] allUsers; 11993 boolean[] perUserInstalled; 11994 synchronized (mPackages) { 11995 PackageSetting ps = mSettings.mPackages.get(packageName); 11996 allUsers = sUserManager.getUserIds(); 11997 perUserInstalled = new boolean[allUsers.length]; 11998 for (int i = 0; i < allUsers.length; i++) { 11999 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12000 } 12001 } 12002 12003 synchronized (mInstallLock) { 12004 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12005 res = deletePackageLI(packageName, removeForUser, 12006 true, allUsers, perUserInstalled, 12007 flags | REMOVE_CHATTY, info, true); 12008 systemUpdate = info.isRemovedPackageSystemUpdate; 12009 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12010 removedForAllUsers = true; 12011 } 12012 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12013 + " removedForAllUsers=" + removedForAllUsers); 12014 } 12015 12016 if (res) { 12017 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12018 12019 // If the removed package was a system update, the old system package 12020 // was re-enabled; we need to broadcast this information 12021 if (systemUpdate) { 12022 Bundle extras = new Bundle(1); 12023 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12024 ? info.removedAppId : info.uid); 12025 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12026 12027 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12028 extras, null, null, null); 12029 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12030 extras, null, null, null); 12031 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12032 null, packageName, null, null); 12033 } 12034 } 12035 // Force a gc here. 12036 Runtime.getRuntime().gc(); 12037 // Delete the resources here after sending the broadcast to let 12038 // other processes clean up before deleting resources. 12039 if (info.args != null) { 12040 synchronized (mInstallLock) { 12041 info.args.doPostDeleteLI(true); 12042 } 12043 } 12044 12045 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12046 } 12047 12048 class PackageRemovedInfo { 12049 String removedPackage; 12050 int uid = -1; 12051 int removedAppId = -1; 12052 int[] removedUsers = null; 12053 boolean isRemovedPackageSystemUpdate = false; 12054 // Clean up resources deleted packages. 12055 InstallArgs args = null; 12056 12057 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12058 Bundle extras = new Bundle(1); 12059 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12060 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12061 if (replacing) { 12062 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12063 } 12064 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12065 if (removedPackage != null) { 12066 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12067 extras, null, null, removedUsers); 12068 if (fullRemove && !replacing) { 12069 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12070 extras, null, null, removedUsers); 12071 } 12072 } 12073 if (removedAppId >= 0) { 12074 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12075 removedUsers); 12076 } 12077 } 12078 } 12079 12080 /* 12081 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12082 * flag is not set, the data directory is removed as well. 12083 * make sure this flag is set for partially installed apps. If not its meaningless to 12084 * delete a partially installed application. 12085 */ 12086 private void removePackageDataLI(PackageSetting ps, 12087 int[] allUserHandles, boolean[] perUserInstalled, 12088 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12089 String packageName = ps.name; 12090 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12091 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12092 // Retrieve object to delete permissions for shared user later on 12093 final PackageSetting deletedPs; 12094 // reader 12095 synchronized (mPackages) { 12096 deletedPs = mSettings.mPackages.get(packageName); 12097 if (outInfo != null) { 12098 outInfo.removedPackage = packageName; 12099 outInfo.removedUsers = deletedPs != null 12100 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12101 : null; 12102 } 12103 } 12104 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12105 removeDataDirsLI(ps.volumeUuid, packageName); 12106 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12107 } 12108 // writer 12109 synchronized (mPackages) { 12110 if (deletedPs != null) { 12111 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12112 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12113 clearDefaultBrowserIfNeeded(packageName); 12114 if (outInfo != null) { 12115 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12116 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12117 } 12118 updatePermissionsLPw(deletedPs.name, null, 0); 12119 if (deletedPs.sharedUser != null) { 12120 // Remove permissions associated with package. Since runtime 12121 // permissions are per user we have to kill the removed package 12122 // or packages running under the shared user of the removed 12123 // package if revoking the permissions requested only by the removed 12124 // package is successful and this causes a change in gids. 12125 for (int userId : UserManagerService.getInstance().getUserIds()) { 12126 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12127 userId); 12128 if (userIdToKill == UserHandle.USER_ALL 12129 || userIdToKill >= UserHandle.USER_OWNER) { 12130 // If gids changed for this user, kill all affected packages. 12131 mHandler.post(new Runnable() { 12132 @Override 12133 public void run() { 12134 // This has to happen with no lock held. 12135 killSettingPackagesForUser(deletedPs, userIdToKill, 12136 KILL_APP_REASON_GIDS_CHANGED); 12137 } 12138 }); 12139 break; 12140 } 12141 } 12142 } 12143 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12144 } 12145 // make sure to preserve per-user disabled state if this removal was just 12146 // a downgrade of a system app to the factory package 12147 if (allUserHandles != null && perUserInstalled != null) { 12148 if (DEBUG_REMOVE) { 12149 Slog.d(TAG, "Propagating install state across downgrade"); 12150 } 12151 for (int i = 0; i < allUserHandles.length; i++) { 12152 if (DEBUG_REMOVE) { 12153 Slog.d(TAG, " user " + allUserHandles[i] 12154 + " => " + perUserInstalled[i]); 12155 } 12156 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12157 } 12158 } 12159 } 12160 // can downgrade to reader 12161 if (writeSettings) { 12162 // Save settings now 12163 mSettings.writeLPr(); 12164 } 12165 } 12166 if (outInfo != null) { 12167 // A user ID was deleted here. Go through all users and remove it 12168 // from KeyStore. 12169 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12170 } 12171 } 12172 12173 static boolean locationIsPrivileged(File path) { 12174 try { 12175 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12176 .getCanonicalPath(); 12177 return path.getCanonicalPath().startsWith(privilegedAppDir); 12178 } catch (IOException e) { 12179 Slog.e(TAG, "Unable to access code path " + path); 12180 } 12181 return false; 12182 } 12183 12184 /* 12185 * Tries to delete system package. 12186 */ 12187 private boolean deleteSystemPackageLI(PackageSetting newPs, 12188 int[] allUserHandles, boolean[] perUserInstalled, 12189 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12190 final boolean applyUserRestrictions 12191 = (allUserHandles != null) && (perUserInstalled != null); 12192 PackageSetting disabledPs = null; 12193 // Confirm if the system package has been updated 12194 // An updated system app can be deleted. This will also have to restore 12195 // the system pkg from system partition 12196 // reader 12197 synchronized (mPackages) { 12198 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12199 } 12200 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12201 + " disabledPs=" + disabledPs); 12202 if (disabledPs == null) { 12203 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12204 return false; 12205 } else if (DEBUG_REMOVE) { 12206 Slog.d(TAG, "Deleting system pkg from data partition"); 12207 } 12208 if (DEBUG_REMOVE) { 12209 if (applyUserRestrictions) { 12210 Slog.d(TAG, "Remembering install states:"); 12211 for (int i = 0; i < allUserHandles.length; i++) { 12212 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12213 } 12214 } 12215 } 12216 // Delete the updated package 12217 outInfo.isRemovedPackageSystemUpdate = true; 12218 if (disabledPs.versionCode < newPs.versionCode) { 12219 // Delete data for downgrades 12220 flags &= ~PackageManager.DELETE_KEEP_DATA; 12221 } else { 12222 // Preserve data by setting flag 12223 flags |= PackageManager.DELETE_KEEP_DATA; 12224 } 12225 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12226 allUserHandles, perUserInstalled, outInfo, writeSettings); 12227 if (!ret) { 12228 return false; 12229 } 12230 // writer 12231 synchronized (mPackages) { 12232 // Reinstate the old system package 12233 mSettings.enableSystemPackageLPw(newPs.name); 12234 // Remove any native libraries from the upgraded package. 12235 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12236 } 12237 // Install the system package 12238 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12239 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12240 if (locationIsPrivileged(disabledPs.codePath)) { 12241 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12242 } 12243 12244 final PackageParser.Package newPkg; 12245 try { 12246 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12247 } catch (PackageManagerException e) { 12248 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12249 return false; 12250 } 12251 12252 // writer 12253 synchronized (mPackages) { 12254 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12255 updatePermissionsLPw(newPkg.packageName, newPkg, 12256 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12257 if (applyUserRestrictions) { 12258 if (DEBUG_REMOVE) { 12259 Slog.d(TAG, "Propagating install state across reinstall"); 12260 } 12261 for (int i = 0; i < allUserHandles.length; i++) { 12262 if (DEBUG_REMOVE) { 12263 Slog.d(TAG, " user " + allUserHandles[i] 12264 + " => " + perUserInstalled[i]); 12265 } 12266 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12267 } 12268 // Regardless of writeSettings we need to ensure that this restriction 12269 // state propagation is persisted 12270 mSettings.writeAllUsersPackageRestrictionsLPr(); 12271 } 12272 // can downgrade to reader here 12273 if (writeSettings) { 12274 mSettings.writeLPr(); 12275 } 12276 } 12277 return true; 12278 } 12279 12280 private boolean deleteInstalledPackageLI(PackageSetting ps, 12281 boolean deleteCodeAndResources, int flags, 12282 int[] allUserHandles, boolean[] perUserInstalled, 12283 PackageRemovedInfo outInfo, boolean writeSettings) { 12284 if (outInfo != null) { 12285 outInfo.uid = ps.appId; 12286 } 12287 12288 // Delete package data from internal structures and also remove data if flag is set 12289 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12290 12291 // Delete application code and resources 12292 if (deleteCodeAndResources && (outInfo != null)) { 12293 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12294 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12295 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12296 } 12297 return true; 12298 } 12299 12300 @Override 12301 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12302 int userId) { 12303 mContext.enforceCallingOrSelfPermission( 12304 android.Manifest.permission.DELETE_PACKAGES, null); 12305 synchronized (mPackages) { 12306 PackageSetting ps = mSettings.mPackages.get(packageName); 12307 if (ps == null) { 12308 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12309 return false; 12310 } 12311 if (!ps.getInstalled(userId)) { 12312 // Can't block uninstall for an app that is not installed or enabled. 12313 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12314 return false; 12315 } 12316 ps.setBlockUninstall(blockUninstall, userId); 12317 mSettings.writePackageRestrictionsLPr(userId); 12318 } 12319 return true; 12320 } 12321 12322 @Override 12323 public boolean getBlockUninstallForUser(String packageName, int userId) { 12324 synchronized (mPackages) { 12325 PackageSetting ps = mSettings.mPackages.get(packageName); 12326 if (ps == null) { 12327 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12328 return false; 12329 } 12330 return ps.getBlockUninstall(userId); 12331 } 12332 } 12333 12334 /* 12335 * This method handles package deletion in general 12336 */ 12337 private boolean deletePackageLI(String packageName, UserHandle user, 12338 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12339 int flags, PackageRemovedInfo outInfo, 12340 boolean writeSettings) { 12341 if (packageName == null) { 12342 Slog.w(TAG, "Attempt to delete null packageName."); 12343 return false; 12344 } 12345 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12346 PackageSetting ps; 12347 boolean dataOnly = false; 12348 int removeUser = -1; 12349 int appId = -1; 12350 synchronized (mPackages) { 12351 ps = mSettings.mPackages.get(packageName); 12352 if (ps == null) { 12353 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12354 return false; 12355 } 12356 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12357 && user.getIdentifier() != UserHandle.USER_ALL) { 12358 // The caller is asking that the package only be deleted for a single 12359 // user. To do this, we just mark its uninstalled state and delete 12360 // its data. If this is a system app, we only allow this to happen if 12361 // they have set the special DELETE_SYSTEM_APP which requests different 12362 // semantics than normal for uninstalling system apps. 12363 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12364 ps.setUserState(user.getIdentifier(), 12365 COMPONENT_ENABLED_STATE_DEFAULT, 12366 false, //installed 12367 true, //stopped 12368 true, //notLaunched 12369 false, //hidden 12370 null, null, null, 12371 false, // blockUninstall 12372 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12373 if (!isSystemApp(ps)) { 12374 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12375 // Other user still have this package installed, so all 12376 // we need to do is clear this user's data and save that 12377 // it is uninstalled. 12378 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12379 removeUser = user.getIdentifier(); 12380 appId = ps.appId; 12381 scheduleWritePackageRestrictionsLocked(removeUser); 12382 } else { 12383 // We need to set it back to 'installed' so the uninstall 12384 // broadcasts will be sent correctly. 12385 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12386 ps.setInstalled(true, user.getIdentifier()); 12387 } 12388 } else { 12389 // This is a system app, so we assume that the 12390 // other users still have this package installed, so all 12391 // we need to do is clear this user's data and save that 12392 // it is uninstalled. 12393 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12394 removeUser = user.getIdentifier(); 12395 appId = ps.appId; 12396 scheduleWritePackageRestrictionsLocked(removeUser); 12397 } 12398 } 12399 } 12400 12401 if (removeUser >= 0) { 12402 // From above, we determined that we are deleting this only 12403 // for a single user. Continue the work here. 12404 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12405 if (outInfo != null) { 12406 outInfo.removedPackage = packageName; 12407 outInfo.removedAppId = appId; 12408 outInfo.removedUsers = new int[] {removeUser}; 12409 } 12410 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12411 removeKeystoreDataIfNeeded(removeUser, appId); 12412 schedulePackageCleaning(packageName, removeUser, false); 12413 synchronized (mPackages) { 12414 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12415 scheduleWritePackageRestrictionsLocked(removeUser); 12416 } 12417 } 12418 return true; 12419 } 12420 12421 if (dataOnly) { 12422 // Delete application data first 12423 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12424 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12425 return true; 12426 } 12427 12428 boolean ret = false; 12429 if (isSystemApp(ps)) { 12430 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12431 // When an updated system application is deleted we delete the existing resources as well and 12432 // fall back to existing code in system partition 12433 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12434 flags, outInfo, writeSettings); 12435 } else { 12436 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12437 // Kill application pre-emptively especially for apps on sd. 12438 killApplication(packageName, ps.appId, "uninstall pkg"); 12439 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12440 allUserHandles, perUserInstalled, 12441 outInfo, writeSettings); 12442 } 12443 12444 return ret; 12445 } 12446 12447 private final class ClearStorageConnection implements ServiceConnection { 12448 IMediaContainerService mContainerService; 12449 12450 @Override 12451 public void onServiceConnected(ComponentName name, IBinder service) { 12452 synchronized (this) { 12453 mContainerService = IMediaContainerService.Stub.asInterface(service); 12454 notifyAll(); 12455 } 12456 } 12457 12458 @Override 12459 public void onServiceDisconnected(ComponentName name) { 12460 } 12461 } 12462 12463 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12464 final boolean mounted; 12465 if (Environment.isExternalStorageEmulated()) { 12466 mounted = true; 12467 } else { 12468 final String status = Environment.getExternalStorageState(); 12469 12470 mounted = status.equals(Environment.MEDIA_MOUNTED) 12471 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12472 } 12473 12474 if (!mounted) { 12475 return; 12476 } 12477 12478 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12479 int[] users; 12480 if (userId == UserHandle.USER_ALL) { 12481 users = sUserManager.getUserIds(); 12482 } else { 12483 users = new int[] { userId }; 12484 } 12485 final ClearStorageConnection conn = new ClearStorageConnection(); 12486 if (mContext.bindServiceAsUser( 12487 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12488 try { 12489 for (int curUser : users) { 12490 long timeout = SystemClock.uptimeMillis() + 5000; 12491 synchronized (conn) { 12492 long now = SystemClock.uptimeMillis(); 12493 while (conn.mContainerService == null && now < timeout) { 12494 try { 12495 conn.wait(timeout - now); 12496 } catch (InterruptedException e) { 12497 } 12498 } 12499 } 12500 if (conn.mContainerService == null) { 12501 return; 12502 } 12503 12504 final UserEnvironment userEnv = new UserEnvironment(curUser); 12505 clearDirectory(conn.mContainerService, 12506 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12507 if (allData) { 12508 clearDirectory(conn.mContainerService, 12509 userEnv.buildExternalStorageAppDataDirs(packageName)); 12510 clearDirectory(conn.mContainerService, 12511 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12512 } 12513 } 12514 } finally { 12515 mContext.unbindService(conn); 12516 } 12517 } 12518 } 12519 12520 @Override 12521 public void clearApplicationUserData(final String packageName, 12522 final IPackageDataObserver observer, final int userId) { 12523 mContext.enforceCallingOrSelfPermission( 12524 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12525 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12526 // Queue up an async operation since the package deletion may take a little while. 12527 mHandler.post(new Runnable() { 12528 public void run() { 12529 mHandler.removeCallbacks(this); 12530 final boolean succeeded; 12531 synchronized (mInstallLock) { 12532 succeeded = clearApplicationUserDataLI(packageName, userId); 12533 } 12534 clearExternalStorageDataSync(packageName, userId, true); 12535 if (succeeded) { 12536 // invoke DeviceStorageMonitor's update method to clear any notifications 12537 DeviceStorageMonitorInternal 12538 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12539 if (dsm != null) { 12540 dsm.checkMemory(); 12541 } 12542 } 12543 if(observer != null) { 12544 try { 12545 observer.onRemoveCompleted(packageName, succeeded); 12546 } catch (RemoteException e) { 12547 Log.i(TAG, "Observer no longer exists."); 12548 } 12549 } //end if observer 12550 } //end run 12551 }); 12552 } 12553 12554 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12555 if (packageName == null) { 12556 Slog.w(TAG, "Attempt to delete null packageName."); 12557 return false; 12558 } 12559 12560 // Try finding details about the requested package 12561 PackageParser.Package pkg; 12562 synchronized (mPackages) { 12563 pkg = mPackages.get(packageName); 12564 if (pkg == null) { 12565 final PackageSetting ps = mSettings.mPackages.get(packageName); 12566 if (ps != null) { 12567 pkg = ps.pkg; 12568 } 12569 } 12570 } 12571 12572 if (pkg == null) { 12573 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12574 } 12575 12576 // Always delete data directories for package, even if we found no other 12577 // record of app. This helps users recover from UID mismatches without 12578 // resorting to a full data wipe. 12579 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12580 if (retCode < 0) { 12581 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12582 return false; 12583 } 12584 12585 if (pkg == null) { 12586 return false; 12587 } 12588 12589 if (pkg != null && pkg.applicationInfo != null) { 12590 final int appId = pkg.applicationInfo.uid; 12591 removeKeystoreDataIfNeeded(userId, appId); 12592 } 12593 12594 // Create a native library symlink only if we have native libraries 12595 // and if the native libraries are 32 bit libraries. We do not provide 12596 // this symlink for 64 bit libraries. 12597 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12598 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12599 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12600 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12601 nativeLibPath, userId) < 0) { 12602 Slog.w(TAG, "Failed linking native library dir"); 12603 return false; 12604 } 12605 } 12606 12607 return true; 12608 } 12609 12610 /** 12611 * Remove entries from the keystore daemon. Will only remove it if the 12612 * {@code appId} is valid. 12613 */ 12614 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12615 if (appId < 0) { 12616 return; 12617 } 12618 12619 final KeyStore keyStore = KeyStore.getInstance(); 12620 if (keyStore != null) { 12621 if (userId == UserHandle.USER_ALL) { 12622 for (final int individual : sUserManager.getUserIds()) { 12623 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12624 } 12625 } else { 12626 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12627 } 12628 } else { 12629 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12630 } 12631 } 12632 12633 @Override 12634 public void deleteApplicationCacheFiles(final String packageName, 12635 final IPackageDataObserver observer) { 12636 mContext.enforceCallingOrSelfPermission( 12637 android.Manifest.permission.DELETE_CACHE_FILES, null); 12638 // Queue up an async operation since the package deletion may take a little while. 12639 final int userId = UserHandle.getCallingUserId(); 12640 mHandler.post(new Runnable() { 12641 public void run() { 12642 mHandler.removeCallbacks(this); 12643 final boolean succeded; 12644 synchronized (mInstallLock) { 12645 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12646 } 12647 clearExternalStorageDataSync(packageName, userId, false); 12648 if (observer != null) { 12649 try { 12650 observer.onRemoveCompleted(packageName, succeded); 12651 } catch (RemoteException e) { 12652 Log.i(TAG, "Observer no longer exists."); 12653 } 12654 } //end if observer 12655 } //end run 12656 }); 12657 } 12658 12659 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12660 if (packageName == null) { 12661 Slog.w(TAG, "Attempt to delete null packageName."); 12662 return false; 12663 } 12664 PackageParser.Package p; 12665 synchronized (mPackages) { 12666 p = mPackages.get(packageName); 12667 } 12668 if (p == null) { 12669 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12670 return false; 12671 } 12672 final ApplicationInfo applicationInfo = p.applicationInfo; 12673 if (applicationInfo == null) { 12674 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12675 return false; 12676 } 12677 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12678 if (retCode < 0) { 12679 Slog.w(TAG, "Couldn't remove cache files for package: " 12680 + packageName + " u" + userId); 12681 return false; 12682 } 12683 return true; 12684 } 12685 12686 @Override 12687 public void getPackageSizeInfo(final String packageName, int userHandle, 12688 final IPackageStatsObserver observer) { 12689 mContext.enforceCallingOrSelfPermission( 12690 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12691 if (packageName == null) { 12692 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12693 } 12694 12695 PackageStats stats = new PackageStats(packageName, userHandle); 12696 12697 /* 12698 * Queue up an async operation since the package measurement may take a 12699 * little while. 12700 */ 12701 Message msg = mHandler.obtainMessage(INIT_COPY); 12702 msg.obj = new MeasureParams(stats, observer); 12703 mHandler.sendMessage(msg); 12704 } 12705 12706 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12707 PackageStats pStats) { 12708 if (packageName == null) { 12709 Slog.w(TAG, "Attempt to get size of null packageName."); 12710 return false; 12711 } 12712 PackageParser.Package p; 12713 boolean dataOnly = false; 12714 String libDirRoot = null; 12715 String asecPath = null; 12716 PackageSetting ps = null; 12717 synchronized (mPackages) { 12718 p = mPackages.get(packageName); 12719 ps = mSettings.mPackages.get(packageName); 12720 if(p == null) { 12721 dataOnly = true; 12722 if((ps == null) || (ps.pkg == null)) { 12723 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12724 return false; 12725 } 12726 p = ps.pkg; 12727 } 12728 if (ps != null) { 12729 libDirRoot = ps.legacyNativeLibraryPathString; 12730 } 12731 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12732 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12733 if (secureContainerId != null) { 12734 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12735 } 12736 } 12737 } 12738 String publicSrcDir = null; 12739 if(!dataOnly) { 12740 final ApplicationInfo applicationInfo = p.applicationInfo; 12741 if (applicationInfo == null) { 12742 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12743 return false; 12744 } 12745 if (p.isForwardLocked()) { 12746 publicSrcDir = applicationInfo.getBaseResourcePath(); 12747 } 12748 } 12749 // TODO: extend to measure size of split APKs 12750 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12751 // not just the first level. 12752 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12753 // just the primary. 12754 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12755 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12756 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12757 if (res < 0) { 12758 return false; 12759 } 12760 12761 // Fix-up for forward-locked applications in ASEC containers. 12762 if (!isExternal(p)) { 12763 pStats.codeSize += pStats.externalCodeSize; 12764 pStats.externalCodeSize = 0L; 12765 } 12766 12767 return true; 12768 } 12769 12770 12771 @Override 12772 public void addPackageToPreferred(String packageName) { 12773 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12774 } 12775 12776 @Override 12777 public void removePackageFromPreferred(String packageName) { 12778 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12779 } 12780 12781 @Override 12782 public List<PackageInfo> getPreferredPackages(int flags) { 12783 return new ArrayList<PackageInfo>(); 12784 } 12785 12786 private int getUidTargetSdkVersionLockedLPr(int uid) { 12787 Object obj = mSettings.getUserIdLPr(uid); 12788 if (obj instanceof SharedUserSetting) { 12789 final SharedUserSetting sus = (SharedUserSetting) obj; 12790 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12791 final Iterator<PackageSetting> it = sus.packages.iterator(); 12792 while (it.hasNext()) { 12793 final PackageSetting ps = it.next(); 12794 if (ps.pkg != null) { 12795 int v = ps.pkg.applicationInfo.targetSdkVersion; 12796 if (v < vers) vers = v; 12797 } 12798 } 12799 return vers; 12800 } else if (obj instanceof PackageSetting) { 12801 final PackageSetting ps = (PackageSetting) obj; 12802 if (ps.pkg != null) { 12803 return ps.pkg.applicationInfo.targetSdkVersion; 12804 } 12805 } 12806 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12807 } 12808 12809 @Override 12810 public void addPreferredActivity(IntentFilter filter, int match, 12811 ComponentName[] set, ComponentName activity, int userId) { 12812 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12813 "Adding preferred"); 12814 } 12815 12816 private void addPreferredActivityInternal(IntentFilter filter, int match, 12817 ComponentName[] set, ComponentName activity, boolean always, int userId, 12818 String opname) { 12819 // writer 12820 int callingUid = Binder.getCallingUid(); 12821 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12822 if (filter.countActions() == 0) { 12823 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12824 return; 12825 } 12826 synchronized (mPackages) { 12827 if (mContext.checkCallingOrSelfPermission( 12828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12829 != PackageManager.PERMISSION_GRANTED) { 12830 if (getUidTargetSdkVersionLockedLPr(callingUid) 12831 < Build.VERSION_CODES.FROYO) { 12832 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12833 + callingUid); 12834 return; 12835 } 12836 mContext.enforceCallingOrSelfPermission( 12837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12838 } 12839 12840 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12841 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12842 + userId + ":"); 12843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12844 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12845 scheduleWritePackageRestrictionsLocked(userId); 12846 } 12847 } 12848 12849 @Override 12850 public void replacePreferredActivity(IntentFilter filter, int match, 12851 ComponentName[] set, ComponentName activity, int userId) { 12852 if (filter.countActions() != 1) { 12853 throw new IllegalArgumentException( 12854 "replacePreferredActivity expects filter to have only 1 action."); 12855 } 12856 if (filter.countDataAuthorities() != 0 12857 || filter.countDataPaths() != 0 12858 || filter.countDataSchemes() > 1 12859 || filter.countDataTypes() != 0) { 12860 throw new IllegalArgumentException( 12861 "replacePreferredActivity expects filter to have no data authorities, " + 12862 "paths, or types; and at most one scheme."); 12863 } 12864 12865 final int callingUid = Binder.getCallingUid(); 12866 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12867 synchronized (mPackages) { 12868 if (mContext.checkCallingOrSelfPermission( 12869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12870 != PackageManager.PERMISSION_GRANTED) { 12871 if (getUidTargetSdkVersionLockedLPr(callingUid) 12872 < Build.VERSION_CODES.FROYO) { 12873 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12874 + Binder.getCallingUid()); 12875 return; 12876 } 12877 mContext.enforceCallingOrSelfPermission( 12878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12879 } 12880 12881 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12882 if (pir != null) { 12883 // Get all of the existing entries that exactly match this filter. 12884 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12885 if (existing != null && existing.size() == 1) { 12886 PreferredActivity cur = existing.get(0); 12887 if (DEBUG_PREFERRED) { 12888 Slog.i(TAG, "Checking replace of preferred:"); 12889 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12890 if (!cur.mPref.mAlways) { 12891 Slog.i(TAG, " -- CUR; not mAlways!"); 12892 } else { 12893 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12894 Slog.i(TAG, " -- CUR: mSet=" 12895 + Arrays.toString(cur.mPref.mSetComponents)); 12896 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12897 Slog.i(TAG, " -- NEW: mMatch=" 12898 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12899 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12900 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12901 } 12902 } 12903 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12904 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12905 && cur.mPref.sameSet(set)) { 12906 // Setting the preferred activity to what it happens to be already 12907 if (DEBUG_PREFERRED) { 12908 Slog.i(TAG, "Replacing with same preferred activity " 12909 + cur.mPref.mShortComponent + " for user " 12910 + userId + ":"); 12911 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12912 } 12913 return; 12914 } 12915 } 12916 12917 if (existing != null) { 12918 if (DEBUG_PREFERRED) { 12919 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12920 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12921 } 12922 for (int i = 0; i < existing.size(); i++) { 12923 PreferredActivity pa = existing.get(i); 12924 if (DEBUG_PREFERRED) { 12925 Slog.i(TAG, "Removing existing preferred activity " 12926 + pa.mPref.mComponent + ":"); 12927 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12928 } 12929 pir.removeFilter(pa); 12930 } 12931 } 12932 } 12933 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12934 "Replacing preferred"); 12935 } 12936 } 12937 12938 @Override 12939 public void clearPackagePreferredActivities(String packageName) { 12940 final int uid = Binder.getCallingUid(); 12941 // writer 12942 synchronized (mPackages) { 12943 PackageParser.Package pkg = mPackages.get(packageName); 12944 if (pkg == null || pkg.applicationInfo.uid != uid) { 12945 if (mContext.checkCallingOrSelfPermission( 12946 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12947 != PackageManager.PERMISSION_GRANTED) { 12948 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12949 < Build.VERSION_CODES.FROYO) { 12950 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12951 + Binder.getCallingUid()); 12952 return; 12953 } 12954 mContext.enforceCallingOrSelfPermission( 12955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12956 } 12957 } 12958 12959 int user = UserHandle.getCallingUserId(); 12960 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12961 scheduleWritePackageRestrictionsLocked(user); 12962 } 12963 } 12964 } 12965 12966 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12967 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12968 ArrayList<PreferredActivity> removed = null; 12969 boolean changed = false; 12970 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12971 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12972 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12973 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12974 continue; 12975 } 12976 Iterator<PreferredActivity> it = pir.filterIterator(); 12977 while (it.hasNext()) { 12978 PreferredActivity pa = it.next(); 12979 // Mark entry for removal only if it matches the package name 12980 // and the entry is of type "always". 12981 if (packageName == null || 12982 (pa.mPref.mComponent.getPackageName().equals(packageName) 12983 && pa.mPref.mAlways)) { 12984 if (removed == null) { 12985 removed = new ArrayList<PreferredActivity>(); 12986 } 12987 removed.add(pa); 12988 } 12989 } 12990 if (removed != null) { 12991 for (int j=0; j<removed.size(); j++) { 12992 PreferredActivity pa = removed.get(j); 12993 pir.removeFilter(pa); 12994 } 12995 changed = true; 12996 } 12997 } 12998 return changed; 12999 } 13000 13001 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13002 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13003 if (userId == UserHandle.USER_ALL) { 13004 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13005 sUserManager.getUserIds())) { 13006 for (int oneUserId : sUserManager.getUserIds()) { 13007 scheduleWritePackageRestrictionsLocked(oneUserId); 13008 } 13009 } 13010 } else { 13011 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13012 scheduleWritePackageRestrictionsLocked(userId); 13013 } 13014 } 13015 } 13016 13017 13018 void clearDefaultBrowserIfNeeded(String packageName) { 13019 for (int oneUserId : sUserManager.getUserIds()) { 13020 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13021 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13022 if (packageName.equals(defaultBrowserPackageName)) { 13023 setDefaultBrowserPackageName(null, oneUserId); 13024 } 13025 } 13026 } 13027 13028 @Override 13029 public void resetPreferredActivities(int userId) { 13030 /* TODO: Actually use userId. Why is it being passed in? */ 13031 mContext.enforceCallingOrSelfPermission( 13032 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13033 // writer 13034 synchronized (mPackages) { 13035 int user = UserHandle.getCallingUserId(); 13036 clearPackagePreferredActivitiesLPw(null, user); 13037 mSettings.readDefaultPreferredAppsLPw(this, user); 13038 scheduleWritePackageRestrictionsLocked(user); 13039 } 13040 } 13041 13042 @Override 13043 public int getPreferredActivities(List<IntentFilter> outFilters, 13044 List<ComponentName> outActivities, String packageName) { 13045 13046 int num = 0; 13047 final int userId = UserHandle.getCallingUserId(); 13048 // reader 13049 synchronized (mPackages) { 13050 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13051 if (pir != null) { 13052 final Iterator<PreferredActivity> it = pir.filterIterator(); 13053 while (it.hasNext()) { 13054 final PreferredActivity pa = it.next(); 13055 if (packageName == null 13056 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13057 && pa.mPref.mAlways)) { 13058 if (outFilters != null) { 13059 outFilters.add(new IntentFilter(pa)); 13060 } 13061 if (outActivities != null) { 13062 outActivities.add(pa.mPref.mComponent); 13063 } 13064 } 13065 } 13066 } 13067 } 13068 13069 return num; 13070 } 13071 13072 @Override 13073 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13074 int userId) { 13075 int callingUid = Binder.getCallingUid(); 13076 if (callingUid != Process.SYSTEM_UID) { 13077 throw new SecurityException( 13078 "addPersistentPreferredActivity can only be run by the system"); 13079 } 13080 if (filter.countActions() == 0) { 13081 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13082 return; 13083 } 13084 synchronized (mPackages) { 13085 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13086 " :"); 13087 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13088 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13089 new PersistentPreferredActivity(filter, activity)); 13090 scheduleWritePackageRestrictionsLocked(userId); 13091 } 13092 } 13093 13094 @Override 13095 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13096 int callingUid = Binder.getCallingUid(); 13097 if (callingUid != Process.SYSTEM_UID) { 13098 throw new SecurityException( 13099 "clearPackagePersistentPreferredActivities can only be run by the system"); 13100 } 13101 ArrayList<PersistentPreferredActivity> removed = null; 13102 boolean changed = false; 13103 synchronized (mPackages) { 13104 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13105 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13106 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13107 .valueAt(i); 13108 if (userId != thisUserId) { 13109 continue; 13110 } 13111 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13112 while (it.hasNext()) { 13113 PersistentPreferredActivity ppa = it.next(); 13114 // Mark entry for removal only if it matches the package name. 13115 if (ppa.mComponent.getPackageName().equals(packageName)) { 13116 if (removed == null) { 13117 removed = new ArrayList<PersistentPreferredActivity>(); 13118 } 13119 removed.add(ppa); 13120 } 13121 } 13122 if (removed != null) { 13123 for (int j=0; j<removed.size(); j++) { 13124 PersistentPreferredActivity ppa = removed.get(j); 13125 ppir.removeFilter(ppa); 13126 } 13127 changed = true; 13128 } 13129 } 13130 13131 if (changed) { 13132 scheduleWritePackageRestrictionsLocked(userId); 13133 } 13134 } 13135 } 13136 13137 /** 13138 * Non-Binder method, support for the backup/restore mechanism: write the 13139 * full set of preferred activities in its canonical XML format. Returns true 13140 * on success; false otherwise. 13141 */ 13142 @Override 13143 public byte[] getPreferredActivityBackup(int userId) { 13144 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13145 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13146 } 13147 13148 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13149 try { 13150 final XmlSerializer serializer = new FastXmlSerializer(); 13151 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13152 serializer.startDocument(null, true); 13153 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13154 13155 synchronized (mPackages) { 13156 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13157 } 13158 13159 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13160 serializer.endDocument(); 13161 serializer.flush(); 13162 } catch (Exception e) { 13163 if (DEBUG_BACKUP) { 13164 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13165 } 13166 return null; 13167 } 13168 13169 return dataStream.toByteArray(); 13170 } 13171 13172 @Override 13173 public void restorePreferredActivities(byte[] backup, int userId) { 13174 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13175 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13176 } 13177 13178 try { 13179 final XmlPullParser parser = Xml.newPullParser(); 13180 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13181 13182 int type; 13183 while ((type = parser.next()) != XmlPullParser.START_TAG 13184 && type != XmlPullParser.END_DOCUMENT) { 13185 } 13186 if (type != XmlPullParser.START_TAG) { 13187 // oops didn't find a start tag?! 13188 if (DEBUG_BACKUP) { 13189 Slog.e(TAG, "Didn't find start tag during restore"); 13190 } 13191 return; 13192 } 13193 13194 // this is supposed to be TAG_PREFERRED_BACKUP 13195 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13196 if (DEBUG_BACKUP) { 13197 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13198 } 13199 return; 13200 } 13201 13202 // skip interfering stuff, then we're aligned with the backing implementation 13203 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13204 synchronized (mPackages) { 13205 mSettings.readPreferredActivitiesLPw(parser, userId); 13206 } 13207 } catch (Exception e) { 13208 if (DEBUG_BACKUP) { 13209 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13210 } 13211 } 13212 } 13213 13214 @Override 13215 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13216 int sourceUserId, int targetUserId, int flags) { 13217 mContext.enforceCallingOrSelfPermission( 13218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13219 int callingUid = Binder.getCallingUid(); 13220 enforceOwnerRights(ownerPackage, callingUid); 13221 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13222 if (intentFilter.countActions() == 0) { 13223 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13224 return; 13225 } 13226 synchronized (mPackages) { 13227 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13228 ownerPackage, targetUserId, flags); 13229 CrossProfileIntentResolver resolver = 13230 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13231 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13232 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13233 if (existing != null) { 13234 int size = existing.size(); 13235 for (int i = 0; i < size; i++) { 13236 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13237 return; 13238 } 13239 } 13240 } 13241 resolver.addFilter(newFilter); 13242 scheduleWritePackageRestrictionsLocked(sourceUserId); 13243 } 13244 } 13245 13246 @Override 13247 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13248 mContext.enforceCallingOrSelfPermission( 13249 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13250 int callingUid = Binder.getCallingUid(); 13251 enforceOwnerRights(ownerPackage, callingUid); 13252 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13253 synchronized (mPackages) { 13254 CrossProfileIntentResolver resolver = 13255 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13256 ArraySet<CrossProfileIntentFilter> set = 13257 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13258 for (CrossProfileIntentFilter filter : set) { 13259 if (filter.getOwnerPackage().equals(ownerPackage)) { 13260 resolver.removeFilter(filter); 13261 } 13262 } 13263 scheduleWritePackageRestrictionsLocked(sourceUserId); 13264 } 13265 } 13266 13267 // Enforcing that callingUid is owning pkg on userId 13268 private void enforceOwnerRights(String pkg, int callingUid) { 13269 // The system owns everything. 13270 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13271 return; 13272 } 13273 int callingUserId = UserHandle.getUserId(callingUid); 13274 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13275 if (pi == null) { 13276 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13277 + callingUserId); 13278 } 13279 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13280 throw new SecurityException("Calling uid " + callingUid 13281 + " does not own package " + pkg); 13282 } 13283 } 13284 13285 @Override 13286 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13287 Intent intent = new Intent(Intent.ACTION_MAIN); 13288 intent.addCategory(Intent.CATEGORY_HOME); 13289 13290 final int callingUserId = UserHandle.getCallingUserId(); 13291 List<ResolveInfo> list = queryIntentActivities(intent, null, 13292 PackageManager.GET_META_DATA, callingUserId); 13293 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13294 true, false, false, callingUserId); 13295 13296 allHomeCandidates.clear(); 13297 if (list != null) { 13298 for (ResolveInfo ri : list) { 13299 allHomeCandidates.add(ri); 13300 } 13301 } 13302 return (preferred == null || preferred.activityInfo == null) 13303 ? null 13304 : new ComponentName(preferred.activityInfo.packageName, 13305 preferred.activityInfo.name); 13306 } 13307 13308 @Override 13309 public void setApplicationEnabledSetting(String appPackageName, 13310 int newState, int flags, int userId, String callingPackage) { 13311 if (!sUserManager.exists(userId)) return; 13312 if (callingPackage == null) { 13313 callingPackage = Integer.toString(Binder.getCallingUid()); 13314 } 13315 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13316 } 13317 13318 @Override 13319 public void setComponentEnabledSetting(ComponentName componentName, 13320 int newState, int flags, int userId) { 13321 if (!sUserManager.exists(userId)) return; 13322 setEnabledSetting(componentName.getPackageName(), 13323 componentName.getClassName(), newState, flags, userId, null); 13324 } 13325 13326 private void setEnabledSetting(final String packageName, String className, int newState, 13327 final int flags, int userId, String callingPackage) { 13328 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13329 || newState == COMPONENT_ENABLED_STATE_ENABLED 13330 || newState == COMPONENT_ENABLED_STATE_DISABLED 13331 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13332 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13333 throw new IllegalArgumentException("Invalid new component state: " 13334 + newState); 13335 } 13336 PackageSetting pkgSetting; 13337 final int uid = Binder.getCallingUid(); 13338 final int permission = mContext.checkCallingOrSelfPermission( 13339 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13340 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13341 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13342 boolean sendNow = false; 13343 boolean isApp = (className == null); 13344 String componentName = isApp ? packageName : className; 13345 int packageUid = -1; 13346 ArrayList<String> components; 13347 13348 // writer 13349 synchronized (mPackages) { 13350 pkgSetting = mSettings.mPackages.get(packageName); 13351 if (pkgSetting == null) { 13352 if (className == null) { 13353 throw new IllegalArgumentException( 13354 "Unknown package: " + packageName); 13355 } 13356 throw new IllegalArgumentException( 13357 "Unknown component: " + packageName 13358 + "/" + className); 13359 } 13360 // Allow root and verify that userId is not being specified by a different user 13361 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13362 throw new SecurityException( 13363 "Permission Denial: attempt to change component state from pid=" 13364 + Binder.getCallingPid() 13365 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13366 } 13367 if (className == null) { 13368 // We're dealing with an application/package level state change 13369 if (pkgSetting.getEnabled(userId) == newState) { 13370 // Nothing to do 13371 return; 13372 } 13373 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13374 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13375 // Don't care about who enables an app. 13376 callingPackage = null; 13377 } 13378 pkgSetting.setEnabled(newState, userId, callingPackage); 13379 // pkgSetting.pkg.mSetEnabled = newState; 13380 } else { 13381 // We're dealing with a component level state change 13382 // First, verify that this is a valid class name. 13383 PackageParser.Package pkg = pkgSetting.pkg; 13384 if (pkg == null || !pkg.hasComponentClassName(className)) { 13385 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13386 throw new IllegalArgumentException("Component class " + className 13387 + " does not exist in " + packageName); 13388 } else { 13389 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13390 + className + " does not exist in " + packageName); 13391 } 13392 } 13393 switch (newState) { 13394 case COMPONENT_ENABLED_STATE_ENABLED: 13395 if (!pkgSetting.enableComponentLPw(className, userId)) { 13396 return; 13397 } 13398 break; 13399 case COMPONENT_ENABLED_STATE_DISABLED: 13400 if (!pkgSetting.disableComponentLPw(className, userId)) { 13401 return; 13402 } 13403 break; 13404 case COMPONENT_ENABLED_STATE_DEFAULT: 13405 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13406 return; 13407 } 13408 break; 13409 default: 13410 Slog.e(TAG, "Invalid new component state: " + newState); 13411 return; 13412 } 13413 } 13414 scheduleWritePackageRestrictionsLocked(userId); 13415 components = mPendingBroadcasts.get(userId, packageName); 13416 final boolean newPackage = components == null; 13417 if (newPackage) { 13418 components = new ArrayList<String>(); 13419 } 13420 if (!components.contains(componentName)) { 13421 components.add(componentName); 13422 } 13423 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13424 sendNow = true; 13425 // Purge entry from pending broadcast list if another one exists already 13426 // since we are sending one right away. 13427 mPendingBroadcasts.remove(userId, packageName); 13428 } else { 13429 if (newPackage) { 13430 mPendingBroadcasts.put(userId, packageName, components); 13431 } 13432 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13433 // Schedule a message 13434 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13435 } 13436 } 13437 } 13438 13439 long callingId = Binder.clearCallingIdentity(); 13440 try { 13441 if (sendNow) { 13442 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13443 sendPackageChangedBroadcast(packageName, 13444 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13445 } 13446 } finally { 13447 Binder.restoreCallingIdentity(callingId); 13448 } 13449 } 13450 13451 private void sendPackageChangedBroadcast(String packageName, 13452 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13453 if (DEBUG_INSTALL) 13454 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13455 + componentNames); 13456 Bundle extras = new Bundle(4); 13457 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13458 String nameList[] = new String[componentNames.size()]; 13459 componentNames.toArray(nameList); 13460 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13461 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13462 extras.putInt(Intent.EXTRA_UID, packageUid); 13463 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13464 new int[] {UserHandle.getUserId(packageUid)}); 13465 } 13466 13467 @Override 13468 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13469 if (!sUserManager.exists(userId)) return; 13470 final int uid = Binder.getCallingUid(); 13471 final int permission = mContext.checkCallingOrSelfPermission( 13472 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13473 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13474 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13475 // writer 13476 synchronized (mPackages) { 13477 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13478 allowedByPermission, uid, userId)) { 13479 scheduleWritePackageRestrictionsLocked(userId); 13480 } 13481 } 13482 } 13483 13484 @Override 13485 public String getInstallerPackageName(String packageName) { 13486 // reader 13487 synchronized (mPackages) { 13488 return mSettings.getInstallerPackageNameLPr(packageName); 13489 } 13490 } 13491 13492 @Override 13493 public int getApplicationEnabledSetting(String packageName, int userId) { 13494 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13495 int uid = Binder.getCallingUid(); 13496 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13497 // reader 13498 synchronized (mPackages) { 13499 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13500 } 13501 } 13502 13503 @Override 13504 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13505 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13506 int uid = Binder.getCallingUid(); 13507 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13508 // reader 13509 synchronized (mPackages) { 13510 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13511 } 13512 } 13513 13514 @Override 13515 public void enterSafeMode() { 13516 enforceSystemOrRoot("Only the system can request entering safe mode"); 13517 13518 if (!mSystemReady) { 13519 mSafeMode = true; 13520 } 13521 } 13522 13523 @Override 13524 public void systemReady() { 13525 mSystemReady = true; 13526 13527 // Read the compatibilty setting when the system is ready. 13528 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13529 mContext.getContentResolver(), 13530 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13531 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13532 if (DEBUG_SETTINGS) { 13533 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13534 } 13535 13536 synchronized (mPackages) { 13537 // Verify that all of the preferred activity components actually 13538 // exist. It is possible for applications to be updated and at 13539 // that point remove a previously declared activity component that 13540 // had been set as a preferred activity. We try to clean this up 13541 // the next time we encounter that preferred activity, but it is 13542 // possible for the user flow to never be able to return to that 13543 // situation so here we do a sanity check to make sure we haven't 13544 // left any junk around. 13545 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13546 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13547 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13548 removed.clear(); 13549 for (PreferredActivity pa : pir.filterSet()) { 13550 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13551 removed.add(pa); 13552 } 13553 } 13554 if (removed.size() > 0) { 13555 for (int r=0; r<removed.size(); r++) { 13556 PreferredActivity pa = removed.get(r); 13557 Slog.w(TAG, "Removing dangling preferred activity: " 13558 + pa.mPref.mComponent); 13559 pir.removeFilter(pa); 13560 } 13561 mSettings.writePackageRestrictionsLPr( 13562 mSettings.mPreferredActivities.keyAt(i)); 13563 } 13564 } 13565 } 13566 sUserManager.systemReady(); 13567 13568 // Kick off any messages waiting for system ready 13569 if (mPostSystemReadyMessages != null) { 13570 for (Message msg : mPostSystemReadyMessages) { 13571 msg.sendToTarget(); 13572 } 13573 mPostSystemReadyMessages = null; 13574 } 13575 13576 // Watch for external volumes that come and go over time 13577 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13578 storage.registerListener(mStorageListener); 13579 13580 mInstallerService.systemReady(); 13581 mPackageDexOptimizer.systemReady(); 13582 } 13583 13584 @Override 13585 public boolean isSafeMode() { 13586 return mSafeMode; 13587 } 13588 13589 @Override 13590 public boolean hasSystemUidErrors() { 13591 return mHasSystemUidErrors; 13592 } 13593 13594 static String arrayToString(int[] array) { 13595 StringBuffer buf = new StringBuffer(128); 13596 buf.append('['); 13597 if (array != null) { 13598 for (int i=0; i<array.length; i++) { 13599 if (i > 0) buf.append(", "); 13600 buf.append(array[i]); 13601 } 13602 } 13603 buf.append(']'); 13604 return buf.toString(); 13605 } 13606 13607 static class DumpState { 13608 public static final int DUMP_LIBS = 1 << 0; 13609 public static final int DUMP_FEATURES = 1 << 1; 13610 public static final int DUMP_RESOLVERS = 1 << 2; 13611 public static final int DUMP_PERMISSIONS = 1 << 3; 13612 public static final int DUMP_PACKAGES = 1 << 4; 13613 public static final int DUMP_SHARED_USERS = 1 << 5; 13614 public static final int DUMP_MESSAGES = 1 << 6; 13615 public static final int DUMP_PROVIDERS = 1 << 7; 13616 public static final int DUMP_VERIFIERS = 1 << 8; 13617 public static final int DUMP_PREFERRED = 1 << 9; 13618 public static final int DUMP_PREFERRED_XML = 1 << 10; 13619 public static final int DUMP_KEYSETS = 1 << 11; 13620 public static final int DUMP_VERSION = 1 << 12; 13621 public static final int DUMP_INSTALLS = 1 << 13; 13622 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13623 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13624 13625 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13626 13627 private int mTypes; 13628 13629 private int mOptions; 13630 13631 private boolean mTitlePrinted; 13632 13633 private SharedUserSetting mSharedUser; 13634 13635 public boolean isDumping(int type) { 13636 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13637 return true; 13638 } 13639 13640 return (mTypes & type) != 0; 13641 } 13642 13643 public void setDump(int type) { 13644 mTypes |= type; 13645 } 13646 13647 public boolean isOptionEnabled(int option) { 13648 return (mOptions & option) != 0; 13649 } 13650 13651 public void setOptionEnabled(int option) { 13652 mOptions |= option; 13653 } 13654 13655 public boolean onTitlePrinted() { 13656 final boolean printed = mTitlePrinted; 13657 mTitlePrinted = true; 13658 return printed; 13659 } 13660 13661 public boolean getTitlePrinted() { 13662 return mTitlePrinted; 13663 } 13664 13665 public void setTitlePrinted(boolean enabled) { 13666 mTitlePrinted = enabled; 13667 } 13668 13669 public SharedUserSetting getSharedUser() { 13670 return mSharedUser; 13671 } 13672 13673 public void setSharedUser(SharedUserSetting user) { 13674 mSharedUser = user; 13675 } 13676 } 13677 13678 @Override 13679 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13680 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13681 != PackageManager.PERMISSION_GRANTED) { 13682 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13683 + Binder.getCallingPid() 13684 + ", uid=" + Binder.getCallingUid() 13685 + " without permission " 13686 + android.Manifest.permission.DUMP); 13687 return; 13688 } 13689 13690 DumpState dumpState = new DumpState(); 13691 boolean fullPreferred = false; 13692 boolean checkin = false; 13693 13694 String packageName = null; 13695 13696 int opti = 0; 13697 while (opti < args.length) { 13698 String opt = args[opti]; 13699 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13700 break; 13701 } 13702 opti++; 13703 13704 if ("-a".equals(opt)) { 13705 // Right now we only know how to print all. 13706 } else if ("-h".equals(opt)) { 13707 pw.println("Package manager dump options:"); 13708 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13709 pw.println(" --checkin: dump for a checkin"); 13710 pw.println(" -f: print details of intent filters"); 13711 pw.println(" -h: print this help"); 13712 pw.println(" cmd may be one of:"); 13713 pw.println(" l[ibraries]: list known shared libraries"); 13714 pw.println(" f[ibraries]: list device features"); 13715 pw.println(" k[eysets]: print known keysets"); 13716 pw.println(" r[esolvers]: dump intent resolvers"); 13717 pw.println(" perm[issions]: dump permissions"); 13718 pw.println(" pref[erred]: print preferred package settings"); 13719 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13720 pw.println(" prov[iders]: dump content providers"); 13721 pw.println(" p[ackages]: dump installed packages"); 13722 pw.println(" s[hared-users]: dump shared user IDs"); 13723 pw.println(" m[essages]: print collected runtime messages"); 13724 pw.println(" v[erifiers]: print package verifier info"); 13725 pw.println(" version: print database version info"); 13726 pw.println(" write: write current settings now"); 13727 pw.println(" <package.name>: info about given package"); 13728 pw.println(" installs: details about install sessions"); 13729 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13730 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13731 return; 13732 } else if ("--checkin".equals(opt)) { 13733 checkin = true; 13734 } else if ("-f".equals(opt)) { 13735 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13736 } else { 13737 pw.println("Unknown argument: " + opt + "; use -h for help"); 13738 } 13739 } 13740 13741 // Is the caller requesting to dump a particular piece of data? 13742 if (opti < args.length) { 13743 String cmd = args[opti]; 13744 opti++; 13745 // Is this a package name? 13746 if ("android".equals(cmd) || cmd.contains(".")) { 13747 packageName = cmd; 13748 // When dumping a single package, we always dump all of its 13749 // filter information since the amount of data will be reasonable. 13750 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13751 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13752 dumpState.setDump(DumpState.DUMP_LIBS); 13753 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13754 dumpState.setDump(DumpState.DUMP_FEATURES); 13755 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13756 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13757 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13758 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13759 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13760 dumpState.setDump(DumpState.DUMP_PREFERRED); 13761 } else if ("preferred-xml".equals(cmd)) { 13762 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13763 if (opti < args.length && "--full".equals(args[opti])) { 13764 fullPreferred = true; 13765 opti++; 13766 } 13767 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13768 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13769 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13770 dumpState.setDump(DumpState.DUMP_PACKAGES); 13771 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13772 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13773 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13774 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13775 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13776 dumpState.setDump(DumpState.DUMP_MESSAGES); 13777 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13778 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13779 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13780 || "intent-filter-verifiers".equals(cmd)) { 13781 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13782 } else if ("version".equals(cmd)) { 13783 dumpState.setDump(DumpState.DUMP_VERSION); 13784 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13785 dumpState.setDump(DumpState.DUMP_KEYSETS); 13786 } else if ("installs".equals(cmd)) { 13787 dumpState.setDump(DumpState.DUMP_INSTALLS); 13788 } else if ("write".equals(cmd)) { 13789 synchronized (mPackages) { 13790 mSettings.writeLPr(); 13791 pw.println("Settings written."); 13792 return; 13793 } 13794 } 13795 } 13796 13797 if (checkin) { 13798 pw.println("vers,1"); 13799 } 13800 13801 // reader 13802 synchronized (mPackages) { 13803 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13804 if (!checkin) { 13805 if (dumpState.onTitlePrinted()) 13806 pw.println(); 13807 pw.println("Database versions:"); 13808 pw.print(" SDK Version:"); 13809 pw.print(" internal="); 13810 pw.print(mSettings.mInternalSdkPlatform); 13811 pw.print(" external="); 13812 pw.println(mSettings.mExternalSdkPlatform); 13813 pw.print(" DB Version:"); 13814 pw.print(" internal="); 13815 pw.print(mSettings.mInternalDatabaseVersion); 13816 pw.print(" external="); 13817 pw.println(mSettings.mExternalDatabaseVersion); 13818 } 13819 } 13820 13821 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13822 if (!checkin) { 13823 if (dumpState.onTitlePrinted()) 13824 pw.println(); 13825 pw.println("Verifiers:"); 13826 pw.print(" Required: "); 13827 pw.print(mRequiredVerifierPackage); 13828 pw.print(" (uid="); 13829 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13830 pw.println(")"); 13831 } else if (mRequiredVerifierPackage != null) { 13832 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13833 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13834 } 13835 } 13836 13837 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13838 packageName == null) { 13839 if (mIntentFilterVerifierComponent != null) { 13840 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13841 if (!checkin) { 13842 if (dumpState.onTitlePrinted()) 13843 pw.println(); 13844 pw.println("Intent Filter Verifier:"); 13845 pw.print(" Using: "); 13846 pw.print(verifierPackageName); 13847 pw.print(" (uid="); 13848 pw.print(getPackageUid(verifierPackageName, 0)); 13849 pw.println(")"); 13850 } else if (verifierPackageName != null) { 13851 pw.print("ifv,"); pw.print(verifierPackageName); 13852 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13853 } 13854 } else { 13855 pw.println(); 13856 pw.println("No Intent Filter Verifier available!"); 13857 } 13858 } 13859 13860 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13861 boolean printedHeader = false; 13862 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13863 while (it.hasNext()) { 13864 String name = it.next(); 13865 SharedLibraryEntry ent = mSharedLibraries.get(name); 13866 if (!checkin) { 13867 if (!printedHeader) { 13868 if (dumpState.onTitlePrinted()) 13869 pw.println(); 13870 pw.println("Libraries:"); 13871 printedHeader = true; 13872 } 13873 pw.print(" "); 13874 } else { 13875 pw.print("lib,"); 13876 } 13877 pw.print(name); 13878 if (!checkin) { 13879 pw.print(" -> "); 13880 } 13881 if (ent.path != null) { 13882 if (!checkin) { 13883 pw.print("(jar) "); 13884 pw.print(ent.path); 13885 } else { 13886 pw.print(",jar,"); 13887 pw.print(ent.path); 13888 } 13889 } else { 13890 if (!checkin) { 13891 pw.print("(apk) "); 13892 pw.print(ent.apk); 13893 } else { 13894 pw.print(",apk,"); 13895 pw.print(ent.apk); 13896 } 13897 } 13898 pw.println(); 13899 } 13900 } 13901 13902 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13903 if (dumpState.onTitlePrinted()) 13904 pw.println(); 13905 if (!checkin) { 13906 pw.println("Features:"); 13907 } 13908 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13909 while (it.hasNext()) { 13910 String name = it.next(); 13911 if (!checkin) { 13912 pw.print(" "); 13913 } else { 13914 pw.print("feat,"); 13915 } 13916 pw.println(name); 13917 } 13918 } 13919 13920 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13921 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13922 : "Activity Resolver Table:", " ", packageName, 13923 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13924 dumpState.setTitlePrinted(true); 13925 } 13926 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13927 : "Receiver Resolver Table:", " ", packageName, 13928 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13929 dumpState.setTitlePrinted(true); 13930 } 13931 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13932 : "Service Resolver Table:", " ", packageName, 13933 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13934 dumpState.setTitlePrinted(true); 13935 } 13936 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13937 : "Provider Resolver Table:", " ", packageName, 13938 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13939 dumpState.setTitlePrinted(true); 13940 } 13941 } 13942 13943 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13944 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13945 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13946 int user = mSettings.mPreferredActivities.keyAt(i); 13947 if (pir.dump(pw, 13948 dumpState.getTitlePrinted() 13949 ? "\nPreferred Activities User " + user + ":" 13950 : "Preferred Activities User " + user + ":", " ", 13951 packageName, true, false)) { 13952 dumpState.setTitlePrinted(true); 13953 } 13954 } 13955 } 13956 13957 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13958 pw.flush(); 13959 FileOutputStream fout = new FileOutputStream(fd); 13960 BufferedOutputStream str = new BufferedOutputStream(fout); 13961 XmlSerializer serializer = new FastXmlSerializer(); 13962 try { 13963 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 13964 serializer.startDocument(null, true); 13965 serializer.setFeature( 13966 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13967 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13968 serializer.endDocument(); 13969 serializer.flush(); 13970 } catch (IllegalArgumentException e) { 13971 pw.println("Failed writing: " + e); 13972 } catch (IllegalStateException e) { 13973 pw.println("Failed writing: " + e); 13974 } catch (IOException e) { 13975 pw.println("Failed writing: " + e); 13976 } 13977 } 13978 13979 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13980 pw.println(); 13981 int count = mSettings.mPackages.size(); 13982 if (count == 0) { 13983 pw.println("No domain preferred apps!"); 13984 pw.println(); 13985 } else { 13986 final String prefix = " "; 13987 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13988 if (allPackageSettings.size() == 0) { 13989 pw.println("No domain preferred apps!"); 13990 pw.println(); 13991 } else { 13992 pw.println("Domain preferred apps status:"); 13993 pw.println(); 13994 count = 0; 13995 for (PackageSetting ps : allPackageSettings) { 13996 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13997 if (ivi == null || ivi.getPackageName() == null) continue; 13998 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13999 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14000 pw.println(prefix + "Status: " + ivi.getStatusString()); 14001 pw.println(); 14002 count++; 14003 } 14004 if (count == 0) { 14005 pw.println(prefix + "No domain preferred app status!"); 14006 pw.println(); 14007 } 14008 for (int userId : sUserManager.getUserIds()) { 14009 pw.println("Domain preferred apps for User " + userId + ":"); 14010 pw.println(); 14011 count = 0; 14012 for (PackageSetting ps : allPackageSettings) { 14013 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14014 if (ivi == null || ivi.getPackageName() == null) { 14015 continue; 14016 } 14017 final int status = ps.getDomainVerificationStatusForUser(userId); 14018 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14019 continue; 14020 } 14021 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14022 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14023 String statusStr = IntentFilterVerificationInfo. 14024 getStatusStringFromValue(status); 14025 pw.println(prefix + "Status: " + statusStr); 14026 pw.println(); 14027 count++; 14028 } 14029 if (count == 0) { 14030 pw.println(prefix + "No domain preferred apps!"); 14031 pw.println(); 14032 } 14033 } 14034 } 14035 } 14036 } 14037 14038 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14039 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14040 if (packageName == null) { 14041 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14042 if (iperm == 0) { 14043 if (dumpState.onTitlePrinted()) 14044 pw.println(); 14045 pw.println("AppOp Permissions:"); 14046 } 14047 pw.print(" AppOp Permission "); 14048 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14049 pw.println(":"); 14050 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14051 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14052 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14053 } 14054 } 14055 } 14056 } 14057 14058 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14059 boolean printedSomething = false; 14060 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14061 if (packageName != null && !packageName.equals(p.info.packageName)) { 14062 continue; 14063 } 14064 if (!printedSomething) { 14065 if (dumpState.onTitlePrinted()) 14066 pw.println(); 14067 pw.println("Registered ContentProviders:"); 14068 printedSomething = true; 14069 } 14070 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14071 pw.print(" "); pw.println(p.toString()); 14072 } 14073 printedSomething = false; 14074 for (Map.Entry<String, PackageParser.Provider> entry : 14075 mProvidersByAuthority.entrySet()) { 14076 PackageParser.Provider p = entry.getValue(); 14077 if (packageName != null && !packageName.equals(p.info.packageName)) { 14078 continue; 14079 } 14080 if (!printedSomething) { 14081 if (dumpState.onTitlePrinted()) 14082 pw.println(); 14083 pw.println("ContentProvider Authorities:"); 14084 printedSomething = true; 14085 } 14086 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14087 pw.print(" "); pw.println(p.toString()); 14088 if (p.info != null && p.info.applicationInfo != null) { 14089 final String appInfo = p.info.applicationInfo.toString(); 14090 pw.print(" applicationInfo="); pw.println(appInfo); 14091 } 14092 } 14093 } 14094 14095 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14096 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14097 } 14098 14099 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14100 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14101 } 14102 14103 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14104 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14105 } 14106 14107 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14108 // XXX should handle packageName != null by dumping only install data that 14109 // the given package is involved with. 14110 if (dumpState.onTitlePrinted()) pw.println(); 14111 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14112 } 14113 14114 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14115 if (dumpState.onTitlePrinted()) pw.println(); 14116 mSettings.dumpReadMessagesLPr(pw, dumpState); 14117 14118 pw.println(); 14119 pw.println("Package warning messages:"); 14120 BufferedReader in = null; 14121 String line = null; 14122 try { 14123 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14124 while ((line = in.readLine()) != null) { 14125 if (line.contains("ignored: updated version")) continue; 14126 pw.println(line); 14127 } 14128 } catch (IOException ignored) { 14129 } finally { 14130 IoUtils.closeQuietly(in); 14131 } 14132 } 14133 14134 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14135 BufferedReader in = null; 14136 String line = null; 14137 try { 14138 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14139 while ((line = in.readLine()) != null) { 14140 if (line.contains("ignored: updated version")) continue; 14141 pw.print("msg,"); 14142 pw.println(line); 14143 } 14144 } catch (IOException ignored) { 14145 } finally { 14146 IoUtils.closeQuietly(in); 14147 } 14148 } 14149 } 14150 } 14151 14152 // ------- apps on sdcard specific code ------- 14153 static final boolean DEBUG_SD_INSTALL = false; 14154 14155 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14156 14157 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14158 14159 private boolean mMediaMounted = false; 14160 14161 static String getEncryptKey() { 14162 try { 14163 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14164 SD_ENCRYPTION_KEYSTORE_NAME); 14165 if (sdEncKey == null) { 14166 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14167 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14168 if (sdEncKey == null) { 14169 Slog.e(TAG, "Failed to create encryption keys"); 14170 return null; 14171 } 14172 } 14173 return sdEncKey; 14174 } catch (NoSuchAlgorithmException nsae) { 14175 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14176 return null; 14177 } catch (IOException ioe) { 14178 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14179 return null; 14180 } 14181 } 14182 14183 /* 14184 * Update media status on PackageManager. 14185 */ 14186 @Override 14187 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14188 int callingUid = Binder.getCallingUid(); 14189 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14190 throw new SecurityException("Media status can only be updated by the system"); 14191 } 14192 // reader; this apparently protects mMediaMounted, but should probably 14193 // be a different lock in that case. 14194 synchronized (mPackages) { 14195 Log.i(TAG, "Updating external media status from " 14196 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14197 + (mediaStatus ? "mounted" : "unmounted")); 14198 if (DEBUG_SD_INSTALL) 14199 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14200 + ", mMediaMounted=" + mMediaMounted); 14201 if (mediaStatus == mMediaMounted) { 14202 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14203 : 0, -1); 14204 mHandler.sendMessage(msg); 14205 return; 14206 } 14207 mMediaMounted = mediaStatus; 14208 } 14209 // Queue up an async operation since the package installation may take a 14210 // little while. 14211 mHandler.post(new Runnable() { 14212 public void run() { 14213 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14214 } 14215 }); 14216 } 14217 14218 /** 14219 * Called by MountService when the initial ASECs to scan are available. 14220 * Should block until all the ASEC containers are finished being scanned. 14221 */ 14222 public void scanAvailableAsecs() { 14223 updateExternalMediaStatusInner(true, false, false); 14224 if (mShouldRestoreconData) { 14225 SELinuxMMAC.setRestoreconDone(); 14226 mShouldRestoreconData = false; 14227 } 14228 } 14229 14230 /* 14231 * Collect information of applications on external media, map them against 14232 * existing containers and update information based on current mount status. 14233 * Please note that we always have to report status if reportStatus has been 14234 * set to true especially when unloading packages. 14235 */ 14236 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14237 boolean externalStorage) { 14238 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14239 int[] uidArr = EmptyArray.INT; 14240 14241 final String[] list = PackageHelper.getSecureContainerList(); 14242 if (ArrayUtils.isEmpty(list)) { 14243 Log.i(TAG, "No secure containers found"); 14244 } else { 14245 // Process list of secure containers and categorize them 14246 // as active or stale based on their package internal state. 14247 14248 // reader 14249 synchronized (mPackages) { 14250 for (String cid : list) { 14251 // Leave stages untouched for now; installer service owns them 14252 if (PackageInstallerService.isStageName(cid)) continue; 14253 14254 if (DEBUG_SD_INSTALL) 14255 Log.i(TAG, "Processing container " + cid); 14256 String pkgName = getAsecPackageName(cid); 14257 if (pkgName == null) { 14258 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14259 continue; 14260 } 14261 if (DEBUG_SD_INSTALL) 14262 Log.i(TAG, "Looking for pkg : " + pkgName); 14263 14264 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14265 if (ps == null) { 14266 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14267 continue; 14268 } 14269 14270 /* 14271 * Skip packages that are not external if we're unmounting 14272 * external storage. 14273 */ 14274 if (externalStorage && !isMounted && !isExternal(ps)) { 14275 continue; 14276 } 14277 14278 final AsecInstallArgs args = new AsecInstallArgs(cid, 14279 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14280 // The package status is changed only if the code path 14281 // matches between settings and the container id. 14282 if (ps.codePathString != null 14283 && ps.codePathString.startsWith(args.getCodePath())) { 14284 if (DEBUG_SD_INSTALL) { 14285 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14286 + " at code path: " + ps.codePathString); 14287 } 14288 14289 // We do have a valid package installed on sdcard 14290 processCids.put(args, ps.codePathString); 14291 final int uid = ps.appId; 14292 if (uid != -1) { 14293 uidArr = ArrayUtils.appendInt(uidArr, uid); 14294 } 14295 } else { 14296 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14297 + ps.codePathString); 14298 } 14299 } 14300 } 14301 14302 Arrays.sort(uidArr); 14303 } 14304 14305 // Process packages with valid entries. 14306 if (isMounted) { 14307 if (DEBUG_SD_INSTALL) 14308 Log.i(TAG, "Loading packages"); 14309 loadMediaPackages(processCids, uidArr); 14310 startCleaningPackages(); 14311 mInstallerService.onSecureContainersAvailable(); 14312 } else { 14313 if (DEBUG_SD_INSTALL) 14314 Log.i(TAG, "Unloading packages"); 14315 unloadMediaPackages(processCids, uidArr, reportStatus); 14316 } 14317 } 14318 14319 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14320 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14321 final int size = infos.size(); 14322 final String[] packageNames = new String[size]; 14323 final int[] packageUids = new int[size]; 14324 for (int i = 0; i < size; i++) { 14325 final ApplicationInfo info = infos.get(i); 14326 packageNames[i] = info.packageName; 14327 packageUids[i] = info.uid; 14328 } 14329 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14330 finishedReceiver); 14331 } 14332 14333 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14334 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14335 sendResourcesChangedBroadcast(mediaStatus, replacing, 14336 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14337 } 14338 14339 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14340 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14341 int size = pkgList.length; 14342 if (size > 0) { 14343 // Send broadcasts here 14344 Bundle extras = new Bundle(); 14345 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14346 if (uidArr != null) { 14347 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14348 } 14349 if (replacing) { 14350 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14351 } 14352 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14353 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14354 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14355 } 14356 } 14357 14358 /* 14359 * Look at potentially valid container ids from processCids If package 14360 * information doesn't match the one on record or package scanning fails, 14361 * the cid is added to list of removeCids. We currently don't delete stale 14362 * containers. 14363 */ 14364 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14365 ArrayList<String> pkgList = new ArrayList<String>(); 14366 Set<AsecInstallArgs> keys = processCids.keySet(); 14367 14368 for (AsecInstallArgs args : keys) { 14369 String codePath = processCids.get(args); 14370 if (DEBUG_SD_INSTALL) 14371 Log.i(TAG, "Loading container : " + args.cid); 14372 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14373 try { 14374 // Make sure there are no container errors first. 14375 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14376 Slog.e(TAG, "Failed to mount cid : " + args.cid 14377 + " when installing from sdcard"); 14378 continue; 14379 } 14380 // Check code path here. 14381 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14382 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14383 + " does not match one in settings " + codePath); 14384 continue; 14385 } 14386 // Parse package 14387 int parseFlags = mDefParseFlags; 14388 if (args.isExternalAsec()) { 14389 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14390 } 14391 if (args.isFwdLocked()) { 14392 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14393 } 14394 14395 synchronized (mInstallLock) { 14396 PackageParser.Package pkg = null; 14397 try { 14398 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14399 } catch (PackageManagerException e) { 14400 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14401 } 14402 // Scan the package 14403 if (pkg != null) { 14404 /* 14405 * TODO why is the lock being held? doPostInstall is 14406 * called in other places without the lock. This needs 14407 * to be straightened out. 14408 */ 14409 // writer 14410 synchronized (mPackages) { 14411 retCode = PackageManager.INSTALL_SUCCEEDED; 14412 pkgList.add(pkg.packageName); 14413 // Post process args 14414 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14415 pkg.applicationInfo.uid); 14416 } 14417 } else { 14418 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14419 } 14420 } 14421 14422 } finally { 14423 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14424 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14425 } 14426 } 14427 } 14428 // writer 14429 synchronized (mPackages) { 14430 // If the platform SDK has changed since the last time we booted, 14431 // we need to re-grant app permission to catch any new ones that 14432 // appear. This is really a hack, and means that apps can in some 14433 // cases get permissions that the user didn't initially explicitly 14434 // allow... it would be nice to have some better way to handle 14435 // this situation. 14436 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14437 if (regrantPermissions) 14438 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14439 + mSdkVersion + "; regranting permissions for external storage"); 14440 mSettings.mExternalSdkPlatform = mSdkVersion; 14441 14442 // Make sure group IDs have been assigned, and any permission 14443 // changes in other apps are accounted for 14444 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14445 | (regrantPermissions 14446 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14447 : 0)); 14448 14449 mSettings.updateExternalDatabaseVersion(); 14450 14451 // can downgrade to reader 14452 // Persist settings 14453 mSettings.writeLPr(); 14454 } 14455 // Send a broadcast to let everyone know we are done processing 14456 if (pkgList.size() > 0) { 14457 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14458 } 14459 } 14460 14461 /* 14462 * Utility method to unload a list of specified containers 14463 */ 14464 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14465 // Just unmount all valid containers. 14466 for (AsecInstallArgs arg : cidArgs) { 14467 synchronized (mInstallLock) { 14468 arg.doPostDeleteLI(false); 14469 } 14470 } 14471 } 14472 14473 /* 14474 * Unload packages mounted on external media. This involves deleting package 14475 * data from internal structures, sending broadcasts about diabled packages, 14476 * gc'ing to free up references, unmounting all secure containers 14477 * corresponding to packages on external media, and posting a 14478 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14479 * that we always have to post this message if status has been requested no 14480 * matter what. 14481 */ 14482 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14483 final boolean reportStatus) { 14484 if (DEBUG_SD_INSTALL) 14485 Log.i(TAG, "unloading media packages"); 14486 ArrayList<String> pkgList = new ArrayList<String>(); 14487 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14488 final Set<AsecInstallArgs> keys = processCids.keySet(); 14489 for (AsecInstallArgs args : keys) { 14490 String pkgName = args.getPackageName(); 14491 if (DEBUG_SD_INSTALL) 14492 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14493 // Delete package internally 14494 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14495 synchronized (mInstallLock) { 14496 boolean res = deletePackageLI(pkgName, null, false, null, null, 14497 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14498 if (res) { 14499 pkgList.add(pkgName); 14500 } else { 14501 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14502 failedList.add(args); 14503 } 14504 } 14505 } 14506 14507 // reader 14508 synchronized (mPackages) { 14509 // We didn't update the settings after removing each package; 14510 // write them now for all packages. 14511 mSettings.writeLPr(); 14512 } 14513 14514 // We have to absolutely send UPDATED_MEDIA_STATUS only 14515 // after confirming that all the receivers processed the ordered 14516 // broadcast when packages get disabled, force a gc to clean things up. 14517 // and unload all the containers. 14518 if (pkgList.size() > 0) { 14519 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14520 new IIntentReceiver.Stub() { 14521 public void performReceive(Intent intent, int resultCode, String data, 14522 Bundle extras, boolean ordered, boolean sticky, 14523 int sendingUser) throws RemoteException { 14524 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14525 reportStatus ? 1 : 0, 1, keys); 14526 mHandler.sendMessage(msg); 14527 } 14528 }); 14529 } else { 14530 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14531 keys); 14532 mHandler.sendMessage(msg); 14533 } 14534 } 14535 14536 private void loadPrivatePackages(VolumeInfo vol) { 14537 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14538 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14539 synchronized (mInstallLock) { 14540 synchronized (mPackages) { 14541 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14542 for (PackageSetting ps : packages) { 14543 final PackageParser.Package pkg; 14544 try { 14545 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14546 loaded.add(pkg.applicationInfo); 14547 } catch (PackageManagerException e) { 14548 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14549 } 14550 } 14551 14552 // TODO: regrant any permissions that changed based since original install 14553 14554 mSettings.writeLPr(); 14555 } 14556 } 14557 14558 Slog.d(TAG, "Loaded packages " + loaded); 14559 sendResourcesChangedBroadcast(true, false, loaded, null); 14560 } 14561 14562 private void unloadPrivatePackages(VolumeInfo vol) { 14563 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14564 synchronized (mInstallLock) { 14565 synchronized (mPackages) { 14566 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14567 for (PackageSetting ps : packages) { 14568 if (ps.pkg == null) continue; 14569 14570 final ApplicationInfo info = ps.pkg.applicationInfo; 14571 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14572 if (deletePackageLI(ps.name, null, false, null, null, 14573 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14574 unloaded.add(info); 14575 } else { 14576 Slog.w(TAG, "Failed to unload " + ps.codePath); 14577 } 14578 } 14579 14580 mSettings.writeLPr(); 14581 } 14582 } 14583 14584 Slog.d(TAG, "Unloaded packages " + unloaded); 14585 sendResourcesChangedBroadcast(false, false, unloaded, null); 14586 } 14587 14588 private void unfreezePackage(String packageName) { 14589 synchronized (mPackages) { 14590 final PackageSetting ps = mSettings.mPackages.get(packageName); 14591 if (ps != null) { 14592 ps.frozen = false; 14593 } 14594 } 14595 } 14596 14597 @Override 14598 public int movePackage(final String packageName, final String volumeUuid) { 14599 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14600 14601 final int moveId = mNextMoveId.getAndIncrement(); 14602 try { 14603 movePackageInternal(packageName, volumeUuid, moveId); 14604 } catch (PackageManagerException e) { 14605 Slog.d(TAG, "Failed to move " + packageName, e); 14606 mMoveCallbacks.notifyStatusChanged(moveId, 14607 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14608 } 14609 return moveId; 14610 } 14611 14612 private void movePackageInternal(final String packageName, final String volumeUuid, 14613 final int moveId) throws PackageManagerException { 14614 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14615 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14616 final PackageManager pm = mContext.getPackageManager(); 14617 14618 final boolean currentAsec; 14619 final String currentVolumeUuid; 14620 final File codeFile; 14621 final String installerPackageName; 14622 final String packageAbiOverride; 14623 final int appId; 14624 final String seinfo; 14625 final String label; 14626 14627 // reader 14628 synchronized (mPackages) { 14629 final PackageParser.Package pkg = mPackages.get(packageName); 14630 final PackageSetting ps = mSettings.mPackages.get(packageName); 14631 if (pkg == null || ps == null) { 14632 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14633 } 14634 14635 if (pkg.applicationInfo.isSystemApp()) { 14636 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14637 "Cannot move system application"); 14638 } 14639 14640 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14641 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14642 "Package already moved to " + volumeUuid); 14643 } 14644 14645 final File probe = new File(pkg.codePath); 14646 final File probeOat = new File(probe, "oat"); 14647 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14648 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14649 "Move only supported for modern cluster style installs"); 14650 } 14651 14652 if (ps.frozen) { 14653 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14654 "Failed to move already frozen package"); 14655 } 14656 ps.frozen = true; 14657 14658 currentAsec = pkg.applicationInfo.isForwardLocked() 14659 || pkg.applicationInfo.isExternalAsec(); 14660 currentVolumeUuid = ps.volumeUuid; 14661 codeFile = new File(pkg.codePath); 14662 installerPackageName = ps.installerPackageName; 14663 packageAbiOverride = ps.cpuAbiOverrideString; 14664 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14665 seinfo = pkg.applicationInfo.seinfo; 14666 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14667 } 14668 14669 // Now that we're guarded by frozen state, kill app during move 14670 killApplication(packageName, appId, "move pkg"); 14671 14672 final Bundle extras = new Bundle(); 14673 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14674 extras.putString(Intent.EXTRA_TITLE, label); 14675 mMoveCallbacks.notifyCreated(moveId, extras); 14676 14677 int installFlags; 14678 final boolean moveCompleteApp; 14679 final File measurePath; 14680 14681 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14682 installFlags = INSTALL_INTERNAL; 14683 moveCompleteApp = !currentAsec; 14684 measurePath = Environment.getDataAppDirectory(volumeUuid); 14685 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14686 installFlags = INSTALL_EXTERNAL; 14687 moveCompleteApp = false; 14688 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14689 } else { 14690 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14691 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14692 || !volume.isMountedWritable()) { 14693 unfreezePackage(packageName); 14694 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14695 "Move location not mounted private volume"); 14696 } 14697 14698 Preconditions.checkState(!currentAsec); 14699 14700 installFlags = INSTALL_INTERNAL; 14701 moveCompleteApp = true; 14702 measurePath = Environment.getDataAppDirectory(volumeUuid); 14703 } 14704 14705 final PackageStats stats = new PackageStats(null, -1); 14706 synchronized (mInstaller) { 14707 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14708 unfreezePackage(packageName); 14709 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14710 "Failed to measure package size"); 14711 } 14712 } 14713 14714 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14715 14716 final long startFreeBytes = measurePath.getFreeSpace(); 14717 final long sizeBytes; 14718 if (moveCompleteApp) { 14719 sizeBytes = stats.codeSize + stats.dataSize; 14720 } else { 14721 sizeBytes = stats.codeSize; 14722 } 14723 14724 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14725 unfreezePackage(packageName); 14726 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14727 "Not enough free space to move"); 14728 } 14729 14730 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14731 14732 final CountDownLatch installedLatch = new CountDownLatch(1); 14733 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14734 @Override 14735 public void onUserActionRequired(Intent intent) throws RemoteException { 14736 throw new IllegalStateException(); 14737 } 14738 14739 @Override 14740 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14741 Bundle extras) throws RemoteException { 14742 Slog.d(TAG, "Install result for move: " 14743 + PackageManager.installStatusToString(returnCode, msg)); 14744 14745 installedLatch.countDown(); 14746 14747 // Regardless of success or failure of the move operation, 14748 // always unfreeze the package 14749 unfreezePackage(packageName); 14750 14751 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14752 switch (status) { 14753 case PackageInstaller.STATUS_SUCCESS: 14754 mMoveCallbacks.notifyStatusChanged(moveId, 14755 PackageManager.MOVE_SUCCEEDED); 14756 break; 14757 case PackageInstaller.STATUS_FAILURE_STORAGE: 14758 mMoveCallbacks.notifyStatusChanged(moveId, 14759 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14760 break; 14761 default: 14762 mMoveCallbacks.notifyStatusChanged(moveId, 14763 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14764 break; 14765 } 14766 } 14767 }; 14768 14769 final MoveInfo move; 14770 if (moveCompleteApp) { 14771 // Kick off a thread to report progress estimates 14772 new Thread() { 14773 @Override 14774 public void run() { 14775 while (true) { 14776 try { 14777 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14778 break; 14779 } 14780 } catch (InterruptedException ignored) { 14781 } 14782 14783 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14784 final int progress = 10 + (int) MathUtils.constrain( 14785 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14786 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14787 } 14788 } 14789 }.start(); 14790 14791 final String dataAppName = codeFile.getName(); 14792 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14793 dataAppName, appId, seinfo); 14794 } else { 14795 move = null; 14796 } 14797 14798 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14799 14800 final Message msg = mHandler.obtainMessage(INIT_COPY); 14801 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14802 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14803 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14804 mHandler.sendMessage(msg); 14805 } 14806 14807 @Override 14808 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14809 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14810 14811 final int realMoveId = mNextMoveId.getAndIncrement(); 14812 final Bundle extras = new Bundle(); 14813 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14814 mMoveCallbacks.notifyCreated(realMoveId, extras); 14815 14816 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14817 @Override 14818 public void onCreated(int moveId, Bundle extras) { 14819 // Ignored 14820 } 14821 14822 @Override 14823 public void onStatusChanged(int moveId, int status, long estMillis) { 14824 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14825 } 14826 }; 14827 14828 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14829 storage.setPrimaryStorageUuid(volumeUuid, callback); 14830 return realMoveId; 14831 } 14832 14833 @Override 14834 public int getMoveStatus(int moveId) { 14835 mContext.enforceCallingOrSelfPermission( 14836 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14837 return mMoveCallbacks.mLastStatus.get(moveId); 14838 } 14839 14840 @Override 14841 public void registerMoveCallback(IPackageMoveObserver callback) { 14842 mContext.enforceCallingOrSelfPermission( 14843 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14844 mMoveCallbacks.register(callback); 14845 } 14846 14847 @Override 14848 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14849 mContext.enforceCallingOrSelfPermission( 14850 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14851 mMoveCallbacks.unregister(callback); 14852 } 14853 14854 @Override 14855 public boolean setInstallLocation(int loc) { 14856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14857 null); 14858 if (getInstallLocation() == loc) { 14859 return true; 14860 } 14861 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14862 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14863 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14864 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14865 return true; 14866 } 14867 return false; 14868 } 14869 14870 @Override 14871 public int getInstallLocation() { 14872 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14873 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14874 PackageHelper.APP_INSTALL_AUTO); 14875 } 14876 14877 /** Called by UserManagerService */ 14878 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14879 mDirtyUsers.remove(userHandle); 14880 mSettings.removeUserLPw(userHandle); 14881 mPendingBroadcasts.remove(userHandle); 14882 if (mInstaller != null) { 14883 // Technically, we shouldn't be doing this with the package lock 14884 // held. However, this is very rare, and there is already so much 14885 // other disk I/O going on, that we'll let it slide for now. 14886 final StorageManager storage = StorageManager.from(mContext); 14887 final List<VolumeInfo> vols = storage.getVolumes(); 14888 for (VolumeInfo vol : vols) { 14889 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14890 final String volumeUuid = vol.getFsUuid(); 14891 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14892 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14893 } 14894 } 14895 } 14896 mUserNeedsBadging.delete(userHandle); 14897 removeUnusedPackagesLILPw(userManager, userHandle); 14898 } 14899 14900 /** 14901 * We're removing userHandle and would like to remove any downloaded packages 14902 * that are no longer in use by any other user. 14903 * @param userHandle the user being removed 14904 */ 14905 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14906 final boolean DEBUG_CLEAN_APKS = false; 14907 int [] users = userManager.getUserIdsLPr(); 14908 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14909 while (psit.hasNext()) { 14910 PackageSetting ps = psit.next(); 14911 if (ps.pkg == null) { 14912 continue; 14913 } 14914 final String packageName = ps.pkg.packageName; 14915 // Skip over if system app 14916 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14917 continue; 14918 } 14919 if (DEBUG_CLEAN_APKS) { 14920 Slog.i(TAG, "Checking package " + packageName); 14921 } 14922 boolean keep = false; 14923 for (int i = 0; i < users.length; i++) { 14924 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14925 keep = true; 14926 if (DEBUG_CLEAN_APKS) { 14927 Slog.i(TAG, " Keeping package " + packageName + " for user " 14928 + users[i]); 14929 } 14930 break; 14931 } 14932 } 14933 if (!keep) { 14934 if (DEBUG_CLEAN_APKS) { 14935 Slog.i(TAG, " Removing package " + packageName); 14936 } 14937 mHandler.post(new Runnable() { 14938 public void run() { 14939 deletePackageX(packageName, userHandle, 0); 14940 } //end run 14941 }); 14942 } 14943 } 14944 } 14945 14946 /** Called by UserManagerService */ 14947 void createNewUserLILPw(int userHandle, File path) { 14948 if (mInstaller != null) { 14949 mInstaller.createUserConfig(userHandle); 14950 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14951 } 14952 } 14953 14954 void newUserCreatedLILPw(int userHandle) { 14955 // Adding a user requires updating runtime permissions for system apps. 14956 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14957 } 14958 14959 @Override 14960 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14961 mContext.enforceCallingOrSelfPermission( 14962 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14963 "Only package verification agents can read the verifier device identity"); 14964 14965 synchronized (mPackages) { 14966 return mSettings.getVerifierDeviceIdentityLPw(); 14967 } 14968 } 14969 14970 @Override 14971 public void setPermissionEnforced(String permission, boolean enforced) { 14972 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14973 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14974 synchronized (mPackages) { 14975 if (mSettings.mReadExternalStorageEnforced == null 14976 || mSettings.mReadExternalStorageEnforced != enforced) { 14977 mSettings.mReadExternalStorageEnforced = enforced; 14978 mSettings.writeLPr(); 14979 } 14980 } 14981 // kill any non-foreground processes so we restart them and 14982 // grant/revoke the GID. 14983 final IActivityManager am = ActivityManagerNative.getDefault(); 14984 if (am != null) { 14985 final long token = Binder.clearCallingIdentity(); 14986 try { 14987 am.killProcessesBelowForeground("setPermissionEnforcement"); 14988 } catch (RemoteException e) { 14989 } finally { 14990 Binder.restoreCallingIdentity(token); 14991 } 14992 } 14993 } else { 14994 throw new IllegalArgumentException("No selective enforcement for " + permission); 14995 } 14996 } 14997 14998 @Override 14999 @Deprecated 15000 public boolean isPermissionEnforced(String permission) { 15001 return true; 15002 } 15003 15004 @Override 15005 public boolean isStorageLow() { 15006 final long token = Binder.clearCallingIdentity(); 15007 try { 15008 final DeviceStorageMonitorInternal 15009 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15010 if (dsm != null) { 15011 return dsm.isMemoryLow(); 15012 } else { 15013 return false; 15014 } 15015 } finally { 15016 Binder.restoreCallingIdentity(token); 15017 } 15018 } 15019 15020 @Override 15021 public IPackageInstaller getPackageInstaller() { 15022 return mInstallerService; 15023 } 15024 15025 private boolean userNeedsBadging(int userId) { 15026 int index = mUserNeedsBadging.indexOfKey(userId); 15027 if (index < 0) { 15028 final UserInfo userInfo; 15029 final long token = Binder.clearCallingIdentity(); 15030 try { 15031 userInfo = sUserManager.getUserInfo(userId); 15032 } finally { 15033 Binder.restoreCallingIdentity(token); 15034 } 15035 final boolean b; 15036 if (userInfo != null && userInfo.isManagedProfile()) { 15037 b = true; 15038 } else { 15039 b = false; 15040 } 15041 mUserNeedsBadging.put(userId, b); 15042 return b; 15043 } 15044 return mUserNeedsBadging.valueAt(index); 15045 } 15046 15047 @Override 15048 public KeySet getKeySetByAlias(String packageName, String alias) { 15049 if (packageName == null || alias == null) { 15050 return null; 15051 } 15052 synchronized(mPackages) { 15053 final PackageParser.Package pkg = mPackages.get(packageName); 15054 if (pkg == null) { 15055 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15056 throw new IllegalArgumentException("Unknown package: " + packageName); 15057 } 15058 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15059 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15060 } 15061 } 15062 15063 @Override 15064 public KeySet getSigningKeySet(String packageName) { 15065 if (packageName == null) { 15066 return null; 15067 } 15068 synchronized(mPackages) { 15069 final PackageParser.Package pkg = mPackages.get(packageName); 15070 if (pkg == null) { 15071 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15072 throw new IllegalArgumentException("Unknown package: " + packageName); 15073 } 15074 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15075 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15076 throw new SecurityException("May not access signing KeySet of other apps."); 15077 } 15078 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15079 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15080 } 15081 } 15082 15083 @Override 15084 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15085 if (packageName == null || ks == null) { 15086 return false; 15087 } 15088 synchronized(mPackages) { 15089 final PackageParser.Package pkg = mPackages.get(packageName); 15090 if (pkg == null) { 15091 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15092 throw new IllegalArgumentException("Unknown package: " + packageName); 15093 } 15094 IBinder ksh = ks.getToken(); 15095 if (ksh instanceof KeySetHandle) { 15096 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15097 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15098 } 15099 return false; 15100 } 15101 } 15102 15103 @Override 15104 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15105 if (packageName == null || ks == null) { 15106 return false; 15107 } 15108 synchronized(mPackages) { 15109 final PackageParser.Package pkg = mPackages.get(packageName); 15110 if (pkg == null) { 15111 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15112 throw new IllegalArgumentException("Unknown package: " + packageName); 15113 } 15114 IBinder ksh = ks.getToken(); 15115 if (ksh instanceof KeySetHandle) { 15116 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15117 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15118 } 15119 return false; 15120 } 15121 } 15122 15123 public void getUsageStatsIfNoPackageUsageInfo() { 15124 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15125 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15126 if (usm == null) { 15127 throw new IllegalStateException("UsageStatsManager must be initialized"); 15128 } 15129 long now = System.currentTimeMillis(); 15130 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15131 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15132 String packageName = entry.getKey(); 15133 PackageParser.Package pkg = mPackages.get(packageName); 15134 if (pkg == null) { 15135 continue; 15136 } 15137 UsageStats usage = entry.getValue(); 15138 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15139 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15140 } 15141 } 15142 } 15143 15144 /** 15145 * Check and throw if the given before/after packages would be considered a 15146 * downgrade. 15147 */ 15148 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15149 throws PackageManagerException { 15150 if (after.versionCode < before.mVersionCode) { 15151 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15152 "Update version code " + after.versionCode + " is older than current " 15153 + before.mVersionCode); 15154 } else if (after.versionCode == before.mVersionCode) { 15155 if (after.baseRevisionCode < before.baseRevisionCode) { 15156 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15157 "Update base revision code " + after.baseRevisionCode 15158 + " is older than current " + before.baseRevisionCode); 15159 } 15160 15161 if (!ArrayUtils.isEmpty(after.splitNames)) { 15162 for (int i = 0; i < after.splitNames.length; i++) { 15163 final String splitName = after.splitNames[i]; 15164 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15165 if (j != -1) { 15166 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15167 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15168 "Update split " + splitName + " revision code " 15169 + after.splitRevisionCodes[i] + " is older than current " 15170 + before.splitRevisionCodes[j]); 15171 } 15172 } 15173 } 15174 } 15175 } 15176 } 15177 15178 private static class MoveCallbacks extends Handler { 15179 private static final int MSG_CREATED = 1; 15180 private static final int MSG_STATUS_CHANGED = 2; 15181 15182 private final RemoteCallbackList<IPackageMoveObserver> 15183 mCallbacks = new RemoteCallbackList<>(); 15184 15185 private final SparseIntArray mLastStatus = new SparseIntArray(); 15186 15187 public MoveCallbacks(Looper looper) { 15188 super(looper); 15189 } 15190 15191 public void register(IPackageMoveObserver callback) { 15192 mCallbacks.register(callback); 15193 } 15194 15195 public void unregister(IPackageMoveObserver callback) { 15196 mCallbacks.unregister(callback); 15197 } 15198 15199 @Override 15200 public void handleMessage(Message msg) { 15201 final SomeArgs args = (SomeArgs) msg.obj; 15202 final int n = mCallbacks.beginBroadcast(); 15203 for (int i = 0; i < n; i++) { 15204 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15205 try { 15206 invokeCallback(callback, msg.what, args); 15207 } catch (RemoteException ignored) { 15208 } 15209 } 15210 mCallbacks.finishBroadcast(); 15211 args.recycle(); 15212 } 15213 15214 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15215 throws RemoteException { 15216 switch (what) { 15217 case MSG_CREATED: { 15218 callback.onCreated(args.argi1, (Bundle) args.arg2); 15219 break; 15220 } 15221 case MSG_STATUS_CHANGED: { 15222 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15223 break; 15224 } 15225 } 15226 } 15227 15228 private void notifyCreated(int moveId, Bundle extras) { 15229 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15230 15231 final SomeArgs args = SomeArgs.obtain(); 15232 args.argi1 = moveId; 15233 args.arg2 = extras; 15234 obtainMessage(MSG_CREATED, args).sendToTarget(); 15235 } 15236 15237 private void notifyStatusChanged(int moveId, int status) { 15238 notifyStatusChanged(moveId, status, -1); 15239 } 15240 15241 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15242 Slog.v(TAG, "Move " + moveId + " status " + status); 15243 15244 final SomeArgs args = SomeArgs.obtain(); 15245 args.argi1 = moveId; 15246 args.argi2 = status; 15247 args.arg3 = estMillis; 15248 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15249 15250 synchronized (mLastStatus) { 15251 mLastStatus.put(moveId, status); 15252 } 15253 } 15254 } 15255} 15256