PackageManagerService.java revision 6503e69d1dfe425f292c6e982bb87cf12b1f4397
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 // Verify the ABIs haven't changed since we last deduced them. 6351 String oldPrimaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 6352 String oldSecondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi; 6353 6354 // TODO: The only purpose of this code is to update the native library paths 6355 // based on the final install location. We can simplify this and avoid having 6356 // to scan the package again. 6357 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */); 6358 if (!TextUtils.equals(oldPrimaryCpuAbi, pkg.applicationInfo.primaryCpuAbi)) { 6359 throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " (" 6360 + oldPrimaryCpuAbi + "-> " + pkg.applicationInfo.primaryCpuAbi); 6361 } 6362 6363 if (!TextUtils.equals(oldSecondaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi)) { 6364 throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " (" 6365 + oldSecondaryCpuAbi + "-> " + pkg.applicationInfo.secondaryCpuAbi); 6366 } 6367 } 6368 6369 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6370 final int[] userIds = sUserManager.getUserIds(); 6371 synchronized (mInstallLock) { 6372 // Create a native library symlink only if we have native libraries 6373 // and if the native libraries are 32 bit libraries. We do not provide 6374 // this symlink for 64 bit libraries. 6375 if (pkg.applicationInfo.primaryCpuAbi != null && 6376 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6377 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6378 for (int userId : userIds) { 6379 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6380 nativeLibPath, userId) < 0) { 6381 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6382 "Failed linking native library dir (user=" + userId + ")"); 6383 } 6384 } 6385 } 6386 } 6387 } 6388 6389 // This is a special case for the "system" package, where the ABI is 6390 // dictated by the zygote configuration (and init.rc). We should keep track 6391 // of this ABI so that we can deal with "normal" applications that run under 6392 // the same UID correctly. 6393 if (mPlatformPackage == pkg) { 6394 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6395 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6396 } 6397 6398 // If there's a mismatch between the abi-override in the package setting 6399 // and the abiOverride specified for the install. Warn about this because we 6400 // would've already compiled the app without taking the package setting into 6401 // account. 6402 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6403 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6404 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6405 " for package: " + pkg.packageName); 6406 } 6407 } 6408 6409 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6410 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6411 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6412 6413 // Copy the derived override back to the parsed package, so that we can 6414 // update the package settings accordingly. 6415 pkg.cpuAbiOverride = cpuAbiOverride; 6416 6417 if (DEBUG_ABI_SELECTION) { 6418 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6419 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6420 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6421 } 6422 6423 // Push the derived path down into PackageSettings so we know what to 6424 // clean up at uninstall time. 6425 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6426 6427 if (DEBUG_ABI_SELECTION) { 6428 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6429 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6430 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6431 } 6432 6433 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6434 // We don't do this here during boot because we can do it all 6435 // at once after scanning all existing packages. 6436 // 6437 // We also do this *before* we perform dexopt on this package, so that 6438 // we can avoid redundant dexopts, and also to make sure we've got the 6439 // code and package path correct. 6440 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6441 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6442 } 6443 6444 if ((scanFlags & SCAN_NO_DEX) == 0) { 6445 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6446 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6447 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6448 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6449 } 6450 } 6451 if (mFactoryTest && pkg.requestedPermissions.contains( 6452 android.Manifest.permission.FACTORY_TEST)) { 6453 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6454 } 6455 6456 ArrayList<PackageParser.Package> clientLibPkgs = null; 6457 6458 // writer 6459 synchronized (mPackages) { 6460 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6461 // Only system apps can add new shared libraries. 6462 if (pkg.libraryNames != null) { 6463 for (int i=0; i<pkg.libraryNames.size(); i++) { 6464 String name = pkg.libraryNames.get(i); 6465 boolean allowed = false; 6466 if (pkg.isUpdatedSystemApp()) { 6467 // New library entries can only be added through the 6468 // system image. This is important to get rid of a lot 6469 // of nasty edge cases: for example if we allowed a non- 6470 // system update of the app to add a library, then uninstalling 6471 // the update would make the library go away, and assumptions 6472 // we made such as through app install filtering would now 6473 // have allowed apps on the device which aren't compatible 6474 // with it. Better to just have the restriction here, be 6475 // conservative, and create many fewer cases that can negatively 6476 // impact the user experience. 6477 final PackageSetting sysPs = mSettings 6478 .getDisabledSystemPkgLPr(pkg.packageName); 6479 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6480 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6481 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6482 allowed = true; 6483 allowed = true; 6484 break; 6485 } 6486 } 6487 } 6488 } else { 6489 allowed = true; 6490 } 6491 if (allowed) { 6492 if (!mSharedLibraries.containsKey(name)) { 6493 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6494 } else if (!name.equals(pkg.packageName)) { 6495 Slog.w(TAG, "Package " + pkg.packageName + " library " 6496 + name + " already exists; skipping"); 6497 } 6498 } else { 6499 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6500 + name + " that is not declared on system image; skipping"); 6501 } 6502 } 6503 if ((scanFlags&SCAN_BOOTING) == 0) { 6504 // If we are not booting, we need to update any applications 6505 // that are clients of our shared library. If we are booting, 6506 // this will all be done once the scan is complete. 6507 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6508 } 6509 } 6510 } 6511 } 6512 6513 // We also need to dexopt any apps that are dependent on this library. Note that 6514 // if these fail, we should abort the install since installing the library will 6515 // result in some apps being broken. 6516 if (clientLibPkgs != null) { 6517 if ((scanFlags & SCAN_NO_DEX) == 0) { 6518 for (int i = 0; i < clientLibPkgs.size(); i++) { 6519 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6520 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6521 null /* instruction sets */, forceDex, 6522 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6523 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6524 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6525 "scanPackageLI failed to dexopt clientLibPkgs"); 6526 } 6527 } 6528 } 6529 } 6530 6531 // Also need to kill any apps that are dependent on the library. 6532 if (clientLibPkgs != null) { 6533 for (int i=0; i<clientLibPkgs.size(); i++) { 6534 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6535 killApplication(clientPkg.applicationInfo.packageName, 6536 clientPkg.applicationInfo.uid, "update lib"); 6537 } 6538 } 6539 6540 // writer 6541 synchronized (mPackages) { 6542 // We don't expect installation to fail beyond this point 6543 6544 // Add the new setting to mSettings 6545 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6546 // Add the new setting to mPackages 6547 mPackages.put(pkg.applicationInfo.packageName, pkg); 6548 // Make sure we don't accidentally delete its data. 6549 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6550 while (iter.hasNext()) { 6551 PackageCleanItem item = iter.next(); 6552 if (pkgName.equals(item.packageName)) { 6553 iter.remove(); 6554 } 6555 } 6556 6557 // Take care of first install / last update times. 6558 if (currentTime != 0) { 6559 if (pkgSetting.firstInstallTime == 0) { 6560 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6561 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6562 pkgSetting.lastUpdateTime = currentTime; 6563 } 6564 } else if (pkgSetting.firstInstallTime == 0) { 6565 // We need *something*. Take time time stamp of the file. 6566 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6567 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6568 if (scanFileTime != pkgSetting.timeStamp) { 6569 // A package on the system image has changed; consider this 6570 // to be an update. 6571 pkgSetting.lastUpdateTime = scanFileTime; 6572 } 6573 } 6574 6575 // Add the package's KeySets to the global KeySetManagerService 6576 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6577 try { 6578 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6579 if (pkg.mKeySetMapping != null) { 6580 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6581 if (pkg.mUpgradeKeySets != null) { 6582 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6583 } 6584 } 6585 } catch (NullPointerException e) { 6586 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6587 } catch (IllegalArgumentException e) { 6588 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6589 } 6590 6591 int N = pkg.providers.size(); 6592 StringBuilder r = null; 6593 int i; 6594 for (i=0; i<N; i++) { 6595 PackageParser.Provider p = pkg.providers.get(i); 6596 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6597 p.info.processName, pkg.applicationInfo.uid); 6598 mProviders.addProvider(p); 6599 p.syncable = p.info.isSyncable; 6600 if (p.info.authority != null) { 6601 String names[] = p.info.authority.split(";"); 6602 p.info.authority = null; 6603 for (int j = 0; j < names.length; j++) { 6604 if (j == 1 && p.syncable) { 6605 // We only want the first authority for a provider to possibly be 6606 // syncable, so if we already added this provider using a different 6607 // authority clear the syncable flag. We copy the provider before 6608 // changing it because the mProviders object contains a reference 6609 // to a provider that we don't want to change. 6610 // Only do this for the second authority since the resulting provider 6611 // object can be the same for all future authorities for this provider. 6612 p = new PackageParser.Provider(p); 6613 p.syncable = false; 6614 } 6615 if (!mProvidersByAuthority.containsKey(names[j])) { 6616 mProvidersByAuthority.put(names[j], p); 6617 if (p.info.authority == null) { 6618 p.info.authority = names[j]; 6619 } else { 6620 p.info.authority = p.info.authority + ";" + names[j]; 6621 } 6622 if (DEBUG_PACKAGE_SCANNING) { 6623 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6624 Log.d(TAG, "Registered content provider: " + names[j] 6625 + ", className = " + p.info.name + ", isSyncable = " 6626 + p.info.isSyncable); 6627 } 6628 } else { 6629 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6630 Slog.w(TAG, "Skipping provider name " + names[j] + 6631 " (in package " + pkg.applicationInfo.packageName + 6632 "): name already used by " 6633 + ((other != null && other.getComponentName() != null) 6634 ? other.getComponentName().getPackageName() : "?")); 6635 } 6636 } 6637 } 6638 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6639 if (r == null) { 6640 r = new StringBuilder(256); 6641 } else { 6642 r.append(' '); 6643 } 6644 r.append(p.info.name); 6645 } 6646 } 6647 if (r != null) { 6648 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6649 } 6650 6651 N = pkg.services.size(); 6652 r = null; 6653 for (i=0; i<N; i++) { 6654 PackageParser.Service s = pkg.services.get(i); 6655 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6656 s.info.processName, pkg.applicationInfo.uid); 6657 mServices.addService(s); 6658 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6659 if (r == null) { 6660 r = new StringBuilder(256); 6661 } else { 6662 r.append(' '); 6663 } 6664 r.append(s.info.name); 6665 } 6666 } 6667 if (r != null) { 6668 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6669 } 6670 6671 N = pkg.receivers.size(); 6672 r = null; 6673 for (i=0; i<N; i++) { 6674 PackageParser.Activity a = pkg.receivers.get(i); 6675 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6676 a.info.processName, pkg.applicationInfo.uid); 6677 mReceivers.addActivity(a, "receiver"); 6678 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6679 if (r == null) { 6680 r = new StringBuilder(256); 6681 } else { 6682 r.append(' '); 6683 } 6684 r.append(a.info.name); 6685 } 6686 } 6687 if (r != null) { 6688 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6689 } 6690 6691 N = pkg.activities.size(); 6692 r = null; 6693 for (i=0; i<N; i++) { 6694 PackageParser.Activity a = pkg.activities.get(i); 6695 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6696 a.info.processName, pkg.applicationInfo.uid); 6697 mActivities.addActivity(a, "activity"); 6698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6699 if (r == null) { 6700 r = new StringBuilder(256); 6701 } else { 6702 r.append(' '); 6703 } 6704 r.append(a.info.name); 6705 } 6706 } 6707 if (r != null) { 6708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6709 } 6710 6711 N = pkg.permissionGroups.size(); 6712 r = null; 6713 for (i=0; i<N; i++) { 6714 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6715 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6716 if (cur == null) { 6717 mPermissionGroups.put(pg.info.name, pg); 6718 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6719 if (r == null) { 6720 r = new StringBuilder(256); 6721 } else { 6722 r.append(' '); 6723 } 6724 r.append(pg.info.name); 6725 } 6726 } else { 6727 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6728 + pg.info.packageName + " ignored: original from " 6729 + cur.info.packageName); 6730 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6731 if (r == null) { 6732 r = new StringBuilder(256); 6733 } else { 6734 r.append(' '); 6735 } 6736 r.append("DUP:"); 6737 r.append(pg.info.name); 6738 } 6739 } 6740 } 6741 if (r != null) { 6742 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6743 } 6744 6745 N = pkg.permissions.size(); 6746 r = null; 6747 for (i=0; i<N; i++) { 6748 PackageParser.Permission p = pkg.permissions.get(i); 6749 6750 // Now that permission groups have a special meaning, we ignore permission 6751 // groups for legacy apps to prevent unexpected behavior. In particular, 6752 // permissions for one app being granted to someone just becuase they happen 6753 // to be in a group defined by another app (before this had no implications). 6754 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6755 p.group = mPermissionGroups.get(p.info.group); 6756 // Warn for a permission in an unknown group. 6757 if (p.info.group != null && p.group == null) { 6758 Slog.w(TAG, "Permission " + p.info.name + " from package " 6759 + p.info.packageName + " in an unknown group " + p.info.group); 6760 } 6761 } 6762 6763 ArrayMap<String, BasePermission> permissionMap = 6764 p.tree ? mSettings.mPermissionTrees 6765 : mSettings.mPermissions; 6766 BasePermission bp = permissionMap.get(p.info.name); 6767 6768 // Allow system apps to redefine non-system permissions 6769 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6770 final boolean currentOwnerIsSystem = (bp.perm != null 6771 && isSystemApp(bp.perm.owner)); 6772 if (isSystemApp(p.owner)) { 6773 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6774 // It's a built-in permission and no owner, take ownership now 6775 bp.packageSetting = pkgSetting; 6776 bp.perm = p; 6777 bp.uid = pkg.applicationInfo.uid; 6778 bp.sourcePackage = p.info.packageName; 6779 } else if (!currentOwnerIsSystem) { 6780 String msg = "New decl " + p.owner + " of permission " 6781 + p.info.name + " is system; overriding " + bp.sourcePackage; 6782 reportSettingsProblem(Log.WARN, msg); 6783 bp = null; 6784 } 6785 } 6786 } 6787 6788 if (bp == null) { 6789 bp = new BasePermission(p.info.name, p.info.packageName, 6790 BasePermission.TYPE_NORMAL); 6791 permissionMap.put(p.info.name, bp); 6792 } 6793 6794 if (bp.perm == null) { 6795 if (bp.sourcePackage == null 6796 || bp.sourcePackage.equals(p.info.packageName)) { 6797 BasePermission tree = findPermissionTreeLP(p.info.name); 6798 if (tree == null 6799 || tree.sourcePackage.equals(p.info.packageName)) { 6800 bp.packageSetting = pkgSetting; 6801 bp.perm = p; 6802 bp.uid = pkg.applicationInfo.uid; 6803 bp.sourcePackage = p.info.packageName; 6804 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6805 if (r == null) { 6806 r = new StringBuilder(256); 6807 } else { 6808 r.append(' '); 6809 } 6810 r.append(p.info.name); 6811 } 6812 } else { 6813 Slog.w(TAG, "Permission " + p.info.name + " from package " 6814 + p.info.packageName + " ignored: base tree " 6815 + tree.name + " is from package " 6816 + tree.sourcePackage); 6817 } 6818 } else { 6819 Slog.w(TAG, "Permission " + p.info.name + " from package " 6820 + p.info.packageName + " ignored: original from " 6821 + bp.sourcePackage); 6822 } 6823 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6824 if (r == null) { 6825 r = new StringBuilder(256); 6826 } else { 6827 r.append(' '); 6828 } 6829 r.append("DUP:"); 6830 r.append(p.info.name); 6831 } 6832 if (bp.perm == p) { 6833 bp.protectionLevel = p.info.protectionLevel; 6834 } 6835 } 6836 6837 if (r != null) { 6838 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6839 } 6840 6841 N = pkg.instrumentation.size(); 6842 r = null; 6843 for (i=0; i<N; i++) { 6844 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6845 a.info.packageName = pkg.applicationInfo.packageName; 6846 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6847 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6848 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6849 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6850 a.info.dataDir = pkg.applicationInfo.dataDir; 6851 6852 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6853 // need other information about the application, like the ABI and what not ? 6854 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6855 mInstrumentation.put(a.getComponentName(), a); 6856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6857 if (r == null) { 6858 r = new StringBuilder(256); 6859 } else { 6860 r.append(' '); 6861 } 6862 r.append(a.info.name); 6863 } 6864 } 6865 if (r != null) { 6866 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6867 } 6868 6869 if (pkg.protectedBroadcasts != null) { 6870 N = pkg.protectedBroadcasts.size(); 6871 for (i=0; i<N; i++) { 6872 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6873 } 6874 } 6875 6876 pkgSetting.setTimeStamp(scanFileTime); 6877 6878 // Create idmap files for pairs of (packages, overlay packages). 6879 // Note: "android", ie framework-res.apk, is handled by native layers. 6880 if (pkg.mOverlayTarget != null) { 6881 // This is an overlay package. 6882 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6883 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6884 mOverlays.put(pkg.mOverlayTarget, 6885 new ArrayMap<String, PackageParser.Package>()); 6886 } 6887 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6888 map.put(pkg.packageName, pkg); 6889 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6890 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6891 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6892 "scanPackageLI failed to createIdmap"); 6893 } 6894 } 6895 } else if (mOverlays.containsKey(pkg.packageName) && 6896 !pkg.packageName.equals("android")) { 6897 // This is a regular package, with one or more known overlay packages. 6898 createIdmapsForPackageLI(pkg); 6899 } 6900 } 6901 6902 return pkg; 6903 } 6904 6905 /** 6906 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6907 * is derived purely on the basis of the contents of {@code scanFile} and 6908 * {@code cpuAbiOverride}. 6909 * 6910 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6911 */ 6912 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6913 String cpuAbiOverride, boolean extractLibs) 6914 throws PackageManagerException { 6915 // TODO: We can probably be smarter about this stuff. For installed apps, 6916 // we can calculate this information at install time once and for all. For 6917 // system apps, we can probably assume that this information doesn't change 6918 // after the first boot scan. As things stand, we do lots of unnecessary work. 6919 6920 // Give ourselves some initial paths; we'll come back for another 6921 // pass once we've determined ABI below. 6922 setNativeLibraryPaths(pkg); 6923 6924 // We would never need to extract libs for forward-locked and external packages, 6925 // since the container service will do it for us. 6926 if (pkg.isForwardLocked() || isExternal(pkg)) { 6927 extractLibs = false; 6928 } 6929 6930 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6931 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6932 6933 NativeLibraryHelper.Handle handle = null; 6934 try { 6935 handle = NativeLibraryHelper.Handle.create(scanFile); 6936 // TODO(multiArch): This can be null for apps that didn't go through the 6937 // usual installation process. We can calculate it again, like we 6938 // do during install time. 6939 // 6940 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6941 // unnecessary. 6942 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6943 6944 // Null out the abis so that they can be recalculated. 6945 pkg.applicationInfo.primaryCpuAbi = null; 6946 pkg.applicationInfo.secondaryCpuAbi = null; 6947 if (isMultiArch(pkg.applicationInfo)) { 6948 // Warn if we've set an abiOverride for multi-lib packages.. 6949 // By definition, we need to copy both 32 and 64 bit libraries for 6950 // such packages. 6951 if (pkg.cpuAbiOverride != null 6952 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6953 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6954 } 6955 6956 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6957 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6958 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6959 if (extractLibs) { 6960 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6961 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6962 useIsaSpecificSubdirs); 6963 } else { 6964 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6965 } 6966 } 6967 6968 maybeThrowExceptionForMultiArchCopy( 6969 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6970 6971 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6972 if (extractLibs) { 6973 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6974 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6975 useIsaSpecificSubdirs); 6976 } else { 6977 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6978 } 6979 } 6980 6981 maybeThrowExceptionForMultiArchCopy( 6982 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6983 6984 if (abi64 >= 0) { 6985 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6986 } 6987 6988 if (abi32 >= 0) { 6989 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6990 if (abi64 >= 0) { 6991 pkg.applicationInfo.secondaryCpuAbi = abi; 6992 } else { 6993 pkg.applicationInfo.primaryCpuAbi = abi; 6994 } 6995 } 6996 } else { 6997 String[] abiList = (cpuAbiOverride != null) ? 6998 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6999 7000 // Enable gross and lame hacks for apps that are built with old 7001 // SDK tools. We must scan their APKs for renderscript bitcode and 7002 // not launch them if it's present. Don't bother checking on devices 7003 // that don't have 64 bit support. 7004 boolean needsRenderScriptOverride = false; 7005 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7006 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7007 abiList = Build.SUPPORTED_32_BIT_ABIS; 7008 needsRenderScriptOverride = true; 7009 } 7010 7011 final int copyRet; 7012 if (extractLibs) { 7013 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7014 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7015 } else { 7016 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7017 } 7018 7019 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7020 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7021 "Error unpackaging native libs for app, errorCode=" + copyRet); 7022 } 7023 7024 if (copyRet >= 0) { 7025 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7026 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7027 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7028 } else if (needsRenderScriptOverride) { 7029 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7030 } 7031 } 7032 } catch (IOException ioe) { 7033 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7034 } finally { 7035 IoUtils.closeQuietly(handle); 7036 } 7037 7038 // Now that we've calculated the ABIs and determined if it's an internal app, 7039 // we will go ahead and populate the nativeLibraryPath. 7040 setNativeLibraryPaths(pkg); 7041 } 7042 7043 /** 7044 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7045 * i.e, so that all packages can be run inside a single process if required. 7046 * 7047 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7048 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7049 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7050 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7051 * updating a package that belongs to a shared user. 7052 * 7053 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7054 * adds unnecessary complexity. 7055 */ 7056 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7057 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7058 String requiredInstructionSet = null; 7059 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7060 requiredInstructionSet = VMRuntime.getInstructionSet( 7061 scannedPackage.applicationInfo.primaryCpuAbi); 7062 } 7063 7064 PackageSetting requirer = null; 7065 for (PackageSetting ps : packagesForUser) { 7066 // If packagesForUser contains scannedPackage, we skip it. This will happen 7067 // when scannedPackage is an update of an existing package. Without this check, 7068 // we will never be able to change the ABI of any package belonging to a shared 7069 // user, even if it's compatible with other packages. 7070 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7071 if (ps.primaryCpuAbiString == null) { 7072 continue; 7073 } 7074 7075 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7076 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7077 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7078 // this but there's not much we can do. 7079 String errorMessage = "Instruction set mismatch, " 7080 + ((requirer == null) ? "[caller]" : requirer) 7081 + " requires " + requiredInstructionSet + " whereas " + ps 7082 + " requires " + instructionSet; 7083 Slog.w(TAG, errorMessage); 7084 } 7085 7086 if (requiredInstructionSet == null) { 7087 requiredInstructionSet = instructionSet; 7088 requirer = ps; 7089 } 7090 } 7091 } 7092 7093 if (requiredInstructionSet != null) { 7094 String adjustedAbi; 7095 if (requirer != null) { 7096 // requirer != null implies that either scannedPackage was null or that scannedPackage 7097 // did not require an ABI, in which case we have to adjust scannedPackage to match 7098 // the ABI of the set (which is the same as requirer's ABI) 7099 adjustedAbi = requirer.primaryCpuAbiString; 7100 if (scannedPackage != null) { 7101 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7102 } 7103 } else { 7104 // requirer == null implies that we're updating all ABIs in the set to 7105 // match scannedPackage. 7106 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7107 } 7108 7109 for (PackageSetting ps : packagesForUser) { 7110 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7111 if (ps.primaryCpuAbiString != null) { 7112 continue; 7113 } 7114 7115 ps.primaryCpuAbiString = adjustedAbi; 7116 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7117 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7118 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7119 7120 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7121 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7122 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7123 ps.primaryCpuAbiString = null; 7124 ps.pkg.applicationInfo.primaryCpuAbi = null; 7125 return; 7126 } else { 7127 mInstaller.rmdex(ps.codePathString, 7128 getDexCodeInstructionSet(getPreferredInstructionSet())); 7129 } 7130 } 7131 } 7132 } 7133 } 7134 } 7135 7136 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7137 synchronized (mPackages) { 7138 mResolverReplaced = true; 7139 // Set up information for custom user intent resolution activity. 7140 mResolveActivity.applicationInfo = pkg.applicationInfo; 7141 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7142 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7143 mResolveActivity.processName = pkg.applicationInfo.packageName; 7144 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7145 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7146 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7147 mResolveActivity.theme = 0; 7148 mResolveActivity.exported = true; 7149 mResolveActivity.enabled = true; 7150 mResolveInfo.activityInfo = mResolveActivity; 7151 mResolveInfo.priority = 0; 7152 mResolveInfo.preferredOrder = 0; 7153 mResolveInfo.match = 0; 7154 mResolveComponentName = mCustomResolverComponentName; 7155 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7156 mResolveComponentName); 7157 } 7158 } 7159 7160 private static String calculateBundledApkRoot(final String codePathString) { 7161 final File codePath = new File(codePathString); 7162 final File codeRoot; 7163 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7164 codeRoot = Environment.getRootDirectory(); 7165 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7166 codeRoot = Environment.getOemDirectory(); 7167 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7168 codeRoot = Environment.getVendorDirectory(); 7169 } else { 7170 // Unrecognized code path; take its top real segment as the apk root: 7171 // e.g. /something/app/blah.apk => /something 7172 try { 7173 File f = codePath.getCanonicalFile(); 7174 File parent = f.getParentFile(); // non-null because codePath is a file 7175 File tmp; 7176 while ((tmp = parent.getParentFile()) != null) { 7177 f = parent; 7178 parent = tmp; 7179 } 7180 codeRoot = f; 7181 Slog.w(TAG, "Unrecognized code path " 7182 + codePath + " - using " + codeRoot); 7183 } catch (IOException e) { 7184 // Can't canonicalize the code path -- shenanigans? 7185 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7186 return Environment.getRootDirectory().getPath(); 7187 } 7188 } 7189 return codeRoot.getPath(); 7190 } 7191 7192 /** 7193 * Derive and set the location of native libraries for the given package, 7194 * which varies depending on where and how the package was installed. 7195 */ 7196 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7197 final ApplicationInfo info = pkg.applicationInfo; 7198 final String codePath = pkg.codePath; 7199 final File codeFile = new File(codePath); 7200 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7201 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7202 7203 info.nativeLibraryRootDir = null; 7204 info.nativeLibraryRootRequiresIsa = false; 7205 info.nativeLibraryDir = null; 7206 info.secondaryNativeLibraryDir = null; 7207 7208 if (isApkFile(codeFile)) { 7209 // Monolithic install 7210 if (bundledApp) { 7211 // If "/system/lib64/apkname" exists, assume that is the per-package 7212 // native library directory to use; otherwise use "/system/lib/apkname". 7213 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7214 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7215 getPrimaryInstructionSet(info)); 7216 7217 // This is a bundled system app so choose the path based on the ABI. 7218 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7219 // is just the default path. 7220 final String apkName = deriveCodePathName(codePath); 7221 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7222 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7223 apkName).getAbsolutePath(); 7224 7225 if (info.secondaryCpuAbi != null) { 7226 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7227 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7228 secondaryLibDir, apkName).getAbsolutePath(); 7229 } 7230 } else if (asecApp) { 7231 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7232 .getAbsolutePath(); 7233 } else { 7234 final String apkName = deriveCodePathName(codePath); 7235 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7236 .getAbsolutePath(); 7237 } 7238 7239 info.nativeLibraryRootRequiresIsa = false; 7240 info.nativeLibraryDir = info.nativeLibraryRootDir; 7241 } else { 7242 // Cluster install 7243 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7244 info.nativeLibraryRootRequiresIsa = true; 7245 7246 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7247 getPrimaryInstructionSet(info)).getAbsolutePath(); 7248 7249 if (info.secondaryCpuAbi != null) { 7250 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7251 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7252 } 7253 } 7254 } 7255 7256 /** 7257 * Calculate the abis and roots for a bundled app. These can uniquely 7258 * be determined from the contents of the system partition, i.e whether 7259 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7260 * of this information, and instead assume that the system was built 7261 * sensibly. 7262 */ 7263 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7264 PackageSetting pkgSetting) { 7265 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7266 7267 // If "/system/lib64/apkname" exists, assume that is the per-package 7268 // native library directory to use; otherwise use "/system/lib/apkname". 7269 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7270 setBundledAppAbi(pkg, apkRoot, apkName); 7271 // pkgSetting might be null during rescan following uninstall of updates 7272 // to a bundled app, so accommodate that possibility. The settings in 7273 // that case will be established later from the parsed package. 7274 // 7275 // If the settings aren't null, sync them up with what we've just derived. 7276 // note that apkRoot isn't stored in the package settings. 7277 if (pkgSetting != null) { 7278 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7279 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7280 } 7281 } 7282 7283 /** 7284 * Deduces the ABI of a bundled app and sets the relevant fields on the 7285 * parsed pkg object. 7286 * 7287 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7288 * under which system libraries are installed. 7289 * @param apkName the name of the installed package. 7290 */ 7291 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7292 final File codeFile = new File(pkg.codePath); 7293 7294 final boolean has64BitLibs; 7295 final boolean has32BitLibs; 7296 if (isApkFile(codeFile)) { 7297 // Monolithic install 7298 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7299 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7300 } else { 7301 // Cluster install 7302 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7303 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7304 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7305 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7306 has64BitLibs = (new File(rootDir, isa)).exists(); 7307 } else { 7308 has64BitLibs = false; 7309 } 7310 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7311 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7312 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7313 has32BitLibs = (new File(rootDir, isa)).exists(); 7314 } else { 7315 has32BitLibs = false; 7316 } 7317 } 7318 7319 if (has64BitLibs && !has32BitLibs) { 7320 // The package has 64 bit libs, but not 32 bit libs. Its primary 7321 // ABI should be 64 bit. We can safely assume here that the bundled 7322 // native libraries correspond to the most preferred ABI in the list. 7323 7324 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7325 pkg.applicationInfo.secondaryCpuAbi = null; 7326 } else if (has32BitLibs && !has64BitLibs) { 7327 // The package has 32 bit libs but not 64 bit libs. Its primary 7328 // ABI should be 32 bit. 7329 7330 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7331 pkg.applicationInfo.secondaryCpuAbi = null; 7332 } else if (has32BitLibs && has64BitLibs) { 7333 // The application has both 64 and 32 bit bundled libraries. We check 7334 // here that the app declares multiArch support, and warn if it doesn't. 7335 // 7336 // We will be lenient here and record both ABIs. The primary will be the 7337 // ABI that's higher on the list, i.e, a device that's configured to prefer 7338 // 64 bit apps will see a 64 bit primary ABI, 7339 7340 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7341 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7342 } 7343 7344 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7346 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7347 } else { 7348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7349 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7350 } 7351 } else { 7352 pkg.applicationInfo.primaryCpuAbi = null; 7353 pkg.applicationInfo.secondaryCpuAbi = null; 7354 } 7355 } 7356 7357 private void killApplication(String pkgName, int appId, String reason) { 7358 // Request the ActivityManager to kill the process(only for existing packages) 7359 // so that we do not end up in a confused state while the user is still using the older 7360 // version of the application while the new one gets installed. 7361 IActivityManager am = ActivityManagerNative.getDefault(); 7362 if (am != null) { 7363 try { 7364 am.killApplicationWithAppId(pkgName, appId, reason); 7365 } catch (RemoteException e) { 7366 } 7367 } 7368 } 7369 7370 void removePackageLI(PackageSetting ps, boolean chatty) { 7371 if (DEBUG_INSTALL) { 7372 if (chatty) 7373 Log.d(TAG, "Removing package " + ps.name); 7374 } 7375 7376 // writer 7377 synchronized (mPackages) { 7378 mPackages.remove(ps.name); 7379 final PackageParser.Package pkg = ps.pkg; 7380 if (pkg != null) { 7381 cleanPackageDataStructuresLILPw(pkg, chatty); 7382 } 7383 } 7384 } 7385 7386 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7387 if (DEBUG_INSTALL) { 7388 if (chatty) 7389 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7390 } 7391 7392 // writer 7393 synchronized (mPackages) { 7394 mPackages.remove(pkg.applicationInfo.packageName); 7395 cleanPackageDataStructuresLILPw(pkg, chatty); 7396 } 7397 } 7398 7399 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7400 int N = pkg.providers.size(); 7401 StringBuilder r = null; 7402 int i; 7403 for (i=0; i<N; i++) { 7404 PackageParser.Provider p = pkg.providers.get(i); 7405 mProviders.removeProvider(p); 7406 if (p.info.authority == null) { 7407 7408 /* There was another ContentProvider with this authority when 7409 * this app was installed so this authority is null, 7410 * Ignore it as we don't have to unregister the provider. 7411 */ 7412 continue; 7413 } 7414 String names[] = p.info.authority.split(";"); 7415 for (int j = 0; j < names.length; j++) { 7416 if (mProvidersByAuthority.get(names[j]) == p) { 7417 mProvidersByAuthority.remove(names[j]); 7418 if (DEBUG_REMOVE) { 7419 if (chatty) 7420 Log.d(TAG, "Unregistered content provider: " + names[j] 7421 + ", className = " + p.info.name + ", isSyncable = " 7422 + p.info.isSyncable); 7423 } 7424 } 7425 } 7426 if (DEBUG_REMOVE && chatty) { 7427 if (r == null) { 7428 r = new StringBuilder(256); 7429 } else { 7430 r.append(' '); 7431 } 7432 r.append(p.info.name); 7433 } 7434 } 7435 if (r != null) { 7436 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7437 } 7438 7439 N = pkg.services.size(); 7440 r = null; 7441 for (i=0; i<N; i++) { 7442 PackageParser.Service s = pkg.services.get(i); 7443 mServices.removeService(s); 7444 if (chatty) { 7445 if (r == null) { 7446 r = new StringBuilder(256); 7447 } else { 7448 r.append(' '); 7449 } 7450 r.append(s.info.name); 7451 } 7452 } 7453 if (r != null) { 7454 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7455 } 7456 7457 N = pkg.receivers.size(); 7458 r = null; 7459 for (i=0; i<N; i++) { 7460 PackageParser.Activity a = pkg.receivers.get(i); 7461 mReceivers.removeActivity(a, "receiver"); 7462 if (DEBUG_REMOVE && chatty) { 7463 if (r == null) { 7464 r = new StringBuilder(256); 7465 } else { 7466 r.append(' '); 7467 } 7468 r.append(a.info.name); 7469 } 7470 } 7471 if (r != null) { 7472 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7473 } 7474 7475 N = pkg.activities.size(); 7476 r = null; 7477 for (i=0; i<N; i++) { 7478 PackageParser.Activity a = pkg.activities.get(i); 7479 mActivities.removeActivity(a, "activity"); 7480 if (DEBUG_REMOVE && chatty) { 7481 if (r == null) { 7482 r = new StringBuilder(256); 7483 } else { 7484 r.append(' '); 7485 } 7486 r.append(a.info.name); 7487 } 7488 } 7489 if (r != null) { 7490 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7491 } 7492 7493 N = pkg.permissions.size(); 7494 r = null; 7495 for (i=0; i<N; i++) { 7496 PackageParser.Permission p = pkg.permissions.get(i); 7497 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7498 if (bp == null) { 7499 bp = mSettings.mPermissionTrees.get(p.info.name); 7500 } 7501 if (bp != null && bp.perm == p) { 7502 bp.perm = null; 7503 if (DEBUG_REMOVE && chatty) { 7504 if (r == null) { 7505 r = new StringBuilder(256); 7506 } else { 7507 r.append(' '); 7508 } 7509 r.append(p.info.name); 7510 } 7511 } 7512 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7513 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7514 if (appOpPerms != null) { 7515 appOpPerms.remove(pkg.packageName); 7516 } 7517 } 7518 } 7519 if (r != null) { 7520 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7521 } 7522 7523 N = pkg.requestedPermissions.size(); 7524 r = null; 7525 for (i=0; i<N; i++) { 7526 String perm = pkg.requestedPermissions.get(i); 7527 BasePermission bp = mSettings.mPermissions.get(perm); 7528 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7529 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7530 if (appOpPerms != null) { 7531 appOpPerms.remove(pkg.packageName); 7532 if (appOpPerms.isEmpty()) { 7533 mAppOpPermissionPackages.remove(perm); 7534 } 7535 } 7536 } 7537 } 7538 if (r != null) { 7539 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7540 } 7541 7542 N = pkg.instrumentation.size(); 7543 r = null; 7544 for (i=0; i<N; i++) { 7545 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7546 mInstrumentation.remove(a.getComponentName()); 7547 if (DEBUG_REMOVE && chatty) { 7548 if (r == null) { 7549 r = new StringBuilder(256); 7550 } else { 7551 r.append(' '); 7552 } 7553 r.append(a.info.name); 7554 } 7555 } 7556 if (r != null) { 7557 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7558 } 7559 7560 r = null; 7561 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7562 // Only system apps can hold shared libraries. 7563 if (pkg.libraryNames != null) { 7564 for (i=0; i<pkg.libraryNames.size(); i++) { 7565 String name = pkg.libraryNames.get(i); 7566 SharedLibraryEntry cur = mSharedLibraries.get(name); 7567 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7568 mSharedLibraries.remove(name); 7569 if (DEBUG_REMOVE && chatty) { 7570 if (r == null) { 7571 r = new StringBuilder(256); 7572 } else { 7573 r.append(' '); 7574 } 7575 r.append(name); 7576 } 7577 } 7578 } 7579 } 7580 } 7581 if (r != null) { 7582 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7583 } 7584 } 7585 7586 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7587 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7588 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7589 return true; 7590 } 7591 } 7592 return false; 7593 } 7594 7595 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7596 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7597 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7598 7599 private void updatePermissionsLPw(String changingPkg, 7600 PackageParser.Package pkgInfo, int flags) { 7601 // Make sure there are no dangling permission trees. 7602 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7603 while (it.hasNext()) { 7604 final BasePermission bp = it.next(); 7605 if (bp.packageSetting == null) { 7606 // We may not yet have parsed the package, so just see if 7607 // we still know about its settings. 7608 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7609 } 7610 if (bp.packageSetting == null) { 7611 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7612 + " from package " + bp.sourcePackage); 7613 it.remove(); 7614 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7615 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7616 Slog.i(TAG, "Removing old permission tree: " + bp.name 7617 + " from package " + bp.sourcePackage); 7618 flags |= UPDATE_PERMISSIONS_ALL; 7619 it.remove(); 7620 } 7621 } 7622 } 7623 7624 // Make sure all dynamic permissions have been assigned to a package, 7625 // and make sure there are no dangling permissions. 7626 it = mSettings.mPermissions.values().iterator(); 7627 while (it.hasNext()) { 7628 final BasePermission bp = it.next(); 7629 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7630 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7631 + bp.name + " pkg=" + bp.sourcePackage 7632 + " info=" + bp.pendingInfo); 7633 if (bp.packageSetting == null && bp.pendingInfo != null) { 7634 final BasePermission tree = findPermissionTreeLP(bp.name); 7635 if (tree != null && tree.perm != null) { 7636 bp.packageSetting = tree.packageSetting; 7637 bp.perm = new PackageParser.Permission(tree.perm.owner, 7638 new PermissionInfo(bp.pendingInfo)); 7639 bp.perm.info.packageName = tree.perm.info.packageName; 7640 bp.perm.info.name = bp.name; 7641 bp.uid = tree.uid; 7642 } 7643 } 7644 } 7645 if (bp.packageSetting == null) { 7646 // We may not yet have parsed the package, so just see if 7647 // we still know about its settings. 7648 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7649 } 7650 if (bp.packageSetting == null) { 7651 Slog.w(TAG, "Removing dangling permission: " + bp.name 7652 + " from package " + bp.sourcePackage); 7653 it.remove(); 7654 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7655 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7656 Slog.i(TAG, "Removing old permission: " + bp.name 7657 + " from package " + bp.sourcePackage); 7658 flags |= UPDATE_PERMISSIONS_ALL; 7659 it.remove(); 7660 } 7661 } 7662 } 7663 7664 // Now update the permissions for all packages, in particular 7665 // replace the granted permissions of the system packages. 7666 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7667 for (PackageParser.Package pkg : mPackages.values()) { 7668 if (pkg != pkgInfo) { 7669 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7670 changingPkg); 7671 } 7672 } 7673 } 7674 7675 if (pkgInfo != null) { 7676 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7677 } 7678 } 7679 7680 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7681 String packageOfInterest) { 7682 // IMPORTANT: There are two types of permissions: install and runtime. 7683 // Install time permissions are granted when the app is installed to 7684 // all device users and users added in the future. Runtime permissions 7685 // are granted at runtime explicitly to specific users. Normal and signature 7686 // protected permissions are install time permissions. Dangerous permissions 7687 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7688 // otherwise they are runtime permissions. This function does not manage 7689 // runtime permissions except for the case an app targeting Lollipop MR1 7690 // being upgraded to target a newer SDK, in which case dangerous permissions 7691 // are transformed from install time to runtime ones. 7692 7693 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7694 if (ps == null) { 7695 return; 7696 } 7697 7698 PermissionsState permissionsState = ps.getPermissionsState(); 7699 PermissionsState origPermissions = permissionsState; 7700 7701 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7702 7703 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7704 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7705 7706 boolean changedInstallPermission = false; 7707 7708 if (replace) { 7709 ps.installPermissionsFixed = false; 7710 if (!ps.isSharedUser()) { 7711 origPermissions = new PermissionsState(permissionsState); 7712 permissionsState.reset(); 7713 } 7714 } 7715 7716 permissionsState.setGlobalGids(mGlobalGids); 7717 7718 final int N = pkg.requestedPermissions.size(); 7719 for (int i=0; i<N; i++) { 7720 final String name = pkg.requestedPermissions.get(i); 7721 final BasePermission bp = mSettings.mPermissions.get(name); 7722 7723 if (DEBUG_INSTALL) { 7724 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7725 } 7726 7727 if (bp == null || bp.packageSetting == null) { 7728 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7729 Slog.w(TAG, "Unknown permission " + name 7730 + " in package " + pkg.packageName); 7731 } 7732 continue; 7733 } 7734 7735 final String perm = bp.name; 7736 boolean allowedSig = false; 7737 int grant = GRANT_DENIED; 7738 7739 // Keep track of app op permissions. 7740 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7741 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7742 if (pkgs == null) { 7743 pkgs = new ArraySet<>(); 7744 mAppOpPermissionPackages.put(bp.name, pkgs); 7745 } 7746 pkgs.add(pkg.packageName); 7747 } 7748 7749 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7750 switch (level) { 7751 case PermissionInfo.PROTECTION_NORMAL: { 7752 // For all apps normal permissions are install time ones. 7753 grant = GRANT_INSTALL; 7754 } break; 7755 7756 case PermissionInfo.PROTECTION_DANGEROUS: { 7757 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7758 // For legacy apps dangerous permissions are install time ones. 7759 grant = GRANT_INSTALL_LEGACY; 7760 } else if (ps.isSystem()) { 7761 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7762 if (origPermissions.hasInstallPermission(bp.name)) { 7763 // If a system app had an install permission, then the app was 7764 // upgraded and we grant the permissions as runtime to all users. 7765 grant = GRANT_UPGRADE; 7766 upgradeUserIds = currentUserIds; 7767 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7768 // If users changed since the last permissions update for a 7769 // system app, we grant the permission as runtime to the new users. 7770 grant = GRANT_UPGRADE; 7771 upgradeUserIds = currentUserIds; 7772 for (int userId : updatedUserIds) { 7773 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7774 } 7775 } else { 7776 // Otherwise, we grant the permission as runtime if the app 7777 // already had it, i.e. we preserve runtime permissions. 7778 grant = GRANT_RUNTIME; 7779 } 7780 } else if (origPermissions.hasInstallPermission(bp.name)) { 7781 // For legacy apps that became modern, install becomes runtime. 7782 grant = GRANT_UPGRADE; 7783 upgradeUserIds = currentUserIds; 7784 } else if (replace) { 7785 // For upgraded modern apps keep runtime permissions unchanged. 7786 grant = GRANT_RUNTIME; 7787 } 7788 } break; 7789 7790 case PermissionInfo.PROTECTION_SIGNATURE: { 7791 // For all apps signature permissions are install time ones. 7792 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7793 if (allowedSig) { 7794 grant = GRANT_INSTALL; 7795 } 7796 } break; 7797 } 7798 7799 if (DEBUG_INSTALL) { 7800 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7801 } 7802 7803 if (grant != GRANT_DENIED) { 7804 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7805 // If this is an existing, non-system package, then 7806 // we can't add any new permissions to it. 7807 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7808 // Except... if this is a permission that was added 7809 // to the platform (note: need to only do this when 7810 // updating the platform). 7811 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7812 grant = GRANT_DENIED; 7813 } 7814 } 7815 } 7816 7817 switch (grant) { 7818 case GRANT_INSTALL: { 7819 // Revoke this as runtime permission to handle the case of 7820 // a runtime permssion being downgraded to an install one. 7821 for (int userId : UserManagerService.getInstance().getUserIds()) { 7822 if (origPermissions.getRuntimePermissionState( 7823 bp.name, userId) != null) { 7824 // Revoke the runtime permission and clear the flags. 7825 origPermissions.revokeRuntimePermission(bp, userId); 7826 origPermissions.updatePermissionFlags(bp, userId, 7827 PackageManager.MASK_PERMISSION_FLAGS, 0); 7828 // If we revoked a permission permission, we have to write. 7829 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7830 changedRuntimePermissionUserIds, userId); 7831 } 7832 } 7833 // Grant an install permission. 7834 if (permissionsState.grantInstallPermission(bp) != 7835 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7836 changedInstallPermission = true; 7837 } 7838 } break; 7839 7840 case GRANT_INSTALL_LEGACY: { 7841 // Grant an install permission. 7842 if (permissionsState.grantInstallPermission(bp) != 7843 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7844 changedInstallPermission = true; 7845 } 7846 } break; 7847 7848 case GRANT_RUNTIME: { 7849 // Grant previously granted runtime permissions. 7850 for (int userId : UserManagerService.getInstance().getUserIds()) { 7851 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7852 PermissionState permissionState = origPermissions 7853 .getRuntimePermissionState(bp.name, userId); 7854 final int flags = permissionState.getFlags(); 7855 if (permissionsState.grantRuntimePermission(bp, userId) == 7856 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7857 // If we cannot put the permission as it was, we have to write. 7858 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7859 changedRuntimePermissionUserIds, userId); 7860 } else { 7861 // System components not only get the permissions but 7862 // they are also fixed, so nothing can change that. 7863 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7864 ? flags 7865 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7866 // Propagate the permission flags. 7867 permissionsState.updatePermissionFlags(bp, userId, 7868 newFlags, newFlags); 7869 } 7870 } 7871 } 7872 } break; 7873 7874 case GRANT_UPGRADE: { 7875 // Grant runtime permissions for a previously held install permission. 7876 PermissionState permissionState = origPermissions 7877 .getInstallPermissionState(bp.name); 7878 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7879 7880 origPermissions.revokeInstallPermission(bp); 7881 // We will be transferring the permission flags, so clear them. 7882 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7883 PackageManager.MASK_PERMISSION_FLAGS, 0); 7884 7885 // If the permission is not to be promoted to runtime we ignore it and 7886 // also its other flags as they are not applicable to install permissions. 7887 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7888 for (int userId : upgradeUserIds) { 7889 if (permissionsState.grantRuntimePermission(bp, userId) != 7890 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7891 // System components not only get the permissions but 7892 // they are also fixed so nothing can change that. 7893 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7894 ? flags 7895 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7896 // Transfer the permission flags. 7897 permissionsState.updatePermissionFlags(bp, userId, 7898 newFlags, newFlags); 7899 // If we granted the permission, we have to write. 7900 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7901 changedRuntimePermissionUserIds, userId); 7902 } 7903 } 7904 } 7905 } break; 7906 7907 default: { 7908 if (packageOfInterest == null 7909 || packageOfInterest.equals(pkg.packageName)) { 7910 Slog.w(TAG, "Not granting permission " + perm 7911 + " to package " + pkg.packageName 7912 + " because it was previously installed without"); 7913 } 7914 } break; 7915 } 7916 } else { 7917 if (permissionsState.revokeInstallPermission(bp) != 7918 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7919 // Also drop the permission flags. 7920 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7921 PackageManager.MASK_PERMISSION_FLAGS, 0); 7922 changedInstallPermission = true; 7923 Slog.i(TAG, "Un-granting permission " + perm 7924 + " from package " + pkg.packageName 7925 + " (protectionLevel=" + bp.protectionLevel 7926 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7927 + ")"); 7928 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7929 // Don't print warning for app op permissions, since it is fine for them 7930 // not to be granted, there is a UI for the user to decide. 7931 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7932 Slog.w(TAG, "Not granting permission " + perm 7933 + " to package " + pkg.packageName 7934 + " (protectionLevel=" + bp.protectionLevel 7935 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7936 + ")"); 7937 } 7938 } 7939 } 7940 } 7941 7942 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7943 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7944 // This is the first that we have heard about this package, so the 7945 // permissions we have now selected are fixed until explicitly 7946 // changed. 7947 ps.installPermissionsFixed = true; 7948 } 7949 7950 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7951 7952 // Persist the runtime permissions state for users with changes. 7953 for (int userId : changedRuntimePermissionUserIds) { 7954 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7955 } 7956 } 7957 7958 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7959 boolean allowed = false; 7960 final int NP = PackageParser.NEW_PERMISSIONS.length; 7961 for (int ip=0; ip<NP; ip++) { 7962 final PackageParser.NewPermissionInfo npi 7963 = PackageParser.NEW_PERMISSIONS[ip]; 7964 if (npi.name.equals(perm) 7965 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7966 allowed = true; 7967 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7968 + pkg.packageName); 7969 break; 7970 } 7971 } 7972 return allowed; 7973 } 7974 7975 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7976 BasePermission bp, PermissionsState origPermissions) { 7977 boolean allowed; 7978 allowed = (compareSignatures( 7979 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7980 == PackageManager.SIGNATURE_MATCH) 7981 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7982 == PackageManager.SIGNATURE_MATCH); 7983 if (!allowed && (bp.protectionLevel 7984 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7985 if (isSystemApp(pkg)) { 7986 // For updated system applications, a system permission 7987 // is granted only if it had been defined by the original application. 7988 if (pkg.isUpdatedSystemApp()) { 7989 final PackageSetting sysPs = mSettings 7990 .getDisabledSystemPkgLPr(pkg.packageName); 7991 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7992 // If the original was granted this permission, we take 7993 // that grant decision as read and propagate it to the 7994 // update. 7995 if (sysPs.isPrivileged()) { 7996 allowed = true; 7997 } 7998 } else { 7999 // The system apk may have been updated with an older 8000 // version of the one on the data partition, but which 8001 // granted a new system permission that it didn't have 8002 // before. In this case we do want to allow the app to 8003 // now get the new permission if the ancestral apk is 8004 // privileged to get it. 8005 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8006 for (int j=0; 8007 j<sysPs.pkg.requestedPermissions.size(); j++) { 8008 if (perm.equals( 8009 sysPs.pkg.requestedPermissions.get(j))) { 8010 allowed = true; 8011 break; 8012 } 8013 } 8014 } 8015 } 8016 } else { 8017 allowed = isPrivilegedApp(pkg); 8018 } 8019 } 8020 } 8021 if (!allowed && (bp.protectionLevel 8022 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8023 // For development permissions, a development permission 8024 // is granted only if it was already granted. 8025 allowed = origPermissions.hasInstallPermission(perm); 8026 } 8027 return allowed; 8028 } 8029 8030 final class ActivityIntentResolver 8031 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8033 boolean defaultOnly, int userId) { 8034 if (!sUserManager.exists(userId)) return null; 8035 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8036 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8037 } 8038 8039 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8040 int userId) { 8041 if (!sUserManager.exists(userId)) return null; 8042 mFlags = flags; 8043 return super.queryIntent(intent, resolvedType, 8044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8045 } 8046 8047 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8048 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8049 if (!sUserManager.exists(userId)) return null; 8050 if (packageActivities == null) { 8051 return null; 8052 } 8053 mFlags = flags; 8054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8055 final int N = packageActivities.size(); 8056 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8057 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8058 8059 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8060 for (int i = 0; i < N; ++i) { 8061 intentFilters = packageActivities.get(i).intents; 8062 if (intentFilters != null && intentFilters.size() > 0) { 8063 PackageParser.ActivityIntentInfo[] array = 8064 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8065 intentFilters.toArray(array); 8066 listCut.add(array); 8067 } 8068 } 8069 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8070 } 8071 8072 public final void addActivity(PackageParser.Activity a, String type) { 8073 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8074 mActivities.put(a.getComponentName(), a); 8075 if (DEBUG_SHOW_INFO) 8076 Log.v( 8077 TAG, " " + type + " " + 8078 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8079 if (DEBUG_SHOW_INFO) 8080 Log.v(TAG, " Class=" + a.info.name); 8081 final int NI = a.intents.size(); 8082 for (int j=0; j<NI; j++) { 8083 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8084 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8085 intent.setPriority(0); 8086 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8087 + a.className + " with priority > 0, forcing to 0"); 8088 } 8089 if (DEBUG_SHOW_INFO) { 8090 Log.v(TAG, " IntentFilter:"); 8091 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8092 } 8093 if (!intent.debugCheck()) { 8094 Log.w(TAG, "==> For Activity " + a.info.name); 8095 } 8096 addFilter(intent); 8097 } 8098 } 8099 8100 public final void removeActivity(PackageParser.Activity a, String type) { 8101 mActivities.remove(a.getComponentName()); 8102 if (DEBUG_SHOW_INFO) { 8103 Log.v(TAG, " " + type + " " 8104 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8105 : a.info.name) + ":"); 8106 Log.v(TAG, " Class=" + a.info.name); 8107 } 8108 final int NI = a.intents.size(); 8109 for (int j=0; j<NI; j++) { 8110 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8111 if (DEBUG_SHOW_INFO) { 8112 Log.v(TAG, " IntentFilter:"); 8113 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8114 } 8115 removeFilter(intent); 8116 } 8117 } 8118 8119 @Override 8120 protected boolean allowFilterResult( 8121 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8122 ActivityInfo filterAi = filter.activity.info; 8123 for (int i=dest.size()-1; i>=0; i--) { 8124 ActivityInfo destAi = dest.get(i).activityInfo; 8125 if (destAi.name == filterAi.name 8126 && destAi.packageName == filterAi.packageName) { 8127 return false; 8128 } 8129 } 8130 return true; 8131 } 8132 8133 @Override 8134 protected ActivityIntentInfo[] newArray(int size) { 8135 return new ActivityIntentInfo[size]; 8136 } 8137 8138 @Override 8139 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8140 if (!sUserManager.exists(userId)) return true; 8141 PackageParser.Package p = filter.activity.owner; 8142 if (p != null) { 8143 PackageSetting ps = (PackageSetting)p.mExtras; 8144 if (ps != null) { 8145 // System apps are never considered stopped for purposes of 8146 // filtering, because there may be no way for the user to 8147 // actually re-launch them. 8148 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8149 && ps.getStopped(userId); 8150 } 8151 } 8152 return false; 8153 } 8154 8155 @Override 8156 protected boolean isPackageForFilter(String packageName, 8157 PackageParser.ActivityIntentInfo info) { 8158 return packageName.equals(info.activity.owner.packageName); 8159 } 8160 8161 @Override 8162 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8163 int match, int userId) { 8164 if (!sUserManager.exists(userId)) return null; 8165 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8166 return null; 8167 } 8168 final PackageParser.Activity activity = info.activity; 8169 if (mSafeMode && (activity.info.applicationInfo.flags 8170 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8171 return null; 8172 } 8173 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8174 if (ps == null) { 8175 return null; 8176 } 8177 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8178 ps.readUserState(userId), userId); 8179 if (ai == null) { 8180 return null; 8181 } 8182 final ResolveInfo res = new ResolveInfo(); 8183 res.activityInfo = ai; 8184 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8185 res.filter = info; 8186 } 8187 if (info != null) { 8188 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8189 } 8190 res.priority = info.getPriority(); 8191 res.preferredOrder = activity.owner.mPreferredOrder; 8192 //System.out.println("Result: " + res.activityInfo.className + 8193 // " = " + res.priority); 8194 res.match = match; 8195 res.isDefault = info.hasDefault; 8196 res.labelRes = info.labelRes; 8197 res.nonLocalizedLabel = info.nonLocalizedLabel; 8198 if (userNeedsBadging(userId)) { 8199 res.noResourceId = true; 8200 } else { 8201 res.icon = info.icon; 8202 } 8203 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8204 return res; 8205 } 8206 8207 @Override 8208 protected void sortResults(List<ResolveInfo> results) { 8209 Collections.sort(results, mResolvePrioritySorter); 8210 } 8211 8212 @Override 8213 protected void dumpFilter(PrintWriter out, String prefix, 8214 PackageParser.ActivityIntentInfo filter) { 8215 out.print(prefix); out.print( 8216 Integer.toHexString(System.identityHashCode(filter.activity))); 8217 out.print(' '); 8218 filter.activity.printComponentShortName(out); 8219 out.print(" filter "); 8220 out.println(Integer.toHexString(System.identityHashCode(filter))); 8221 } 8222 8223 @Override 8224 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8225 return filter.activity; 8226 } 8227 8228 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8229 PackageParser.Activity activity = (PackageParser.Activity)label; 8230 out.print(prefix); out.print( 8231 Integer.toHexString(System.identityHashCode(activity))); 8232 out.print(' '); 8233 activity.printComponentShortName(out); 8234 if (count > 1) { 8235 out.print(" ("); out.print(count); out.print(" filters)"); 8236 } 8237 out.println(); 8238 } 8239 8240// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8241// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8242// final List<ResolveInfo> retList = Lists.newArrayList(); 8243// while (i.hasNext()) { 8244// final ResolveInfo resolveInfo = i.next(); 8245// if (isEnabledLP(resolveInfo.activityInfo)) { 8246// retList.add(resolveInfo); 8247// } 8248// } 8249// return retList; 8250// } 8251 8252 // Keys are String (activity class name), values are Activity. 8253 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8254 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8255 private int mFlags; 8256 } 8257 8258 private final class ServiceIntentResolver 8259 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8260 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8261 boolean defaultOnly, int userId) { 8262 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8263 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8264 } 8265 8266 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8267 int userId) { 8268 if (!sUserManager.exists(userId)) return null; 8269 mFlags = flags; 8270 return super.queryIntent(intent, resolvedType, 8271 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8272 } 8273 8274 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8275 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8276 if (!sUserManager.exists(userId)) return null; 8277 if (packageServices == null) { 8278 return null; 8279 } 8280 mFlags = flags; 8281 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8282 final int N = packageServices.size(); 8283 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8284 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8285 8286 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8287 for (int i = 0; i < N; ++i) { 8288 intentFilters = packageServices.get(i).intents; 8289 if (intentFilters != null && intentFilters.size() > 0) { 8290 PackageParser.ServiceIntentInfo[] array = 8291 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8292 intentFilters.toArray(array); 8293 listCut.add(array); 8294 } 8295 } 8296 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8297 } 8298 8299 public final void addService(PackageParser.Service s) { 8300 mServices.put(s.getComponentName(), s); 8301 if (DEBUG_SHOW_INFO) { 8302 Log.v(TAG, " " 8303 + (s.info.nonLocalizedLabel != null 8304 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8305 Log.v(TAG, " Class=" + s.info.name); 8306 } 8307 final int NI = s.intents.size(); 8308 int j; 8309 for (j=0; j<NI; j++) { 8310 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8311 if (DEBUG_SHOW_INFO) { 8312 Log.v(TAG, " IntentFilter:"); 8313 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8314 } 8315 if (!intent.debugCheck()) { 8316 Log.w(TAG, "==> For Service " + s.info.name); 8317 } 8318 addFilter(intent); 8319 } 8320 } 8321 8322 public final void removeService(PackageParser.Service s) { 8323 mServices.remove(s.getComponentName()); 8324 if (DEBUG_SHOW_INFO) { 8325 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8326 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8327 Log.v(TAG, " Class=" + s.info.name); 8328 } 8329 final int NI = s.intents.size(); 8330 int j; 8331 for (j=0; j<NI; j++) { 8332 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8333 if (DEBUG_SHOW_INFO) { 8334 Log.v(TAG, " IntentFilter:"); 8335 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8336 } 8337 removeFilter(intent); 8338 } 8339 } 8340 8341 @Override 8342 protected boolean allowFilterResult( 8343 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8344 ServiceInfo filterSi = filter.service.info; 8345 for (int i=dest.size()-1; i>=0; i--) { 8346 ServiceInfo destAi = dest.get(i).serviceInfo; 8347 if (destAi.name == filterSi.name 8348 && destAi.packageName == filterSi.packageName) { 8349 return false; 8350 } 8351 } 8352 return true; 8353 } 8354 8355 @Override 8356 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8357 return new PackageParser.ServiceIntentInfo[size]; 8358 } 8359 8360 @Override 8361 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8362 if (!sUserManager.exists(userId)) return true; 8363 PackageParser.Package p = filter.service.owner; 8364 if (p != null) { 8365 PackageSetting ps = (PackageSetting)p.mExtras; 8366 if (ps != null) { 8367 // System apps are never considered stopped for purposes of 8368 // filtering, because there may be no way for the user to 8369 // actually re-launch them. 8370 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8371 && ps.getStopped(userId); 8372 } 8373 } 8374 return false; 8375 } 8376 8377 @Override 8378 protected boolean isPackageForFilter(String packageName, 8379 PackageParser.ServiceIntentInfo info) { 8380 return packageName.equals(info.service.owner.packageName); 8381 } 8382 8383 @Override 8384 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8385 int match, int userId) { 8386 if (!sUserManager.exists(userId)) return null; 8387 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8388 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8389 return null; 8390 } 8391 final PackageParser.Service service = info.service; 8392 if (mSafeMode && (service.info.applicationInfo.flags 8393 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8394 return null; 8395 } 8396 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8397 if (ps == null) { 8398 return null; 8399 } 8400 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8401 ps.readUserState(userId), userId); 8402 if (si == null) { 8403 return null; 8404 } 8405 final ResolveInfo res = new ResolveInfo(); 8406 res.serviceInfo = si; 8407 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8408 res.filter = filter; 8409 } 8410 res.priority = info.getPriority(); 8411 res.preferredOrder = service.owner.mPreferredOrder; 8412 res.match = match; 8413 res.isDefault = info.hasDefault; 8414 res.labelRes = info.labelRes; 8415 res.nonLocalizedLabel = info.nonLocalizedLabel; 8416 res.icon = info.icon; 8417 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8418 return res; 8419 } 8420 8421 @Override 8422 protected void sortResults(List<ResolveInfo> results) { 8423 Collections.sort(results, mResolvePrioritySorter); 8424 } 8425 8426 @Override 8427 protected void dumpFilter(PrintWriter out, String prefix, 8428 PackageParser.ServiceIntentInfo filter) { 8429 out.print(prefix); out.print( 8430 Integer.toHexString(System.identityHashCode(filter.service))); 8431 out.print(' '); 8432 filter.service.printComponentShortName(out); 8433 out.print(" filter "); 8434 out.println(Integer.toHexString(System.identityHashCode(filter))); 8435 } 8436 8437 @Override 8438 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8439 return filter.service; 8440 } 8441 8442 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8443 PackageParser.Service service = (PackageParser.Service)label; 8444 out.print(prefix); out.print( 8445 Integer.toHexString(System.identityHashCode(service))); 8446 out.print(' '); 8447 service.printComponentShortName(out); 8448 if (count > 1) { 8449 out.print(" ("); out.print(count); out.print(" filters)"); 8450 } 8451 out.println(); 8452 } 8453 8454// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8455// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8456// final List<ResolveInfo> retList = Lists.newArrayList(); 8457// while (i.hasNext()) { 8458// final ResolveInfo resolveInfo = (ResolveInfo) i; 8459// if (isEnabledLP(resolveInfo.serviceInfo)) { 8460// retList.add(resolveInfo); 8461// } 8462// } 8463// return retList; 8464// } 8465 8466 // Keys are String (activity class name), values are Activity. 8467 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8468 = new ArrayMap<ComponentName, PackageParser.Service>(); 8469 private int mFlags; 8470 }; 8471 8472 private final class ProviderIntentResolver 8473 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8474 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8475 boolean defaultOnly, int userId) { 8476 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8477 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8478 } 8479 8480 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8481 int userId) { 8482 if (!sUserManager.exists(userId)) 8483 return null; 8484 mFlags = flags; 8485 return super.queryIntent(intent, resolvedType, 8486 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8487 } 8488 8489 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8490 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8491 if (!sUserManager.exists(userId)) 8492 return null; 8493 if (packageProviders == null) { 8494 return null; 8495 } 8496 mFlags = flags; 8497 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8498 final int N = packageProviders.size(); 8499 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8500 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8501 8502 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8503 for (int i = 0; i < N; ++i) { 8504 intentFilters = packageProviders.get(i).intents; 8505 if (intentFilters != null && intentFilters.size() > 0) { 8506 PackageParser.ProviderIntentInfo[] array = 8507 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8508 intentFilters.toArray(array); 8509 listCut.add(array); 8510 } 8511 } 8512 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8513 } 8514 8515 public final void addProvider(PackageParser.Provider p) { 8516 if (mProviders.containsKey(p.getComponentName())) { 8517 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8518 return; 8519 } 8520 8521 mProviders.put(p.getComponentName(), p); 8522 if (DEBUG_SHOW_INFO) { 8523 Log.v(TAG, " " 8524 + (p.info.nonLocalizedLabel != null 8525 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8526 Log.v(TAG, " Class=" + p.info.name); 8527 } 8528 final int NI = p.intents.size(); 8529 int j; 8530 for (j = 0; j < NI; j++) { 8531 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8532 if (DEBUG_SHOW_INFO) { 8533 Log.v(TAG, " IntentFilter:"); 8534 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8535 } 8536 if (!intent.debugCheck()) { 8537 Log.w(TAG, "==> For Provider " + p.info.name); 8538 } 8539 addFilter(intent); 8540 } 8541 } 8542 8543 public final void removeProvider(PackageParser.Provider p) { 8544 mProviders.remove(p.getComponentName()); 8545 if (DEBUG_SHOW_INFO) { 8546 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8547 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8548 Log.v(TAG, " Class=" + p.info.name); 8549 } 8550 final int NI = p.intents.size(); 8551 int j; 8552 for (j = 0; j < NI; j++) { 8553 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8554 if (DEBUG_SHOW_INFO) { 8555 Log.v(TAG, " IntentFilter:"); 8556 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8557 } 8558 removeFilter(intent); 8559 } 8560 } 8561 8562 @Override 8563 protected boolean allowFilterResult( 8564 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8565 ProviderInfo filterPi = filter.provider.info; 8566 for (int i = dest.size() - 1; i >= 0; i--) { 8567 ProviderInfo destPi = dest.get(i).providerInfo; 8568 if (destPi.name == filterPi.name 8569 && destPi.packageName == filterPi.packageName) { 8570 return false; 8571 } 8572 } 8573 return true; 8574 } 8575 8576 @Override 8577 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8578 return new PackageParser.ProviderIntentInfo[size]; 8579 } 8580 8581 @Override 8582 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8583 if (!sUserManager.exists(userId)) 8584 return true; 8585 PackageParser.Package p = filter.provider.owner; 8586 if (p != null) { 8587 PackageSetting ps = (PackageSetting) p.mExtras; 8588 if (ps != null) { 8589 // System apps are never considered stopped for purposes of 8590 // filtering, because there may be no way for the user to 8591 // actually re-launch them. 8592 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8593 && ps.getStopped(userId); 8594 } 8595 } 8596 return false; 8597 } 8598 8599 @Override 8600 protected boolean isPackageForFilter(String packageName, 8601 PackageParser.ProviderIntentInfo info) { 8602 return packageName.equals(info.provider.owner.packageName); 8603 } 8604 8605 @Override 8606 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8607 int match, int userId) { 8608 if (!sUserManager.exists(userId)) 8609 return null; 8610 final PackageParser.ProviderIntentInfo info = filter; 8611 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8612 return null; 8613 } 8614 final PackageParser.Provider provider = info.provider; 8615 if (mSafeMode && (provider.info.applicationInfo.flags 8616 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8617 return null; 8618 } 8619 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8620 if (ps == null) { 8621 return null; 8622 } 8623 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8624 ps.readUserState(userId), userId); 8625 if (pi == null) { 8626 return null; 8627 } 8628 final ResolveInfo res = new ResolveInfo(); 8629 res.providerInfo = pi; 8630 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8631 res.filter = filter; 8632 } 8633 res.priority = info.getPriority(); 8634 res.preferredOrder = provider.owner.mPreferredOrder; 8635 res.match = match; 8636 res.isDefault = info.hasDefault; 8637 res.labelRes = info.labelRes; 8638 res.nonLocalizedLabel = info.nonLocalizedLabel; 8639 res.icon = info.icon; 8640 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8641 return res; 8642 } 8643 8644 @Override 8645 protected void sortResults(List<ResolveInfo> results) { 8646 Collections.sort(results, mResolvePrioritySorter); 8647 } 8648 8649 @Override 8650 protected void dumpFilter(PrintWriter out, String prefix, 8651 PackageParser.ProviderIntentInfo filter) { 8652 out.print(prefix); 8653 out.print( 8654 Integer.toHexString(System.identityHashCode(filter.provider))); 8655 out.print(' '); 8656 filter.provider.printComponentShortName(out); 8657 out.print(" filter "); 8658 out.println(Integer.toHexString(System.identityHashCode(filter))); 8659 } 8660 8661 @Override 8662 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8663 return filter.provider; 8664 } 8665 8666 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8667 PackageParser.Provider provider = (PackageParser.Provider)label; 8668 out.print(prefix); out.print( 8669 Integer.toHexString(System.identityHashCode(provider))); 8670 out.print(' '); 8671 provider.printComponentShortName(out); 8672 if (count > 1) { 8673 out.print(" ("); out.print(count); out.print(" filters)"); 8674 } 8675 out.println(); 8676 } 8677 8678 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8679 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8680 private int mFlags; 8681 }; 8682 8683 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8684 new Comparator<ResolveInfo>() { 8685 public int compare(ResolveInfo r1, ResolveInfo r2) { 8686 int v1 = r1.priority; 8687 int v2 = r2.priority; 8688 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8689 if (v1 != v2) { 8690 return (v1 > v2) ? -1 : 1; 8691 } 8692 v1 = r1.preferredOrder; 8693 v2 = r2.preferredOrder; 8694 if (v1 != v2) { 8695 return (v1 > v2) ? -1 : 1; 8696 } 8697 if (r1.isDefault != r2.isDefault) { 8698 return r1.isDefault ? -1 : 1; 8699 } 8700 v1 = r1.match; 8701 v2 = r2.match; 8702 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8703 if (v1 != v2) { 8704 return (v1 > v2) ? -1 : 1; 8705 } 8706 if (r1.system != r2.system) { 8707 return r1.system ? -1 : 1; 8708 } 8709 return 0; 8710 } 8711 }; 8712 8713 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8714 new Comparator<ProviderInfo>() { 8715 public int compare(ProviderInfo p1, ProviderInfo p2) { 8716 final int v1 = p1.initOrder; 8717 final int v2 = p2.initOrder; 8718 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8719 } 8720 }; 8721 8722 final void sendPackageBroadcast(final String action, final String pkg, 8723 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8724 final int[] userIds) { 8725 mHandler.post(new Runnable() { 8726 @Override 8727 public void run() { 8728 try { 8729 final IActivityManager am = ActivityManagerNative.getDefault(); 8730 if (am == null) return; 8731 final int[] resolvedUserIds; 8732 if (userIds == null) { 8733 resolvedUserIds = am.getRunningUserIds(); 8734 } else { 8735 resolvedUserIds = userIds; 8736 } 8737 for (int id : resolvedUserIds) { 8738 final Intent intent = new Intent(action, 8739 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8740 if (extras != null) { 8741 intent.putExtras(extras); 8742 } 8743 if (targetPkg != null) { 8744 intent.setPackage(targetPkg); 8745 } 8746 // Modify the UID when posting to other users 8747 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8748 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8749 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8750 intent.putExtra(Intent.EXTRA_UID, uid); 8751 } 8752 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8753 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8754 if (DEBUG_BROADCASTS) { 8755 RuntimeException here = new RuntimeException("here"); 8756 here.fillInStackTrace(); 8757 Slog.d(TAG, "Sending to user " + id + ": " 8758 + intent.toShortString(false, true, false, false) 8759 + " " + intent.getExtras(), here); 8760 } 8761 am.broadcastIntent(null, intent, null, finishedReceiver, 8762 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8763 finishedReceiver != null, false, id); 8764 } 8765 } catch (RemoteException ex) { 8766 } 8767 } 8768 }); 8769 } 8770 8771 /** 8772 * Check if the external storage media is available. This is true if there 8773 * is a mounted external storage medium or if the external storage is 8774 * emulated. 8775 */ 8776 private boolean isExternalMediaAvailable() { 8777 return mMediaMounted || Environment.isExternalStorageEmulated(); 8778 } 8779 8780 @Override 8781 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8782 // writer 8783 synchronized (mPackages) { 8784 if (!isExternalMediaAvailable()) { 8785 // If the external storage is no longer mounted at this point, 8786 // the caller may not have been able to delete all of this 8787 // packages files and can not delete any more. Bail. 8788 return null; 8789 } 8790 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8791 if (lastPackage != null) { 8792 pkgs.remove(lastPackage); 8793 } 8794 if (pkgs.size() > 0) { 8795 return pkgs.get(0); 8796 } 8797 } 8798 return null; 8799 } 8800 8801 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8802 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8803 userId, andCode ? 1 : 0, packageName); 8804 if (mSystemReady) { 8805 msg.sendToTarget(); 8806 } else { 8807 if (mPostSystemReadyMessages == null) { 8808 mPostSystemReadyMessages = new ArrayList<>(); 8809 } 8810 mPostSystemReadyMessages.add(msg); 8811 } 8812 } 8813 8814 void startCleaningPackages() { 8815 // reader 8816 synchronized (mPackages) { 8817 if (!isExternalMediaAvailable()) { 8818 return; 8819 } 8820 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8821 return; 8822 } 8823 } 8824 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8825 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8826 IActivityManager am = ActivityManagerNative.getDefault(); 8827 if (am != null) { 8828 try { 8829 am.startService(null, intent, null, UserHandle.USER_OWNER); 8830 } catch (RemoteException e) { 8831 } 8832 } 8833 } 8834 8835 @Override 8836 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8837 int installFlags, String installerPackageName, VerificationParams verificationParams, 8838 String packageAbiOverride) { 8839 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8840 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8841 } 8842 8843 @Override 8844 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8845 int installFlags, String installerPackageName, VerificationParams verificationParams, 8846 String packageAbiOverride, int userId) { 8847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8848 8849 final int callingUid = Binder.getCallingUid(); 8850 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8851 8852 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8853 try { 8854 if (observer != null) { 8855 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8856 } 8857 } catch (RemoteException re) { 8858 } 8859 return; 8860 } 8861 8862 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8863 installFlags |= PackageManager.INSTALL_FROM_ADB; 8864 8865 } else { 8866 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8867 // about installerPackageName. 8868 8869 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8870 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8871 } 8872 8873 UserHandle user; 8874 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8875 user = UserHandle.ALL; 8876 } else { 8877 user = new UserHandle(userId); 8878 } 8879 8880 // Only system components can circumvent runtime permissions when installing. 8881 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8882 && mContext.checkCallingOrSelfPermission(Manifest.permission 8883 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8884 throw new SecurityException("You need the " 8885 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8886 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8887 } 8888 8889 verificationParams.setInstallerUid(callingUid); 8890 8891 final File originFile = new File(originPath); 8892 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8893 8894 final Message msg = mHandler.obtainMessage(INIT_COPY); 8895 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8896 null, verificationParams, user, packageAbiOverride); 8897 mHandler.sendMessage(msg); 8898 } 8899 8900 void installStage(String packageName, File stagedDir, String stagedCid, 8901 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8902 String installerPackageName, int installerUid, UserHandle user) { 8903 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8904 params.referrerUri, installerUid, null); 8905 8906 final OriginInfo origin; 8907 if (stagedDir != null) { 8908 origin = OriginInfo.fromStagedFile(stagedDir); 8909 } else { 8910 origin = OriginInfo.fromStagedContainer(stagedCid); 8911 } 8912 8913 final Message msg = mHandler.obtainMessage(INIT_COPY); 8914 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8915 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8916 mHandler.sendMessage(msg); 8917 } 8918 8919 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8920 Bundle extras = new Bundle(1); 8921 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8922 8923 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8924 packageName, extras, null, null, new int[] {userId}); 8925 try { 8926 IActivityManager am = ActivityManagerNative.getDefault(); 8927 final boolean isSystem = 8928 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8929 if (isSystem && am.isUserRunning(userId, false)) { 8930 // The just-installed/enabled app is bundled on the system, so presumed 8931 // to be able to run automatically without needing an explicit launch. 8932 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8933 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8934 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8935 .setPackage(packageName); 8936 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8937 android.app.AppOpsManager.OP_NONE, false, false, userId); 8938 } 8939 } catch (RemoteException e) { 8940 // shouldn't happen 8941 Slog.w(TAG, "Unable to bootstrap installed package", e); 8942 } 8943 } 8944 8945 @Override 8946 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8947 int userId) { 8948 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8949 PackageSetting pkgSetting; 8950 final int uid = Binder.getCallingUid(); 8951 enforceCrossUserPermission(uid, userId, true, true, 8952 "setApplicationHiddenSetting for user " + userId); 8953 8954 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8955 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8956 return false; 8957 } 8958 8959 long callingId = Binder.clearCallingIdentity(); 8960 try { 8961 boolean sendAdded = false; 8962 boolean sendRemoved = false; 8963 // writer 8964 synchronized (mPackages) { 8965 pkgSetting = mSettings.mPackages.get(packageName); 8966 if (pkgSetting == null) { 8967 return false; 8968 } 8969 if (pkgSetting.getHidden(userId) != hidden) { 8970 pkgSetting.setHidden(hidden, userId); 8971 mSettings.writePackageRestrictionsLPr(userId); 8972 if (hidden) { 8973 sendRemoved = true; 8974 } else { 8975 sendAdded = true; 8976 } 8977 } 8978 } 8979 if (sendAdded) { 8980 sendPackageAddedForUser(packageName, pkgSetting, userId); 8981 return true; 8982 } 8983 if (sendRemoved) { 8984 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8985 "hiding pkg"); 8986 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8987 } 8988 } finally { 8989 Binder.restoreCallingIdentity(callingId); 8990 } 8991 return false; 8992 } 8993 8994 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8995 int userId) { 8996 final PackageRemovedInfo info = new PackageRemovedInfo(); 8997 info.removedPackage = packageName; 8998 info.removedUsers = new int[] {userId}; 8999 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9000 info.sendBroadcast(false, false, false); 9001 } 9002 9003 /** 9004 * Returns true if application is not found or there was an error. Otherwise it returns 9005 * the hidden state of the package for the given user. 9006 */ 9007 @Override 9008 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9009 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9010 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9011 false, "getApplicationHidden for user " + userId); 9012 PackageSetting pkgSetting; 9013 long callingId = Binder.clearCallingIdentity(); 9014 try { 9015 // writer 9016 synchronized (mPackages) { 9017 pkgSetting = mSettings.mPackages.get(packageName); 9018 if (pkgSetting == null) { 9019 return true; 9020 } 9021 return pkgSetting.getHidden(userId); 9022 } 9023 } finally { 9024 Binder.restoreCallingIdentity(callingId); 9025 } 9026 } 9027 9028 /** 9029 * @hide 9030 */ 9031 @Override 9032 public int installExistingPackageAsUser(String packageName, int userId) { 9033 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9034 null); 9035 PackageSetting pkgSetting; 9036 final int uid = Binder.getCallingUid(); 9037 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9038 + userId); 9039 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9040 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9041 } 9042 9043 long callingId = Binder.clearCallingIdentity(); 9044 try { 9045 boolean sendAdded = false; 9046 9047 // writer 9048 synchronized (mPackages) { 9049 pkgSetting = mSettings.mPackages.get(packageName); 9050 if (pkgSetting == null) { 9051 return PackageManager.INSTALL_FAILED_INVALID_URI; 9052 } 9053 if (!pkgSetting.getInstalled(userId)) { 9054 pkgSetting.setInstalled(true, userId); 9055 pkgSetting.setHidden(false, userId); 9056 mSettings.writePackageRestrictionsLPr(userId); 9057 sendAdded = true; 9058 } 9059 } 9060 9061 if (sendAdded) { 9062 sendPackageAddedForUser(packageName, pkgSetting, userId); 9063 } 9064 } finally { 9065 Binder.restoreCallingIdentity(callingId); 9066 } 9067 9068 return PackageManager.INSTALL_SUCCEEDED; 9069 } 9070 9071 boolean isUserRestricted(int userId, String restrictionKey) { 9072 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9073 if (restrictions.getBoolean(restrictionKey, false)) { 9074 Log.w(TAG, "User is restricted: " + restrictionKey); 9075 return true; 9076 } 9077 return false; 9078 } 9079 9080 @Override 9081 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9082 mContext.enforceCallingOrSelfPermission( 9083 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9084 "Only package verification agents can verify applications"); 9085 9086 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9087 final PackageVerificationResponse response = new PackageVerificationResponse( 9088 verificationCode, Binder.getCallingUid()); 9089 msg.arg1 = id; 9090 msg.obj = response; 9091 mHandler.sendMessage(msg); 9092 } 9093 9094 @Override 9095 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9096 long millisecondsToDelay) { 9097 mContext.enforceCallingOrSelfPermission( 9098 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9099 "Only package verification agents can extend verification timeouts"); 9100 9101 final PackageVerificationState state = mPendingVerification.get(id); 9102 final PackageVerificationResponse response = new PackageVerificationResponse( 9103 verificationCodeAtTimeout, Binder.getCallingUid()); 9104 9105 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9106 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9107 } 9108 if (millisecondsToDelay < 0) { 9109 millisecondsToDelay = 0; 9110 } 9111 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9112 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9113 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9114 } 9115 9116 if ((state != null) && !state.timeoutExtended()) { 9117 state.extendTimeout(); 9118 9119 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9120 msg.arg1 = id; 9121 msg.obj = response; 9122 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9123 } 9124 } 9125 9126 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9127 int verificationCode, UserHandle user) { 9128 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9129 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9130 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9131 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9132 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9133 9134 mContext.sendBroadcastAsUser(intent, user, 9135 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9136 } 9137 9138 private ComponentName matchComponentForVerifier(String packageName, 9139 List<ResolveInfo> receivers) { 9140 ActivityInfo targetReceiver = null; 9141 9142 final int NR = receivers.size(); 9143 for (int i = 0; i < NR; i++) { 9144 final ResolveInfo info = receivers.get(i); 9145 if (info.activityInfo == null) { 9146 continue; 9147 } 9148 9149 if (packageName.equals(info.activityInfo.packageName)) { 9150 targetReceiver = info.activityInfo; 9151 break; 9152 } 9153 } 9154 9155 if (targetReceiver == null) { 9156 return null; 9157 } 9158 9159 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9160 } 9161 9162 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9163 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9164 if (pkgInfo.verifiers.length == 0) { 9165 return null; 9166 } 9167 9168 final int N = pkgInfo.verifiers.length; 9169 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9170 for (int i = 0; i < N; i++) { 9171 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9172 9173 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9174 receivers); 9175 if (comp == null) { 9176 continue; 9177 } 9178 9179 final int verifierUid = getUidForVerifier(verifierInfo); 9180 if (verifierUid == -1) { 9181 continue; 9182 } 9183 9184 if (DEBUG_VERIFY) { 9185 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9186 + " with the correct signature"); 9187 } 9188 sufficientVerifiers.add(comp); 9189 verificationState.addSufficientVerifier(verifierUid); 9190 } 9191 9192 return sufficientVerifiers; 9193 } 9194 9195 private int getUidForVerifier(VerifierInfo verifierInfo) { 9196 synchronized (mPackages) { 9197 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9198 if (pkg == null) { 9199 return -1; 9200 } else if (pkg.mSignatures.length != 1) { 9201 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9202 + " has more than one signature; ignoring"); 9203 return -1; 9204 } 9205 9206 /* 9207 * If the public key of the package's signature does not match 9208 * our expected public key, then this is a different package and 9209 * we should skip. 9210 */ 9211 9212 final byte[] expectedPublicKey; 9213 try { 9214 final Signature verifierSig = pkg.mSignatures[0]; 9215 final PublicKey publicKey = verifierSig.getPublicKey(); 9216 expectedPublicKey = publicKey.getEncoded(); 9217 } catch (CertificateException e) { 9218 return -1; 9219 } 9220 9221 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9222 9223 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9224 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9225 + " does not have the expected public key; ignoring"); 9226 return -1; 9227 } 9228 9229 return pkg.applicationInfo.uid; 9230 } 9231 } 9232 9233 @Override 9234 public void finishPackageInstall(int token) { 9235 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9236 9237 if (DEBUG_INSTALL) { 9238 Slog.v(TAG, "BM finishing package install for " + token); 9239 } 9240 9241 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9242 mHandler.sendMessage(msg); 9243 } 9244 9245 /** 9246 * Get the verification agent timeout. 9247 * 9248 * @return verification timeout in milliseconds 9249 */ 9250 private long getVerificationTimeout() { 9251 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9252 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9253 DEFAULT_VERIFICATION_TIMEOUT); 9254 } 9255 9256 /** 9257 * Get the default verification agent response code. 9258 * 9259 * @return default verification response code 9260 */ 9261 private int getDefaultVerificationResponse() { 9262 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9263 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9264 DEFAULT_VERIFICATION_RESPONSE); 9265 } 9266 9267 /** 9268 * Check whether or not package verification has been enabled. 9269 * 9270 * @return true if verification should be performed 9271 */ 9272 private boolean isVerificationEnabled(int userId, int installFlags) { 9273 if (!DEFAULT_VERIFY_ENABLE) { 9274 return false; 9275 } 9276 9277 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9278 9279 // Check if installing from ADB 9280 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9281 // Do not run verification in a test harness environment 9282 if (ActivityManager.isRunningInTestHarness()) { 9283 return false; 9284 } 9285 if (ensureVerifyAppsEnabled) { 9286 return true; 9287 } 9288 // Check if the developer does not want package verification for ADB installs 9289 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9290 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9291 return false; 9292 } 9293 } 9294 9295 if (ensureVerifyAppsEnabled) { 9296 return true; 9297 } 9298 9299 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9300 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9301 } 9302 9303 @Override 9304 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9305 throws RemoteException { 9306 mContext.enforceCallingOrSelfPermission( 9307 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9308 "Only intentfilter verification agents can verify applications"); 9309 9310 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9311 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9312 Binder.getCallingUid(), verificationCode, failedDomains); 9313 msg.arg1 = id; 9314 msg.obj = response; 9315 mHandler.sendMessage(msg); 9316 } 9317 9318 @Override 9319 public int getIntentVerificationStatus(String packageName, int userId) { 9320 synchronized (mPackages) { 9321 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9322 } 9323 } 9324 9325 @Override 9326 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9327 boolean result = false; 9328 synchronized (mPackages) { 9329 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9330 } 9331 if (result) { 9332 scheduleWritePackageRestrictionsLocked(userId); 9333 } 9334 return result; 9335 } 9336 9337 @Override 9338 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9339 synchronized (mPackages) { 9340 return mSettings.getIntentFilterVerificationsLPr(packageName); 9341 } 9342 } 9343 9344 @Override 9345 public List<IntentFilter> getAllIntentFilters(String packageName) { 9346 if (TextUtils.isEmpty(packageName)) { 9347 return Collections.<IntentFilter>emptyList(); 9348 } 9349 synchronized (mPackages) { 9350 PackageParser.Package pkg = mPackages.get(packageName); 9351 if (pkg == null || pkg.activities == null) { 9352 return Collections.<IntentFilter>emptyList(); 9353 } 9354 final int count = pkg.activities.size(); 9355 ArrayList<IntentFilter> result = new ArrayList<>(); 9356 for (int n=0; n<count; n++) { 9357 PackageParser.Activity activity = pkg.activities.get(n); 9358 if (activity.intents != null || activity.intents.size() > 0) { 9359 result.addAll(activity.intents); 9360 } 9361 } 9362 return result; 9363 } 9364 } 9365 9366 @Override 9367 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9368 synchronized (mPackages) { 9369 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9370 if (packageName != null) { 9371 result |= updateIntentVerificationStatus(packageName, 9372 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9373 UserHandle.myUserId()); 9374 } 9375 return result; 9376 } 9377 } 9378 9379 @Override 9380 public String getDefaultBrowserPackageName(int userId) { 9381 synchronized (mPackages) { 9382 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9383 } 9384 } 9385 9386 /** 9387 * Get the "allow unknown sources" setting. 9388 * 9389 * @return the current "allow unknown sources" setting 9390 */ 9391 private int getUnknownSourcesSettings() { 9392 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9393 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9394 -1); 9395 } 9396 9397 @Override 9398 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9399 final int uid = Binder.getCallingUid(); 9400 // writer 9401 synchronized (mPackages) { 9402 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9403 if (targetPackageSetting == null) { 9404 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9405 } 9406 9407 PackageSetting installerPackageSetting; 9408 if (installerPackageName != null) { 9409 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9410 if (installerPackageSetting == null) { 9411 throw new IllegalArgumentException("Unknown installer package: " 9412 + installerPackageName); 9413 } 9414 } else { 9415 installerPackageSetting = null; 9416 } 9417 9418 Signature[] callerSignature; 9419 Object obj = mSettings.getUserIdLPr(uid); 9420 if (obj != null) { 9421 if (obj instanceof SharedUserSetting) { 9422 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9423 } else if (obj instanceof PackageSetting) { 9424 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9425 } else { 9426 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9427 } 9428 } else { 9429 throw new SecurityException("Unknown calling uid " + uid); 9430 } 9431 9432 // Verify: can't set installerPackageName to a package that is 9433 // not signed with the same cert as the caller. 9434 if (installerPackageSetting != null) { 9435 if (compareSignatures(callerSignature, 9436 installerPackageSetting.signatures.mSignatures) 9437 != PackageManager.SIGNATURE_MATCH) { 9438 throw new SecurityException( 9439 "Caller does not have same cert as new installer package " 9440 + installerPackageName); 9441 } 9442 } 9443 9444 // Verify: if target already has an installer package, it must 9445 // be signed with the same cert as the caller. 9446 if (targetPackageSetting.installerPackageName != null) { 9447 PackageSetting setting = mSettings.mPackages.get( 9448 targetPackageSetting.installerPackageName); 9449 // If the currently set package isn't valid, then it's always 9450 // okay to change it. 9451 if (setting != null) { 9452 if (compareSignatures(callerSignature, 9453 setting.signatures.mSignatures) 9454 != PackageManager.SIGNATURE_MATCH) { 9455 throw new SecurityException( 9456 "Caller does not have same cert as old installer package " 9457 + targetPackageSetting.installerPackageName); 9458 } 9459 } 9460 } 9461 9462 // Okay! 9463 targetPackageSetting.installerPackageName = installerPackageName; 9464 scheduleWriteSettingsLocked(); 9465 } 9466 } 9467 9468 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9469 // Queue up an async operation since the package installation may take a little while. 9470 mHandler.post(new Runnable() { 9471 public void run() { 9472 mHandler.removeCallbacks(this); 9473 // Result object to be returned 9474 PackageInstalledInfo res = new PackageInstalledInfo(); 9475 res.returnCode = currentStatus; 9476 res.uid = -1; 9477 res.pkg = null; 9478 res.removedInfo = new PackageRemovedInfo(); 9479 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9480 args.doPreInstall(res.returnCode); 9481 synchronized (mInstallLock) { 9482 installPackageLI(args, res); 9483 } 9484 args.doPostInstall(res.returnCode, res.uid); 9485 } 9486 9487 // A restore should be performed at this point if (a) the install 9488 // succeeded, (b) the operation is not an update, and (c) the new 9489 // package has not opted out of backup participation. 9490 final boolean update = res.removedInfo.removedPackage != null; 9491 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9492 boolean doRestore = !update 9493 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9494 9495 // Set up the post-install work request bookkeeping. This will be used 9496 // and cleaned up by the post-install event handling regardless of whether 9497 // there's a restore pass performed. Token values are >= 1. 9498 int token; 9499 if (mNextInstallToken < 0) mNextInstallToken = 1; 9500 token = mNextInstallToken++; 9501 9502 PostInstallData data = new PostInstallData(args, res); 9503 mRunningInstalls.put(token, data); 9504 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9505 9506 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9507 // Pass responsibility to the Backup Manager. It will perform a 9508 // restore if appropriate, then pass responsibility back to the 9509 // Package Manager to run the post-install observer callbacks 9510 // and broadcasts. 9511 IBackupManager bm = IBackupManager.Stub.asInterface( 9512 ServiceManager.getService(Context.BACKUP_SERVICE)); 9513 if (bm != null) { 9514 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9515 + " to BM for possible restore"); 9516 try { 9517 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9518 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9519 } else { 9520 doRestore = false; 9521 } 9522 } catch (RemoteException e) { 9523 // can't happen; the backup manager is local 9524 } catch (Exception e) { 9525 Slog.e(TAG, "Exception trying to enqueue restore", e); 9526 doRestore = false; 9527 } 9528 } else { 9529 Slog.e(TAG, "Backup Manager not found!"); 9530 doRestore = false; 9531 } 9532 } 9533 9534 if (!doRestore) { 9535 // No restore possible, or the Backup Manager was mysteriously not 9536 // available -- just fire the post-install work request directly. 9537 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9538 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9539 mHandler.sendMessage(msg); 9540 } 9541 } 9542 }); 9543 } 9544 9545 private abstract class HandlerParams { 9546 private static final int MAX_RETRIES = 4; 9547 9548 /** 9549 * Number of times startCopy() has been attempted and had a non-fatal 9550 * error. 9551 */ 9552 private int mRetries = 0; 9553 9554 /** User handle for the user requesting the information or installation. */ 9555 private final UserHandle mUser; 9556 9557 HandlerParams(UserHandle user) { 9558 mUser = user; 9559 } 9560 9561 UserHandle getUser() { 9562 return mUser; 9563 } 9564 9565 final boolean startCopy() { 9566 boolean res; 9567 try { 9568 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9569 9570 if (++mRetries > MAX_RETRIES) { 9571 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9572 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9573 handleServiceError(); 9574 return false; 9575 } else { 9576 handleStartCopy(); 9577 res = true; 9578 } 9579 } catch (RemoteException e) { 9580 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9581 mHandler.sendEmptyMessage(MCS_RECONNECT); 9582 res = false; 9583 } 9584 handleReturnCode(); 9585 return res; 9586 } 9587 9588 final void serviceError() { 9589 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9590 handleServiceError(); 9591 handleReturnCode(); 9592 } 9593 9594 abstract void handleStartCopy() throws RemoteException; 9595 abstract void handleServiceError(); 9596 abstract void handleReturnCode(); 9597 } 9598 9599 class MeasureParams extends HandlerParams { 9600 private final PackageStats mStats; 9601 private boolean mSuccess; 9602 9603 private final IPackageStatsObserver mObserver; 9604 9605 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9606 super(new UserHandle(stats.userHandle)); 9607 mObserver = observer; 9608 mStats = stats; 9609 } 9610 9611 @Override 9612 public String toString() { 9613 return "MeasureParams{" 9614 + Integer.toHexString(System.identityHashCode(this)) 9615 + " " + mStats.packageName + "}"; 9616 } 9617 9618 @Override 9619 void handleStartCopy() throws RemoteException { 9620 synchronized (mInstallLock) { 9621 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9622 } 9623 9624 if (mSuccess) { 9625 final boolean mounted; 9626 if (Environment.isExternalStorageEmulated()) { 9627 mounted = true; 9628 } else { 9629 final String status = Environment.getExternalStorageState(); 9630 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9631 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9632 } 9633 9634 if (mounted) { 9635 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9636 9637 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9638 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9639 9640 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9641 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9642 9643 // Always subtract cache size, since it's a subdirectory 9644 mStats.externalDataSize -= mStats.externalCacheSize; 9645 9646 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9647 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9648 9649 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9650 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9651 } 9652 } 9653 } 9654 9655 @Override 9656 void handleReturnCode() { 9657 if (mObserver != null) { 9658 try { 9659 mObserver.onGetStatsCompleted(mStats, mSuccess); 9660 } catch (RemoteException e) { 9661 Slog.i(TAG, "Observer no longer exists."); 9662 } 9663 } 9664 } 9665 9666 @Override 9667 void handleServiceError() { 9668 Slog.e(TAG, "Could not measure application " + mStats.packageName 9669 + " external storage"); 9670 } 9671 } 9672 9673 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9674 throws RemoteException { 9675 long result = 0; 9676 for (File path : paths) { 9677 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9678 } 9679 return result; 9680 } 9681 9682 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9683 for (File path : paths) { 9684 try { 9685 mcs.clearDirectory(path.getAbsolutePath()); 9686 } catch (RemoteException e) { 9687 } 9688 } 9689 } 9690 9691 static class OriginInfo { 9692 /** 9693 * Location where install is coming from, before it has been 9694 * copied/renamed into place. This could be a single monolithic APK 9695 * file, or a cluster directory. This location may be untrusted. 9696 */ 9697 final File file; 9698 final String cid; 9699 9700 /** 9701 * Flag indicating that {@link #file} or {@link #cid} has already been 9702 * staged, meaning downstream users don't need to defensively copy the 9703 * contents. 9704 */ 9705 final boolean staged; 9706 9707 /** 9708 * Flag indicating that {@link #file} or {@link #cid} is an already 9709 * installed app that is being moved. 9710 */ 9711 final boolean existing; 9712 9713 final String resolvedPath; 9714 final File resolvedFile; 9715 9716 static OriginInfo fromNothing() { 9717 return new OriginInfo(null, null, false, false); 9718 } 9719 9720 static OriginInfo fromUntrustedFile(File file) { 9721 return new OriginInfo(file, null, false, false); 9722 } 9723 9724 static OriginInfo fromExistingFile(File file) { 9725 return new OriginInfo(file, null, false, true); 9726 } 9727 9728 static OriginInfo fromStagedFile(File file) { 9729 return new OriginInfo(file, null, true, false); 9730 } 9731 9732 static OriginInfo fromStagedContainer(String cid) { 9733 return new OriginInfo(null, cid, true, false); 9734 } 9735 9736 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9737 this.file = file; 9738 this.cid = cid; 9739 this.staged = staged; 9740 this.existing = existing; 9741 9742 if (cid != null) { 9743 resolvedPath = PackageHelper.getSdDir(cid); 9744 resolvedFile = new File(resolvedPath); 9745 } else if (file != null) { 9746 resolvedPath = file.getAbsolutePath(); 9747 resolvedFile = file; 9748 } else { 9749 resolvedPath = null; 9750 resolvedFile = null; 9751 } 9752 } 9753 } 9754 9755 class MoveInfo { 9756 final int moveId; 9757 final String fromUuid; 9758 final String toUuid; 9759 final String packageName; 9760 final String dataAppName; 9761 final int appId; 9762 final String seinfo; 9763 9764 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9765 String dataAppName, int appId, String seinfo) { 9766 this.moveId = moveId; 9767 this.fromUuid = fromUuid; 9768 this.toUuid = toUuid; 9769 this.packageName = packageName; 9770 this.dataAppName = dataAppName; 9771 this.appId = appId; 9772 this.seinfo = seinfo; 9773 } 9774 } 9775 9776 class InstallParams extends HandlerParams { 9777 final OriginInfo origin; 9778 final MoveInfo move; 9779 final IPackageInstallObserver2 observer; 9780 int installFlags; 9781 final String installerPackageName; 9782 final String volumeUuid; 9783 final VerificationParams verificationParams; 9784 private InstallArgs mArgs; 9785 private int mRet; 9786 final String packageAbiOverride; 9787 9788 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9789 int installFlags, String installerPackageName, String volumeUuid, 9790 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9791 super(user); 9792 this.origin = origin; 9793 this.move = move; 9794 this.observer = observer; 9795 this.installFlags = installFlags; 9796 this.installerPackageName = installerPackageName; 9797 this.volumeUuid = volumeUuid; 9798 this.verificationParams = verificationParams; 9799 this.packageAbiOverride = packageAbiOverride; 9800 } 9801 9802 @Override 9803 public String toString() { 9804 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9805 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9806 } 9807 9808 public ManifestDigest getManifestDigest() { 9809 if (verificationParams == null) { 9810 return null; 9811 } 9812 return verificationParams.getManifestDigest(); 9813 } 9814 9815 private int installLocationPolicy(PackageInfoLite pkgLite) { 9816 String packageName = pkgLite.packageName; 9817 int installLocation = pkgLite.installLocation; 9818 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9819 // reader 9820 synchronized (mPackages) { 9821 PackageParser.Package pkg = mPackages.get(packageName); 9822 if (pkg != null) { 9823 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9824 // Check for downgrading. 9825 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9826 try { 9827 checkDowngrade(pkg, pkgLite); 9828 } catch (PackageManagerException e) { 9829 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9830 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9831 } 9832 } 9833 // Check for updated system application. 9834 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9835 if (onSd) { 9836 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9837 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9838 } 9839 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9840 } else { 9841 if (onSd) { 9842 // Install flag overrides everything. 9843 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9844 } 9845 // If current upgrade specifies particular preference 9846 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9847 // Application explicitly specified internal. 9848 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9849 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9850 // App explictly prefers external. Let policy decide 9851 } else { 9852 // Prefer previous location 9853 if (isExternal(pkg)) { 9854 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9855 } 9856 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9857 } 9858 } 9859 } else { 9860 // Invalid install. Return error code 9861 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9862 } 9863 } 9864 } 9865 // All the special cases have been taken care of. 9866 // Return result based on recommended install location. 9867 if (onSd) { 9868 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9869 } 9870 return pkgLite.recommendedInstallLocation; 9871 } 9872 9873 /* 9874 * Invoke remote method to get package information and install 9875 * location values. Override install location based on default 9876 * policy if needed and then create install arguments based 9877 * on the install location. 9878 */ 9879 public void handleStartCopy() throws RemoteException { 9880 int ret = PackageManager.INSTALL_SUCCEEDED; 9881 9882 // If we're already staged, we've firmly committed to an install location 9883 if (origin.staged) { 9884 if (origin.file != null) { 9885 installFlags |= PackageManager.INSTALL_INTERNAL; 9886 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9887 } else if (origin.cid != null) { 9888 installFlags |= PackageManager.INSTALL_EXTERNAL; 9889 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9890 } else { 9891 throw new IllegalStateException("Invalid stage location"); 9892 } 9893 } 9894 9895 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9896 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9897 9898 PackageInfoLite pkgLite = null; 9899 9900 if (onInt && onSd) { 9901 // Check if both bits are set. 9902 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9903 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9904 } else { 9905 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9906 packageAbiOverride); 9907 9908 /* 9909 * If we have too little free space, try to free cache 9910 * before giving up. 9911 */ 9912 if (!origin.staged && pkgLite.recommendedInstallLocation 9913 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9914 // TODO: focus freeing disk space on the target device 9915 final StorageManager storage = StorageManager.from(mContext); 9916 final long lowThreshold = storage.getStorageLowBytes( 9917 Environment.getDataDirectory()); 9918 9919 final long sizeBytes = mContainerService.calculateInstalledSize( 9920 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9921 9922 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9923 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9924 installFlags, packageAbiOverride); 9925 } 9926 9927 /* 9928 * The cache free must have deleted the file we 9929 * downloaded to install. 9930 * 9931 * TODO: fix the "freeCache" call to not delete 9932 * the file we care about. 9933 */ 9934 if (pkgLite.recommendedInstallLocation 9935 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9936 pkgLite.recommendedInstallLocation 9937 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9938 } 9939 } 9940 } 9941 9942 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9943 int loc = pkgLite.recommendedInstallLocation; 9944 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9945 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9946 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9947 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9948 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9949 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9950 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9951 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9952 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9953 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9954 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9955 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9956 } else { 9957 // Override with defaults if needed. 9958 loc = installLocationPolicy(pkgLite); 9959 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9960 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9961 } else if (!onSd && !onInt) { 9962 // Override install location with flags 9963 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9964 // Set the flag to install on external media. 9965 installFlags |= PackageManager.INSTALL_EXTERNAL; 9966 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9967 } else { 9968 // Make sure the flag for installing on external 9969 // media is unset 9970 installFlags |= PackageManager.INSTALL_INTERNAL; 9971 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9972 } 9973 } 9974 } 9975 } 9976 9977 final InstallArgs args = createInstallArgs(this); 9978 mArgs = args; 9979 9980 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9981 /* 9982 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9983 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9984 */ 9985 int userIdentifier = getUser().getIdentifier(); 9986 if (userIdentifier == UserHandle.USER_ALL 9987 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9988 userIdentifier = UserHandle.USER_OWNER; 9989 } 9990 9991 /* 9992 * Determine if we have any installed package verifiers. If we 9993 * do, then we'll defer to them to verify the packages. 9994 */ 9995 final int requiredUid = mRequiredVerifierPackage == null ? -1 9996 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9997 if (!origin.existing && requiredUid != -1 9998 && isVerificationEnabled(userIdentifier, installFlags)) { 9999 final Intent verification = new Intent( 10000 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10001 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10002 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10003 PACKAGE_MIME_TYPE); 10004 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10005 10006 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10007 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10008 0 /* TODO: Which userId? */); 10009 10010 if (DEBUG_VERIFY) { 10011 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10012 + verification.toString() + " with " + pkgLite.verifiers.length 10013 + " optional verifiers"); 10014 } 10015 10016 final int verificationId = mPendingVerificationToken++; 10017 10018 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10019 10020 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10021 installerPackageName); 10022 10023 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10024 installFlags); 10025 10026 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10027 pkgLite.packageName); 10028 10029 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10030 pkgLite.versionCode); 10031 10032 if (verificationParams != null) { 10033 if (verificationParams.getVerificationURI() != null) { 10034 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10035 verificationParams.getVerificationURI()); 10036 } 10037 if (verificationParams.getOriginatingURI() != null) { 10038 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10039 verificationParams.getOriginatingURI()); 10040 } 10041 if (verificationParams.getReferrer() != null) { 10042 verification.putExtra(Intent.EXTRA_REFERRER, 10043 verificationParams.getReferrer()); 10044 } 10045 if (verificationParams.getOriginatingUid() >= 0) { 10046 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10047 verificationParams.getOriginatingUid()); 10048 } 10049 if (verificationParams.getInstallerUid() >= 0) { 10050 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10051 verificationParams.getInstallerUid()); 10052 } 10053 } 10054 10055 final PackageVerificationState verificationState = new PackageVerificationState( 10056 requiredUid, args); 10057 10058 mPendingVerification.append(verificationId, verificationState); 10059 10060 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10061 receivers, verificationState); 10062 10063 /* 10064 * If any sufficient verifiers were listed in the package 10065 * manifest, attempt to ask them. 10066 */ 10067 if (sufficientVerifiers != null) { 10068 final int N = sufficientVerifiers.size(); 10069 if (N == 0) { 10070 Slog.i(TAG, "Additional verifiers required, but none installed."); 10071 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10072 } else { 10073 for (int i = 0; i < N; i++) { 10074 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10075 10076 final Intent sufficientIntent = new Intent(verification); 10077 sufficientIntent.setComponent(verifierComponent); 10078 10079 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10080 } 10081 } 10082 } 10083 10084 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10085 mRequiredVerifierPackage, receivers); 10086 if (ret == PackageManager.INSTALL_SUCCEEDED 10087 && mRequiredVerifierPackage != null) { 10088 /* 10089 * Send the intent to the required verification agent, 10090 * but only start the verification timeout after the 10091 * target BroadcastReceivers have run. 10092 */ 10093 verification.setComponent(requiredVerifierComponent); 10094 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10095 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10096 new BroadcastReceiver() { 10097 @Override 10098 public void onReceive(Context context, Intent intent) { 10099 final Message msg = mHandler 10100 .obtainMessage(CHECK_PENDING_VERIFICATION); 10101 msg.arg1 = verificationId; 10102 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10103 } 10104 }, null, 0, null, null); 10105 10106 /* 10107 * We don't want the copy to proceed until verification 10108 * succeeds, so null out this field. 10109 */ 10110 mArgs = null; 10111 } 10112 } else { 10113 /* 10114 * No package verification is enabled, so immediately start 10115 * the remote call to initiate copy using temporary file. 10116 */ 10117 ret = args.copyApk(mContainerService, true); 10118 } 10119 } 10120 10121 mRet = ret; 10122 } 10123 10124 @Override 10125 void handleReturnCode() { 10126 // If mArgs is null, then MCS couldn't be reached. When it 10127 // reconnects, it will try again to install. At that point, this 10128 // will succeed. 10129 if (mArgs != null) { 10130 processPendingInstall(mArgs, mRet); 10131 } 10132 } 10133 10134 @Override 10135 void handleServiceError() { 10136 mArgs = createInstallArgs(this); 10137 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10138 } 10139 10140 public boolean isForwardLocked() { 10141 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10142 } 10143 } 10144 10145 /** 10146 * Used during creation of InstallArgs 10147 * 10148 * @param installFlags package installation flags 10149 * @return true if should be installed on external storage 10150 */ 10151 private static boolean installOnExternalAsec(int installFlags) { 10152 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10153 return false; 10154 } 10155 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10156 return true; 10157 } 10158 return false; 10159 } 10160 10161 /** 10162 * Used during creation of InstallArgs 10163 * 10164 * @param installFlags package installation flags 10165 * @return true if should be installed as forward locked 10166 */ 10167 private static boolean installForwardLocked(int installFlags) { 10168 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10169 } 10170 10171 private InstallArgs createInstallArgs(InstallParams params) { 10172 if (params.move != null) { 10173 return new MoveInstallArgs(params); 10174 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10175 return new AsecInstallArgs(params); 10176 } else { 10177 return new FileInstallArgs(params); 10178 } 10179 } 10180 10181 /** 10182 * Create args that describe an existing installed package. Typically used 10183 * when cleaning up old installs, or used as a move source. 10184 */ 10185 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10186 String resourcePath, String[] instructionSets) { 10187 final boolean isInAsec; 10188 if (installOnExternalAsec(installFlags)) { 10189 /* Apps on SD card are always in ASEC containers. */ 10190 isInAsec = true; 10191 } else if (installForwardLocked(installFlags) 10192 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10193 /* 10194 * Forward-locked apps are only in ASEC containers if they're the 10195 * new style 10196 */ 10197 isInAsec = true; 10198 } else { 10199 isInAsec = false; 10200 } 10201 10202 if (isInAsec) { 10203 return new AsecInstallArgs(codePath, instructionSets, 10204 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10205 } else { 10206 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10207 } 10208 } 10209 10210 static abstract class InstallArgs { 10211 /** @see InstallParams#origin */ 10212 final OriginInfo origin; 10213 /** @see InstallParams#move */ 10214 final MoveInfo move; 10215 10216 final IPackageInstallObserver2 observer; 10217 // Always refers to PackageManager flags only 10218 final int installFlags; 10219 final String installerPackageName; 10220 final String volumeUuid; 10221 final ManifestDigest manifestDigest; 10222 final UserHandle user; 10223 final String abiOverride; 10224 10225 // The list of instruction sets supported by this app. This is currently 10226 // only used during the rmdex() phase to clean up resources. We can get rid of this 10227 // if we move dex files under the common app path. 10228 /* nullable */ String[] instructionSets; 10229 10230 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10231 int installFlags, String installerPackageName, String volumeUuid, 10232 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10233 String abiOverride) { 10234 this.origin = origin; 10235 this.move = move; 10236 this.installFlags = installFlags; 10237 this.observer = observer; 10238 this.installerPackageName = installerPackageName; 10239 this.volumeUuid = volumeUuid; 10240 this.manifestDigest = manifestDigest; 10241 this.user = user; 10242 this.instructionSets = instructionSets; 10243 this.abiOverride = abiOverride; 10244 } 10245 10246 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10247 abstract int doPreInstall(int status); 10248 10249 /** 10250 * Rename package into final resting place. All paths on the given 10251 * scanned package should be updated to reflect the rename. 10252 */ 10253 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10254 abstract int doPostInstall(int status, int uid); 10255 10256 /** @see PackageSettingBase#codePathString */ 10257 abstract String getCodePath(); 10258 /** @see PackageSettingBase#resourcePathString */ 10259 abstract String getResourcePath(); 10260 10261 // Need installer lock especially for dex file removal. 10262 abstract void cleanUpResourcesLI(); 10263 abstract boolean doPostDeleteLI(boolean delete); 10264 10265 /** 10266 * Called before the source arguments are copied. This is used mostly 10267 * for MoveParams when it needs to read the source file to put it in the 10268 * destination. 10269 */ 10270 int doPreCopy() { 10271 return PackageManager.INSTALL_SUCCEEDED; 10272 } 10273 10274 /** 10275 * Called after the source arguments are copied. This is used mostly for 10276 * MoveParams when it needs to read the source file to put it in the 10277 * destination. 10278 * 10279 * @return 10280 */ 10281 int doPostCopy(int uid) { 10282 return PackageManager.INSTALL_SUCCEEDED; 10283 } 10284 10285 protected boolean isFwdLocked() { 10286 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10287 } 10288 10289 protected boolean isExternalAsec() { 10290 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10291 } 10292 10293 UserHandle getUser() { 10294 return user; 10295 } 10296 } 10297 10298 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10299 if (!allCodePaths.isEmpty()) { 10300 if (instructionSets == null) { 10301 throw new IllegalStateException("instructionSet == null"); 10302 } 10303 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10304 for (String codePath : allCodePaths) { 10305 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10306 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10307 if (retCode < 0) { 10308 Slog.w(TAG, "Couldn't remove dex file for package: " 10309 + " at location " + codePath + ", retcode=" + retCode); 10310 // we don't consider this to be a failure of the core package deletion 10311 } 10312 } 10313 } 10314 } 10315 } 10316 10317 /** 10318 * Logic to handle installation of non-ASEC applications, including copying 10319 * and renaming logic. 10320 */ 10321 class FileInstallArgs extends InstallArgs { 10322 private File codeFile; 10323 private File resourceFile; 10324 10325 // Example topology: 10326 // /data/app/com.example/base.apk 10327 // /data/app/com.example/split_foo.apk 10328 // /data/app/com.example/lib/arm/libfoo.so 10329 // /data/app/com.example/lib/arm64/libfoo.so 10330 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10331 10332 /** New install */ 10333 FileInstallArgs(InstallParams params) { 10334 super(params.origin, params.move, params.observer, params.installFlags, 10335 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10336 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10337 if (isFwdLocked()) { 10338 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10339 } 10340 } 10341 10342 /** Existing install */ 10343 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10344 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10345 null); 10346 this.codeFile = (codePath != null) ? new File(codePath) : null; 10347 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10348 } 10349 10350 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10351 if (origin.staged) { 10352 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10353 codeFile = origin.file; 10354 resourceFile = origin.file; 10355 return PackageManager.INSTALL_SUCCEEDED; 10356 } 10357 10358 try { 10359 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10360 codeFile = tempDir; 10361 resourceFile = tempDir; 10362 } catch (IOException e) { 10363 Slog.w(TAG, "Failed to create copy file: " + e); 10364 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10365 } 10366 10367 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10368 @Override 10369 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10370 if (!FileUtils.isValidExtFilename(name)) { 10371 throw new IllegalArgumentException("Invalid filename: " + name); 10372 } 10373 try { 10374 final File file = new File(codeFile, name); 10375 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10376 O_RDWR | O_CREAT, 0644); 10377 Os.chmod(file.getAbsolutePath(), 0644); 10378 return new ParcelFileDescriptor(fd); 10379 } catch (ErrnoException e) { 10380 throw new RemoteException("Failed to open: " + e.getMessage()); 10381 } 10382 } 10383 }; 10384 10385 int ret = PackageManager.INSTALL_SUCCEEDED; 10386 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10387 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10388 Slog.e(TAG, "Failed to copy package"); 10389 return ret; 10390 } 10391 10392 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10393 NativeLibraryHelper.Handle handle = null; 10394 try { 10395 handle = NativeLibraryHelper.Handle.create(codeFile); 10396 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10397 abiOverride); 10398 } catch (IOException e) { 10399 Slog.e(TAG, "Copying native libraries failed", e); 10400 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10401 } finally { 10402 IoUtils.closeQuietly(handle); 10403 } 10404 10405 return ret; 10406 } 10407 10408 int doPreInstall(int status) { 10409 if (status != PackageManager.INSTALL_SUCCEEDED) { 10410 cleanUp(); 10411 } 10412 return status; 10413 } 10414 10415 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10416 if (status != PackageManager.INSTALL_SUCCEEDED) { 10417 cleanUp(); 10418 return false; 10419 } 10420 10421 final File targetDir = codeFile.getParentFile(); 10422 final File beforeCodeFile = codeFile; 10423 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10424 10425 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10426 try { 10427 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10428 } catch (ErrnoException e) { 10429 Slog.d(TAG, "Failed to rename", e); 10430 return false; 10431 } 10432 10433 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10434 Slog.d(TAG, "Failed to restorecon"); 10435 return false; 10436 } 10437 10438 // Reflect the rename internally 10439 codeFile = afterCodeFile; 10440 resourceFile = afterCodeFile; 10441 10442 // Reflect the rename in scanned details 10443 pkg.codePath = afterCodeFile.getAbsolutePath(); 10444 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10445 pkg.baseCodePath); 10446 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10447 pkg.splitCodePaths); 10448 10449 // Reflect the rename in app info 10450 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10451 pkg.applicationInfo.setCodePath(pkg.codePath); 10452 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10453 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10454 pkg.applicationInfo.setResourcePath(pkg.codePath); 10455 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10456 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10457 10458 return true; 10459 } 10460 10461 int doPostInstall(int status, int uid) { 10462 if (status != PackageManager.INSTALL_SUCCEEDED) { 10463 cleanUp(); 10464 } 10465 return status; 10466 } 10467 10468 @Override 10469 String getCodePath() { 10470 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10471 } 10472 10473 @Override 10474 String getResourcePath() { 10475 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10476 } 10477 10478 private boolean cleanUp() { 10479 if (codeFile == null || !codeFile.exists()) { 10480 return false; 10481 } 10482 10483 if (codeFile.isDirectory()) { 10484 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10485 } else { 10486 codeFile.delete(); 10487 } 10488 10489 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10490 resourceFile.delete(); 10491 } 10492 10493 return true; 10494 } 10495 10496 void cleanUpResourcesLI() { 10497 // Try enumerating all code paths before deleting 10498 List<String> allCodePaths = Collections.EMPTY_LIST; 10499 if (codeFile != null && codeFile.exists()) { 10500 try { 10501 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10502 allCodePaths = pkg.getAllCodePaths(); 10503 } catch (PackageParserException e) { 10504 // Ignored; we tried our best 10505 } 10506 } 10507 10508 cleanUp(); 10509 removeDexFiles(allCodePaths, instructionSets); 10510 } 10511 10512 boolean doPostDeleteLI(boolean delete) { 10513 // XXX err, shouldn't we respect the delete flag? 10514 cleanUpResourcesLI(); 10515 return true; 10516 } 10517 } 10518 10519 private boolean isAsecExternal(String cid) { 10520 final String asecPath = PackageHelper.getSdFilesystem(cid); 10521 return !asecPath.startsWith(mAsecInternalPath); 10522 } 10523 10524 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10525 PackageManagerException { 10526 if (copyRet < 0) { 10527 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10528 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10529 throw new PackageManagerException(copyRet, message); 10530 } 10531 } 10532 } 10533 10534 /** 10535 * Extract the MountService "container ID" from the full code path of an 10536 * .apk. 10537 */ 10538 static String cidFromCodePath(String fullCodePath) { 10539 int eidx = fullCodePath.lastIndexOf("/"); 10540 String subStr1 = fullCodePath.substring(0, eidx); 10541 int sidx = subStr1.lastIndexOf("/"); 10542 return subStr1.substring(sidx+1, eidx); 10543 } 10544 10545 /** 10546 * Logic to handle installation of ASEC applications, including copying and 10547 * renaming logic. 10548 */ 10549 class AsecInstallArgs extends InstallArgs { 10550 static final String RES_FILE_NAME = "pkg.apk"; 10551 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10552 10553 String cid; 10554 String packagePath; 10555 String resourcePath; 10556 10557 /** New install */ 10558 AsecInstallArgs(InstallParams params) { 10559 super(params.origin, params.move, params.observer, params.installFlags, 10560 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10561 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10562 } 10563 10564 /** Existing install */ 10565 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10566 boolean isExternal, boolean isForwardLocked) { 10567 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10568 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10569 instructionSets, null); 10570 // Hackily pretend we're still looking at a full code path 10571 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10572 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10573 } 10574 10575 // Extract cid from fullCodePath 10576 int eidx = fullCodePath.lastIndexOf("/"); 10577 String subStr1 = fullCodePath.substring(0, eidx); 10578 int sidx = subStr1.lastIndexOf("/"); 10579 cid = subStr1.substring(sidx+1, eidx); 10580 setMountPath(subStr1); 10581 } 10582 10583 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10584 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10585 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10586 instructionSets, null); 10587 this.cid = cid; 10588 setMountPath(PackageHelper.getSdDir(cid)); 10589 } 10590 10591 void createCopyFile() { 10592 cid = mInstallerService.allocateExternalStageCidLegacy(); 10593 } 10594 10595 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10596 if (origin.staged) { 10597 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10598 cid = origin.cid; 10599 setMountPath(PackageHelper.getSdDir(cid)); 10600 return PackageManager.INSTALL_SUCCEEDED; 10601 } 10602 10603 if (temp) { 10604 createCopyFile(); 10605 } else { 10606 /* 10607 * Pre-emptively destroy the container since it's destroyed if 10608 * copying fails due to it existing anyway. 10609 */ 10610 PackageHelper.destroySdDir(cid); 10611 } 10612 10613 final String newMountPath = imcs.copyPackageToContainer( 10614 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10615 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10616 10617 if (newMountPath != null) { 10618 setMountPath(newMountPath); 10619 return PackageManager.INSTALL_SUCCEEDED; 10620 } else { 10621 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10622 } 10623 } 10624 10625 @Override 10626 String getCodePath() { 10627 return packagePath; 10628 } 10629 10630 @Override 10631 String getResourcePath() { 10632 return resourcePath; 10633 } 10634 10635 int doPreInstall(int status) { 10636 if (status != PackageManager.INSTALL_SUCCEEDED) { 10637 // Destroy container 10638 PackageHelper.destroySdDir(cid); 10639 } else { 10640 boolean mounted = PackageHelper.isContainerMounted(cid); 10641 if (!mounted) { 10642 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10643 Process.SYSTEM_UID); 10644 if (newMountPath != null) { 10645 setMountPath(newMountPath); 10646 } else { 10647 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10648 } 10649 } 10650 } 10651 return status; 10652 } 10653 10654 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10655 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10656 String newMountPath = null; 10657 if (PackageHelper.isContainerMounted(cid)) { 10658 // Unmount the container 10659 if (!PackageHelper.unMountSdDir(cid)) { 10660 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10661 return false; 10662 } 10663 } 10664 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10665 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10666 " which might be stale. Will try to clean up."); 10667 // Clean up the stale container and proceed to recreate. 10668 if (!PackageHelper.destroySdDir(newCacheId)) { 10669 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10670 return false; 10671 } 10672 // Successfully cleaned up stale container. Try to rename again. 10673 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10674 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10675 + " inspite of cleaning it up."); 10676 return false; 10677 } 10678 } 10679 if (!PackageHelper.isContainerMounted(newCacheId)) { 10680 Slog.w(TAG, "Mounting container " + newCacheId); 10681 newMountPath = PackageHelper.mountSdDir(newCacheId, 10682 getEncryptKey(), Process.SYSTEM_UID); 10683 } else { 10684 newMountPath = PackageHelper.getSdDir(newCacheId); 10685 } 10686 if (newMountPath == null) { 10687 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10688 return false; 10689 } 10690 Log.i(TAG, "Succesfully renamed " + cid + 10691 " to " + newCacheId + 10692 " at new path: " + newMountPath); 10693 cid = newCacheId; 10694 10695 final File beforeCodeFile = new File(packagePath); 10696 setMountPath(newMountPath); 10697 final File afterCodeFile = new File(packagePath); 10698 10699 // Reflect the rename in scanned details 10700 pkg.codePath = afterCodeFile.getAbsolutePath(); 10701 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10702 pkg.baseCodePath); 10703 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10704 pkg.splitCodePaths); 10705 10706 // Reflect the rename in app info 10707 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10708 pkg.applicationInfo.setCodePath(pkg.codePath); 10709 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10710 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10711 pkg.applicationInfo.setResourcePath(pkg.codePath); 10712 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10713 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10714 10715 return true; 10716 } 10717 10718 private void setMountPath(String mountPath) { 10719 final File mountFile = new File(mountPath); 10720 10721 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10722 if (monolithicFile.exists()) { 10723 packagePath = monolithicFile.getAbsolutePath(); 10724 if (isFwdLocked()) { 10725 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10726 } else { 10727 resourcePath = packagePath; 10728 } 10729 } else { 10730 packagePath = mountFile.getAbsolutePath(); 10731 resourcePath = packagePath; 10732 } 10733 } 10734 10735 int doPostInstall(int status, int uid) { 10736 if (status != PackageManager.INSTALL_SUCCEEDED) { 10737 cleanUp(); 10738 } else { 10739 final int groupOwner; 10740 final String protectedFile; 10741 if (isFwdLocked()) { 10742 groupOwner = UserHandle.getSharedAppGid(uid); 10743 protectedFile = RES_FILE_NAME; 10744 } else { 10745 groupOwner = -1; 10746 protectedFile = null; 10747 } 10748 10749 if (uid < Process.FIRST_APPLICATION_UID 10750 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10751 Slog.e(TAG, "Failed to finalize " + cid); 10752 PackageHelper.destroySdDir(cid); 10753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10754 } 10755 10756 boolean mounted = PackageHelper.isContainerMounted(cid); 10757 if (!mounted) { 10758 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10759 } 10760 } 10761 return status; 10762 } 10763 10764 private void cleanUp() { 10765 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10766 10767 // Destroy secure container 10768 PackageHelper.destroySdDir(cid); 10769 } 10770 10771 private List<String> getAllCodePaths() { 10772 final File codeFile = new File(getCodePath()); 10773 if (codeFile != null && codeFile.exists()) { 10774 try { 10775 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10776 return pkg.getAllCodePaths(); 10777 } catch (PackageParserException e) { 10778 // Ignored; we tried our best 10779 } 10780 } 10781 return Collections.EMPTY_LIST; 10782 } 10783 10784 void cleanUpResourcesLI() { 10785 // Enumerate all code paths before deleting 10786 cleanUpResourcesLI(getAllCodePaths()); 10787 } 10788 10789 private void cleanUpResourcesLI(List<String> allCodePaths) { 10790 cleanUp(); 10791 removeDexFiles(allCodePaths, instructionSets); 10792 } 10793 10794 String getPackageName() { 10795 return getAsecPackageName(cid); 10796 } 10797 10798 boolean doPostDeleteLI(boolean delete) { 10799 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10800 final List<String> allCodePaths = getAllCodePaths(); 10801 boolean mounted = PackageHelper.isContainerMounted(cid); 10802 if (mounted) { 10803 // Unmount first 10804 if (PackageHelper.unMountSdDir(cid)) { 10805 mounted = false; 10806 } 10807 } 10808 if (!mounted && delete) { 10809 cleanUpResourcesLI(allCodePaths); 10810 } 10811 return !mounted; 10812 } 10813 10814 @Override 10815 int doPreCopy() { 10816 if (isFwdLocked()) { 10817 if (!PackageHelper.fixSdPermissions(cid, 10818 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10819 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10820 } 10821 } 10822 10823 return PackageManager.INSTALL_SUCCEEDED; 10824 } 10825 10826 @Override 10827 int doPostCopy(int uid) { 10828 if (isFwdLocked()) { 10829 if (uid < Process.FIRST_APPLICATION_UID 10830 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10831 RES_FILE_NAME)) { 10832 Slog.e(TAG, "Failed to finalize " + cid); 10833 PackageHelper.destroySdDir(cid); 10834 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10835 } 10836 } 10837 10838 return PackageManager.INSTALL_SUCCEEDED; 10839 } 10840 } 10841 10842 /** 10843 * Logic to handle movement of existing installed applications. 10844 */ 10845 class MoveInstallArgs extends InstallArgs { 10846 private File codeFile; 10847 private File resourceFile; 10848 10849 /** New install */ 10850 MoveInstallArgs(InstallParams params) { 10851 super(params.origin, params.move, params.observer, params.installFlags, 10852 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10853 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10854 } 10855 10856 int copyApk(IMediaContainerService imcs, boolean temp) { 10857 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10858 + move.toUuid); 10859 synchronized (mInstaller) { 10860 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10861 move.dataAppName, move.appId, move.seinfo) != 0) { 10862 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10863 } 10864 } 10865 10866 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10867 resourceFile = codeFile; 10868 Slog.d(TAG, "codeFile after move is " + codeFile); 10869 10870 return PackageManager.INSTALL_SUCCEEDED; 10871 } 10872 10873 int doPreInstall(int status) { 10874 if (status != PackageManager.INSTALL_SUCCEEDED) { 10875 cleanUp(); 10876 } 10877 return status; 10878 } 10879 10880 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10881 if (status != PackageManager.INSTALL_SUCCEEDED) { 10882 cleanUp(); 10883 return false; 10884 } 10885 10886 // Reflect the move in app info 10887 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10888 pkg.applicationInfo.setCodePath(pkg.codePath); 10889 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10890 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10891 pkg.applicationInfo.setResourcePath(pkg.codePath); 10892 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10893 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10894 10895 return true; 10896 } 10897 10898 int doPostInstall(int status, int uid) { 10899 if (status != PackageManager.INSTALL_SUCCEEDED) { 10900 cleanUp(); 10901 } 10902 return status; 10903 } 10904 10905 @Override 10906 String getCodePath() { 10907 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10908 } 10909 10910 @Override 10911 String getResourcePath() { 10912 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10913 } 10914 10915 private boolean cleanUp() { 10916 if (codeFile == null || !codeFile.exists()) { 10917 return false; 10918 } 10919 10920 if (codeFile.isDirectory()) { 10921 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10922 } else { 10923 codeFile.delete(); 10924 } 10925 10926 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10927 resourceFile.delete(); 10928 } 10929 10930 return true; 10931 } 10932 10933 void cleanUpResourcesLI() { 10934 cleanUp(); 10935 } 10936 10937 boolean doPostDeleteLI(boolean delete) { 10938 // XXX err, shouldn't we respect the delete flag? 10939 cleanUpResourcesLI(); 10940 return true; 10941 } 10942 } 10943 10944 static String getAsecPackageName(String packageCid) { 10945 int idx = packageCid.lastIndexOf("-"); 10946 if (idx == -1) { 10947 return packageCid; 10948 } 10949 return packageCid.substring(0, idx); 10950 } 10951 10952 // Utility method used to create code paths based on package name and available index. 10953 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10954 String idxStr = ""; 10955 int idx = 1; 10956 // Fall back to default value of idx=1 if prefix is not 10957 // part of oldCodePath 10958 if (oldCodePath != null) { 10959 String subStr = oldCodePath; 10960 // Drop the suffix right away 10961 if (suffix != null && subStr.endsWith(suffix)) { 10962 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10963 } 10964 // If oldCodePath already contains prefix find out the 10965 // ending index to either increment or decrement. 10966 int sidx = subStr.lastIndexOf(prefix); 10967 if (sidx != -1) { 10968 subStr = subStr.substring(sidx + prefix.length()); 10969 if (subStr != null) { 10970 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10971 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10972 } 10973 try { 10974 idx = Integer.parseInt(subStr); 10975 if (idx <= 1) { 10976 idx++; 10977 } else { 10978 idx--; 10979 } 10980 } catch(NumberFormatException e) { 10981 } 10982 } 10983 } 10984 } 10985 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10986 return prefix + idxStr; 10987 } 10988 10989 private File getNextCodePath(File targetDir, String packageName) { 10990 int suffix = 1; 10991 File result; 10992 do { 10993 result = new File(targetDir, packageName + "-" + suffix); 10994 suffix++; 10995 } while (result.exists()); 10996 return result; 10997 } 10998 10999 // Utility method that returns the relative package path with respect 11000 // to the installation directory. Like say for /data/data/com.test-1.apk 11001 // string com.test-1 is returned. 11002 static String deriveCodePathName(String codePath) { 11003 if (codePath == null) { 11004 return null; 11005 } 11006 final File codeFile = new File(codePath); 11007 final String name = codeFile.getName(); 11008 if (codeFile.isDirectory()) { 11009 return name; 11010 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11011 final int lastDot = name.lastIndexOf('.'); 11012 return name.substring(0, lastDot); 11013 } else { 11014 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11015 return null; 11016 } 11017 } 11018 11019 class PackageInstalledInfo { 11020 String name; 11021 int uid; 11022 // The set of users that originally had this package installed. 11023 int[] origUsers; 11024 // The set of users that now have this package installed. 11025 int[] newUsers; 11026 PackageParser.Package pkg; 11027 int returnCode; 11028 String returnMsg; 11029 PackageRemovedInfo removedInfo; 11030 11031 public void setError(int code, String msg) { 11032 returnCode = code; 11033 returnMsg = msg; 11034 Slog.w(TAG, msg); 11035 } 11036 11037 public void setError(String msg, PackageParserException e) { 11038 returnCode = e.error; 11039 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11040 Slog.w(TAG, msg, e); 11041 } 11042 11043 public void setError(String msg, PackageManagerException e) { 11044 returnCode = e.error; 11045 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11046 Slog.w(TAG, msg, e); 11047 } 11048 11049 // In some error cases we want to convey more info back to the observer 11050 String origPackage; 11051 String origPermission; 11052 } 11053 11054 /* 11055 * Install a non-existing package. 11056 */ 11057 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11058 UserHandle user, String installerPackageName, String volumeUuid, 11059 PackageInstalledInfo res) { 11060 // Remember this for later, in case we need to rollback this install 11061 String pkgName = pkg.packageName; 11062 11063 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11064 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11065 UserHandle.USER_OWNER).exists(); 11066 synchronized(mPackages) { 11067 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11068 // A package with the same name is already installed, though 11069 // it has been renamed to an older name. The package we 11070 // are trying to install should be installed as an update to 11071 // the existing one, but that has not been requested, so bail. 11072 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11073 + " without first uninstalling package running as " 11074 + mSettings.mRenamedPackages.get(pkgName)); 11075 return; 11076 } 11077 if (mPackages.containsKey(pkgName)) { 11078 // Don't allow installation over an existing package with the same name. 11079 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11080 + " without first uninstalling."); 11081 return; 11082 } 11083 } 11084 11085 try { 11086 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11087 System.currentTimeMillis(), user); 11088 11089 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11090 // delete the partially installed application. the data directory will have to be 11091 // restored if it was already existing 11092 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11093 // remove package from internal structures. Note that we want deletePackageX to 11094 // delete the package data and cache directories that it created in 11095 // scanPackageLocked, unless those directories existed before we even tried to 11096 // install. 11097 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11098 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11099 res.removedInfo, true); 11100 } 11101 11102 } catch (PackageManagerException e) { 11103 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11104 } 11105 } 11106 11107 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11108 // Upgrade keysets are being used. Determine if new package has a superset of the 11109 // required keys. 11110 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11111 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11112 for (int i = 0; i < upgradeKeySets.length; i++) { 11113 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11114 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11115 return true; 11116 } 11117 } 11118 return false; 11119 } 11120 11121 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11122 UserHandle user, String installerPackageName, String volumeUuid, 11123 PackageInstalledInfo res) { 11124 final PackageParser.Package oldPackage; 11125 final String pkgName = pkg.packageName; 11126 final int[] allUsers; 11127 final boolean[] perUserInstalled; 11128 final boolean weFroze; 11129 11130 // First find the old package info and check signatures 11131 synchronized(mPackages) { 11132 oldPackage = mPackages.get(pkgName); 11133 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11134 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11135 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11136 // default to original signature matching 11137 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11138 != PackageManager.SIGNATURE_MATCH) { 11139 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11140 "New package has a different signature: " + pkgName); 11141 return; 11142 } 11143 } else { 11144 if(!checkUpgradeKeySetLP(ps, pkg)) { 11145 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11146 "New package not signed by keys specified by upgrade-keysets: " 11147 + pkgName); 11148 return; 11149 } 11150 } 11151 11152 // In case of rollback, remember per-user/profile install state 11153 allUsers = sUserManager.getUserIds(); 11154 perUserInstalled = new boolean[allUsers.length]; 11155 for (int i = 0; i < allUsers.length; i++) { 11156 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11157 } 11158 11159 // Mark the app as frozen to prevent launching during the upgrade 11160 // process, and then kill all running instances 11161 if (!ps.frozen) { 11162 ps.frozen = true; 11163 weFroze = true; 11164 } else { 11165 weFroze = false; 11166 } 11167 } 11168 11169 // Now that we're guarded by frozen state, kill app during upgrade 11170 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11171 11172 try { 11173 boolean sysPkg = (isSystemApp(oldPackage)); 11174 if (sysPkg) { 11175 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11176 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11177 } else { 11178 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11179 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11180 } 11181 } finally { 11182 // Regardless of success or failure of upgrade steps above, always 11183 // unfreeze the package if we froze it 11184 if (weFroze) { 11185 unfreezePackage(pkgName); 11186 } 11187 } 11188 } 11189 11190 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11191 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11192 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11193 String volumeUuid, PackageInstalledInfo res) { 11194 String pkgName = deletedPackage.packageName; 11195 boolean deletedPkg = true; 11196 boolean updatedSettings = false; 11197 11198 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11199 + deletedPackage); 11200 long origUpdateTime; 11201 if (pkg.mExtras != null) { 11202 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11203 } else { 11204 origUpdateTime = 0; 11205 } 11206 11207 // First delete the existing package while retaining the data directory 11208 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11209 res.removedInfo, true)) { 11210 // If the existing package wasn't successfully deleted 11211 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11212 deletedPkg = false; 11213 } else { 11214 // Successfully deleted the old package; proceed with replace. 11215 11216 // If deleted package lived in a container, give users a chance to 11217 // relinquish resources before killing. 11218 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11219 if (DEBUG_INSTALL) { 11220 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11221 } 11222 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11223 final ArrayList<String> pkgList = new ArrayList<String>(1); 11224 pkgList.add(deletedPackage.applicationInfo.packageName); 11225 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11226 } 11227 11228 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11229 try { 11230 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11231 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11232 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11233 perUserInstalled, res, user); 11234 updatedSettings = true; 11235 } catch (PackageManagerException e) { 11236 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11237 } 11238 } 11239 11240 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11241 // remove package from internal structures. Note that we want deletePackageX to 11242 // delete the package data and cache directories that it created in 11243 // scanPackageLocked, unless those directories existed before we even tried to 11244 // install. 11245 if(updatedSettings) { 11246 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11247 deletePackageLI( 11248 pkgName, null, true, allUsers, perUserInstalled, 11249 PackageManager.DELETE_KEEP_DATA, 11250 res.removedInfo, true); 11251 } 11252 // Since we failed to install the new package we need to restore the old 11253 // package that we deleted. 11254 if (deletedPkg) { 11255 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11256 File restoreFile = new File(deletedPackage.codePath); 11257 // Parse old package 11258 boolean oldExternal = isExternal(deletedPackage); 11259 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11260 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11261 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11262 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11263 try { 11264 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11265 } catch (PackageManagerException e) { 11266 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11267 + e.getMessage()); 11268 return; 11269 } 11270 // Restore of old package succeeded. Update permissions. 11271 // writer 11272 synchronized (mPackages) { 11273 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11274 UPDATE_PERMISSIONS_ALL); 11275 // can downgrade to reader 11276 mSettings.writeLPr(); 11277 } 11278 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11279 } 11280 } 11281 } 11282 11283 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11284 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11285 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11286 String volumeUuid, PackageInstalledInfo res) { 11287 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11288 + ", old=" + deletedPackage); 11289 boolean disabledSystem = false; 11290 boolean updatedSettings = false; 11291 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11292 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11293 != 0) { 11294 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11295 } 11296 String packageName = deletedPackage.packageName; 11297 if (packageName == null) { 11298 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11299 "Attempt to delete null packageName."); 11300 return; 11301 } 11302 PackageParser.Package oldPkg; 11303 PackageSetting oldPkgSetting; 11304 // reader 11305 synchronized (mPackages) { 11306 oldPkg = mPackages.get(packageName); 11307 oldPkgSetting = mSettings.mPackages.get(packageName); 11308 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11309 (oldPkgSetting == null)) { 11310 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11311 "Couldn't find package:" + packageName + " information"); 11312 return; 11313 } 11314 } 11315 11316 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11317 res.removedInfo.removedPackage = packageName; 11318 // Remove existing system package 11319 removePackageLI(oldPkgSetting, true); 11320 // writer 11321 synchronized (mPackages) { 11322 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11323 if (!disabledSystem && deletedPackage != null) { 11324 // We didn't need to disable the .apk as a current system package, 11325 // which means we are replacing another update that is already 11326 // installed. We need to make sure to delete the older one's .apk. 11327 res.removedInfo.args = createInstallArgsForExisting(0, 11328 deletedPackage.applicationInfo.getCodePath(), 11329 deletedPackage.applicationInfo.getResourcePath(), 11330 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11331 } else { 11332 res.removedInfo.args = null; 11333 } 11334 } 11335 11336 // Successfully disabled the old package. Now proceed with re-installation 11337 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11338 11339 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11340 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11341 11342 PackageParser.Package newPackage = null; 11343 try { 11344 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11345 if (newPackage.mExtras != null) { 11346 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11347 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11348 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11349 11350 // is the update attempting to change shared user? that isn't going to work... 11351 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11352 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11353 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11354 + " to " + newPkgSetting.sharedUser); 11355 updatedSettings = true; 11356 } 11357 } 11358 11359 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11360 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11361 perUserInstalled, res, user); 11362 updatedSettings = true; 11363 } 11364 11365 } catch (PackageManagerException e) { 11366 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11367 } 11368 11369 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11370 // Re installation failed. Restore old information 11371 // Remove new pkg information 11372 if (newPackage != null) { 11373 removeInstalledPackageLI(newPackage, true); 11374 } 11375 // Add back the old system package 11376 try { 11377 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11378 } catch (PackageManagerException e) { 11379 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11380 } 11381 // Restore the old system information in Settings 11382 synchronized (mPackages) { 11383 if (disabledSystem) { 11384 mSettings.enableSystemPackageLPw(packageName); 11385 } 11386 if (updatedSettings) { 11387 mSettings.setInstallerPackageName(packageName, 11388 oldPkgSetting.installerPackageName); 11389 } 11390 mSettings.writeLPr(); 11391 } 11392 } 11393 } 11394 11395 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11396 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11397 UserHandle user) { 11398 String pkgName = newPackage.packageName; 11399 synchronized (mPackages) { 11400 //write settings. the installStatus will be incomplete at this stage. 11401 //note that the new package setting would have already been 11402 //added to mPackages. It hasn't been persisted yet. 11403 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11404 mSettings.writeLPr(); 11405 } 11406 11407 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11408 11409 synchronized (mPackages) { 11410 updatePermissionsLPw(newPackage.packageName, newPackage, 11411 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11412 ? UPDATE_PERMISSIONS_ALL : 0)); 11413 // For system-bundled packages, we assume that installing an upgraded version 11414 // of the package implies that the user actually wants to run that new code, 11415 // so we enable the package. 11416 PackageSetting ps = mSettings.mPackages.get(pkgName); 11417 if (ps != null) { 11418 if (isSystemApp(newPackage)) { 11419 // NB: implicit assumption that system package upgrades apply to all users 11420 if (DEBUG_INSTALL) { 11421 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11422 } 11423 if (res.origUsers != null) { 11424 for (int userHandle : res.origUsers) { 11425 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11426 userHandle, installerPackageName); 11427 } 11428 } 11429 // Also convey the prior install/uninstall state 11430 if (allUsers != null && perUserInstalled != null) { 11431 for (int i = 0; i < allUsers.length; i++) { 11432 if (DEBUG_INSTALL) { 11433 Slog.d(TAG, " user " + allUsers[i] 11434 + " => " + perUserInstalled[i]); 11435 } 11436 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11437 } 11438 // these install state changes will be persisted in the 11439 // upcoming call to mSettings.writeLPr(). 11440 } 11441 } 11442 // It's implied that when a user requests installation, they want the app to be 11443 // installed and enabled. 11444 int userId = user.getIdentifier(); 11445 if (userId != UserHandle.USER_ALL) { 11446 ps.setInstalled(true, userId); 11447 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11448 } 11449 } 11450 res.name = pkgName; 11451 res.uid = newPackage.applicationInfo.uid; 11452 res.pkg = newPackage; 11453 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11454 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11455 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11456 //to update install status 11457 mSettings.writeLPr(); 11458 } 11459 } 11460 11461 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11462 final int installFlags = args.installFlags; 11463 final String installerPackageName = args.installerPackageName; 11464 final String volumeUuid = args.volumeUuid; 11465 final File tmpPackageFile = new File(args.getCodePath()); 11466 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11467 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11468 || (args.volumeUuid != null)); 11469 boolean replace = false; 11470 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11471 // Result object to be returned 11472 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11473 11474 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11475 // Retrieve PackageSettings and parse package 11476 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11477 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11478 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11479 PackageParser pp = new PackageParser(); 11480 pp.setSeparateProcesses(mSeparateProcesses); 11481 pp.setDisplayMetrics(mMetrics); 11482 11483 final PackageParser.Package pkg; 11484 try { 11485 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11486 } catch (PackageParserException e) { 11487 res.setError("Failed parse during installPackageLI", e); 11488 return; 11489 } 11490 11491 // Mark that we have an install time CPU ABI override. 11492 pkg.cpuAbiOverride = args.abiOverride; 11493 11494 String pkgName = res.name = pkg.packageName; 11495 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11496 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11497 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11498 return; 11499 } 11500 } 11501 11502 try { 11503 pp.collectCertificates(pkg, parseFlags); 11504 pp.collectManifestDigest(pkg); 11505 } catch (PackageParserException e) { 11506 res.setError("Failed collect during installPackageLI", e); 11507 return; 11508 } 11509 11510 /* If the installer passed in a manifest digest, compare it now. */ 11511 if (args.manifestDigest != null) { 11512 if (DEBUG_INSTALL) { 11513 final String parsedManifest = pkg.manifestDigest == null ? "null" 11514 : pkg.manifestDigest.toString(); 11515 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11516 + parsedManifest); 11517 } 11518 11519 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11520 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11521 return; 11522 } 11523 } else if (DEBUG_INSTALL) { 11524 final String parsedManifest = pkg.manifestDigest == null 11525 ? "null" : pkg.manifestDigest.toString(); 11526 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11527 } 11528 11529 // Get rid of all references to package scan path via parser. 11530 pp = null; 11531 String oldCodePath = null; 11532 boolean systemApp = false; 11533 synchronized (mPackages) { 11534 // Check if installing already existing package 11535 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11536 String oldName = mSettings.mRenamedPackages.get(pkgName); 11537 if (pkg.mOriginalPackages != null 11538 && pkg.mOriginalPackages.contains(oldName) 11539 && mPackages.containsKey(oldName)) { 11540 // This package is derived from an original package, 11541 // and this device has been updating from that original 11542 // name. We must continue using the original name, so 11543 // rename the new package here. 11544 pkg.setPackageName(oldName); 11545 pkgName = pkg.packageName; 11546 replace = true; 11547 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11548 + oldName + " pkgName=" + pkgName); 11549 } else if (mPackages.containsKey(pkgName)) { 11550 // This package, under its official name, already exists 11551 // on the device; we should replace it. 11552 replace = true; 11553 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11554 } 11555 11556 // Prevent apps opting out from runtime permissions 11557 if (replace) { 11558 PackageParser.Package oldPackage = mPackages.get(pkgName); 11559 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11560 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11561 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11562 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11563 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11564 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11565 + " doesn't support runtime permissions but the old" 11566 + " target SDK " + oldTargetSdk + " does."); 11567 return; 11568 } 11569 } 11570 } 11571 11572 PackageSetting ps = mSettings.mPackages.get(pkgName); 11573 if (ps != null) { 11574 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11575 11576 // Quick sanity check that we're signed correctly if updating; 11577 // we'll check this again later when scanning, but we want to 11578 // bail early here before tripping over redefined permissions. 11579 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11580 try { 11581 verifySignaturesLP(ps, pkg); 11582 } catch (PackageManagerException e) { 11583 res.setError(e.error, e.getMessage()); 11584 return; 11585 } 11586 } else { 11587 if (!checkUpgradeKeySetLP(ps, pkg)) { 11588 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11589 + pkg.packageName + " upgrade keys do not match the " 11590 + "previously installed version"); 11591 return; 11592 } 11593 } 11594 11595 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11596 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11597 systemApp = (ps.pkg.applicationInfo.flags & 11598 ApplicationInfo.FLAG_SYSTEM) != 0; 11599 } 11600 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11601 } 11602 11603 // Check whether the newly-scanned package wants to define an already-defined perm 11604 int N = pkg.permissions.size(); 11605 for (int i = N-1; i >= 0; i--) { 11606 PackageParser.Permission perm = pkg.permissions.get(i); 11607 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11608 if (bp != null) { 11609 // If the defining package is signed with our cert, it's okay. This 11610 // also includes the "updating the same package" case, of course. 11611 // "updating same package" could also involve key-rotation. 11612 final boolean sigsOk; 11613 if (!bp.sourcePackage.equals(pkg.packageName) 11614 || !(bp.packageSetting instanceof PackageSetting) 11615 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11616 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11617 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11618 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11619 } else { 11620 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11621 } 11622 if (!sigsOk) { 11623 // If the owning package is the system itself, we log but allow 11624 // install to proceed; we fail the install on all other permission 11625 // redefinitions. 11626 if (!bp.sourcePackage.equals("android")) { 11627 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11628 + pkg.packageName + " attempting to redeclare permission " 11629 + perm.info.name + " already owned by " + bp.sourcePackage); 11630 res.origPermission = perm.info.name; 11631 res.origPackage = bp.sourcePackage; 11632 return; 11633 } else { 11634 Slog.w(TAG, "Package " + pkg.packageName 11635 + " attempting to redeclare system permission " 11636 + perm.info.name + "; ignoring new declaration"); 11637 pkg.permissions.remove(i); 11638 } 11639 } 11640 } 11641 } 11642 11643 } 11644 11645 if (systemApp && onExternal) { 11646 // Disable updates to system apps on sdcard 11647 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11648 "Cannot install updates to system apps on sdcard"); 11649 return; 11650 } 11651 11652 if (args.move != null) { 11653 // We did an in-place move, so dex is ready to roll 11654 scanFlags |= SCAN_NO_DEX; 11655 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11656 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11657 scanFlags |= SCAN_NO_DEX; 11658 11659 try { 11660 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11661 true /* extract libs */); 11662 } catch (PackageManagerException pme) { 11663 Slog.e(TAG, "Error deriving application ABI", pme); 11664 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error "); 11665 return; 11666 } 11667 11668 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11669 int result = mPackageDexOptimizer 11670 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11671 false /* defer */, false /* inclDependencies */); 11672 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11673 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11674 return; 11675 } 11676 } 11677 11678 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11679 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11680 return; 11681 } 11682 11683 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11684 11685 if (replace) { 11686 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11687 installerPackageName, volumeUuid, res); 11688 } else { 11689 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11690 args.user, installerPackageName, volumeUuid, res); 11691 } 11692 synchronized (mPackages) { 11693 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11694 if (ps != null) { 11695 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11696 } 11697 } 11698 } 11699 11700 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11701 if (mIntentFilterVerifierComponent == null) { 11702 Slog.d(TAG, "No IntentFilter verification will not be done as " 11703 + "there is no IntentFilterVerifier available!"); 11704 return; 11705 } 11706 11707 final int verifierUid = getPackageUid( 11708 mIntentFilterVerifierComponent.getPackageName(), 11709 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11710 11711 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11712 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11713 msg.obj = pkg; 11714 msg.arg1 = userId; 11715 msg.arg2 = verifierUid; 11716 11717 mHandler.sendMessage(msg); 11718 } 11719 11720 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11721 PackageParser.Package pkg) { 11722 int size = pkg.activities.size(); 11723 if (size == 0) { 11724 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11725 return; 11726 } 11727 11728 final boolean hasDomainURLs = hasDomainURLs(pkg); 11729 if (!hasDomainURLs) { 11730 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11731 return; 11732 } 11733 11734 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11735 + " Activities needs verification ..."); 11736 11737 final int verificationId = mIntentFilterVerificationToken++; 11738 int count = 0; 11739 final String packageName = pkg.packageName; 11740 ArrayList<String> allHosts = new ArrayList<>(); 11741 11742 synchronized (mPackages) { 11743 for (PackageParser.Activity a : pkg.activities) { 11744 for (ActivityIntentInfo filter : a.intents) { 11745 boolean needsFilterVerification = filter.needsVerification(); 11746 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11747 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11748 mIntentFilterVerifier.addOneIntentFilterVerification( 11749 verifierUid, userId, verificationId, filter, packageName); 11750 count++; 11751 } else if (!needsFilterVerification) { 11752 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11753 if (hasValidDomains(filter)) { 11754 ArrayList<String> hosts = filter.getHostsList(); 11755 if (hosts.size() > 0) { 11756 allHosts.addAll(hosts); 11757 } else { 11758 if (allHosts.isEmpty()) { 11759 allHosts.add("*"); 11760 } 11761 } 11762 } 11763 } else { 11764 Slog.d(TAG, "Verification already done for IntentFilter:" 11765 + filter.toString()); 11766 } 11767 } 11768 } 11769 } 11770 11771 if (count > 0) { 11772 mIntentFilterVerifier.startVerifications(userId); 11773 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11774 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11775 } else { 11776 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11777 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11778 packageName, allHosts) != null) { 11779 scheduleWriteSettingsLocked(); 11780 } 11781 } 11782 } 11783 11784 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11785 final ComponentName cn = filter.activity.getComponentName(); 11786 final String packageName = cn.getPackageName(); 11787 11788 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11789 packageName); 11790 if (ivi == null) { 11791 return true; 11792 } 11793 int status = ivi.getStatus(); 11794 switch (status) { 11795 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11796 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11797 return true; 11798 11799 default: 11800 // Nothing to do 11801 return false; 11802 } 11803 } 11804 11805 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11806 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11807 || ((pkg.applicationInfo.privateFlags 11808 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11809 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11810 } 11811 11812 private static boolean isMultiArch(PackageSetting ps) { 11813 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11814 } 11815 11816 private static boolean isMultiArch(ApplicationInfo info) { 11817 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11818 } 11819 11820 private static boolean isExternal(PackageParser.Package pkg) { 11821 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11822 } 11823 11824 private static boolean isExternal(PackageSetting ps) { 11825 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11826 } 11827 11828 private static boolean isExternal(ApplicationInfo info) { 11829 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11830 } 11831 11832 private static boolean isSystemApp(PackageParser.Package pkg) { 11833 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11834 } 11835 11836 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11837 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11838 } 11839 11840 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11841 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11842 } 11843 11844 private static boolean isSystemApp(PackageSetting ps) { 11845 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11846 } 11847 11848 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11849 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11850 } 11851 11852 private int packageFlagsToInstallFlags(PackageSetting ps) { 11853 int installFlags = 0; 11854 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11855 // This existing package was an external ASEC install when we have 11856 // the external flag without a UUID 11857 installFlags |= PackageManager.INSTALL_EXTERNAL; 11858 } 11859 if (ps.isForwardLocked()) { 11860 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11861 } 11862 return installFlags; 11863 } 11864 11865 private void deleteTempPackageFiles() { 11866 final FilenameFilter filter = new FilenameFilter() { 11867 public boolean accept(File dir, String name) { 11868 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11869 } 11870 }; 11871 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11872 file.delete(); 11873 } 11874 } 11875 11876 @Override 11877 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11878 int flags) { 11879 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11880 flags); 11881 } 11882 11883 @Override 11884 public void deletePackage(final String packageName, 11885 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11886 mContext.enforceCallingOrSelfPermission( 11887 android.Manifest.permission.DELETE_PACKAGES, null); 11888 final int uid = Binder.getCallingUid(); 11889 if (UserHandle.getUserId(uid) != userId) { 11890 mContext.enforceCallingPermission( 11891 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11892 "deletePackage for user " + userId); 11893 } 11894 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11895 try { 11896 observer.onPackageDeleted(packageName, 11897 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11898 } catch (RemoteException re) { 11899 } 11900 return; 11901 } 11902 11903 boolean uninstallBlocked = false; 11904 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11905 int[] users = sUserManager.getUserIds(); 11906 for (int i = 0; i < users.length; ++i) { 11907 if (getBlockUninstallForUser(packageName, users[i])) { 11908 uninstallBlocked = true; 11909 break; 11910 } 11911 } 11912 } else { 11913 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11914 } 11915 if (uninstallBlocked) { 11916 try { 11917 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11918 null); 11919 } catch (RemoteException re) { 11920 } 11921 return; 11922 } 11923 11924 if (DEBUG_REMOVE) { 11925 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11926 } 11927 // Queue up an async operation since the package deletion may take a little while. 11928 mHandler.post(new Runnable() { 11929 public void run() { 11930 mHandler.removeCallbacks(this); 11931 final int returnCode = deletePackageX(packageName, userId, flags); 11932 if (observer != null) { 11933 try { 11934 observer.onPackageDeleted(packageName, returnCode, null); 11935 } catch (RemoteException e) { 11936 Log.i(TAG, "Observer no longer exists."); 11937 } //end catch 11938 } //end if 11939 } //end run 11940 }); 11941 } 11942 11943 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11944 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11945 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11946 try { 11947 if (dpm != null) { 11948 if (dpm.isDeviceOwner(packageName)) { 11949 return true; 11950 } 11951 int[] users; 11952 if (userId == UserHandle.USER_ALL) { 11953 users = sUserManager.getUserIds(); 11954 } else { 11955 users = new int[]{userId}; 11956 } 11957 for (int i = 0; i < users.length; ++i) { 11958 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11959 return true; 11960 } 11961 } 11962 } 11963 } catch (RemoteException e) { 11964 } 11965 return false; 11966 } 11967 11968 /** 11969 * This method is an internal method that could be get invoked either 11970 * to delete an installed package or to clean up a failed installation. 11971 * After deleting an installed package, a broadcast is sent to notify any 11972 * listeners that the package has been installed. For cleaning up a failed 11973 * installation, the broadcast is not necessary since the package's 11974 * installation wouldn't have sent the initial broadcast either 11975 * The key steps in deleting a package are 11976 * deleting the package information in internal structures like mPackages, 11977 * deleting the packages base directories through installd 11978 * updating mSettings to reflect current status 11979 * persisting settings for later use 11980 * sending a broadcast if necessary 11981 */ 11982 private int deletePackageX(String packageName, int userId, int flags) { 11983 final PackageRemovedInfo info = new PackageRemovedInfo(); 11984 final boolean res; 11985 11986 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11987 ? UserHandle.ALL : new UserHandle(userId); 11988 11989 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11990 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11991 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11992 } 11993 11994 boolean removedForAllUsers = false; 11995 boolean systemUpdate = false; 11996 11997 // for the uninstall-updates case and restricted profiles, remember the per- 11998 // userhandle installed state 11999 int[] allUsers; 12000 boolean[] perUserInstalled; 12001 synchronized (mPackages) { 12002 PackageSetting ps = mSettings.mPackages.get(packageName); 12003 allUsers = sUserManager.getUserIds(); 12004 perUserInstalled = new boolean[allUsers.length]; 12005 for (int i = 0; i < allUsers.length; i++) { 12006 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12007 } 12008 } 12009 12010 synchronized (mInstallLock) { 12011 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12012 res = deletePackageLI(packageName, removeForUser, 12013 true, allUsers, perUserInstalled, 12014 flags | REMOVE_CHATTY, info, true); 12015 systemUpdate = info.isRemovedPackageSystemUpdate; 12016 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12017 removedForAllUsers = true; 12018 } 12019 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12020 + " removedForAllUsers=" + removedForAllUsers); 12021 } 12022 12023 if (res) { 12024 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12025 12026 // If the removed package was a system update, the old system package 12027 // was re-enabled; we need to broadcast this information 12028 if (systemUpdate) { 12029 Bundle extras = new Bundle(1); 12030 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12031 ? info.removedAppId : info.uid); 12032 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12033 12034 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12035 extras, null, null, null); 12036 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12037 extras, null, null, null); 12038 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12039 null, packageName, null, null); 12040 } 12041 } 12042 // Force a gc here. 12043 Runtime.getRuntime().gc(); 12044 // Delete the resources here after sending the broadcast to let 12045 // other processes clean up before deleting resources. 12046 if (info.args != null) { 12047 synchronized (mInstallLock) { 12048 info.args.doPostDeleteLI(true); 12049 } 12050 } 12051 12052 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12053 } 12054 12055 class PackageRemovedInfo { 12056 String removedPackage; 12057 int uid = -1; 12058 int removedAppId = -1; 12059 int[] removedUsers = null; 12060 boolean isRemovedPackageSystemUpdate = false; 12061 // Clean up resources deleted packages. 12062 InstallArgs args = null; 12063 12064 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12065 Bundle extras = new Bundle(1); 12066 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12067 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12068 if (replacing) { 12069 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12070 } 12071 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12072 if (removedPackage != null) { 12073 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12074 extras, null, null, removedUsers); 12075 if (fullRemove && !replacing) { 12076 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12077 extras, null, null, removedUsers); 12078 } 12079 } 12080 if (removedAppId >= 0) { 12081 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12082 removedUsers); 12083 } 12084 } 12085 } 12086 12087 /* 12088 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12089 * flag is not set, the data directory is removed as well. 12090 * make sure this flag is set for partially installed apps. If not its meaningless to 12091 * delete a partially installed application. 12092 */ 12093 private void removePackageDataLI(PackageSetting ps, 12094 int[] allUserHandles, boolean[] perUserInstalled, 12095 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12096 String packageName = ps.name; 12097 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12098 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12099 // Retrieve object to delete permissions for shared user later on 12100 final PackageSetting deletedPs; 12101 // reader 12102 synchronized (mPackages) { 12103 deletedPs = mSettings.mPackages.get(packageName); 12104 if (outInfo != null) { 12105 outInfo.removedPackage = packageName; 12106 outInfo.removedUsers = deletedPs != null 12107 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12108 : null; 12109 } 12110 } 12111 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12112 removeDataDirsLI(ps.volumeUuid, packageName); 12113 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12114 } 12115 // writer 12116 synchronized (mPackages) { 12117 if (deletedPs != null) { 12118 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12119 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12120 clearDefaultBrowserIfNeeded(packageName); 12121 if (outInfo != null) { 12122 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12123 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12124 } 12125 updatePermissionsLPw(deletedPs.name, null, 0); 12126 if (deletedPs.sharedUser != null) { 12127 // Remove permissions associated with package. Since runtime 12128 // permissions are per user we have to kill the removed package 12129 // or packages running under the shared user of the removed 12130 // package if revoking the permissions requested only by the removed 12131 // package is successful and this causes a change in gids. 12132 for (int userId : UserManagerService.getInstance().getUserIds()) { 12133 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12134 userId); 12135 if (userIdToKill == UserHandle.USER_ALL 12136 || userIdToKill >= UserHandle.USER_OWNER) { 12137 // If gids changed for this user, kill all affected packages. 12138 mHandler.post(new Runnable() { 12139 @Override 12140 public void run() { 12141 // This has to happen with no lock held. 12142 killSettingPackagesForUser(deletedPs, userIdToKill, 12143 KILL_APP_REASON_GIDS_CHANGED); 12144 } 12145 }); 12146 break; 12147 } 12148 } 12149 } 12150 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12151 } 12152 // make sure to preserve per-user disabled state if this removal was just 12153 // a downgrade of a system app to the factory package 12154 if (allUserHandles != null && perUserInstalled != null) { 12155 if (DEBUG_REMOVE) { 12156 Slog.d(TAG, "Propagating install state across downgrade"); 12157 } 12158 for (int i = 0; i < allUserHandles.length; i++) { 12159 if (DEBUG_REMOVE) { 12160 Slog.d(TAG, " user " + allUserHandles[i] 12161 + " => " + perUserInstalled[i]); 12162 } 12163 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12164 } 12165 } 12166 } 12167 // can downgrade to reader 12168 if (writeSettings) { 12169 // Save settings now 12170 mSettings.writeLPr(); 12171 } 12172 } 12173 if (outInfo != null) { 12174 // A user ID was deleted here. Go through all users and remove it 12175 // from KeyStore. 12176 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12177 } 12178 } 12179 12180 static boolean locationIsPrivileged(File path) { 12181 try { 12182 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12183 .getCanonicalPath(); 12184 return path.getCanonicalPath().startsWith(privilegedAppDir); 12185 } catch (IOException e) { 12186 Slog.e(TAG, "Unable to access code path " + path); 12187 } 12188 return false; 12189 } 12190 12191 /* 12192 * Tries to delete system package. 12193 */ 12194 private boolean deleteSystemPackageLI(PackageSetting newPs, 12195 int[] allUserHandles, boolean[] perUserInstalled, 12196 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12197 final boolean applyUserRestrictions 12198 = (allUserHandles != null) && (perUserInstalled != null); 12199 PackageSetting disabledPs = null; 12200 // Confirm if the system package has been updated 12201 // An updated system app can be deleted. This will also have to restore 12202 // the system pkg from system partition 12203 // reader 12204 synchronized (mPackages) { 12205 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12206 } 12207 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12208 + " disabledPs=" + disabledPs); 12209 if (disabledPs == null) { 12210 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12211 return false; 12212 } else if (DEBUG_REMOVE) { 12213 Slog.d(TAG, "Deleting system pkg from data partition"); 12214 } 12215 if (DEBUG_REMOVE) { 12216 if (applyUserRestrictions) { 12217 Slog.d(TAG, "Remembering install states:"); 12218 for (int i = 0; i < allUserHandles.length; i++) { 12219 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12220 } 12221 } 12222 } 12223 // Delete the updated package 12224 outInfo.isRemovedPackageSystemUpdate = true; 12225 if (disabledPs.versionCode < newPs.versionCode) { 12226 // Delete data for downgrades 12227 flags &= ~PackageManager.DELETE_KEEP_DATA; 12228 } else { 12229 // Preserve data by setting flag 12230 flags |= PackageManager.DELETE_KEEP_DATA; 12231 } 12232 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12233 allUserHandles, perUserInstalled, outInfo, writeSettings); 12234 if (!ret) { 12235 return false; 12236 } 12237 // writer 12238 synchronized (mPackages) { 12239 // Reinstate the old system package 12240 mSettings.enableSystemPackageLPw(newPs.name); 12241 // Remove any native libraries from the upgraded package. 12242 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12243 } 12244 // Install the system package 12245 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12246 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12247 if (locationIsPrivileged(disabledPs.codePath)) { 12248 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12249 } 12250 12251 final PackageParser.Package newPkg; 12252 try { 12253 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12254 } catch (PackageManagerException e) { 12255 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12256 return false; 12257 } 12258 12259 // writer 12260 synchronized (mPackages) { 12261 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12262 updatePermissionsLPw(newPkg.packageName, newPkg, 12263 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12264 if (applyUserRestrictions) { 12265 if (DEBUG_REMOVE) { 12266 Slog.d(TAG, "Propagating install state across reinstall"); 12267 } 12268 for (int i = 0; i < allUserHandles.length; i++) { 12269 if (DEBUG_REMOVE) { 12270 Slog.d(TAG, " user " + allUserHandles[i] 12271 + " => " + perUserInstalled[i]); 12272 } 12273 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12274 } 12275 // Regardless of writeSettings we need to ensure that this restriction 12276 // state propagation is persisted 12277 mSettings.writeAllUsersPackageRestrictionsLPr(); 12278 } 12279 // can downgrade to reader here 12280 if (writeSettings) { 12281 mSettings.writeLPr(); 12282 } 12283 } 12284 return true; 12285 } 12286 12287 private boolean deleteInstalledPackageLI(PackageSetting ps, 12288 boolean deleteCodeAndResources, int flags, 12289 int[] allUserHandles, boolean[] perUserInstalled, 12290 PackageRemovedInfo outInfo, boolean writeSettings) { 12291 if (outInfo != null) { 12292 outInfo.uid = ps.appId; 12293 } 12294 12295 // Delete package data from internal structures and also remove data if flag is set 12296 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12297 12298 // Delete application code and resources 12299 if (deleteCodeAndResources && (outInfo != null)) { 12300 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12301 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12302 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12303 } 12304 return true; 12305 } 12306 12307 @Override 12308 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12309 int userId) { 12310 mContext.enforceCallingOrSelfPermission( 12311 android.Manifest.permission.DELETE_PACKAGES, null); 12312 synchronized (mPackages) { 12313 PackageSetting ps = mSettings.mPackages.get(packageName); 12314 if (ps == null) { 12315 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12316 return false; 12317 } 12318 if (!ps.getInstalled(userId)) { 12319 // Can't block uninstall for an app that is not installed or enabled. 12320 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12321 return false; 12322 } 12323 ps.setBlockUninstall(blockUninstall, userId); 12324 mSettings.writePackageRestrictionsLPr(userId); 12325 } 12326 return true; 12327 } 12328 12329 @Override 12330 public boolean getBlockUninstallForUser(String packageName, int userId) { 12331 synchronized (mPackages) { 12332 PackageSetting ps = mSettings.mPackages.get(packageName); 12333 if (ps == null) { 12334 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12335 return false; 12336 } 12337 return ps.getBlockUninstall(userId); 12338 } 12339 } 12340 12341 /* 12342 * This method handles package deletion in general 12343 */ 12344 private boolean deletePackageLI(String packageName, UserHandle user, 12345 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12346 int flags, PackageRemovedInfo outInfo, 12347 boolean writeSettings) { 12348 if (packageName == null) { 12349 Slog.w(TAG, "Attempt to delete null packageName."); 12350 return false; 12351 } 12352 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12353 PackageSetting ps; 12354 boolean dataOnly = false; 12355 int removeUser = -1; 12356 int appId = -1; 12357 synchronized (mPackages) { 12358 ps = mSettings.mPackages.get(packageName); 12359 if (ps == null) { 12360 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12361 return false; 12362 } 12363 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12364 && user.getIdentifier() != UserHandle.USER_ALL) { 12365 // The caller is asking that the package only be deleted for a single 12366 // user. To do this, we just mark its uninstalled state and delete 12367 // its data. If this is a system app, we only allow this to happen if 12368 // they have set the special DELETE_SYSTEM_APP which requests different 12369 // semantics than normal for uninstalling system apps. 12370 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12371 ps.setUserState(user.getIdentifier(), 12372 COMPONENT_ENABLED_STATE_DEFAULT, 12373 false, //installed 12374 true, //stopped 12375 true, //notLaunched 12376 false, //hidden 12377 null, null, null, 12378 false, // blockUninstall 12379 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12380 if (!isSystemApp(ps)) { 12381 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12382 // Other user still have this package installed, so all 12383 // we need to do is clear this user's data and save that 12384 // it is uninstalled. 12385 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12386 removeUser = user.getIdentifier(); 12387 appId = ps.appId; 12388 scheduleWritePackageRestrictionsLocked(removeUser); 12389 } else { 12390 // We need to set it back to 'installed' so the uninstall 12391 // broadcasts will be sent correctly. 12392 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12393 ps.setInstalled(true, user.getIdentifier()); 12394 } 12395 } else { 12396 // This is a system app, so we assume that the 12397 // other users still have this package installed, so all 12398 // we need to do is clear this user's data and save that 12399 // it is uninstalled. 12400 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12401 removeUser = user.getIdentifier(); 12402 appId = ps.appId; 12403 scheduleWritePackageRestrictionsLocked(removeUser); 12404 } 12405 } 12406 } 12407 12408 if (removeUser >= 0) { 12409 // From above, we determined that we are deleting this only 12410 // for a single user. Continue the work here. 12411 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12412 if (outInfo != null) { 12413 outInfo.removedPackage = packageName; 12414 outInfo.removedAppId = appId; 12415 outInfo.removedUsers = new int[] {removeUser}; 12416 } 12417 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12418 removeKeystoreDataIfNeeded(removeUser, appId); 12419 schedulePackageCleaning(packageName, removeUser, false); 12420 synchronized (mPackages) { 12421 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12422 scheduleWritePackageRestrictionsLocked(removeUser); 12423 } 12424 } 12425 return true; 12426 } 12427 12428 if (dataOnly) { 12429 // Delete application data first 12430 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12431 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12432 return true; 12433 } 12434 12435 boolean ret = false; 12436 if (isSystemApp(ps)) { 12437 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12438 // When an updated system application is deleted we delete the existing resources as well and 12439 // fall back to existing code in system partition 12440 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12441 flags, outInfo, writeSettings); 12442 } else { 12443 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12444 // Kill application pre-emptively especially for apps on sd. 12445 killApplication(packageName, ps.appId, "uninstall pkg"); 12446 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12447 allUserHandles, perUserInstalled, 12448 outInfo, writeSettings); 12449 } 12450 12451 return ret; 12452 } 12453 12454 private final class ClearStorageConnection implements ServiceConnection { 12455 IMediaContainerService mContainerService; 12456 12457 @Override 12458 public void onServiceConnected(ComponentName name, IBinder service) { 12459 synchronized (this) { 12460 mContainerService = IMediaContainerService.Stub.asInterface(service); 12461 notifyAll(); 12462 } 12463 } 12464 12465 @Override 12466 public void onServiceDisconnected(ComponentName name) { 12467 } 12468 } 12469 12470 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12471 final boolean mounted; 12472 if (Environment.isExternalStorageEmulated()) { 12473 mounted = true; 12474 } else { 12475 final String status = Environment.getExternalStorageState(); 12476 12477 mounted = status.equals(Environment.MEDIA_MOUNTED) 12478 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12479 } 12480 12481 if (!mounted) { 12482 return; 12483 } 12484 12485 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12486 int[] users; 12487 if (userId == UserHandle.USER_ALL) { 12488 users = sUserManager.getUserIds(); 12489 } else { 12490 users = new int[] { userId }; 12491 } 12492 final ClearStorageConnection conn = new ClearStorageConnection(); 12493 if (mContext.bindServiceAsUser( 12494 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12495 try { 12496 for (int curUser : users) { 12497 long timeout = SystemClock.uptimeMillis() + 5000; 12498 synchronized (conn) { 12499 long now = SystemClock.uptimeMillis(); 12500 while (conn.mContainerService == null && now < timeout) { 12501 try { 12502 conn.wait(timeout - now); 12503 } catch (InterruptedException e) { 12504 } 12505 } 12506 } 12507 if (conn.mContainerService == null) { 12508 return; 12509 } 12510 12511 final UserEnvironment userEnv = new UserEnvironment(curUser); 12512 clearDirectory(conn.mContainerService, 12513 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12514 if (allData) { 12515 clearDirectory(conn.mContainerService, 12516 userEnv.buildExternalStorageAppDataDirs(packageName)); 12517 clearDirectory(conn.mContainerService, 12518 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12519 } 12520 } 12521 } finally { 12522 mContext.unbindService(conn); 12523 } 12524 } 12525 } 12526 12527 @Override 12528 public void clearApplicationUserData(final String packageName, 12529 final IPackageDataObserver observer, final int userId) { 12530 mContext.enforceCallingOrSelfPermission( 12531 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12532 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12533 // Queue up an async operation since the package deletion may take a little while. 12534 mHandler.post(new Runnable() { 12535 public void run() { 12536 mHandler.removeCallbacks(this); 12537 final boolean succeeded; 12538 synchronized (mInstallLock) { 12539 succeeded = clearApplicationUserDataLI(packageName, userId); 12540 } 12541 clearExternalStorageDataSync(packageName, userId, true); 12542 if (succeeded) { 12543 // invoke DeviceStorageMonitor's update method to clear any notifications 12544 DeviceStorageMonitorInternal 12545 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12546 if (dsm != null) { 12547 dsm.checkMemory(); 12548 } 12549 } 12550 if(observer != null) { 12551 try { 12552 observer.onRemoveCompleted(packageName, succeeded); 12553 } catch (RemoteException e) { 12554 Log.i(TAG, "Observer no longer exists."); 12555 } 12556 } //end if observer 12557 } //end run 12558 }); 12559 } 12560 12561 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12562 if (packageName == null) { 12563 Slog.w(TAG, "Attempt to delete null packageName."); 12564 return false; 12565 } 12566 12567 // Try finding details about the requested package 12568 PackageParser.Package pkg; 12569 synchronized (mPackages) { 12570 pkg = mPackages.get(packageName); 12571 if (pkg == null) { 12572 final PackageSetting ps = mSettings.mPackages.get(packageName); 12573 if (ps != null) { 12574 pkg = ps.pkg; 12575 } 12576 } 12577 } 12578 12579 if (pkg == null) { 12580 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12581 } 12582 12583 // Always delete data directories for package, even if we found no other 12584 // record of app. This helps users recover from UID mismatches without 12585 // resorting to a full data wipe. 12586 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12587 if (retCode < 0) { 12588 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12589 return false; 12590 } 12591 12592 if (pkg == null) { 12593 return false; 12594 } 12595 12596 if (pkg != null && pkg.applicationInfo != null) { 12597 final int appId = pkg.applicationInfo.uid; 12598 removeKeystoreDataIfNeeded(userId, appId); 12599 } 12600 12601 // Create a native library symlink only if we have native libraries 12602 // and if the native libraries are 32 bit libraries. We do not provide 12603 // this symlink for 64 bit libraries. 12604 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12605 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12606 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12607 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12608 nativeLibPath, userId) < 0) { 12609 Slog.w(TAG, "Failed linking native library dir"); 12610 return false; 12611 } 12612 } 12613 12614 return true; 12615 } 12616 12617 /** 12618 * Remove entries from the keystore daemon. Will only remove it if the 12619 * {@code appId} is valid. 12620 */ 12621 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12622 if (appId < 0) { 12623 return; 12624 } 12625 12626 final KeyStore keyStore = KeyStore.getInstance(); 12627 if (keyStore != null) { 12628 if (userId == UserHandle.USER_ALL) { 12629 for (final int individual : sUserManager.getUserIds()) { 12630 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12631 } 12632 } else { 12633 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12634 } 12635 } else { 12636 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12637 } 12638 } 12639 12640 @Override 12641 public void deleteApplicationCacheFiles(final String packageName, 12642 final IPackageDataObserver observer) { 12643 mContext.enforceCallingOrSelfPermission( 12644 android.Manifest.permission.DELETE_CACHE_FILES, null); 12645 // Queue up an async operation since the package deletion may take a little while. 12646 final int userId = UserHandle.getCallingUserId(); 12647 mHandler.post(new Runnable() { 12648 public void run() { 12649 mHandler.removeCallbacks(this); 12650 final boolean succeded; 12651 synchronized (mInstallLock) { 12652 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12653 } 12654 clearExternalStorageDataSync(packageName, userId, false); 12655 if (observer != null) { 12656 try { 12657 observer.onRemoveCompleted(packageName, succeded); 12658 } catch (RemoteException e) { 12659 Log.i(TAG, "Observer no longer exists."); 12660 } 12661 } //end if observer 12662 } //end run 12663 }); 12664 } 12665 12666 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12667 if (packageName == null) { 12668 Slog.w(TAG, "Attempt to delete null packageName."); 12669 return false; 12670 } 12671 PackageParser.Package p; 12672 synchronized (mPackages) { 12673 p = mPackages.get(packageName); 12674 } 12675 if (p == null) { 12676 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12677 return false; 12678 } 12679 final ApplicationInfo applicationInfo = p.applicationInfo; 12680 if (applicationInfo == null) { 12681 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12682 return false; 12683 } 12684 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12685 if (retCode < 0) { 12686 Slog.w(TAG, "Couldn't remove cache files for package: " 12687 + packageName + " u" + userId); 12688 return false; 12689 } 12690 return true; 12691 } 12692 12693 @Override 12694 public void getPackageSizeInfo(final String packageName, int userHandle, 12695 final IPackageStatsObserver observer) { 12696 mContext.enforceCallingOrSelfPermission( 12697 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12698 if (packageName == null) { 12699 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12700 } 12701 12702 PackageStats stats = new PackageStats(packageName, userHandle); 12703 12704 /* 12705 * Queue up an async operation since the package measurement may take a 12706 * little while. 12707 */ 12708 Message msg = mHandler.obtainMessage(INIT_COPY); 12709 msg.obj = new MeasureParams(stats, observer); 12710 mHandler.sendMessage(msg); 12711 } 12712 12713 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12714 PackageStats pStats) { 12715 if (packageName == null) { 12716 Slog.w(TAG, "Attempt to get size of null packageName."); 12717 return false; 12718 } 12719 PackageParser.Package p; 12720 boolean dataOnly = false; 12721 String libDirRoot = null; 12722 String asecPath = null; 12723 PackageSetting ps = null; 12724 synchronized (mPackages) { 12725 p = mPackages.get(packageName); 12726 ps = mSettings.mPackages.get(packageName); 12727 if(p == null) { 12728 dataOnly = true; 12729 if((ps == null) || (ps.pkg == null)) { 12730 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12731 return false; 12732 } 12733 p = ps.pkg; 12734 } 12735 if (ps != null) { 12736 libDirRoot = ps.legacyNativeLibraryPathString; 12737 } 12738 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12739 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12740 if (secureContainerId != null) { 12741 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12742 } 12743 } 12744 } 12745 String publicSrcDir = null; 12746 if(!dataOnly) { 12747 final ApplicationInfo applicationInfo = p.applicationInfo; 12748 if (applicationInfo == null) { 12749 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12750 return false; 12751 } 12752 if (p.isForwardLocked()) { 12753 publicSrcDir = applicationInfo.getBaseResourcePath(); 12754 } 12755 } 12756 // TODO: extend to measure size of split APKs 12757 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12758 // not just the first level. 12759 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12760 // just the primary. 12761 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12762 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12763 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12764 if (res < 0) { 12765 return false; 12766 } 12767 12768 // Fix-up for forward-locked applications in ASEC containers. 12769 if (!isExternal(p)) { 12770 pStats.codeSize += pStats.externalCodeSize; 12771 pStats.externalCodeSize = 0L; 12772 } 12773 12774 return true; 12775 } 12776 12777 12778 @Override 12779 public void addPackageToPreferred(String packageName) { 12780 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12781 } 12782 12783 @Override 12784 public void removePackageFromPreferred(String packageName) { 12785 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12786 } 12787 12788 @Override 12789 public List<PackageInfo> getPreferredPackages(int flags) { 12790 return new ArrayList<PackageInfo>(); 12791 } 12792 12793 private int getUidTargetSdkVersionLockedLPr(int uid) { 12794 Object obj = mSettings.getUserIdLPr(uid); 12795 if (obj instanceof SharedUserSetting) { 12796 final SharedUserSetting sus = (SharedUserSetting) obj; 12797 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12798 final Iterator<PackageSetting> it = sus.packages.iterator(); 12799 while (it.hasNext()) { 12800 final PackageSetting ps = it.next(); 12801 if (ps.pkg != null) { 12802 int v = ps.pkg.applicationInfo.targetSdkVersion; 12803 if (v < vers) vers = v; 12804 } 12805 } 12806 return vers; 12807 } else if (obj instanceof PackageSetting) { 12808 final PackageSetting ps = (PackageSetting) obj; 12809 if (ps.pkg != null) { 12810 return ps.pkg.applicationInfo.targetSdkVersion; 12811 } 12812 } 12813 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12814 } 12815 12816 @Override 12817 public void addPreferredActivity(IntentFilter filter, int match, 12818 ComponentName[] set, ComponentName activity, int userId) { 12819 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12820 "Adding preferred"); 12821 } 12822 12823 private void addPreferredActivityInternal(IntentFilter filter, int match, 12824 ComponentName[] set, ComponentName activity, boolean always, int userId, 12825 String opname) { 12826 // writer 12827 int callingUid = Binder.getCallingUid(); 12828 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12829 if (filter.countActions() == 0) { 12830 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12831 return; 12832 } 12833 synchronized (mPackages) { 12834 if (mContext.checkCallingOrSelfPermission( 12835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12836 != PackageManager.PERMISSION_GRANTED) { 12837 if (getUidTargetSdkVersionLockedLPr(callingUid) 12838 < Build.VERSION_CODES.FROYO) { 12839 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12840 + callingUid); 12841 return; 12842 } 12843 mContext.enforceCallingOrSelfPermission( 12844 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12845 } 12846 12847 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12848 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12849 + userId + ":"); 12850 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12851 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12852 scheduleWritePackageRestrictionsLocked(userId); 12853 } 12854 } 12855 12856 @Override 12857 public void replacePreferredActivity(IntentFilter filter, int match, 12858 ComponentName[] set, ComponentName activity, int userId) { 12859 if (filter.countActions() != 1) { 12860 throw new IllegalArgumentException( 12861 "replacePreferredActivity expects filter to have only 1 action."); 12862 } 12863 if (filter.countDataAuthorities() != 0 12864 || filter.countDataPaths() != 0 12865 || filter.countDataSchemes() > 1 12866 || filter.countDataTypes() != 0) { 12867 throw new IllegalArgumentException( 12868 "replacePreferredActivity expects filter to have no data authorities, " + 12869 "paths, or types; and at most one scheme."); 12870 } 12871 12872 final int callingUid = Binder.getCallingUid(); 12873 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12874 synchronized (mPackages) { 12875 if (mContext.checkCallingOrSelfPermission( 12876 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12877 != PackageManager.PERMISSION_GRANTED) { 12878 if (getUidTargetSdkVersionLockedLPr(callingUid) 12879 < Build.VERSION_CODES.FROYO) { 12880 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12881 + Binder.getCallingUid()); 12882 return; 12883 } 12884 mContext.enforceCallingOrSelfPermission( 12885 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12886 } 12887 12888 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12889 if (pir != null) { 12890 // Get all of the existing entries that exactly match this filter. 12891 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12892 if (existing != null && existing.size() == 1) { 12893 PreferredActivity cur = existing.get(0); 12894 if (DEBUG_PREFERRED) { 12895 Slog.i(TAG, "Checking replace of preferred:"); 12896 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12897 if (!cur.mPref.mAlways) { 12898 Slog.i(TAG, " -- CUR; not mAlways!"); 12899 } else { 12900 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12901 Slog.i(TAG, " -- CUR: mSet=" 12902 + Arrays.toString(cur.mPref.mSetComponents)); 12903 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12904 Slog.i(TAG, " -- NEW: mMatch=" 12905 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12906 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12907 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12908 } 12909 } 12910 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12911 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12912 && cur.mPref.sameSet(set)) { 12913 // Setting the preferred activity to what it happens to be already 12914 if (DEBUG_PREFERRED) { 12915 Slog.i(TAG, "Replacing with same preferred activity " 12916 + cur.mPref.mShortComponent + " for user " 12917 + userId + ":"); 12918 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12919 } 12920 return; 12921 } 12922 } 12923 12924 if (existing != null) { 12925 if (DEBUG_PREFERRED) { 12926 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12927 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12928 } 12929 for (int i = 0; i < existing.size(); i++) { 12930 PreferredActivity pa = existing.get(i); 12931 if (DEBUG_PREFERRED) { 12932 Slog.i(TAG, "Removing existing preferred activity " 12933 + pa.mPref.mComponent + ":"); 12934 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12935 } 12936 pir.removeFilter(pa); 12937 } 12938 } 12939 } 12940 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12941 "Replacing preferred"); 12942 } 12943 } 12944 12945 @Override 12946 public void clearPackagePreferredActivities(String packageName) { 12947 final int uid = Binder.getCallingUid(); 12948 // writer 12949 synchronized (mPackages) { 12950 PackageParser.Package pkg = mPackages.get(packageName); 12951 if (pkg == null || pkg.applicationInfo.uid != uid) { 12952 if (mContext.checkCallingOrSelfPermission( 12953 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12954 != PackageManager.PERMISSION_GRANTED) { 12955 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12956 < Build.VERSION_CODES.FROYO) { 12957 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12958 + Binder.getCallingUid()); 12959 return; 12960 } 12961 mContext.enforceCallingOrSelfPermission( 12962 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12963 } 12964 } 12965 12966 int user = UserHandle.getCallingUserId(); 12967 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12968 scheduleWritePackageRestrictionsLocked(user); 12969 } 12970 } 12971 } 12972 12973 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12974 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12975 ArrayList<PreferredActivity> removed = null; 12976 boolean changed = false; 12977 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12978 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12979 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12980 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12981 continue; 12982 } 12983 Iterator<PreferredActivity> it = pir.filterIterator(); 12984 while (it.hasNext()) { 12985 PreferredActivity pa = it.next(); 12986 // Mark entry for removal only if it matches the package name 12987 // and the entry is of type "always". 12988 if (packageName == null || 12989 (pa.mPref.mComponent.getPackageName().equals(packageName) 12990 && pa.mPref.mAlways)) { 12991 if (removed == null) { 12992 removed = new ArrayList<PreferredActivity>(); 12993 } 12994 removed.add(pa); 12995 } 12996 } 12997 if (removed != null) { 12998 for (int j=0; j<removed.size(); j++) { 12999 PreferredActivity pa = removed.get(j); 13000 pir.removeFilter(pa); 13001 } 13002 changed = true; 13003 } 13004 } 13005 return changed; 13006 } 13007 13008 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13009 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13010 if (userId == UserHandle.USER_ALL) { 13011 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13012 sUserManager.getUserIds())) { 13013 for (int oneUserId : sUserManager.getUserIds()) { 13014 scheduleWritePackageRestrictionsLocked(oneUserId); 13015 } 13016 } 13017 } else { 13018 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13019 scheduleWritePackageRestrictionsLocked(userId); 13020 } 13021 } 13022 } 13023 13024 13025 void clearDefaultBrowserIfNeeded(String packageName) { 13026 for (int oneUserId : sUserManager.getUserIds()) { 13027 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13028 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13029 if (packageName.equals(defaultBrowserPackageName)) { 13030 setDefaultBrowserPackageName(null, oneUserId); 13031 } 13032 } 13033 } 13034 13035 @Override 13036 public void resetPreferredActivities(int userId) { 13037 /* TODO: Actually use userId. Why is it being passed in? */ 13038 mContext.enforceCallingOrSelfPermission( 13039 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13040 // writer 13041 synchronized (mPackages) { 13042 int user = UserHandle.getCallingUserId(); 13043 clearPackagePreferredActivitiesLPw(null, user); 13044 mSettings.readDefaultPreferredAppsLPw(this, user); 13045 scheduleWritePackageRestrictionsLocked(user); 13046 } 13047 } 13048 13049 @Override 13050 public int getPreferredActivities(List<IntentFilter> outFilters, 13051 List<ComponentName> outActivities, String packageName) { 13052 13053 int num = 0; 13054 final int userId = UserHandle.getCallingUserId(); 13055 // reader 13056 synchronized (mPackages) { 13057 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13058 if (pir != null) { 13059 final Iterator<PreferredActivity> it = pir.filterIterator(); 13060 while (it.hasNext()) { 13061 final PreferredActivity pa = it.next(); 13062 if (packageName == null 13063 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13064 && pa.mPref.mAlways)) { 13065 if (outFilters != null) { 13066 outFilters.add(new IntentFilter(pa)); 13067 } 13068 if (outActivities != null) { 13069 outActivities.add(pa.mPref.mComponent); 13070 } 13071 } 13072 } 13073 } 13074 } 13075 13076 return num; 13077 } 13078 13079 @Override 13080 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13081 int userId) { 13082 int callingUid = Binder.getCallingUid(); 13083 if (callingUid != Process.SYSTEM_UID) { 13084 throw new SecurityException( 13085 "addPersistentPreferredActivity can only be run by the system"); 13086 } 13087 if (filter.countActions() == 0) { 13088 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13089 return; 13090 } 13091 synchronized (mPackages) { 13092 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13093 " :"); 13094 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13095 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13096 new PersistentPreferredActivity(filter, activity)); 13097 scheduleWritePackageRestrictionsLocked(userId); 13098 } 13099 } 13100 13101 @Override 13102 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13103 int callingUid = Binder.getCallingUid(); 13104 if (callingUid != Process.SYSTEM_UID) { 13105 throw new SecurityException( 13106 "clearPackagePersistentPreferredActivities can only be run by the system"); 13107 } 13108 ArrayList<PersistentPreferredActivity> removed = null; 13109 boolean changed = false; 13110 synchronized (mPackages) { 13111 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13112 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13113 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13114 .valueAt(i); 13115 if (userId != thisUserId) { 13116 continue; 13117 } 13118 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13119 while (it.hasNext()) { 13120 PersistentPreferredActivity ppa = it.next(); 13121 // Mark entry for removal only if it matches the package name. 13122 if (ppa.mComponent.getPackageName().equals(packageName)) { 13123 if (removed == null) { 13124 removed = new ArrayList<PersistentPreferredActivity>(); 13125 } 13126 removed.add(ppa); 13127 } 13128 } 13129 if (removed != null) { 13130 for (int j=0; j<removed.size(); j++) { 13131 PersistentPreferredActivity ppa = removed.get(j); 13132 ppir.removeFilter(ppa); 13133 } 13134 changed = true; 13135 } 13136 } 13137 13138 if (changed) { 13139 scheduleWritePackageRestrictionsLocked(userId); 13140 } 13141 } 13142 } 13143 13144 /** 13145 * Non-Binder method, support for the backup/restore mechanism: write the 13146 * full set of preferred activities in its canonical XML format. Returns true 13147 * on success; false otherwise. 13148 */ 13149 @Override 13150 public byte[] getPreferredActivityBackup(int userId) { 13151 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13152 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13153 } 13154 13155 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13156 try { 13157 final XmlSerializer serializer = new FastXmlSerializer(); 13158 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13159 serializer.startDocument(null, true); 13160 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13161 13162 synchronized (mPackages) { 13163 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13164 } 13165 13166 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13167 serializer.endDocument(); 13168 serializer.flush(); 13169 } catch (Exception e) { 13170 if (DEBUG_BACKUP) { 13171 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13172 } 13173 return null; 13174 } 13175 13176 return dataStream.toByteArray(); 13177 } 13178 13179 @Override 13180 public void restorePreferredActivities(byte[] backup, int userId) { 13181 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13182 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13183 } 13184 13185 try { 13186 final XmlPullParser parser = Xml.newPullParser(); 13187 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13188 13189 int type; 13190 while ((type = parser.next()) != XmlPullParser.START_TAG 13191 && type != XmlPullParser.END_DOCUMENT) { 13192 } 13193 if (type != XmlPullParser.START_TAG) { 13194 // oops didn't find a start tag?! 13195 if (DEBUG_BACKUP) { 13196 Slog.e(TAG, "Didn't find start tag during restore"); 13197 } 13198 return; 13199 } 13200 13201 // this is supposed to be TAG_PREFERRED_BACKUP 13202 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13203 if (DEBUG_BACKUP) { 13204 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13205 } 13206 return; 13207 } 13208 13209 // skip interfering stuff, then we're aligned with the backing implementation 13210 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13211 synchronized (mPackages) { 13212 mSettings.readPreferredActivitiesLPw(parser, userId); 13213 } 13214 } catch (Exception e) { 13215 if (DEBUG_BACKUP) { 13216 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13217 } 13218 } 13219 } 13220 13221 @Override 13222 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13223 int sourceUserId, int targetUserId, int flags) { 13224 mContext.enforceCallingOrSelfPermission( 13225 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13226 int callingUid = Binder.getCallingUid(); 13227 enforceOwnerRights(ownerPackage, callingUid); 13228 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13229 if (intentFilter.countActions() == 0) { 13230 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13231 return; 13232 } 13233 synchronized (mPackages) { 13234 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13235 ownerPackage, targetUserId, flags); 13236 CrossProfileIntentResolver resolver = 13237 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13238 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13239 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13240 if (existing != null) { 13241 int size = existing.size(); 13242 for (int i = 0; i < size; i++) { 13243 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13244 return; 13245 } 13246 } 13247 } 13248 resolver.addFilter(newFilter); 13249 scheduleWritePackageRestrictionsLocked(sourceUserId); 13250 } 13251 } 13252 13253 @Override 13254 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13255 mContext.enforceCallingOrSelfPermission( 13256 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13257 int callingUid = Binder.getCallingUid(); 13258 enforceOwnerRights(ownerPackage, callingUid); 13259 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13260 synchronized (mPackages) { 13261 CrossProfileIntentResolver resolver = 13262 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13263 ArraySet<CrossProfileIntentFilter> set = 13264 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13265 for (CrossProfileIntentFilter filter : set) { 13266 if (filter.getOwnerPackage().equals(ownerPackage)) { 13267 resolver.removeFilter(filter); 13268 } 13269 } 13270 scheduleWritePackageRestrictionsLocked(sourceUserId); 13271 } 13272 } 13273 13274 // Enforcing that callingUid is owning pkg on userId 13275 private void enforceOwnerRights(String pkg, int callingUid) { 13276 // The system owns everything. 13277 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13278 return; 13279 } 13280 int callingUserId = UserHandle.getUserId(callingUid); 13281 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13282 if (pi == null) { 13283 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13284 + callingUserId); 13285 } 13286 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13287 throw new SecurityException("Calling uid " + callingUid 13288 + " does not own package " + pkg); 13289 } 13290 } 13291 13292 @Override 13293 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13294 Intent intent = new Intent(Intent.ACTION_MAIN); 13295 intent.addCategory(Intent.CATEGORY_HOME); 13296 13297 final int callingUserId = UserHandle.getCallingUserId(); 13298 List<ResolveInfo> list = queryIntentActivities(intent, null, 13299 PackageManager.GET_META_DATA, callingUserId); 13300 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13301 true, false, false, callingUserId); 13302 13303 allHomeCandidates.clear(); 13304 if (list != null) { 13305 for (ResolveInfo ri : list) { 13306 allHomeCandidates.add(ri); 13307 } 13308 } 13309 return (preferred == null || preferred.activityInfo == null) 13310 ? null 13311 : new ComponentName(preferred.activityInfo.packageName, 13312 preferred.activityInfo.name); 13313 } 13314 13315 @Override 13316 public void setApplicationEnabledSetting(String appPackageName, 13317 int newState, int flags, int userId, String callingPackage) { 13318 if (!sUserManager.exists(userId)) return; 13319 if (callingPackage == null) { 13320 callingPackage = Integer.toString(Binder.getCallingUid()); 13321 } 13322 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13323 } 13324 13325 @Override 13326 public void setComponentEnabledSetting(ComponentName componentName, 13327 int newState, int flags, int userId) { 13328 if (!sUserManager.exists(userId)) return; 13329 setEnabledSetting(componentName.getPackageName(), 13330 componentName.getClassName(), newState, flags, userId, null); 13331 } 13332 13333 private void setEnabledSetting(final String packageName, String className, int newState, 13334 final int flags, int userId, String callingPackage) { 13335 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13336 || newState == COMPONENT_ENABLED_STATE_ENABLED 13337 || newState == COMPONENT_ENABLED_STATE_DISABLED 13338 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13339 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13340 throw new IllegalArgumentException("Invalid new component state: " 13341 + newState); 13342 } 13343 PackageSetting pkgSetting; 13344 final int uid = Binder.getCallingUid(); 13345 final int permission = mContext.checkCallingOrSelfPermission( 13346 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13347 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13348 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13349 boolean sendNow = false; 13350 boolean isApp = (className == null); 13351 String componentName = isApp ? packageName : className; 13352 int packageUid = -1; 13353 ArrayList<String> components; 13354 13355 // writer 13356 synchronized (mPackages) { 13357 pkgSetting = mSettings.mPackages.get(packageName); 13358 if (pkgSetting == null) { 13359 if (className == null) { 13360 throw new IllegalArgumentException( 13361 "Unknown package: " + packageName); 13362 } 13363 throw new IllegalArgumentException( 13364 "Unknown component: " + packageName 13365 + "/" + className); 13366 } 13367 // Allow root and verify that userId is not being specified by a different user 13368 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13369 throw new SecurityException( 13370 "Permission Denial: attempt to change component state from pid=" 13371 + Binder.getCallingPid() 13372 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13373 } 13374 if (className == null) { 13375 // We're dealing with an application/package level state change 13376 if (pkgSetting.getEnabled(userId) == newState) { 13377 // Nothing to do 13378 return; 13379 } 13380 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13381 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13382 // Don't care about who enables an app. 13383 callingPackage = null; 13384 } 13385 pkgSetting.setEnabled(newState, userId, callingPackage); 13386 // pkgSetting.pkg.mSetEnabled = newState; 13387 } else { 13388 // We're dealing with a component level state change 13389 // First, verify that this is a valid class name. 13390 PackageParser.Package pkg = pkgSetting.pkg; 13391 if (pkg == null || !pkg.hasComponentClassName(className)) { 13392 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13393 throw new IllegalArgumentException("Component class " + className 13394 + " does not exist in " + packageName); 13395 } else { 13396 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13397 + className + " does not exist in " + packageName); 13398 } 13399 } 13400 switch (newState) { 13401 case COMPONENT_ENABLED_STATE_ENABLED: 13402 if (!pkgSetting.enableComponentLPw(className, userId)) { 13403 return; 13404 } 13405 break; 13406 case COMPONENT_ENABLED_STATE_DISABLED: 13407 if (!pkgSetting.disableComponentLPw(className, userId)) { 13408 return; 13409 } 13410 break; 13411 case COMPONENT_ENABLED_STATE_DEFAULT: 13412 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13413 return; 13414 } 13415 break; 13416 default: 13417 Slog.e(TAG, "Invalid new component state: " + newState); 13418 return; 13419 } 13420 } 13421 scheduleWritePackageRestrictionsLocked(userId); 13422 components = mPendingBroadcasts.get(userId, packageName); 13423 final boolean newPackage = components == null; 13424 if (newPackage) { 13425 components = new ArrayList<String>(); 13426 } 13427 if (!components.contains(componentName)) { 13428 components.add(componentName); 13429 } 13430 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13431 sendNow = true; 13432 // Purge entry from pending broadcast list if another one exists already 13433 // since we are sending one right away. 13434 mPendingBroadcasts.remove(userId, packageName); 13435 } else { 13436 if (newPackage) { 13437 mPendingBroadcasts.put(userId, packageName, components); 13438 } 13439 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13440 // Schedule a message 13441 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13442 } 13443 } 13444 } 13445 13446 long callingId = Binder.clearCallingIdentity(); 13447 try { 13448 if (sendNow) { 13449 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13450 sendPackageChangedBroadcast(packageName, 13451 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13452 } 13453 } finally { 13454 Binder.restoreCallingIdentity(callingId); 13455 } 13456 } 13457 13458 private void sendPackageChangedBroadcast(String packageName, 13459 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13460 if (DEBUG_INSTALL) 13461 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13462 + componentNames); 13463 Bundle extras = new Bundle(4); 13464 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13465 String nameList[] = new String[componentNames.size()]; 13466 componentNames.toArray(nameList); 13467 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13468 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13469 extras.putInt(Intent.EXTRA_UID, packageUid); 13470 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13471 new int[] {UserHandle.getUserId(packageUid)}); 13472 } 13473 13474 @Override 13475 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13476 if (!sUserManager.exists(userId)) return; 13477 final int uid = Binder.getCallingUid(); 13478 final int permission = mContext.checkCallingOrSelfPermission( 13479 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13480 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13481 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13482 // writer 13483 synchronized (mPackages) { 13484 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13485 allowedByPermission, uid, userId)) { 13486 scheduleWritePackageRestrictionsLocked(userId); 13487 } 13488 } 13489 } 13490 13491 @Override 13492 public String getInstallerPackageName(String packageName) { 13493 // reader 13494 synchronized (mPackages) { 13495 return mSettings.getInstallerPackageNameLPr(packageName); 13496 } 13497 } 13498 13499 @Override 13500 public int getApplicationEnabledSetting(String packageName, int userId) { 13501 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13502 int uid = Binder.getCallingUid(); 13503 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13504 // reader 13505 synchronized (mPackages) { 13506 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13507 } 13508 } 13509 13510 @Override 13511 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13512 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13513 int uid = Binder.getCallingUid(); 13514 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13515 // reader 13516 synchronized (mPackages) { 13517 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13518 } 13519 } 13520 13521 @Override 13522 public void enterSafeMode() { 13523 enforceSystemOrRoot("Only the system can request entering safe mode"); 13524 13525 if (!mSystemReady) { 13526 mSafeMode = true; 13527 } 13528 } 13529 13530 @Override 13531 public void systemReady() { 13532 mSystemReady = true; 13533 13534 // Read the compatibilty setting when the system is ready. 13535 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13536 mContext.getContentResolver(), 13537 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13538 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13539 if (DEBUG_SETTINGS) { 13540 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13541 } 13542 13543 synchronized (mPackages) { 13544 // Verify that all of the preferred activity components actually 13545 // exist. It is possible for applications to be updated and at 13546 // that point remove a previously declared activity component that 13547 // had been set as a preferred activity. We try to clean this up 13548 // the next time we encounter that preferred activity, but it is 13549 // possible for the user flow to never be able to return to that 13550 // situation so here we do a sanity check to make sure we haven't 13551 // left any junk around. 13552 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13553 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13554 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13555 removed.clear(); 13556 for (PreferredActivity pa : pir.filterSet()) { 13557 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13558 removed.add(pa); 13559 } 13560 } 13561 if (removed.size() > 0) { 13562 for (int r=0; r<removed.size(); r++) { 13563 PreferredActivity pa = removed.get(r); 13564 Slog.w(TAG, "Removing dangling preferred activity: " 13565 + pa.mPref.mComponent); 13566 pir.removeFilter(pa); 13567 } 13568 mSettings.writePackageRestrictionsLPr( 13569 mSettings.mPreferredActivities.keyAt(i)); 13570 } 13571 } 13572 } 13573 sUserManager.systemReady(); 13574 13575 // Kick off any messages waiting for system ready 13576 if (mPostSystemReadyMessages != null) { 13577 for (Message msg : mPostSystemReadyMessages) { 13578 msg.sendToTarget(); 13579 } 13580 mPostSystemReadyMessages = null; 13581 } 13582 13583 // Watch for external volumes that come and go over time 13584 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13585 storage.registerListener(mStorageListener); 13586 13587 mInstallerService.systemReady(); 13588 mPackageDexOptimizer.systemReady(); 13589 } 13590 13591 @Override 13592 public boolean isSafeMode() { 13593 return mSafeMode; 13594 } 13595 13596 @Override 13597 public boolean hasSystemUidErrors() { 13598 return mHasSystemUidErrors; 13599 } 13600 13601 static String arrayToString(int[] array) { 13602 StringBuffer buf = new StringBuffer(128); 13603 buf.append('['); 13604 if (array != null) { 13605 for (int i=0; i<array.length; i++) { 13606 if (i > 0) buf.append(", "); 13607 buf.append(array[i]); 13608 } 13609 } 13610 buf.append(']'); 13611 return buf.toString(); 13612 } 13613 13614 static class DumpState { 13615 public static final int DUMP_LIBS = 1 << 0; 13616 public static final int DUMP_FEATURES = 1 << 1; 13617 public static final int DUMP_RESOLVERS = 1 << 2; 13618 public static final int DUMP_PERMISSIONS = 1 << 3; 13619 public static final int DUMP_PACKAGES = 1 << 4; 13620 public static final int DUMP_SHARED_USERS = 1 << 5; 13621 public static final int DUMP_MESSAGES = 1 << 6; 13622 public static final int DUMP_PROVIDERS = 1 << 7; 13623 public static final int DUMP_VERIFIERS = 1 << 8; 13624 public static final int DUMP_PREFERRED = 1 << 9; 13625 public static final int DUMP_PREFERRED_XML = 1 << 10; 13626 public static final int DUMP_KEYSETS = 1 << 11; 13627 public static final int DUMP_VERSION = 1 << 12; 13628 public static final int DUMP_INSTALLS = 1 << 13; 13629 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13630 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13631 13632 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13633 13634 private int mTypes; 13635 13636 private int mOptions; 13637 13638 private boolean mTitlePrinted; 13639 13640 private SharedUserSetting mSharedUser; 13641 13642 public boolean isDumping(int type) { 13643 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13644 return true; 13645 } 13646 13647 return (mTypes & type) != 0; 13648 } 13649 13650 public void setDump(int type) { 13651 mTypes |= type; 13652 } 13653 13654 public boolean isOptionEnabled(int option) { 13655 return (mOptions & option) != 0; 13656 } 13657 13658 public void setOptionEnabled(int option) { 13659 mOptions |= option; 13660 } 13661 13662 public boolean onTitlePrinted() { 13663 final boolean printed = mTitlePrinted; 13664 mTitlePrinted = true; 13665 return printed; 13666 } 13667 13668 public boolean getTitlePrinted() { 13669 return mTitlePrinted; 13670 } 13671 13672 public void setTitlePrinted(boolean enabled) { 13673 mTitlePrinted = enabled; 13674 } 13675 13676 public SharedUserSetting getSharedUser() { 13677 return mSharedUser; 13678 } 13679 13680 public void setSharedUser(SharedUserSetting user) { 13681 mSharedUser = user; 13682 } 13683 } 13684 13685 @Override 13686 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13687 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13688 != PackageManager.PERMISSION_GRANTED) { 13689 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13690 + Binder.getCallingPid() 13691 + ", uid=" + Binder.getCallingUid() 13692 + " without permission " 13693 + android.Manifest.permission.DUMP); 13694 return; 13695 } 13696 13697 DumpState dumpState = new DumpState(); 13698 boolean fullPreferred = false; 13699 boolean checkin = false; 13700 13701 String packageName = null; 13702 13703 int opti = 0; 13704 while (opti < args.length) { 13705 String opt = args[opti]; 13706 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13707 break; 13708 } 13709 opti++; 13710 13711 if ("-a".equals(opt)) { 13712 // Right now we only know how to print all. 13713 } else if ("-h".equals(opt)) { 13714 pw.println("Package manager dump options:"); 13715 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13716 pw.println(" --checkin: dump for a checkin"); 13717 pw.println(" -f: print details of intent filters"); 13718 pw.println(" -h: print this help"); 13719 pw.println(" cmd may be one of:"); 13720 pw.println(" l[ibraries]: list known shared libraries"); 13721 pw.println(" f[ibraries]: list device features"); 13722 pw.println(" k[eysets]: print known keysets"); 13723 pw.println(" r[esolvers]: dump intent resolvers"); 13724 pw.println(" perm[issions]: dump permissions"); 13725 pw.println(" pref[erred]: print preferred package settings"); 13726 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13727 pw.println(" prov[iders]: dump content providers"); 13728 pw.println(" p[ackages]: dump installed packages"); 13729 pw.println(" s[hared-users]: dump shared user IDs"); 13730 pw.println(" m[essages]: print collected runtime messages"); 13731 pw.println(" v[erifiers]: print package verifier info"); 13732 pw.println(" version: print database version info"); 13733 pw.println(" write: write current settings now"); 13734 pw.println(" <package.name>: info about given package"); 13735 pw.println(" installs: details about install sessions"); 13736 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13737 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13738 return; 13739 } else if ("--checkin".equals(opt)) { 13740 checkin = true; 13741 } else if ("-f".equals(opt)) { 13742 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13743 } else { 13744 pw.println("Unknown argument: " + opt + "; use -h for help"); 13745 } 13746 } 13747 13748 // Is the caller requesting to dump a particular piece of data? 13749 if (opti < args.length) { 13750 String cmd = args[opti]; 13751 opti++; 13752 // Is this a package name? 13753 if ("android".equals(cmd) || cmd.contains(".")) { 13754 packageName = cmd; 13755 // When dumping a single package, we always dump all of its 13756 // filter information since the amount of data will be reasonable. 13757 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13758 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13759 dumpState.setDump(DumpState.DUMP_LIBS); 13760 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13761 dumpState.setDump(DumpState.DUMP_FEATURES); 13762 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13763 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13764 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13765 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13766 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13767 dumpState.setDump(DumpState.DUMP_PREFERRED); 13768 } else if ("preferred-xml".equals(cmd)) { 13769 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13770 if (opti < args.length && "--full".equals(args[opti])) { 13771 fullPreferred = true; 13772 opti++; 13773 } 13774 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13775 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13776 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13777 dumpState.setDump(DumpState.DUMP_PACKAGES); 13778 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13779 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13780 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13781 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13782 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13783 dumpState.setDump(DumpState.DUMP_MESSAGES); 13784 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13785 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13786 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13787 || "intent-filter-verifiers".equals(cmd)) { 13788 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13789 } else if ("version".equals(cmd)) { 13790 dumpState.setDump(DumpState.DUMP_VERSION); 13791 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13792 dumpState.setDump(DumpState.DUMP_KEYSETS); 13793 } else if ("installs".equals(cmd)) { 13794 dumpState.setDump(DumpState.DUMP_INSTALLS); 13795 } else if ("write".equals(cmd)) { 13796 synchronized (mPackages) { 13797 mSettings.writeLPr(); 13798 pw.println("Settings written."); 13799 return; 13800 } 13801 } 13802 } 13803 13804 if (checkin) { 13805 pw.println("vers,1"); 13806 } 13807 13808 // reader 13809 synchronized (mPackages) { 13810 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13811 if (!checkin) { 13812 if (dumpState.onTitlePrinted()) 13813 pw.println(); 13814 pw.println("Database versions:"); 13815 pw.print(" SDK Version:"); 13816 pw.print(" internal="); 13817 pw.print(mSettings.mInternalSdkPlatform); 13818 pw.print(" external="); 13819 pw.println(mSettings.mExternalSdkPlatform); 13820 pw.print(" DB Version:"); 13821 pw.print(" internal="); 13822 pw.print(mSettings.mInternalDatabaseVersion); 13823 pw.print(" external="); 13824 pw.println(mSettings.mExternalDatabaseVersion); 13825 } 13826 } 13827 13828 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13829 if (!checkin) { 13830 if (dumpState.onTitlePrinted()) 13831 pw.println(); 13832 pw.println("Verifiers:"); 13833 pw.print(" Required: "); 13834 pw.print(mRequiredVerifierPackage); 13835 pw.print(" (uid="); 13836 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13837 pw.println(")"); 13838 } else if (mRequiredVerifierPackage != null) { 13839 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13840 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13841 } 13842 } 13843 13844 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13845 packageName == null) { 13846 if (mIntentFilterVerifierComponent != null) { 13847 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13848 if (!checkin) { 13849 if (dumpState.onTitlePrinted()) 13850 pw.println(); 13851 pw.println("Intent Filter Verifier:"); 13852 pw.print(" Using: "); 13853 pw.print(verifierPackageName); 13854 pw.print(" (uid="); 13855 pw.print(getPackageUid(verifierPackageName, 0)); 13856 pw.println(")"); 13857 } else if (verifierPackageName != null) { 13858 pw.print("ifv,"); pw.print(verifierPackageName); 13859 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13860 } 13861 } else { 13862 pw.println(); 13863 pw.println("No Intent Filter Verifier available!"); 13864 } 13865 } 13866 13867 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13868 boolean printedHeader = false; 13869 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13870 while (it.hasNext()) { 13871 String name = it.next(); 13872 SharedLibraryEntry ent = mSharedLibraries.get(name); 13873 if (!checkin) { 13874 if (!printedHeader) { 13875 if (dumpState.onTitlePrinted()) 13876 pw.println(); 13877 pw.println("Libraries:"); 13878 printedHeader = true; 13879 } 13880 pw.print(" "); 13881 } else { 13882 pw.print("lib,"); 13883 } 13884 pw.print(name); 13885 if (!checkin) { 13886 pw.print(" -> "); 13887 } 13888 if (ent.path != null) { 13889 if (!checkin) { 13890 pw.print("(jar) "); 13891 pw.print(ent.path); 13892 } else { 13893 pw.print(",jar,"); 13894 pw.print(ent.path); 13895 } 13896 } else { 13897 if (!checkin) { 13898 pw.print("(apk) "); 13899 pw.print(ent.apk); 13900 } else { 13901 pw.print(",apk,"); 13902 pw.print(ent.apk); 13903 } 13904 } 13905 pw.println(); 13906 } 13907 } 13908 13909 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13910 if (dumpState.onTitlePrinted()) 13911 pw.println(); 13912 if (!checkin) { 13913 pw.println("Features:"); 13914 } 13915 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13916 while (it.hasNext()) { 13917 String name = it.next(); 13918 if (!checkin) { 13919 pw.print(" "); 13920 } else { 13921 pw.print("feat,"); 13922 } 13923 pw.println(name); 13924 } 13925 } 13926 13927 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13928 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13929 : "Activity Resolver Table:", " ", packageName, 13930 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13931 dumpState.setTitlePrinted(true); 13932 } 13933 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13934 : "Receiver Resolver Table:", " ", packageName, 13935 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13936 dumpState.setTitlePrinted(true); 13937 } 13938 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13939 : "Service Resolver Table:", " ", packageName, 13940 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13941 dumpState.setTitlePrinted(true); 13942 } 13943 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13944 : "Provider Resolver Table:", " ", packageName, 13945 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13946 dumpState.setTitlePrinted(true); 13947 } 13948 } 13949 13950 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13951 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13952 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13953 int user = mSettings.mPreferredActivities.keyAt(i); 13954 if (pir.dump(pw, 13955 dumpState.getTitlePrinted() 13956 ? "\nPreferred Activities User " + user + ":" 13957 : "Preferred Activities User " + user + ":", " ", 13958 packageName, true, false)) { 13959 dumpState.setTitlePrinted(true); 13960 } 13961 } 13962 } 13963 13964 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13965 pw.flush(); 13966 FileOutputStream fout = new FileOutputStream(fd); 13967 BufferedOutputStream str = new BufferedOutputStream(fout); 13968 XmlSerializer serializer = new FastXmlSerializer(); 13969 try { 13970 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 13971 serializer.startDocument(null, true); 13972 serializer.setFeature( 13973 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13974 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13975 serializer.endDocument(); 13976 serializer.flush(); 13977 } catch (IllegalArgumentException e) { 13978 pw.println("Failed writing: " + e); 13979 } catch (IllegalStateException e) { 13980 pw.println("Failed writing: " + e); 13981 } catch (IOException e) { 13982 pw.println("Failed writing: " + e); 13983 } 13984 } 13985 13986 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13987 pw.println(); 13988 int count = mSettings.mPackages.size(); 13989 if (count == 0) { 13990 pw.println("No domain preferred apps!"); 13991 pw.println(); 13992 } else { 13993 final String prefix = " "; 13994 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13995 if (allPackageSettings.size() == 0) { 13996 pw.println("No domain preferred apps!"); 13997 pw.println(); 13998 } else { 13999 pw.println("Domain preferred apps status:"); 14000 pw.println(); 14001 count = 0; 14002 for (PackageSetting ps : allPackageSettings) { 14003 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14004 if (ivi == null || ivi.getPackageName() == null) continue; 14005 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14006 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14007 pw.println(prefix + "Status: " + ivi.getStatusString()); 14008 pw.println(); 14009 count++; 14010 } 14011 if (count == 0) { 14012 pw.println(prefix + "No domain preferred app status!"); 14013 pw.println(); 14014 } 14015 for (int userId : sUserManager.getUserIds()) { 14016 pw.println("Domain preferred apps for User " + userId + ":"); 14017 pw.println(); 14018 count = 0; 14019 for (PackageSetting ps : allPackageSettings) { 14020 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14021 if (ivi == null || ivi.getPackageName() == null) { 14022 continue; 14023 } 14024 final int status = ps.getDomainVerificationStatusForUser(userId); 14025 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14026 continue; 14027 } 14028 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14029 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14030 String statusStr = IntentFilterVerificationInfo. 14031 getStatusStringFromValue(status); 14032 pw.println(prefix + "Status: " + statusStr); 14033 pw.println(); 14034 count++; 14035 } 14036 if (count == 0) { 14037 pw.println(prefix + "No domain preferred apps!"); 14038 pw.println(); 14039 } 14040 } 14041 } 14042 } 14043 } 14044 14045 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14046 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14047 if (packageName == null) { 14048 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14049 if (iperm == 0) { 14050 if (dumpState.onTitlePrinted()) 14051 pw.println(); 14052 pw.println("AppOp Permissions:"); 14053 } 14054 pw.print(" AppOp Permission "); 14055 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14056 pw.println(":"); 14057 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14058 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14059 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14060 } 14061 } 14062 } 14063 } 14064 14065 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14066 boolean printedSomething = false; 14067 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14068 if (packageName != null && !packageName.equals(p.info.packageName)) { 14069 continue; 14070 } 14071 if (!printedSomething) { 14072 if (dumpState.onTitlePrinted()) 14073 pw.println(); 14074 pw.println("Registered ContentProviders:"); 14075 printedSomething = true; 14076 } 14077 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14078 pw.print(" "); pw.println(p.toString()); 14079 } 14080 printedSomething = false; 14081 for (Map.Entry<String, PackageParser.Provider> entry : 14082 mProvidersByAuthority.entrySet()) { 14083 PackageParser.Provider p = entry.getValue(); 14084 if (packageName != null && !packageName.equals(p.info.packageName)) { 14085 continue; 14086 } 14087 if (!printedSomething) { 14088 if (dumpState.onTitlePrinted()) 14089 pw.println(); 14090 pw.println("ContentProvider Authorities:"); 14091 printedSomething = true; 14092 } 14093 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14094 pw.print(" "); pw.println(p.toString()); 14095 if (p.info != null && p.info.applicationInfo != null) { 14096 final String appInfo = p.info.applicationInfo.toString(); 14097 pw.print(" applicationInfo="); pw.println(appInfo); 14098 } 14099 } 14100 } 14101 14102 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14103 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14104 } 14105 14106 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14107 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14108 } 14109 14110 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14111 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14112 } 14113 14114 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14115 // XXX should handle packageName != null by dumping only install data that 14116 // the given package is involved with. 14117 if (dumpState.onTitlePrinted()) pw.println(); 14118 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14119 } 14120 14121 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14122 if (dumpState.onTitlePrinted()) pw.println(); 14123 mSettings.dumpReadMessagesLPr(pw, dumpState); 14124 14125 pw.println(); 14126 pw.println("Package warning messages:"); 14127 BufferedReader in = null; 14128 String line = null; 14129 try { 14130 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14131 while ((line = in.readLine()) != null) { 14132 if (line.contains("ignored: updated version")) continue; 14133 pw.println(line); 14134 } 14135 } catch (IOException ignored) { 14136 } finally { 14137 IoUtils.closeQuietly(in); 14138 } 14139 } 14140 14141 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14142 BufferedReader in = null; 14143 String line = null; 14144 try { 14145 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14146 while ((line = in.readLine()) != null) { 14147 if (line.contains("ignored: updated version")) continue; 14148 pw.print("msg,"); 14149 pw.println(line); 14150 } 14151 } catch (IOException ignored) { 14152 } finally { 14153 IoUtils.closeQuietly(in); 14154 } 14155 } 14156 } 14157 } 14158 14159 // ------- apps on sdcard specific code ------- 14160 static final boolean DEBUG_SD_INSTALL = false; 14161 14162 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14163 14164 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14165 14166 private boolean mMediaMounted = false; 14167 14168 static String getEncryptKey() { 14169 try { 14170 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14171 SD_ENCRYPTION_KEYSTORE_NAME); 14172 if (sdEncKey == null) { 14173 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14174 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14175 if (sdEncKey == null) { 14176 Slog.e(TAG, "Failed to create encryption keys"); 14177 return null; 14178 } 14179 } 14180 return sdEncKey; 14181 } catch (NoSuchAlgorithmException nsae) { 14182 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14183 return null; 14184 } catch (IOException ioe) { 14185 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14186 return null; 14187 } 14188 } 14189 14190 /* 14191 * Update media status on PackageManager. 14192 */ 14193 @Override 14194 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14195 int callingUid = Binder.getCallingUid(); 14196 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14197 throw new SecurityException("Media status can only be updated by the system"); 14198 } 14199 // reader; this apparently protects mMediaMounted, but should probably 14200 // be a different lock in that case. 14201 synchronized (mPackages) { 14202 Log.i(TAG, "Updating external media status from " 14203 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14204 + (mediaStatus ? "mounted" : "unmounted")); 14205 if (DEBUG_SD_INSTALL) 14206 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14207 + ", mMediaMounted=" + mMediaMounted); 14208 if (mediaStatus == mMediaMounted) { 14209 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14210 : 0, -1); 14211 mHandler.sendMessage(msg); 14212 return; 14213 } 14214 mMediaMounted = mediaStatus; 14215 } 14216 // Queue up an async operation since the package installation may take a 14217 // little while. 14218 mHandler.post(new Runnable() { 14219 public void run() { 14220 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14221 } 14222 }); 14223 } 14224 14225 /** 14226 * Called by MountService when the initial ASECs to scan are available. 14227 * Should block until all the ASEC containers are finished being scanned. 14228 */ 14229 public void scanAvailableAsecs() { 14230 updateExternalMediaStatusInner(true, false, false); 14231 if (mShouldRestoreconData) { 14232 SELinuxMMAC.setRestoreconDone(); 14233 mShouldRestoreconData = false; 14234 } 14235 } 14236 14237 /* 14238 * Collect information of applications on external media, map them against 14239 * existing containers and update information based on current mount status. 14240 * Please note that we always have to report status if reportStatus has been 14241 * set to true especially when unloading packages. 14242 */ 14243 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14244 boolean externalStorage) { 14245 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14246 int[] uidArr = EmptyArray.INT; 14247 14248 final String[] list = PackageHelper.getSecureContainerList(); 14249 if (ArrayUtils.isEmpty(list)) { 14250 Log.i(TAG, "No secure containers found"); 14251 } else { 14252 // Process list of secure containers and categorize them 14253 // as active or stale based on their package internal state. 14254 14255 // reader 14256 synchronized (mPackages) { 14257 for (String cid : list) { 14258 // Leave stages untouched for now; installer service owns them 14259 if (PackageInstallerService.isStageName(cid)) continue; 14260 14261 if (DEBUG_SD_INSTALL) 14262 Log.i(TAG, "Processing container " + cid); 14263 String pkgName = getAsecPackageName(cid); 14264 if (pkgName == null) { 14265 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14266 continue; 14267 } 14268 if (DEBUG_SD_INSTALL) 14269 Log.i(TAG, "Looking for pkg : " + pkgName); 14270 14271 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14272 if (ps == null) { 14273 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14274 continue; 14275 } 14276 14277 /* 14278 * Skip packages that are not external if we're unmounting 14279 * external storage. 14280 */ 14281 if (externalStorage && !isMounted && !isExternal(ps)) { 14282 continue; 14283 } 14284 14285 final AsecInstallArgs args = new AsecInstallArgs(cid, 14286 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14287 // The package status is changed only if the code path 14288 // matches between settings and the container id. 14289 if (ps.codePathString != null 14290 && ps.codePathString.startsWith(args.getCodePath())) { 14291 if (DEBUG_SD_INSTALL) { 14292 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14293 + " at code path: " + ps.codePathString); 14294 } 14295 14296 // We do have a valid package installed on sdcard 14297 processCids.put(args, ps.codePathString); 14298 final int uid = ps.appId; 14299 if (uid != -1) { 14300 uidArr = ArrayUtils.appendInt(uidArr, uid); 14301 } 14302 } else { 14303 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14304 + ps.codePathString); 14305 } 14306 } 14307 } 14308 14309 Arrays.sort(uidArr); 14310 } 14311 14312 // Process packages with valid entries. 14313 if (isMounted) { 14314 if (DEBUG_SD_INSTALL) 14315 Log.i(TAG, "Loading packages"); 14316 loadMediaPackages(processCids, uidArr); 14317 startCleaningPackages(); 14318 mInstallerService.onSecureContainersAvailable(); 14319 } else { 14320 if (DEBUG_SD_INSTALL) 14321 Log.i(TAG, "Unloading packages"); 14322 unloadMediaPackages(processCids, uidArr, reportStatus); 14323 } 14324 } 14325 14326 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14327 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14328 final int size = infos.size(); 14329 final String[] packageNames = new String[size]; 14330 final int[] packageUids = new int[size]; 14331 for (int i = 0; i < size; i++) { 14332 final ApplicationInfo info = infos.get(i); 14333 packageNames[i] = info.packageName; 14334 packageUids[i] = info.uid; 14335 } 14336 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14337 finishedReceiver); 14338 } 14339 14340 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14341 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14342 sendResourcesChangedBroadcast(mediaStatus, replacing, 14343 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14344 } 14345 14346 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14347 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14348 int size = pkgList.length; 14349 if (size > 0) { 14350 // Send broadcasts here 14351 Bundle extras = new Bundle(); 14352 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14353 if (uidArr != null) { 14354 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14355 } 14356 if (replacing) { 14357 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14358 } 14359 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14360 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14361 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14362 } 14363 } 14364 14365 /* 14366 * Look at potentially valid container ids from processCids If package 14367 * information doesn't match the one on record or package scanning fails, 14368 * the cid is added to list of removeCids. We currently don't delete stale 14369 * containers. 14370 */ 14371 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14372 ArrayList<String> pkgList = new ArrayList<String>(); 14373 Set<AsecInstallArgs> keys = processCids.keySet(); 14374 14375 for (AsecInstallArgs args : keys) { 14376 String codePath = processCids.get(args); 14377 if (DEBUG_SD_INSTALL) 14378 Log.i(TAG, "Loading container : " + args.cid); 14379 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14380 try { 14381 // Make sure there are no container errors first. 14382 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14383 Slog.e(TAG, "Failed to mount cid : " + args.cid 14384 + " when installing from sdcard"); 14385 continue; 14386 } 14387 // Check code path here. 14388 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14389 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14390 + " does not match one in settings " + codePath); 14391 continue; 14392 } 14393 // Parse package 14394 int parseFlags = mDefParseFlags; 14395 if (args.isExternalAsec()) { 14396 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14397 } 14398 if (args.isFwdLocked()) { 14399 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14400 } 14401 14402 synchronized (mInstallLock) { 14403 PackageParser.Package pkg = null; 14404 try { 14405 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14406 } catch (PackageManagerException e) { 14407 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14408 } 14409 // Scan the package 14410 if (pkg != null) { 14411 /* 14412 * TODO why is the lock being held? doPostInstall is 14413 * called in other places without the lock. This needs 14414 * to be straightened out. 14415 */ 14416 // writer 14417 synchronized (mPackages) { 14418 retCode = PackageManager.INSTALL_SUCCEEDED; 14419 pkgList.add(pkg.packageName); 14420 // Post process args 14421 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14422 pkg.applicationInfo.uid); 14423 } 14424 } else { 14425 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14426 } 14427 } 14428 14429 } finally { 14430 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14431 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14432 } 14433 } 14434 } 14435 // writer 14436 synchronized (mPackages) { 14437 // If the platform SDK has changed since the last time we booted, 14438 // we need to re-grant app permission to catch any new ones that 14439 // appear. This is really a hack, and means that apps can in some 14440 // cases get permissions that the user didn't initially explicitly 14441 // allow... it would be nice to have some better way to handle 14442 // this situation. 14443 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14444 if (regrantPermissions) 14445 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14446 + mSdkVersion + "; regranting permissions for external storage"); 14447 mSettings.mExternalSdkPlatform = mSdkVersion; 14448 14449 // Make sure group IDs have been assigned, and any permission 14450 // changes in other apps are accounted for 14451 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14452 | (regrantPermissions 14453 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14454 : 0)); 14455 14456 mSettings.updateExternalDatabaseVersion(); 14457 14458 // can downgrade to reader 14459 // Persist settings 14460 mSettings.writeLPr(); 14461 } 14462 // Send a broadcast to let everyone know we are done processing 14463 if (pkgList.size() > 0) { 14464 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14465 } 14466 } 14467 14468 /* 14469 * Utility method to unload a list of specified containers 14470 */ 14471 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14472 // Just unmount all valid containers. 14473 for (AsecInstallArgs arg : cidArgs) { 14474 synchronized (mInstallLock) { 14475 arg.doPostDeleteLI(false); 14476 } 14477 } 14478 } 14479 14480 /* 14481 * Unload packages mounted on external media. This involves deleting package 14482 * data from internal structures, sending broadcasts about diabled packages, 14483 * gc'ing to free up references, unmounting all secure containers 14484 * corresponding to packages on external media, and posting a 14485 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14486 * that we always have to post this message if status has been requested no 14487 * matter what. 14488 */ 14489 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14490 final boolean reportStatus) { 14491 if (DEBUG_SD_INSTALL) 14492 Log.i(TAG, "unloading media packages"); 14493 ArrayList<String> pkgList = new ArrayList<String>(); 14494 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14495 final Set<AsecInstallArgs> keys = processCids.keySet(); 14496 for (AsecInstallArgs args : keys) { 14497 String pkgName = args.getPackageName(); 14498 if (DEBUG_SD_INSTALL) 14499 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14500 // Delete package internally 14501 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14502 synchronized (mInstallLock) { 14503 boolean res = deletePackageLI(pkgName, null, false, null, null, 14504 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14505 if (res) { 14506 pkgList.add(pkgName); 14507 } else { 14508 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14509 failedList.add(args); 14510 } 14511 } 14512 } 14513 14514 // reader 14515 synchronized (mPackages) { 14516 // We didn't update the settings after removing each package; 14517 // write them now for all packages. 14518 mSettings.writeLPr(); 14519 } 14520 14521 // We have to absolutely send UPDATED_MEDIA_STATUS only 14522 // after confirming that all the receivers processed the ordered 14523 // broadcast when packages get disabled, force a gc to clean things up. 14524 // and unload all the containers. 14525 if (pkgList.size() > 0) { 14526 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14527 new IIntentReceiver.Stub() { 14528 public void performReceive(Intent intent, int resultCode, String data, 14529 Bundle extras, boolean ordered, boolean sticky, 14530 int sendingUser) throws RemoteException { 14531 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14532 reportStatus ? 1 : 0, 1, keys); 14533 mHandler.sendMessage(msg); 14534 } 14535 }); 14536 } else { 14537 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14538 keys); 14539 mHandler.sendMessage(msg); 14540 } 14541 } 14542 14543 private void loadPrivatePackages(VolumeInfo vol) { 14544 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14545 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14546 synchronized (mInstallLock) { 14547 synchronized (mPackages) { 14548 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14549 for (PackageSetting ps : packages) { 14550 final PackageParser.Package pkg; 14551 try { 14552 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14553 loaded.add(pkg.applicationInfo); 14554 } catch (PackageManagerException e) { 14555 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14556 } 14557 } 14558 14559 // TODO: regrant any permissions that changed based since original install 14560 14561 mSettings.writeLPr(); 14562 } 14563 } 14564 14565 Slog.d(TAG, "Loaded packages " + loaded); 14566 sendResourcesChangedBroadcast(true, false, loaded, null); 14567 } 14568 14569 private void unloadPrivatePackages(VolumeInfo vol) { 14570 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14571 synchronized (mInstallLock) { 14572 synchronized (mPackages) { 14573 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14574 for (PackageSetting ps : packages) { 14575 if (ps.pkg == null) continue; 14576 14577 final ApplicationInfo info = ps.pkg.applicationInfo; 14578 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14579 if (deletePackageLI(ps.name, null, false, null, null, 14580 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14581 unloaded.add(info); 14582 } else { 14583 Slog.w(TAG, "Failed to unload " + ps.codePath); 14584 } 14585 } 14586 14587 mSettings.writeLPr(); 14588 } 14589 } 14590 14591 Slog.d(TAG, "Unloaded packages " + unloaded); 14592 sendResourcesChangedBroadcast(false, false, unloaded, null); 14593 } 14594 14595 private void unfreezePackage(String packageName) { 14596 synchronized (mPackages) { 14597 final PackageSetting ps = mSettings.mPackages.get(packageName); 14598 if (ps != null) { 14599 ps.frozen = false; 14600 } 14601 } 14602 } 14603 14604 @Override 14605 public int movePackage(final String packageName, final String volumeUuid) { 14606 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14607 14608 final int moveId = mNextMoveId.getAndIncrement(); 14609 try { 14610 movePackageInternal(packageName, volumeUuid, moveId); 14611 } catch (PackageManagerException e) { 14612 Slog.d(TAG, "Failed to move " + packageName, e); 14613 mMoveCallbacks.notifyStatusChanged(moveId, 14614 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14615 } 14616 return moveId; 14617 } 14618 14619 private void movePackageInternal(final String packageName, final String volumeUuid, 14620 final int moveId) throws PackageManagerException { 14621 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14622 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14623 final PackageManager pm = mContext.getPackageManager(); 14624 14625 final boolean currentAsec; 14626 final String currentVolumeUuid; 14627 final File codeFile; 14628 final String installerPackageName; 14629 final String packageAbiOverride; 14630 final int appId; 14631 final String seinfo; 14632 final String label; 14633 14634 // reader 14635 synchronized (mPackages) { 14636 final PackageParser.Package pkg = mPackages.get(packageName); 14637 final PackageSetting ps = mSettings.mPackages.get(packageName); 14638 if (pkg == null || ps == null) { 14639 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14640 } 14641 14642 if (pkg.applicationInfo.isSystemApp()) { 14643 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14644 "Cannot move system application"); 14645 } 14646 14647 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14648 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14649 "Package already moved to " + volumeUuid); 14650 } 14651 14652 final File probe = new File(pkg.codePath); 14653 final File probeOat = new File(probe, "oat"); 14654 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14655 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14656 "Move only supported for modern cluster style installs"); 14657 } 14658 14659 if (ps.frozen) { 14660 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14661 "Failed to move already frozen package"); 14662 } 14663 ps.frozen = true; 14664 14665 currentAsec = pkg.applicationInfo.isForwardLocked() 14666 || pkg.applicationInfo.isExternalAsec(); 14667 currentVolumeUuid = ps.volumeUuid; 14668 codeFile = new File(pkg.codePath); 14669 installerPackageName = ps.installerPackageName; 14670 packageAbiOverride = ps.cpuAbiOverrideString; 14671 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14672 seinfo = pkg.applicationInfo.seinfo; 14673 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14674 } 14675 14676 // Now that we're guarded by frozen state, kill app during move 14677 killApplication(packageName, appId, "move pkg"); 14678 14679 final Bundle extras = new Bundle(); 14680 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14681 extras.putString(Intent.EXTRA_TITLE, label); 14682 mMoveCallbacks.notifyCreated(moveId, extras); 14683 14684 int installFlags; 14685 final boolean moveCompleteApp; 14686 final File measurePath; 14687 14688 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14689 installFlags = INSTALL_INTERNAL; 14690 moveCompleteApp = !currentAsec; 14691 measurePath = Environment.getDataAppDirectory(volumeUuid); 14692 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14693 installFlags = INSTALL_EXTERNAL; 14694 moveCompleteApp = false; 14695 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14696 } else { 14697 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14698 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14699 || !volume.isMountedWritable()) { 14700 unfreezePackage(packageName); 14701 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14702 "Move location not mounted private volume"); 14703 } 14704 14705 Preconditions.checkState(!currentAsec); 14706 14707 installFlags = INSTALL_INTERNAL; 14708 moveCompleteApp = true; 14709 measurePath = Environment.getDataAppDirectory(volumeUuid); 14710 } 14711 14712 final PackageStats stats = new PackageStats(null, -1); 14713 synchronized (mInstaller) { 14714 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14715 unfreezePackage(packageName); 14716 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14717 "Failed to measure package size"); 14718 } 14719 } 14720 14721 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14722 14723 final long startFreeBytes = measurePath.getFreeSpace(); 14724 final long sizeBytes; 14725 if (moveCompleteApp) { 14726 sizeBytes = stats.codeSize + stats.dataSize; 14727 } else { 14728 sizeBytes = stats.codeSize; 14729 } 14730 14731 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14732 unfreezePackage(packageName); 14733 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14734 "Not enough free space to move"); 14735 } 14736 14737 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14738 14739 final CountDownLatch installedLatch = new CountDownLatch(1); 14740 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14741 @Override 14742 public void onUserActionRequired(Intent intent) throws RemoteException { 14743 throw new IllegalStateException(); 14744 } 14745 14746 @Override 14747 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14748 Bundle extras) throws RemoteException { 14749 Slog.d(TAG, "Install result for move: " 14750 + PackageManager.installStatusToString(returnCode, msg)); 14751 14752 installedLatch.countDown(); 14753 14754 // Regardless of success or failure of the move operation, 14755 // always unfreeze the package 14756 unfreezePackage(packageName); 14757 14758 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14759 switch (status) { 14760 case PackageInstaller.STATUS_SUCCESS: 14761 mMoveCallbacks.notifyStatusChanged(moveId, 14762 PackageManager.MOVE_SUCCEEDED); 14763 break; 14764 case PackageInstaller.STATUS_FAILURE_STORAGE: 14765 mMoveCallbacks.notifyStatusChanged(moveId, 14766 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14767 break; 14768 default: 14769 mMoveCallbacks.notifyStatusChanged(moveId, 14770 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14771 break; 14772 } 14773 } 14774 }; 14775 14776 final MoveInfo move; 14777 if (moveCompleteApp) { 14778 // Kick off a thread to report progress estimates 14779 new Thread() { 14780 @Override 14781 public void run() { 14782 while (true) { 14783 try { 14784 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14785 break; 14786 } 14787 } catch (InterruptedException ignored) { 14788 } 14789 14790 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14791 final int progress = 10 + (int) MathUtils.constrain( 14792 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14793 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14794 } 14795 } 14796 }.start(); 14797 14798 final String dataAppName = codeFile.getName(); 14799 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14800 dataAppName, appId, seinfo); 14801 } else { 14802 move = null; 14803 } 14804 14805 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14806 14807 final Message msg = mHandler.obtainMessage(INIT_COPY); 14808 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14809 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14810 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14811 mHandler.sendMessage(msg); 14812 } 14813 14814 @Override 14815 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14816 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14817 14818 final int realMoveId = mNextMoveId.getAndIncrement(); 14819 final Bundle extras = new Bundle(); 14820 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14821 mMoveCallbacks.notifyCreated(realMoveId, extras); 14822 14823 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14824 @Override 14825 public void onCreated(int moveId, Bundle extras) { 14826 // Ignored 14827 } 14828 14829 @Override 14830 public void onStatusChanged(int moveId, int status, long estMillis) { 14831 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14832 } 14833 }; 14834 14835 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14836 storage.setPrimaryStorageUuid(volumeUuid, callback); 14837 return realMoveId; 14838 } 14839 14840 @Override 14841 public int getMoveStatus(int moveId) { 14842 mContext.enforceCallingOrSelfPermission( 14843 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14844 return mMoveCallbacks.mLastStatus.get(moveId); 14845 } 14846 14847 @Override 14848 public void registerMoveCallback(IPackageMoveObserver callback) { 14849 mContext.enforceCallingOrSelfPermission( 14850 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14851 mMoveCallbacks.register(callback); 14852 } 14853 14854 @Override 14855 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14856 mContext.enforceCallingOrSelfPermission( 14857 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14858 mMoveCallbacks.unregister(callback); 14859 } 14860 14861 @Override 14862 public boolean setInstallLocation(int loc) { 14863 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14864 null); 14865 if (getInstallLocation() == loc) { 14866 return true; 14867 } 14868 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14869 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14870 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14871 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14872 return true; 14873 } 14874 return false; 14875 } 14876 14877 @Override 14878 public int getInstallLocation() { 14879 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14880 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14881 PackageHelper.APP_INSTALL_AUTO); 14882 } 14883 14884 /** Called by UserManagerService */ 14885 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14886 mDirtyUsers.remove(userHandle); 14887 mSettings.removeUserLPw(userHandle); 14888 mPendingBroadcasts.remove(userHandle); 14889 if (mInstaller != null) { 14890 // Technically, we shouldn't be doing this with the package lock 14891 // held. However, this is very rare, and there is already so much 14892 // other disk I/O going on, that we'll let it slide for now. 14893 final StorageManager storage = StorageManager.from(mContext); 14894 final List<VolumeInfo> vols = storage.getVolumes(); 14895 for (VolumeInfo vol : vols) { 14896 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14897 final String volumeUuid = vol.getFsUuid(); 14898 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14899 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14900 } 14901 } 14902 } 14903 mUserNeedsBadging.delete(userHandle); 14904 removeUnusedPackagesLILPw(userManager, userHandle); 14905 } 14906 14907 /** 14908 * We're removing userHandle and would like to remove any downloaded packages 14909 * that are no longer in use by any other user. 14910 * @param userHandle the user being removed 14911 */ 14912 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14913 final boolean DEBUG_CLEAN_APKS = false; 14914 int [] users = userManager.getUserIdsLPr(); 14915 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14916 while (psit.hasNext()) { 14917 PackageSetting ps = psit.next(); 14918 if (ps.pkg == null) { 14919 continue; 14920 } 14921 final String packageName = ps.pkg.packageName; 14922 // Skip over if system app 14923 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14924 continue; 14925 } 14926 if (DEBUG_CLEAN_APKS) { 14927 Slog.i(TAG, "Checking package " + packageName); 14928 } 14929 boolean keep = false; 14930 for (int i = 0; i < users.length; i++) { 14931 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14932 keep = true; 14933 if (DEBUG_CLEAN_APKS) { 14934 Slog.i(TAG, " Keeping package " + packageName + " for user " 14935 + users[i]); 14936 } 14937 break; 14938 } 14939 } 14940 if (!keep) { 14941 if (DEBUG_CLEAN_APKS) { 14942 Slog.i(TAG, " Removing package " + packageName); 14943 } 14944 mHandler.post(new Runnable() { 14945 public void run() { 14946 deletePackageX(packageName, userHandle, 0); 14947 } //end run 14948 }); 14949 } 14950 } 14951 } 14952 14953 /** Called by UserManagerService */ 14954 void createNewUserLILPw(int userHandle, File path) { 14955 if (mInstaller != null) { 14956 mInstaller.createUserConfig(userHandle); 14957 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14958 } 14959 } 14960 14961 void newUserCreatedLILPw(int userHandle) { 14962 // Adding a user requires updating runtime permissions for system apps. 14963 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14964 } 14965 14966 @Override 14967 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14968 mContext.enforceCallingOrSelfPermission( 14969 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14970 "Only package verification agents can read the verifier device identity"); 14971 14972 synchronized (mPackages) { 14973 return mSettings.getVerifierDeviceIdentityLPw(); 14974 } 14975 } 14976 14977 @Override 14978 public void setPermissionEnforced(String permission, boolean enforced) { 14979 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14980 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14981 synchronized (mPackages) { 14982 if (mSettings.mReadExternalStorageEnforced == null 14983 || mSettings.mReadExternalStorageEnforced != enforced) { 14984 mSettings.mReadExternalStorageEnforced = enforced; 14985 mSettings.writeLPr(); 14986 } 14987 } 14988 // kill any non-foreground processes so we restart them and 14989 // grant/revoke the GID. 14990 final IActivityManager am = ActivityManagerNative.getDefault(); 14991 if (am != null) { 14992 final long token = Binder.clearCallingIdentity(); 14993 try { 14994 am.killProcessesBelowForeground("setPermissionEnforcement"); 14995 } catch (RemoteException e) { 14996 } finally { 14997 Binder.restoreCallingIdentity(token); 14998 } 14999 } 15000 } else { 15001 throw new IllegalArgumentException("No selective enforcement for " + permission); 15002 } 15003 } 15004 15005 @Override 15006 @Deprecated 15007 public boolean isPermissionEnforced(String permission) { 15008 return true; 15009 } 15010 15011 @Override 15012 public boolean isStorageLow() { 15013 final long token = Binder.clearCallingIdentity(); 15014 try { 15015 final DeviceStorageMonitorInternal 15016 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15017 if (dsm != null) { 15018 return dsm.isMemoryLow(); 15019 } else { 15020 return false; 15021 } 15022 } finally { 15023 Binder.restoreCallingIdentity(token); 15024 } 15025 } 15026 15027 @Override 15028 public IPackageInstaller getPackageInstaller() { 15029 return mInstallerService; 15030 } 15031 15032 private boolean userNeedsBadging(int userId) { 15033 int index = mUserNeedsBadging.indexOfKey(userId); 15034 if (index < 0) { 15035 final UserInfo userInfo; 15036 final long token = Binder.clearCallingIdentity(); 15037 try { 15038 userInfo = sUserManager.getUserInfo(userId); 15039 } finally { 15040 Binder.restoreCallingIdentity(token); 15041 } 15042 final boolean b; 15043 if (userInfo != null && userInfo.isManagedProfile()) { 15044 b = true; 15045 } else { 15046 b = false; 15047 } 15048 mUserNeedsBadging.put(userId, b); 15049 return b; 15050 } 15051 return mUserNeedsBadging.valueAt(index); 15052 } 15053 15054 @Override 15055 public KeySet getKeySetByAlias(String packageName, String alias) { 15056 if (packageName == null || alias == null) { 15057 return null; 15058 } 15059 synchronized(mPackages) { 15060 final PackageParser.Package pkg = mPackages.get(packageName); 15061 if (pkg == null) { 15062 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15063 throw new IllegalArgumentException("Unknown package: " + packageName); 15064 } 15065 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15066 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15067 } 15068 } 15069 15070 @Override 15071 public KeySet getSigningKeySet(String packageName) { 15072 if (packageName == null) { 15073 return null; 15074 } 15075 synchronized(mPackages) { 15076 final PackageParser.Package pkg = mPackages.get(packageName); 15077 if (pkg == null) { 15078 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15079 throw new IllegalArgumentException("Unknown package: " + packageName); 15080 } 15081 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15082 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15083 throw new SecurityException("May not access signing KeySet of other apps."); 15084 } 15085 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15086 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15087 } 15088 } 15089 15090 @Override 15091 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15092 if (packageName == null || ks == null) { 15093 return false; 15094 } 15095 synchronized(mPackages) { 15096 final PackageParser.Package pkg = mPackages.get(packageName); 15097 if (pkg == null) { 15098 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15099 throw new IllegalArgumentException("Unknown package: " + packageName); 15100 } 15101 IBinder ksh = ks.getToken(); 15102 if (ksh instanceof KeySetHandle) { 15103 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15104 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15105 } 15106 return false; 15107 } 15108 } 15109 15110 @Override 15111 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15112 if (packageName == null || ks == null) { 15113 return false; 15114 } 15115 synchronized(mPackages) { 15116 final PackageParser.Package pkg = mPackages.get(packageName); 15117 if (pkg == null) { 15118 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15119 throw new IllegalArgumentException("Unknown package: " + packageName); 15120 } 15121 IBinder ksh = ks.getToken(); 15122 if (ksh instanceof KeySetHandle) { 15123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15124 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15125 } 15126 return false; 15127 } 15128 } 15129 15130 public void getUsageStatsIfNoPackageUsageInfo() { 15131 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15132 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15133 if (usm == null) { 15134 throw new IllegalStateException("UsageStatsManager must be initialized"); 15135 } 15136 long now = System.currentTimeMillis(); 15137 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15138 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15139 String packageName = entry.getKey(); 15140 PackageParser.Package pkg = mPackages.get(packageName); 15141 if (pkg == null) { 15142 continue; 15143 } 15144 UsageStats usage = entry.getValue(); 15145 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15146 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15147 } 15148 } 15149 } 15150 15151 /** 15152 * Check and throw if the given before/after packages would be considered a 15153 * downgrade. 15154 */ 15155 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15156 throws PackageManagerException { 15157 if (after.versionCode < before.mVersionCode) { 15158 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15159 "Update version code " + after.versionCode + " is older than current " 15160 + before.mVersionCode); 15161 } else if (after.versionCode == before.mVersionCode) { 15162 if (after.baseRevisionCode < before.baseRevisionCode) { 15163 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15164 "Update base revision code " + after.baseRevisionCode 15165 + " is older than current " + before.baseRevisionCode); 15166 } 15167 15168 if (!ArrayUtils.isEmpty(after.splitNames)) { 15169 for (int i = 0; i < after.splitNames.length; i++) { 15170 final String splitName = after.splitNames[i]; 15171 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15172 if (j != -1) { 15173 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15174 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15175 "Update split " + splitName + " revision code " 15176 + after.splitRevisionCodes[i] + " is older than current " 15177 + before.splitRevisionCodes[j]); 15178 } 15179 } 15180 } 15181 } 15182 } 15183 } 15184 15185 private static class MoveCallbacks extends Handler { 15186 private static final int MSG_CREATED = 1; 15187 private static final int MSG_STATUS_CHANGED = 2; 15188 15189 private final RemoteCallbackList<IPackageMoveObserver> 15190 mCallbacks = new RemoteCallbackList<>(); 15191 15192 private final SparseIntArray mLastStatus = new SparseIntArray(); 15193 15194 public MoveCallbacks(Looper looper) { 15195 super(looper); 15196 } 15197 15198 public void register(IPackageMoveObserver callback) { 15199 mCallbacks.register(callback); 15200 } 15201 15202 public void unregister(IPackageMoveObserver callback) { 15203 mCallbacks.unregister(callback); 15204 } 15205 15206 @Override 15207 public void handleMessage(Message msg) { 15208 final SomeArgs args = (SomeArgs) msg.obj; 15209 final int n = mCallbacks.beginBroadcast(); 15210 for (int i = 0; i < n; i++) { 15211 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15212 try { 15213 invokeCallback(callback, msg.what, args); 15214 } catch (RemoteException ignored) { 15215 } 15216 } 15217 mCallbacks.finishBroadcast(); 15218 args.recycle(); 15219 } 15220 15221 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15222 throws RemoteException { 15223 switch (what) { 15224 case MSG_CREATED: { 15225 callback.onCreated(args.argi1, (Bundle) args.arg2); 15226 break; 15227 } 15228 case MSG_STATUS_CHANGED: { 15229 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15230 break; 15231 } 15232 } 15233 } 15234 15235 private void notifyCreated(int moveId, Bundle extras) { 15236 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15237 15238 final SomeArgs args = SomeArgs.obtain(); 15239 args.argi1 = moveId; 15240 args.arg2 = extras; 15241 obtainMessage(MSG_CREATED, args).sendToTarget(); 15242 } 15243 15244 private void notifyStatusChanged(int moveId, int status) { 15245 notifyStatusChanged(moveId, status, -1); 15246 } 15247 15248 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15249 Slog.v(TAG, "Move " + moveId + " status " + status); 15250 15251 final SomeArgs args = SomeArgs.obtain(); 15252 args.argi1 = moveId; 15253 args.argi2 = status; 15254 args.arg3 = estMillis; 15255 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15256 15257 synchronized (mLastStatus) { 15258 mLastStatus.put(moveId, status); 15259 } 15260 } 15261 } 15262} 15263