PackageManagerService.java revision 857c3019bac34bbabaa8d5ebb4ab0047ca07cfc5
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 a runtime one. */ 373 private static final int GRANT_RUNTIME = 3; 374 375 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 376 private static final int GRANT_UPGRADE = 4; 377 378 final ServiceThread mHandlerThread; 379 380 final PackageHandler mHandler; 381 382 /** 383 * Messages for {@link #mHandler} that need to wait for system ready before 384 * being dispatched. 385 */ 386 private ArrayList<Message> mPostSystemReadyMessages; 387 388 final int mSdkVersion = Build.VERSION.SDK_INT; 389 390 final Context mContext; 391 final boolean mFactoryTest; 392 final boolean mOnlyCore; 393 final boolean mLazyDexOpt; 394 final long mDexOptLRUThresholdInMills; 395 final DisplayMetrics mMetrics; 396 final int mDefParseFlags; 397 final String[] mSeparateProcesses; 398 final boolean mIsUpgrade; 399 400 // This is where all application persistent data goes. 401 final File mAppDataDir; 402 403 // This is where all application persistent data goes for secondary users. 404 final File mUserAppDataDir; 405 406 /** The location for ASEC container files on internal storage. */ 407 final String mAsecInternalPath; 408 409 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 410 // LOCK HELD. Can be called with mInstallLock held. 411 final Installer mInstaller; 412 413 /** Directory where installed third-party apps stored */ 414 final File mAppInstallDir; 415 416 /** 417 * Directory to which applications installed internally have their 418 * 32 bit native libraries copied. 419 */ 420 private File mAppLib32InstallDir; 421 422 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 423 // apps. 424 final File mDrmAppPrivateInstallDir; 425 426 // ---------------------------------------------------------------- 427 428 // Lock for state used when installing and doing other long running 429 // operations. Methods that must be called with this lock held have 430 // the suffix "LI". 431 final Object mInstallLock = new Object(); 432 433 // ---------------------------------------------------------------- 434 435 // Keys are String (package name), values are Package. This also serves 436 // as the lock for the global state. Methods that must be called with 437 // this lock held have the prefix "LP". 438 final ArrayMap<String, PackageParser.Package> mPackages = 439 new ArrayMap<String, PackageParser.Package>(); 440 441 // Tracks available target package names -> overlay package paths. 442 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 443 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 444 445 final Settings mSettings; 446 boolean mRestoredSettings; 447 448 // System configuration read by SystemConfig. 449 final int[] mGlobalGids; 450 final SparseArray<ArraySet<String>> mSystemPermissions; 451 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 452 453 // If mac_permissions.xml was found for seinfo labeling. 454 boolean mFoundPolicyFile; 455 456 // If a recursive restorecon of /data/data/<pkg> is needed. 457 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 458 459 public static final class SharedLibraryEntry { 460 public final String path; 461 public final String apk; 462 463 SharedLibraryEntry(String _path, String _apk) { 464 path = _path; 465 apk = _apk; 466 } 467 } 468 469 // Currently known shared libraries. 470 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 471 new ArrayMap<String, SharedLibraryEntry>(); 472 473 // All available activities, for your resolving pleasure. 474 final ActivityIntentResolver mActivities = 475 new ActivityIntentResolver(); 476 477 // All available receivers, for your resolving pleasure. 478 final ActivityIntentResolver mReceivers = 479 new ActivityIntentResolver(); 480 481 // All available services, for your resolving pleasure. 482 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 483 484 // All available providers, for your resolving pleasure. 485 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 486 487 // Mapping from provider base names (first directory in content URI codePath) 488 // to the provider information. 489 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 490 new ArrayMap<String, PackageParser.Provider>(); 491 492 // Mapping from instrumentation class names to info about them. 493 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 494 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 495 496 // Mapping from permission names to info about them. 497 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 498 new ArrayMap<String, PackageParser.PermissionGroup>(); 499 500 // Packages whose data we have transfered into another package, thus 501 // should no longer exist. 502 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 503 504 // Broadcast actions that are only available to the system. 505 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 506 507 /** List of packages waiting for verification. */ 508 final SparseArray<PackageVerificationState> mPendingVerification 509 = new SparseArray<PackageVerificationState>(); 510 511 /** Set of packages associated with each app op permission. */ 512 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 513 514 final PackageInstallerService mInstallerService; 515 516 private final PackageDexOptimizer mPackageDexOptimizer; 517 518 private AtomicInteger mNextMoveId = new AtomicInteger(); 519 private final MoveCallbacks mMoveCallbacks; 520 521 // Cache of users who need badging. 522 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 523 524 /** Token for keys in mPendingVerification. */ 525 private int mPendingVerificationToken = 0; 526 527 volatile boolean mSystemReady; 528 volatile boolean mSafeMode; 529 volatile boolean mHasSystemUidErrors; 530 531 ApplicationInfo mAndroidApplication; 532 final ActivityInfo mResolveActivity = new ActivityInfo(); 533 final ResolveInfo mResolveInfo = new ResolveInfo(); 534 ComponentName mResolveComponentName; 535 PackageParser.Package mPlatformPackage; 536 ComponentName mCustomResolverComponentName; 537 538 boolean mResolverReplaced = false; 539 540 private final ComponentName mIntentFilterVerifierComponent; 541 private int mIntentFilterVerificationToken = 0; 542 543 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 544 = new SparseArray<IntentFilterVerificationState>(); 545 546 private interface IntentFilterVerifier<T extends IntentFilter> { 547 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 548 T filter, String packageName); 549 void startVerifications(int userId); 550 void receiveVerificationResponse(int verificationId); 551 } 552 553 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 554 private Context mContext; 555 private ComponentName mIntentFilterVerifierComponent; 556 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 557 558 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 559 mContext = context; 560 mIntentFilterVerifierComponent = verifierComponent; 561 } 562 563 private String getDefaultScheme() { 564 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 565 return IntentFilter.SCHEME_HTTP; 566 } 567 568 @Override 569 public void startVerifications(int userId) { 570 // Launch verifications requests 571 int count = mCurrentIntentFilterVerifications.size(); 572 for (int n=0; n<count; n++) { 573 int verificationId = mCurrentIntentFilterVerifications.get(n); 574 final IntentFilterVerificationState ivs = 575 mIntentFilterVerificationStates.get(verificationId); 576 577 String packageName = ivs.getPackageName(); 578 579 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 580 final int filterCount = filters.size(); 581 ArraySet<String> domainsSet = new ArraySet<>(); 582 for (int m=0; m<filterCount; m++) { 583 PackageParser.ActivityIntentInfo filter = filters.get(m); 584 domainsSet.addAll(filter.getHostsList()); 585 } 586 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 587 synchronized (mPackages) { 588 if (mSettings.createIntentFilterVerificationIfNeededLPw( 589 packageName, domainsList) != null) { 590 scheduleWriteSettingsLocked(); 591 } 592 } 593 sendVerificationRequest(userId, verificationId, ivs); 594 } 595 mCurrentIntentFilterVerifications.clear(); 596 } 597 598 private void sendVerificationRequest(int userId, int verificationId, 599 IntentFilterVerificationState ivs) { 600 601 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 602 verificationIntent.putExtra( 603 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 604 verificationId); 605 verificationIntent.putExtra( 606 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 607 getDefaultScheme()); 608 verificationIntent.putExtra( 609 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 610 ivs.getHostsString()); 611 verificationIntent.putExtra( 612 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 613 ivs.getPackageName()); 614 verificationIntent.setComponent(mIntentFilterVerifierComponent); 615 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 616 617 UserHandle user = new UserHandle(userId); 618 mContext.sendBroadcastAsUser(verificationIntent, user); 619 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 620 } 621 622 public void receiveVerificationResponse(int verificationId) { 623 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 624 625 final boolean verified = ivs.isVerified(); 626 627 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 628 final int count = filters.size(); 629 for (int n=0; n<count; n++) { 630 PackageParser.ActivityIntentInfo filter = filters.get(n); 631 filter.setVerified(verified); 632 633 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 634 + verified + " and hosts:" + ivs.getHostsString()); 635 } 636 637 mIntentFilterVerificationStates.remove(verificationId); 638 639 final String packageName = ivs.getPackageName(); 640 IntentFilterVerificationInfo ivi = null; 641 642 synchronized (mPackages) { 643 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 644 } 645 if (ivi == null) { 646 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 647 + verificationId + " packageName:" + packageName); 648 return; 649 } 650 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 651 + verificationId); 652 653 synchronized (mPackages) { 654 if (verified) { 655 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 656 } else { 657 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 658 } 659 scheduleWriteSettingsLocked(); 660 661 final int userId = ivs.getUserId(); 662 if (userId != UserHandle.USER_ALL) { 663 final int userStatus = 664 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 665 666 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 667 boolean needUpdate = false; 668 669 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 670 // already been set by the User thru the Disambiguation dialog 671 switch (userStatus) { 672 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 673 if (verified) { 674 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 675 } else { 676 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 677 } 678 needUpdate = true; 679 break; 680 681 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 682 if (verified) { 683 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 684 needUpdate = true; 685 } 686 break; 687 688 default: 689 // Nothing to do 690 } 691 692 if (needUpdate) { 693 mSettings.updateIntentFilterVerificationStatusLPw( 694 packageName, updatedStatus, userId); 695 scheduleWritePackageRestrictionsLocked(userId); 696 } 697 } 698 } 699 } 700 701 @Override 702 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 703 ActivityIntentInfo filter, String packageName) { 704 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 705 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 706 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 707 return false; 708 } 709 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 710 if (ivs == null) { 711 ivs = createDomainVerificationState(verifierId, userId, verificationId, 712 packageName); 713 } 714 if (!hasValidDomains(filter)) { 715 return false; 716 } 717 ivs.addFilter(filter); 718 return true; 719 } 720 721 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 722 int userId, int verificationId, String packageName) { 723 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 724 verifierId, userId, packageName); 725 ivs.setPendingState(); 726 synchronized (mPackages) { 727 mIntentFilterVerificationStates.append(verificationId, ivs); 728 mCurrentIntentFilterVerifications.add(verificationId); 729 } 730 return ivs; 731 } 732 } 733 734 private static boolean hasValidDomains(ActivityIntentInfo filter) { 735 return hasValidDomains(filter, true); 736 } 737 738 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 739 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 740 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 741 if (!hasHTTPorHTTPS) { 742 if (logging) { 743 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 744 } 745 return false; 746 } 747 return true; 748 } 749 750 private IntentFilterVerifier mIntentFilterVerifier; 751 752 // Set of pending broadcasts for aggregating enable/disable of components. 753 static class PendingPackageBroadcasts { 754 // for each user id, a map of <package name -> components within that package> 755 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 756 757 public PendingPackageBroadcasts() { 758 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 759 } 760 761 public ArrayList<String> get(int userId, String packageName) { 762 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 763 return packages.get(packageName); 764 } 765 766 public void put(int userId, String packageName, ArrayList<String> components) { 767 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 768 packages.put(packageName, components); 769 } 770 771 public void remove(int userId, String packageName) { 772 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 773 if (packages != null) { 774 packages.remove(packageName); 775 } 776 } 777 778 public void remove(int userId) { 779 mUidMap.remove(userId); 780 } 781 782 public int userIdCount() { 783 return mUidMap.size(); 784 } 785 786 public int userIdAt(int n) { 787 return mUidMap.keyAt(n); 788 } 789 790 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 791 return mUidMap.get(userId); 792 } 793 794 public int size() { 795 // total number of pending broadcast entries across all userIds 796 int num = 0; 797 for (int i = 0; i< mUidMap.size(); i++) { 798 num += mUidMap.valueAt(i).size(); 799 } 800 return num; 801 } 802 803 public void clear() { 804 mUidMap.clear(); 805 } 806 807 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 808 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 809 if (map == null) { 810 map = new ArrayMap<String, ArrayList<String>>(); 811 mUidMap.put(userId, map); 812 } 813 return map; 814 } 815 } 816 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 817 818 // Service Connection to remote media container service to copy 819 // package uri's from external media onto secure containers 820 // or internal storage. 821 private IMediaContainerService mContainerService = null; 822 823 static final int SEND_PENDING_BROADCAST = 1; 824 static final int MCS_BOUND = 3; 825 static final int END_COPY = 4; 826 static final int INIT_COPY = 5; 827 static final int MCS_UNBIND = 6; 828 static final int START_CLEANING_PACKAGE = 7; 829 static final int FIND_INSTALL_LOC = 8; 830 static final int POST_INSTALL = 9; 831 static final int MCS_RECONNECT = 10; 832 static final int MCS_GIVE_UP = 11; 833 static final int UPDATED_MEDIA_STATUS = 12; 834 static final int WRITE_SETTINGS = 13; 835 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 836 static final int PACKAGE_VERIFIED = 15; 837 static final int CHECK_PENDING_VERIFICATION = 16; 838 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 839 static final int INTENT_FILTER_VERIFIED = 18; 840 841 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 842 843 // Delay time in millisecs 844 static final int BROADCAST_DELAY = 10 * 1000; 845 846 static UserManagerService sUserManager; 847 848 // Stores a list of users whose package restrictions file needs to be updated 849 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 850 851 final private DefaultContainerConnection mDefContainerConn = 852 new DefaultContainerConnection(); 853 class DefaultContainerConnection implements ServiceConnection { 854 public void onServiceConnected(ComponentName name, IBinder service) { 855 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 856 IMediaContainerService imcs = 857 IMediaContainerService.Stub.asInterface(service); 858 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 859 } 860 861 public void onServiceDisconnected(ComponentName name) { 862 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 863 } 864 }; 865 866 // Recordkeeping of restore-after-install operations that are currently in flight 867 // between the Package Manager and the Backup Manager 868 class PostInstallData { 869 public InstallArgs args; 870 public PackageInstalledInfo res; 871 872 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 873 args = _a; 874 res = _r; 875 } 876 }; 877 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 878 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 879 880 // backup/restore of preferred activity state 881 private static final String TAG_PREFERRED_BACKUP = "pa"; 882 883 private final String mRequiredVerifierPackage; 884 885 private final PackageUsage mPackageUsage = new PackageUsage(); 886 887 private class PackageUsage { 888 private static final int WRITE_INTERVAL 889 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 890 891 private final Object mFileLock = new Object(); 892 private final AtomicLong mLastWritten = new AtomicLong(0); 893 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 894 895 private boolean mIsHistoricalPackageUsageAvailable = true; 896 897 boolean isHistoricalPackageUsageAvailable() { 898 return mIsHistoricalPackageUsageAvailable; 899 } 900 901 void write(boolean force) { 902 if (force) { 903 writeInternal(); 904 return; 905 } 906 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 907 && !DEBUG_DEXOPT) { 908 return; 909 } 910 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 911 new Thread("PackageUsage_DiskWriter") { 912 @Override 913 public void run() { 914 try { 915 writeInternal(); 916 } finally { 917 mBackgroundWriteRunning.set(false); 918 } 919 } 920 }.start(); 921 } 922 } 923 924 private void writeInternal() { 925 synchronized (mPackages) { 926 synchronized (mFileLock) { 927 AtomicFile file = getFile(); 928 FileOutputStream f = null; 929 try { 930 f = file.startWrite(); 931 BufferedOutputStream out = new BufferedOutputStream(f); 932 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 933 StringBuilder sb = new StringBuilder(); 934 for (PackageParser.Package pkg : mPackages.values()) { 935 if (pkg.mLastPackageUsageTimeInMills == 0) { 936 continue; 937 } 938 sb.setLength(0); 939 sb.append(pkg.packageName); 940 sb.append(' '); 941 sb.append((long)pkg.mLastPackageUsageTimeInMills); 942 sb.append('\n'); 943 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 944 } 945 out.flush(); 946 file.finishWrite(f); 947 } catch (IOException e) { 948 if (f != null) { 949 file.failWrite(f); 950 } 951 Log.e(TAG, "Failed to write package usage times", e); 952 } 953 } 954 } 955 mLastWritten.set(SystemClock.elapsedRealtime()); 956 } 957 958 void readLP() { 959 synchronized (mFileLock) { 960 AtomicFile file = getFile(); 961 BufferedInputStream in = null; 962 try { 963 in = new BufferedInputStream(file.openRead()); 964 StringBuffer sb = new StringBuffer(); 965 while (true) { 966 String packageName = readToken(in, sb, ' '); 967 if (packageName == null) { 968 break; 969 } 970 String timeInMillisString = readToken(in, sb, '\n'); 971 if (timeInMillisString == null) { 972 throw new IOException("Failed to find last usage time for package " 973 + packageName); 974 } 975 PackageParser.Package pkg = mPackages.get(packageName); 976 if (pkg == null) { 977 continue; 978 } 979 long timeInMillis; 980 try { 981 timeInMillis = Long.parseLong(timeInMillisString.toString()); 982 } catch (NumberFormatException e) { 983 throw new IOException("Failed to parse " + timeInMillisString 984 + " as a long.", e); 985 } 986 pkg.mLastPackageUsageTimeInMills = timeInMillis; 987 } 988 } catch (FileNotFoundException expected) { 989 mIsHistoricalPackageUsageAvailable = false; 990 } catch (IOException e) { 991 Log.w(TAG, "Failed to read package usage times", e); 992 } finally { 993 IoUtils.closeQuietly(in); 994 } 995 } 996 mLastWritten.set(SystemClock.elapsedRealtime()); 997 } 998 999 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1000 throws IOException { 1001 sb.setLength(0); 1002 while (true) { 1003 int ch = in.read(); 1004 if (ch == -1) { 1005 if (sb.length() == 0) { 1006 return null; 1007 } 1008 throw new IOException("Unexpected EOF"); 1009 } 1010 if (ch == endOfToken) { 1011 return sb.toString(); 1012 } 1013 sb.append((char)ch); 1014 } 1015 } 1016 1017 private AtomicFile getFile() { 1018 File dataDir = Environment.getDataDirectory(); 1019 File systemDir = new File(dataDir, "system"); 1020 File fname = new File(systemDir, "package-usage.list"); 1021 return new AtomicFile(fname); 1022 } 1023 } 1024 1025 class PackageHandler extends Handler { 1026 private boolean mBound = false; 1027 final ArrayList<HandlerParams> mPendingInstalls = 1028 new ArrayList<HandlerParams>(); 1029 1030 private boolean connectToService() { 1031 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1032 " DefaultContainerService"); 1033 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1034 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1035 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1036 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1038 mBound = true; 1039 return true; 1040 } 1041 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1042 return false; 1043 } 1044 1045 private void disconnectService() { 1046 mContainerService = null; 1047 mBound = false; 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1049 mContext.unbindService(mDefContainerConn); 1050 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1051 } 1052 1053 PackageHandler(Looper looper) { 1054 super(looper); 1055 } 1056 1057 public void handleMessage(Message msg) { 1058 try { 1059 doHandleMessage(msg); 1060 } finally { 1061 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1062 } 1063 } 1064 1065 void doHandleMessage(Message msg) { 1066 switch (msg.what) { 1067 case INIT_COPY: { 1068 HandlerParams params = (HandlerParams) msg.obj; 1069 int idx = mPendingInstalls.size(); 1070 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1071 // If a bind was already initiated we dont really 1072 // need to do anything. The pending install 1073 // will be processed later on. 1074 if (!mBound) { 1075 // If this is the only one pending we might 1076 // have to bind to the service again. 1077 if (!connectToService()) { 1078 Slog.e(TAG, "Failed to bind to media container service"); 1079 params.serviceError(); 1080 return; 1081 } else { 1082 // Once we bind to the service, the first 1083 // pending request will be processed. 1084 mPendingInstalls.add(idx, params); 1085 } 1086 } else { 1087 mPendingInstalls.add(idx, params); 1088 // Already bound to the service. Just make 1089 // sure we trigger off processing the first request. 1090 if (idx == 0) { 1091 mHandler.sendEmptyMessage(MCS_BOUND); 1092 } 1093 } 1094 break; 1095 } 1096 case MCS_BOUND: { 1097 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1098 if (msg.obj != null) { 1099 mContainerService = (IMediaContainerService) msg.obj; 1100 } 1101 if (mContainerService == null) { 1102 // Something seriously wrong. Bail out 1103 Slog.e(TAG, "Cannot bind to media container service"); 1104 for (HandlerParams params : mPendingInstalls) { 1105 // Indicate service bind error 1106 params.serviceError(); 1107 } 1108 mPendingInstalls.clear(); 1109 } else if (mPendingInstalls.size() > 0) { 1110 HandlerParams params = mPendingInstalls.get(0); 1111 if (params != null) { 1112 if (params.startCopy()) { 1113 // We are done... look for more work or to 1114 // go idle. 1115 if (DEBUG_SD_INSTALL) Log.i(TAG, 1116 "Checking for more work or unbind..."); 1117 // Delete pending install 1118 if (mPendingInstalls.size() > 0) { 1119 mPendingInstalls.remove(0); 1120 } 1121 if (mPendingInstalls.size() == 0) { 1122 if (mBound) { 1123 if (DEBUG_SD_INSTALL) Log.i(TAG, 1124 "Posting delayed MCS_UNBIND"); 1125 removeMessages(MCS_UNBIND); 1126 Message ubmsg = obtainMessage(MCS_UNBIND); 1127 // Unbind after a little delay, to avoid 1128 // continual thrashing. 1129 sendMessageDelayed(ubmsg, 10000); 1130 } 1131 } else { 1132 // There are more pending requests in queue. 1133 // Just post MCS_BOUND message to trigger processing 1134 // of next pending install. 1135 if (DEBUG_SD_INSTALL) Log.i(TAG, 1136 "Posting MCS_BOUND for next work"); 1137 mHandler.sendEmptyMessage(MCS_BOUND); 1138 } 1139 } 1140 } 1141 } else { 1142 // Should never happen ideally. 1143 Slog.w(TAG, "Empty queue"); 1144 } 1145 break; 1146 } 1147 case MCS_RECONNECT: { 1148 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1149 if (mPendingInstalls.size() > 0) { 1150 if (mBound) { 1151 disconnectService(); 1152 } 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 for (HandlerParams params : mPendingInstalls) { 1156 // Indicate service bind error 1157 params.serviceError(); 1158 } 1159 mPendingInstalls.clear(); 1160 } 1161 } 1162 break; 1163 } 1164 case MCS_UNBIND: { 1165 // If there is no actual work left, then time to unbind. 1166 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1167 1168 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1169 if (mBound) { 1170 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1171 1172 disconnectService(); 1173 } 1174 } else if (mPendingInstalls.size() > 0) { 1175 // There are more pending requests in queue. 1176 // Just post MCS_BOUND message to trigger processing 1177 // of next pending install. 1178 mHandler.sendEmptyMessage(MCS_BOUND); 1179 } 1180 1181 break; 1182 } 1183 case MCS_GIVE_UP: { 1184 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1185 mPendingInstalls.remove(0); 1186 break; 1187 } 1188 case SEND_PENDING_BROADCAST: { 1189 String packages[]; 1190 ArrayList<String> components[]; 1191 int size = 0; 1192 int uids[]; 1193 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1194 synchronized (mPackages) { 1195 if (mPendingBroadcasts == null) { 1196 return; 1197 } 1198 size = mPendingBroadcasts.size(); 1199 if (size <= 0) { 1200 // Nothing to be done. Just return 1201 return; 1202 } 1203 packages = new String[size]; 1204 components = new ArrayList[size]; 1205 uids = new int[size]; 1206 int i = 0; // filling out the above arrays 1207 1208 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1209 int packageUserId = mPendingBroadcasts.userIdAt(n); 1210 Iterator<Map.Entry<String, ArrayList<String>>> it 1211 = mPendingBroadcasts.packagesForUserId(packageUserId) 1212 .entrySet().iterator(); 1213 while (it.hasNext() && i < size) { 1214 Map.Entry<String, ArrayList<String>> ent = it.next(); 1215 packages[i] = ent.getKey(); 1216 components[i] = ent.getValue(); 1217 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1218 uids[i] = (ps != null) 1219 ? UserHandle.getUid(packageUserId, ps.appId) 1220 : -1; 1221 i++; 1222 } 1223 } 1224 size = i; 1225 mPendingBroadcasts.clear(); 1226 } 1227 // Send broadcasts 1228 for (int i = 0; i < size; i++) { 1229 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1230 } 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1232 break; 1233 } 1234 case START_CLEANING_PACKAGE: { 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1236 final String packageName = (String)msg.obj; 1237 final int userId = msg.arg1; 1238 final boolean andCode = msg.arg2 != 0; 1239 synchronized (mPackages) { 1240 if (userId == UserHandle.USER_ALL) { 1241 int[] users = sUserManager.getUserIds(); 1242 for (int user : users) { 1243 mSettings.addPackageToCleanLPw( 1244 new PackageCleanItem(user, packageName, andCode)); 1245 } 1246 } else { 1247 mSettings.addPackageToCleanLPw( 1248 new PackageCleanItem(userId, packageName, andCode)); 1249 } 1250 } 1251 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1252 startCleaningPackages(); 1253 } break; 1254 case POST_INSTALL: { 1255 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1256 PostInstallData data = mRunningInstalls.get(msg.arg1); 1257 mRunningInstalls.delete(msg.arg1); 1258 boolean deleteOld = false; 1259 1260 if (data != null) { 1261 InstallArgs args = data.args; 1262 PackageInstalledInfo res = data.res; 1263 1264 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1265 res.removedInfo.sendBroadcast(false, true, false); 1266 Bundle extras = new Bundle(1); 1267 extras.putInt(Intent.EXTRA_UID, res.uid); 1268 1269 // Now that we successfully installed the package, grant runtime 1270 // permissions if requested before broadcasting the install. 1271 if ((args.installFlags 1272 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1273 grantRequestedRuntimePermissions(res.pkg, 1274 args.user.getIdentifier()); 1275 } 1276 1277 // Determine the set of users who are adding this 1278 // package for the first time vs. those who are seeing 1279 // an update. 1280 int[] firstUsers; 1281 int[] updateUsers = new int[0]; 1282 if (res.origUsers == null || res.origUsers.length == 0) { 1283 firstUsers = res.newUsers; 1284 } else { 1285 firstUsers = new int[0]; 1286 for (int i=0; i<res.newUsers.length; i++) { 1287 int user = res.newUsers[i]; 1288 boolean isNew = true; 1289 for (int j=0; j<res.origUsers.length; j++) { 1290 if (res.origUsers[j] == user) { 1291 isNew = false; 1292 break; 1293 } 1294 } 1295 if (isNew) { 1296 int[] newFirst = new int[firstUsers.length+1]; 1297 System.arraycopy(firstUsers, 0, newFirst, 0, 1298 firstUsers.length); 1299 newFirst[firstUsers.length] = user; 1300 firstUsers = newFirst; 1301 } else { 1302 int[] newUpdate = new int[updateUsers.length+1]; 1303 System.arraycopy(updateUsers, 0, newUpdate, 0, 1304 updateUsers.length); 1305 newUpdate[updateUsers.length] = user; 1306 updateUsers = newUpdate; 1307 } 1308 } 1309 } 1310 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1311 res.pkg.applicationInfo.packageName, 1312 extras, null, null, firstUsers); 1313 final boolean update = res.removedInfo.removedPackage != null; 1314 if (update) { 1315 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1316 } 1317 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1318 res.pkg.applicationInfo.packageName, 1319 extras, null, null, updateUsers); 1320 if (update) { 1321 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1322 res.pkg.applicationInfo.packageName, 1323 extras, null, null, updateUsers); 1324 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1325 null, null, 1326 res.pkg.applicationInfo.packageName, null, updateUsers); 1327 1328 // treat asec-hosted packages like removable media on upgrade 1329 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1330 if (DEBUG_INSTALL) { 1331 Slog.i(TAG, "upgrading pkg " + res.pkg 1332 + " is ASEC-hosted -> AVAILABLE"); 1333 } 1334 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1335 ArrayList<String> pkgList = new ArrayList<String>(1); 1336 pkgList.add(res.pkg.applicationInfo.packageName); 1337 sendResourcesChangedBroadcast(true, true, 1338 pkgList,uidArray, null); 1339 } 1340 } 1341 if (res.removedInfo.args != null) { 1342 // Remove the replaced package's older resources safely now 1343 deleteOld = true; 1344 } 1345 1346 // Log current value of "unknown sources" setting 1347 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1348 getUnknownSourcesSettings()); 1349 } 1350 // Force a gc to clear up things 1351 Runtime.getRuntime().gc(); 1352 // We delete after a gc for applications on sdcard. 1353 if (deleteOld) { 1354 synchronized (mInstallLock) { 1355 res.removedInfo.args.doPostDeleteLI(true); 1356 } 1357 } 1358 if (args.observer != null) { 1359 try { 1360 Bundle extras = extrasForInstallResult(res); 1361 args.observer.onPackageInstalled(res.name, res.returnCode, 1362 res.returnMsg, extras); 1363 } catch (RemoteException e) { 1364 Slog.i(TAG, "Observer no longer exists."); 1365 } 1366 } 1367 } else { 1368 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1369 } 1370 } break; 1371 case UPDATED_MEDIA_STATUS: { 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1373 boolean reportStatus = msg.arg1 == 1; 1374 boolean doGc = msg.arg2 == 1; 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1376 if (doGc) { 1377 // Force a gc to clear up stale containers. 1378 Runtime.getRuntime().gc(); 1379 } 1380 if (msg.obj != null) { 1381 @SuppressWarnings("unchecked") 1382 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1384 // Unload containers 1385 unloadAllContainers(args); 1386 } 1387 if (reportStatus) { 1388 try { 1389 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1390 PackageHelper.getMountService().finishMediaUpdate(); 1391 } catch (RemoteException e) { 1392 Log.e(TAG, "MountService not running?"); 1393 } 1394 } 1395 } break; 1396 case WRITE_SETTINGS: { 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 synchronized (mPackages) { 1399 removeMessages(WRITE_SETTINGS); 1400 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1401 mSettings.writeLPr(); 1402 mDirtyUsers.clear(); 1403 } 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1405 } break; 1406 case WRITE_PACKAGE_RESTRICTIONS: { 1407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1408 synchronized (mPackages) { 1409 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1410 for (int userId : mDirtyUsers) { 1411 mSettings.writePackageRestrictionsLPr(userId); 1412 } 1413 mDirtyUsers.clear(); 1414 } 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } break; 1417 case CHECK_PENDING_VERIFICATION: { 1418 final int verificationId = msg.arg1; 1419 final PackageVerificationState state = mPendingVerification.get(verificationId); 1420 1421 if ((state != null) && !state.timeoutExtended()) { 1422 final InstallArgs args = state.getInstallArgs(); 1423 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1424 1425 Slog.i(TAG, "Verification timed out for " + originUri); 1426 mPendingVerification.remove(verificationId); 1427 1428 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1429 1430 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1431 Slog.i(TAG, "Continuing with installation of " + originUri); 1432 state.setVerifierResponse(Binder.getCallingUid(), 1433 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1434 broadcastPackageVerified(verificationId, originUri, 1435 PackageManager.VERIFICATION_ALLOW, 1436 state.getInstallArgs().getUser()); 1437 try { 1438 ret = args.copyApk(mContainerService, true); 1439 } catch (RemoteException e) { 1440 Slog.e(TAG, "Could not contact the ContainerService"); 1441 } 1442 } else { 1443 broadcastPackageVerified(verificationId, originUri, 1444 PackageManager.VERIFICATION_REJECT, 1445 state.getInstallArgs().getUser()); 1446 } 1447 1448 processPendingInstall(args, ret); 1449 mHandler.sendEmptyMessage(MCS_UNBIND); 1450 } 1451 break; 1452 } 1453 case PACKAGE_VERIFIED: { 1454 final int verificationId = msg.arg1; 1455 1456 final PackageVerificationState state = mPendingVerification.get(verificationId); 1457 if (state == null) { 1458 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1459 break; 1460 } 1461 1462 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1463 1464 state.setVerifierResponse(response.callerUid, response.code); 1465 1466 if (state.isVerificationComplete()) { 1467 mPendingVerification.remove(verificationId); 1468 1469 final InstallArgs args = state.getInstallArgs(); 1470 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1471 1472 int ret; 1473 if (state.isInstallAllowed()) { 1474 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1475 broadcastPackageVerified(verificationId, originUri, 1476 response.code, state.getInstallArgs().getUser()); 1477 try { 1478 ret = args.copyApk(mContainerService, true); 1479 } catch (RemoteException e) { 1480 Slog.e(TAG, "Could not contact the ContainerService"); 1481 } 1482 } else { 1483 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1484 } 1485 1486 processPendingInstall(args, ret); 1487 1488 mHandler.sendEmptyMessage(MCS_UNBIND); 1489 } 1490 1491 break; 1492 } 1493 case START_INTENT_FILTER_VERIFICATIONS: { 1494 int userId = msg.arg1; 1495 int verifierUid = msg.arg2; 1496 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1497 1498 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1499 break; 1500 } 1501 case INTENT_FILTER_VERIFIED: { 1502 final int verificationId = msg.arg1; 1503 1504 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1505 verificationId); 1506 if (state == null) { 1507 Slog.w(TAG, "Invalid IntentFilter verification token " 1508 + verificationId + " received"); 1509 break; 1510 } 1511 1512 final int userId = state.getUserId(); 1513 1514 Slog.d(TAG, "Processing IntentFilter verification with token:" 1515 + verificationId + " and userId:" + userId); 1516 1517 final IntentFilterVerificationResponse response = 1518 (IntentFilterVerificationResponse) msg.obj; 1519 1520 state.setVerifierResponse(response.callerUid, response.code); 1521 1522 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1523 + " and userId:" + userId 1524 + " is settings verifier response with response code:" 1525 + response.code); 1526 1527 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1528 Slog.d(TAG, "Domains failing verification: " 1529 + response.getFailedDomainsString()); 1530 } 1531 1532 if (state.isVerificationComplete()) { 1533 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1534 } else { 1535 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1536 + " was not said to be complete"); 1537 } 1538 1539 break; 1540 } 1541 } 1542 } 1543 } 1544 1545 private StorageEventListener mStorageListener = new StorageEventListener() { 1546 @Override 1547 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1548 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1549 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1550 // TODO: ensure that private directories exist for all active users 1551 // TODO: remove user data whose serial number doesn't match 1552 loadPrivatePackages(vol); 1553 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1554 unloadPrivatePackages(vol); 1555 } 1556 } 1557 1558 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1559 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1560 updateExternalMediaStatus(true, false); 1561 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1562 updateExternalMediaStatus(false, false); 1563 } 1564 } 1565 } 1566 1567 @Override 1568 public void onVolumeForgotten(String fsUuid) { 1569 // TODO: remove all packages hosted on this uuid 1570 } 1571 }; 1572 1573 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1574 if (userId >= UserHandle.USER_OWNER) { 1575 grantRequestedRuntimePermissionsForUser(pkg, userId); 1576 } else if (userId == UserHandle.USER_ALL) { 1577 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1578 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1579 } 1580 } 1581 } 1582 1583 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1584 SettingBase sb = (SettingBase) pkg.mExtras; 1585 if (sb == null) { 1586 return; 1587 } 1588 1589 PermissionsState permissionsState = sb.getPermissionsState(); 1590 1591 for (String permission : pkg.requestedPermissions) { 1592 BasePermission bp = mSettings.mPermissions.get(permission); 1593 if (bp != null && bp.isRuntime()) { 1594 permissionsState.grantRuntimePermission(bp, userId); 1595 } 1596 } 1597 } 1598 1599 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1600 Bundle extras = null; 1601 switch (res.returnCode) { 1602 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1603 extras = new Bundle(); 1604 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1605 res.origPermission); 1606 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1607 res.origPackage); 1608 break; 1609 } 1610 case PackageManager.INSTALL_SUCCEEDED: { 1611 extras = new Bundle(); 1612 extras.putBoolean(Intent.EXTRA_REPLACING, 1613 res.removedInfo != null && res.removedInfo.removedPackage != null); 1614 break; 1615 } 1616 } 1617 return extras; 1618 } 1619 1620 void scheduleWriteSettingsLocked() { 1621 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1622 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1623 } 1624 } 1625 1626 void scheduleWritePackageRestrictionsLocked(int userId) { 1627 if (!sUserManager.exists(userId)) return; 1628 mDirtyUsers.add(userId); 1629 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1630 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1631 } 1632 } 1633 1634 public static PackageManagerService main(Context context, Installer installer, 1635 boolean factoryTest, boolean onlyCore) { 1636 PackageManagerService m = new PackageManagerService(context, installer, 1637 factoryTest, onlyCore); 1638 ServiceManager.addService("package", m); 1639 return m; 1640 } 1641 1642 static String[] splitString(String str, char sep) { 1643 int count = 1; 1644 int i = 0; 1645 while ((i=str.indexOf(sep, i)) >= 0) { 1646 count++; 1647 i++; 1648 } 1649 1650 String[] res = new String[count]; 1651 i=0; 1652 count = 0; 1653 int lastI=0; 1654 while ((i=str.indexOf(sep, i)) >= 0) { 1655 res[count] = str.substring(lastI, i); 1656 count++; 1657 i++; 1658 lastI = i; 1659 } 1660 res[count] = str.substring(lastI, str.length()); 1661 return res; 1662 } 1663 1664 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1665 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1666 Context.DISPLAY_SERVICE); 1667 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1668 } 1669 1670 public PackageManagerService(Context context, Installer installer, 1671 boolean factoryTest, boolean onlyCore) { 1672 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1673 SystemClock.uptimeMillis()); 1674 1675 if (mSdkVersion <= 0) { 1676 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1677 } 1678 1679 mContext = context; 1680 mFactoryTest = factoryTest; 1681 mOnlyCore = onlyCore; 1682 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1683 mMetrics = new DisplayMetrics(); 1684 mSettings = new Settings(mPackages); 1685 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1686 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1687 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1688 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1689 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 1698 // TODO: add a property to control this? 1699 long dexOptLRUThresholdInMinutes; 1700 if (mLazyDexOpt) { 1701 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1702 } else { 1703 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1704 } 1705 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1706 1707 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1708 if (separateProcesses != null && separateProcesses.length() > 0) { 1709 if ("*".equals(separateProcesses)) { 1710 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1711 mSeparateProcesses = null; 1712 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1713 } else { 1714 mDefParseFlags = 0; 1715 mSeparateProcesses = separateProcesses.split(","); 1716 Slog.w(TAG, "Running with debug.separate_processes: " 1717 + separateProcesses); 1718 } 1719 } else { 1720 mDefParseFlags = 0; 1721 mSeparateProcesses = null; 1722 } 1723 1724 mInstaller = installer; 1725 mPackageDexOptimizer = new PackageDexOptimizer(this); 1726 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1727 1728 getDefaultDisplayMetrics(context, mMetrics); 1729 1730 SystemConfig systemConfig = SystemConfig.getInstance(); 1731 mGlobalGids = systemConfig.getGlobalGids(); 1732 mSystemPermissions = systemConfig.getSystemPermissions(); 1733 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1734 1735 synchronized (mInstallLock) { 1736 // writer 1737 synchronized (mPackages) { 1738 mHandlerThread = new ServiceThread(TAG, 1739 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1740 mHandlerThread.start(); 1741 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1742 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1743 1744 File dataDir = Environment.getDataDirectory(); 1745 mAppDataDir = new File(dataDir, "data"); 1746 mAppInstallDir = new File(dataDir, "app"); 1747 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1748 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1749 mUserAppDataDir = new File(dataDir, "user"); 1750 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1751 1752 sUserManager = new UserManagerService(context, this, 1753 mInstallLock, mPackages); 1754 1755 // Propagate permission configuration in to package manager. 1756 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1757 = systemConfig.getPermissions(); 1758 for (int i=0; i<permConfig.size(); i++) { 1759 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1760 BasePermission bp = mSettings.mPermissions.get(perm.name); 1761 if (bp == null) { 1762 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1763 mSettings.mPermissions.put(perm.name, bp); 1764 } 1765 if (perm.gids != null) { 1766 bp.setGids(perm.gids, perm.perUser); 1767 } 1768 } 1769 1770 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1771 for (int i=0; i<libConfig.size(); i++) { 1772 mSharedLibraries.put(libConfig.keyAt(i), 1773 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1774 } 1775 1776 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1777 1778 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1779 mSdkVersion, mOnlyCore); 1780 1781 String customResolverActivity = Resources.getSystem().getString( 1782 R.string.config_customResolverActivity); 1783 if (TextUtils.isEmpty(customResolverActivity)) { 1784 customResolverActivity = null; 1785 } else { 1786 mCustomResolverComponentName = ComponentName.unflattenFromString( 1787 customResolverActivity); 1788 } 1789 1790 long startTime = SystemClock.uptimeMillis(); 1791 1792 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1793 startTime); 1794 1795 // Set flag to monitor and not change apk file paths when 1796 // scanning install directories. 1797 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1798 1799 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1800 1801 /** 1802 * Add everything in the in the boot class path to the 1803 * list of process files because dexopt will have been run 1804 * if necessary during zygote startup. 1805 */ 1806 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1807 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1808 1809 if (bootClassPath != null) { 1810 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1811 for (String element : bootClassPathElements) { 1812 alreadyDexOpted.add(element); 1813 } 1814 } else { 1815 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1816 } 1817 1818 if (systemServerClassPath != null) { 1819 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1820 for (String element : systemServerClassPathElements) { 1821 alreadyDexOpted.add(element); 1822 } 1823 } else { 1824 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1825 } 1826 1827 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1828 final String[] dexCodeInstructionSets = 1829 getDexCodeInstructionSets( 1830 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1831 1832 /** 1833 * Ensure all external libraries have had dexopt run on them. 1834 */ 1835 if (mSharedLibraries.size() > 0) { 1836 // NOTE: For now, we're compiling these system "shared libraries" 1837 // (and framework jars) into all available architectures. It's possible 1838 // to compile them only when we come across an app that uses them (there's 1839 // already logic for that in scanPackageLI) but that adds some complexity. 1840 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1841 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1842 final String lib = libEntry.path; 1843 if (lib == null) { 1844 continue; 1845 } 1846 1847 try { 1848 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1849 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1850 alreadyDexOpted.add(lib); 1851 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1852 } 1853 } catch (FileNotFoundException e) { 1854 Slog.w(TAG, "Library not found: " + lib); 1855 } catch (IOException e) { 1856 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1857 + e.getMessage()); 1858 } 1859 } 1860 } 1861 } 1862 1863 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1864 1865 // Gross hack for now: we know this file doesn't contain any 1866 // code, so don't dexopt it to avoid the resulting log spew. 1867 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1868 1869 // Gross hack for now: we know this file is only part of 1870 // the boot class path for art, so don't dexopt it to 1871 // avoid the resulting log spew. 1872 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1873 1874 /** 1875 * And there are a number of commands implemented in Java, which 1876 * we currently need to do the dexopt on so that they can be 1877 * run from a non-root shell. 1878 */ 1879 String[] frameworkFiles = frameworkDir.list(); 1880 if (frameworkFiles != null) { 1881 // TODO: We could compile these only for the most preferred ABI. We should 1882 // first double check that the dex files for these commands are not referenced 1883 // by other system apps. 1884 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1885 for (int i=0; i<frameworkFiles.length; i++) { 1886 File libPath = new File(frameworkDir, frameworkFiles[i]); 1887 String path = libPath.getPath(); 1888 // Skip the file if we already did it. 1889 if (alreadyDexOpted.contains(path)) { 1890 continue; 1891 } 1892 // Skip the file if it is not a type we want to dexopt. 1893 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1894 continue; 1895 } 1896 try { 1897 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1898 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1899 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1900 } 1901 } catch (FileNotFoundException e) { 1902 Slog.w(TAG, "Jar not found: " + path); 1903 } catch (IOException e) { 1904 Slog.w(TAG, "Exception reading jar: " + path, e); 1905 } 1906 } 1907 } 1908 } 1909 1910 // Collect vendor overlay packages. 1911 // (Do this before scanning any apps.) 1912 // For security and version matching reason, only consider 1913 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1914 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1915 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1916 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1917 1918 // Find base frameworks (resource packages without code). 1919 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1920 | PackageParser.PARSE_IS_SYSTEM_DIR 1921 | PackageParser.PARSE_IS_PRIVILEGED, 1922 scanFlags | SCAN_NO_DEX, 0); 1923 1924 // Collected privileged system packages. 1925 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1926 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1927 | PackageParser.PARSE_IS_SYSTEM_DIR 1928 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1929 1930 // Collect ordinary system packages. 1931 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1932 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1933 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1934 1935 // Collect all vendor packages. 1936 File vendorAppDir = new File("/vendor/app"); 1937 try { 1938 vendorAppDir = vendorAppDir.getCanonicalFile(); 1939 } catch (IOException e) { 1940 // failed to look up canonical path, continue with original one 1941 } 1942 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1943 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1944 1945 // Collect all OEM packages. 1946 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1947 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1949 1950 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1951 mInstaller.moveFiles(); 1952 1953 // Prune any system packages that no longer exist. 1954 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1955 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1956 if (!mOnlyCore) { 1957 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1958 while (psit.hasNext()) { 1959 PackageSetting ps = psit.next(); 1960 1961 /* 1962 * If this is not a system app, it can't be a 1963 * disable system app. 1964 */ 1965 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1966 continue; 1967 } 1968 1969 /* 1970 * If the package is scanned, it's not erased. 1971 */ 1972 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1973 if (scannedPkg != null) { 1974 /* 1975 * If the system app is both scanned and in the 1976 * disabled packages list, then it must have been 1977 * added via OTA. Remove it from the currently 1978 * scanned package so the previously user-installed 1979 * application can be scanned. 1980 */ 1981 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1982 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1983 + ps.name + "; removing system app. Last known codePath=" 1984 + ps.codePathString + ", installStatus=" + ps.installStatus 1985 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1986 + scannedPkg.mVersionCode); 1987 removePackageLI(ps, true); 1988 expectingBetter.put(ps.name, ps.codePath); 1989 } 1990 1991 continue; 1992 } 1993 1994 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1995 psit.remove(); 1996 logCriticalInfo(Log.WARN, "System package " + ps.name 1997 + " no longer exists; wiping its data"); 1998 removeDataDirsLI(null, ps.name); 1999 } else { 2000 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2001 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2002 possiblyDeletedUpdatedSystemApps.add(ps.name); 2003 } 2004 } 2005 } 2006 } 2007 2008 //look for any incomplete package installations 2009 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2010 //clean up list 2011 for(int i = 0; i < deletePkgsList.size(); i++) { 2012 //clean up here 2013 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2014 } 2015 //delete tmp files 2016 deleteTempPackageFiles(); 2017 2018 // Remove any shared userIDs that have no associated packages 2019 mSettings.pruneSharedUsersLPw(); 2020 2021 if (!mOnlyCore) { 2022 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2023 SystemClock.uptimeMillis()); 2024 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2025 2026 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2027 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2028 2029 /** 2030 * Remove disable package settings for any updated system 2031 * apps that were removed via an OTA. If they're not a 2032 * previously-updated app, remove them completely. 2033 * Otherwise, just revoke their system-level permissions. 2034 */ 2035 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2036 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2037 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2038 2039 String msg; 2040 if (deletedPkg == null) { 2041 msg = "Updated system package " + deletedAppName 2042 + " no longer exists; wiping its data"; 2043 removeDataDirsLI(null, deletedAppName); 2044 } else { 2045 msg = "Updated system app + " + deletedAppName 2046 + " no longer present; removing system privileges for " 2047 + deletedAppName; 2048 2049 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2050 2051 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2052 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2053 } 2054 logCriticalInfo(Log.WARN, msg); 2055 } 2056 2057 /** 2058 * Make sure all system apps that we expected to appear on 2059 * the userdata partition actually showed up. If they never 2060 * appeared, crawl back and revive the system version. 2061 */ 2062 for (int i = 0; i < expectingBetter.size(); i++) { 2063 final String packageName = expectingBetter.keyAt(i); 2064 if (!mPackages.containsKey(packageName)) { 2065 final File scanFile = expectingBetter.valueAt(i); 2066 2067 logCriticalInfo(Log.WARN, "Expected better " + packageName 2068 + " but never showed up; reverting to system"); 2069 2070 final int reparseFlags; 2071 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2072 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR 2074 | PackageParser.PARSE_IS_PRIVILEGED; 2075 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2076 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2077 | PackageParser.PARSE_IS_SYSTEM_DIR; 2078 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2079 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR; 2081 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2082 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR; 2084 } else { 2085 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2086 continue; 2087 } 2088 2089 mSettings.enableSystemPackageLPw(packageName); 2090 2091 try { 2092 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2093 } catch (PackageManagerException e) { 2094 Slog.e(TAG, "Failed to parse original system package: " 2095 + e.getMessage()); 2096 } 2097 } 2098 } 2099 } 2100 2101 // Now that we know all of the shared libraries, update all clients to have 2102 // the correct library paths. 2103 updateAllSharedLibrariesLPw(); 2104 2105 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2106 // NOTE: We ignore potential failures here during a system scan (like 2107 // the rest of the commands above) because there's precious little we 2108 // can do about it. A settings error is reported, though. 2109 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2110 false /* force dexopt */, false /* defer dexopt */); 2111 } 2112 2113 // Now that we know all the packages we are keeping, 2114 // read and update their last usage times. 2115 mPackageUsage.readLP(); 2116 2117 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2118 SystemClock.uptimeMillis()); 2119 Slog.i(TAG, "Time to scan packages: " 2120 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2121 + " seconds"); 2122 2123 // If the platform SDK has changed since the last time we booted, 2124 // we need to re-grant app permission to catch any new ones that 2125 // appear. This is really a hack, and means that apps can in some 2126 // cases get permissions that the user didn't initially explicitly 2127 // allow... it would be nice to have some better way to handle 2128 // this situation. 2129 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2130 != mSdkVersion; 2131 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2132 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2133 + "; regranting permissions for internal storage"); 2134 mSettings.mInternalSdkPlatform = mSdkVersion; 2135 2136 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2137 | (regrantPermissions 2138 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2139 : 0)); 2140 2141 // If this is the first boot, and it is a normal boot, then 2142 // we need to initialize the default preferred apps. 2143 if (!mRestoredSettings && !onlyCore) { 2144 mSettings.readDefaultPreferredAppsLPw(this, 0); 2145 } 2146 2147 // If this is first boot after an OTA, and a normal boot, then 2148 // we need to clear code cache directories. 2149 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2150 if (mIsUpgrade && !onlyCore) { 2151 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2152 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2153 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2154 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2155 } 2156 mSettings.mFingerprint = Build.FINGERPRINT; 2157 } 2158 2159 primeDomainVerificationsLPw(false); 2160 checkDefaultBrowser(); 2161 2162 // All the changes are done during package scanning. 2163 mSettings.updateInternalDatabaseVersion(); 2164 2165 // can downgrade to reader 2166 mSettings.writeLPr(); 2167 2168 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2169 SystemClock.uptimeMillis()); 2170 2171 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2172 2173 mInstallerService = new PackageInstallerService(context, this); 2174 2175 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2176 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2177 mIntentFilterVerifierComponent); 2178 2179 } // synchronized (mPackages) 2180 } // synchronized (mInstallLock) 2181 2182 // Now after opening every single application zip, make sure they 2183 // are all flushed. Not really needed, but keeps things nice and 2184 // tidy. 2185 Runtime.getRuntime().gc(); 2186 } 2187 2188 @Override 2189 public boolean isFirstBoot() { 2190 return !mRestoredSettings; 2191 } 2192 2193 @Override 2194 public boolean isOnlyCoreApps() { 2195 return mOnlyCore; 2196 } 2197 2198 @Override 2199 public boolean isUpgrade() { 2200 return mIsUpgrade; 2201 } 2202 2203 private String getRequiredVerifierLPr() { 2204 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2205 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2206 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2207 2208 String requiredVerifier = null; 2209 2210 final int N = receivers.size(); 2211 for (int i = 0; i < N; i++) { 2212 final ResolveInfo info = receivers.get(i); 2213 2214 if (info.activityInfo == null) { 2215 continue; 2216 } 2217 2218 final String packageName = info.activityInfo.packageName; 2219 2220 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2221 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2222 continue; 2223 } 2224 2225 if (requiredVerifier != null) { 2226 throw new RuntimeException("There can be only one required verifier"); 2227 } 2228 2229 requiredVerifier = packageName; 2230 } 2231 2232 return requiredVerifier; 2233 } 2234 2235 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2236 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2237 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2238 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2239 2240 ComponentName verifierComponentName = null; 2241 2242 int priority = -1000; 2243 final int N = receivers.size(); 2244 for (int i = 0; i < N; i++) { 2245 final ResolveInfo info = receivers.get(i); 2246 2247 if (info.activityInfo == null) { 2248 continue; 2249 } 2250 2251 final String packageName = info.activityInfo.packageName; 2252 2253 final PackageSetting ps = mSettings.mPackages.get(packageName); 2254 if (ps == null) { 2255 continue; 2256 } 2257 2258 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2259 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2260 continue; 2261 } 2262 2263 // Select the IntentFilterVerifier with the highest priority 2264 if (priority < info.priority) { 2265 priority = info.priority; 2266 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2267 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2268 " with priority: " + info.priority); 2269 } 2270 } 2271 2272 return verifierComponentName; 2273 } 2274 2275 private void primeDomainVerificationsLPw(boolean logging) { 2276 Slog.d(TAG, "Start priming domain verifications"); 2277 boolean updated = false; 2278 ArraySet<String> allHostsSet = new ArraySet<>(); 2279 for (PackageParser.Package pkg : mPackages.values()) { 2280 final String packageName = pkg.packageName; 2281 if (!hasDomainURLs(pkg)) { 2282 if (logging) { 2283 Slog.d(TAG, "No priming domain verifications for " + 2284 "package with no domain URLs: " + packageName); 2285 } 2286 continue; 2287 } 2288 if (!pkg.isSystemApp()) { 2289 if (logging) { 2290 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2291 packageName); 2292 } 2293 continue; 2294 } 2295 for (PackageParser.Activity a : pkg.activities) { 2296 for (ActivityIntentInfo filter : a.intents) { 2297 if (hasValidDomains(filter, false)) { 2298 allHostsSet.addAll(filter.getHostsList()); 2299 } 2300 } 2301 } 2302 if (allHostsSet.size() == 0) { 2303 allHostsSet.add("*"); 2304 } 2305 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2306 IntentFilterVerificationInfo ivi = 2307 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2308 if (ivi != null) { 2309 // We will always log this 2310 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2311 " with hosts:" + ivi.getDomainsString()); 2312 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2313 updated = true; 2314 } 2315 else { 2316 if (logging) { 2317 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2318 } 2319 } 2320 allHostsSet.clear(); 2321 } 2322 if (updated) { 2323 if (logging) { 2324 Slog.d(TAG, "Will need to write primed domain verifications"); 2325 } 2326 } 2327 Slog.d(TAG, "End priming domain verifications"); 2328 } 2329 2330 private void checkDefaultBrowser() { 2331 final int myUserId = UserHandle.myUserId(); 2332 final String packageName = getDefaultBrowserPackageName(myUserId); 2333 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2334 if (info == null) { 2335 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2336 packageName); 2337 setDefaultBrowserPackageName(null, myUserId); 2338 } 2339 } 2340 2341 @Override 2342 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2343 throws RemoteException { 2344 try { 2345 return super.onTransact(code, data, reply, flags); 2346 } catch (RuntimeException e) { 2347 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2348 Slog.wtf(TAG, "Package Manager Crash", e); 2349 } 2350 throw e; 2351 } 2352 } 2353 2354 void cleanupInstallFailedPackage(PackageSetting ps) { 2355 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2356 2357 removeDataDirsLI(ps.volumeUuid, ps.name); 2358 if (ps.codePath != null) { 2359 if (ps.codePath.isDirectory()) { 2360 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2361 } else { 2362 ps.codePath.delete(); 2363 } 2364 } 2365 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2366 if (ps.resourcePath.isDirectory()) { 2367 FileUtils.deleteContents(ps.resourcePath); 2368 } 2369 ps.resourcePath.delete(); 2370 } 2371 mSettings.removePackageLPw(ps.name); 2372 } 2373 2374 static int[] appendInts(int[] cur, int[] add) { 2375 if (add == null) return cur; 2376 if (cur == null) return add; 2377 final int N = add.length; 2378 for (int i=0; i<N; i++) { 2379 cur = appendInt(cur, add[i]); 2380 } 2381 return cur; 2382 } 2383 2384 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2385 if (!sUserManager.exists(userId)) return null; 2386 final PackageSetting ps = (PackageSetting) p.mExtras; 2387 if (ps == null) { 2388 return null; 2389 } 2390 2391 final PermissionsState permissionsState = ps.getPermissionsState(); 2392 2393 final int[] gids = permissionsState.computeGids(userId); 2394 final Set<String> permissions = permissionsState.getPermissions(userId); 2395 final PackageUserState state = ps.readUserState(userId); 2396 2397 return PackageParser.generatePackageInfo(p, gids, flags, 2398 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2399 } 2400 2401 @Override 2402 public boolean isPackageFrozen(String packageName) { 2403 synchronized (mPackages) { 2404 final PackageSetting ps = mSettings.mPackages.get(packageName); 2405 if (ps != null) { 2406 return ps.frozen; 2407 } 2408 } 2409 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2410 return true; 2411 } 2412 2413 @Override 2414 public boolean isPackageAvailable(String packageName, int userId) { 2415 if (!sUserManager.exists(userId)) return false; 2416 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2417 synchronized (mPackages) { 2418 PackageParser.Package p = mPackages.get(packageName); 2419 if (p != null) { 2420 final PackageSetting ps = (PackageSetting) p.mExtras; 2421 if (ps != null) { 2422 final PackageUserState state = ps.readUserState(userId); 2423 if (state != null) { 2424 return PackageParser.isAvailable(state); 2425 } 2426 } 2427 } 2428 } 2429 return false; 2430 } 2431 2432 @Override 2433 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2434 if (!sUserManager.exists(userId)) return null; 2435 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2436 // reader 2437 synchronized (mPackages) { 2438 PackageParser.Package p = mPackages.get(packageName); 2439 if (DEBUG_PACKAGE_INFO) 2440 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2441 if (p != null) { 2442 return generatePackageInfo(p, flags, userId); 2443 } 2444 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2445 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2446 } 2447 } 2448 return null; 2449 } 2450 2451 @Override 2452 public String[] currentToCanonicalPackageNames(String[] names) { 2453 String[] out = new String[names.length]; 2454 // reader 2455 synchronized (mPackages) { 2456 for (int i=names.length-1; i>=0; i--) { 2457 PackageSetting ps = mSettings.mPackages.get(names[i]); 2458 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2459 } 2460 } 2461 return out; 2462 } 2463 2464 @Override 2465 public String[] canonicalToCurrentPackageNames(String[] names) { 2466 String[] out = new String[names.length]; 2467 // reader 2468 synchronized (mPackages) { 2469 for (int i=names.length-1; i>=0; i--) { 2470 String cur = mSettings.mRenamedPackages.get(names[i]); 2471 out[i] = cur != null ? cur : names[i]; 2472 } 2473 } 2474 return out; 2475 } 2476 2477 @Override 2478 public int getPackageUid(String packageName, int userId) { 2479 if (!sUserManager.exists(userId)) return -1; 2480 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2481 2482 // reader 2483 synchronized (mPackages) { 2484 PackageParser.Package p = mPackages.get(packageName); 2485 if(p != null) { 2486 return UserHandle.getUid(userId, p.applicationInfo.uid); 2487 } 2488 PackageSetting ps = mSettings.mPackages.get(packageName); 2489 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2490 return -1; 2491 } 2492 p = ps.pkg; 2493 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2494 } 2495 } 2496 2497 @Override 2498 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2499 if (!sUserManager.exists(userId)) { 2500 return null; 2501 } 2502 2503 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2504 "getPackageGids"); 2505 2506 // reader 2507 synchronized (mPackages) { 2508 PackageParser.Package p = mPackages.get(packageName); 2509 if (DEBUG_PACKAGE_INFO) { 2510 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2511 } 2512 if (p != null) { 2513 PackageSetting ps = (PackageSetting) p.mExtras; 2514 return ps.getPermissionsState().computeGids(userId); 2515 } 2516 } 2517 2518 return null; 2519 } 2520 2521 static PermissionInfo generatePermissionInfo( 2522 BasePermission bp, int flags) { 2523 if (bp.perm != null) { 2524 return PackageParser.generatePermissionInfo(bp.perm, flags); 2525 } 2526 PermissionInfo pi = new PermissionInfo(); 2527 pi.name = bp.name; 2528 pi.packageName = bp.sourcePackage; 2529 pi.nonLocalizedLabel = bp.name; 2530 pi.protectionLevel = bp.protectionLevel; 2531 return pi; 2532 } 2533 2534 @Override 2535 public PermissionInfo getPermissionInfo(String name, int flags) { 2536 // reader 2537 synchronized (mPackages) { 2538 final BasePermission p = mSettings.mPermissions.get(name); 2539 if (p != null) { 2540 return generatePermissionInfo(p, flags); 2541 } 2542 return null; 2543 } 2544 } 2545 2546 @Override 2547 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2548 // reader 2549 synchronized (mPackages) { 2550 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2551 for (BasePermission p : mSettings.mPermissions.values()) { 2552 if (group == null) { 2553 if (p.perm == null || p.perm.info.group == null) { 2554 out.add(generatePermissionInfo(p, flags)); 2555 } 2556 } else { 2557 if (p.perm != null && group.equals(p.perm.info.group)) { 2558 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2559 } 2560 } 2561 } 2562 2563 if (out.size() > 0) { 2564 return out; 2565 } 2566 return mPermissionGroups.containsKey(group) ? out : null; 2567 } 2568 } 2569 2570 @Override 2571 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2572 // reader 2573 synchronized (mPackages) { 2574 return PackageParser.generatePermissionGroupInfo( 2575 mPermissionGroups.get(name), flags); 2576 } 2577 } 2578 2579 @Override 2580 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2581 // reader 2582 synchronized (mPackages) { 2583 final int N = mPermissionGroups.size(); 2584 ArrayList<PermissionGroupInfo> out 2585 = new ArrayList<PermissionGroupInfo>(N); 2586 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2587 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2588 } 2589 return out; 2590 } 2591 } 2592 2593 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2594 int userId) { 2595 if (!sUserManager.exists(userId)) return null; 2596 PackageSetting ps = mSettings.mPackages.get(packageName); 2597 if (ps != null) { 2598 if (ps.pkg == null) { 2599 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2600 flags, userId); 2601 if (pInfo != null) { 2602 return pInfo.applicationInfo; 2603 } 2604 return null; 2605 } 2606 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2607 ps.readUserState(userId), userId); 2608 } 2609 return null; 2610 } 2611 2612 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2613 int userId) { 2614 if (!sUserManager.exists(userId)) return null; 2615 PackageSetting ps = mSettings.mPackages.get(packageName); 2616 if (ps != null) { 2617 PackageParser.Package pkg = ps.pkg; 2618 if (pkg == null) { 2619 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2620 return null; 2621 } 2622 // Only data remains, so we aren't worried about code paths 2623 pkg = new PackageParser.Package(packageName); 2624 pkg.applicationInfo.packageName = packageName; 2625 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2626 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2627 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2628 packageName, userId).getAbsolutePath(); 2629 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2630 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2631 } 2632 return generatePackageInfo(pkg, flags, userId); 2633 } 2634 return null; 2635 } 2636 2637 @Override 2638 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2639 if (!sUserManager.exists(userId)) return null; 2640 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2641 // writer 2642 synchronized (mPackages) { 2643 PackageParser.Package p = mPackages.get(packageName); 2644 if (DEBUG_PACKAGE_INFO) Log.v( 2645 TAG, "getApplicationInfo " + packageName 2646 + ": " + p); 2647 if (p != null) { 2648 PackageSetting ps = mSettings.mPackages.get(packageName); 2649 if (ps == null) return null; 2650 // Note: isEnabledLP() does not apply here - always return info 2651 return PackageParser.generateApplicationInfo( 2652 p, flags, ps.readUserState(userId), userId); 2653 } 2654 if ("android".equals(packageName)||"system".equals(packageName)) { 2655 return mAndroidApplication; 2656 } 2657 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2658 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2659 } 2660 } 2661 return null; 2662 } 2663 2664 @Override 2665 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2666 final IPackageDataObserver observer) { 2667 mContext.enforceCallingOrSelfPermission( 2668 android.Manifest.permission.CLEAR_APP_CACHE, null); 2669 // Queue up an async operation since clearing cache may take a little while. 2670 mHandler.post(new Runnable() { 2671 public void run() { 2672 mHandler.removeCallbacks(this); 2673 int retCode = -1; 2674 synchronized (mInstallLock) { 2675 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2676 if (retCode < 0) { 2677 Slog.w(TAG, "Couldn't clear application caches"); 2678 } 2679 } 2680 if (observer != null) { 2681 try { 2682 observer.onRemoveCompleted(null, (retCode >= 0)); 2683 } catch (RemoteException e) { 2684 Slog.w(TAG, "RemoveException when invoking call back"); 2685 } 2686 } 2687 } 2688 }); 2689 } 2690 2691 @Override 2692 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2693 final IntentSender pi) { 2694 mContext.enforceCallingOrSelfPermission( 2695 android.Manifest.permission.CLEAR_APP_CACHE, null); 2696 // Queue up an async operation since clearing cache may take a little while. 2697 mHandler.post(new Runnable() { 2698 public void run() { 2699 mHandler.removeCallbacks(this); 2700 int retCode = -1; 2701 synchronized (mInstallLock) { 2702 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2703 if (retCode < 0) { 2704 Slog.w(TAG, "Couldn't clear application caches"); 2705 } 2706 } 2707 if(pi != null) { 2708 try { 2709 // Callback via pending intent 2710 int code = (retCode >= 0) ? 1 : 0; 2711 pi.sendIntent(null, code, null, 2712 null, null); 2713 } catch (SendIntentException e1) { 2714 Slog.i(TAG, "Failed to send pending intent"); 2715 } 2716 } 2717 } 2718 }); 2719 } 2720 2721 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2722 synchronized (mInstallLock) { 2723 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2724 throw new IOException("Failed to free enough space"); 2725 } 2726 } 2727 } 2728 2729 @Override 2730 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2731 if (!sUserManager.exists(userId)) return null; 2732 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2733 synchronized (mPackages) { 2734 PackageParser.Activity a = mActivities.mActivities.get(component); 2735 2736 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2737 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2738 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2739 if (ps == null) return null; 2740 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2741 userId); 2742 } 2743 if (mResolveComponentName.equals(component)) { 2744 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2745 new PackageUserState(), userId); 2746 } 2747 } 2748 return null; 2749 } 2750 2751 @Override 2752 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2753 String resolvedType) { 2754 synchronized (mPackages) { 2755 PackageParser.Activity a = mActivities.mActivities.get(component); 2756 if (a == null) { 2757 return false; 2758 } 2759 for (int i=0; i<a.intents.size(); i++) { 2760 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2761 intent.getData(), intent.getCategories(), TAG) >= 0) { 2762 return true; 2763 } 2764 } 2765 return false; 2766 } 2767 } 2768 2769 @Override 2770 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2771 if (!sUserManager.exists(userId)) return null; 2772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2773 synchronized (mPackages) { 2774 PackageParser.Activity a = mReceivers.mActivities.get(component); 2775 if (DEBUG_PACKAGE_INFO) Log.v( 2776 TAG, "getReceiverInfo " + component + ": " + a); 2777 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2778 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2779 if (ps == null) return null; 2780 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2781 userId); 2782 } 2783 } 2784 return null; 2785 } 2786 2787 @Override 2788 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2789 if (!sUserManager.exists(userId)) return null; 2790 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2791 synchronized (mPackages) { 2792 PackageParser.Service s = mServices.mServices.get(component); 2793 if (DEBUG_PACKAGE_INFO) Log.v( 2794 TAG, "getServiceInfo " + component + ": " + s); 2795 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2796 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2797 if (ps == null) return null; 2798 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2799 userId); 2800 } 2801 } 2802 return null; 2803 } 2804 2805 @Override 2806 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2807 if (!sUserManager.exists(userId)) return null; 2808 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2809 synchronized (mPackages) { 2810 PackageParser.Provider p = mProviders.mProviders.get(component); 2811 if (DEBUG_PACKAGE_INFO) Log.v( 2812 TAG, "getProviderInfo " + component + ": " + p); 2813 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2814 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2815 if (ps == null) return null; 2816 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2817 userId); 2818 } 2819 } 2820 return null; 2821 } 2822 2823 @Override 2824 public String[] getSystemSharedLibraryNames() { 2825 Set<String> libSet; 2826 synchronized (mPackages) { 2827 libSet = mSharedLibraries.keySet(); 2828 int size = libSet.size(); 2829 if (size > 0) { 2830 String[] libs = new String[size]; 2831 libSet.toArray(libs); 2832 return libs; 2833 } 2834 } 2835 return null; 2836 } 2837 2838 /** 2839 * @hide 2840 */ 2841 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2842 synchronized (mPackages) { 2843 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2844 if (lib != null && lib.apk != null) { 2845 return mPackages.get(lib.apk); 2846 } 2847 } 2848 return null; 2849 } 2850 2851 @Override 2852 public FeatureInfo[] getSystemAvailableFeatures() { 2853 Collection<FeatureInfo> featSet; 2854 synchronized (mPackages) { 2855 featSet = mAvailableFeatures.values(); 2856 int size = featSet.size(); 2857 if (size > 0) { 2858 FeatureInfo[] features = new FeatureInfo[size+1]; 2859 featSet.toArray(features); 2860 FeatureInfo fi = new FeatureInfo(); 2861 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2862 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2863 features[size] = fi; 2864 return features; 2865 } 2866 } 2867 return null; 2868 } 2869 2870 @Override 2871 public boolean hasSystemFeature(String name) { 2872 synchronized (mPackages) { 2873 return mAvailableFeatures.containsKey(name); 2874 } 2875 } 2876 2877 private void checkValidCaller(int uid, int userId) { 2878 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2879 return; 2880 2881 throw new SecurityException("Caller uid=" + uid 2882 + " is not privileged to communicate with user=" + userId); 2883 } 2884 2885 @Override 2886 public int checkPermission(String permName, String pkgName, int userId) { 2887 if (!sUserManager.exists(userId)) { 2888 return PackageManager.PERMISSION_DENIED; 2889 } 2890 2891 synchronized (mPackages) { 2892 final PackageParser.Package p = mPackages.get(pkgName); 2893 if (p != null && p.mExtras != null) { 2894 final PackageSetting ps = (PackageSetting) p.mExtras; 2895 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2896 return PackageManager.PERMISSION_GRANTED; 2897 } 2898 } 2899 } 2900 2901 return PackageManager.PERMISSION_DENIED; 2902 } 2903 2904 @Override 2905 public int checkUidPermission(String permName, int uid) { 2906 final int userId = UserHandle.getUserId(uid); 2907 2908 if (!sUserManager.exists(userId)) { 2909 return PackageManager.PERMISSION_DENIED; 2910 } 2911 2912 synchronized (mPackages) { 2913 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2914 if (obj != null) { 2915 final SettingBase ps = (SettingBase) obj; 2916 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2917 return PackageManager.PERMISSION_GRANTED; 2918 } 2919 } else { 2920 ArraySet<String> perms = mSystemPermissions.get(uid); 2921 if (perms != null && perms.contains(permName)) { 2922 return PackageManager.PERMISSION_GRANTED; 2923 } 2924 } 2925 } 2926 2927 return PackageManager.PERMISSION_DENIED; 2928 } 2929 2930 /** 2931 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2932 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2933 * @param checkShell TODO(yamasani): 2934 * @param message the message to log on security exception 2935 */ 2936 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2937 boolean checkShell, String message) { 2938 if (userId < 0) { 2939 throw new IllegalArgumentException("Invalid userId " + userId); 2940 } 2941 if (checkShell) { 2942 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2943 } 2944 if (userId == UserHandle.getUserId(callingUid)) return; 2945 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2946 if (requireFullPermission) { 2947 mContext.enforceCallingOrSelfPermission( 2948 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2949 } else { 2950 try { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } catch (SecurityException se) { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2956 } 2957 } 2958 } 2959 } 2960 2961 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2962 if (callingUid == Process.SHELL_UID) { 2963 if (userHandle >= 0 2964 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2965 throw new SecurityException("Shell does not have permission to access user " 2966 + userHandle); 2967 } else if (userHandle < 0) { 2968 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2969 + Debug.getCallers(3)); 2970 } 2971 } 2972 } 2973 2974 private BasePermission findPermissionTreeLP(String permName) { 2975 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2976 if (permName.startsWith(bp.name) && 2977 permName.length() > bp.name.length() && 2978 permName.charAt(bp.name.length()) == '.') { 2979 return bp; 2980 } 2981 } 2982 return null; 2983 } 2984 2985 private BasePermission checkPermissionTreeLP(String permName) { 2986 if (permName != null) { 2987 BasePermission bp = findPermissionTreeLP(permName); 2988 if (bp != null) { 2989 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2990 return bp; 2991 } 2992 throw new SecurityException("Calling uid " 2993 + Binder.getCallingUid() 2994 + " is not allowed to add to permission tree " 2995 + bp.name + " owned by uid " + bp.uid); 2996 } 2997 } 2998 throw new SecurityException("No permission tree found for " + permName); 2999 } 3000 3001 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3002 if (s1 == null) { 3003 return s2 == null; 3004 } 3005 if (s2 == null) { 3006 return false; 3007 } 3008 if (s1.getClass() != s2.getClass()) { 3009 return false; 3010 } 3011 return s1.equals(s2); 3012 } 3013 3014 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3015 if (pi1.icon != pi2.icon) return false; 3016 if (pi1.logo != pi2.logo) return false; 3017 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3018 if (!compareStrings(pi1.name, pi2.name)) return false; 3019 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3020 // We'll take care of setting this one. 3021 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3022 // These are not currently stored in settings. 3023 //if (!compareStrings(pi1.group, pi2.group)) return false; 3024 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3025 //if (pi1.labelRes != pi2.labelRes) return false; 3026 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3027 return true; 3028 } 3029 3030 int permissionInfoFootprint(PermissionInfo info) { 3031 int size = info.name.length(); 3032 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3033 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3034 return size; 3035 } 3036 3037 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3038 int size = 0; 3039 for (BasePermission perm : mSettings.mPermissions.values()) { 3040 if (perm.uid == tree.uid) { 3041 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3042 } 3043 } 3044 return size; 3045 } 3046 3047 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3048 // We calculate the max size of permissions defined by this uid and throw 3049 // if that plus the size of 'info' would exceed our stated maximum. 3050 if (tree.uid != Process.SYSTEM_UID) { 3051 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3052 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3053 throw new SecurityException("Permission tree size cap exceeded"); 3054 } 3055 } 3056 } 3057 3058 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3059 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3060 throw new SecurityException("Label must be specified in permission"); 3061 } 3062 BasePermission tree = checkPermissionTreeLP(info.name); 3063 BasePermission bp = mSettings.mPermissions.get(info.name); 3064 boolean added = bp == null; 3065 boolean changed = true; 3066 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3067 if (added) { 3068 enforcePermissionCapLocked(info, tree); 3069 bp = new BasePermission(info.name, tree.sourcePackage, 3070 BasePermission.TYPE_DYNAMIC); 3071 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3072 throw new SecurityException( 3073 "Not allowed to modify non-dynamic permission " 3074 + info.name); 3075 } else { 3076 if (bp.protectionLevel == fixedLevel 3077 && bp.perm.owner.equals(tree.perm.owner) 3078 && bp.uid == tree.uid 3079 && comparePermissionInfos(bp.perm.info, info)) { 3080 changed = false; 3081 } 3082 } 3083 bp.protectionLevel = fixedLevel; 3084 info = new PermissionInfo(info); 3085 info.protectionLevel = fixedLevel; 3086 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3087 bp.perm.info.packageName = tree.perm.info.packageName; 3088 bp.uid = tree.uid; 3089 if (added) { 3090 mSettings.mPermissions.put(info.name, bp); 3091 } 3092 if (changed) { 3093 if (!async) { 3094 mSettings.writeLPr(); 3095 } else { 3096 scheduleWriteSettingsLocked(); 3097 } 3098 } 3099 return added; 3100 } 3101 3102 @Override 3103 public boolean addPermission(PermissionInfo info) { 3104 synchronized (mPackages) { 3105 return addPermissionLocked(info, false); 3106 } 3107 } 3108 3109 @Override 3110 public boolean addPermissionAsync(PermissionInfo info) { 3111 synchronized (mPackages) { 3112 return addPermissionLocked(info, true); 3113 } 3114 } 3115 3116 @Override 3117 public void removePermission(String name) { 3118 synchronized (mPackages) { 3119 checkPermissionTreeLP(name); 3120 BasePermission bp = mSettings.mPermissions.get(name); 3121 if (bp != null) { 3122 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3123 throw new SecurityException( 3124 "Not allowed to modify non-dynamic permission " 3125 + name); 3126 } 3127 mSettings.mPermissions.remove(name); 3128 mSettings.writeLPr(); 3129 } 3130 } 3131 } 3132 3133 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3134 BasePermission bp) { 3135 int index = pkg.requestedPermissions.indexOf(bp.name); 3136 if (index == -1) { 3137 throw new SecurityException("Package " + pkg.packageName 3138 + " has not requested permission " + bp.name); 3139 } 3140 if (!bp.isRuntime()) { 3141 throw new SecurityException("Permission " + bp.name 3142 + " is not a changeable permission type"); 3143 } 3144 } 3145 3146 @Override 3147 public void grantRuntimePermission(String packageName, String name, int userId) { 3148 if (!sUserManager.exists(userId)) { 3149 return; 3150 } 3151 3152 mContext.enforceCallingOrSelfPermission( 3153 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3154 "grantRuntimePermission"); 3155 3156 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3157 "grantRuntimePermission"); 3158 3159 boolean gidsChanged = false; 3160 final SettingBase sb; 3161 3162 synchronized (mPackages) { 3163 final PackageParser.Package pkg = mPackages.get(packageName); 3164 if (pkg == null) { 3165 throw new IllegalArgumentException("Unknown package: " + packageName); 3166 } 3167 3168 final BasePermission bp = mSettings.mPermissions.get(name); 3169 if (bp == null) { 3170 throw new IllegalArgumentException("Unknown permission: " + name); 3171 } 3172 3173 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3174 3175 sb = (SettingBase) pkg.mExtras; 3176 if (sb == null) { 3177 throw new IllegalArgumentException("Unknown package: " + packageName); 3178 } 3179 3180 final PermissionsState permissionsState = sb.getPermissionsState(); 3181 3182 final int result = permissionsState.grantRuntimePermission(bp, userId); 3183 switch (result) { 3184 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3185 return; 3186 } 3187 3188 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3189 gidsChanged = true; 3190 } 3191 break; 3192 } 3193 3194 // Not critical if that is lost - app has to request again. 3195 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3196 } 3197 3198 if (gidsChanged) { 3199 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3200 } 3201 } 3202 3203 @Override 3204 public void revokeRuntimePermission(String packageName, String name, int userId) { 3205 if (!sUserManager.exists(userId)) { 3206 return; 3207 } 3208 3209 mContext.enforceCallingOrSelfPermission( 3210 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3211 "revokeRuntimePermission"); 3212 3213 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3214 "revokeRuntimePermission"); 3215 3216 final SettingBase sb; 3217 3218 synchronized (mPackages) { 3219 final PackageParser.Package pkg = mPackages.get(packageName); 3220 if (pkg == null) { 3221 throw new IllegalArgumentException("Unknown package: " + packageName); 3222 } 3223 3224 final BasePermission bp = mSettings.mPermissions.get(name); 3225 if (bp == null) { 3226 throw new IllegalArgumentException("Unknown permission: " + name); 3227 } 3228 3229 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3230 3231 sb = (SettingBase) pkg.mExtras; 3232 if (sb == null) { 3233 throw new IllegalArgumentException("Unknown package: " + packageName); 3234 } 3235 3236 final PermissionsState permissionsState = sb.getPermissionsState(); 3237 3238 if (permissionsState.revokeRuntimePermission(bp, userId) == 3239 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3240 return; 3241 } 3242 3243 // Critical, after this call app should never have the permission. 3244 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3245 } 3246 3247 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3248 } 3249 3250 @Override 3251 public int getPermissionFlags(String name, String packageName, int userId) { 3252 if (!sUserManager.exists(userId)) { 3253 return 0; 3254 } 3255 3256 mContext.enforceCallingOrSelfPermission( 3257 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3258 "getPermissionFlags"); 3259 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3261 "getPermissionFlags"); 3262 3263 synchronized (mPackages) { 3264 final PackageParser.Package pkg = mPackages.get(packageName); 3265 if (pkg == null) { 3266 throw new IllegalArgumentException("Unknown package: " + packageName); 3267 } 3268 3269 final BasePermission bp = mSettings.mPermissions.get(name); 3270 if (bp == null) { 3271 throw new IllegalArgumentException("Unknown permission: " + name); 3272 } 3273 3274 SettingBase sb = (SettingBase) pkg.mExtras; 3275 if (sb == null) { 3276 throw new IllegalArgumentException("Unknown package: " + packageName); 3277 } 3278 3279 PermissionsState permissionsState = sb.getPermissionsState(); 3280 return permissionsState.getPermissionFlags(name, userId); 3281 } 3282 } 3283 3284 @Override 3285 public void updatePermissionFlags(String name, String packageName, int flagMask, 3286 int flagValues, int userId) { 3287 if (!sUserManager.exists(userId)) { 3288 return; 3289 } 3290 3291 mContext.enforceCallingOrSelfPermission( 3292 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3293 "updatePermissionFlags"); 3294 3295 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3296 "updatePermissionFlags"); 3297 3298 // Only the system can change policy flags. 3299 if (getCallingUid() != Process.SYSTEM_UID) { 3300 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3301 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3302 } 3303 3304 // Only the package manager can change system flags. 3305 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3306 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3307 3308 synchronized (mPackages) { 3309 final PackageParser.Package pkg = mPackages.get(packageName); 3310 if (pkg == null) { 3311 throw new IllegalArgumentException("Unknown package: " + packageName); 3312 } 3313 3314 final BasePermission bp = mSettings.mPermissions.get(name); 3315 if (bp == null) { 3316 throw new IllegalArgumentException("Unknown permission: " + name); 3317 } 3318 3319 SettingBase sb = (SettingBase) pkg.mExtras; 3320 if (sb == null) { 3321 throw new IllegalArgumentException("Unknown package: " + packageName); 3322 } 3323 3324 PermissionsState permissionsState = sb.getPermissionsState(); 3325 3326 // Only the package manager can change flags for system component permissions. 3327 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3328 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3329 return; 3330 } 3331 3332 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3333 // Install and runtime permissions are stored in different places, 3334 // so figure out what permission changed and persist the change. 3335 if (permissionsState.getInstallPermissionState(name) != null) { 3336 scheduleWriteSettingsLocked(); 3337 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3338 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3339 } 3340 } 3341 } 3342 } 3343 3344 @Override 3345 public boolean isProtectedBroadcast(String actionName) { 3346 synchronized (mPackages) { 3347 return mProtectedBroadcasts.contains(actionName); 3348 } 3349 } 3350 3351 @Override 3352 public int checkSignatures(String pkg1, String pkg2) { 3353 synchronized (mPackages) { 3354 final PackageParser.Package p1 = mPackages.get(pkg1); 3355 final PackageParser.Package p2 = mPackages.get(pkg2); 3356 if (p1 == null || p1.mExtras == null 3357 || p2 == null || p2.mExtras == null) { 3358 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3359 } 3360 return compareSignatures(p1.mSignatures, p2.mSignatures); 3361 } 3362 } 3363 3364 @Override 3365 public int checkUidSignatures(int uid1, int uid2) { 3366 // Map to base uids. 3367 uid1 = UserHandle.getAppId(uid1); 3368 uid2 = UserHandle.getAppId(uid2); 3369 // reader 3370 synchronized (mPackages) { 3371 Signature[] s1; 3372 Signature[] s2; 3373 Object obj = mSettings.getUserIdLPr(uid1); 3374 if (obj != null) { 3375 if (obj instanceof SharedUserSetting) { 3376 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3377 } else if (obj instanceof PackageSetting) { 3378 s1 = ((PackageSetting)obj).signatures.mSignatures; 3379 } else { 3380 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3381 } 3382 } else { 3383 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3384 } 3385 obj = mSettings.getUserIdLPr(uid2); 3386 if (obj != null) { 3387 if (obj instanceof SharedUserSetting) { 3388 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3389 } else if (obj instanceof PackageSetting) { 3390 s2 = ((PackageSetting)obj).signatures.mSignatures; 3391 } else { 3392 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3393 } 3394 } else { 3395 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3396 } 3397 return compareSignatures(s1, s2); 3398 } 3399 } 3400 3401 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3402 final long identity = Binder.clearCallingIdentity(); 3403 try { 3404 if (sb instanceof SharedUserSetting) { 3405 SharedUserSetting sus = (SharedUserSetting) sb; 3406 final int packageCount = sus.packages.size(); 3407 for (int i = 0; i < packageCount; i++) { 3408 PackageSetting susPs = sus.packages.valueAt(i); 3409 if (userId == UserHandle.USER_ALL) { 3410 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3411 } else { 3412 final int uid = UserHandle.getUid(userId, susPs.appId); 3413 killUid(uid, reason); 3414 } 3415 } 3416 } else if (sb instanceof PackageSetting) { 3417 PackageSetting ps = (PackageSetting) sb; 3418 if (userId == UserHandle.USER_ALL) { 3419 killApplication(ps.pkg.packageName, ps.appId, reason); 3420 } else { 3421 final int uid = UserHandle.getUid(userId, ps.appId); 3422 killUid(uid, reason); 3423 } 3424 } 3425 } finally { 3426 Binder.restoreCallingIdentity(identity); 3427 } 3428 } 3429 3430 private static void killUid(int uid, String reason) { 3431 IActivityManager am = ActivityManagerNative.getDefault(); 3432 if (am != null) { 3433 try { 3434 am.killUid(uid, reason); 3435 } catch (RemoteException e) { 3436 /* ignore - same process */ 3437 } 3438 } 3439 } 3440 3441 /** 3442 * Compares two sets of signatures. Returns: 3443 * <br /> 3444 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3445 * <br /> 3446 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3447 * <br /> 3448 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3449 * <br /> 3450 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3451 * <br /> 3452 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3453 */ 3454 static int compareSignatures(Signature[] s1, Signature[] s2) { 3455 if (s1 == null) { 3456 return s2 == null 3457 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3458 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3459 } 3460 3461 if (s2 == null) { 3462 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3463 } 3464 3465 if (s1.length != s2.length) { 3466 return PackageManager.SIGNATURE_NO_MATCH; 3467 } 3468 3469 // Since both signature sets are of size 1, we can compare without HashSets. 3470 if (s1.length == 1) { 3471 return s1[0].equals(s2[0]) ? 3472 PackageManager.SIGNATURE_MATCH : 3473 PackageManager.SIGNATURE_NO_MATCH; 3474 } 3475 3476 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3477 for (Signature sig : s1) { 3478 set1.add(sig); 3479 } 3480 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3481 for (Signature sig : s2) { 3482 set2.add(sig); 3483 } 3484 // Make sure s2 contains all signatures in s1. 3485 if (set1.equals(set2)) { 3486 return PackageManager.SIGNATURE_MATCH; 3487 } 3488 return PackageManager.SIGNATURE_NO_MATCH; 3489 } 3490 3491 /** 3492 * If the database version for this type of package (internal storage or 3493 * external storage) is less than the version where package signatures 3494 * were updated, return true. 3495 */ 3496 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3497 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3498 DatabaseVersion.SIGNATURE_END_ENTITY)) 3499 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3500 DatabaseVersion.SIGNATURE_END_ENTITY)); 3501 } 3502 3503 /** 3504 * Used for backward compatibility to make sure any packages with 3505 * certificate chains get upgraded to the new style. {@code existingSigs} 3506 * will be in the old format (since they were stored on disk from before the 3507 * system upgrade) and {@code scannedSigs} will be in the newer format. 3508 */ 3509 private int compareSignaturesCompat(PackageSignatures existingSigs, 3510 PackageParser.Package scannedPkg) { 3511 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3512 return PackageManager.SIGNATURE_NO_MATCH; 3513 } 3514 3515 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3516 for (Signature sig : existingSigs.mSignatures) { 3517 existingSet.add(sig); 3518 } 3519 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3520 for (Signature sig : scannedPkg.mSignatures) { 3521 try { 3522 Signature[] chainSignatures = sig.getChainSignatures(); 3523 for (Signature chainSig : chainSignatures) { 3524 scannedCompatSet.add(chainSig); 3525 } 3526 } catch (CertificateEncodingException e) { 3527 scannedCompatSet.add(sig); 3528 } 3529 } 3530 /* 3531 * Make sure the expanded scanned set contains all signatures in the 3532 * existing one. 3533 */ 3534 if (scannedCompatSet.equals(existingSet)) { 3535 // Migrate the old signatures to the new scheme. 3536 existingSigs.assignSignatures(scannedPkg.mSignatures); 3537 // The new KeySets will be re-added later in the scanning process. 3538 synchronized (mPackages) { 3539 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3540 } 3541 return PackageManager.SIGNATURE_MATCH; 3542 } 3543 return PackageManager.SIGNATURE_NO_MATCH; 3544 } 3545 3546 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3547 if (isExternal(scannedPkg)) { 3548 return mSettings.isExternalDatabaseVersionOlderThan( 3549 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3550 } else { 3551 return mSettings.isInternalDatabaseVersionOlderThan( 3552 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3553 } 3554 } 3555 3556 private int compareSignaturesRecover(PackageSignatures existingSigs, 3557 PackageParser.Package scannedPkg) { 3558 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3559 return PackageManager.SIGNATURE_NO_MATCH; 3560 } 3561 3562 String msg = null; 3563 try { 3564 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3565 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3566 + scannedPkg.packageName); 3567 return PackageManager.SIGNATURE_MATCH; 3568 } 3569 } catch (CertificateException e) { 3570 msg = e.getMessage(); 3571 } 3572 3573 logCriticalInfo(Log.INFO, 3574 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3575 return PackageManager.SIGNATURE_NO_MATCH; 3576 } 3577 3578 @Override 3579 public String[] getPackagesForUid(int uid) { 3580 uid = UserHandle.getAppId(uid); 3581 // reader 3582 synchronized (mPackages) { 3583 Object obj = mSettings.getUserIdLPr(uid); 3584 if (obj instanceof SharedUserSetting) { 3585 final SharedUserSetting sus = (SharedUserSetting) obj; 3586 final int N = sus.packages.size(); 3587 final String[] res = new String[N]; 3588 final Iterator<PackageSetting> it = sus.packages.iterator(); 3589 int i = 0; 3590 while (it.hasNext()) { 3591 res[i++] = it.next().name; 3592 } 3593 return res; 3594 } else if (obj instanceof PackageSetting) { 3595 final PackageSetting ps = (PackageSetting) obj; 3596 return new String[] { ps.name }; 3597 } 3598 } 3599 return null; 3600 } 3601 3602 @Override 3603 public String getNameForUid(int uid) { 3604 // reader 3605 synchronized (mPackages) { 3606 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3607 if (obj instanceof SharedUserSetting) { 3608 final SharedUserSetting sus = (SharedUserSetting) obj; 3609 return sus.name + ":" + sus.userId; 3610 } else if (obj instanceof PackageSetting) { 3611 final PackageSetting ps = (PackageSetting) obj; 3612 return ps.name; 3613 } 3614 } 3615 return null; 3616 } 3617 3618 @Override 3619 public int getUidForSharedUser(String sharedUserName) { 3620 if(sharedUserName == null) { 3621 return -1; 3622 } 3623 // reader 3624 synchronized (mPackages) { 3625 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3626 if (suid == null) { 3627 return -1; 3628 } 3629 return suid.userId; 3630 } 3631 } 3632 3633 @Override 3634 public int getFlagsForUid(int uid) { 3635 synchronized (mPackages) { 3636 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3637 if (obj instanceof SharedUserSetting) { 3638 final SharedUserSetting sus = (SharedUserSetting) obj; 3639 return sus.pkgFlags; 3640 } else if (obj instanceof PackageSetting) { 3641 final PackageSetting ps = (PackageSetting) obj; 3642 return ps.pkgFlags; 3643 } 3644 } 3645 return 0; 3646 } 3647 3648 @Override 3649 public int getPrivateFlagsForUid(int uid) { 3650 synchronized (mPackages) { 3651 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3652 if (obj instanceof SharedUserSetting) { 3653 final SharedUserSetting sus = (SharedUserSetting) obj; 3654 return sus.pkgPrivateFlags; 3655 } else if (obj instanceof PackageSetting) { 3656 final PackageSetting ps = (PackageSetting) obj; 3657 return ps.pkgPrivateFlags; 3658 } 3659 } 3660 return 0; 3661 } 3662 3663 @Override 3664 public boolean isUidPrivileged(int uid) { 3665 uid = UserHandle.getAppId(uid); 3666 // reader 3667 synchronized (mPackages) { 3668 Object obj = mSettings.getUserIdLPr(uid); 3669 if (obj instanceof SharedUserSetting) { 3670 final SharedUserSetting sus = (SharedUserSetting) obj; 3671 final Iterator<PackageSetting> it = sus.packages.iterator(); 3672 while (it.hasNext()) { 3673 if (it.next().isPrivileged()) { 3674 return true; 3675 } 3676 } 3677 } else if (obj instanceof PackageSetting) { 3678 final PackageSetting ps = (PackageSetting) obj; 3679 return ps.isPrivileged(); 3680 } 3681 } 3682 return false; 3683 } 3684 3685 @Override 3686 public String[] getAppOpPermissionPackages(String permissionName) { 3687 synchronized (mPackages) { 3688 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3689 if (pkgs == null) { 3690 return null; 3691 } 3692 return pkgs.toArray(new String[pkgs.size()]); 3693 } 3694 } 3695 3696 @Override 3697 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3698 int flags, int userId) { 3699 if (!sUserManager.exists(userId)) return null; 3700 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3701 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3702 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3703 } 3704 3705 @Override 3706 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3707 IntentFilter filter, int match, ComponentName activity) { 3708 final int userId = UserHandle.getCallingUserId(); 3709 if (DEBUG_PREFERRED) { 3710 Log.v(TAG, "setLastChosenActivity intent=" + intent 3711 + " resolvedType=" + resolvedType 3712 + " flags=" + flags 3713 + " filter=" + filter 3714 + " match=" + match 3715 + " activity=" + activity); 3716 filter.dump(new PrintStreamPrinter(System.out), " "); 3717 } 3718 intent.setComponent(null); 3719 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3720 // Find any earlier preferred or last chosen entries and nuke them 3721 findPreferredActivity(intent, resolvedType, 3722 flags, query, 0, false, true, false, userId); 3723 // Add the new activity as the last chosen for this filter 3724 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3725 "Setting last chosen"); 3726 } 3727 3728 @Override 3729 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3730 final int userId = UserHandle.getCallingUserId(); 3731 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3732 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3733 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3734 false, false, false, userId); 3735 } 3736 3737 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3738 int flags, List<ResolveInfo> query, int userId) { 3739 if (query != null) { 3740 final int N = query.size(); 3741 if (N == 1) { 3742 return query.get(0); 3743 } else if (N > 1) { 3744 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3745 // If there is more than one activity with the same priority, 3746 // then let the user decide between them. 3747 ResolveInfo r0 = query.get(0); 3748 ResolveInfo r1 = query.get(1); 3749 if (DEBUG_INTENT_MATCHING || debug) { 3750 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3751 + r1.activityInfo.name + "=" + r1.priority); 3752 } 3753 // If the first activity has a higher priority, or a different 3754 // default, then it is always desireable to pick it. 3755 if (r0.priority != r1.priority 3756 || r0.preferredOrder != r1.preferredOrder 3757 || r0.isDefault != r1.isDefault) { 3758 return query.get(0); 3759 } 3760 // If we have saved a preference for a preferred activity for 3761 // this Intent, use that. 3762 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3763 flags, query, r0.priority, true, false, debug, userId); 3764 if (ri != null) { 3765 return ri; 3766 } 3767 if (userId != 0) { 3768 ri = new ResolveInfo(mResolveInfo); 3769 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3770 ri.activityInfo.applicationInfo = new ApplicationInfo( 3771 ri.activityInfo.applicationInfo); 3772 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3773 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3774 return ri; 3775 } 3776 return mResolveInfo; 3777 } 3778 } 3779 return null; 3780 } 3781 3782 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3783 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3784 final int N = query.size(); 3785 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3786 .get(userId); 3787 // Get the list of persistent preferred activities that handle the intent 3788 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3789 List<PersistentPreferredActivity> pprefs = ppir != null 3790 ? ppir.queryIntent(intent, resolvedType, 3791 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3792 : null; 3793 if (pprefs != null && pprefs.size() > 0) { 3794 final int M = pprefs.size(); 3795 for (int i=0; i<M; i++) { 3796 final PersistentPreferredActivity ppa = pprefs.get(i); 3797 if (DEBUG_PREFERRED || debug) { 3798 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3799 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3800 + "\n component=" + ppa.mComponent); 3801 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3802 } 3803 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3804 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3805 if (DEBUG_PREFERRED || debug) { 3806 Slog.v(TAG, "Found persistent preferred activity:"); 3807 if (ai != null) { 3808 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3809 } else { 3810 Slog.v(TAG, " null"); 3811 } 3812 } 3813 if (ai == null) { 3814 // This previously registered persistent preferred activity 3815 // component is no longer known. Ignore it and do NOT remove it. 3816 continue; 3817 } 3818 for (int j=0; j<N; j++) { 3819 final ResolveInfo ri = query.get(j); 3820 if (!ri.activityInfo.applicationInfo.packageName 3821 .equals(ai.applicationInfo.packageName)) { 3822 continue; 3823 } 3824 if (!ri.activityInfo.name.equals(ai.name)) { 3825 continue; 3826 } 3827 // Found a persistent preference that can handle the intent. 3828 if (DEBUG_PREFERRED || debug) { 3829 Slog.v(TAG, "Returning persistent preferred activity: " + 3830 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3831 } 3832 return ri; 3833 } 3834 } 3835 } 3836 return null; 3837 } 3838 3839 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3840 List<ResolveInfo> query, int priority, boolean always, 3841 boolean removeMatches, boolean debug, int userId) { 3842 if (!sUserManager.exists(userId)) return null; 3843 // writer 3844 synchronized (mPackages) { 3845 if (intent.getSelector() != null) { 3846 intent = intent.getSelector(); 3847 } 3848 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3849 3850 // Try to find a matching persistent preferred activity. 3851 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3852 debug, userId); 3853 3854 // If a persistent preferred activity matched, use it. 3855 if (pri != null) { 3856 return pri; 3857 } 3858 3859 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3860 // Get the list of preferred activities that handle the intent 3861 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3862 List<PreferredActivity> prefs = pir != null 3863 ? pir.queryIntent(intent, resolvedType, 3864 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3865 : null; 3866 if (prefs != null && prefs.size() > 0) { 3867 boolean changed = false; 3868 try { 3869 // First figure out how good the original match set is. 3870 // We will only allow preferred activities that came 3871 // from the same match quality. 3872 int match = 0; 3873 3874 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3875 3876 final int N = query.size(); 3877 for (int j=0; j<N; j++) { 3878 final ResolveInfo ri = query.get(j); 3879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3880 + ": 0x" + Integer.toHexString(match)); 3881 if (ri.match > match) { 3882 match = ri.match; 3883 } 3884 } 3885 3886 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3887 + Integer.toHexString(match)); 3888 3889 match &= IntentFilter.MATCH_CATEGORY_MASK; 3890 final int M = prefs.size(); 3891 for (int i=0; i<M; i++) { 3892 final PreferredActivity pa = prefs.get(i); 3893 if (DEBUG_PREFERRED || debug) { 3894 Slog.v(TAG, "Checking PreferredActivity ds=" 3895 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3896 + "\n component=" + pa.mPref.mComponent); 3897 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3898 } 3899 if (pa.mPref.mMatch != match) { 3900 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3901 + Integer.toHexString(pa.mPref.mMatch)); 3902 continue; 3903 } 3904 // If it's not an "always" type preferred activity and that's what we're 3905 // looking for, skip it. 3906 if (always && !pa.mPref.mAlways) { 3907 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3908 continue; 3909 } 3910 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3911 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3912 if (DEBUG_PREFERRED || debug) { 3913 Slog.v(TAG, "Found preferred activity:"); 3914 if (ai != null) { 3915 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3916 } else { 3917 Slog.v(TAG, " null"); 3918 } 3919 } 3920 if (ai == null) { 3921 // This previously registered preferred activity 3922 // component is no longer known. Most likely an update 3923 // to the app was installed and in the new version this 3924 // component no longer exists. Clean it up by removing 3925 // it from the preferred activities list, and skip it. 3926 Slog.w(TAG, "Removing dangling preferred activity: " 3927 + pa.mPref.mComponent); 3928 pir.removeFilter(pa); 3929 changed = true; 3930 continue; 3931 } 3932 for (int j=0; j<N; j++) { 3933 final ResolveInfo ri = query.get(j); 3934 if (!ri.activityInfo.applicationInfo.packageName 3935 .equals(ai.applicationInfo.packageName)) { 3936 continue; 3937 } 3938 if (!ri.activityInfo.name.equals(ai.name)) { 3939 continue; 3940 } 3941 3942 if (removeMatches) { 3943 pir.removeFilter(pa); 3944 changed = true; 3945 if (DEBUG_PREFERRED) { 3946 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3947 } 3948 break; 3949 } 3950 3951 // Okay we found a previously set preferred or last chosen app. 3952 // If the result set is different from when this 3953 // was created, we need to clear it and re-ask the 3954 // user their preference, if we're looking for an "always" type entry. 3955 if (always && !pa.mPref.sameSet(query)) { 3956 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3957 + intent + " type " + resolvedType); 3958 if (DEBUG_PREFERRED) { 3959 Slog.v(TAG, "Removing preferred activity since set changed " 3960 + pa.mPref.mComponent); 3961 } 3962 pir.removeFilter(pa); 3963 // Re-add the filter as a "last chosen" entry (!always) 3964 PreferredActivity lastChosen = new PreferredActivity( 3965 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3966 pir.addFilter(lastChosen); 3967 changed = true; 3968 return null; 3969 } 3970 3971 // Yay! Either the set matched or we're looking for the last chosen 3972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3973 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3974 return ri; 3975 } 3976 } 3977 } finally { 3978 if (changed) { 3979 if (DEBUG_PREFERRED) { 3980 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3981 } 3982 scheduleWritePackageRestrictionsLocked(userId); 3983 } 3984 } 3985 } 3986 } 3987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3988 return null; 3989 } 3990 3991 /* 3992 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3993 */ 3994 @Override 3995 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3996 int targetUserId) { 3997 mContext.enforceCallingOrSelfPermission( 3998 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3999 List<CrossProfileIntentFilter> matches = 4000 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4001 if (matches != null) { 4002 int size = matches.size(); 4003 for (int i = 0; i < size; i++) { 4004 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4005 } 4006 } 4007 return false; 4008 } 4009 4010 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4011 String resolvedType, int userId) { 4012 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4013 if (resolver != null) { 4014 return resolver.queryIntent(intent, resolvedType, false, userId); 4015 } 4016 return null; 4017 } 4018 4019 @Override 4020 public List<ResolveInfo> queryIntentActivities(Intent intent, 4021 String resolvedType, int flags, int userId) { 4022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4023 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4024 ComponentName comp = intent.getComponent(); 4025 if (comp == null) { 4026 if (intent.getSelector() != null) { 4027 intent = intent.getSelector(); 4028 comp = intent.getComponent(); 4029 } 4030 } 4031 4032 if (comp != null) { 4033 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4034 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4035 if (ai != null) { 4036 final ResolveInfo ri = new ResolveInfo(); 4037 ri.activityInfo = ai; 4038 list.add(ri); 4039 } 4040 return list; 4041 } 4042 4043 // reader 4044 synchronized (mPackages) { 4045 final String pkgName = intent.getPackage(); 4046 if (pkgName == null) { 4047 List<CrossProfileIntentFilter> matchingFilters = 4048 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4049 // Check for results that need to skip the current profile. 4050 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4051 resolvedType, flags, userId); 4052 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4053 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4054 result.add(resolveInfo); 4055 return filterIfNotPrimaryUser(result, userId); 4056 } 4057 4058 // Check for results in the current profile. 4059 List<ResolveInfo> result = mActivities.queryIntent( 4060 intent, resolvedType, flags, userId); 4061 4062 // Check for cross profile results. 4063 resolveInfo = queryCrossProfileIntents( 4064 matchingFilters, intent, resolvedType, flags, userId); 4065 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4066 result.add(resolveInfo); 4067 Collections.sort(result, mResolvePrioritySorter); 4068 } 4069 result = filterIfNotPrimaryUser(result, userId); 4070 if (result.size() > 1 && hasWebURI(intent)) { 4071 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4072 } 4073 return result; 4074 } 4075 final PackageParser.Package pkg = mPackages.get(pkgName); 4076 if (pkg != null) { 4077 return filterIfNotPrimaryUser( 4078 mActivities.queryIntentForPackage( 4079 intent, resolvedType, flags, pkg.activities, userId), 4080 userId); 4081 } 4082 return new ArrayList<ResolveInfo>(); 4083 } 4084 } 4085 4086 private boolean isUserEnabled(int userId) { 4087 long callingId = Binder.clearCallingIdentity(); 4088 try { 4089 UserInfo userInfo = sUserManager.getUserInfo(userId); 4090 return userInfo != null && userInfo.isEnabled(); 4091 } finally { 4092 Binder.restoreCallingIdentity(callingId); 4093 } 4094 } 4095 4096 /** 4097 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4098 * 4099 * @return filtered list 4100 */ 4101 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4102 if (userId == UserHandle.USER_OWNER) { 4103 return resolveInfos; 4104 } 4105 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4106 ResolveInfo info = resolveInfos.get(i); 4107 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4108 resolveInfos.remove(i); 4109 } 4110 } 4111 return resolveInfos; 4112 } 4113 4114 private static boolean hasWebURI(Intent intent) { 4115 if (intent.getData() == null) { 4116 return false; 4117 } 4118 final String scheme = intent.getScheme(); 4119 if (TextUtils.isEmpty(scheme)) { 4120 return false; 4121 } 4122 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4123 } 4124 4125 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4126 int flags, List<ResolveInfo> candidates) { 4127 if (DEBUG_PREFERRED) { 4128 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4129 candidates.size()); 4130 } 4131 4132 final int userId = UserHandle.getCallingUserId(); 4133 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4134 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4135 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4136 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4137 4138 synchronized (mPackages) { 4139 final int count = candidates.size(); 4140 // First, try to use the domain prefered App. Partition the candidates into four lists: 4141 // one for the final results, one for the "do not use ever", one for "undefined status" 4142 // and finally one for "Browser App type". 4143 for (int n=0; n<count; n++) { 4144 ResolveInfo info = candidates.get(n); 4145 String packageName = info.activityInfo.packageName; 4146 PackageSetting ps = mSettings.mPackages.get(packageName); 4147 if (ps != null) { 4148 // Add to the special match all list (Browser use case) 4149 if (info.handleAllWebDataURI) { 4150 matchAllList.add(info); 4151 continue; 4152 } 4153 // Try to get the status from User settings first 4154 int status = getDomainVerificationStatusLPr(ps, userId); 4155 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4156 result.add(info); 4157 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4158 neverList.add(info); 4159 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4160 undefinedList.add(info); 4161 } 4162 } 4163 } 4164 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4165 result.addAll(undefinedList); 4166 // If there is nothing selected, add all candidates and remove the ones that the User 4167 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4168 // also remove Browser Apps ones. 4169 // If there is still none after this pass, add all Browser Apps and 4170 // let the User decide with the Disambiguation dialog if there are several ones. 4171 if (result.size() == 0) { 4172 result.addAll(candidates); 4173 } 4174 result.removeAll(neverList); 4175 result.removeAll(matchAllList); 4176 if (result.size() == 0) { 4177 if ((flags & MATCH_ALL) != 0) { 4178 result.addAll(matchAllList); 4179 } else { 4180 // Try to add the Default Browser if we can 4181 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4182 UserHandle.myUserId()); 4183 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4184 boolean defaultBrowserFound = false; 4185 final int browserCount = matchAllList.size(); 4186 for (int n=0; n<browserCount; n++) { 4187 ResolveInfo browser = matchAllList.get(n); 4188 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4189 result.add(browser); 4190 defaultBrowserFound = true; 4191 break; 4192 } 4193 } 4194 if (!defaultBrowserFound) { 4195 result.addAll(matchAllList); 4196 } 4197 } else { 4198 result.addAll(matchAllList); 4199 } 4200 } 4201 } 4202 } 4203 if (DEBUG_PREFERRED) { 4204 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4205 result.size()); 4206 } 4207 return result; 4208 } 4209 4210 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4211 int status = ps.getDomainVerificationStatusForUser(userId); 4212 // if none available, get the master status 4213 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4214 if (ps.getIntentFilterVerificationInfo() != null) { 4215 status = ps.getIntentFilterVerificationInfo().getStatus(); 4216 } 4217 } 4218 return status; 4219 } 4220 4221 private ResolveInfo querySkipCurrentProfileIntents( 4222 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4223 int flags, int sourceUserId) { 4224 if (matchingFilters != null) { 4225 int size = matchingFilters.size(); 4226 for (int i = 0; i < size; i ++) { 4227 CrossProfileIntentFilter filter = matchingFilters.get(i); 4228 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4229 // Checking if there are activities in the target user that can handle the 4230 // intent. 4231 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4232 flags, sourceUserId); 4233 if (resolveInfo != null) { 4234 return resolveInfo; 4235 } 4236 } 4237 } 4238 } 4239 return null; 4240 } 4241 4242 // Return matching ResolveInfo if any for skip current profile intent filters. 4243 private ResolveInfo queryCrossProfileIntents( 4244 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4245 int flags, int sourceUserId) { 4246 if (matchingFilters != null) { 4247 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4248 // match the same intent. For performance reasons, it is better not to 4249 // run queryIntent twice for the same userId 4250 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4251 int size = matchingFilters.size(); 4252 for (int i = 0; i < size; i++) { 4253 CrossProfileIntentFilter filter = matchingFilters.get(i); 4254 int targetUserId = filter.getTargetUserId(); 4255 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4256 && !alreadyTriedUserIds.get(targetUserId)) { 4257 // Checking if there are activities in the target user that can handle the 4258 // intent. 4259 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4260 flags, sourceUserId); 4261 if (resolveInfo != null) return resolveInfo; 4262 alreadyTriedUserIds.put(targetUserId, true); 4263 } 4264 } 4265 } 4266 return null; 4267 } 4268 4269 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4270 String resolvedType, int flags, int sourceUserId) { 4271 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4272 resolvedType, flags, filter.getTargetUserId()); 4273 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4274 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4275 } 4276 return null; 4277 } 4278 4279 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4280 int sourceUserId, int targetUserId) { 4281 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4282 String className; 4283 if (targetUserId == UserHandle.USER_OWNER) { 4284 className = FORWARD_INTENT_TO_USER_OWNER; 4285 } else { 4286 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4287 } 4288 ComponentName forwardingActivityComponentName = new ComponentName( 4289 mAndroidApplication.packageName, className); 4290 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4291 sourceUserId); 4292 if (targetUserId == UserHandle.USER_OWNER) { 4293 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4294 forwardingResolveInfo.noResourceId = true; 4295 } 4296 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4297 forwardingResolveInfo.priority = 0; 4298 forwardingResolveInfo.preferredOrder = 0; 4299 forwardingResolveInfo.match = 0; 4300 forwardingResolveInfo.isDefault = true; 4301 forwardingResolveInfo.filter = filter; 4302 forwardingResolveInfo.targetUserId = targetUserId; 4303 return forwardingResolveInfo; 4304 } 4305 4306 @Override 4307 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4308 Intent[] specifics, String[] specificTypes, Intent intent, 4309 String resolvedType, int flags, int userId) { 4310 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4311 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4312 false, "query intent activity options"); 4313 final String resultsAction = intent.getAction(); 4314 4315 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4316 | PackageManager.GET_RESOLVED_FILTER, userId); 4317 4318 if (DEBUG_INTENT_MATCHING) { 4319 Log.v(TAG, "Query " + intent + ": " + results); 4320 } 4321 4322 int specificsPos = 0; 4323 int N; 4324 4325 // todo: note that the algorithm used here is O(N^2). This 4326 // isn't a problem in our current environment, but if we start running 4327 // into situations where we have more than 5 or 10 matches then this 4328 // should probably be changed to something smarter... 4329 4330 // First we go through and resolve each of the specific items 4331 // that were supplied, taking care of removing any corresponding 4332 // duplicate items in the generic resolve list. 4333 if (specifics != null) { 4334 for (int i=0; i<specifics.length; i++) { 4335 final Intent sintent = specifics[i]; 4336 if (sintent == null) { 4337 continue; 4338 } 4339 4340 if (DEBUG_INTENT_MATCHING) { 4341 Log.v(TAG, "Specific #" + i + ": " + sintent); 4342 } 4343 4344 String action = sintent.getAction(); 4345 if (resultsAction != null && resultsAction.equals(action)) { 4346 // If this action was explicitly requested, then don't 4347 // remove things that have it. 4348 action = null; 4349 } 4350 4351 ResolveInfo ri = null; 4352 ActivityInfo ai = null; 4353 4354 ComponentName comp = sintent.getComponent(); 4355 if (comp == null) { 4356 ri = resolveIntent( 4357 sintent, 4358 specificTypes != null ? specificTypes[i] : null, 4359 flags, userId); 4360 if (ri == null) { 4361 continue; 4362 } 4363 if (ri == mResolveInfo) { 4364 // ACK! Must do something better with this. 4365 } 4366 ai = ri.activityInfo; 4367 comp = new ComponentName(ai.applicationInfo.packageName, 4368 ai.name); 4369 } else { 4370 ai = getActivityInfo(comp, flags, userId); 4371 if (ai == null) { 4372 continue; 4373 } 4374 } 4375 4376 // Look for any generic query activities that are duplicates 4377 // of this specific one, and remove them from the results. 4378 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4379 N = results.size(); 4380 int j; 4381 for (j=specificsPos; j<N; j++) { 4382 ResolveInfo sri = results.get(j); 4383 if ((sri.activityInfo.name.equals(comp.getClassName()) 4384 && sri.activityInfo.applicationInfo.packageName.equals( 4385 comp.getPackageName())) 4386 || (action != null && sri.filter.matchAction(action))) { 4387 results.remove(j); 4388 if (DEBUG_INTENT_MATCHING) Log.v( 4389 TAG, "Removing duplicate item from " + j 4390 + " due to specific " + specificsPos); 4391 if (ri == null) { 4392 ri = sri; 4393 } 4394 j--; 4395 N--; 4396 } 4397 } 4398 4399 // Add this specific item to its proper place. 4400 if (ri == null) { 4401 ri = new ResolveInfo(); 4402 ri.activityInfo = ai; 4403 } 4404 results.add(specificsPos, ri); 4405 ri.specificIndex = i; 4406 specificsPos++; 4407 } 4408 } 4409 4410 // Now we go through the remaining generic results and remove any 4411 // duplicate actions that are found here. 4412 N = results.size(); 4413 for (int i=specificsPos; i<N-1; i++) { 4414 final ResolveInfo rii = results.get(i); 4415 if (rii.filter == null) { 4416 continue; 4417 } 4418 4419 // Iterate over all of the actions of this result's intent 4420 // filter... typically this should be just one. 4421 final Iterator<String> it = rii.filter.actionsIterator(); 4422 if (it == null) { 4423 continue; 4424 } 4425 while (it.hasNext()) { 4426 final String action = it.next(); 4427 if (resultsAction != null && resultsAction.equals(action)) { 4428 // If this action was explicitly requested, then don't 4429 // remove things that have it. 4430 continue; 4431 } 4432 for (int j=i+1; j<N; j++) { 4433 final ResolveInfo rij = results.get(j); 4434 if (rij.filter != null && rij.filter.hasAction(action)) { 4435 results.remove(j); 4436 if (DEBUG_INTENT_MATCHING) Log.v( 4437 TAG, "Removing duplicate item from " + j 4438 + " due to action " + action + " at " + i); 4439 j--; 4440 N--; 4441 } 4442 } 4443 } 4444 4445 // If the caller didn't request filter information, drop it now 4446 // so we don't have to marshall/unmarshall it. 4447 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4448 rii.filter = null; 4449 } 4450 } 4451 4452 // Filter out the caller activity if so requested. 4453 if (caller != null) { 4454 N = results.size(); 4455 for (int i=0; i<N; i++) { 4456 ActivityInfo ainfo = results.get(i).activityInfo; 4457 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4458 && caller.getClassName().equals(ainfo.name)) { 4459 results.remove(i); 4460 break; 4461 } 4462 } 4463 } 4464 4465 // If the caller didn't request filter information, 4466 // drop them now so we don't have to 4467 // marshall/unmarshall it. 4468 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4469 N = results.size(); 4470 for (int i=0; i<N; i++) { 4471 results.get(i).filter = null; 4472 } 4473 } 4474 4475 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4476 return results; 4477 } 4478 4479 @Override 4480 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4481 int userId) { 4482 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4483 ComponentName comp = intent.getComponent(); 4484 if (comp == null) { 4485 if (intent.getSelector() != null) { 4486 intent = intent.getSelector(); 4487 comp = intent.getComponent(); 4488 } 4489 } 4490 if (comp != null) { 4491 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4492 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4493 if (ai != null) { 4494 ResolveInfo ri = new ResolveInfo(); 4495 ri.activityInfo = ai; 4496 list.add(ri); 4497 } 4498 return list; 4499 } 4500 4501 // reader 4502 synchronized (mPackages) { 4503 String pkgName = intent.getPackage(); 4504 if (pkgName == null) { 4505 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4506 } 4507 final PackageParser.Package pkg = mPackages.get(pkgName); 4508 if (pkg != null) { 4509 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4510 userId); 4511 } 4512 return null; 4513 } 4514 } 4515 4516 @Override 4517 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4518 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4519 if (!sUserManager.exists(userId)) return null; 4520 if (query != null) { 4521 if (query.size() >= 1) { 4522 // If there is more than one service with the same priority, 4523 // just arbitrarily pick the first one. 4524 return query.get(0); 4525 } 4526 } 4527 return null; 4528 } 4529 4530 @Override 4531 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4532 int userId) { 4533 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4534 ComponentName comp = intent.getComponent(); 4535 if (comp == null) { 4536 if (intent.getSelector() != null) { 4537 intent = intent.getSelector(); 4538 comp = intent.getComponent(); 4539 } 4540 } 4541 if (comp != null) { 4542 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4543 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4544 if (si != null) { 4545 final ResolveInfo ri = new ResolveInfo(); 4546 ri.serviceInfo = si; 4547 list.add(ri); 4548 } 4549 return list; 4550 } 4551 4552 // reader 4553 synchronized (mPackages) { 4554 String pkgName = intent.getPackage(); 4555 if (pkgName == null) { 4556 return mServices.queryIntent(intent, resolvedType, flags, userId); 4557 } 4558 final PackageParser.Package pkg = mPackages.get(pkgName); 4559 if (pkg != null) { 4560 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4561 userId); 4562 } 4563 return null; 4564 } 4565 } 4566 4567 @Override 4568 public List<ResolveInfo> queryIntentContentProviders( 4569 Intent intent, String resolvedType, int flags, int userId) { 4570 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4571 ComponentName comp = intent.getComponent(); 4572 if (comp == null) { 4573 if (intent.getSelector() != null) { 4574 intent = intent.getSelector(); 4575 comp = intent.getComponent(); 4576 } 4577 } 4578 if (comp != null) { 4579 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4580 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4581 if (pi != null) { 4582 final ResolveInfo ri = new ResolveInfo(); 4583 ri.providerInfo = pi; 4584 list.add(ri); 4585 } 4586 return list; 4587 } 4588 4589 // reader 4590 synchronized (mPackages) { 4591 String pkgName = intent.getPackage(); 4592 if (pkgName == null) { 4593 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4594 } 4595 final PackageParser.Package pkg = mPackages.get(pkgName); 4596 if (pkg != null) { 4597 return mProviders.queryIntentForPackage( 4598 intent, resolvedType, flags, pkg.providers, userId); 4599 } 4600 return null; 4601 } 4602 } 4603 4604 @Override 4605 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4606 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4607 4608 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4609 4610 // writer 4611 synchronized (mPackages) { 4612 ArrayList<PackageInfo> list; 4613 if (listUninstalled) { 4614 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4615 for (PackageSetting ps : mSettings.mPackages.values()) { 4616 PackageInfo pi; 4617 if (ps.pkg != null) { 4618 pi = generatePackageInfo(ps.pkg, flags, userId); 4619 } else { 4620 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4621 } 4622 if (pi != null) { 4623 list.add(pi); 4624 } 4625 } 4626 } else { 4627 list = new ArrayList<PackageInfo>(mPackages.size()); 4628 for (PackageParser.Package p : mPackages.values()) { 4629 PackageInfo pi = generatePackageInfo(p, flags, userId); 4630 if (pi != null) { 4631 list.add(pi); 4632 } 4633 } 4634 } 4635 4636 return new ParceledListSlice<PackageInfo>(list); 4637 } 4638 } 4639 4640 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4641 String[] permissions, boolean[] tmp, int flags, int userId) { 4642 int numMatch = 0; 4643 final PermissionsState permissionsState = ps.getPermissionsState(); 4644 for (int i=0; i<permissions.length; i++) { 4645 final String permission = permissions[i]; 4646 if (permissionsState.hasPermission(permission, userId)) { 4647 tmp[i] = true; 4648 numMatch++; 4649 } else { 4650 tmp[i] = false; 4651 } 4652 } 4653 if (numMatch == 0) { 4654 return; 4655 } 4656 PackageInfo pi; 4657 if (ps.pkg != null) { 4658 pi = generatePackageInfo(ps.pkg, flags, userId); 4659 } else { 4660 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4661 } 4662 // The above might return null in cases of uninstalled apps or install-state 4663 // skew across users/profiles. 4664 if (pi != null) { 4665 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4666 if (numMatch == permissions.length) { 4667 pi.requestedPermissions = permissions; 4668 } else { 4669 pi.requestedPermissions = new String[numMatch]; 4670 numMatch = 0; 4671 for (int i=0; i<permissions.length; i++) { 4672 if (tmp[i]) { 4673 pi.requestedPermissions[numMatch] = permissions[i]; 4674 numMatch++; 4675 } 4676 } 4677 } 4678 } 4679 list.add(pi); 4680 } 4681 } 4682 4683 @Override 4684 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4685 String[] permissions, int flags, int userId) { 4686 if (!sUserManager.exists(userId)) return null; 4687 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4688 4689 // writer 4690 synchronized (mPackages) { 4691 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4692 boolean[] tmpBools = new boolean[permissions.length]; 4693 if (listUninstalled) { 4694 for (PackageSetting ps : mSettings.mPackages.values()) { 4695 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4696 } 4697 } else { 4698 for (PackageParser.Package pkg : mPackages.values()) { 4699 PackageSetting ps = (PackageSetting)pkg.mExtras; 4700 if (ps != null) { 4701 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4702 userId); 4703 } 4704 } 4705 } 4706 4707 return new ParceledListSlice<PackageInfo>(list); 4708 } 4709 } 4710 4711 @Override 4712 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4713 if (!sUserManager.exists(userId)) return null; 4714 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4715 4716 // writer 4717 synchronized (mPackages) { 4718 ArrayList<ApplicationInfo> list; 4719 if (listUninstalled) { 4720 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4721 for (PackageSetting ps : mSettings.mPackages.values()) { 4722 ApplicationInfo ai; 4723 if (ps.pkg != null) { 4724 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4725 ps.readUserState(userId), userId); 4726 } else { 4727 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4728 } 4729 if (ai != null) { 4730 list.add(ai); 4731 } 4732 } 4733 } else { 4734 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4735 for (PackageParser.Package p : mPackages.values()) { 4736 if (p.mExtras != null) { 4737 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4738 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4739 if (ai != null) { 4740 list.add(ai); 4741 } 4742 } 4743 } 4744 } 4745 4746 return new ParceledListSlice<ApplicationInfo>(list); 4747 } 4748 } 4749 4750 public List<ApplicationInfo> getPersistentApplications(int flags) { 4751 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4752 4753 // reader 4754 synchronized (mPackages) { 4755 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4756 final int userId = UserHandle.getCallingUserId(); 4757 while (i.hasNext()) { 4758 final PackageParser.Package p = i.next(); 4759 if (p.applicationInfo != null 4760 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4761 && (!mSafeMode || isSystemApp(p))) { 4762 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4763 if (ps != null) { 4764 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4765 ps.readUserState(userId), userId); 4766 if (ai != null) { 4767 finalList.add(ai); 4768 } 4769 } 4770 } 4771 } 4772 } 4773 4774 return finalList; 4775 } 4776 4777 @Override 4778 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4779 if (!sUserManager.exists(userId)) return null; 4780 // reader 4781 synchronized (mPackages) { 4782 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4783 PackageSetting ps = provider != null 4784 ? mSettings.mPackages.get(provider.owner.packageName) 4785 : null; 4786 return ps != null 4787 && mSettings.isEnabledLPr(provider.info, flags, userId) 4788 && (!mSafeMode || (provider.info.applicationInfo.flags 4789 &ApplicationInfo.FLAG_SYSTEM) != 0) 4790 ? PackageParser.generateProviderInfo(provider, flags, 4791 ps.readUserState(userId), userId) 4792 : null; 4793 } 4794 } 4795 4796 /** 4797 * @deprecated 4798 */ 4799 @Deprecated 4800 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4801 // reader 4802 synchronized (mPackages) { 4803 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4804 .entrySet().iterator(); 4805 final int userId = UserHandle.getCallingUserId(); 4806 while (i.hasNext()) { 4807 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4808 PackageParser.Provider p = entry.getValue(); 4809 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4810 4811 if (ps != null && p.syncable 4812 && (!mSafeMode || (p.info.applicationInfo.flags 4813 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4814 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4815 ps.readUserState(userId), userId); 4816 if (info != null) { 4817 outNames.add(entry.getKey()); 4818 outInfo.add(info); 4819 } 4820 } 4821 } 4822 } 4823 } 4824 4825 @Override 4826 public List<ProviderInfo> queryContentProviders(String processName, 4827 int uid, int flags) { 4828 ArrayList<ProviderInfo> finalList = null; 4829 // reader 4830 synchronized (mPackages) { 4831 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4832 final int userId = processName != null ? 4833 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4834 while (i.hasNext()) { 4835 final PackageParser.Provider p = i.next(); 4836 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4837 if (ps != null && p.info.authority != null 4838 && (processName == null 4839 || (p.info.processName.equals(processName) 4840 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4841 && mSettings.isEnabledLPr(p.info, flags, userId) 4842 && (!mSafeMode 4843 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4844 if (finalList == null) { 4845 finalList = new ArrayList<ProviderInfo>(3); 4846 } 4847 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4848 ps.readUserState(userId), userId); 4849 if (info != null) { 4850 finalList.add(info); 4851 } 4852 } 4853 } 4854 } 4855 4856 if (finalList != null) { 4857 Collections.sort(finalList, mProviderInitOrderSorter); 4858 } 4859 4860 return finalList; 4861 } 4862 4863 @Override 4864 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4865 int flags) { 4866 // reader 4867 synchronized (mPackages) { 4868 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4869 return PackageParser.generateInstrumentationInfo(i, flags); 4870 } 4871 } 4872 4873 @Override 4874 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4875 int flags) { 4876 ArrayList<InstrumentationInfo> finalList = 4877 new ArrayList<InstrumentationInfo>(); 4878 4879 // reader 4880 synchronized (mPackages) { 4881 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4882 while (i.hasNext()) { 4883 final PackageParser.Instrumentation p = i.next(); 4884 if (targetPackage == null 4885 || targetPackage.equals(p.info.targetPackage)) { 4886 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4887 flags); 4888 if (ii != null) { 4889 finalList.add(ii); 4890 } 4891 } 4892 } 4893 } 4894 4895 return finalList; 4896 } 4897 4898 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4899 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4900 if (overlays == null) { 4901 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4902 return; 4903 } 4904 for (PackageParser.Package opkg : overlays.values()) { 4905 // Not much to do if idmap fails: we already logged the error 4906 // and we certainly don't want to abort installation of pkg simply 4907 // because an overlay didn't fit properly. For these reasons, 4908 // ignore the return value of createIdmapForPackagePairLI. 4909 createIdmapForPackagePairLI(pkg, opkg); 4910 } 4911 } 4912 4913 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4914 PackageParser.Package opkg) { 4915 if (!opkg.mTrustedOverlay) { 4916 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4917 opkg.baseCodePath + ": overlay not trusted"); 4918 return false; 4919 } 4920 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4921 if (overlaySet == null) { 4922 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4923 opkg.baseCodePath + " but target package has no known overlays"); 4924 return false; 4925 } 4926 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4927 // TODO: generate idmap for split APKs 4928 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4929 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4930 + opkg.baseCodePath); 4931 return false; 4932 } 4933 PackageParser.Package[] overlayArray = 4934 overlaySet.values().toArray(new PackageParser.Package[0]); 4935 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4936 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4937 return p1.mOverlayPriority - p2.mOverlayPriority; 4938 } 4939 }; 4940 Arrays.sort(overlayArray, cmp); 4941 4942 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4943 int i = 0; 4944 for (PackageParser.Package p : overlayArray) { 4945 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4946 } 4947 return true; 4948 } 4949 4950 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4951 final File[] files = dir.listFiles(); 4952 if (ArrayUtils.isEmpty(files)) { 4953 Log.d(TAG, "No files in app dir " + dir); 4954 return; 4955 } 4956 4957 if (DEBUG_PACKAGE_SCANNING) { 4958 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4959 + " flags=0x" + Integer.toHexString(parseFlags)); 4960 } 4961 4962 for (File file : files) { 4963 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4964 && !PackageInstallerService.isStageName(file.getName()); 4965 if (!isPackage) { 4966 // Ignore entries which are not packages 4967 continue; 4968 } 4969 try { 4970 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4971 scanFlags, currentTime, null); 4972 } catch (PackageManagerException e) { 4973 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4974 4975 // Delete invalid userdata apps 4976 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4977 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4978 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4979 if (file.isDirectory()) { 4980 mInstaller.rmPackageDir(file.getAbsolutePath()); 4981 } else { 4982 file.delete(); 4983 } 4984 } 4985 } 4986 } 4987 } 4988 4989 private static File getSettingsProblemFile() { 4990 File dataDir = Environment.getDataDirectory(); 4991 File systemDir = new File(dataDir, "system"); 4992 File fname = new File(systemDir, "uiderrors.txt"); 4993 return fname; 4994 } 4995 4996 static void reportSettingsProblem(int priority, String msg) { 4997 logCriticalInfo(priority, msg); 4998 } 4999 5000 static void logCriticalInfo(int priority, String msg) { 5001 Slog.println(priority, TAG, msg); 5002 EventLogTags.writePmCriticalInfo(msg); 5003 try { 5004 File fname = getSettingsProblemFile(); 5005 FileOutputStream out = new FileOutputStream(fname, true); 5006 PrintWriter pw = new FastPrintWriter(out); 5007 SimpleDateFormat formatter = new SimpleDateFormat(); 5008 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5009 pw.println(dateString + ": " + msg); 5010 pw.close(); 5011 FileUtils.setPermissions( 5012 fname.toString(), 5013 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5014 -1, -1); 5015 } catch (java.io.IOException e) { 5016 } 5017 } 5018 5019 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5020 PackageParser.Package pkg, File srcFile, int parseFlags) 5021 throws PackageManagerException { 5022 if (ps != null 5023 && ps.codePath.equals(srcFile) 5024 && ps.timeStamp == srcFile.lastModified() 5025 && !isCompatSignatureUpdateNeeded(pkg) 5026 && !isRecoverSignatureUpdateNeeded(pkg)) { 5027 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5028 if (ps.signatures.mSignatures != null 5029 && ps.signatures.mSignatures.length != 0 5030 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5031 // Optimization: reuse the existing cached certificates 5032 // if the package appears to be unchanged. 5033 pkg.mSignatures = ps.signatures.mSignatures; 5034 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5035 synchronized (mPackages) { 5036 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5037 } 5038 return; 5039 } 5040 5041 Slog.w(TAG, "PackageSetting for " + ps.name 5042 + " is missing signatures. Collecting certs again to recover them."); 5043 } else { 5044 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5045 } 5046 5047 try { 5048 pp.collectCertificates(pkg, parseFlags); 5049 pp.collectManifestDigest(pkg); 5050 } catch (PackageParserException e) { 5051 throw PackageManagerException.from(e); 5052 } 5053 } 5054 5055 /* 5056 * Scan a package and return the newly parsed package. 5057 * Returns null in case of errors and the error code is stored in mLastScanError 5058 */ 5059 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5060 long currentTime, UserHandle user) throws PackageManagerException { 5061 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5062 parseFlags |= mDefParseFlags; 5063 PackageParser pp = new PackageParser(); 5064 pp.setSeparateProcesses(mSeparateProcesses); 5065 pp.setOnlyCoreApps(mOnlyCore); 5066 pp.setDisplayMetrics(mMetrics); 5067 5068 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5069 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5070 } 5071 5072 final PackageParser.Package pkg; 5073 try { 5074 pkg = pp.parsePackage(scanFile, parseFlags); 5075 } catch (PackageParserException e) { 5076 throw PackageManagerException.from(e); 5077 } 5078 5079 PackageSetting ps = null; 5080 PackageSetting updatedPkg; 5081 // reader 5082 synchronized (mPackages) { 5083 // Look to see if we already know about this package. 5084 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5085 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5086 // This package has been renamed to its original name. Let's 5087 // use that. 5088 ps = mSettings.peekPackageLPr(oldName); 5089 } 5090 // If there was no original package, see one for the real package name. 5091 if (ps == null) { 5092 ps = mSettings.peekPackageLPr(pkg.packageName); 5093 } 5094 // Check to see if this package could be hiding/updating a system 5095 // package. Must look for it either under the original or real 5096 // package name depending on our state. 5097 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5098 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5099 } 5100 boolean updatedPkgBetter = false; 5101 // First check if this is a system package that may involve an update 5102 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5103 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5104 // it needs to drop FLAG_PRIVILEGED. 5105 if (locationIsPrivileged(scanFile)) { 5106 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5107 } else { 5108 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5109 } 5110 5111 if (ps != null && !ps.codePath.equals(scanFile)) { 5112 // The path has changed from what was last scanned... check the 5113 // version of the new path against what we have stored to determine 5114 // what to do. 5115 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5116 if (pkg.mVersionCode <= ps.versionCode) { 5117 // The system package has been updated and the code path does not match 5118 // Ignore entry. Skip it. 5119 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5120 + " ignored: updated version " + ps.versionCode 5121 + " better than this " + pkg.mVersionCode); 5122 if (!updatedPkg.codePath.equals(scanFile)) { 5123 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5124 + ps.name + " changing from " + updatedPkg.codePathString 5125 + " to " + scanFile); 5126 updatedPkg.codePath = scanFile; 5127 updatedPkg.codePathString = scanFile.toString(); 5128 updatedPkg.resourcePath = scanFile; 5129 updatedPkg.resourcePathString = scanFile.toString(); 5130 } 5131 updatedPkg.pkg = pkg; 5132 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5133 } else { 5134 // The current app on the system partition is better than 5135 // what we have updated to on the data partition; switch 5136 // back to the system partition version. 5137 // At this point, its safely assumed that package installation for 5138 // apps in system partition will go through. If not there won't be a working 5139 // version of the app 5140 // writer 5141 synchronized (mPackages) { 5142 // Just remove the loaded entries from package lists. 5143 mPackages.remove(ps.name); 5144 } 5145 5146 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5147 + " reverting from " + ps.codePathString 5148 + ": new version " + pkg.mVersionCode 5149 + " better than installed " + ps.versionCode); 5150 5151 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5152 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5153 synchronized (mInstallLock) { 5154 args.cleanUpResourcesLI(); 5155 } 5156 synchronized (mPackages) { 5157 mSettings.enableSystemPackageLPw(ps.name); 5158 } 5159 updatedPkgBetter = true; 5160 } 5161 } 5162 } 5163 5164 if (updatedPkg != null) { 5165 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5166 // initially 5167 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5168 5169 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5170 // flag set initially 5171 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5172 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5173 } 5174 } 5175 5176 // Verify certificates against what was last scanned 5177 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5178 5179 /* 5180 * A new system app appeared, but we already had a non-system one of the 5181 * same name installed earlier. 5182 */ 5183 boolean shouldHideSystemApp = false; 5184 if (updatedPkg == null && ps != null 5185 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5186 /* 5187 * Check to make sure the signatures match first. If they don't, 5188 * wipe the installed application and its data. 5189 */ 5190 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5191 != PackageManager.SIGNATURE_MATCH) { 5192 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5193 + " signatures don't match existing userdata copy; removing"); 5194 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5195 ps = null; 5196 } else { 5197 /* 5198 * If the newly-added system app is an older version than the 5199 * already installed version, hide it. It will be scanned later 5200 * and re-added like an update. 5201 */ 5202 if (pkg.mVersionCode <= ps.versionCode) { 5203 shouldHideSystemApp = true; 5204 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5205 + " but new version " + pkg.mVersionCode + " better than installed " 5206 + ps.versionCode + "; hiding system"); 5207 } else { 5208 /* 5209 * The newly found system app is a newer version that the 5210 * one previously installed. Simply remove the 5211 * already-installed application and replace it with our own 5212 * while keeping the application data. 5213 */ 5214 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5215 + " reverting from " + ps.codePathString + ": new version " 5216 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5217 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5218 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5219 synchronized (mInstallLock) { 5220 args.cleanUpResourcesLI(); 5221 } 5222 } 5223 } 5224 } 5225 5226 // The apk is forward locked (not public) if its code and resources 5227 // are kept in different files. (except for app in either system or 5228 // vendor path). 5229 // TODO grab this value from PackageSettings 5230 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5231 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5232 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5233 } 5234 } 5235 5236 // TODO: extend to support forward-locked splits 5237 String resourcePath = null; 5238 String baseResourcePath = null; 5239 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5240 if (ps != null && ps.resourcePathString != null) { 5241 resourcePath = ps.resourcePathString; 5242 baseResourcePath = ps.resourcePathString; 5243 } else { 5244 // Should not happen at all. Just log an error. 5245 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5246 } 5247 } else { 5248 resourcePath = pkg.codePath; 5249 baseResourcePath = pkg.baseCodePath; 5250 } 5251 5252 // Set application objects path explicitly. 5253 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5254 pkg.applicationInfo.setCodePath(pkg.codePath); 5255 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5256 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5257 pkg.applicationInfo.setResourcePath(resourcePath); 5258 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5259 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5260 5261 // Note that we invoke the following method only if we are about to unpack an application 5262 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5263 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5264 5265 /* 5266 * If the system app should be overridden by a previously installed 5267 * data, hide the system app now and let the /data/app scan pick it up 5268 * again. 5269 */ 5270 if (shouldHideSystemApp) { 5271 synchronized (mPackages) { 5272 /* 5273 * We have to grant systems permissions before we hide, because 5274 * grantPermissions will assume the package update is trying to 5275 * expand its permissions. 5276 */ 5277 grantPermissionsLPw(pkg, true, pkg.packageName); 5278 mSettings.disableSystemPackageLPw(pkg.packageName); 5279 } 5280 } 5281 5282 return scannedPkg; 5283 } 5284 5285 private static String fixProcessName(String defProcessName, 5286 String processName, int uid) { 5287 if (processName == null) { 5288 return defProcessName; 5289 } 5290 return processName; 5291 } 5292 5293 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5294 throws PackageManagerException { 5295 if (pkgSetting.signatures.mSignatures != null) { 5296 // Already existing package. Make sure signatures match 5297 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5298 == PackageManager.SIGNATURE_MATCH; 5299 if (!match) { 5300 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5301 == PackageManager.SIGNATURE_MATCH; 5302 } 5303 if (!match) { 5304 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5305 == PackageManager.SIGNATURE_MATCH; 5306 } 5307 if (!match) { 5308 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5309 + pkg.packageName + " signatures do not match the " 5310 + "previously installed version; ignoring!"); 5311 } 5312 } 5313 5314 // Check for shared user signatures 5315 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5316 // Already existing package. Make sure signatures match 5317 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5318 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5319 if (!match) { 5320 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5321 == PackageManager.SIGNATURE_MATCH; 5322 } 5323 if (!match) { 5324 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5325 == PackageManager.SIGNATURE_MATCH; 5326 } 5327 if (!match) { 5328 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5329 "Package " + pkg.packageName 5330 + " has no signatures that match those in shared user " 5331 + pkgSetting.sharedUser.name + "; ignoring!"); 5332 } 5333 } 5334 } 5335 5336 /** 5337 * Enforces that only the system UID or root's UID can call a method exposed 5338 * via Binder. 5339 * 5340 * @param message used as message if SecurityException is thrown 5341 * @throws SecurityException if the caller is not system or root 5342 */ 5343 private static final void enforceSystemOrRoot(String message) { 5344 final int uid = Binder.getCallingUid(); 5345 if (uid != Process.SYSTEM_UID && uid != 0) { 5346 throw new SecurityException(message); 5347 } 5348 } 5349 5350 @Override 5351 public void performBootDexOpt() { 5352 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5353 5354 // Before everything else, see whether we need to fstrim. 5355 try { 5356 IMountService ms = PackageHelper.getMountService(); 5357 if (ms != null) { 5358 final boolean isUpgrade = isUpgrade(); 5359 boolean doTrim = isUpgrade; 5360 if (doTrim) { 5361 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5362 } else { 5363 final long interval = android.provider.Settings.Global.getLong( 5364 mContext.getContentResolver(), 5365 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5366 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5367 if (interval > 0) { 5368 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5369 if (timeSinceLast > interval) { 5370 doTrim = true; 5371 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5372 + "; running immediately"); 5373 } 5374 } 5375 } 5376 if (doTrim) { 5377 if (!isFirstBoot()) { 5378 try { 5379 ActivityManagerNative.getDefault().showBootMessage( 5380 mContext.getResources().getString( 5381 R.string.android_upgrading_fstrim), true); 5382 } catch (RemoteException e) { 5383 } 5384 } 5385 ms.runMaintenance(); 5386 } 5387 } else { 5388 Slog.e(TAG, "Mount service unavailable!"); 5389 } 5390 } catch (RemoteException e) { 5391 // Can't happen; MountService is local 5392 } 5393 5394 final ArraySet<PackageParser.Package> pkgs; 5395 synchronized (mPackages) { 5396 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5397 } 5398 5399 if (pkgs != null) { 5400 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5401 // in case the device runs out of space. 5402 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5403 // Give priority to core apps. 5404 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5405 PackageParser.Package pkg = it.next(); 5406 if (pkg.coreApp) { 5407 if (DEBUG_DEXOPT) { 5408 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5409 } 5410 sortedPkgs.add(pkg); 5411 it.remove(); 5412 } 5413 } 5414 // Give priority to system apps that listen for pre boot complete. 5415 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5416 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5417 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5418 PackageParser.Package pkg = it.next(); 5419 if (pkgNames.contains(pkg.packageName)) { 5420 if (DEBUG_DEXOPT) { 5421 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5422 } 5423 sortedPkgs.add(pkg); 5424 it.remove(); 5425 } 5426 } 5427 // Give priority to system apps. 5428 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5429 PackageParser.Package pkg = it.next(); 5430 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5431 if (DEBUG_DEXOPT) { 5432 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5433 } 5434 sortedPkgs.add(pkg); 5435 it.remove(); 5436 } 5437 } 5438 // Give priority to updated system apps. 5439 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5440 PackageParser.Package pkg = it.next(); 5441 if (pkg.isUpdatedSystemApp()) { 5442 if (DEBUG_DEXOPT) { 5443 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5444 } 5445 sortedPkgs.add(pkg); 5446 it.remove(); 5447 } 5448 } 5449 // Give priority to apps that listen for boot complete. 5450 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5451 pkgNames = getPackageNamesForIntent(intent); 5452 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5453 PackageParser.Package pkg = it.next(); 5454 if (pkgNames.contains(pkg.packageName)) { 5455 if (DEBUG_DEXOPT) { 5456 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5457 } 5458 sortedPkgs.add(pkg); 5459 it.remove(); 5460 } 5461 } 5462 // Filter out packages that aren't recently used. 5463 filterRecentlyUsedApps(pkgs); 5464 // Add all remaining apps. 5465 for (PackageParser.Package pkg : pkgs) { 5466 if (DEBUG_DEXOPT) { 5467 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5468 } 5469 sortedPkgs.add(pkg); 5470 } 5471 5472 // If we want to be lazy, filter everything that wasn't recently used. 5473 if (mLazyDexOpt) { 5474 filterRecentlyUsedApps(sortedPkgs); 5475 } 5476 5477 int i = 0; 5478 int total = sortedPkgs.size(); 5479 File dataDir = Environment.getDataDirectory(); 5480 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5481 if (lowThreshold == 0) { 5482 throw new IllegalStateException("Invalid low memory threshold"); 5483 } 5484 for (PackageParser.Package pkg : sortedPkgs) { 5485 long usableSpace = dataDir.getUsableSpace(); 5486 if (usableSpace < lowThreshold) { 5487 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5488 break; 5489 } 5490 performBootDexOpt(pkg, ++i, total); 5491 } 5492 } 5493 } 5494 5495 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5496 // Filter out packages that aren't recently used. 5497 // 5498 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5499 // should do a full dexopt. 5500 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5501 int total = pkgs.size(); 5502 int skipped = 0; 5503 long now = System.currentTimeMillis(); 5504 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5505 PackageParser.Package pkg = i.next(); 5506 long then = pkg.mLastPackageUsageTimeInMills; 5507 if (then + mDexOptLRUThresholdInMills < now) { 5508 if (DEBUG_DEXOPT) { 5509 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5510 ((then == 0) ? "never" : new Date(then))); 5511 } 5512 i.remove(); 5513 skipped++; 5514 } 5515 } 5516 if (DEBUG_DEXOPT) { 5517 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5518 } 5519 } 5520 } 5521 5522 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5523 List<ResolveInfo> ris = null; 5524 try { 5525 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5526 intent, null, 0, UserHandle.USER_OWNER); 5527 } catch (RemoteException e) { 5528 } 5529 ArraySet<String> pkgNames = new ArraySet<String>(); 5530 if (ris != null) { 5531 for (ResolveInfo ri : ris) { 5532 pkgNames.add(ri.activityInfo.packageName); 5533 } 5534 } 5535 return pkgNames; 5536 } 5537 5538 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5539 if (DEBUG_DEXOPT) { 5540 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5541 } 5542 if (!isFirstBoot()) { 5543 try { 5544 ActivityManagerNative.getDefault().showBootMessage( 5545 mContext.getResources().getString(R.string.android_upgrading_apk, 5546 curr, total), true); 5547 } catch (RemoteException e) { 5548 } 5549 } 5550 PackageParser.Package p = pkg; 5551 synchronized (mInstallLock) { 5552 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5553 false /* force dex */, false /* defer */, true /* include dependencies */); 5554 } 5555 } 5556 5557 @Override 5558 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5559 return performDexOpt(packageName, instructionSet, false); 5560 } 5561 5562 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5563 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5564 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5565 if (!dexopt && !updateUsage) { 5566 // We aren't going to dexopt or update usage, so bail early. 5567 return false; 5568 } 5569 PackageParser.Package p; 5570 final String targetInstructionSet; 5571 synchronized (mPackages) { 5572 p = mPackages.get(packageName); 5573 if (p == null) { 5574 return false; 5575 } 5576 if (updateUsage) { 5577 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5578 } 5579 mPackageUsage.write(false); 5580 if (!dexopt) { 5581 // We aren't going to dexopt, so bail early. 5582 return false; 5583 } 5584 5585 targetInstructionSet = instructionSet != null ? instructionSet : 5586 getPrimaryInstructionSet(p.applicationInfo); 5587 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5588 return false; 5589 } 5590 } 5591 5592 synchronized (mInstallLock) { 5593 final String[] instructionSets = new String[] { targetInstructionSet }; 5594 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5595 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5596 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5597 } 5598 } 5599 5600 public ArraySet<String> getPackagesThatNeedDexOpt() { 5601 ArraySet<String> pkgs = null; 5602 synchronized (mPackages) { 5603 for (PackageParser.Package p : mPackages.values()) { 5604 if (DEBUG_DEXOPT) { 5605 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5606 } 5607 if (!p.mDexOptPerformed.isEmpty()) { 5608 continue; 5609 } 5610 if (pkgs == null) { 5611 pkgs = new ArraySet<String>(); 5612 } 5613 pkgs.add(p.packageName); 5614 } 5615 } 5616 return pkgs; 5617 } 5618 5619 public void shutdown() { 5620 mPackageUsage.write(true); 5621 } 5622 5623 @Override 5624 public void forceDexOpt(String packageName) { 5625 enforceSystemOrRoot("forceDexOpt"); 5626 5627 PackageParser.Package pkg; 5628 synchronized (mPackages) { 5629 pkg = mPackages.get(packageName); 5630 if (pkg == null) { 5631 throw new IllegalArgumentException("Missing package: " + packageName); 5632 } 5633 } 5634 5635 synchronized (mInstallLock) { 5636 final String[] instructionSets = new String[] { 5637 getPrimaryInstructionSet(pkg.applicationInfo) }; 5638 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5639 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5640 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5641 throw new IllegalStateException("Failed to dexopt: " + res); 5642 } 5643 } 5644 } 5645 5646 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5647 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5648 Slog.w(TAG, "Unable to update from " + oldPkg.name 5649 + " to " + newPkg.packageName 5650 + ": old package not in system partition"); 5651 return false; 5652 } else if (mPackages.get(oldPkg.name) != null) { 5653 Slog.w(TAG, "Unable to update from " + oldPkg.name 5654 + " to " + newPkg.packageName 5655 + ": old package still exists"); 5656 return false; 5657 } 5658 return true; 5659 } 5660 5661 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5662 int[] users = sUserManager.getUserIds(); 5663 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5664 if (res < 0) { 5665 return res; 5666 } 5667 for (int user : users) { 5668 if (user != 0) { 5669 res = mInstaller.createUserData(volumeUuid, packageName, 5670 UserHandle.getUid(user, uid), user, seinfo); 5671 if (res < 0) { 5672 return res; 5673 } 5674 } 5675 } 5676 return res; 5677 } 5678 5679 private int removeDataDirsLI(String volumeUuid, String packageName) { 5680 int[] users = sUserManager.getUserIds(); 5681 int res = 0; 5682 for (int user : users) { 5683 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5684 if (resInner < 0) { 5685 res = resInner; 5686 } 5687 } 5688 5689 return res; 5690 } 5691 5692 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5693 int[] users = sUserManager.getUserIds(); 5694 int res = 0; 5695 for (int user : users) { 5696 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5697 if (resInner < 0) { 5698 res = resInner; 5699 } 5700 } 5701 return res; 5702 } 5703 5704 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5705 PackageParser.Package changingLib) { 5706 if (file.path != null) { 5707 usesLibraryFiles.add(file.path); 5708 return; 5709 } 5710 PackageParser.Package p = mPackages.get(file.apk); 5711 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5712 // If we are doing this while in the middle of updating a library apk, 5713 // then we need to make sure to use that new apk for determining the 5714 // dependencies here. (We haven't yet finished committing the new apk 5715 // to the package manager state.) 5716 if (p == null || p.packageName.equals(changingLib.packageName)) { 5717 p = changingLib; 5718 } 5719 } 5720 if (p != null) { 5721 usesLibraryFiles.addAll(p.getAllCodePaths()); 5722 } 5723 } 5724 5725 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5726 PackageParser.Package changingLib) throws PackageManagerException { 5727 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5728 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5729 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5730 for (int i=0; i<N; i++) { 5731 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5732 if (file == null) { 5733 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5734 "Package " + pkg.packageName + " requires unavailable shared library " 5735 + pkg.usesLibraries.get(i) + "; failing!"); 5736 } 5737 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5738 } 5739 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5740 for (int i=0; i<N; i++) { 5741 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5742 if (file == null) { 5743 Slog.w(TAG, "Package " + pkg.packageName 5744 + " desires unavailable shared library " 5745 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5746 } else { 5747 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5748 } 5749 } 5750 N = usesLibraryFiles.size(); 5751 if (N > 0) { 5752 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5753 } else { 5754 pkg.usesLibraryFiles = null; 5755 } 5756 } 5757 } 5758 5759 private static boolean hasString(List<String> list, List<String> which) { 5760 if (list == null) { 5761 return false; 5762 } 5763 for (int i=list.size()-1; i>=0; i--) { 5764 for (int j=which.size()-1; j>=0; j--) { 5765 if (which.get(j).equals(list.get(i))) { 5766 return true; 5767 } 5768 } 5769 } 5770 return false; 5771 } 5772 5773 private void updateAllSharedLibrariesLPw() { 5774 for (PackageParser.Package pkg : mPackages.values()) { 5775 try { 5776 updateSharedLibrariesLPw(pkg, null); 5777 } catch (PackageManagerException e) { 5778 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5779 } 5780 } 5781 } 5782 5783 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5784 PackageParser.Package changingPkg) { 5785 ArrayList<PackageParser.Package> res = null; 5786 for (PackageParser.Package pkg : mPackages.values()) { 5787 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5788 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5789 if (res == null) { 5790 res = new ArrayList<PackageParser.Package>(); 5791 } 5792 res.add(pkg); 5793 try { 5794 updateSharedLibrariesLPw(pkg, changingPkg); 5795 } catch (PackageManagerException e) { 5796 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5797 } 5798 } 5799 } 5800 return res; 5801 } 5802 5803 /** 5804 * Derive the value of the {@code cpuAbiOverride} based on the provided 5805 * value and an optional stored value from the package settings. 5806 */ 5807 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5808 String cpuAbiOverride = null; 5809 5810 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5811 cpuAbiOverride = null; 5812 } else if (abiOverride != null) { 5813 cpuAbiOverride = abiOverride; 5814 } else if (settings != null) { 5815 cpuAbiOverride = settings.cpuAbiOverrideString; 5816 } 5817 5818 return cpuAbiOverride; 5819 } 5820 5821 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5822 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5823 boolean success = false; 5824 try { 5825 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5826 currentTime, user); 5827 success = true; 5828 return res; 5829 } finally { 5830 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5831 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5832 } 5833 } 5834 } 5835 5836 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5837 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5838 final File scanFile = new File(pkg.codePath); 5839 if (pkg.applicationInfo.getCodePath() == null || 5840 pkg.applicationInfo.getResourcePath() == null) { 5841 // Bail out. The resource and code paths haven't been set. 5842 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5843 "Code and resource paths haven't been set correctly"); 5844 } 5845 5846 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5847 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5848 } else { 5849 // Only allow system apps to be flagged as core apps. 5850 pkg.coreApp = false; 5851 } 5852 5853 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5854 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5855 } 5856 5857 if (mCustomResolverComponentName != null && 5858 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5859 setUpCustomResolverActivity(pkg); 5860 } 5861 5862 if (pkg.packageName.equals("android")) { 5863 synchronized (mPackages) { 5864 if (mAndroidApplication != null) { 5865 Slog.w(TAG, "*************************************************"); 5866 Slog.w(TAG, "Core android package being redefined. Skipping."); 5867 Slog.w(TAG, " file=" + scanFile); 5868 Slog.w(TAG, "*************************************************"); 5869 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5870 "Core android package being redefined. Skipping."); 5871 } 5872 5873 // Set up information for our fall-back user intent resolution activity. 5874 mPlatformPackage = pkg; 5875 pkg.mVersionCode = mSdkVersion; 5876 mAndroidApplication = pkg.applicationInfo; 5877 5878 if (!mResolverReplaced) { 5879 mResolveActivity.applicationInfo = mAndroidApplication; 5880 mResolveActivity.name = ResolverActivity.class.getName(); 5881 mResolveActivity.packageName = mAndroidApplication.packageName; 5882 mResolveActivity.processName = "system:ui"; 5883 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5884 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5885 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5886 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5887 mResolveActivity.exported = true; 5888 mResolveActivity.enabled = true; 5889 mResolveInfo.activityInfo = mResolveActivity; 5890 mResolveInfo.priority = 0; 5891 mResolveInfo.preferredOrder = 0; 5892 mResolveInfo.match = 0; 5893 mResolveComponentName = new ComponentName( 5894 mAndroidApplication.packageName, mResolveActivity.name); 5895 } 5896 } 5897 } 5898 5899 if (DEBUG_PACKAGE_SCANNING) { 5900 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5901 Log.d(TAG, "Scanning package " + pkg.packageName); 5902 } 5903 5904 if (mPackages.containsKey(pkg.packageName) 5905 || mSharedLibraries.containsKey(pkg.packageName)) { 5906 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5907 "Application package " + pkg.packageName 5908 + " already installed. Skipping duplicate."); 5909 } 5910 5911 // If we're only installing presumed-existing packages, require that the 5912 // scanned APK is both already known and at the path previously established 5913 // for it. Previously unknown packages we pick up normally, but if we have an 5914 // a priori expectation about this package's install presence, enforce it. 5915 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5916 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5917 if (known != null) { 5918 if (DEBUG_PACKAGE_SCANNING) { 5919 Log.d(TAG, "Examining " + pkg.codePath 5920 + " and requiring known paths " + known.codePathString 5921 + " & " + known.resourcePathString); 5922 } 5923 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5924 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5925 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5926 "Application package " + pkg.packageName 5927 + " found at " + pkg.applicationInfo.getCodePath() 5928 + " but expected at " + known.codePathString + "; ignoring."); 5929 } 5930 } 5931 } 5932 5933 // Initialize package source and resource directories 5934 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5935 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5936 5937 SharedUserSetting suid = null; 5938 PackageSetting pkgSetting = null; 5939 5940 if (!isSystemApp(pkg)) { 5941 // Only system apps can use these features. 5942 pkg.mOriginalPackages = null; 5943 pkg.mRealPackage = null; 5944 pkg.mAdoptPermissions = null; 5945 } 5946 5947 // writer 5948 synchronized (mPackages) { 5949 if (pkg.mSharedUserId != null) { 5950 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5951 if (suid == null) { 5952 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5953 "Creating application package " + pkg.packageName 5954 + " for shared user failed"); 5955 } 5956 if (DEBUG_PACKAGE_SCANNING) { 5957 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5958 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5959 + "): packages=" + suid.packages); 5960 } 5961 } 5962 5963 // Check if we are renaming from an original package name. 5964 PackageSetting origPackage = null; 5965 String realName = null; 5966 if (pkg.mOriginalPackages != null) { 5967 // This package may need to be renamed to a previously 5968 // installed name. Let's check on that... 5969 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5970 if (pkg.mOriginalPackages.contains(renamed)) { 5971 // This package had originally been installed as the 5972 // original name, and we have already taken care of 5973 // transitioning to the new one. Just update the new 5974 // one to continue using the old name. 5975 realName = pkg.mRealPackage; 5976 if (!pkg.packageName.equals(renamed)) { 5977 // Callers into this function may have already taken 5978 // care of renaming the package; only do it here if 5979 // it is not already done. 5980 pkg.setPackageName(renamed); 5981 } 5982 5983 } else { 5984 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5985 if ((origPackage = mSettings.peekPackageLPr( 5986 pkg.mOriginalPackages.get(i))) != null) { 5987 // We do have the package already installed under its 5988 // original name... should we use it? 5989 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5990 // New package is not compatible with original. 5991 origPackage = null; 5992 continue; 5993 } else if (origPackage.sharedUser != null) { 5994 // Make sure uid is compatible between packages. 5995 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5996 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5997 + " to " + pkg.packageName + ": old uid " 5998 + origPackage.sharedUser.name 5999 + " differs from " + pkg.mSharedUserId); 6000 origPackage = null; 6001 continue; 6002 } 6003 } else { 6004 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6005 + pkg.packageName + " to old name " + origPackage.name); 6006 } 6007 break; 6008 } 6009 } 6010 } 6011 } 6012 6013 if (mTransferedPackages.contains(pkg.packageName)) { 6014 Slog.w(TAG, "Package " + pkg.packageName 6015 + " was transferred to another, but its .apk remains"); 6016 } 6017 6018 // Just create the setting, don't add it yet. For already existing packages 6019 // the PkgSetting exists already and doesn't have to be created. 6020 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6021 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6022 pkg.applicationInfo.primaryCpuAbi, 6023 pkg.applicationInfo.secondaryCpuAbi, 6024 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6025 user, false); 6026 if (pkgSetting == null) { 6027 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6028 "Creating application package " + pkg.packageName + " failed"); 6029 } 6030 6031 if (pkgSetting.origPackage != null) { 6032 // If we are first transitioning from an original package, 6033 // fix up the new package's name now. We need to do this after 6034 // looking up the package under its new name, so getPackageLP 6035 // can take care of fiddling things correctly. 6036 pkg.setPackageName(origPackage.name); 6037 6038 // File a report about this. 6039 String msg = "New package " + pkgSetting.realName 6040 + " renamed to replace old package " + pkgSetting.name; 6041 reportSettingsProblem(Log.WARN, msg); 6042 6043 // Make a note of it. 6044 mTransferedPackages.add(origPackage.name); 6045 6046 // No longer need to retain this. 6047 pkgSetting.origPackage = null; 6048 } 6049 6050 if (realName != null) { 6051 // Make a note of it. 6052 mTransferedPackages.add(pkg.packageName); 6053 } 6054 6055 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6056 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6057 } 6058 6059 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6060 // Check all shared libraries and map to their actual file path. 6061 // We only do this here for apps not on a system dir, because those 6062 // are the only ones that can fail an install due to this. We 6063 // will take care of the system apps by updating all of their 6064 // library paths after the scan is done. 6065 updateSharedLibrariesLPw(pkg, null); 6066 } 6067 6068 if (mFoundPolicyFile) { 6069 SELinuxMMAC.assignSeinfoValue(pkg); 6070 } 6071 6072 pkg.applicationInfo.uid = pkgSetting.appId; 6073 pkg.mExtras = pkgSetting; 6074 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6075 try { 6076 verifySignaturesLP(pkgSetting, pkg); 6077 // We just determined the app is signed correctly, so bring 6078 // over the latest parsed certs. 6079 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6080 } catch (PackageManagerException e) { 6081 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6082 throw e; 6083 } 6084 // The signature has changed, but this package is in the system 6085 // image... let's recover! 6086 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6087 // However... if this package is part of a shared user, but it 6088 // doesn't match the signature of the shared user, let's fail. 6089 // What this means is that you can't change the signatures 6090 // associated with an overall shared user, which doesn't seem all 6091 // that unreasonable. 6092 if (pkgSetting.sharedUser != null) { 6093 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6094 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6095 throw new PackageManagerException( 6096 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6097 "Signature mismatch for shared user : " 6098 + pkgSetting.sharedUser); 6099 } 6100 } 6101 // File a report about this. 6102 String msg = "System package " + pkg.packageName 6103 + " signature changed; retaining data."; 6104 reportSettingsProblem(Log.WARN, msg); 6105 } 6106 } else { 6107 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6108 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6109 + pkg.packageName + " upgrade keys do not match the " 6110 + "previously installed version"); 6111 } else { 6112 // We just determined the app is signed correctly, so bring 6113 // over the latest parsed certs. 6114 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6115 } 6116 } 6117 // Verify that this new package doesn't have any content providers 6118 // that conflict with existing packages. Only do this if the 6119 // package isn't already installed, since we don't want to break 6120 // things that are installed. 6121 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6122 final int N = pkg.providers.size(); 6123 int i; 6124 for (i=0; i<N; i++) { 6125 PackageParser.Provider p = pkg.providers.get(i); 6126 if (p.info.authority != null) { 6127 String names[] = p.info.authority.split(";"); 6128 for (int j = 0; j < names.length; j++) { 6129 if (mProvidersByAuthority.containsKey(names[j])) { 6130 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6131 final String otherPackageName = 6132 ((other != null && other.getComponentName() != null) ? 6133 other.getComponentName().getPackageName() : "?"); 6134 throw new PackageManagerException( 6135 INSTALL_FAILED_CONFLICTING_PROVIDER, 6136 "Can't install because provider name " + names[j] 6137 + " (in package " + pkg.applicationInfo.packageName 6138 + ") is already used by " + otherPackageName); 6139 } 6140 } 6141 } 6142 } 6143 } 6144 6145 if (pkg.mAdoptPermissions != null) { 6146 // This package wants to adopt ownership of permissions from 6147 // another package. 6148 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6149 final String origName = pkg.mAdoptPermissions.get(i); 6150 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6151 if (orig != null) { 6152 if (verifyPackageUpdateLPr(orig, pkg)) { 6153 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6154 + pkg.packageName); 6155 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6156 } 6157 } 6158 } 6159 } 6160 } 6161 6162 final String pkgName = pkg.packageName; 6163 6164 final long scanFileTime = scanFile.lastModified(); 6165 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6166 pkg.applicationInfo.processName = fixProcessName( 6167 pkg.applicationInfo.packageName, 6168 pkg.applicationInfo.processName, 6169 pkg.applicationInfo.uid); 6170 6171 File dataPath; 6172 if (mPlatformPackage == pkg) { 6173 // The system package is special. 6174 dataPath = new File(Environment.getDataDirectory(), "system"); 6175 6176 pkg.applicationInfo.dataDir = dataPath.getPath(); 6177 6178 } else { 6179 // This is a normal package, need to make its data directory. 6180 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6181 UserHandle.USER_OWNER); 6182 6183 boolean uidError = false; 6184 if (dataPath.exists()) { 6185 int currentUid = 0; 6186 try { 6187 StructStat stat = Os.stat(dataPath.getPath()); 6188 currentUid = stat.st_uid; 6189 } catch (ErrnoException e) { 6190 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6191 } 6192 6193 // If we have mismatched owners for the data path, we have a problem. 6194 if (currentUid != pkg.applicationInfo.uid) { 6195 boolean recovered = false; 6196 if (currentUid == 0) { 6197 // The directory somehow became owned by root. Wow. 6198 // This is probably because the system was stopped while 6199 // installd was in the middle of messing with its libs 6200 // directory. Ask installd to fix that. 6201 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6202 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6203 if (ret >= 0) { 6204 recovered = true; 6205 String msg = "Package " + pkg.packageName 6206 + " unexpectedly changed to uid 0; recovered to " + 6207 + pkg.applicationInfo.uid; 6208 reportSettingsProblem(Log.WARN, msg); 6209 } 6210 } 6211 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6212 || (scanFlags&SCAN_BOOTING) != 0)) { 6213 // If this is a system app, we can at least delete its 6214 // current data so the application will still work. 6215 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6216 if (ret >= 0) { 6217 // TODO: Kill the processes first 6218 // Old data gone! 6219 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6220 ? "System package " : "Third party package "; 6221 String msg = prefix + pkg.packageName 6222 + " has changed from uid: " 6223 + currentUid + " to " 6224 + pkg.applicationInfo.uid + "; old data erased"; 6225 reportSettingsProblem(Log.WARN, msg); 6226 recovered = true; 6227 6228 // And now re-install the app. 6229 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6230 pkg.applicationInfo.seinfo); 6231 if (ret == -1) { 6232 // Ack should not happen! 6233 msg = prefix + pkg.packageName 6234 + " could not have data directory re-created after delete."; 6235 reportSettingsProblem(Log.WARN, msg); 6236 throw new PackageManagerException( 6237 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6238 } 6239 } 6240 if (!recovered) { 6241 mHasSystemUidErrors = true; 6242 } 6243 } else if (!recovered) { 6244 // If we allow this install to proceed, we will be broken. 6245 // Abort, abort! 6246 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6247 "scanPackageLI"); 6248 } 6249 if (!recovered) { 6250 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6251 + pkg.applicationInfo.uid + "/fs_" 6252 + currentUid; 6253 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6254 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6255 String msg = "Package " + pkg.packageName 6256 + " has mismatched uid: " 6257 + currentUid + " on disk, " 6258 + pkg.applicationInfo.uid + " in settings"; 6259 // writer 6260 synchronized (mPackages) { 6261 mSettings.mReadMessages.append(msg); 6262 mSettings.mReadMessages.append('\n'); 6263 uidError = true; 6264 if (!pkgSetting.uidError) { 6265 reportSettingsProblem(Log.ERROR, msg); 6266 } 6267 } 6268 } 6269 } 6270 pkg.applicationInfo.dataDir = dataPath.getPath(); 6271 if (mShouldRestoreconData) { 6272 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6273 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6274 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6275 } 6276 } else { 6277 if (DEBUG_PACKAGE_SCANNING) { 6278 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6279 Log.v(TAG, "Want this data dir: " + dataPath); 6280 } 6281 //invoke installer to do the actual installation 6282 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6283 pkg.applicationInfo.seinfo); 6284 if (ret < 0) { 6285 // Error from installer 6286 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6287 "Unable to create data dirs [errorCode=" + ret + "]"); 6288 } 6289 6290 if (dataPath.exists()) { 6291 pkg.applicationInfo.dataDir = dataPath.getPath(); 6292 } else { 6293 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6294 pkg.applicationInfo.dataDir = null; 6295 } 6296 } 6297 6298 pkgSetting.uidError = uidError; 6299 } 6300 6301 final String path = scanFile.getPath(); 6302 final String codePath = pkg.applicationInfo.getCodePath(); 6303 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6304 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6305 setBundledAppAbisAndRoots(pkg, pkgSetting); 6306 6307 // If we haven't found any native libraries for the app, check if it has 6308 // renderscript code. We'll need to force the app to 32 bit if it has 6309 // renderscript bitcode. 6310 if (pkg.applicationInfo.primaryCpuAbi == null 6311 && pkg.applicationInfo.secondaryCpuAbi == null 6312 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6313 NativeLibraryHelper.Handle handle = null; 6314 try { 6315 handle = NativeLibraryHelper.Handle.create(scanFile); 6316 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6317 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6318 } 6319 } catch (IOException ioe) { 6320 Slog.w(TAG, "Error scanning system app : " + ioe); 6321 } finally { 6322 IoUtils.closeQuietly(handle); 6323 } 6324 } 6325 6326 setNativeLibraryPaths(pkg); 6327 } else { 6328 // TODO: We can probably be smarter about this stuff. For installed apps, 6329 // we can calculate this information at install time once and for all. For 6330 // system apps, we can probably assume that this information doesn't change 6331 // after the first boot scan. As things stand, we do lots of unnecessary work. 6332 6333 // Give ourselves some initial paths; we'll come back for another 6334 // pass once we've determined ABI below. 6335 setNativeLibraryPaths(pkg); 6336 6337 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6338 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6339 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6340 6341 NativeLibraryHelper.Handle handle = null; 6342 try { 6343 handle = NativeLibraryHelper.Handle.create(scanFile); 6344 // TODO(multiArch): This can be null for apps that didn't go through the 6345 // usual installation process. We can calculate it again, like we 6346 // do during install time. 6347 // 6348 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6349 // unnecessary. 6350 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6351 6352 // Null out the abis so that they can be recalculated. 6353 pkg.applicationInfo.primaryCpuAbi = null; 6354 pkg.applicationInfo.secondaryCpuAbi = null; 6355 if (isMultiArch(pkg.applicationInfo)) { 6356 // Warn if we've set an abiOverride for multi-lib packages.. 6357 // By definition, we need to copy both 32 and 64 bit libraries for 6358 // such packages. 6359 if (pkg.cpuAbiOverride != null 6360 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6361 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6362 } 6363 6364 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6365 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6366 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6367 if (isAsec) { 6368 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6369 } else { 6370 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6371 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6372 useIsaSpecificSubdirs); 6373 } 6374 } 6375 6376 maybeThrowExceptionForMultiArchCopy( 6377 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6378 6379 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6380 if (isAsec) { 6381 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6382 } else { 6383 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6384 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6385 useIsaSpecificSubdirs); 6386 } 6387 } 6388 6389 maybeThrowExceptionForMultiArchCopy( 6390 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6391 6392 if (abi64 >= 0) { 6393 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6394 } 6395 6396 if (abi32 >= 0) { 6397 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6398 if (abi64 >= 0) { 6399 pkg.applicationInfo.secondaryCpuAbi = abi; 6400 } else { 6401 pkg.applicationInfo.primaryCpuAbi = abi; 6402 } 6403 } 6404 } else { 6405 String[] abiList = (cpuAbiOverride != null) ? 6406 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6407 6408 // Enable gross and lame hacks for apps that are built with old 6409 // SDK tools. We must scan their APKs for renderscript bitcode and 6410 // not launch them if it's present. Don't bother checking on devices 6411 // that don't have 64 bit support. 6412 boolean needsRenderScriptOverride = false; 6413 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6414 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6415 abiList = Build.SUPPORTED_32_BIT_ABIS; 6416 needsRenderScriptOverride = true; 6417 } 6418 6419 final int copyRet; 6420 if (isAsec) { 6421 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6422 } else { 6423 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6424 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6425 } 6426 6427 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6428 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6429 "Error unpackaging native libs for app, errorCode=" + copyRet); 6430 } 6431 6432 if (copyRet >= 0) { 6433 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6434 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6435 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6436 } else if (needsRenderScriptOverride) { 6437 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6438 } 6439 } 6440 } catch (IOException ioe) { 6441 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6442 } finally { 6443 IoUtils.closeQuietly(handle); 6444 } 6445 6446 // Now that we've calculated the ABIs and determined if it's an internal app, 6447 // we will go ahead and populate the nativeLibraryPath. 6448 setNativeLibraryPaths(pkg); 6449 6450 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6451 final int[] userIds = sUserManager.getUserIds(); 6452 synchronized (mInstallLock) { 6453 // Create a native library symlink only if we have native libraries 6454 // and if the native libraries are 32 bit libraries. We do not provide 6455 // this symlink for 64 bit libraries. 6456 if (pkg.applicationInfo.primaryCpuAbi != null && 6457 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6458 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6459 for (int userId : userIds) { 6460 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6461 nativeLibPath, userId) < 0) { 6462 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6463 "Failed linking native library dir (user=" + userId + ")"); 6464 } 6465 } 6466 } 6467 } 6468 } 6469 6470 // This is a special case for the "system" package, where the ABI is 6471 // dictated by the zygote configuration (and init.rc). We should keep track 6472 // of this ABI so that we can deal with "normal" applications that run under 6473 // the same UID correctly. 6474 if (mPlatformPackage == pkg) { 6475 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6476 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6477 } 6478 6479 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6480 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6481 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6482 // Copy the derived override back to the parsed package, so that we can 6483 // update the package settings accordingly. 6484 pkg.cpuAbiOverride = cpuAbiOverride; 6485 6486 if (DEBUG_ABI_SELECTION) { 6487 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6488 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6489 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6490 } 6491 6492 // Push the derived path down into PackageSettings so we know what to 6493 // clean up at uninstall time. 6494 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6495 6496 if (DEBUG_ABI_SELECTION) { 6497 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6498 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6499 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6500 } 6501 6502 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6503 // We don't do this here during boot because we can do it all 6504 // at once after scanning all existing packages. 6505 // 6506 // We also do this *before* we perform dexopt on this package, so that 6507 // we can avoid redundant dexopts, and also to make sure we've got the 6508 // code and package path correct. 6509 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6510 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6511 } 6512 6513 if ((scanFlags & SCAN_NO_DEX) == 0) { 6514 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6515 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6516 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6517 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6518 } 6519 } 6520 if (mFactoryTest && pkg.requestedPermissions.contains( 6521 android.Manifest.permission.FACTORY_TEST)) { 6522 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6523 } 6524 6525 ArrayList<PackageParser.Package> clientLibPkgs = null; 6526 6527 // writer 6528 synchronized (mPackages) { 6529 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6530 // Only system apps can add new shared libraries. 6531 if (pkg.libraryNames != null) { 6532 for (int i=0; i<pkg.libraryNames.size(); i++) { 6533 String name = pkg.libraryNames.get(i); 6534 boolean allowed = false; 6535 if (pkg.isUpdatedSystemApp()) { 6536 // New library entries can only be added through the 6537 // system image. This is important to get rid of a lot 6538 // of nasty edge cases: for example if we allowed a non- 6539 // system update of the app to add a library, then uninstalling 6540 // the update would make the library go away, and assumptions 6541 // we made such as through app install filtering would now 6542 // have allowed apps on the device which aren't compatible 6543 // with it. Better to just have the restriction here, be 6544 // conservative, and create many fewer cases that can negatively 6545 // impact the user experience. 6546 final PackageSetting sysPs = mSettings 6547 .getDisabledSystemPkgLPr(pkg.packageName); 6548 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6549 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6550 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6551 allowed = true; 6552 allowed = true; 6553 break; 6554 } 6555 } 6556 } 6557 } else { 6558 allowed = true; 6559 } 6560 if (allowed) { 6561 if (!mSharedLibraries.containsKey(name)) { 6562 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6563 } else if (!name.equals(pkg.packageName)) { 6564 Slog.w(TAG, "Package " + pkg.packageName + " library " 6565 + name + " already exists; skipping"); 6566 } 6567 } else { 6568 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6569 + name + " that is not declared on system image; skipping"); 6570 } 6571 } 6572 if ((scanFlags&SCAN_BOOTING) == 0) { 6573 // If we are not booting, we need to update any applications 6574 // that are clients of our shared library. If we are booting, 6575 // this will all be done once the scan is complete. 6576 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6577 } 6578 } 6579 } 6580 } 6581 6582 // We also need to dexopt any apps that are dependent on this library. Note that 6583 // if these fail, we should abort the install since installing the library will 6584 // result in some apps being broken. 6585 if (clientLibPkgs != null) { 6586 if ((scanFlags & SCAN_NO_DEX) == 0) { 6587 for (int i = 0; i < clientLibPkgs.size(); i++) { 6588 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6589 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6590 null /* instruction sets */, forceDex, 6591 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6592 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6593 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6594 "scanPackageLI failed to dexopt clientLibPkgs"); 6595 } 6596 } 6597 } 6598 } 6599 6600 // Also need to kill any apps that are dependent on the library. 6601 if (clientLibPkgs != null) { 6602 for (int i=0; i<clientLibPkgs.size(); i++) { 6603 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6604 killApplication(clientPkg.applicationInfo.packageName, 6605 clientPkg.applicationInfo.uid, "update lib"); 6606 } 6607 } 6608 6609 // writer 6610 synchronized (mPackages) { 6611 // We don't expect installation to fail beyond this point 6612 6613 // Add the new setting to mSettings 6614 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6615 // Add the new setting to mPackages 6616 mPackages.put(pkg.applicationInfo.packageName, pkg); 6617 // Make sure we don't accidentally delete its data. 6618 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6619 while (iter.hasNext()) { 6620 PackageCleanItem item = iter.next(); 6621 if (pkgName.equals(item.packageName)) { 6622 iter.remove(); 6623 } 6624 } 6625 6626 // Take care of first install / last update times. 6627 if (currentTime != 0) { 6628 if (pkgSetting.firstInstallTime == 0) { 6629 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6630 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6631 pkgSetting.lastUpdateTime = currentTime; 6632 } 6633 } else if (pkgSetting.firstInstallTime == 0) { 6634 // We need *something*. Take time time stamp of the file. 6635 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6636 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6637 if (scanFileTime != pkgSetting.timeStamp) { 6638 // A package on the system image has changed; consider this 6639 // to be an update. 6640 pkgSetting.lastUpdateTime = scanFileTime; 6641 } 6642 } 6643 6644 // Add the package's KeySets to the global KeySetManagerService 6645 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6646 try { 6647 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6648 if (pkg.mKeySetMapping != null) { 6649 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6650 if (pkg.mUpgradeKeySets != null) { 6651 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6652 } 6653 } 6654 } catch (NullPointerException e) { 6655 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6656 } catch (IllegalArgumentException e) { 6657 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6658 } 6659 6660 int N = pkg.providers.size(); 6661 StringBuilder r = null; 6662 int i; 6663 for (i=0; i<N; i++) { 6664 PackageParser.Provider p = pkg.providers.get(i); 6665 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6666 p.info.processName, pkg.applicationInfo.uid); 6667 mProviders.addProvider(p); 6668 p.syncable = p.info.isSyncable; 6669 if (p.info.authority != null) { 6670 String names[] = p.info.authority.split(";"); 6671 p.info.authority = null; 6672 for (int j = 0; j < names.length; j++) { 6673 if (j == 1 && p.syncable) { 6674 // We only want the first authority for a provider to possibly be 6675 // syncable, so if we already added this provider using a different 6676 // authority clear the syncable flag. We copy the provider before 6677 // changing it because the mProviders object contains a reference 6678 // to a provider that we don't want to change. 6679 // Only do this for the second authority since the resulting provider 6680 // object can be the same for all future authorities for this provider. 6681 p = new PackageParser.Provider(p); 6682 p.syncable = false; 6683 } 6684 if (!mProvidersByAuthority.containsKey(names[j])) { 6685 mProvidersByAuthority.put(names[j], p); 6686 if (p.info.authority == null) { 6687 p.info.authority = names[j]; 6688 } else { 6689 p.info.authority = p.info.authority + ";" + names[j]; 6690 } 6691 if (DEBUG_PACKAGE_SCANNING) { 6692 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6693 Log.d(TAG, "Registered content provider: " + names[j] 6694 + ", className = " + p.info.name + ", isSyncable = " 6695 + p.info.isSyncable); 6696 } 6697 } else { 6698 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6699 Slog.w(TAG, "Skipping provider name " + names[j] + 6700 " (in package " + pkg.applicationInfo.packageName + 6701 "): name already used by " 6702 + ((other != null && other.getComponentName() != null) 6703 ? other.getComponentName().getPackageName() : "?")); 6704 } 6705 } 6706 } 6707 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6708 if (r == null) { 6709 r = new StringBuilder(256); 6710 } else { 6711 r.append(' '); 6712 } 6713 r.append(p.info.name); 6714 } 6715 } 6716 if (r != null) { 6717 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6718 } 6719 6720 N = pkg.services.size(); 6721 r = null; 6722 for (i=0; i<N; i++) { 6723 PackageParser.Service s = pkg.services.get(i); 6724 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6725 s.info.processName, pkg.applicationInfo.uid); 6726 mServices.addService(s); 6727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append(s.info.name); 6734 } 6735 } 6736 if (r != null) { 6737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6738 } 6739 6740 N = pkg.receivers.size(); 6741 r = null; 6742 for (i=0; i<N; i++) { 6743 PackageParser.Activity a = pkg.receivers.get(i); 6744 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6745 a.info.processName, pkg.applicationInfo.uid); 6746 mReceivers.addActivity(a, "receiver"); 6747 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6748 if (r == null) { 6749 r = new StringBuilder(256); 6750 } else { 6751 r.append(' '); 6752 } 6753 r.append(a.info.name); 6754 } 6755 } 6756 if (r != null) { 6757 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6758 } 6759 6760 N = pkg.activities.size(); 6761 r = null; 6762 for (i=0; i<N; i++) { 6763 PackageParser.Activity a = pkg.activities.get(i); 6764 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6765 a.info.processName, pkg.applicationInfo.uid); 6766 mActivities.addActivity(a, "activity"); 6767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6768 if (r == null) { 6769 r = new StringBuilder(256); 6770 } else { 6771 r.append(' '); 6772 } 6773 r.append(a.info.name); 6774 } 6775 } 6776 if (r != null) { 6777 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6778 } 6779 6780 N = pkg.permissionGroups.size(); 6781 r = null; 6782 for (i=0; i<N; i++) { 6783 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6784 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6785 if (cur == null) { 6786 mPermissionGroups.put(pg.info.name, pg); 6787 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6788 if (r == null) { 6789 r = new StringBuilder(256); 6790 } else { 6791 r.append(' '); 6792 } 6793 r.append(pg.info.name); 6794 } 6795 } else { 6796 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6797 + pg.info.packageName + " ignored: original from " 6798 + cur.info.packageName); 6799 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6800 if (r == null) { 6801 r = new StringBuilder(256); 6802 } else { 6803 r.append(' '); 6804 } 6805 r.append("DUP:"); 6806 r.append(pg.info.name); 6807 } 6808 } 6809 } 6810 if (r != null) { 6811 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6812 } 6813 6814 N = pkg.permissions.size(); 6815 r = null; 6816 for (i=0; i<N; i++) { 6817 PackageParser.Permission p = pkg.permissions.get(i); 6818 6819 // Now that permission groups have a special meaning, we ignore permission 6820 // groups for legacy apps to prevent unexpected behavior. In particular, 6821 // permissions for one app being granted to someone just becuase they happen 6822 // to be in a group defined by another app (before this had no implications). 6823 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6824 p.group = mPermissionGroups.get(p.info.group); 6825 // Warn for a permission in an unknown group. 6826 if (p.info.group != null && p.group == null) { 6827 Slog.w(TAG, "Permission " + p.info.name + " from package " 6828 + p.info.packageName + " in an unknown group " + p.info.group); 6829 } 6830 } 6831 6832 ArrayMap<String, BasePermission> permissionMap = 6833 p.tree ? mSettings.mPermissionTrees 6834 : mSettings.mPermissions; 6835 BasePermission bp = permissionMap.get(p.info.name); 6836 6837 // Allow system apps to redefine non-system permissions 6838 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6839 final boolean currentOwnerIsSystem = (bp.perm != null 6840 && isSystemApp(bp.perm.owner)); 6841 if (isSystemApp(p.owner)) { 6842 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6843 // It's a built-in permission and no owner, take ownership now 6844 bp.packageSetting = pkgSetting; 6845 bp.perm = p; 6846 bp.uid = pkg.applicationInfo.uid; 6847 bp.sourcePackage = p.info.packageName; 6848 } else if (!currentOwnerIsSystem) { 6849 String msg = "New decl " + p.owner + " of permission " 6850 + p.info.name + " is system; overriding " + bp.sourcePackage; 6851 reportSettingsProblem(Log.WARN, msg); 6852 bp = null; 6853 } 6854 } 6855 } 6856 6857 if (bp == null) { 6858 bp = new BasePermission(p.info.name, p.info.packageName, 6859 BasePermission.TYPE_NORMAL); 6860 permissionMap.put(p.info.name, bp); 6861 } 6862 6863 if (bp.perm == null) { 6864 if (bp.sourcePackage == null 6865 || bp.sourcePackage.equals(p.info.packageName)) { 6866 BasePermission tree = findPermissionTreeLP(p.info.name); 6867 if (tree == null 6868 || tree.sourcePackage.equals(p.info.packageName)) { 6869 bp.packageSetting = pkgSetting; 6870 bp.perm = p; 6871 bp.uid = pkg.applicationInfo.uid; 6872 bp.sourcePackage = p.info.packageName; 6873 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6874 if (r == null) { 6875 r = new StringBuilder(256); 6876 } else { 6877 r.append(' '); 6878 } 6879 r.append(p.info.name); 6880 } 6881 } else { 6882 Slog.w(TAG, "Permission " + p.info.name + " from package " 6883 + p.info.packageName + " ignored: base tree " 6884 + tree.name + " is from package " 6885 + tree.sourcePackage); 6886 } 6887 } else { 6888 Slog.w(TAG, "Permission " + p.info.name + " from package " 6889 + p.info.packageName + " ignored: original from " 6890 + bp.sourcePackage); 6891 } 6892 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6893 if (r == null) { 6894 r = new StringBuilder(256); 6895 } else { 6896 r.append(' '); 6897 } 6898 r.append("DUP:"); 6899 r.append(p.info.name); 6900 } 6901 if (bp.perm == p) { 6902 bp.protectionLevel = p.info.protectionLevel; 6903 } 6904 } 6905 6906 if (r != null) { 6907 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6908 } 6909 6910 N = pkg.instrumentation.size(); 6911 r = null; 6912 for (i=0; i<N; i++) { 6913 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6914 a.info.packageName = pkg.applicationInfo.packageName; 6915 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6916 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6917 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6918 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6919 a.info.dataDir = pkg.applicationInfo.dataDir; 6920 6921 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6922 // need other information about the application, like the ABI and what not ? 6923 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6924 mInstrumentation.put(a.getComponentName(), a); 6925 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6926 if (r == null) { 6927 r = new StringBuilder(256); 6928 } else { 6929 r.append(' '); 6930 } 6931 r.append(a.info.name); 6932 } 6933 } 6934 if (r != null) { 6935 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6936 } 6937 6938 if (pkg.protectedBroadcasts != null) { 6939 N = pkg.protectedBroadcasts.size(); 6940 for (i=0; i<N; i++) { 6941 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6942 } 6943 } 6944 6945 pkgSetting.setTimeStamp(scanFileTime); 6946 6947 // Create idmap files for pairs of (packages, overlay packages). 6948 // Note: "android", ie framework-res.apk, is handled by native layers. 6949 if (pkg.mOverlayTarget != null) { 6950 // This is an overlay package. 6951 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6952 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6953 mOverlays.put(pkg.mOverlayTarget, 6954 new ArrayMap<String, PackageParser.Package>()); 6955 } 6956 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6957 map.put(pkg.packageName, pkg); 6958 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6959 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6960 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6961 "scanPackageLI failed to createIdmap"); 6962 } 6963 } 6964 } else if (mOverlays.containsKey(pkg.packageName) && 6965 !pkg.packageName.equals("android")) { 6966 // This is a regular package, with one or more known overlay packages. 6967 createIdmapsForPackageLI(pkg); 6968 } 6969 } 6970 6971 return pkg; 6972 } 6973 6974 /** 6975 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6976 * i.e, so that all packages can be run inside a single process if required. 6977 * 6978 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6979 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6980 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6981 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6982 * updating a package that belongs to a shared user. 6983 * 6984 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6985 * adds unnecessary complexity. 6986 */ 6987 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6988 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6989 String requiredInstructionSet = null; 6990 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6991 requiredInstructionSet = VMRuntime.getInstructionSet( 6992 scannedPackage.applicationInfo.primaryCpuAbi); 6993 } 6994 6995 PackageSetting requirer = null; 6996 for (PackageSetting ps : packagesForUser) { 6997 // If packagesForUser contains scannedPackage, we skip it. This will happen 6998 // when scannedPackage is an update of an existing package. Without this check, 6999 // we will never be able to change the ABI of any package belonging to a shared 7000 // user, even if it's compatible with other packages. 7001 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7002 if (ps.primaryCpuAbiString == null) { 7003 continue; 7004 } 7005 7006 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7007 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7008 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7009 // this but there's not much we can do. 7010 String errorMessage = "Instruction set mismatch, " 7011 + ((requirer == null) ? "[caller]" : requirer) 7012 + " requires " + requiredInstructionSet + " whereas " + ps 7013 + " requires " + instructionSet; 7014 Slog.w(TAG, errorMessage); 7015 } 7016 7017 if (requiredInstructionSet == null) { 7018 requiredInstructionSet = instructionSet; 7019 requirer = ps; 7020 } 7021 } 7022 } 7023 7024 if (requiredInstructionSet != null) { 7025 String adjustedAbi; 7026 if (requirer != null) { 7027 // requirer != null implies that either scannedPackage was null or that scannedPackage 7028 // did not require an ABI, in which case we have to adjust scannedPackage to match 7029 // the ABI of the set (which is the same as requirer's ABI) 7030 adjustedAbi = requirer.primaryCpuAbiString; 7031 if (scannedPackage != null) { 7032 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7033 } 7034 } else { 7035 // requirer == null implies that we're updating all ABIs in the set to 7036 // match scannedPackage. 7037 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7038 } 7039 7040 for (PackageSetting ps : packagesForUser) { 7041 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7042 if (ps.primaryCpuAbiString != null) { 7043 continue; 7044 } 7045 7046 ps.primaryCpuAbiString = adjustedAbi; 7047 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7048 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7049 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7050 7051 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7052 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7053 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7054 ps.primaryCpuAbiString = null; 7055 ps.pkg.applicationInfo.primaryCpuAbi = null; 7056 return; 7057 } else { 7058 mInstaller.rmdex(ps.codePathString, 7059 getDexCodeInstructionSet(getPreferredInstructionSet())); 7060 } 7061 } 7062 } 7063 } 7064 } 7065 } 7066 7067 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7068 synchronized (mPackages) { 7069 mResolverReplaced = true; 7070 // Set up information for custom user intent resolution activity. 7071 mResolveActivity.applicationInfo = pkg.applicationInfo; 7072 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7073 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7074 mResolveActivity.processName = pkg.applicationInfo.packageName; 7075 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7076 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7077 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7078 mResolveActivity.theme = 0; 7079 mResolveActivity.exported = true; 7080 mResolveActivity.enabled = true; 7081 mResolveInfo.activityInfo = mResolveActivity; 7082 mResolveInfo.priority = 0; 7083 mResolveInfo.preferredOrder = 0; 7084 mResolveInfo.match = 0; 7085 mResolveComponentName = mCustomResolverComponentName; 7086 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7087 mResolveComponentName); 7088 } 7089 } 7090 7091 private static String calculateBundledApkRoot(final String codePathString) { 7092 final File codePath = new File(codePathString); 7093 final File codeRoot; 7094 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7095 codeRoot = Environment.getRootDirectory(); 7096 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7097 codeRoot = Environment.getOemDirectory(); 7098 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7099 codeRoot = Environment.getVendorDirectory(); 7100 } else { 7101 // Unrecognized code path; take its top real segment as the apk root: 7102 // e.g. /something/app/blah.apk => /something 7103 try { 7104 File f = codePath.getCanonicalFile(); 7105 File parent = f.getParentFile(); // non-null because codePath is a file 7106 File tmp; 7107 while ((tmp = parent.getParentFile()) != null) { 7108 f = parent; 7109 parent = tmp; 7110 } 7111 codeRoot = f; 7112 Slog.w(TAG, "Unrecognized code path " 7113 + codePath + " - using " + codeRoot); 7114 } catch (IOException e) { 7115 // Can't canonicalize the code path -- shenanigans? 7116 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7117 return Environment.getRootDirectory().getPath(); 7118 } 7119 } 7120 return codeRoot.getPath(); 7121 } 7122 7123 /** 7124 * Derive and set the location of native libraries for the given package, 7125 * which varies depending on where and how the package was installed. 7126 */ 7127 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7128 final ApplicationInfo info = pkg.applicationInfo; 7129 final String codePath = pkg.codePath; 7130 final File codeFile = new File(codePath); 7131 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7132 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7133 7134 info.nativeLibraryRootDir = null; 7135 info.nativeLibraryRootRequiresIsa = false; 7136 info.nativeLibraryDir = null; 7137 info.secondaryNativeLibraryDir = null; 7138 7139 if (isApkFile(codeFile)) { 7140 // Monolithic install 7141 if (bundledApp) { 7142 // If "/system/lib64/apkname" exists, assume that is the per-package 7143 // native library directory to use; otherwise use "/system/lib/apkname". 7144 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7145 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7146 getPrimaryInstructionSet(info)); 7147 7148 // This is a bundled system app so choose the path based on the ABI. 7149 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7150 // is just the default path. 7151 final String apkName = deriveCodePathName(codePath); 7152 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7153 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7154 apkName).getAbsolutePath(); 7155 7156 if (info.secondaryCpuAbi != null) { 7157 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7158 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7159 secondaryLibDir, apkName).getAbsolutePath(); 7160 } 7161 } else if (asecApp) { 7162 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7163 .getAbsolutePath(); 7164 } else { 7165 final String apkName = deriveCodePathName(codePath); 7166 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7167 .getAbsolutePath(); 7168 } 7169 7170 info.nativeLibraryRootRequiresIsa = false; 7171 info.nativeLibraryDir = info.nativeLibraryRootDir; 7172 } else { 7173 // Cluster install 7174 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7175 info.nativeLibraryRootRequiresIsa = true; 7176 7177 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7178 getPrimaryInstructionSet(info)).getAbsolutePath(); 7179 7180 if (info.secondaryCpuAbi != null) { 7181 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7182 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7183 } 7184 } 7185 } 7186 7187 /** 7188 * Calculate the abis and roots for a bundled app. These can uniquely 7189 * be determined from the contents of the system partition, i.e whether 7190 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7191 * of this information, and instead assume that the system was built 7192 * sensibly. 7193 */ 7194 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7195 PackageSetting pkgSetting) { 7196 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7197 7198 // If "/system/lib64/apkname" exists, assume that is the per-package 7199 // native library directory to use; otherwise use "/system/lib/apkname". 7200 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7201 setBundledAppAbi(pkg, apkRoot, apkName); 7202 // pkgSetting might be null during rescan following uninstall of updates 7203 // to a bundled app, so accommodate that possibility. The settings in 7204 // that case will be established later from the parsed package. 7205 // 7206 // If the settings aren't null, sync them up with what we've just derived. 7207 // note that apkRoot isn't stored in the package settings. 7208 if (pkgSetting != null) { 7209 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7210 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7211 } 7212 } 7213 7214 /** 7215 * Deduces the ABI of a bundled app and sets the relevant fields on the 7216 * parsed pkg object. 7217 * 7218 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7219 * under which system libraries are installed. 7220 * @param apkName the name of the installed package. 7221 */ 7222 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7223 final File codeFile = new File(pkg.codePath); 7224 7225 final boolean has64BitLibs; 7226 final boolean has32BitLibs; 7227 if (isApkFile(codeFile)) { 7228 // Monolithic install 7229 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7230 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7231 } else { 7232 // Cluster install 7233 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7234 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7235 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7236 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7237 has64BitLibs = (new File(rootDir, isa)).exists(); 7238 } else { 7239 has64BitLibs = false; 7240 } 7241 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7242 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7243 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7244 has32BitLibs = (new File(rootDir, isa)).exists(); 7245 } else { 7246 has32BitLibs = false; 7247 } 7248 } 7249 7250 if (has64BitLibs && !has32BitLibs) { 7251 // The package has 64 bit libs, but not 32 bit libs. Its primary 7252 // ABI should be 64 bit. We can safely assume here that the bundled 7253 // native libraries correspond to the most preferred ABI in the list. 7254 7255 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7256 pkg.applicationInfo.secondaryCpuAbi = null; 7257 } else if (has32BitLibs && !has64BitLibs) { 7258 // The package has 32 bit libs but not 64 bit libs. Its primary 7259 // ABI should be 32 bit. 7260 7261 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7262 pkg.applicationInfo.secondaryCpuAbi = null; 7263 } else if (has32BitLibs && has64BitLibs) { 7264 // The application has both 64 and 32 bit bundled libraries. We check 7265 // here that the app declares multiArch support, and warn if it doesn't. 7266 // 7267 // We will be lenient here and record both ABIs. The primary will be the 7268 // ABI that's higher on the list, i.e, a device that's configured to prefer 7269 // 64 bit apps will see a 64 bit primary ABI, 7270 7271 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7272 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7273 } 7274 7275 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7276 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7277 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7278 } else { 7279 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7280 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7281 } 7282 } else { 7283 pkg.applicationInfo.primaryCpuAbi = null; 7284 pkg.applicationInfo.secondaryCpuAbi = null; 7285 } 7286 } 7287 7288 private void killApplication(String pkgName, int appId, String reason) { 7289 // Request the ActivityManager to kill the process(only for existing packages) 7290 // so that we do not end up in a confused state while the user is still using the older 7291 // version of the application while the new one gets installed. 7292 IActivityManager am = ActivityManagerNative.getDefault(); 7293 if (am != null) { 7294 try { 7295 am.killApplicationWithAppId(pkgName, appId, reason); 7296 } catch (RemoteException e) { 7297 } 7298 } 7299 } 7300 7301 void removePackageLI(PackageSetting ps, boolean chatty) { 7302 if (DEBUG_INSTALL) { 7303 if (chatty) 7304 Log.d(TAG, "Removing package " + ps.name); 7305 } 7306 7307 // writer 7308 synchronized (mPackages) { 7309 mPackages.remove(ps.name); 7310 final PackageParser.Package pkg = ps.pkg; 7311 if (pkg != null) { 7312 cleanPackageDataStructuresLILPw(pkg, chatty); 7313 } 7314 } 7315 } 7316 7317 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7318 if (DEBUG_INSTALL) { 7319 if (chatty) 7320 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7321 } 7322 7323 // writer 7324 synchronized (mPackages) { 7325 mPackages.remove(pkg.applicationInfo.packageName); 7326 cleanPackageDataStructuresLILPw(pkg, chatty); 7327 } 7328 } 7329 7330 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7331 int N = pkg.providers.size(); 7332 StringBuilder r = null; 7333 int i; 7334 for (i=0; i<N; i++) { 7335 PackageParser.Provider p = pkg.providers.get(i); 7336 mProviders.removeProvider(p); 7337 if (p.info.authority == null) { 7338 7339 /* There was another ContentProvider with this authority when 7340 * this app was installed so this authority is null, 7341 * Ignore it as we don't have to unregister the provider. 7342 */ 7343 continue; 7344 } 7345 String names[] = p.info.authority.split(";"); 7346 for (int j = 0; j < names.length; j++) { 7347 if (mProvidersByAuthority.get(names[j]) == p) { 7348 mProvidersByAuthority.remove(names[j]); 7349 if (DEBUG_REMOVE) { 7350 if (chatty) 7351 Log.d(TAG, "Unregistered content provider: " + names[j] 7352 + ", className = " + p.info.name + ", isSyncable = " 7353 + p.info.isSyncable); 7354 } 7355 } 7356 } 7357 if (DEBUG_REMOVE && chatty) { 7358 if (r == null) { 7359 r = new StringBuilder(256); 7360 } else { 7361 r.append(' '); 7362 } 7363 r.append(p.info.name); 7364 } 7365 } 7366 if (r != null) { 7367 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7368 } 7369 7370 N = pkg.services.size(); 7371 r = null; 7372 for (i=0; i<N; i++) { 7373 PackageParser.Service s = pkg.services.get(i); 7374 mServices.removeService(s); 7375 if (chatty) { 7376 if (r == null) { 7377 r = new StringBuilder(256); 7378 } else { 7379 r.append(' '); 7380 } 7381 r.append(s.info.name); 7382 } 7383 } 7384 if (r != null) { 7385 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7386 } 7387 7388 N = pkg.receivers.size(); 7389 r = null; 7390 for (i=0; i<N; i++) { 7391 PackageParser.Activity a = pkg.receivers.get(i); 7392 mReceivers.removeActivity(a, "receiver"); 7393 if (DEBUG_REMOVE && chatty) { 7394 if (r == null) { 7395 r = new StringBuilder(256); 7396 } else { 7397 r.append(' '); 7398 } 7399 r.append(a.info.name); 7400 } 7401 } 7402 if (r != null) { 7403 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7404 } 7405 7406 N = pkg.activities.size(); 7407 r = null; 7408 for (i=0; i<N; i++) { 7409 PackageParser.Activity a = pkg.activities.get(i); 7410 mActivities.removeActivity(a, "activity"); 7411 if (DEBUG_REMOVE && chatty) { 7412 if (r == null) { 7413 r = new StringBuilder(256); 7414 } else { 7415 r.append(' '); 7416 } 7417 r.append(a.info.name); 7418 } 7419 } 7420 if (r != null) { 7421 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7422 } 7423 7424 N = pkg.permissions.size(); 7425 r = null; 7426 for (i=0; i<N; i++) { 7427 PackageParser.Permission p = pkg.permissions.get(i); 7428 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7429 if (bp == null) { 7430 bp = mSettings.mPermissionTrees.get(p.info.name); 7431 } 7432 if (bp != null && bp.perm == p) { 7433 bp.perm = null; 7434 if (DEBUG_REMOVE && chatty) { 7435 if (r == null) { 7436 r = new StringBuilder(256); 7437 } else { 7438 r.append(' '); 7439 } 7440 r.append(p.info.name); 7441 } 7442 } 7443 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7444 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7445 if (appOpPerms != null) { 7446 appOpPerms.remove(pkg.packageName); 7447 } 7448 } 7449 } 7450 if (r != null) { 7451 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7452 } 7453 7454 N = pkg.requestedPermissions.size(); 7455 r = null; 7456 for (i=0; i<N; i++) { 7457 String perm = pkg.requestedPermissions.get(i); 7458 BasePermission bp = mSettings.mPermissions.get(perm); 7459 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7460 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7461 if (appOpPerms != null) { 7462 appOpPerms.remove(pkg.packageName); 7463 if (appOpPerms.isEmpty()) { 7464 mAppOpPermissionPackages.remove(perm); 7465 } 7466 } 7467 } 7468 } 7469 if (r != null) { 7470 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7471 } 7472 7473 N = pkg.instrumentation.size(); 7474 r = null; 7475 for (i=0; i<N; i++) { 7476 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7477 mInstrumentation.remove(a.getComponentName()); 7478 if (DEBUG_REMOVE && chatty) { 7479 if (r == null) { 7480 r = new StringBuilder(256); 7481 } else { 7482 r.append(' '); 7483 } 7484 r.append(a.info.name); 7485 } 7486 } 7487 if (r != null) { 7488 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7489 } 7490 7491 r = null; 7492 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7493 // Only system apps can hold shared libraries. 7494 if (pkg.libraryNames != null) { 7495 for (i=0; i<pkg.libraryNames.size(); i++) { 7496 String name = pkg.libraryNames.get(i); 7497 SharedLibraryEntry cur = mSharedLibraries.get(name); 7498 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7499 mSharedLibraries.remove(name); 7500 if (DEBUG_REMOVE && chatty) { 7501 if (r == null) { 7502 r = new StringBuilder(256); 7503 } else { 7504 r.append(' '); 7505 } 7506 r.append(name); 7507 } 7508 } 7509 } 7510 } 7511 } 7512 if (r != null) { 7513 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7514 } 7515 } 7516 7517 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7518 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7519 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7520 return true; 7521 } 7522 } 7523 return false; 7524 } 7525 7526 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7527 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7528 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7529 7530 private void updatePermissionsLPw(String changingPkg, 7531 PackageParser.Package pkgInfo, int flags) { 7532 // Make sure there are no dangling permission trees. 7533 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7534 while (it.hasNext()) { 7535 final BasePermission bp = it.next(); 7536 if (bp.packageSetting == null) { 7537 // We may not yet have parsed the package, so just see if 7538 // we still know about its settings. 7539 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7540 } 7541 if (bp.packageSetting == null) { 7542 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7543 + " from package " + bp.sourcePackage); 7544 it.remove(); 7545 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7546 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7547 Slog.i(TAG, "Removing old permission tree: " + bp.name 7548 + " from package " + bp.sourcePackage); 7549 flags |= UPDATE_PERMISSIONS_ALL; 7550 it.remove(); 7551 } 7552 } 7553 } 7554 7555 // Make sure all dynamic permissions have been assigned to a package, 7556 // and make sure there are no dangling permissions. 7557 it = mSettings.mPermissions.values().iterator(); 7558 while (it.hasNext()) { 7559 final BasePermission bp = it.next(); 7560 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7561 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7562 + bp.name + " pkg=" + bp.sourcePackage 7563 + " info=" + bp.pendingInfo); 7564 if (bp.packageSetting == null && bp.pendingInfo != null) { 7565 final BasePermission tree = findPermissionTreeLP(bp.name); 7566 if (tree != null && tree.perm != null) { 7567 bp.packageSetting = tree.packageSetting; 7568 bp.perm = new PackageParser.Permission(tree.perm.owner, 7569 new PermissionInfo(bp.pendingInfo)); 7570 bp.perm.info.packageName = tree.perm.info.packageName; 7571 bp.perm.info.name = bp.name; 7572 bp.uid = tree.uid; 7573 } 7574 } 7575 } 7576 if (bp.packageSetting == null) { 7577 // We may not yet have parsed the package, so just see if 7578 // we still know about its settings. 7579 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7580 } 7581 if (bp.packageSetting == null) { 7582 Slog.w(TAG, "Removing dangling permission: " + bp.name 7583 + " from package " + bp.sourcePackage); 7584 it.remove(); 7585 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7586 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7587 Slog.i(TAG, "Removing old permission: " + bp.name 7588 + " from package " + bp.sourcePackage); 7589 flags |= UPDATE_PERMISSIONS_ALL; 7590 it.remove(); 7591 } 7592 } 7593 } 7594 7595 // Now update the permissions for all packages, in particular 7596 // replace the granted permissions of the system packages. 7597 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7598 for (PackageParser.Package pkg : mPackages.values()) { 7599 if (pkg != pkgInfo) { 7600 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7601 changingPkg); 7602 } 7603 } 7604 } 7605 7606 if (pkgInfo != null) { 7607 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7608 } 7609 } 7610 7611 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7612 String packageOfInterest) { 7613 // IMPORTANT: There are two types of permissions: install and runtime. 7614 // Install time permissions are granted when the app is installed to 7615 // all device users and users added in the future. Runtime permissions 7616 // are granted at runtime explicitly to specific users. Normal and signature 7617 // protected permissions are install time permissions. Dangerous permissions 7618 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7619 // otherwise they are runtime permissions. This function does not manage 7620 // runtime permissions except for the case an app targeting Lollipop MR1 7621 // being upgraded to target a newer SDK, in which case dangerous permissions 7622 // are transformed from install time to runtime ones. 7623 7624 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7625 if (ps == null) { 7626 return; 7627 } 7628 7629 PermissionsState permissionsState = ps.getPermissionsState(); 7630 PermissionsState origPermissions = permissionsState; 7631 7632 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7633 7634 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7635 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7636 7637 boolean changedInstallPermission = false; 7638 7639 if (replace) { 7640 ps.installPermissionsFixed = false; 7641 if (!ps.isSharedUser()) { 7642 origPermissions = new PermissionsState(permissionsState); 7643 permissionsState.reset(); 7644 } 7645 } 7646 7647 permissionsState.setGlobalGids(mGlobalGids); 7648 7649 final int N = pkg.requestedPermissions.size(); 7650 for (int i=0; i<N; i++) { 7651 final String name = pkg.requestedPermissions.get(i); 7652 final BasePermission bp = mSettings.mPermissions.get(name); 7653 7654 if (DEBUG_INSTALL) { 7655 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7656 } 7657 7658 if (bp == null || bp.packageSetting == null) { 7659 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7660 Slog.w(TAG, "Unknown permission " + name 7661 + " in package " + pkg.packageName); 7662 } 7663 continue; 7664 } 7665 7666 final String perm = bp.name; 7667 boolean allowedSig = false; 7668 int grant = GRANT_DENIED; 7669 7670 // Keep track of app op permissions. 7671 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7672 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7673 if (pkgs == null) { 7674 pkgs = new ArraySet<>(); 7675 mAppOpPermissionPackages.put(bp.name, pkgs); 7676 } 7677 pkgs.add(pkg.packageName); 7678 } 7679 7680 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7681 switch (level) { 7682 case PermissionInfo.PROTECTION_NORMAL: { 7683 // For all apps normal permissions are install time ones. 7684 grant = GRANT_INSTALL; 7685 } break; 7686 7687 case PermissionInfo.PROTECTION_DANGEROUS: { 7688 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7689 // For legacy apps dangerous permissions are install time ones. 7690 grant = GRANT_INSTALL; 7691 } else if (ps.isSystem()) { 7692 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7693 if (origPermissions.hasInstallPermission(bp.name)) { 7694 // If a system app had an install permission, then the app was 7695 // upgraded and we grant the permissions as runtime to all users. 7696 grant = GRANT_UPGRADE; 7697 upgradeUserIds = currentUserIds; 7698 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7699 // If users changed since the last permissions update for a 7700 // system app, we grant the permission as runtime to the new users. 7701 grant = GRANT_UPGRADE; 7702 upgradeUserIds = currentUserIds; 7703 for (int userId : updatedUserIds) { 7704 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7705 } 7706 } else { 7707 // Otherwise, we grant the permission as runtime if the app 7708 // already had it, i.e. we preserve runtime permissions. 7709 grant = GRANT_RUNTIME; 7710 } 7711 } else if (origPermissions.hasInstallPermission(bp.name)) { 7712 // For legacy apps that became modern, install becomes runtime. 7713 grant = GRANT_UPGRADE; 7714 upgradeUserIds = currentUserIds; 7715 } else if (replace) { 7716 // For upgraded modern apps keep runtime permissions unchanged. 7717 grant = GRANT_RUNTIME; 7718 } 7719 } break; 7720 7721 case PermissionInfo.PROTECTION_SIGNATURE: { 7722 // For all apps signature permissions are install time ones. 7723 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7724 if (allowedSig) { 7725 grant = GRANT_INSTALL; 7726 } 7727 } break; 7728 } 7729 7730 if (DEBUG_INSTALL) { 7731 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7732 } 7733 7734 if (grant != GRANT_DENIED) { 7735 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7736 // If this is an existing, non-system package, then 7737 // we can't add any new permissions to it. 7738 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7739 // Except... if this is a permission that was added 7740 // to the platform (note: need to only do this when 7741 // updating the platform). 7742 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7743 grant = GRANT_DENIED; 7744 } 7745 } 7746 } 7747 7748 switch (grant) { 7749 case GRANT_INSTALL: { 7750 // Grant an install permission. 7751 if (permissionsState.grantInstallPermission(bp) != 7752 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7753 changedInstallPermission = true; 7754 } 7755 } break; 7756 7757 case GRANT_RUNTIME: { 7758 // Grant previously granted runtime permissions. 7759 for (int userId : UserManagerService.getInstance().getUserIds()) { 7760 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7761 PermissionState permissionState = origPermissions 7762 .getRuntimePermissionState(bp.name, userId); 7763 final int flags = permissionState.getFlags(); 7764 if (permissionsState.grantRuntimePermission(bp, userId) == 7765 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7766 // If we cannot put the permission as it was, we have to write. 7767 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7768 changedRuntimePermissionUserIds, userId); 7769 } else { 7770 // System components not only get the permissions but 7771 // they are also fixed, so nothing can change that. 7772 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7773 ? flags 7774 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7775 // Propagate the permission flags. 7776 permissionsState.updatePermissionFlags(bp, userId, 7777 newFlags, newFlags); 7778 } 7779 } 7780 } 7781 } break; 7782 7783 case GRANT_UPGRADE: { 7784 // Grant runtime permissions for a previously held install permission. 7785 PermissionState permissionState = origPermissions 7786 .getInstallPermissionState(bp.name); 7787 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7788 7789 origPermissions.revokeInstallPermission(bp); 7790 // We will be transferring the permission flags, so clear them. 7791 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7792 PackageManager.MASK_PERMISSION_FLAGS, 0); 7793 7794 // If the permission is not to be promoted to runtime we ignore it and 7795 // also its other flags as they are not applicable to install permissions. 7796 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7797 for (int userId : upgradeUserIds) { 7798 if (permissionsState.grantRuntimePermission(bp, userId) != 7799 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7800 // System components not only get the permissions but 7801 // they are also fixed so nothing can change that. 7802 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7803 ? flags 7804 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7805 // Transfer the permission flags. 7806 permissionsState.updatePermissionFlags(bp, userId, 7807 newFlags, newFlags); 7808 // If we granted the permission, we have to write. 7809 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7810 changedRuntimePermissionUserIds, userId); 7811 } 7812 } 7813 } 7814 } break; 7815 7816 default: { 7817 if (packageOfInterest == null 7818 || packageOfInterest.equals(pkg.packageName)) { 7819 Slog.w(TAG, "Not granting permission " + perm 7820 + " to package " + pkg.packageName 7821 + " because it was previously installed without"); 7822 } 7823 } break; 7824 } 7825 } else { 7826 if (permissionsState.revokeInstallPermission(bp) != 7827 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7828 // Also drop the permission flags. 7829 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7830 PackageManager.MASK_PERMISSION_FLAGS, 0); 7831 changedInstallPermission = true; 7832 Slog.i(TAG, "Un-granting permission " + perm 7833 + " from package " + pkg.packageName 7834 + " (protectionLevel=" + bp.protectionLevel 7835 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7836 + ")"); 7837 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7838 // Don't print warning for app op permissions, since it is fine for them 7839 // not to be granted, there is a UI for the user to decide. 7840 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7841 Slog.w(TAG, "Not granting permission " + perm 7842 + " to package " + pkg.packageName 7843 + " (protectionLevel=" + bp.protectionLevel 7844 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7845 + ")"); 7846 } 7847 } 7848 } 7849 } 7850 7851 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7852 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7853 // This is the first that we have heard about this package, so the 7854 // permissions we have now selected are fixed until explicitly 7855 // changed. 7856 ps.installPermissionsFixed = true; 7857 } 7858 7859 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7860 7861 // Persist the runtime permissions state for users with changes. 7862 for (int userId : changedRuntimePermissionUserIds) { 7863 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7864 } 7865 } 7866 7867 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7868 boolean allowed = false; 7869 final int NP = PackageParser.NEW_PERMISSIONS.length; 7870 for (int ip=0; ip<NP; ip++) { 7871 final PackageParser.NewPermissionInfo npi 7872 = PackageParser.NEW_PERMISSIONS[ip]; 7873 if (npi.name.equals(perm) 7874 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7875 allowed = true; 7876 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7877 + pkg.packageName); 7878 break; 7879 } 7880 } 7881 return allowed; 7882 } 7883 7884 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7885 BasePermission bp, PermissionsState origPermissions) { 7886 boolean allowed; 7887 allowed = (compareSignatures( 7888 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7889 == PackageManager.SIGNATURE_MATCH) 7890 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7891 == PackageManager.SIGNATURE_MATCH); 7892 if (!allowed && (bp.protectionLevel 7893 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7894 if (isSystemApp(pkg)) { 7895 // For updated system applications, a system permission 7896 // is granted only if it had been defined by the original application. 7897 if (pkg.isUpdatedSystemApp()) { 7898 final PackageSetting sysPs = mSettings 7899 .getDisabledSystemPkgLPr(pkg.packageName); 7900 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7901 // If the original was granted this permission, we take 7902 // that grant decision as read and propagate it to the 7903 // update. 7904 if (sysPs.isPrivileged()) { 7905 allowed = true; 7906 } 7907 } else { 7908 // The system apk may have been updated with an older 7909 // version of the one on the data partition, but which 7910 // granted a new system permission that it didn't have 7911 // before. In this case we do want to allow the app to 7912 // now get the new permission if the ancestral apk is 7913 // privileged to get it. 7914 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7915 for (int j=0; 7916 j<sysPs.pkg.requestedPermissions.size(); j++) { 7917 if (perm.equals( 7918 sysPs.pkg.requestedPermissions.get(j))) { 7919 allowed = true; 7920 break; 7921 } 7922 } 7923 } 7924 } 7925 } else { 7926 allowed = isPrivilegedApp(pkg); 7927 } 7928 } 7929 } 7930 if (!allowed && (bp.protectionLevel 7931 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7932 // For development permissions, a development permission 7933 // is granted only if it was already granted. 7934 allowed = origPermissions.hasInstallPermission(perm); 7935 } 7936 return allowed; 7937 } 7938 7939 final class ActivityIntentResolver 7940 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7941 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7942 boolean defaultOnly, int userId) { 7943 if (!sUserManager.exists(userId)) return null; 7944 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7945 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7946 } 7947 7948 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7949 int userId) { 7950 if (!sUserManager.exists(userId)) return null; 7951 mFlags = flags; 7952 return super.queryIntent(intent, resolvedType, 7953 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7954 } 7955 7956 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7957 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7958 if (!sUserManager.exists(userId)) return null; 7959 if (packageActivities == null) { 7960 return null; 7961 } 7962 mFlags = flags; 7963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7964 final int N = packageActivities.size(); 7965 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7966 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7967 7968 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7969 for (int i = 0; i < N; ++i) { 7970 intentFilters = packageActivities.get(i).intents; 7971 if (intentFilters != null && intentFilters.size() > 0) { 7972 PackageParser.ActivityIntentInfo[] array = 7973 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7974 intentFilters.toArray(array); 7975 listCut.add(array); 7976 } 7977 } 7978 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7979 } 7980 7981 public final void addActivity(PackageParser.Activity a, String type) { 7982 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7983 mActivities.put(a.getComponentName(), a); 7984 if (DEBUG_SHOW_INFO) 7985 Log.v( 7986 TAG, " " + type + " " + 7987 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7988 if (DEBUG_SHOW_INFO) 7989 Log.v(TAG, " Class=" + a.info.name); 7990 final int NI = a.intents.size(); 7991 for (int j=0; j<NI; j++) { 7992 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7993 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7994 intent.setPriority(0); 7995 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7996 + a.className + " with priority > 0, forcing to 0"); 7997 } 7998 if (DEBUG_SHOW_INFO) { 7999 Log.v(TAG, " IntentFilter:"); 8000 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8001 } 8002 if (!intent.debugCheck()) { 8003 Log.w(TAG, "==> For Activity " + a.info.name); 8004 } 8005 addFilter(intent); 8006 } 8007 } 8008 8009 public final void removeActivity(PackageParser.Activity a, String type) { 8010 mActivities.remove(a.getComponentName()); 8011 if (DEBUG_SHOW_INFO) { 8012 Log.v(TAG, " " + type + " " 8013 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8014 : a.info.name) + ":"); 8015 Log.v(TAG, " Class=" + a.info.name); 8016 } 8017 final int NI = a.intents.size(); 8018 for (int j=0; j<NI; j++) { 8019 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8020 if (DEBUG_SHOW_INFO) { 8021 Log.v(TAG, " IntentFilter:"); 8022 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8023 } 8024 removeFilter(intent); 8025 } 8026 } 8027 8028 @Override 8029 protected boolean allowFilterResult( 8030 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8031 ActivityInfo filterAi = filter.activity.info; 8032 for (int i=dest.size()-1; i>=0; i--) { 8033 ActivityInfo destAi = dest.get(i).activityInfo; 8034 if (destAi.name == filterAi.name 8035 && destAi.packageName == filterAi.packageName) { 8036 return false; 8037 } 8038 } 8039 return true; 8040 } 8041 8042 @Override 8043 protected ActivityIntentInfo[] newArray(int size) { 8044 return new ActivityIntentInfo[size]; 8045 } 8046 8047 @Override 8048 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8049 if (!sUserManager.exists(userId)) return true; 8050 PackageParser.Package p = filter.activity.owner; 8051 if (p != null) { 8052 PackageSetting ps = (PackageSetting)p.mExtras; 8053 if (ps != null) { 8054 // System apps are never considered stopped for purposes of 8055 // filtering, because there may be no way for the user to 8056 // actually re-launch them. 8057 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8058 && ps.getStopped(userId); 8059 } 8060 } 8061 return false; 8062 } 8063 8064 @Override 8065 protected boolean isPackageForFilter(String packageName, 8066 PackageParser.ActivityIntentInfo info) { 8067 return packageName.equals(info.activity.owner.packageName); 8068 } 8069 8070 @Override 8071 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8072 int match, int userId) { 8073 if (!sUserManager.exists(userId)) return null; 8074 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8075 return null; 8076 } 8077 final PackageParser.Activity activity = info.activity; 8078 if (mSafeMode && (activity.info.applicationInfo.flags 8079 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8080 return null; 8081 } 8082 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8083 if (ps == null) { 8084 return null; 8085 } 8086 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8087 ps.readUserState(userId), userId); 8088 if (ai == null) { 8089 return null; 8090 } 8091 final ResolveInfo res = new ResolveInfo(); 8092 res.activityInfo = ai; 8093 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8094 res.filter = info; 8095 } 8096 if (info != null) { 8097 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8098 } 8099 res.priority = info.getPriority(); 8100 res.preferredOrder = activity.owner.mPreferredOrder; 8101 //System.out.println("Result: " + res.activityInfo.className + 8102 // " = " + res.priority); 8103 res.match = match; 8104 res.isDefault = info.hasDefault; 8105 res.labelRes = info.labelRes; 8106 res.nonLocalizedLabel = info.nonLocalizedLabel; 8107 if (userNeedsBadging(userId)) { 8108 res.noResourceId = true; 8109 } else { 8110 res.icon = info.icon; 8111 } 8112 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8113 return res; 8114 } 8115 8116 @Override 8117 protected void sortResults(List<ResolveInfo> results) { 8118 Collections.sort(results, mResolvePrioritySorter); 8119 } 8120 8121 @Override 8122 protected void dumpFilter(PrintWriter out, String prefix, 8123 PackageParser.ActivityIntentInfo filter) { 8124 out.print(prefix); out.print( 8125 Integer.toHexString(System.identityHashCode(filter.activity))); 8126 out.print(' '); 8127 filter.activity.printComponentShortName(out); 8128 out.print(" filter "); 8129 out.println(Integer.toHexString(System.identityHashCode(filter))); 8130 } 8131 8132 @Override 8133 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8134 return filter.activity; 8135 } 8136 8137 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8138 PackageParser.Activity activity = (PackageParser.Activity)label; 8139 out.print(prefix); out.print( 8140 Integer.toHexString(System.identityHashCode(activity))); 8141 out.print(' '); 8142 activity.printComponentShortName(out); 8143 if (count > 1) { 8144 out.print(" ("); out.print(count); out.print(" filters)"); 8145 } 8146 out.println(); 8147 } 8148 8149// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8150// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8151// final List<ResolveInfo> retList = Lists.newArrayList(); 8152// while (i.hasNext()) { 8153// final ResolveInfo resolveInfo = i.next(); 8154// if (isEnabledLP(resolveInfo.activityInfo)) { 8155// retList.add(resolveInfo); 8156// } 8157// } 8158// return retList; 8159// } 8160 8161 // Keys are String (activity class name), values are Activity. 8162 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8163 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8164 private int mFlags; 8165 } 8166 8167 private final class ServiceIntentResolver 8168 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8169 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8170 boolean defaultOnly, int userId) { 8171 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8172 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8173 } 8174 8175 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8176 int userId) { 8177 if (!sUserManager.exists(userId)) return null; 8178 mFlags = flags; 8179 return super.queryIntent(intent, resolvedType, 8180 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8181 } 8182 8183 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8184 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8185 if (!sUserManager.exists(userId)) return null; 8186 if (packageServices == null) { 8187 return null; 8188 } 8189 mFlags = flags; 8190 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8191 final int N = packageServices.size(); 8192 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8193 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8194 8195 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8196 for (int i = 0; i < N; ++i) { 8197 intentFilters = packageServices.get(i).intents; 8198 if (intentFilters != null && intentFilters.size() > 0) { 8199 PackageParser.ServiceIntentInfo[] array = 8200 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8201 intentFilters.toArray(array); 8202 listCut.add(array); 8203 } 8204 } 8205 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8206 } 8207 8208 public final void addService(PackageParser.Service s) { 8209 mServices.put(s.getComponentName(), s); 8210 if (DEBUG_SHOW_INFO) { 8211 Log.v(TAG, " " 8212 + (s.info.nonLocalizedLabel != null 8213 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8214 Log.v(TAG, " Class=" + s.info.name); 8215 } 8216 final int NI = s.intents.size(); 8217 int j; 8218 for (j=0; j<NI; j++) { 8219 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8220 if (DEBUG_SHOW_INFO) { 8221 Log.v(TAG, " IntentFilter:"); 8222 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8223 } 8224 if (!intent.debugCheck()) { 8225 Log.w(TAG, "==> For Service " + s.info.name); 8226 } 8227 addFilter(intent); 8228 } 8229 } 8230 8231 public final void removeService(PackageParser.Service s) { 8232 mServices.remove(s.getComponentName()); 8233 if (DEBUG_SHOW_INFO) { 8234 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8235 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8236 Log.v(TAG, " Class=" + s.info.name); 8237 } 8238 final int NI = s.intents.size(); 8239 int j; 8240 for (j=0; j<NI; j++) { 8241 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8242 if (DEBUG_SHOW_INFO) { 8243 Log.v(TAG, " IntentFilter:"); 8244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8245 } 8246 removeFilter(intent); 8247 } 8248 } 8249 8250 @Override 8251 protected boolean allowFilterResult( 8252 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8253 ServiceInfo filterSi = filter.service.info; 8254 for (int i=dest.size()-1; i>=0; i--) { 8255 ServiceInfo destAi = dest.get(i).serviceInfo; 8256 if (destAi.name == filterSi.name 8257 && destAi.packageName == filterSi.packageName) { 8258 return false; 8259 } 8260 } 8261 return true; 8262 } 8263 8264 @Override 8265 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8266 return new PackageParser.ServiceIntentInfo[size]; 8267 } 8268 8269 @Override 8270 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8271 if (!sUserManager.exists(userId)) return true; 8272 PackageParser.Package p = filter.service.owner; 8273 if (p != null) { 8274 PackageSetting ps = (PackageSetting)p.mExtras; 8275 if (ps != null) { 8276 // System apps are never considered stopped for purposes of 8277 // filtering, because there may be no way for the user to 8278 // actually re-launch them. 8279 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8280 && ps.getStopped(userId); 8281 } 8282 } 8283 return false; 8284 } 8285 8286 @Override 8287 protected boolean isPackageForFilter(String packageName, 8288 PackageParser.ServiceIntentInfo info) { 8289 return packageName.equals(info.service.owner.packageName); 8290 } 8291 8292 @Override 8293 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8294 int match, int userId) { 8295 if (!sUserManager.exists(userId)) return null; 8296 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8297 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8298 return null; 8299 } 8300 final PackageParser.Service service = info.service; 8301 if (mSafeMode && (service.info.applicationInfo.flags 8302 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8303 return null; 8304 } 8305 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8306 if (ps == null) { 8307 return null; 8308 } 8309 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8310 ps.readUserState(userId), userId); 8311 if (si == null) { 8312 return null; 8313 } 8314 final ResolveInfo res = new ResolveInfo(); 8315 res.serviceInfo = si; 8316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8317 res.filter = filter; 8318 } 8319 res.priority = info.getPriority(); 8320 res.preferredOrder = service.owner.mPreferredOrder; 8321 res.match = match; 8322 res.isDefault = info.hasDefault; 8323 res.labelRes = info.labelRes; 8324 res.nonLocalizedLabel = info.nonLocalizedLabel; 8325 res.icon = info.icon; 8326 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8327 return res; 8328 } 8329 8330 @Override 8331 protected void sortResults(List<ResolveInfo> results) { 8332 Collections.sort(results, mResolvePrioritySorter); 8333 } 8334 8335 @Override 8336 protected void dumpFilter(PrintWriter out, String prefix, 8337 PackageParser.ServiceIntentInfo filter) { 8338 out.print(prefix); out.print( 8339 Integer.toHexString(System.identityHashCode(filter.service))); 8340 out.print(' '); 8341 filter.service.printComponentShortName(out); 8342 out.print(" filter "); 8343 out.println(Integer.toHexString(System.identityHashCode(filter))); 8344 } 8345 8346 @Override 8347 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8348 return filter.service; 8349 } 8350 8351 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8352 PackageParser.Service service = (PackageParser.Service)label; 8353 out.print(prefix); out.print( 8354 Integer.toHexString(System.identityHashCode(service))); 8355 out.print(' '); 8356 service.printComponentShortName(out); 8357 if (count > 1) { 8358 out.print(" ("); out.print(count); out.print(" filters)"); 8359 } 8360 out.println(); 8361 } 8362 8363// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8364// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8365// final List<ResolveInfo> retList = Lists.newArrayList(); 8366// while (i.hasNext()) { 8367// final ResolveInfo resolveInfo = (ResolveInfo) i; 8368// if (isEnabledLP(resolveInfo.serviceInfo)) { 8369// retList.add(resolveInfo); 8370// } 8371// } 8372// return retList; 8373// } 8374 8375 // Keys are String (activity class name), values are Activity. 8376 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8377 = new ArrayMap<ComponentName, PackageParser.Service>(); 8378 private int mFlags; 8379 }; 8380 8381 private final class ProviderIntentResolver 8382 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8383 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8384 boolean defaultOnly, int userId) { 8385 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8386 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8387 } 8388 8389 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8390 int userId) { 8391 if (!sUserManager.exists(userId)) 8392 return null; 8393 mFlags = flags; 8394 return super.queryIntent(intent, resolvedType, 8395 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8396 } 8397 8398 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8399 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8400 if (!sUserManager.exists(userId)) 8401 return null; 8402 if (packageProviders == null) { 8403 return null; 8404 } 8405 mFlags = flags; 8406 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8407 final int N = packageProviders.size(); 8408 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8409 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8410 8411 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8412 for (int i = 0; i < N; ++i) { 8413 intentFilters = packageProviders.get(i).intents; 8414 if (intentFilters != null && intentFilters.size() > 0) { 8415 PackageParser.ProviderIntentInfo[] array = 8416 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8417 intentFilters.toArray(array); 8418 listCut.add(array); 8419 } 8420 } 8421 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8422 } 8423 8424 public final void addProvider(PackageParser.Provider p) { 8425 if (mProviders.containsKey(p.getComponentName())) { 8426 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8427 return; 8428 } 8429 8430 mProviders.put(p.getComponentName(), p); 8431 if (DEBUG_SHOW_INFO) { 8432 Log.v(TAG, " " 8433 + (p.info.nonLocalizedLabel != null 8434 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8435 Log.v(TAG, " Class=" + p.info.name); 8436 } 8437 final int NI = p.intents.size(); 8438 int j; 8439 for (j = 0; j < NI; j++) { 8440 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8441 if (DEBUG_SHOW_INFO) { 8442 Log.v(TAG, " IntentFilter:"); 8443 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8444 } 8445 if (!intent.debugCheck()) { 8446 Log.w(TAG, "==> For Provider " + p.info.name); 8447 } 8448 addFilter(intent); 8449 } 8450 } 8451 8452 public final void removeProvider(PackageParser.Provider p) { 8453 mProviders.remove(p.getComponentName()); 8454 if (DEBUG_SHOW_INFO) { 8455 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8456 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8457 Log.v(TAG, " Class=" + p.info.name); 8458 } 8459 final int NI = p.intents.size(); 8460 int j; 8461 for (j = 0; j < NI; j++) { 8462 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8463 if (DEBUG_SHOW_INFO) { 8464 Log.v(TAG, " IntentFilter:"); 8465 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8466 } 8467 removeFilter(intent); 8468 } 8469 } 8470 8471 @Override 8472 protected boolean allowFilterResult( 8473 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8474 ProviderInfo filterPi = filter.provider.info; 8475 for (int i = dest.size() - 1; i >= 0; i--) { 8476 ProviderInfo destPi = dest.get(i).providerInfo; 8477 if (destPi.name == filterPi.name 8478 && destPi.packageName == filterPi.packageName) { 8479 return false; 8480 } 8481 } 8482 return true; 8483 } 8484 8485 @Override 8486 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8487 return new PackageParser.ProviderIntentInfo[size]; 8488 } 8489 8490 @Override 8491 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8492 if (!sUserManager.exists(userId)) 8493 return true; 8494 PackageParser.Package p = filter.provider.owner; 8495 if (p != null) { 8496 PackageSetting ps = (PackageSetting) p.mExtras; 8497 if (ps != null) { 8498 // System apps are never considered stopped for purposes of 8499 // filtering, because there may be no way for the user to 8500 // actually re-launch them. 8501 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8502 && ps.getStopped(userId); 8503 } 8504 } 8505 return false; 8506 } 8507 8508 @Override 8509 protected boolean isPackageForFilter(String packageName, 8510 PackageParser.ProviderIntentInfo info) { 8511 return packageName.equals(info.provider.owner.packageName); 8512 } 8513 8514 @Override 8515 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8516 int match, int userId) { 8517 if (!sUserManager.exists(userId)) 8518 return null; 8519 final PackageParser.ProviderIntentInfo info = filter; 8520 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8521 return null; 8522 } 8523 final PackageParser.Provider provider = info.provider; 8524 if (mSafeMode && (provider.info.applicationInfo.flags 8525 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8526 return null; 8527 } 8528 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8529 if (ps == null) { 8530 return null; 8531 } 8532 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8533 ps.readUserState(userId), userId); 8534 if (pi == null) { 8535 return null; 8536 } 8537 final ResolveInfo res = new ResolveInfo(); 8538 res.providerInfo = pi; 8539 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8540 res.filter = filter; 8541 } 8542 res.priority = info.getPriority(); 8543 res.preferredOrder = provider.owner.mPreferredOrder; 8544 res.match = match; 8545 res.isDefault = info.hasDefault; 8546 res.labelRes = info.labelRes; 8547 res.nonLocalizedLabel = info.nonLocalizedLabel; 8548 res.icon = info.icon; 8549 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8550 return res; 8551 } 8552 8553 @Override 8554 protected void sortResults(List<ResolveInfo> results) { 8555 Collections.sort(results, mResolvePrioritySorter); 8556 } 8557 8558 @Override 8559 protected void dumpFilter(PrintWriter out, String prefix, 8560 PackageParser.ProviderIntentInfo filter) { 8561 out.print(prefix); 8562 out.print( 8563 Integer.toHexString(System.identityHashCode(filter.provider))); 8564 out.print(' '); 8565 filter.provider.printComponentShortName(out); 8566 out.print(" filter "); 8567 out.println(Integer.toHexString(System.identityHashCode(filter))); 8568 } 8569 8570 @Override 8571 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8572 return filter.provider; 8573 } 8574 8575 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8576 PackageParser.Provider provider = (PackageParser.Provider)label; 8577 out.print(prefix); out.print( 8578 Integer.toHexString(System.identityHashCode(provider))); 8579 out.print(' '); 8580 provider.printComponentShortName(out); 8581 if (count > 1) { 8582 out.print(" ("); out.print(count); out.print(" filters)"); 8583 } 8584 out.println(); 8585 } 8586 8587 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8588 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8589 private int mFlags; 8590 }; 8591 8592 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8593 new Comparator<ResolveInfo>() { 8594 public int compare(ResolveInfo r1, ResolveInfo r2) { 8595 int v1 = r1.priority; 8596 int v2 = r2.priority; 8597 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8598 if (v1 != v2) { 8599 return (v1 > v2) ? -1 : 1; 8600 } 8601 v1 = r1.preferredOrder; 8602 v2 = r2.preferredOrder; 8603 if (v1 != v2) { 8604 return (v1 > v2) ? -1 : 1; 8605 } 8606 if (r1.isDefault != r2.isDefault) { 8607 return r1.isDefault ? -1 : 1; 8608 } 8609 v1 = r1.match; 8610 v2 = r2.match; 8611 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8612 if (v1 != v2) { 8613 return (v1 > v2) ? -1 : 1; 8614 } 8615 if (r1.system != r2.system) { 8616 return r1.system ? -1 : 1; 8617 } 8618 return 0; 8619 } 8620 }; 8621 8622 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8623 new Comparator<ProviderInfo>() { 8624 public int compare(ProviderInfo p1, ProviderInfo p2) { 8625 final int v1 = p1.initOrder; 8626 final int v2 = p2.initOrder; 8627 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8628 } 8629 }; 8630 8631 final void sendPackageBroadcast(final String action, final String pkg, 8632 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8633 final int[] userIds) { 8634 mHandler.post(new Runnable() { 8635 @Override 8636 public void run() { 8637 try { 8638 final IActivityManager am = ActivityManagerNative.getDefault(); 8639 if (am == null) return; 8640 final int[] resolvedUserIds; 8641 if (userIds == null) { 8642 resolvedUserIds = am.getRunningUserIds(); 8643 } else { 8644 resolvedUserIds = userIds; 8645 } 8646 for (int id : resolvedUserIds) { 8647 final Intent intent = new Intent(action, 8648 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8649 if (extras != null) { 8650 intent.putExtras(extras); 8651 } 8652 if (targetPkg != null) { 8653 intent.setPackage(targetPkg); 8654 } 8655 // Modify the UID when posting to other users 8656 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8657 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8658 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8659 intent.putExtra(Intent.EXTRA_UID, uid); 8660 } 8661 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8662 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8663 if (DEBUG_BROADCASTS) { 8664 RuntimeException here = new RuntimeException("here"); 8665 here.fillInStackTrace(); 8666 Slog.d(TAG, "Sending to user " + id + ": " 8667 + intent.toShortString(false, true, false, false) 8668 + " " + intent.getExtras(), here); 8669 } 8670 am.broadcastIntent(null, intent, null, finishedReceiver, 8671 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8672 finishedReceiver != null, false, id); 8673 } 8674 } catch (RemoteException ex) { 8675 } 8676 } 8677 }); 8678 } 8679 8680 /** 8681 * Check if the external storage media is available. This is true if there 8682 * is a mounted external storage medium or if the external storage is 8683 * emulated. 8684 */ 8685 private boolean isExternalMediaAvailable() { 8686 return mMediaMounted || Environment.isExternalStorageEmulated(); 8687 } 8688 8689 @Override 8690 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8691 // writer 8692 synchronized (mPackages) { 8693 if (!isExternalMediaAvailable()) { 8694 // If the external storage is no longer mounted at this point, 8695 // the caller may not have been able to delete all of this 8696 // packages files and can not delete any more. Bail. 8697 return null; 8698 } 8699 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8700 if (lastPackage != null) { 8701 pkgs.remove(lastPackage); 8702 } 8703 if (pkgs.size() > 0) { 8704 return pkgs.get(0); 8705 } 8706 } 8707 return null; 8708 } 8709 8710 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8711 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8712 userId, andCode ? 1 : 0, packageName); 8713 if (mSystemReady) { 8714 msg.sendToTarget(); 8715 } else { 8716 if (mPostSystemReadyMessages == null) { 8717 mPostSystemReadyMessages = new ArrayList<>(); 8718 } 8719 mPostSystemReadyMessages.add(msg); 8720 } 8721 } 8722 8723 void startCleaningPackages() { 8724 // reader 8725 synchronized (mPackages) { 8726 if (!isExternalMediaAvailable()) { 8727 return; 8728 } 8729 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8730 return; 8731 } 8732 } 8733 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8734 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8735 IActivityManager am = ActivityManagerNative.getDefault(); 8736 if (am != null) { 8737 try { 8738 am.startService(null, intent, null, UserHandle.USER_OWNER); 8739 } catch (RemoteException e) { 8740 } 8741 } 8742 } 8743 8744 @Override 8745 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8746 int installFlags, String installerPackageName, VerificationParams verificationParams, 8747 String packageAbiOverride) { 8748 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8749 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8750 } 8751 8752 @Override 8753 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8754 int installFlags, String installerPackageName, VerificationParams verificationParams, 8755 String packageAbiOverride, int userId) { 8756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8757 8758 final int callingUid = Binder.getCallingUid(); 8759 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8760 8761 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8762 try { 8763 if (observer != null) { 8764 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8765 } 8766 } catch (RemoteException re) { 8767 } 8768 return; 8769 } 8770 8771 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8772 installFlags |= PackageManager.INSTALL_FROM_ADB; 8773 8774 } else { 8775 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8776 // about installerPackageName. 8777 8778 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8779 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8780 } 8781 8782 UserHandle user; 8783 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8784 user = UserHandle.ALL; 8785 } else { 8786 user = new UserHandle(userId); 8787 } 8788 8789 // Only system components can circumvent runtime permissions when installing. 8790 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8791 && mContext.checkCallingOrSelfPermission(Manifest.permission 8792 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8793 throw new SecurityException("You need the " 8794 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8795 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8796 } 8797 8798 verificationParams.setInstallerUid(callingUid); 8799 8800 final File originFile = new File(originPath); 8801 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8802 8803 final Message msg = mHandler.obtainMessage(INIT_COPY); 8804 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8805 null, verificationParams, user, packageAbiOverride); 8806 mHandler.sendMessage(msg); 8807 } 8808 8809 void installStage(String packageName, File stagedDir, String stagedCid, 8810 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8811 String installerPackageName, int installerUid, UserHandle user) { 8812 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8813 params.referrerUri, installerUid, null); 8814 8815 final OriginInfo origin; 8816 if (stagedDir != null) { 8817 origin = OriginInfo.fromStagedFile(stagedDir); 8818 } else { 8819 origin = OriginInfo.fromStagedContainer(stagedCid); 8820 } 8821 8822 final Message msg = mHandler.obtainMessage(INIT_COPY); 8823 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8824 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8825 mHandler.sendMessage(msg); 8826 } 8827 8828 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8829 Bundle extras = new Bundle(1); 8830 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8831 8832 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8833 packageName, extras, null, null, new int[] {userId}); 8834 try { 8835 IActivityManager am = ActivityManagerNative.getDefault(); 8836 final boolean isSystem = 8837 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8838 if (isSystem && am.isUserRunning(userId, false)) { 8839 // The just-installed/enabled app is bundled on the system, so presumed 8840 // to be able to run automatically without needing an explicit launch. 8841 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8842 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8843 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8844 .setPackage(packageName); 8845 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8846 android.app.AppOpsManager.OP_NONE, false, false, userId); 8847 } 8848 } catch (RemoteException e) { 8849 // shouldn't happen 8850 Slog.w(TAG, "Unable to bootstrap installed package", e); 8851 } 8852 } 8853 8854 @Override 8855 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8856 int userId) { 8857 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8858 PackageSetting pkgSetting; 8859 final int uid = Binder.getCallingUid(); 8860 enforceCrossUserPermission(uid, userId, true, true, 8861 "setApplicationHiddenSetting for user " + userId); 8862 8863 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8864 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8865 return false; 8866 } 8867 8868 long callingId = Binder.clearCallingIdentity(); 8869 try { 8870 boolean sendAdded = false; 8871 boolean sendRemoved = false; 8872 // writer 8873 synchronized (mPackages) { 8874 pkgSetting = mSettings.mPackages.get(packageName); 8875 if (pkgSetting == null) { 8876 return false; 8877 } 8878 if (pkgSetting.getHidden(userId) != hidden) { 8879 pkgSetting.setHidden(hidden, userId); 8880 mSettings.writePackageRestrictionsLPr(userId); 8881 if (hidden) { 8882 sendRemoved = true; 8883 } else { 8884 sendAdded = true; 8885 } 8886 } 8887 } 8888 if (sendAdded) { 8889 sendPackageAddedForUser(packageName, pkgSetting, userId); 8890 return true; 8891 } 8892 if (sendRemoved) { 8893 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8894 "hiding pkg"); 8895 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8896 } 8897 } finally { 8898 Binder.restoreCallingIdentity(callingId); 8899 } 8900 return false; 8901 } 8902 8903 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8904 int userId) { 8905 final PackageRemovedInfo info = new PackageRemovedInfo(); 8906 info.removedPackage = packageName; 8907 info.removedUsers = new int[] {userId}; 8908 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8909 info.sendBroadcast(false, false, false); 8910 } 8911 8912 /** 8913 * Returns true if application is not found or there was an error. Otherwise it returns 8914 * the hidden state of the package for the given user. 8915 */ 8916 @Override 8917 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8918 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8919 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8920 false, "getApplicationHidden for user " + userId); 8921 PackageSetting pkgSetting; 8922 long callingId = Binder.clearCallingIdentity(); 8923 try { 8924 // writer 8925 synchronized (mPackages) { 8926 pkgSetting = mSettings.mPackages.get(packageName); 8927 if (pkgSetting == null) { 8928 return true; 8929 } 8930 return pkgSetting.getHidden(userId); 8931 } 8932 } finally { 8933 Binder.restoreCallingIdentity(callingId); 8934 } 8935 } 8936 8937 /** 8938 * @hide 8939 */ 8940 @Override 8941 public int installExistingPackageAsUser(String packageName, int userId) { 8942 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8943 null); 8944 PackageSetting pkgSetting; 8945 final int uid = Binder.getCallingUid(); 8946 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8947 + userId); 8948 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8949 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8950 } 8951 8952 long callingId = Binder.clearCallingIdentity(); 8953 try { 8954 boolean sendAdded = false; 8955 8956 // writer 8957 synchronized (mPackages) { 8958 pkgSetting = mSettings.mPackages.get(packageName); 8959 if (pkgSetting == null) { 8960 return PackageManager.INSTALL_FAILED_INVALID_URI; 8961 } 8962 if (!pkgSetting.getInstalled(userId)) { 8963 pkgSetting.setInstalled(true, userId); 8964 pkgSetting.setHidden(false, userId); 8965 mSettings.writePackageRestrictionsLPr(userId); 8966 sendAdded = true; 8967 } 8968 } 8969 8970 if (sendAdded) { 8971 sendPackageAddedForUser(packageName, pkgSetting, userId); 8972 } 8973 } finally { 8974 Binder.restoreCallingIdentity(callingId); 8975 } 8976 8977 return PackageManager.INSTALL_SUCCEEDED; 8978 } 8979 8980 boolean isUserRestricted(int userId, String restrictionKey) { 8981 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8982 if (restrictions.getBoolean(restrictionKey, false)) { 8983 Log.w(TAG, "User is restricted: " + restrictionKey); 8984 return true; 8985 } 8986 return false; 8987 } 8988 8989 @Override 8990 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8991 mContext.enforceCallingOrSelfPermission( 8992 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8993 "Only package verification agents can verify applications"); 8994 8995 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8996 final PackageVerificationResponse response = new PackageVerificationResponse( 8997 verificationCode, Binder.getCallingUid()); 8998 msg.arg1 = id; 8999 msg.obj = response; 9000 mHandler.sendMessage(msg); 9001 } 9002 9003 @Override 9004 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9005 long millisecondsToDelay) { 9006 mContext.enforceCallingOrSelfPermission( 9007 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9008 "Only package verification agents can extend verification timeouts"); 9009 9010 final PackageVerificationState state = mPendingVerification.get(id); 9011 final PackageVerificationResponse response = new PackageVerificationResponse( 9012 verificationCodeAtTimeout, Binder.getCallingUid()); 9013 9014 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9015 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9016 } 9017 if (millisecondsToDelay < 0) { 9018 millisecondsToDelay = 0; 9019 } 9020 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9021 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9022 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9023 } 9024 9025 if ((state != null) && !state.timeoutExtended()) { 9026 state.extendTimeout(); 9027 9028 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9029 msg.arg1 = id; 9030 msg.obj = response; 9031 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9032 } 9033 } 9034 9035 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9036 int verificationCode, UserHandle user) { 9037 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9038 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9039 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9040 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9041 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9042 9043 mContext.sendBroadcastAsUser(intent, user, 9044 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9045 } 9046 9047 private ComponentName matchComponentForVerifier(String packageName, 9048 List<ResolveInfo> receivers) { 9049 ActivityInfo targetReceiver = null; 9050 9051 final int NR = receivers.size(); 9052 for (int i = 0; i < NR; i++) { 9053 final ResolveInfo info = receivers.get(i); 9054 if (info.activityInfo == null) { 9055 continue; 9056 } 9057 9058 if (packageName.equals(info.activityInfo.packageName)) { 9059 targetReceiver = info.activityInfo; 9060 break; 9061 } 9062 } 9063 9064 if (targetReceiver == null) { 9065 return null; 9066 } 9067 9068 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9069 } 9070 9071 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9072 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9073 if (pkgInfo.verifiers.length == 0) { 9074 return null; 9075 } 9076 9077 final int N = pkgInfo.verifiers.length; 9078 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9079 for (int i = 0; i < N; i++) { 9080 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9081 9082 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9083 receivers); 9084 if (comp == null) { 9085 continue; 9086 } 9087 9088 final int verifierUid = getUidForVerifier(verifierInfo); 9089 if (verifierUid == -1) { 9090 continue; 9091 } 9092 9093 if (DEBUG_VERIFY) { 9094 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9095 + " with the correct signature"); 9096 } 9097 sufficientVerifiers.add(comp); 9098 verificationState.addSufficientVerifier(verifierUid); 9099 } 9100 9101 return sufficientVerifiers; 9102 } 9103 9104 private int getUidForVerifier(VerifierInfo verifierInfo) { 9105 synchronized (mPackages) { 9106 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9107 if (pkg == null) { 9108 return -1; 9109 } else if (pkg.mSignatures.length != 1) { 9110 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9111 + " has more than one signature; ignoring"); 9112 return -1; 9113 } 9114 9115 /* 9116 * If the public key of the package's signature does not match 9117 * our expected public key, then this is a different package and 9118 * we should skip. 9119 */ 9120 9121 final byte[] expectedPublicKey; 9122 try { 9123 final Signature verifierSig = pkg.mSignatures[0]; 9124 final PublicKey publicKey = verifierSig.getPublicKey(); 9125 expectedPublicKey = publicKey.getEncoded(); 9126 } catch (CertificateException e) { 9127 return -1; 9128 } 9129 9130 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9131 9132 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9133 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9134 + " does not have the expected public key; ignoring"); 9135 return -1; 9136 } 9137 9138 return pkg.applicationInfo.uid; 9139 } 9140 } 9141 9142 @Override 9143 public void finishPackageInstall(int token) { 9144 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9145 9146 if (DEBUG_INSTALL) { 9147 Slog.v(TAG, "BM finishing package install for " + token); 9148 } 9149 9150 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9151 mHandler.sendMessage(msg); 9152 } 9153 9154 /** 9155 * Get the verification agent timeout. 9156 * 9157 * @return verification timeout in milliseconds 9158 */ 9159 private long getVerificationTimeout() { 9160 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9161 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9162 DEFAULT_VERIFICATION_TIMEOUT); 9163 } 9164 9165 /** 9166 * Get the default verification agent response code. 9167 * 9168 * @return default verification response code 9169 */ 9170 private int getDefaultVerificationResponse() { 9171 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9172 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9173 DEFAULT_VERIFICATION_RESPONSE); 9174 } 9175 9176 /** 9177 * Check whether or not package verification has been enabled. 9178 * 9179 * @return true if verification should be performed 9180 */ 9181 private boolean isVerificationEnabled(int userId, int installFlags) { 9182 if (!DEFAULT_VERIFY_ENABLE) { 9183 return false; 9184 } 9185 9186 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9187 9188 // Check if installing from ADB 9189 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9190 // Do not run verification in a test harness environment 9191 if (ActivityManager.isRunningInTestHarness()) { 9192 return false; 9193 } 9194 if (ensureVerifyAppsEnabled) { 9195 return true; 9196 } 9197 // Check if the developer does not want package verification for ADB installs 9198 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9199 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9200 return false; 9201 } 9202 } 9203 9204 if (ensureVerifyAppsEnabled) { 9205 return true; 9206 } 9207 9208 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9209 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9210 } 9211 9212 @Override 9213 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9214 throws RemoteException { 9215 mContext.enforceCallingOrSelfPermission( 9216 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9217 "Only intentfilter verification agents can verify applications"); 9218 9219 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9220 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9221 Binder.getCallingUid(), verificationCode, failedDomains); 9222 msg.arg1 = id; 9223 msg.obj = response; 9224 mHandler.sendMessage(msg); 9225 } 9226 9227 @Override 9228 public int getIntentVerificationStatus(String packageName, int userId) { 9229 synchronized (mPackages) { 9230 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9231 } 9232 } 9233 9234 @Override 9235 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9236 boolean result = false; 9237 synchronized (mPackages) { 9238 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9239 } 9240 if (result) { 9241 scheduleWritePackageRestrictionsLocked(userId); 9242 } 9243 return result; 9244 } 9245 9246 @Override 9247 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9248 synchronized (mPackages) { 9249 return mSettings.getIntentFilterVerificationsLPr(packageName); 9250 } 9251 } 9252 9253 @Override 9254 public List<IntentFilter> getAllIntentFilters(String packageName) { 9255 if (TextUtils.isEmpty(packageName)) { 9256 return Collections.<IntentFilter>emptyList(); 9257 } 9258 synchronized (mPackages) { 9259 PackageParser.Package pkg = mPackages.get(packageName); 9260 if (pkg == null || pkg.activities == null) { 9261 return Collections.<IntentFilter>emptyList(); 9262 } 9263 final int count = pkg.activities.size(); 9264 ArrayList<IntentFilter> result = new ArrayList<>(); 9265 for (int n=0; n<count; n++) { 9266 PackageParser.Activity activity = pkg.activities.get(n); 9267 if (activity.intents != null || activity.intents.size() > 0) { 9268 result.addAll(activity.intents); 9269 } 9270 } 9271 return result; 9272 } 9273 } 9274 9275 @Override 9276 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9277 synchronized (mPackages) { 9278 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9279 if (packageName != null) { 9280 result |= updateIntentVerificationStatus(packageName, 9281 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9282 UserHandle.myUserId()); 9283 } 9284 return result; 9285 } 9286 } 9287 9288 @Override 9289 public String getDefaultBrowserPackageName(int userId) { 9290 synchronized (mPackages) { 9291 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9292 } 9293 } 9294 9295 /** 9296 * Get the "allow unknown sources" setting. 9297 * 9298 * @return the current "allow unknown sources" setting 9299 */ 9300 private int getUnknownSourcesSettings() { 9301 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9302 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9303 -1); 9304 } 9305 9306 @Override 9307 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9308 final int uid = Binder.getCallingUid(); 9309 // writer 9310 synchronized (mPackages) { 9311 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9312 if (targetPackageSetting == null) { 9313 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9314 } 9315 9316 PackageSetting installerPackageSetting; 9317 if (installerPackageName != null) { 9318 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9319 if (installerPackageSetting == null) { 9320 throw new IllegalArgumentException("Unknown installer package: " 9321 + installerPackageName); 9322 } 9323 } else { 9324 installerPackageSetting = null; 9325 } 9326 9327 Signature[] callerSignature; 9328 Object obj = mSettings.getUserIdLPr(uid); 9329 if (obj != null) { 9330 if (obj instanceof SharedUserSetting) { 9331 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9332 } else if (obj instanceof PackageSetting) { 9333 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9334 } else { 9335 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9336 } 9337 } else { 9338 throw new SecurityException("Unknown calling uid " + uid); 9339 } 9340 9341 // Verify: can't set installerPackageName to a package that is 9342 // not signed with the same cert as the caller. 9343 if (installerPackageSetting != null) { 9344 if (compareSignatures(callerSignature, 9345 installerPackageSetting.signatures.mSignatures) 9346 != PackageManager.SIGNATURE_MATCH) { 9347 throw new SecurityException( 9348 "Caller does not have same cert as new installer package " 9349 + installerPackageName); 9350 } 9351 } 9352 9353 // Verify: if target already has an installer package, it must 9354 // be signed with the same cert as the caller. 9355 if (targetPackageSetting.installerPackageName != null) { 9356 PackageSetting setting = mSettings.mPackages.get( 9357 targetPackageSetting.installerPackageName); 9358 // If the currently set package isn't valid, then it's always 9359 // okay to change it. 9360 if (setting != null) { 9361 if (compareSignatures(callerSignature, 9362 setting.signatures.mSignatures) 9363 != PackageManager.SIGNATURE_MATCH) { 9364 throw new SecurityException( 9365 "Caller does not have same cert as old installer package " 9366 + targetPackageSetting.installerPackageName); 9367 } 9368 } 9369 } 9370 9371 // Okay! 9372 targetPackageSetting.installerPackageName = installerPackageName; 9373 scheduleWriteSettingsLocked(); 9374 } 9375 } 9376 9377 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9378 // Queue up an async operation since the package installation may take a little while. 9379 mHandler.post(new Runnable() { 9380 public void run() { 9381 mHandler.removeCallbacks(this); 9382 // Result object to be returned 9383 PackageInstalledInfo res = new PackageInstalledInfo(); 9384 res.returnCode = currentStatus; 9385 res.uid = -1; 9386 res.pkg = null; 9387 res.removedInfo = new PackageRemovedInfo(); 9388 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9389 args.doPreInstall(res.returnCode); 9390 synchronized (mInstallLock) { 9391 installPackageLI(args, res); 9392 } 9393 args.doPostInstall(res.returnCode, res.uid); 9394 } 9395 9396 // A restore should be performed at this point if (a) the install 9397 // succeeded, (b) the operation is not an update, and (c) the new 9398 // package has not opted out of backup participation. 9399 final boolean update = res.removedInfo.removedPackage != null; 9400 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9401 boolean doRestore = !update 9402 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9403 9404 // Set up the post-install work request bookkeeping. This will be used 9405 // and cleaned up by the post-install event handling regardless of whether 9406 // there's a restore pass performed. Token values are >= 1. 9407 int token; 9408 if (mNextInstallToken < 0) mNextInstallToken = 1; 9409 token = mNextInstallToken++; 9410 9411 PostInstallData data = new PostInstallData(args, res); 9412 mRunningInstalls.put(token, data); 9413 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9414 9415 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9416 // Pass responsibility to the Backup Manager. It will perform a 9417 // restore if appropriate, then pass responsibility back to the 9418 // Package Manager to run the post-install observer callbacks 9419 // and broadcasts. 9420 IBackupManager bm = IBackupManager.Stub.asInterface( 9421 ServiceManager.getService(Context.BACKUP_SERVICE)); 9422 if (bm != null) { 9423 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9424 + " to BM for possible restore"); 9425 try { 9426 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9427 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9428 } else { 9429 doRestore = false; 9430 } 9431 } catch (RemoteException e) { 9432 // can't happen; the backup manager is local 9433 } catch (Exception e) { 9434 Slog.e(TAG, "Exception trying to enqueue restore", e); 9435 doRestore = false; 9436 } 9437 } else { 9438 Slog.e(TAG, "Backup Manager not found!"); 9439 doRestore = false; 9440 } 9441 } 9442 9443 if (!doRestore) { 9444 // No restore possible, or the Backup Manager was mysteriously not 9445 // available -- just fire the post-install work request directly. 9446 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9447 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9448 mHandler.sendMessage(msg); 9449 } 9450 } 9451 }); 9452 } 9453 9454 private abstract class HandlerParams { 9455 private static final int MAX_RETRIES = 4; 9456 9457 /** 9458 * Number of times startCopy() has been attempted and had a non-fatal 9459 * error. 9460 */ 9461 private int mRetries = 0; 9462 9463 /** User handle for the user requesting the information or installation. */ 9464 private final UserHandle mUser; 9465 9466 HandlerParams(UserHandle user) { 9467 mUser = user; 9468 } 9469 9470 UserHandle getUser() { 9471 return mUser; 9472 } 9473 9474 final boolean startCopy() { 9475 boolean res; 9476 try { 9477 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9478 9479 if (++mRetries > MAX_RETRIES) { 9480 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9481 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9482 handleServiceError(); 9483 return false; 9484 } else { 9485 handleStartCopy(); 9486 res = true; 9487 } 9488 } catch (RemoteException e) { 9489 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9490 mHandler.sendEmptyMessage(MCS_RECONNECT); 9491 res = false; 9492 } 9493 handleReturnCode(); 9494 return res; 9495 } 9496 9497 final void serviceError() { 9498 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9499 handleServiceError(); 9500 handleReturnCode(); 9501 } 9502 9503 abstract void handleStartCopy() throws RemoteException; 9504 abstract void handleServiceError(); 9505 abstract void handleReturnCode(); 9506 } 9507 9508 class MeasureParams extends HandlerParams { 9509 private final PackageStats mStats; 9510 private boolean mSuccess; 9511 9512 private final IPackageStatsObserver mObserver; 9513 9514 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9515 super(new UserHandle(stats.userHandle)); 9516 mObserver = observer; 9517 mStats = stats; 9518 } 9519 9520 @Override 9521 public String toString() { 9522 return "MeasureParams{" 9523 + Integer.toHexString(System.identityHashCode(this)) 9524 + " " + mStats.packageName + "}"; 9525 } 9526 9527 @Override 9528 void handleStartCopy() throws RemoteException { 9529 synchronized (mInstallLock) { 9530 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9531 } 9532 9533 if (mSuccess) { 9534 final boolean mounted; 9535 if (Environment.isExternalStorageEmulated()) { 9536 mounted = true; 9537 } else { 9538 final String status = Environment.getExternalStorageState(); 9539 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9540 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9541 } 9542 9543 if (mounted) { 9544 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9545 9546 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9547 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9548 9549 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9550 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9551 9552 // Always subtract cache size, since it's a subdirectory 9553 mStats.externalDataSize -= mStats.externalCacheSize; 9554 9555 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9556 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9557 9558 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9559 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9560 } 9561 } 9562 } 9563 9564 @Override 9565 void handleReturnCode() { 9566 if (mObserver != null) { 9567 try { 9568 mObserver.onGetStatsCompleted(mStats, mSuccess); 9569 } catch (RemoteException e) { 9570 Slog.i(TAG, "Observer no longer exists."); 9571 } 9572 } 9573 } 9574 9575 @Override 9576 void handleServiceError() { 9577 Slog.e(TAG, "Could not measure application " + mStats.packageName 9578 + " external storage"); 9579 } 9580 } 9581 9582 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9583 throws RemoteException { 9584 long result = 0; 9585 for (File path : paths) { 9586 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9587 } 9588 return result; 9589 } 9590 9591 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9592 for (File path : paths) { 9593 try { 9594 mcs.clearDirectory(path.getAbsolutePath()); 9595 } catch (RemoteException e) { 9596 } 9597 } 9598 } 9599 9600 static class OriginInfo { 9601 /** 9602 * Location where install is coming from, before it has been 9603 * copied/renamed into place. This could be a single monolithic APK 9604 * file, or a cluster directory. This location may be untrusted. 9605 */ 9606 final File file; 9607 final String cid; 9608 9609 /** 9610 * Flag indicating that {@link #file} or {@link #cid} has already been 9611 * staged, meaning downstream users don't need to defensively copy the 9612 * contents. 9613 */ 9614 final boolean staged; 9615 9616 /** 9617 * Flag indicating that {@link #file} or {@link #cid} is an already 9618 * installed app that is being moved. 9619 */ 9620 final boolean existing; 9621 9622 final String resolvedPath; 9623 final File resolvedFile; 9624 9625 static OriginInfo fromNothing() { 9626 return new OriginInfo(null, null, false, false); 9627 } 9628 9629 static OriginInfo fromUntrustedFile(File file) { 9630 return new OriginInfo(file, null, false, false); 9631 } 9632 9633 static OriginInfo fromExistingFile(File file) { 9634 return new OriginInfo(file, null, false, true); 9635 } 9636 9637 static OriginInfo fromStagedFile(File file) { 9638 return new OriginInfo(file, null, true, false); 9639 } 9640 9641 static OriginInfo fromStagedContainer(String cid) { 9642 return new OriginInfo(null, cid, true, false); 9643 } 9644 9645 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9646 this.file = file; 9647 this.cid = cid; 9648 this.staged = staged; 9649 this.existing = existing; 9650 9651 if (cid != null) { 9652 resolvedPath = PackageHelper.getSdDir(cid); 9653 resolvedFile = new File(resolvedPath); 9654 } else if (file != null) { 9655 resolvedPath = file.getAbsolutePath(); 9656 resolvedFile = file; 9657 } else { 9658 resolvedPath = null; 9659 resolvedFile = null; 9660 } 9661 } 9662 } 9663 9664 class MoveInfo { 9665 final int moveId; 9666 final String fromUuid; 9667 final String toUuid; 9668 final String packageName; 9669 final String dataAppName; 9670 final int appId; 9671 final String seinfo; 9672 9673 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9674 String dataAppName, int appId, String seinfo) { 9675 this.moveId = moveId; 9676 this.fromUuid = fromUuid; 9677 this.toUuid = toUuid; 9678 this.packageName = packageName; 9679 this.dataAppName = dataAppName; 9680 this.appId = appId; 9681 this.seinfo = seinfo; 9682 } 9683 } 9684 9685 class InstallParams extends HandlerParams { 9686 final OriginInfo origin; 9687 final MoveInfo move; 9688 final IPackageInstallObserver2 observer; 9689 int installFlags; 9690 final String installerPackageName; 9691 final String volumeUuid; 9692 final VerificationParams verificationParams; 9693 private InstallArgs mArgs; 9694 private int mRet; 9695 final String packageAbiOverride; 9696 9697 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9698 int installFlags, String installerPackageName, String volumeUuid, 9699 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9700 super(user); 9701 this.origin = origin; 9702 this.move = move; 9703 this.observer = observer; 9704 this.installFlags = installFlags; 9705 this.installerPackageName = installerPackageName; 9706 this.volumeUuid = volumeUuid; 9707 this.verificationParams = verificationParams; 9708 this.packageAbiOverride = packageAbiOverride; 9709 } 9710 9711 @Override 9712 public String toString() { 9713 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9714 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9715 } 9716 9717 public ManifestDigest getManifestDigest() { 9718 if (verificationParams == null) { 9719 return null; 9720 } 9721 return verificationParams.getManifestDigest(); 9722 } 9723 9724 private int installLocationPolicy(PackageInfoLite pkgLite) { 9725 String packageName = pkgLite.packageName; 9726 int installLocation = pkgLite.installLocation; 9727 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9728 // reader 9729 synchronized (mPackages) { 9730 PackageParser.Package pkg = mPackages.get(packageName); 9731 if (pkg != null) { 9732 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9733 // Check for downgrading. 9734 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9735 try { 9736 checkDowngrade(pkg, pkgLite); 9737 } catch (PackageManagerException e) { 9738 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9739 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9740 } 9741 } 9742 // Check for updated system application. 9743 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9744 if (onSd) { 9745 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9746 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9747 } 9748 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9749 } else { 9750 if (onSd) { 9751 // Install flag overrides everything. 9752 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9753 } 9754 // If current upgrade specifies particular preference 9755 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9756 // Application explicitly specified internal. 9757 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9758 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9759 // App explictly prefers external. Let policy decide 9760 } else { 9761 // Prefer previous location 9762 if (isExternal(pkg)) { 9763 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9764 } 9765 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9766 } 9767 } 9768 } else { 9769 // Invalid install. Return error code 9770 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9771 } 9772 } 9773 } 9774 // All the special cases have been taken care of. 9775 // Return result based on recommended install location. 9776 if (onSd) { 9777 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9778 } 9779 return pkgLite.recommendedInstallLocation; 9780 } 9781 9782 /* 9783 * Invoke remote method to get package information and install 9784 * location values. Override install location based on default 9785 * policy if needed and then create install arguments based 9786 * on the install location. 9787 */ 9788 public void handleStartCopy() throws RemoteException { 9789 int ret = PackageManager.INSTALL_SUCCEEDED; 9790 9791 // If we're already staged, we've firmly committed to an install location 9792 if (origin.staged) { 9793 if (origin.file != null) { 9794 installFlags |= PackageManager.INSTALL_INTERNAL; 9795 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9796 } else if (origin.cid != null) { 9797 installFlags |= PackageManager.INSTALL_EXTERNAL; 9798 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9799 } else { 9800 throw new IllegalStateException("Invalid stage location"); 9801 } 9802 } 9803 9804 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9805 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9806 9807 PackageInfoLite pkgLite = null; 9808 9809 if (onInt && onSd) { 9810 // Check if both bits are set. 9811 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9812 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9813 } else { 9814 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9815 packageAbiOverride); 9816 9817 /* 9818 * If we have too little free space, try to free cache 9819 * before giving up. 9820 */ 9821 if (!origin.staged && pkgLite.recommendedInstallLocation 9822 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9823 // TODO: focus freeing disk space on the target device 9824 final StorageManager storage = StorageManager.from(mContext); 9825 final long lowThreshold = storage.getStorageLowBytes( 9826 Environment.getDataDirectory()); 9827 9828 final long sizeBytes = mContainerService.calculateInstalledSize( 9829 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9830 9831 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9832 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9833 installFlags, packageAbiOverride); 9834 } 9835 9836 /* 9837 * The cache free must have deleted the file we 9838 * downloaded to install. 9839 * 9840 * TODO: fix the "freeCache" call to not delete 9841 * the file we care about. 9842 */ 9843 if (pkgLite.recommendedInstallLocation 9844 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9845 pkgLite.recommendedInstallLocation 9846 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9847 } 9848 } 9849 } 9850 9851 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9852 int loc = pkgLite.recommendedInstallLocation; 9853 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9854 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9855 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9856 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9857 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9858 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9859 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9860 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9861 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9862 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9863 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9864 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9865 } else { 9866 // Override with defaults if needed. 9867 loc = installLocationPolicy(pkgLite); 9868 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9869 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9870 } else if (!onSd && !onInt) { 9871 // Override install location with flags 9872 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9873 // Set the flag to install on external media. 9874 installFlags |= PackageManager.INSTALL_EXTERNAL; 9875 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9876 } else { 9877 // Make sure the flag for installing on external 9878 // media is unset 9879 installFlags |= PackageManager.INSTALL_INTERNAL; 9880 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9881 } 9882 } 9883 } 9884 } 9885 9886 final InstallArgs args = createInstallArgs(this); 9887 mArgs = args; 9888 9889 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9890 /* 9891 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9892 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9893 */ 9894 int userIdentifier = getUser().getIdentifier(); 9895 if (userIdentifier == UserHandle.USER_ALL 9896 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9897 userIdentifier = UserHandle.USER_OWNER; 9898 } 9899 9900 /* 9901 * Determine if we have any installed package verifiers. If we 9902 * do, then we'll defer to them to verify the packages. 9903 */ 9904 final int requiredUid = mRequiredVerifierPackage == null ? -1 9905 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9906 if (!origin.existing && requiredUid != -1 9907 && isVerificationEnabled(userIdentifier, installFlags)) { 9908 final Intent verification = new Intent( 9909 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9910 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9911 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9912 PACKAGE_MIME_TYPE); 9913 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9914 9915 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9916 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9917 0 /* TODO: Which userId? */); 9918 9919 if (DEBUG_VERIFY) { 9920 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9921 + verification.toString() + " with " + pkgLite.verifiers.length 9922 + " optional verifiers"); 9923 } 9924 9925 final int verificationId = mPendingVerificationToken++; 9926 9927 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9928 9929 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9930 installerPackageName); 9931 9932 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9933 installFlags); 9934 9935 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9936 pkgLite.packageName); 9937 9938 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9939 pkgLite.versionCode); 9940 9941 if (verificationParams != null) { 9942 if (verificationParams.getVerificationURI() != null) { 9943 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9944 verificationParams.getVerificationURI()); 9945 } 9946 if (verificationParams.getOriginatingURI() != null) { 9947 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9948 verificationParams.getOriginatingURI()); 9949 } 9950 if (verificationParams.getReferrer() != null) { 9951 verification.putExtra(Intent.EXTRA_REFERRER, 9952 verificationParams.getReferrer()); 9953 } 9954 if (verificationParams.getOriginatingUid() >= 0) { 9955 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9956 verificationParams.getOriginatingUid()); 9957 } 9958 if (verificationParams.getInstallerUid() >= 0) { 9959 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9960 verificationParams.getInstallerUid()); 9961 } 9962 } 9963 9964 final PackageVerificationState verificationState = new PackageVerificationState( 9965 requiredUid, args); 9966 9967 mPendingVerification.append(verificationId, verificationState); 9968 9969 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9970 receivers, verificationState); 9971 9972 /* 9973 * If any sufficient verifiers were listed in the package 9974 * manifest, attempt to ask them. 9975 */ 9976 if (sufficientVerifiers != null) { 9977 final int N = sufficientVerifiers.size(); 9978 if (N == 0) { 9979 Slog.i(TAG, "Additional verifiers required, but none installed."); 9980 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9981 } else { 9982 for (int i = 0; i < N; i++) { 9983 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9984 9985 final Intent sufficientIntent = new Intent(verification); 9986 sufficientIntent.setComponent(verifierComponent); 9987 9988 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9989 } 9990 } 9991 } 9992 9993 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9994 mRequiredVerifierPackage, receivers); 9995 if (ret == PackageManager.INSTALL_SUCCEEDED 9996 && mRequiredVerifierPackage != null) { 9997 /* 9998 * Send the intent to the required verification agent, 9999 * but only start the verification timeout after the 10000 * target BroadcastReceivers have run. 10001 */ 10002 verification.setComponent(requiredVerifierComponent); 10003 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10004 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10005 new BroadcastReceiver() { 10006 @Override 10007 public void onReceive(Context context, Intent intent) { 10008 final Message msg = mHandler 10009 .obtainMessage(CHECK_PENDING_VERIFICATION); 10010 msg.arg1 = verificationId; 10011 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10012 } 10013 }, null, 0, null, null); 10014 10015 /* 10016 * We don't want the copy to proceed until verification 10017 * succeeds, so null out this field. 10018 */ 10019 mArgs = null; 10020 } 10021 } else { 10022 /* 10023 * No package verification is enabled, so immediately start 10024 * the remote call to initiate copy using temporary file. 10025 */ 10026 ret = args.copyApk(mContainerService, true); 10027 } 10028 } 10029 10030 mRet = ret; 10031 } 10032 10033 @Override 10034 void handleReturnCode() { 10035 // If mArgs is null, then MCS couldn't be reached. When it 10036 // reconnects, it will try again to install. At that point, this 10037 // will succeed. 10038 if (mArgs != null) { 10039 processPendingInstall(mArgs, mRet); 10040 } 10041 } 10042 10043 @Override 10044 void handleServiceError() { 10045 mArgs = createInstallArgs(this); 10046 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10047 } 10048 10049 public boolean isForwardLocked() { 10050 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10051 } 10052 } 10053 10054 /** 10055 * Used during creation of InstallArgs 10056 * 10057 * @param installFlags package installation flags 10058 * @return true if should be installed on external storage 10059 */ 10060 private static boolean installOnExternalAsec(int installFlags) { 10061 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10062 return false; 10063 } 10064 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10065 return true; 10066 } 10067 return false; 10068 } 10069 10070 /** 10071 * Used during creation of InstallArgs 10072 * 10073 * @param installFlags package installation flags 10074 * @return true if should be installed as forward locked 10075 */ 10076 private static boolean installForwardLocked(int installFlags) { 10077 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10078 } 10079 10080 private InstallArgs createInstallArgs(InstallParams params) { 10081 if (params.move != null) { 10082 return new MoveInstallArgs(params); 10083 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10084 return new AsecInstallArgs(params); 10085 } else { 10086 return new FileInstallArgs(params); 10087 } 10088 } 10089 10090 /** 10091 * Create args that describe an existing installed package. Typically used 10092 * when cleaning up old installs, or used as a move source. 10093 */ 10094 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10095 String resourcePath, String[] instructionSets) { 10096 final boolean isInAsec; 10097 if (installOnExternalAsec(installFlags)) { 10098 /* Apps on SD card are always in ASEC containers. */ 10099 isInAsec = true; 10100 } else if (installForwardLocked(installFlags) 10101 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10102 /* 10103 * Forward-locked apps are only in ASEC containers if they're the 10104 * new style 10105 */ 10106 isInAsec = true; 10107 } else { 10108 isInAsec = false; 10109 } 10110 10111 if (isInAsec) { 10112 return new AsecInstallArgs(codePath, instructionSets, 10113 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10114 } else { 10115 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10116 } 10117 } 10118 10119 static abstract class InstallArgs { 10120 /** @see InstallParams#origin */ 10121 final OriginInfo origin; 10122 /** @see InstallParams#move */ 10123 final MoveInfo move; 10124 10125 final IPackageInstallObserver2 observer; 10126 // Always refers to PackageManager flags only 10127 final int installFlags; 10128 final String installerPackageName; 10129 final String volumeUuid; 10130 final ManifestDigest manifestDigest; 10131 final UserHandle user; 10132 final String abiOverride; 10133 10134 // The list of instruction sets supported by this app. This is currently 10135 // only used during the rmdex() phase to clean up resources. We can get rid of this 10136 // if we move dex files under the common app path. 10137 /* nullable */ String[] instructionSets; 10138 10139 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10140 int installFlags, String installerPackageName, String volumeUuid, 10141 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10142 String abiOverride) { 10143 this.origin = origin; 10144 this.move = move; 10145 this.installFlags = installFlags; 10146 this.observer = observer; 10147 this.installerPackageName = installerPackageName; 10148 this.volumeUuid = volumeUuid; 10149 this.manifestDigest = manifestDigest; 10150 this.user = user; 10151 this.instructionSets = instructionSets; 10152 this.abiOverride = abiOverride; 10153 } 10154 10155 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10156 abstract int doPreInstall(int status); 10157 10158 /** 10159 * Rename package into final resting place. All paths on the given 10160 * scanned package should be updated to reflect the rename. 10161 */ 10162 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10163 abstract int doPostInstall(int status, int uid); 10164 10165 /** @see PackageSettingBase#codePathString */ 10166 abstract String getCodePath(); 10167 /** @see PackageSettingBase#resourcePathString */ 10168 abstract String getResourcePath(); 10169 10170 // Need installer lock especially for dex file removal. 10171 abstract void cleanUpResourcesLI(); 10172 abstract boolean doPostDeleteLI(boolean delete); 10173 10174 /** 10175 * Called before the source arguments are copied. This is used mostly 10176 * for MoveParams when it needs to read the source file to put it in the 10177 * destination. 10178 */ 10179 int doPreCopy() { 10180 return PackageManager.INSTALL_SUCCEEDED; 10181 } 10182 10183 /** 10184 * Called after the source arguments are copied. This is used mostly for 10185 * MoveParams when it needs to read the source file to put it in the 10186 * destination. 10187 * 10188 * @return 10189 */ 10190 int doPostCopy(int uid) { 10191 return PackageManager.INSTALL_SUCCEEDED; 10192 } 10193 10194 protected boolean isFwdLocked() { 10195 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10196 } 10197 10198 protected boolean isExternalAsec() { 10199 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10200 } 10201 10202 UserHandle getUser() { 10203 return user; 10204 } 10205 } 10206 10207 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10208 if (!allCodePaths.isEmpty()) { 10209 if (instructionSets == null) { 10210 throw new IllegalStateException("instructionSet == null"); 10211 } 10212 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10213 for (String codePath : allCodePaths) { 10214 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10215 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10216 if (retCode < 0) { 10217 Slog.w(TAG, "Couldn't remove dex file for package: " 10218 + " at location " + codePath + ", retcode=" + retCode); 10219 // we don't consider this to be a failure of the core package deletion 10220 } 10221 } 10222 } 10223 } 10224 } 10225 10226 /** 10227 * Logic to handle installation of non-ASEC applications, including copying 10228 * and renaming logic. 10229 */ 10230 class FileInstallArgs extends InstallArgs { 10231 private File codeFile; 10232 private File resourceFile; 10233 10234 // Example topology: 10235 // /data/app/com.example/base.apk 10236 // /data/app/com.example/split_foo.apk 10237 // /data/app/com.example/lib/arm/libfoo.so 10238 // /data/app/com.example/lib/arm64/libfoo.so 10239 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10240 10241 /** New install */ 10242 FileInstallArgs(InstallParams params) { 10243 super(params.origin, params.move, params.observer, params.installFlags, 10244 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10245 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10246 if (isFwdLocked()) { 10247 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10248 } 10249 } 10250 10251 /** Existing install */ 10252 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10253 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10254 null); 10255 this.codeFile = (codePath != null) ? new File(codePath) : null; 10256 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10257 } 10258 10259 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10260 if (origin.staged) { 10261 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10262 codeFile = origin.file; 10263 resourceFile = origin.file; 10264 return PackageManager.INSTALL_SUCCEEDED; 10265 } 10266 10267 try { 10268 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10269 codeFile = tempDir; 10270 resourceFile = tempDir; 10271 } catch (IOException e) { 10272 Slog.w(TAG, "Failed to create copy file: " + e); 10273 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10274 } 10275 10276 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10277 @Override 10278 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10279 if (!FileUtils.isValidExtFilename(name)) { 10280 throw new IllegalArgumentException("Invalid filename: " + name); 10281 } 10282 try { 10283 final File file = new File(codeFile, name); 10284 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10285 O_RDWR | O_CREAT, 0644); 10286 Os.chmod(file.getAbsolutePath(), 0644); 10287 return new ParcelFileDescriptor(fd); 10288 } catch (ErrnoException e) { 10289 throw new RemoteException("Failed to open: " + e.getMessage()); 10290 } 10291 } 10292 }; 10293 10294 int ret = PackageManager.INSTALL_SUCCEEDED; 10295 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10296 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10297 Slog.e(TAG, "Failed to copy package"); 10298 return ret; 10299 } 10300 10301 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10302 NativeLibraryHelper.Handle handle = null; 10303 try { 10304 handle = NativeLibraryHelper.Handle.create(codeFile); 10305 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10306 abiOverride); 10307 } catch (IOException e) { 10308 Slog.e(TAG, "Copying native libraries failed", e); 10309 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10310 } finally { 10311 IoUtils.closeQuietly(handle); 10312 } 10313 10314 return ret; 10315 } 10316 10317 int doPreInstall(int status) { 10318 if (status != PackageManager.INSTALL_SUCCEEDED) { 10319 cleanUp(); 10320 } 10321 return status; 10322 } 10323 10324 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10325 if (status != PackageManager.INSTALL_SUCCEEDED) { 10326 cleanUp(); 10327 return false; 10328 } 10329 10330 final File targetDir = codeFile.getParentFile(); 10331 final File beforeCodeFile = codeFile; 10332 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10333 10334 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10335 try { 10336 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10337 } catch (ErrnoException e) { 10338 Slog.d(TAG, "Failed to rename", e); 10339 return false; 10340 } 10341 10342 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10343 Slog.d(TAG, "Failed to restorecon"); 10344 return false; 10345 } 10346 10347 // Reflect the rename internally 10348 codeFile = afterCodeFile; 10349 resourceFile = afterCodeFile; 10350 10351 // Reflect the rename in scanned details 10352 pkg.codePath = afterCodeFile.getAbsolutePath(); 10353 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10354 pkg.baseCodePath); 10355 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10356 pkg.splitCodePaths); 10357 10358 // Reflect the rename in app info 10359 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10360 pkg.applicationInfo.setCodePath(pkg.codePath); 10361 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10362 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10363 pkg.applicationInfo.setResourcePath(pkg.codePath); 10364 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10365 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10366 10367 return true; 10368 } 10369 10370 int doPostInstall(int status, int uid) { 10371 if (status != PackageManager.INSTALL_SUCCEEDED) { 10372 cleanUp(); 10373 } 10374 return status; 10375 } 10376 10377 @Override 10378 String getCodePath() { 10379 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10380 } 10381 10382 @Override 10383 String getResourcePath() { 10384 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10385 } 10386 10387 private boolean cleanUp() { 10388 if (codeFile == null || !codeFile.exists()) { 10389 return false; 10390 } 10391 10392 if (codeFile.isDirectory()) { 10393 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10394 } else { 10395 codeFile.delete(); 10396 } 10397 10398 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10399 resourceFile.delete(); 10400 } 10401 10402 return true; 10403 } 10404 10405 void cleanUpResourcesLI() { 10406 // Try enumerating all code paths before deleting 10407 List<String> allCodePaths = Collections.EMPTY_LIST; 10408 if (codeFile != null && codeFile.exists()) { 10409 try { 10410 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10411 allCodePaths = pkg.getAllCodePaths(); 10412 } catch (PackageParserException e) { 10413 // Ignored; we tried our best 10414 } 10415 } 10416 10417 cleanUp(); 10418 removeDexFiles(allCodePaths, instructionSets); 10419 } 10420 10421 boolean doPostDeleteLI(boolean delete) { 10422 // XXX err, shouldn't we respect the delete flag? 10423 cleanUpResourcesLI(); 10424 return true; 10425 } 10426 } 10427 10428 private boolean isAsecExternal(String cid) { 10429 final String asecPath = PackageHelper.getSdFilesystem(cid); 10430 return !asecPath.startsWith(mAsecInternalPath); 10431 } 10432 10433 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10434 PackageManagerException { 10435 if (copyRet < 0) { 10436 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10437 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10438 throw new PackageManagerException(copyRet, message); 10439 } 10440 } 10441 } 10442 10443 /** 10444 * Extract the MountService "container ID" from the full code path of an 10445 * .apk. 10446 */ 10447 static String cidFromCodePath(String fullCodePath) { 10448 int eidx = fullCodePath.lastIndexOf("/"); 10449 String subStr1 = fullCodePath.substring(0, eidx); 10450 int sidx = subStr1.lastIndexOf("/"); 10451 return subStr1.substring(sidx+1, eidx); 10452 } 10453 10454 /** 10455 * Logic to handle installation of ASEC applications, including copying and 10456 * renaming logic. 10457 */ 10458 class AsecInstallArgs extends InstallArgs { 10459 static final String RES_FILE_NAME = "pkg.apk"; 10460 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10461 10462 String cid; 10463 String packagePath; 10464 String resourcePath; 10465 10466 /** New install */ 10467 AsecInstallArgs(InstallParams params) { 10468 super(params.origin, params.move, params.observer, params.installFlags, 10469 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10470 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10471 } 10472 10473 /** Existing install */ 10474 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10475 boolean isExternal, boolean isForwardLocked) { 10476 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10477 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10478 instructionSets, null); 10479 // Hackily pretend we're still looking at a full code path 10480 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10481 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10482 } 10483 10484 // Extract cid from fullCodePath 10485 int eidx = fullCodePath.lastIndexOf("/"); 10486 String subStr1 = fullCodePath.substring(0, eidx); 10487 int sidx = subStr1.lastIndexOf("/"); 10488 cid = subStr1.substring(sidx+1, eidx); 10489 setMountPath(subStr1); 10490 } 10491 10492 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10493 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10494 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10495 instructionSets, null); 10496 this.cid = cid; 10497 setMountPath(PackageHelper.getSdDir(cid)); 10498 } 10499 10500 void createCopyFile() { 10501 cid = mInstallerService.allocateExternalStageCidLegacy(); 10502 } 10503 10504 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10505 if (origin.staged) { 10506 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10507 cid = origin.cid; 10508 setMountPath(PackageHelper.getSdDir(cid)); 10509 return PackageManager.INSTALL_SUCCEEDED; 10510 } 10511 10512 if (temp) { 10513 createCopyFile(); 10514 } else { 10515 /* 10516 * Pre-emptively destroy the container since it's destroyed if 10517 * copying fails due to it existing anyway. 10518 */ 10519 PackageHelper.destroySdDir(cid); 10520 } 10521 10522 final String newMountPath = imcs.copyPackageToContainer( 10523 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10524 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10525 10526 if (newMountPath != null) { 10527 setMountPath(newMountPath); 10528 return PackageManager.INSTALL_SUCCEEDED; 10529 } else { 10530 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10531 } 10532 } 10533 10534 @Override 10535 String getCodePath() { 10536 return packagePath; 10537 } 10538 10539 @Override 10540 String getResourcePath() { 10541 return resourcePath; 10542 } 10543 10544 int doPreInstall(int status) { 10545 if (status != PackageManager.INSTALL_SUCCEEDED) { 10546 // Destroy container 10547 PackageHelper.destroySdDir(cid); 10548 } else { 10549 boolean mounted = PackageHelper.isContainerMounted(cid); 10550 if (!mounted) { 10551 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10552 Process.SYSTEM_UID); 10553 if (newMountPath != null) { 10554 setMountPath(newMountPath); 10555 } else { 10556 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10557 } 10558 } 10559 } 10560 return status; 10561 } 10562 10563 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10564 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10565 String newMountPath = null; 10566 if (PackageHelper.isContainerMounted(cid)) { 10567 // Unmount the container 10568 if (!PackageHelper.unMountSdDir(cid)) { 10569 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10570 return false; 10571 } 10572 } 10573 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10574 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10575 " which might be stale. Will try to clean up."); 10576 // Clean up the stale container and proceed to recreate. 10577 if (!PackageHelper.destroySdDir(newCacheId)) { 10578 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10579 return false; 10580 } 10581 // Successfully cleaned up stale container. Try to rename again. 10582 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10583 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10584 + " inspite of cleaning it up."); 10585 return false; 10586 } 10587 } 10588 if (!PackageHelper.isContainerMounted(newCacheId)) { 10589 Slog.w(TAG, "Mounting container " + newCacheId); 10590 newMountPath = PackageHelper.mountSdDir(newCacheId, 10591 getEncryptKey(), Process.SYSTEM_UID); 10592 } else { 10593 newMountPath = PackageHelper.getSdDir(newCacheId); 10594 } 10595 if (newMountPath == null) { 10596 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10597 return false; 10598 } 10599 Log.i(TAG, "Succesfully renamed " + cid + 10600 " to " + newCacheId + 10601 " at new path: " + newMountPath); 10602 cid = newCacheId; 10603 10604 final File beforeCodeFile = new File(packagePath); 10605 setMountPath(newMountPath); 10606 final File afterCodeFile = new File(packagePath); 10607 10608 // Reflect the rename in scanned details 10609 pkg.codePath = afterCodeFile.getAbsolutePath(); 10610 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10611 pkg.baseCodePath); 10612 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10613 pkg.splitCodePaths); 10614 10615 // Reflect the rename in app info 10616 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10617 pkg.applicationInfo.setCodePath(pkg.codePath); 10618 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10619 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10620 pkg.applicationInfo.setResourcePath(pkg.codePath); 10621 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10622 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10623 10624 return true; 10625 } 10626 10627 private void setMountPath(String mountPath) { 10628 final File mountFile = new File(mountPath); 10629 10630 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10631 if (monolithicFile.exists()) { 10632 packagePath = monolithicFile.getAbsolutePath(); 10633 if (isFwdLocked()) { 10634 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10635 } else { 10636 resourcePath = packagePath; 10637 } 10638 } else { 10639 packagePath = mountFile.getAbsolutePath(); 10640 resourcePath = packagePath; 10641 } 10642 } 10643 10644 int doPostInstall(int status, int uid) { 10645 if (status != PackageManager.INSTALL_SUCCEEDED) { 10646 cleanUp(); 10647 } else { 10648 final int groupOwner; 10649 final String protectedFile; 10650 if (isFwdLocked()) { 10651 groupOwner = UserHandle.getSharedAppGid(uid); 10652 protectedFile = RES_FILE_NAME; 10653 } else { 10654 groupOwner = -1; 10655 protectedFile = null; 10656 } 10657 10658 if (uid < Process.FIRST_APPLICATION_UID 10659 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10660 Slog.e(TAG, "Failed to finalize " + cid); 10661 PackageHelper.destroySdDir(cid); 10662 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10663 } 10664 10665 boolean mounted = PackageHelper.isContainerMounted(cid); 10666 if (!mounted) { 10667 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10668 } 10669 } 10670 return status; 10671 } 10672 10673 private void cleanUp() { 10674 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10675 10676 // Destroy secure container 10677 PackageHelper.destroySdDir(cid); 10678 } 10679 10680 private List<String> getAllCodePaths() { 10681 final File codeFile = new File(getCodePath()); 10682 if (codeFile != null && codeFile.exists()) { 10683 try { 10684 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10685 return pkg.getAllCodePaths(); 10686 } catch (PackageParserException e) { 10687 // Ignored; we tried our best 10688 } 10689 } 10690 return Collections.EMPTY_LIST; 10691 } 10692 10693 void cleanUpResourcesLI() { 10694 // Enumerate all code paths before deleting 10695 cleanUpResourcesLI(getAllCodePaths()); 10696 } 10697 10698 private void cleanUpResourcesLI(List<String> allCodePaths) { 10699 cleanUp(); 10700 removeDexFiles(allCodePaths, instructionSets); 10701 } 10702 10703 String getPackageName() { 10704 return getAsecPackageName(cid); 10705 } 10706 10707 boolean doPostDeleteLI(boolean delete) { 10708 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10709 final List<String> allCodePaths = getAllCodePaths(); 10710 boolean mounted = PackageHelper.isContainerMounted(cid); 10711 if (mounted) { 10712 // Unmount first 10713 if (PackageHelper.unMountSdDir(cid)) { 10714 mounted = false; 10715 } 10716 } 10717 if (!mounted && delete) { 10718 cleanUpResourcesLI(allCodePaths); 10719 } 10720 return !mounted; 10721 } 10722 10723 @Override 10724 int doPreCopy() { 10725 if (isFwdLocked()) { 10726 if (!PackageHelper.fixSdPermissions(cid, 10727 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10728 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10729 } 10730 } 10731 10732 return PackageManager.INSTALL_SUCCEEDED; 10733 } 10734 10735 @Override 10736 int doPostCopy(int uid) { 10737 if (isFwdLocked()) { 10738 if (uid < Process.FIRST_APPLICATION_UID 10739 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10740 RES_FILE_NAME)) { 10741 Slog.e(TAG, "Failed to finalize " + cid); 10742 PackageHelper.destroySdDir(cid); 10743 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10744 } 10745 } 10746 10747 return PackageManager.INSTALL_SUCCEEDED; 10748 } 10749 } 10750 10751 /** 10752 * Logic to handle movement of existing installed applications. 10753 */ 10754 class MoveInstallArgs extends InstallArgs { 10755 private File codeFile; 10756 private File resourceFile; 10757 10758 /** New install */ 10759 MoveInstallArgs(InstallParams params) { 10760 super(params.origin, params.move, params.observer, params.installFlags, 10761 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10762 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10763 } 10764 10765 int copyApk(IMediaContainerService imcs, boolean temp) { 10766 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10767 + move.toUuid); 10768 synchronized (mInstaller) { 10769 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10770 move.dataAppName, move.appId, move.seinfo) != 0) { 10771 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10772 } 10773 } 10774 10775 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10776 resourceFile = codeFile; 10777 Slog.d(TAG, "codeFile after move is " + codeFile); 10778 10779 return PackageManager.INSTALL_SUCCEEDED; 10780 } 10781 10782 int doPreInstall(int status) { 10783 if (status != PackageManager.INSTALL_SUCCEEDED) { 10784 cleanUp(); 10785 } 10786 return status; 10787 } 10788 10789 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10790 if (status != PackageManager.INSTALL_SUCCEEDED) { 10791 cleanUp(); 10792 return false; 10793 } 10794 10795 // Reflect the move in app info 10796 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10797 pkg.applicationInfo.setCodePath(pkg.codePath); 10798 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10799 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10800 pkg.applicationInfo.setResourcePath(pkg.codePath); 10801 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10802 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10803 10804 return true; 10805 } 10806 10807 int doPostInstall(int status, int uid) { 10808 if (status != PackageManager.INSTALL_SUCCEEDED) { 10809 cleanUp(); 10810 } 10811 return status; 10812 } 10813 10814 @Override 10815 String getCodePath() { 10816 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10817 } 10818 10819 @Override 10820 String getResourcePath() { 10821 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10822 } 10823 10824 private boolean cleanUp() { 10825 if (codeFile == null || !codeFile.exists()) { 10826 return false; 10827 } 10828 10829 if (codeFile.isDirectory()) { 10830 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10831 } else { 10832 codeFile.delete(); 10833 } 10834 10835 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10836 resourceFile.delete(); 10837 } 10838 10839 return true; 10840 } 10841 10842 void cleanUpResourcesLI() { 10843 cleanUp(); 10844 } 10845 10846 boolean doPostDeleteLI(boolean delete) { 10847 // XXX err, shouldn't we respect the delete flag? 10848 cleanUpResourcesLI(); 10849 return true; 10850 } 10851 } 10852 10853 static String getAsecPackageName(String packageCid) { 10854 int idx = packageCid.lastIndexOf("-"); 10855 if (idx == -1) { 10856 return packageCid; 10857 } 10858 return packageCid.substring(0, idx); 10859 } 10860 10861 // Utility method used to create code paths based on package name and available index. 10862 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10863 String idxStr = ""; 10864 int idx = 1; 10865 // Fall back to default value of idx=1 if prefix is not 10866 // part of oldCodePath 10867 if (oldCodePath != null) { 10868 String subStr = oldCodePath; 10869 // Drop the suffix right away 10870 if (suffix != null && subStr.endsWith(suffix)) { 10871 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10872 } 10873 // If oldCodePath already contains prefix find out the 10874 // ending index to either increment or decrement. 10875 int sidx = subStr.lastIndexOf(prefix); 10876 if (sidx != -1) { 10877 subStr = subStr.substring(sidx + prefix.length()); 10878 if (subStr != null) { 10879 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10880 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10881 } 10882 try { 10883 idx = Integer.parseInt(subStr); 10884 if (idx <= 1) { 10885 idx++; 10886 } else { 10887 idx--; 10888 } 10889 } catch(NumberFormatException e) { 10890 } 10891 } 10892 } 10893 } 10894 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10895 return prefix + idxStr; 10896 } 10897 10898 private File getNextCodePath(File targetDir, String packageName) { 10899 int suffix = 1; 10900 File result; 10901 do { 10902 result = new File(targetDir, packageName + "-" + suffix); 10903 suffix++; 10904 } while (result.exists()); 10905 return result; 10906 } 10907 10908 // Utility method that returns the relative package path with respect 10909 // to the installation directory. Like say for /data/data/com.test-1.apk 10910 // string com.test-1 is returned. 10911 static String deriveCodePathName(String codePath) { 10912 if (codePath == null) { 10913 return null; 10914 } 10915 final File codeFile = new File(codePath); 10916 final String name = codeFile.getName(); 10917 if (codeFile.isDirectory()) { 10918 return name; 10919 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10920 final int lastDot = name.lastIndexOf('.'); 10921 return name.substring(0, lastDot); 10922 } else { 10923 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10924 return null; 10925 } 10926 } 10927 10928 class PackageInstalledInfo { 10929 String name; 10930 int uid; 10931 // The set of users that originally had this package installed. 10932 int[] origUsers; 10933 // The set of users that now have this package installed. 10934 int[] newUsers; 10935 PackageParser.Package pkg; 10936 int returnCode; 10937 String returnMsg; 10938 PackageRemovedInfo removedInfo; 10939 10940 public void setError(int code, String msg) { 10941 returnCode = code; 10942 returnMsg = msg; 10943 Slog.w(TAG, msg); 10944 } 10945 10946 public void setError(String msg, PackageParserException e) { 10947 returnCode = e.error; 10948 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10949 Slog.w(TAG, msg, e); 10950 } 10951 10952 public void setError(String msg, PackageManagerException e) { 10953 returnCode = e.error; 10954 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10955 Slog.w(TAG, msg, e); 10956 } 10957 10958 // In some error cases we want to convey more info back to the observer 10959 String origPackage; 10960 String origPermission; 10961 } 10962 10963 /* 10964 * Install a non-existing package. 10965 */ 10966 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10967 UserHandle user, String installerPackageName, String volumeUuid, 10968 PackageInstalledInfo res) { 10969 // Remember this for later, in case we need to rollback this install 10970 String pkgName = pkg.packageName; 10971 10972 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10973 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10974 UserHandle.USER_OWNER).exists(); 10975 synchronized(mPackages) { 10976 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10977 // A package with the same name is already installed, though 10978 // it has been renamed to an older name. The package we 10979 // are trying to install should be installed as an update to 10980 // the existing one, but that has not been requested, so bail. 10981 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10982 + " without first uninstalling package running as " 10983 + mSettings.mRenamedPackages.get(pkgName)); 10984 return; 10985 } 10986 if (mPackages.containsKey(pkgName)) { 10987 // Don't allow installation over an existing package with the same name. 10988 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10989 + " without first uninstalling."); 10990 return; 10991 } 10992 } 10993 10994 try { 10995 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10996 System.currentTimeMillis(), user); 10997 10998 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10999 // delete the partially installed application. the data directory will have to be 11000 // restored if it was already existing 11001 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11002 // remove package from internal structures. Note that we want deletePackageX to 11003 // delete the package data and cache directories that it created in 11004 // scanPackageLocked, unless those directories existed before we even tried to 11005 // install. 11006 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11007 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11008 res.removedInfo, true); 11009 } 11010 11011 } catch (PackageManagerException e) { 11012 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11013 } 11014 } 11015 11016 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11017 // Upgrade keysets are being used. Determine if new package has a superset of the 11018 // required keys. 11019 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11020 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11021 for (int i = 0; i < upgradeKeySets.length; i++) { 11022 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11023 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11024 return true; 11025 } 11026 } 11027 return false; 11028 } 11029 11030 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11031 UserHandle user, String installerPackageName, String volumeUuid, 11032 PackageInstalledInfo res) { 11033 final PackageParser.Package oldPackage; 11034 final String pkgName = pkg.packageName; 11035 final int[] allUsers; 11036 final boolean[] perUserInstalled; 11037 final boolean weFroze; 11038 11039 // First find the old package info and check signatures 11040 synchronized(mPackages) { 11041 oldPackage = mPackages.get(pkgName); 11042 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11043 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11044 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11045 // default to original signature matching 11046 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11047 != PackageManager.SIGNATURE_MATCH) { 11048 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11049 "New package has a different signature: " + pkgName); 11050 return; 11051 } 11052 } else { 11053 if(!checkUpgradeKeySetLP(ps, pkg)) { 11054 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11055 "New package not signed by keys specified by upgrade-keysets: " 11056 + pkgName); 11057 return; 11058 } 11059 } 11060 11061 // In case of rollback, remember per-user/profile install state 11062 allUsers = sUserManager.getUserIds(); 11063 perUserInstalled = new boolean[allUsers.length]; 11064 for (int i = 0; i < allUsers.length; i++) { 11065 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11066 } 11067 11068 // Mark the app as frozen to prevent launching during the upgrade 11069 // process, and then kill all running instances 11070 if (!ps.frozen) { 11071 ps.frozen = true; 11072 weFroze = true; 11073 } else { 11074 weFroze = false; 11075 } 11076 } 11077 11078 // Now that we're guarded by frozen state, kill app during upgrade 11079 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11080 11081 try { 11082 boolean sysPkg = (isSystemApp(oldPackage)); 11083 if (sysPkg) { 11084 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11085 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11086 } else { 11087 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11088 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11089 } 11090 } finally { 11091 // Regardless of success or failure of upgrade steps above, always 11092 // unfreeze the package if we froze it 11093 if (weFroze) { 11094 unfreezePackage(pkgName); 11095 } 11096 } 11097 } 11098 11099 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11100 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11101 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11102 String volumeUuid, PackageInstalledInfo res) { 11103 String pkgName = deletedPackage.packageName; 11104 boolean deletedPkg = true; 11105 boolean updatedSettings = false; 11106 11107 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11108 + deletedPackage); 11109 long origUpdateTime; 11110 if (pkg.mExtras != null) { 11111 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11112 } else { 11113 origUpdateTime = 0; 11114 } 11115 11116 // First delete the existing package while retaining the data directory 11117 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11118 res.removedInfo, true)) { 11119 // If the existing package wasn't successfully deleted 11120 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11121 deletedPkg = false; 11122 } else { 11123 // Successfully deleted the old package; proceed with replace. 11124 11125 // If deleted package lived in a container, give users a chance to 11126 // relinquish resources before killing. 11127 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11128 if (DEBUG_INSTALL) { 11129 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11130 } 11131 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11132 final ArrayList<String> pkgList = new ArrayList<String>(1); 11133 pkgList.add(deletedPackage.applicationInfo.packageName); 11134 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11135 } 11136 11137 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11138 try { 11139 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11140 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11141 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11142 perUserInstalled, res, user); 11143 updatedSettings = true; 11144 } catch (PackageManagerException e) { 11145 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11146 } 11147 } 11148 11149 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11150 // remove package from internal structures. Note that we want deletePackageX to 11151 // delete the package data and cache directories that it created in 11152 // scanPackageLocked, unless those directories existed before we even tried to 11153 // install. 11154 if(updatedSettings) { 11155 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11156 deletePackageLI( 11157 pkgName, null, true, allUsers, perUserInstalled, 11158 PackageManager.DELETE_KEEP_DATA, 11159 res.removedInfo, true); 11160 } 11161 // Since we failed to install the new package we need to restore the old 11162 // package that we deleted. 11163 if (deletedPkg) { 11164 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11165 File restoreFile = new File(deletedPackage.codePath); 11166 // Parse old package 11167 boolean oldExternal = isExternal(deletedPackage); 11168 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11169 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11170 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11171 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11172 try { 11173 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11174 } catch (PackageManagerException e) { 11175 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11176 + e.getMessage()); 11177 return; 11178 } 11179 // Restore of old package succeeded. Update permissions. 11180 // writer 11181 synchronized (mPackages) { 11182 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11183 UPDATE_PERMISSIONS_ALL); 11184 // can downgrade to reader 11185 mSettings.writeLPr(); 11186 } 11187 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11188 } 11189 } 11190 } 11191 11192 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11193 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11194 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11195 String volumeUuid, PackageInstalledInfo res) { 11196 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11197 + ", old=" + deletedPackage); 11198 boolean disabledSystem = false; 11199 boolean updatedSettings = false; 11200 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11201 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11202 != 0) { 11203 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11204 } 11205 String packageName = deletedPackage.packageName; 11206 if (packageName == null) { 11207 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11208 "Attempt to delete null packageName."); 11209 return; 11210 } 11211 PackageParser.Package oldPkg; 11212 PackageSetting oldPkgSetting; 11213 // reader 11214 synchronized (mPackages) { 11215 oldPkg = mPackages.get(packageName); 11216 oldPkgSetting = mSettings.mPackages.get(packageName); 11217 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11218 (oldPkgSetting == null)) { 11219 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11220 "Couldn't find package:" + packageName + " information"); 11221 return; 11222 } 11223 } 11224 11225 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11226 res.removedInfo.removedPackage = packageName; 11227 // Remove existing system package 11228 removePackageLI(oldPkgSetting, true); 11229 // writer 11230 synchronized (mPackages) { 11231 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11232 if (!disabledSystem && deletedPackage != null) { 11233 // We didn't need to disable the .apk as a current system package, 11234 // which means we are replacing another update that is already 11235 // installed. We need to make sure to delete the older one's .apk. 11236 res.removedInfo.args = createInstallArgsForExisting(0, 11237 deletedPackage.applicationInfo.getCodePath(), 11238 deletedPackage.applicationInfo.getResourcePath(), 11239 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11240 } else { 11241 res.removedInfo.args = null; 11242 } 11243 } 11244 11245 // Successfully disabled the old package. Now proceed with re-installation 11246 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11247 11248 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11249 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11250 11251 PackageParser.Package newPackage = null; 11252 try { 11253 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11254 if (newPackage.mExtras != null) { 11255 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11256 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11257 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11258 11259 // is the update attempting to change shared user? that isn't going to work... 11260 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11261 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11262 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11263 + " to " + newPkgSetting.sharedUser); 11264 updatedSettings = true; 11265 } 11266 } 11267 11268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11269 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11270 perUserInstalled, res, user); 11271 updatedSettings = true; 11272 } 11273 11274 } catch (PackageManagerException e) { 11275 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11276 } 11277 11278 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11279 // Re installation failed. Restore old information 11280 // Remove new pkg information 11281 if (newPackage != null) { 11282 removeInstalledPackageLI(newPackage, true); 11283 } 11284 // Add back the old system package 11285 try { 11286 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11287 } catch (PackageManagerException e) { 11288 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11289 } 11290 // Restore the old system information in Settings 11291 synchronized (mPackages) { 11292 if (disabledSystem) { 11293 mSettings.enableSystemPackageLPw(packageName); 11294 } 11295 if (updatedSettings) { 11296 mSettings.setInstallerPackageName(packageName, 11297 oldPkgSetting.installerPackageName); 11298 } 11299 mSettings.writeLPr(); 11300 } 11301 } 11302 } 11303 11304 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11305 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11306 UserHandle user) { 11307 String pkgName = newPackage.packageName; 11308 synchronized (mPackages) { 11309 //write settings. the installStatus will be incomplete at this stage. 11310 //note that the new package setting would have already been 11311 //added to mPackages. It hasn't been persisted yet. 11312 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11313 mSettings.writeLPr(); 11314 } 11315 11316 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11317 11318 synchronized (mPackages) { 11319 updatePermissionsLPw(newPackage.packageName, newPackage, 11320 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11321 ? UPDATE_PERMISSIONS_ALL : 0)); 11322 // For system-bundled packages, we assume that installing an upgraded version 11323 // of the package implies that the user actually wants to run that new code, 11324 // so we enable the package. 11325 PackageSetting ps = mSettings.mPackages.get(pkgName); 11326 if (ps != null) { 11327 if (isSystemApp(newPackage)) { 11328 // NB: implicit assumption that system package upgrades apply to all users 11329 if (DEBUG_INSTALL) { 11330 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11331 } 11332 if (res.origUsers != null) { 11333 for (int userHandle : res.origUsers) { 11334 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11335 userHandle, installerPackageName); 11336 } 11337 } 11338 // Also convey the prior install/uninstall state 11339 if (allUsers != null && perUserInstalled != null) { 11340 for (int i = 0; i < allUsers.length; i++) { 11341 if (DEBUG_INSTALL) { 11342 Slog.d(TAG, " user " + allUsers[i] 11343 + " => " + perUserInstalled[i]); 11344 } 11345 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11346 } 11347 // these install state changes will be persisted in the 11348 // upcoming call to mSettings.writeLPr(). 11349 } 11350 } 11351 // It's implied that when a user requests installation, they want the app to be 11352 // installed and enabled. 11353 int userId = user.getIdentifier(); 11354 if (userId != UserHandle.USER_ALL) { 11355 ps.setInstalled(true, userId); 11356 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11357 } 11358 } 11359 res.name = pkgName; 11360 res.uid = newPackage.applicationInfo.uid; 11361 res.pkg = newPackage; 11362 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11363 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11364 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11365 //to update install status 11366 mSettings.writeLPr(); 11367 } 11368 } 11369 11370 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11371 final int installFlags = args.installFlags; 11372 final String installerPackageName = args.installerPackageName; 11373 final String volumeUuid = args.volumeUuid; 11374 final File tmpPackageFile = new File(args.getCodePath()); 11375 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11376 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11377 || (args.volumeUuid != null)); 11378 boolean replace = false; 11379 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11380 // Result object to be returned 11381 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11382 11383 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11384 // Retrieve PackageSettings and parse package 11385 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11386 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11387 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11388 PackageParser pp = new PackageParser(); 11389 pp.setSeparateProcesses(mSeparateProcesses); 11390 pp.setDisplayMetrics(mMetrics); 11391 11392 final PackageParser.Package pkg; 11393 try { 11394 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11395 } catch (PackageParserException e) { 11396 res.setError("Failed parse during installPackageLI", e); 11397 return; 11398 } 11399 11400 // Mark that we have an install time CPU ABI override. 11401 pkg.cpuAbiOverride = args.abiOverride; 11402 11403 String pkgName = res.name = pkg.packageName; 11404 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11405 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11406 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11407 return; 11408 } 11409 } 11410 11411 try { 11412 pp.collectCertificates(pkg, parseFlags); 11413 pp.collectManifestDigest(pkg); 11414 } catch (PackageParserException e) { 11415 res.setError("Failed collect during installPackageLI", e); 11416 return; 11417 } 11418 11419 /* If the installer passed in a manifest digest, compare it now. */ 11420 if (args.manifestDigest != null) { 11421 if (DEBUG_INSTALL) { 11422 final String parsedManifest = pkg.manifestDigest == null ? "null" 11423 : pkg.manifestDigest.toString(); 11424 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11425 + parsedManifest); 11426 } 11427 11428 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11429 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11430 return; 11431 } 11432 } else if (DEBUG_INSTALL) { 11433 final String parsedManifest = pkg.manifestDigest == null 11434 ? "null" : pkg.manifestDigest.toString(); 11435 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11436 } 11437 11438 // Get rid of all references to package scan path via parser. 11439 pp = null; 11440 String oldCodePath = null; 11441 boolean systemApp = false; 11442 synchronized (mPackages) { 11443 // Check if installing already existing package 11444 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11445 String oldName = mSettings.mRenamedPackages.get(pkgName); 11446 if (pkg.mOriginalPackages != null 11447 && pkg.mOriginalPackages.contains(oldName) 11448 && mPackages.containsKey(oldName)) { 11449 // This package is derived from an original package, 11450 // and this device has been updating from that original 11451 // name. We must continue using the original name, so 11452 // rename the new package here. 11453 pkg.setPackageName(oldName); 11454 pkgName = pkg.packageName; 11455 replace = true; 11456 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11457 + oldName + " pkgName=" + pkgName); 11458 } else if (mPackages.containsKey(pkgName)) { 11459 // This package, under its official name, already exists 11460 // on the device; we should replace it. 11461 replace = true; 11462 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11463 } 11464 11465 // Prevent apps opting out from runtime permissions 11466 if (replace) { 11467 PackageParser.Package oldPackage = mPackages.get(pkgName); 11468 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11469 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11470 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11471 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11472 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11473 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11474 + " doesn't support runtime permissions but the old" 11475 + " target SDK " + oldTargetSdk + " does."); 11476 return; 11477 } 11478 } 11479 } 11480 11481 PackageSetting ps = mSettings.mPackages.get(pkgName); 11482 if (ps != null) { 11483 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11484 11485 // Quick sanity check that we're signed correctly if updating; 11486 // we'll check this again later when scanning, but we want to 11487 // bail early here before tripping over redefined permissions. 11488 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11489 try { 11490 verifySignaturesLP(ps, pkg); 11491 } catch (PackageManagerException e) { 11492 res.setError(e.error, e.getMessage()); 11493 return; 11494 } 11495 } else { 11496 if (!checkUpgradeKeySetLP(ps, pkg)) { 11497 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11498 + pkg.packageName + " upgrade keys do not match the " 11499 + "previously installed version"); 11500 return; 11501 } 11502 } 11503 11504 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11505 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11506 systemApp = (ps.pkg.applicationInfo.flags & 11507 ApplicationInfo.FLAG_SYSTEM) != 0; 11508 } 11509 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11510 } 11511 11512 // Check whether the newly-scanned package wants to define an already-defined perm 11513 int N = pkg.permissions.size(); 11514 for (int i = N-1; i >= 0; i--) { 11515 PackageParser.Permission perm = pkg.permissions.get(i); 11516 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11517 if (bp != null) { 11518 // If the defining package is signed with our cert, it's okay. This 11519 // also includes the "updating the same package" case, of course. 11520 // "updating same package" could also involve key-rotation. 11521 final boolean sigsOk; 11522 if (!bp.sourcePackage.equals(pkg.packageName) 11523 || !(bp.packageSetting instanceof PackageSetting) 11524 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11525 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11526 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11527 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11528 } else { 11529 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11530 } 11531 if (!sigsOk) { 11532 // If the owning package is the system itself, we log but allow 11533 // install to proceed; we fail the install on all other permission 11534 // redefinitions. 11535 if (!bp.sourcePackage.equals("android")) { 11536 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11537 + pkg.packageName + " attempting to redeclare permission " 11538 + perm.info.name + " already owned by " + bp.sourcePackage); 11539 res.origPermission = perm.info.name; 11540 res.origPackage = bp.sourcePackage; 11541 return; 11542 } else { 11543 Slog.w(TAG, "Package " + pkg.packageName 11544 + " attempting to redeclare system permission " 11545 + perm.info.name + "; ignoring new declaration"); 11546 pkg.permissions.remove(i); 11547 } 11548 } 11549 } 11550 } 11551 11552 } 11553 11554 if (systemApp && onExternal) { 11555 // Disable updates to system apps on sdcard 11556 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11557 "Cannot install updates to system apps on sdcard"); 11558 return; 11559 } 11560 11561 if (args.move != null) { 11562 // We did an in-place move, so dex is ready to roll 11563 scanFlags |= SCAN_NO_DEX; 11564 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11565 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11566 scanFlags |= SCAN_NO_DEX; 11567 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11568 int result = mPackageDexOptimizer 11569 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11570 false /* defer */, false /* inclDependencies */); 11571 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11572 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11573 return; 11574 } 11575 } 11576 11577 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11578 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11579 return; 11580 } 11581 11582 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11583 11584 if (replace) { 11585 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11586 installerPackageName, volumeUuid, res); 11587 } else { 11588 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11589 args.user, installerPackageName, volumeUuid, res); 11590 } 11591 synchronized (mPackages) { 11592 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11593 if (ps != null) { 11594 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11595 } 11596 } 11597 } 11598 11599 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11600 if (mIntentFilterVerifierComponent == null) { 11601 Slog.d(TAG, "No IntentFilter verification will not be done as " 11602 + "there is no IntentFilterVerifier available!"); 11603 return; 11604 } 11605 11606 final int verifierUid = getPackageUid( 11607 mIntentFilterVerifierComponent.getPackageName(), 11608 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11609 11610 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11611 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11612 msg.obj = pkg; 11613 msg.arg1 = userId; 11614 msg.arg2 = verifierUid; 11615 11616 mHandler.sendMessage(msg); 11617 } 11618 11619 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11620 PackageParser.Package pkg) { 11621 int size = pkg.activities.size(); 11622 if (size == 0) { 11623 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11624 return; 11625 } 11626 11627 final boolean hasDomainURLs = hasDomainURLs(pkg); 11628 if (!hasDomainURLs) { 11629 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11630 return; 11631 } 11632 11633 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11634 + " Activities needs verification ..."); 11635 11636 final int verificationId = mIntentFilterVerificationToken++; 11637 int count = 0; 11638 final String packageName = pkg.packageName; 11639 ArrayList<String> allHosts = new ArrayList<>(); 11640 11641 synchronized (mPackages) { 11642 for (PackageParser.Activity a : pkg.activities) { 11643 for (ActivityIntentInfo filter : a.intents) { 11644 boolean needsFilterVerification = filter.needsVerification(); 11645 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11646 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11647 mIntentFilterVerifier.addOneIntentFilterVerification( 11648 verifierUid, userId, verificationId, filter, packageName); 11649 count++; 11650 } else if (!needsFilterVerification) { 11651 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11652 if (hasValidDomains(filter)) { 11653 ArrayList<String> hosts = filter.getHostsList(); 11654 if (hosts.size() > 0) { 11655 allHosts.addAll(hosts); 11656 } else { 11657 if (allHosts.isEmpty()) { 11658 allHosts.add("*"); 11659 } 11660 } 11661 } 11662 } else { 11663 Slog.d(TAG, "Verification already done for IntentFilter:" 11664 + filter.toString()); 11665 } 11666 } 11667 } 11668 } 11669 11670 if (count > 0) { 11671 mIntentFilterVerifier.startVerifications(userId); 11672 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11673 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11674 } else { 11675 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11676 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11677 packageName, allHosts) != null) { 11678 scheduleWriteSettingsLocked(); 11679 } 11680 } 11681 } 11682 11683 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11684 final ComponentName cn = filter.activity.getComponentName(); 11685 final String packageName = cn.getPackageName(); 11686 11687 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11688 packageName); 11689 if (ivi == null) { 11690 return true; 11691 } 11692 int status = ivi.getStatus(); 11693 switch (status) { 11694 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11695 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11696 return true; 11697 11698 default: 11699 // Nothing to do 11700 return false; 11701 } 11702 } 11703 11704 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11705 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11706 || ((pkg.applicationInfo.privateFlags 11707 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11708 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11709 } 11710 11711 private static boolean isMultiArch(PackageSetting ps) { 11712 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11713 } 11714 11715 private static boolean isMultiArch(ApplicationInfo info) { 11716 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11717 } 11718 11719 private static boolean isExternal(PackageParser.Package pkg) { 11720 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11721 } 11722 11723 private static boolean isExternal(PackageSetting ps) { 11724 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11725 } 11726 11727 private static boolean isExternal(ApplicationInfo info) { 11728 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11729 } 11730 11731 private static boolean isSystemApp(PackageParser.Package pkg) { 11732 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11733 } 11734 11735 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11736 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11737 } 11738 11739 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11740 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11741 } 11742 11743 private static boolean isSystemApp(PackageSetting ps) { 11744 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11745 } 11746 11747 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11748 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11749 } 11750 11751 private int packageFlagsToInstallFlags(PackageSetting ps) { 11752 int installFlags = 0; 11753 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11754 // This existing package was an external ASEC install when we have 11755 // the external flag without a UUID 11756 installFlags |= PackageManager.INSTALL_EXTERNAL; 11757 } 11758 if (ps.isForwardLocked()) { 11759 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11760 } 11761 return installFlags; 11762 } 11763 11764 private void deleteTempPackageFiles() { 11765 final FilenameFilter filter = new FilenameFilter() { 11766 public boolean accept(File dir, String name) { 11767 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11768 } 11769 }; 11770 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11771 file.delete(); 11772 } 11773 } 11774 11775 @Override 11776 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11777 int flags) { 11778 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11779 flags); 11780 } 11781 11782 @Override 11783 public void deletePackage(final String packageName, 11784 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11785 mContext.enforceCallingOrSelfPermission( 11786 android.Manifest.permission.DELETE_PACKAGES, null); 11787 final int uid = Binder.getCallingUid(); 11788 if (UserHandle.getUserId(uid) != userId) { 11789 mContext.enforceCallingPermission( 11790 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11791 "deletePackage for user " + userId); 11792 } 11793 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11794 try { 11795 observer.onPackageDeleted(packageName, 11796 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11797 } catch (RemoteException re) { 11798 } 11799 return; 11800 } 11801 11802 boolean uninstallBlocked = false; 11803 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11804 int[] users = sUserManager.getUserIds(); 11805 for (int i = 0; i < users.length; ++i) { 11806 if (getBlockUninstallForUser(packageName, users[i])) { 11807 uninstallBlocked = true; 11808 break; 11809 } 11810 } 11811 } else { 11812 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11813 } 11814 if (uninstallBlocked) { 11815 try { 11816 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11817 null); 11818 } catch (RemoteException re) { 11819 } 11820 return; 11821 } 11822 11823 if (DEBUG_REMOVE) { 11824 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11825 } 11826 // Queue up an async operation since the package deletion may take a little while. 11827 mHandler.post(new Runnable() { 11828 public void run() { 11829 mHandler.removeCallbacks(this); 11830 final int returnCode = deletePackageX(packageName, userId, flags); 11831 if (observer != null) { 11832 try { 11833 observer.onPackageDeleted(packageName, returnCode, null); 11834 } catch (RemoteException e) { 11835 Log.i(TAG, "Observer no longer exists."); 11836 } //end catch 11837 } //end if 11838 } //end run 11839 }); 11840 } 11841 11842 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11843 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11844 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11845 try { 11846 if (dpm != null) { 11847 if (dpm.isDeviceOwner(packageName)) { 11848 return true; 11849 } 11850 int[] users; 11851 if (userId == UserHandle.USER_ALL) { 11852 users = sUserManager.getUserIds(); 11853 } else { 11854 users = new int[]{userId}; 11855 } 11856 for (int i = 0; i < users.length; ++i) { 11857 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11858 return true; 11859 } 11860 } 11861 } 11862 } catch (RemoteException e) { 11863 } 11864 return false; 11865 } 11866 11867 /** 11868 * This method is an internal method that could be get invoked either 11869 * to delete an installed package or to clean up a failed installation. 11870 * After deleting an installed package, a broadcast is sent to notify any 11871 * listeners that the package has been installed. For cleaning up a failed 11872 * installation, the broadcast is not necessary since the package's 11873 * installation wouldn't have sent the initial broadcast either 11874 * The key steps in deleting a package are 11875 * deleting the package information in internal structures like mPackages, 11876 * deleting the packages base directories through installd 11877 * updating mSettings to reflect current status 11878 * persisting settings for later use 11879 * sending a broadcast if necessary 11880 */ 11881 private int deletePackageX(String packageName, int userId, int flags) { 11882 final PackageRemovedInfo info = new PackageRemovedInfo(); 11883 final boolean res; 11884 11885 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11886 ? UserHandle.ALL : new UserHandle(userId); 11887 11888 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11889 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11890 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11891 } 11892 11893 boolean removedForAllUsers = false; 11894 boolean systemUpdate = false; 11895 11896 // for the uninstall-updates case and restricted profiles, remember the per- 11897 // userhandle installed state 11898 int[] allUsers; 11899 boolean[] perUserInstalled; 11900 synchronized (mPackages) { 11901 PackageSetting ps = mSettings.mPackages.get(packageName); 11902 allUsers = sUserManager.getUserIds(); 11903 perUserInstalled = new boolean[allUsers.length]; 11904 for (int i = 0; i < allUsers.length; i++) { 11905 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11906 } 11907 } 11908 11909 synchronized (mInstallLock) { 11910 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11911 res = deletePackageLI(packageName, removeForUser, 11912 true, allUsers, perUserInstalled, 11913 flags | REMOVE_CHATTY, info, true); 11914 systemUpdate = info.isRemovedPackageSystemUpdate; 11915 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11916 removedForAllUsers = true; 11917 } 11918 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11919 + " removedForAllUsers=" + removedForAllUsers); 11920 } 11921 11922 if (res) { 11923 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11924 11925 // If the removed package was a system update, the old system package 11926 // was re-enabled; we need to broadcast this information 11927 if (systemUpdate) { 11928 Bundle extras = new Bundle(1); 11929 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11930 ? info.removedAppId : info.uid); 11931 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11932 11933 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11934 extras, null, null, null); 11935 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11936 extras, null, null, null); 11937 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11938 null, packageName, null, null); 11939 } 11940 } 11941 // Force a gc here. 11942 Runtime.getRuntime().gc(); 11943 // Delete the resources here after sending the broadcast to let 11944 // other processes clean up before deleting resources. 11945 if (info.args != null) { 11946 synchronized (mInstallLock) { 11947 info.args.doPostDeleteLI(true); 11948 } 11949 } 11950 11951 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11952 } 11953 11954 class PackageRemovedInfo { 11955 String removedPackage; 11956 int uid = -1; 11957 int removedAppId = -1; 11958 int[] removedUsers = null; 11959 boolean isRemovedPackageSystemUpdate = false; 11960 // Clean up resources deleted packages. 11961 InstallArgs args = null; 11962 11963 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11964 Bundle extras = new Bundle(1); 11965 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11966 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11967 if (replacing) { 11968 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11969 } 11970 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11971 if (removedPackage != null) { 11972 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11973 extras, null, null, removedUsers); 11974 if (fullRemove && !replacing) { 11975 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11976 extras, null, null, removedUsers); 11977 } 11978 } 11979 if (removedAppId >= 0) { 11980 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11981 removedUsers); 11982 } 11983 } 11984 } 11985 11986 /* 11987 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11988 * flag is not set, the data directory is removed as well. 11989 * make sure this flag is set for partially installed apps. If not its meaningless to 11990 * delete a partially installed application. 11991 */ 11992 private void removePackageDataLI(PackageSetting ps, 11993 int[] allUserHandles, boolean[] perUserInstalled, 11994 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11995 String packageName = ps.name; 11996 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11997 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11998 // Retrieve object to delete permissions for shared user later on 11999 final PackageSetting deletedPs; 12000 // reader 12001 synchronized (mPackages) { 12002 deletedPs = mSettings.mPackages.get(packageName); 12003 if (outInfo != null) { 12004 outInfo.removedPackage = packageName; 12005 outInfo.removedUsers = deletedPs != null 12006 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12007 : null; 12008 } 12009 } 12010 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12011 removeDataDirsLI(ps.volumeUuid, packageName); 12012 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12013 } 12014 // writer 12015 synchronized (mPackages) { 12016 if (deletedPs != null) { 12017 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12018 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12019 clearDefaultBrowserIfNeeded(packageName); 12020 if (outInfo != null) { 12021 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12022 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12023 } 12024 updatePermissionsLPw(deletedPs.name, null, 0); 12025 if (deletedPs.sharedUser != null) { 12026 // Remove permissions associated with package. Since runtime 12027 // permissions are per user we have to kill the removed package 12028 // or packages running under the shared user of the removed 12029 // package if revoking the permissions requested only by the removed 12030 // package is successful and this causes a change in gids. 12031 for (int userId : UserManagerService.getInstance().getUserIds()) { 12032 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12033 userId); 12034 if (userIdToKill == UserHandle.USER_ALL 12035 || userIdToKill >= UserHandle.USER_OWNER) { 12036 // If gids changed for this user, kill all affected packages. 12037 mHandler.post(new Runnable() { 12038 @Override 12039 public void run() { 12040 // This has to happen with no lock held. 12041 killSettingPackagesForUser(deletedPs, userIdToKill, 12042 KILL_APP_REASON_GIDS_CHANGED); 12043 } 12044 }); 12045 break; 12046 } 12047 } 12048 } 12049 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12050 } 12051 // make sure to preserve per-user disabled state if this removal was just 12052 // a downgrade of a system app to the factory package 12053 if (allUserHandles != null && perUserInstalled != null) { 12054 if (DEBUG_REMOVE) { 12055 Slog.d(TAG, "Propagating install state across downgrade"); 12056 } 12057 for (int i = 0; i < allUserHandles.length; i++) { 12058 if (DEBUG_REMOVE) { 12059 Slog.d(TAG, " user " + allUserHandles[i] 12060 + " => " + perUserInstalled[i]); 12061 } 12062 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12063 } 12064 } 12065 } 12066 // can downgrade to reader 12067 if (writeSettings) { 12068 // Save settings now 12069 mSettings.writeLPr(); 12070 } 12071 } 12072 if (outInfo != null) { 12073 // A user ID was deleted here. Go through all users and remove it 12074 // from KeyStore. 12075 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12076 } 12077 } 12078 12079 static boolean locationIsPrivileged(File path) { 12080 try { 12081 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12082 .getCanonicalPath(); 12083 return path.getCanonicalPath().startsWith(privilegedAppDir); 12084 } catch (IOException e) { 12085 Slog.e(TAG, "Unable to access code path " + path); 12086 } 12087 return false; 12088 } 12089 12090 /* 12091 * Tries to delete system package. 12092 */ 12093 private boolean deleteSystemPackageLI(PackageSetting newPs, 12094 int[] allUserHandles, boolean[] perUserInstalled, 12095 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12096 final boolean applyUserRestrictions 12097 = (allUserHandles != null) && (perUserInstalled != null); 12098 PackageSetting disabledPs = null; 12099 // Confirm if the system package has been updated 12100 // An updated system app can be deleted. This will also have to restore 12101 // the system pkg from system partition 12102 // reader 12103 synchronized (mPackages) { 12104 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12105 } 12106 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12107 + " disabledPs=" + disabledPs); 12108 if (disabledPs == null) { 12109 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12110 return false; 12111 } else if (DEBUG_REMOVE) { 12112 Slog.d(TAG, "Deleting system pkg from data partition"); 12113 } 12114 if (DEBUG_REMOVE) { 12115 if (applyUserRestrictions) { 12116 Slog.d(TAG, "Remembering install states:"); 12117 for (int i = 0; i < allUserHandles.length; i++) { 12118 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12119 } 12120 } 12121 } 12122 // Delete the updated package 12123 outInfo.isRemovedPackageSystemUpdate = true; 12124 if (disabledPs.versionCode < newPs.versionCode) { 12125 // Delete data for downgrades 12126 flags &= ~PackageManager.DELETE_KEEP_DATA; 12127 } else { 12128 // Preserve data by setting flag 12129 flags |= PackageManager.DELETE_KEEP_DATA; 12130 } 12131 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12132 allUserHandles, perUserInstalled, outInfo, writeSettings); 12133 if (!ret) { 12134 return false; 12135 } 12136 // writer 12137 synchronized (mPackages) { 12138 // Reinstate the old system package 12139 mSettings.enableSystemPackageLPw(newPs.name); 12140 // Remove any native libraries from the upgraded package. 12141 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12142 } 12143 // Install the system package 12144 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12145 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12146 if (locationIsPrivileged(disabledPs.codePath)) { 12147 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12148 } 12149 12150 final PackageParser.Package newPkg; 12151 try { 12152 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12153 } catch (PackageManagerException e) { 12154 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12155 return false; 12156 } 12157 12158 // writer 12159 synchronized (mPackages) { 12160 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12161 updatePermissionsLPw(newPkg.packageName, newPkg, 12162 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12163 if (applyUserRestrictions) { 12164 if (DEBUG_REMOVE) { 12165 Slog.d(TAG, "Propagating install state across reinstall"); 12166 } 12167 for (int i = 0; i < allUserHandles.length; i++) { 12168 if (DEBUG_REMOVE) { 12169 Slog.d(TAG, " user " + allUserHandles[i] 12170 + " => " + perUserInstalled[i]); 12171 } 12172 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12173 } 12174 // Regardless of writeSettings we need to ensure that this restriction 12175 // state propagation is persisted 12176 mSettings.writeAllUsersPackageRestrictionsLPr(); 12177 } 12178 // can downgrade to reader here 12179 if (writeSettings) { 12180 mSettings.writeLPr(); 12181 } 12182 } 12183 return true; 12184 } 12185 12186 private boolean deleteInstalledPackageLI(PackageSetting ps, 12187 boolean deleteCodeAndResources, int flags, 12188 int[] allUserHandles, boolean[] perUserInstalled, 12189 PackageRemovedInfo outInfo, boolean writeSettings) { 12190 if (outInfo != null) { 12191 outInfo.uid = ps.appId; 12192 } 12193 12194 // Delete package data from internal structures and also remove data if flag is set 12195 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12196 12197 // Delete application code and resources 12198 if (deleteCodeAndResources && (outInfo != null)) { 12199 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12200 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12201 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12202 } 12203 return true; 12204 } 12205 12206 @Override 12207 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12208 int userId) { 12209 mContext.enforceCallingOrSelfPermission( 12210 android.Manifest.permission.DELETE_PACKAGES, null); 12211 synchronized (mPackages) { 12212 PackageSetting ps = mSettings.mPackages.get(packageName); 12213 if (ps == null) { 12214 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12215 return false; 12216 } 12217 if (!ps.getInstalled(userId)) { 12218 // Can't block uninstall for an app that is not installed or enabled. 12219 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12220 return false; 12221 } 12222 ps.setBlockUninstall(blockUninstall, userId); 12223 mSettings.writePackageRestrictionsLPr(userId); 12224 } 12225 return true; 12226 } 12227 12228 @Override 12229 public boolean getBlockUninstallForUser(String packageName, int userId) { 12230 synchronized (mPackages) { 12231 PackageSetting ps = mSettings.mPackages.get(packageName); 12232 if (ps == null) { 12233 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12234 return false; 12235 } 12236 return ps.getBlockUninstall(userId); 12237 } 12238 } 12239 12240 /* 12241 * This method handles package deletion in general 12242 */ 12243 private boolean deletePackageLI(String packageName, UserHandle user, 12244 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12245 int flags, PackageRemovedInfo outInfo, 12246 boolean writeSettings) { 12247 if (packageName == null) { 12248 Slog.w(TAG, "Attempt to delete null packageName."); 12249 return false; 12250 } 12251 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12252 PackageSetting ps; 12253 boolean dataOnly = false; 12254 int removeUser = -1; 12255 int appId = -1; 12256 synchronized (mPackages) { 12257 ps = mSettings.mPackages.get(packageName); 12258 if (ps == null) { 12259 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12260 return false; 12261 } 12262 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12263 && user.getIdentifier() != UserHandle.USER_ALL) { 12264 // The caller is asking that the package only be deleted for a single 12265 // user. To do this, we just mark its uninstalled state and delete 12266 // its data. If this is a system app, we only allow this to happen if 12267 // they have set the special DELETE_SYSTEM_APP which requests different 12268 // semantics than normal for uninstalling system apps. 12269 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12270 ps.setUserState(user.getIdentifier(), 12271 COMPONENT_ENABLED_STATE_DEFAULT, 12272 false, //installed 12273 true, //stopped 12274 true, //notLaunched 12275 false, //hidden 12276 null, null, null, 12277 false, // blockUninstall 12278 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12279 if (!isSystemApp(ps)) { 12280 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12281 // Other user still have this package installed, so all 12282 // we need to do is clear this user's data and save that 12283 // it is uninstalled. 12284 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12285 removeUser = user.getIdentifier(); 12286 appId = ps.appId; 12287 scheduleWritePackageRestrictionsLocked(removeUser); 12288 } else { 12289 // We need to set it back to 'installed' so the uninstall 12290 // broadcasts will be sent correctly. 12291 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12292 ps.setInstalled(true, user.getIdentifier()); 12293 } 12294 } else { 12295 // This is a system app, so we assume that the 12296 // other users still have this package installed, so all 12297 // we need to do is clear this user's data and save that 12298 // it is uninstalled. 12299 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12300 removeUser = user.getIdentifier(); 12301 appId = ps.appId; 12302 scheduleWritePackageRestrictionsLocked(removeUser); 12303 } 12304 } 12305 } 12306 12307 if (removeUser >= 0) { 12308 // From above, we determined that we are deleting this only 12309 // for a single user. Continue the work here. 12310 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12311 if (outInfo != null) { 12312 outInfo.removedPackage = packageName; 12313 outInfo.removedAppId = appId; 12314 outInfo.removedUsers = new int[] {removeUser}; 12315 } 12316 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12317 removeKeystoreDataIfNeeded(removeUser, appId); 12318 schedulePackageCleaning(packageName, removeUser, false); 12319 synchronized (mPackages) { 12320 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12321 scheduleWritePackageRestrictionsLocked(removeUser); 12322 } 12323 } 12324 return true; 12325 } 12326 12327 if (dataOnly) { 12328 // Delete application data first 12329 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12330 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12331 return true; 12332 } 12333 12334 boolean ret = false; 12335 if (isSystemApp(ps)) { 12336 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12337 // When an updated system application is deleted we delete the existing resources as well and 12338 // fall back to existing code in system partition 12339 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12340 flags, outInfo, writeSettings); 12341 } else { 12342 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12343 // Kill application pre-emptively especially for apps on sd. 12344 killApplication(packageName, ps.appId, "uninstall pkg"); 12345 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12346 allUserHandles, perUserInstalled, 12347 outInfo, writeSettings); 12348 } 12349 12350 return ret; 12351 } 12352 12353 private final class ClearStorageConnection implements ServiceConnection { 12354 IMediaContainerService mContainerService; 12355 12356 @Override 12357 public void onServiceConnected(ComponentName name, IBinder service) { 12358 synchronized (this) { 12359 mContainerService = IMediaContainerService.Stub.asInterface(service); 12360 notifyAll(); 12361 } 12362 } 12363 12364 @Override 12365 public void onServiceDisconnected(ComponentName name) { 12366 } 12367 } 12368 12369 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12370 final boolean mounted; 12371 if (Environment.isExternalStorageEmulated()) { 12372 mounted = true; 12373 } else { 12374 final String status = Environment.getExternalStorageState(); 12375 12376 mounted = status.equals(Environment.MEDIA_MOUNTED) 12377 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12378 } 12379 12380 if (!mounted) { 12381 return; 12382 } 12383 12384 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12385 int[] users; 12386 if (userId == UserHandle.USER_ALL) { 12387 users = sUserManager.getUserIds(); 12388 } else { 12389 users = new int[] { userId }; 12390 } 12391 final ClearStorageConnection conn = new ClearStorageConnection(); 12392 if (mContext.bindServiceAsUser( 12393 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12394 try { 12395 for (int curUser : users) { 12396 long timeout = SystemClock.uptimeMillis() + 5000; 12397 synchronized (conn) { 12398 long now = SystemClock.uptimeMillis(); 12399 while (conn.mContainerService == null && now < timeout) { 12400 try { 12401 conn.wait(timeout - now); 12402 } catch (InterruptedException e) { 12403 } 12404 } 12405 } 12406 if (conn.mContainerService == null) { 12407 return; 12408 } 12409 12410 final UserEnvironment userEnv = new UserEnvironment(curUser); 12411 clearDirectory(conn.mContainerService, 12412 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12413 if (allData) { 12414 clearDirectory(conn.mContainerService, 12415 userEnv.buildExternalStorageAppDataDirs(packageName)); 12416 clearDirectory(conn.mContainerService, 12417 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12418 } 12419 } 12420 } finally { 12421 mContext.unbindService(conn); 12422 } 12423 } 12424 } 12425 12426 @Override 12427 public void clearApplicationUserData(final String packageName, 12428 final IPackageDataObserver observer, final int userId) { 12429 mContext.enforceCallingOrSelfPermission( 12430 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12431 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12432 // Queue up an async operation since the package deletion may take a little while. 12433 mHandler.post(new Runnable() { 12434 public void run() { 12435 mHandler.removeCallbacks(this); 12436 final boolean succeeded; 12437 synchronized (mInstallLock) { 12438 succeeded = clearApplicationUserDataLI(packageName, userId); 12439 } 12440 clearExternalStorageDataSync(packageName, userId, true); 12441 if (succeeded) { 12442 // invoke DeviceStorageMonitor's update method to clear any notifications 12443 DeviceStorageMonitorInternal 12444 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12445 if (dsm != null) { 12446 dsm.checkMemory(); 12447 } 12448 } 12449 if(observer != null) { 12450 try { 12451 observer.onRemoveCompleted(packageName, succeeded); 12452 } catch (RemoteException e) { 12453 Log.i(TAG, "Observer no longer exists."); 12454 } 12455 } //end if observer 12456 } //end run 12457 }); 12458 } 12459 12460 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12461 if (packageName == null) { 12462 Slog.w(TAG, "Attempt to delete null packageName."); 12463 return false; 12464 } 12465 12466 // Try finding details about the requested package 12467 PackageParser.Package pkg; 12468 synchronized (mPackages) { 12469 pkg = mPackages.get(packageName); 12470 if (pkg == null) { 12471 final PackageSetting ps = mSettings.mPackages.get(packageName); 12472 if (ps != null) { 12473 pkg = ps.pkg; 12474 } 12475 } 12476 } 12477 12478 if (pkg == null) { 12479 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12480 } 12481 12482 // Always delete data directories for package, even if we found no other 12483 // record of app. This helps users recover from UID mismatches without 12484 // resorting to a full data wipe. 12485 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12486 if (retCode < 0) { 12487 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12488 return false; 12489 } 12490 12491 if (pkg == null) { 12492 return false; 12493 } 12494 12495 if (pkg != null && pkg.applicationInfo != null) { 12496 final int appId = pkg.applicationInfo.uid; 12497 removeKeystoreDataIfNeeded(userId, appId); 12498 } 12499 12500 // Create a native library symlink only if we have native libraries 12501 // and if the native libraries are 32 bit libraries. We do not provide 12502 // this symlink for 64 bit libraries. 12503 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12504 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12505 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12506 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12507 nativeLibPath, userId) < 0) { 12508 Slog.w(TAG, "Failed linking native library dir"); 12509 return false; 12510 } 12511 } 12512 12513 return true; 12514 } 12515 12516 /** 12517 * Remove entries from the keystore daemon. Will only remove it if the 12518 * {@code appId} is valid. 12519 */ 12520 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12521 if (appId < 0) { 12522 return; 12523 } 12524 12525 final KeyStore keyStore = KeyStore.getInstance(); 12526 if (keyStore != null) { 12527 if (userId == UserHandle.USER_ALL) { 12528 for (final int individual : sUserManager.getUserIds()) { 12529 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12530 } 12531 } else { 12532 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12533 } 12534 } else { 12535 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12536 } 12537 } 12538 12539 @Override 12540 public void deleteApplicationCacheFiles(final String packageName, 12541 final IPackageDataObserver observer) { 12542 mContext.enforceCallingOrSelfPermission( 12543 android.Manifest.permission.DELETE_CACHE_FILES, null); 12544 // Queue up an async operation since the package deletion may take a little while. 12545 final int userId = UserHandle.getCallingUserId(); 12546 mHandler.post(new Runnable() { 12547 public void run() { 12548 mHandler.removeCallbacks(this); 12549 final boolean succeded; 12550 synchronized (mInstallLock) { 12551 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12552 } 12553 clearExternalStorageDataSync(packageName, userId, false); 12554 if (observer != null) { 12555 try { 12556 observer.onRemoveCompleted(packageName, succeded); 12557 } catch (RemoteException e) { 12558 Log.i(TAG, "Observer no longer exists."); 12559 } 12560 } //end if observer 12561 } //end run 12562 }); 12563 } 12564 12565 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12566 if (packageName == null) { 12567 Slog.w(TAG, "Attempt to delete null packageName."); 12568 return false; 12569 } 12570 PackageParser.Package p; 12571 synchronized (mPackages) { 12572 p = mPackages.get(packageName); 12573 } 12574 if (p == null) { 12575 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12576 return false; 12577 } 12578 final ApplicationInfo applicationInfo = p.applicationInfo; 12579 if (applicationInfo == null) { 12580 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12581 return false; 12582 } 12583 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12584 if (retCode < 0) { 12585 Slog.w(TAG, "Couldn't remove cache files for package: " 12586 + packageName + " u" + userId); 12587 return false; 12588 } 12589 return true; 12590 } 12591 12592 @Override 12593 public void getPackageSizeInfo(final String packageName, int userHandle, 12594 final IPackageStatsObserver observer) { 12595 mContext.enforceCallingOrSelfPermission( 12596 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12597 if (packageName == null) { 12598 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12599 } 12600 12601 PackageStats stats = new PackageStats(packageName, userHandle); 12602 12603 /* 12604 * Queue up an async operation since the package measurement may take a 12605 * little while. 12606 */ 12607 Message msg = mHandler.obtainMessage(INIT_COPY); 12608 msg.obj = new MeasureParams(stats, observer); 12609 mHandler.sendMessage(msg); 12610 } 12611 12612 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12613 PackageStats pStats) { 12614 if (packageName == null) { 12615 Slog.w(TAG, "Attempt to get size of null packageName."); 12616 return false; 12617 } 12618 PackageParser.Package p; 12619 boolean dataOnly = false; 12620 String libDirRoot = null; 12621 String asecPath = null; 12622 PackageSetting ps = null; 12623 synchronized (mPackages) { 12624 p = mPackages.get(packageName); 12625 ps = mSettings.mPackages.get(packageName); 12626 if(p == null) { 12627 dataOnly = true; 12628 if((ps == null) || (ps.pkg == null)) { 12629 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12630 return false; 12631 } 12632 p = ps.pkg; 12633 } 12634 if (ps != null) { 12635 libDirRoot = ps.legacyNativeLibraryPathString; 12636 } 12637 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12638 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12639 if (secureContainerId != null) { 12640 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12641 } 12642 } 12643 } 12644 String publicSrcDir = null; 12645 if(!dataOnly) { 12646 final ApplicationInfo applicationInfo = p.applicationInfo; 12647 if (applicationInfo == null) { 12648 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12649 return false; 12650 } 12651 if (p.isForwardLocked()) { 12652 publicSrcDir = applicationInfo.getBaseResourcePath(); 12653 } 12654 } 12655 // TODO: extend to measure size of split APKs 12656 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12657 // not just the first level. 12658 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12659 // just the primary. 12660 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12661 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12662 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12663 if (res < 0) { 12664 return false; 12665 } 12666 12667 // Fix-up for forward-locked applications in ASEC containers. 12668 if (!isExternal(p)) { 12669 pStats.codeSize += pStats.externalCodeSize; 12670 pStats.externalCodeSize = 0L; 12671 } 12672 12673 return true; 12674 } 12675 12676 12677 @Override 12678 public void addPackageToPreferred(String packageName) { 12679 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12680 } 12681 12682 @Override 12683 public void removePackageFromPreferred(String packageName) { 12684 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12685 } 12686 12687 @Override 12688 public List<PackageInfo> getPreferredPackages(int flags) { 12689 return new ArrayList<PackageInfo>(); 12690 } 12691 12692 private int getUidTargetSdkVersionLockedLPr(int uid) { 12693 Object obj = mSettings.getUserIdLPr(uid); 12694 if (obj instanceof SharedUserSetting) { 12695 final SharedUserSetting sus = (SharedUserSetting) obj; 12696 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12697 final Iterator<PackageSetting> it = sus.packages.iterator(); 12698 while (it.hasNext()) { 12699 final PackageSetting ps = it.next(); 12700 if (ps.pkg != null) { 12701 int v = ps.pkg.applicationInfo.targetSdkVersion; 12702 if (v < vers) vers = v; 12703 } 12704 } 12705 return vers; 12706 } else if (obj instanceof PackageSetting) { 12707 final PackageSetting ps = (PackageSetting) obj; 12708 if (ps.pkg != null) { 12709 return ps.pkg.applicationInfo.targetSdkVersion; 12710 } 12711 } 12712 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12713 } 12714 12715 @Override 12716 public void addPreferredActivity(IntentFilter filter, int match, 12717 ComponentName[] set, ComponentName activity, int userId) { 12718 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12719 "Adding preferred"); 12720 } 12721 12722 private void addPreferredActivityInternal(IntentFilter filter, int match, 12723 ComponentName[] set, ComponentName activity, boolean always, int userId, 12724 String opname) { 12725 // writer 12726 int callingUid = Binder.getCallingUid(); 12727 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12728 if (filter.countActions() == 0) { 12729 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12730 return; 12731 } 12732 synchronized (mPackages) { 12733 if (mContext.checkCallingOrSelfPermission( 12734 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12735 != PackageManager.PERMISSION_GRANTED) { 12736 if (getUidTargetSdkVersionLockedLPr(callingUid) 12737 < Build.VERSION_CODES.FROYO) { 12738 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12739 + callingUid); 12740 return; 12741 } 12742 mContext.enforceCallingOrSelfPermission( 12743 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12744 } 12745 12746 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12747 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12748 + userId + ":"); 12749 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12750 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12751 scheduleWritePackageRestrictionsLocked(userId); 12752 } 12753 } 12754 12755 @Override 12756 public void replacePreferredActivity(IntentFilter filter, int match, 12757 ComponentName[] set, ComponentName activity, int userId) { 12758 if (filter.countActions() != 1) { 12759 throw new IllegalArgumentException( 12760 "replacePreferredActivity expects filter to have only 1 action."); 12761 } 12762 if (filter.countDataAuthorities() != 0 12763 || filter.countDataPaths() != 0 12764 || filter.countDataSchemes() > 1 12765 || filter.countDataTypes() != 0) { 12766 throw new IllegalArgumentException( 12767 "replacePreferredActivity expects filter to have no data authorities, " + 12768 "paths, or types; and at most one scheme."); 12769 } 12770 12771 final int callingUid = Binder.getCallingUid(); 12772 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12773 synchronized (mPackages) { 12774 if (mContext.checkCallingOrSelfPermission( 12775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12776 != PackageManager.PERMISSION_GRANTED) { 12777 if (getUidTargetSdkVersionLockedLPr(callingUid) 12778 < Build.VERSION_CODES.FROYO) { 12779 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12780 + Binder.getCallingUid()); 12781 return; 12782 } 12783 mContext.enforceCallingOrSelfPermission( 12784 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12785 } 12786 12787 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12788 if (pir != null) { 12789 // Get all of the existing entries that exactly match this filter. 12790 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12791 if (existing != null && existing.size() == 1) { 12792 PreferredActivity cur = existing.get(0); 12793 if (DEBUG_PREFERRED) { 12794 Slog.i(TAG, "Checking replace of preferred:"); 12795 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12796 if (!cur.mPref.mAlways) { 12797 Slog.i(TAG, " -- CUR; not mAlways!"); 12798 } else { 12799 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12800 Slog.i(TAG, " -- CUR: mSet=" 12801 + Arrays.toString(cur.mPref.mSetComponents)); 12802 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12803 Slog.i(TAG, " -- NEW: mMatch=" 12804 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12805 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12806 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12807 } 12808 } 12809 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12810 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12811 && cur.mPref.sameSet(set)) { 12812 // Setting the preferred activity to what it happens to be already 12813 if (DEBUG_PREFERRED) { 12814 Slog.i(TAG, "Replacing with same preferred activity " 12815 + cur.mPref.mShortComponent + " for user " 12816 + userId + ":"); 12817 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12818 } 12819 return; 12820 } 12821 } 12822 12823 if (existing != null) { 12824 if (DEBUG_PREFERRED) { 12825 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12826 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12827 } 12828 for (int i = 0; i < existing.size(); i++) { 12829 PreferredActivity pa = existing.get(i); 12830 if (DEBUG_PREFERRED) { 12831 Slog.i(TAG, "Removing existing preferred activity " 12832 + pa.mPref.mComponent + ":"); 12833 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12834 } 12835 pir.removeFilter(pa); 12836 } 12837 } 12838 } 12839 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12840 "Replacing preferred"); 12841 } 12842 } 12843 12844 @Override 12845 public void clearPackagePreferredActivities(String packageName) { 12846 final int uid = Binder.getCallingUid(); 12847 // writer 12848 synchronized (mPackages) { 12849 PackageParser.Package pkg = mPackages.get(packageName); 12850 if (pkg == null || pkg.applicationInfo.uid != uid) { 12851 if (mContext.checkCallingOrSelfPermission( 12852 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12853 != PackageManager.PERMISSION_GRANTED) { 12854 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12855 < Build.VERSION_CODES.FROYO) { 12856 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12857 + Binder.getCallingUid()); 12858 return; 12859 } 12860 mContext.enforceCallingOrSelfPermission( 12861 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12862 } 12863 } 12864 12865 int user = UserHandle.getCallingUserId(); 12866 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12867 scheduleWritePackageRestrictionsLocked(user); 12868 } 12869 } 12870 } 12871 12872 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12873 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12874 ArrayList<PreferredActivity> removed = null; 12875 boolean changed = false; 12876 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12877 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12878 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12879 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12880 continue; 12881 } 12882 Iterator<PreferredActivity> it = pir.filterIterator(); 12883 while (it.hasNext()) { 12884 PreferredActivity pa = it.next(); 12885 // Mark entry for removal only if it matches the package name 12886 // and the entry is of type "always". 12887 if (packageName == null || 12888 (pa.mPref.mComponent.getPackageName().equals(packageName) 12889 && pa.mPref.mAlways)) { 12890 if (removed == null) { 12891 removed = new ArrayList<PreferredActivity>(); 12892 } 12893 removed.add(pa); 12894 } 12895 } 12896 if (removed != null) { 12897 for (int j=0; j<removed.size(); j++) { 12898 PreferredActivity pa = removed.get(j); 12899 pir.removeFilter(pa); 12900 } 12901 changed = true; 12902 } 12903 } 12904 return changed; 12905 } 12906 12907 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12908 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12909 if (userId == UserHandle.USER_ALL) { 12910 if (mSettings.removeIntentFilterVerificationLPw(packageName, 12911 sUserManager.getUserIds())) { 12912 for (int oneUserId : sUserManager.getUserIds()) { 12913 scheduleWritePackageRestrictionsLocked(oneUserId); 12914 } 12915 } 12916 } else { 12917 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 12918 scheduleWritePackageRestrictionsLocked(userId); 12919 } 12920 } 12921 } 12922 12923 12924 void clearDefaultBrowserIfNeeded(String packageName) { 12925 for (int oneUserId : sUserManager.getUserIds()) { 12926 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 12927 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 12928 if (packageName.equals(defaultBrowserPackageName)) { 12929 setDefaultBrowserPackageName(null, oneUserId); 12930 } 12931 } 12932 } 12933 12934 @Override 12935 public void resetPreferredActivities(int userId) { 12936 /* TODO: Actually use userId. Why is it being passed in? */ 12937 mContext.enforceCallingOrSelfPermission( 12938 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12939 // writer 12940 synchronized (mPackages) { 12941 int user = UserHandle.getCallingUserId(); 12942 clearPackagePreferredActivitiesLPw(null, user); 12943 mSettings.readDefaultPreferredAppsLPw(this, user); 12944 scheduleWritePackageRestrictionsLocked(user); 12945 } 12946 } 12947 12948 @Override 12949 public int getPreferredActivities(List<IntentFilter> outFilters, 12950 List<ComponentName> outActivities, String packageName) { 12951 12952 int num = 0; 12953 final int userId = UserHandle.getCallingUserId(); 12954 // reader 12955 synchronized (mPackages) { 12956 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12957 if (pir != null) { 12958 final Iterator<PreferredActivity> it = pir.filterIterator(); 12959 while (it.hasNext()) { 12960 final PreferredActivity pa = it.next(); 12961 if (packageName == null 12962 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12963 && pa.mPref.mAlways)) { 12964 if (outFilters != null) { 12965 outFilters.add(new IntentFilter(pa)); 12966 } 12967 if (outActivities != null) { 12968 outActivities.add(pa.mPref.mComponent); 12969 } 12970 } 12971 } 12972 } 12973 } 12974 12975 return num; 12976 } 12977 12978 @Override 12979 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12980 int userId) { 12981 int callingUid = Binder.getCallingUid(); 12982 if (callingUid != Process.SYSTEM_UID) { 12983 throw new SecurityException( 12984 "addPersistentPreferredActivity can only be run by the system"); 12985 } 12986 if (filter.countActions() == 0) { 12987 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12988 return; 12989 } 12990 synchronized (mPackages) { 12991 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12992 " :"); 12993 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12994 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12995 new PersistentPreferredActivity(filter, activity)); 12996 scheduleWritePackageRestrictionsLocked(userId); 12997 } 12998 } 12999 13000 @Override 13001 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13002 int callingUid = Binder.getCallingUid(); 13003 if (callingUid != Process.SYSTEM_UID) { 13004 throw new SecurityException( 13005 "clearPackagePersistentPreferredActivities can only be run by the system"); 13006 } 13007 ArrayList<PersistentPreferredActivity> removed = null; 13008 boolean changed = false; 13009 synchronized (mPackages) { 13010 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13011 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13012 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13013 .valueAt(i); 13014 if (userId != thisUserId) { 13015 continue; 13016 } 13017 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13018 while (it.hasNext()) { 13019 PersistentPreferredActivity ppa = it.next(); 13020 // Mark entry for removal only if it matches the package name. 13021 if (ppa.mComponent.getPackageName().equals(packageName)) { 13022 if (removed == null) { 13023 removed = new ArrayList<PersistentPreferredActivity>(); 13024 } 13025 removed.add(ppa); 13026 } 13027 } 13028 if (removed != null) { 13029 for (int j=0; j<removed.size(); j++) { 13030 PersistentPreferredActivity ppa = removed.get(j); 13031 ppir.removeFilter(ppa); 13032 } 13033 changed = true; 13034 } 13035 } 13036 13037 if (changed) { 13038 scheduleWritePackageRestrictionsLocked(userId); 13039 } 13040 } 13041 } 13042 13043 /** 13044 * Non-Binder method, support for the backup/restore mechanism: write the 13045 * full set of preferred activities in its canonical XML format. Returns true 13046 * on success; false otherwise. 13047 */ 13048 @Override 13049 public byte[] getPreferredActivityBackup(int userId) { 13050 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13051 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13052 } 13053 13054 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13055 try { 13056 final XmlSerializer serializer = new FastXmlSerializer(); 13057 serializer.setOutput(dataStream, "utf-8"); 13058 serializer.startDocument(null, true); 13059 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13060 13061 synchronized (mPackages) { 13062 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13063 } 13064 13065 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13066 serializer.endDocument(); 13067 serializer.flush(); 13068 } catch (Exception e) { 13069 if (DEBUG_BACKUP) { 13070 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13071 } 13072 return null; 13073 } 13074 13075 return dataStream.toByteArray(); 13076 } 13077 13078 @Override 13079 public void restorePreferredActivities(byte[] backup, int userId) { 13080 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13081 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13082 } 13083 13084 try { 13085 final XmlPullParser parser = Xml.newPullParser(); 13086 parser.setInput(new ByteArrayInputStream(backup), null); 13087 13088 int type; 13089 while ((type = parser.next()) != XmlPullParser.START_TAG 13090 && type != XmlPullParser.END_DOCUMENT) { 13091 } 13092 if (type != XmlPullParser.START_TAG) { 13093 // oops didn't find a start tag?! 13094 if (DEBUG_BACKUP) { 13095 Slog.e(TAG, "Didn't find start tag during restore"); 13096 } 13097 return; 13098 } 13099 13100 // this is supposed to be TAG_PREFERRED_BACKUP 13101 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13102 if (DEBUG_BACKUP) { 13103 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13104 } 13105 return; 13106 } 13107 13108 // skip interfering stuff, then we're aligned with the backing implementation 13109 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13110 synchronized (mPackages) { 13111 mSettings.readPreferredActivitiesLPw(parser, userId); 13112 } 13113 } catch (Exception e) { 13114 if (DEBUG_BACKUP) { 13115 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13116 } 13117 } 13118 } 13119 13120 @Override 13121 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13122 int sourceUserId, int targetUserId, int flags) { 13123 mContext.enforceCallingOrSelfPermission( 13124 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13125 int callingUid = Binder.getCallingUid(); 13126 enforceOwnerRights(ownerPackage, callingUid); 13127 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13128 if (intentFilter.countActions() == 0) { 13129 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13130 return; 13131 } 13132 synchronized (mPackages) { 13133 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13134 ownerPackage, targetUserId, flags); 13135 CrossProfileIntentResolver resolver = 13136 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13137 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13138 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13139 if (existing != null) { 13140 int size = existing.size(); 13141 for (int i = 0; i < size; i++) { 13142 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13143 return; 13144 } 13145 } 13146 } 13147 resolver.addFilter(newFilter); 13148 scheduleWritePackageRestrictionsLocked(sourceUserId); 13149 } 13150 } 13151 13152 @Override 13153 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13154 mContext.enforceCallingOrSelfPermission( 13155 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13156 int callingUid = Binder.getCallingUid(); 13157 enforceOwnerRights(ownerPackage, callingUid); 13158 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13159 synchronized (mPackages) { 13160 CrossProfileIntentResolver resolver = 13161 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13162 ArraySet<CrossProfileIntentFilter> set = 13163 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13164 for (CrossProfileIntentFilter filter : set) { 13165 if (filter.getOwnerPackage().equals(ownerPackage)) { 13166 resolver.removeFilter(filter); 13167 } 13168 } 13169 scheduleWritePackageRestrictionsLocked(sourceUserId); 13170 } 13171 } 13172 13173 // Enforcing that callingUid is owning pkg on userId 13174 private void enforceOwnerRights(String pkg, int callingUid) { 13175 // The system owns everything. 13176 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13177 return; 13178 } 13179 int callingUserId = UserHandle.getUserId(callingUid); 13180 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13181 if (pi == null) { 13182 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13183 + callingUserId); 13184 } 13185 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13186 throw new SecurityException("Calling uid " + callingUid 13187 + " does not own package " + pkg); 13188 } 13189 } 13190 13191 @Override 13192 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13193 Intent intent = new Intent(Intent.ACTION_MAIN); 13194 intent.addCategory(Intent.CATEGORY_HOME); 13195 13196 final int callingUserId = UserHandle.getCallingUserId(); 13197 List<ResolveInfo> list = queryIntentActivities(intent, null, 13198 PackageManager.GET_META_DATA, callingUserId); 13199 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13200 true, false, false, callingUserId); 13201 13202 allHomeCandidates.clear(); 13203 if (list != null) { 13204 for (ResolveInfo ri : list) { 13205 allHomeCandidates.add(ri); 13206 } 13207 } 13208 return (preferred == null || preferred.activityInfo == null) 13209 ? null 13210 : new ComponentName(preferred.activityInfo.packageName, 13211 preferred.activityInfo.name); 13212 } 13213 13214 @Override 13215 public void setApplicationEnabledSetting(String appPackageName, 13216 int newState, int flags, int userId, String callingPackage) { 13217 if (!sUserManager.exists(userId)) return; 13218 if (callingPackage == null) { 13219 callingPackage = Integer.toString(Binder.getCallingUid()); 13220 } 13221 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13222 } 13223 13224 @Override 13225 public void setComponentEnabledSetting(ComponentName componentName, 13226 int newState, int flags, int userId) { 13227 if (!sUserManager.exists(userId)) return; 13228 setEnabledSetting(componentName.getPackageName(), 13229 componentName.getClassName(), newState, flags, userId, null); 13230 } 13231 13232 private void setEnabledSetting(final String packageName, String className, int newState, 13233 final int flags, int userId, String callingPackage) { 13234 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13235 || newState == COMPONENT_ENABLED_STATE_ENABLED 13236 || newState == COMPONENT_ENABLED_STATE_DISABLED 13237 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13238 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13239 throw new IllegalArgumentException("Invalid new component state: " 13240 + newState); 13241 } 13242 PackageSetting pkgSetting; 13243 final int uid = Binder.getCallingUid(); 13244 final int permission = mContext.checkCallingOrSelfPermission( 13245 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13246 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13247 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13248 boolean sendNow = false; 13249 boolean isApp = (className == null); 13250 String componentName = isApp ? packageName : className; 13251 int packageUid = -1; 13252 ArrayList<String> components; 13253 13254 // writer 13255 synchronized (mPackages) { 13256 pkgSetting = mSettings.mPackages.get(packageName); 13257 if (pkgSetting == null) { 13258 if (className == null) { 13259 throw new IllegalArgumentException( 13260 "Unknown package: " + packageName); 13261 } 13262 throw new IllegalArgumentException( 13263 "Unknown component: " + packageName 13264 + "/" + className); 13265 } 13266 // Allow root and verify that userId is not being specified by a different user 13267 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13268 throw new SecurityException( 13269 "Permission Denial: attempt to change component state from pid=" 13270 + Binder.getCallingPid() 13271 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13272 } 13273 if (className == null) { 13274 // We're dealing with an application/package level state change 13275 if (pkgSetting.getEnabled(userId) == newState) { 13276 // Nothing to do 13277 return; 13278 } 13279 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13280 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13281 // Don't care about who enables an app. 13282 callingPackage = null; 13283 } 13284 pkgSetting.setEnabled(newState, userId, callingPackage); 13285 // pkgSetting.pkg.mSetEnabled = newState; 13286 } else { 13287 // We're dealing with a component level state change 13288 // First, verify that this is a valid class name. 13289 PackageParser.Package pkg = pkgSetting.pkg; 13290 if (pkg == null || !pkg.hasComponentClassName(className)) { 13291 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13292 throw new IllegalArgumentException("Component class " + className 13293 + " does not exist in " + packageName); 13294 } else { 13295 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13296 + className + " does not exist in " + packageName); 13297 } 13298 } 13299 switch (newState) { 13300 case COMPONENT_ENABLED_STATE_ENABLED: 13301 if (!pkgSetting.enableComponentLPw(className, userId)) { 13302 return; 13303 } 13304 break; 13305 case COMPONENT_ENABLED_STATE_DISABLED: 13306 if (!pkgSetting.disableComponentLPw(className, userId)) { 13307 return; 13308 } 13309 break; 13310 case COMPONENT_ENABLED_STATE_DEFAULT: 13311 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13312 return; 13313 } 13314 break; 13315 default: 13316 Slog.e(TAG, "Invalid new component state: " + newState); 13317 return; 13318 } 13319 } 13320 scheduleWritePackageRestrictionsLocked(userId); 13321 components = mPendingBroadcasts.get(userId, packageName); 13322 final boolean newPackage = components == null; 13323 if (newPackage) { 13324 components = new ArrayList<String>(); 13325 } 13326 if (!components.contains(componentName)) { 13327 components.add(componentName); 13328 } 13329 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13330 sendNow = true; 13331 // Purge entry from pending broadcast list if another one exists already 13332 // since we are sending one right away. 13333 mPendingBroadcasts.remove(userId, packageName); 13334 } else { 13335 if (newPackage) { 13336 mPendingBroadcasts.put(userId, packageName, components); 13337 } 13338 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13339 // Schedule a message 13340 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13341 } 13342 } 13343 } 13344 13345 long callingId = Binder.clearCallingIdentity(); 13346 try { 13347 if (sendNow) { 13348 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13349 sendPackageChangedBroadcast(packageName, 13350 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13351 } 13352 } finally { 13353 Binder.restoreCallingIdentity(callingId); 13354 } 13355 } 13356 13357 private void sendPackageChangedBroadcast(String packageName, 13358 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13359 if (DEBUG_INSTALL) 13360 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13361 + componentNames); 13362 Bundle extras = new Bundle(4); 13363 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13364 String nameList[] = new String[componentNames.size()]; 13365 componentNames.toArray(nameList); 13366 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13367 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13368 extras.putInt(Intent.EXTRA_UID, packageUid); 13369 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13370 new int[] {UserHandle.getUserId(packageUid)}); 13371 } 13372 13373 @Override 13374 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13375 if (!sUserManager.exists(userId)) return; 13376 final int uid = Binder.getCallingUid(); 13377 final int permission = mContext.checkCallingOrSelfPermission( 13378 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13379 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13380 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13381 // writer 13382 synchronized (mPackages) { 13383 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13384 allowedByPermission, uid, userId)) { 13385 scheduleWritePackageRestrictionsLocked(userId); 13386 } 13387 } 13388 } 13389 13390 @Override 13391 public String getInstallerPackageName(String packageName) { 13392 // reader 13393 synchronized (mPackages) { 13394 return mSettings.getInstallerPackageNameLPr(packageName); 13395 } 13396 } 13397 13398 @Override 13399 public int getApplicationEnabledSetting(String packageName, int userId) { 13400 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13401 int uid = Binder.getCallingUid(); 13402 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13403 // reader 13404 synchronized (mPackages) { 13405 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13406 } 13407 } 13408 13409 @Override 13410 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13411 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13412 int uid = Binder.getCallingUid(); 13413 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13414 // reader 13415 synchronized (mPackages) { 13416 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13417 } 13418 } 13419 13420 @Override 13421 public void enterSafeMode() { 13422 enforceSystemOrRoot("Only the system can request entering safe mode"); 13423 13424 if (!mSystemReady) { 13425 mSafeMode = true; 13426 } 13427 } 13428 13429 @Override 13430 public void systemReady() { 13431 mSystemReady = true; 13432 13433 // Read the compatibilty setting when the system is ready. 13434 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13435 mContext.getContentResolver(), 13436 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13437 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13438 if (DEBUG_SETTINGS) { 13439 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13440 } 13441 13442 synchronized (mPackages) { 13443 // Verify that all of the preferred activity components actually 13444 // exist. It is possible for applications to be updated and at 13445 // that point remove a previously declared activity component that 13446 // had been set as a preferred activity. We try to clean this up 13447 // the next time we encounter that preferred activity, but it is 13448 // possible for the user flow to never be able to return to that 13449 // situation so here we do a sanity check to make sure we haven't 13450 // left any junk around. 13451 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13452 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13453 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13454 removed.clear(); 13455 for (PreferredActivity pa : pir.filterSet()) { 13456 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13457 removed.add(pa); 13458 } 13459 } 13460 if (removed.size() > 0) { 13461 for (int r=0; r<removed.size(); r++) { 13462 PreferredActivity pa = removed.get(r); 13463 Slog.w(TAG, "Removing dangling preferred activity: " 13464 + pa.mPref.mComponent); 13465 pir.removeFilter(pa); 13466 } 13467 mSettings.writePackageRestrictionsLPr( 13468 mSettings.mPreferredActivities.keyAt(i)); 13469 } 13470 } 13471 } 13472 sUserManager.systemReady(); 13473 13474 // Kick off any messages waiting for system ready 13475 if (mPostSystemReadyMessages != null) { 13476 for (Message msg : mPostSystemReadyMessages) { 13477 msg.sendToTarget(); 13478 } 13479 mPostSystemReadyMessages = null; 13480 } 13481 13482 // Watch for external volumes that come and go over time 13483 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13484 storage.registerListener(mStorageListener); 13485 13486 mInstallerService.systemReady(); 13487 } 13488 13489 @Override 13490 public boolean isSafeMode() { 13491 return mSafeMode; 13492 } 13493 13494 @Override 13495 public boolean hasSystemUidErrors() { 13496 return mHasSystemUidErrors; 13497 } 13498 13499 static String arrayToString(int[] array) { 13500 StringBuffer buf = new StringBuffer(128); 13501 buf.append('['); 13502 if (array != null) { 13503 for (int i=0; i<array.length; i++) { 13504 if (i > 0) buf.append(", "); 13505 buf.append(array[i]); 13506 } 13507 } 13508 buf.append(']'); 13509 return buf.toString(); 13510 } 13511 13512 static class DumpState { 13513 public static final int DUMP_LIBS = 1 << 0; 13514 public static final int DUMP_FEATURES = 1 << 1; 13515 public static final int DUMP_RESOLVERS = 1 << 2; 13516 public static final int DUMP_PERMISSIONS = 1 << 3; 13517 public static final int DUMP_PACKAGES = 1 << 4; 13518 public static final int DUMP_SHARED_USERS = 1 << 5; 13519 public static final int DUMP_MESSAGES = 1 << 6; 13520 public static final int DUMP_PROVIDERS = 1 << 7; 13521 public static final int DUMP_VERIFIERS = 1 << 8; 13522 public static final int DUMP_PREFERRED = 1 << 9; 13523 public static final int DUMP_PREFERRED_XML = 1 << 10; 13524 public static final int DUMP_KEYSETS = 1 << 11; 13525 public static final int DUMP_VERSION = 1 << 12; 13526 public static final int DUMP_INSTALLS = 1 << 13; 13527 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13528 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13529 13530 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13531 13532 private int mTypes; 13533 13534 private int mOptions; 13535 13536 private boolean mTitlePrinted; 13537 13538 private SharedUserSetting mSharedUser; 13539 13540 public boolean isDumping(int type) { 13541 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13542 return true; 13543 } 13544 13545 return (mTypes & type) != 0; 13546 } 13547 13548 public void setDump(int type) { 13549 mTypes |= type; 13550 } 13551 13552 public boolean isOptionEnabled(int option) { 13553 return (mOptions & option) != 0; 13554 } 13555 13556 public void setOptionEnabled(int option) { 13557 mOptions |= option; 13558 } 13559 13560 public boolean onTitlePrinted() { 13561 final boolean printed = mTitlePrinted; 13562 mTitlePrinted = true; 13563 return printed; 13564 } 13565 13566 public boolean getTitlePrinted() { 13567 return mTitlePrinted; 13568 } 13569 13570 public void setTitlePrinted(boolean enabled) { 13571 mTitlePrinted = enabled; 13572 } 13573 13574 public SharedUserSetting getSharedUser() { 13575 return mSharedUser; 13576 } 13577 13578 public void setSharedUser(SharedUserSetting user) { 13579 mSharedUser = user; 13580 } 13581 } 13582 13583 @Override 13584 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13585 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13586 != PackageManager.PERMISSION_GRANTED) { 13587 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13588 + Binder.getCallingPid() 13589 + ", uid=" + Binder.getCallingUid() 13590 + " without permission " 13591 + android.Manifest.permission.DUMP); 13592 return; 13593 } 13594 13595 DumpState dumpState = new DumpState(); 13596 boolean fullPreferred = false; 13597 boolean checkin = false; 13598 13599 String packageName = null; 13600 13601 int opti = 0; 13602 while (opti < args.length) { 13603 String opt = args[opti]; 13604 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13605 break; 13606 } 13607 opti++; 13608 13609 if ("-a".equals(opt)) { 13610 // Right now we only know how to print all. 13611 } else if ("-h".equals(opt)) { 13612 pw.println("Package manager dump options:"); 13613 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13614 pw.println(" --checkin: dump for a checkin"); 13615 pw.println(" -f: print details of intent filters"); 13616 pw.println(" -h: print this help"); 13617 pw.println(" cmd may be one of:"); 13618 pw.println(" l[ibraries]: list known shared libraries"); 13619 pw.println(" f[ibraries]: list device features"); 13620 pw.println(" k[eysets]: print known keysets"); 13621 pw.println(" r[esolvers]: dump intent resolvers"); 13622 pw.println(" perm[issions]: dump permissions"); 13623 pw.println(" pref[erred]: print preferred package settings"); 13624 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13625 pw.println(" prov[iders]: dump content providers"); 13626 pw.println(" p[ackages]: dump installed packages"); 13627 pw.println(" s[hared-users]: dump shared user IDs"); 13628 pw.println(" m[essages]: print collected runtime messages"); 13629 pw.println(" v[erifiers]: print package verifier info"); 13630 pw.println(" version: print database version info"); 13631 pw.println(" write: write current settings now"); 13632 pw.println(" <package.name>: info about given package"); 13633 pw.println(" installs: details about install sessions"); 13634 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13635 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13636 return; 13637 } else if ("--checkin".equals(opt)) { 13638 checkin = true; 13639 } else if ("-f".equals(opt)) { 13640 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13641 } else { 13642 pw.println("Unknown argument: " + opt + "; use -h for help"); 13643 } 13644 } 13645 13646 // Is the caller requesting to dump a particular piece of data? 13647 if (opti < args.length) { 13648 String cmd = args[opti]; 13649 opti++; 13650 // Is this a package name? 13651 if ("android".equals(cmd) || cmd.contains(".")) { 13652 packageName = cmd; 13653 // When dumping a single package, we always dump all of its 13654 // filter information since the amount of data will be reasonable. 13655 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13656 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13657 dumpState.setDump(DumpState.DUMP_LIBS); 13658 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13659 dumpState.setDump(DumpState.DUMP_FEATURES); 13660 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13661 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13662 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13663 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13664 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13665 dumpState.setDump(DumpState.DUMP_PREFERRED); 13666 } else if ("preferred-xml".equals(cmd)) { 13667 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13668 if (opti < args.length && "--full".equals(args[opti])) { 13669 fullPreferred = true; 13670 opti++; 13671 } 13672 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13673 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13674 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13675 dumpState.setDump(DumpState.DUMP_PACKAGES); 13676 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13677 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13678 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13679 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13680 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13681 dumpState.setDump(DumpState.DUMP_MESSAGES); 13682 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13683 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13684 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13685 || "intent-filter-verifiers".equals(cmd)) { 13686 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13687 } else if ("version".equals(cmd)) { 13688 dumpState.setDump(DumpState.DUMP_VERSION); 13689 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13690 dumpState.setDump(DumpState.DUMP_KEYSETS); 13691 } else if ("installs".equals(cmd)) { 13692 dumpState.setDump(DumpState.DUMP_INSTALLS); 13693 } else if ("write".equals(cmd)) { 13694 synchronized (mPackages) { 13695 mSettings.writeLPr(); 13696 pw.println("Settings written."); 13697 return; 13698 } 13699 } 13700 } 13701 13702 if (checkin) { 13703 pw.println("vers,1"); 13704 } 13705 13706 // reader 13707 synchronized (mPackages) { 13708 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13709 if (!checkin) { 13710 if (dumpState.onTitlePrinted()) 13711 pw.println(); 13712 pw.println("Database versions:"); 13713 pw.print(" SDK Version:"); 13714 pw.print(" internal="); 13715 pw.print(mSettings.mInternalSdkPlatform); 13716 pw.print(" external="); 13717 pw.println(mSettings.mExternalSdkPlatform); 13718 pw.print(" DB Version:"); 13719 pw.print(" internal="); 13720 pw.print(mSettings.mInternalDatabaseVersion); 13721 pw.print(" external="); 13722 pw.println(mSettings.mExternalDatabaseVersion); 13723 } 13724 } 13725 13726 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13727 if (!checkin) { 13728 if (dumpState.onTitlePrinted()) 13729 pw.println(); 13730 pw.println("Verifiers:"); 13731 pw.print(" Required: "); 13732 pw.print(mRequiredVerifierPackage); 13733 pw.print(" (uid="); 13734 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13735 pw.println(")"); 13736 } else if (mRequiredVerifierPackage != null) { 13737 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13738 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13739 } 13740 } 13741 13742 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13743 packageName == null) { 13744 if (mIntentFilterVerifierComponent != null) { 13745 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13746 if (!checkin) { 13747 if (dumpState.onTitlePrinted()) 13748 pw.println(); 13749 pw.println("Intent Filter Verifier:"); 13750 pw.print(" Using: "); 13751 pw.print(verifierPackageName); 13752 pw.print(" (uid="); 13753 pw.print(getPackageUid(verifierPackageName, 0)); 13754 pw.println(")"); 13755 } else if (verifierPackageName != null) { 13756 pw.print("ifv,"); pw.print(verifierPackageName); 13757 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13758 } 13759 } else { 13760 pw.println(); 13761 pw.println("No Intent Filter Verifier available!"); 13762 } 13763 } 13764 13765 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13766 boolean printedHeader = false; 13767 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13768 while (it.hasNext()) { 13769 String name = it.next(); 13770 SharedLibraryEntry ent = mSharedLibraries.get(name); 13771 if (!checkin) { 13772 if (!printedHeader) { 13773 if (dumpState.onTitlePrinted()) 13774 pw.println(); 13775 pw.println("Libraries:"); 13776 printedHeader = true; 13777 } 13778 pw.print(" "); 13779 } else { 13780 pw.print("lib,"); 13781 } 13782 pw.print(name); 13783 if (!checkin) { 13784 pw.print(" -> "); 13785 } 13786 if (ent.path != null) { 13787 if (!checkin) { 13788 pw.print("(jar) "); 13789 pw.print(ent.path); 13790 } else { 13791 pw.print(",jar,"); 13792 pw.print(ent.path); 13793 } 13794 } else { 13795 if (!checkin) { 13796 pw.print("(apk) "); 13797 pw.print(ent.apk); 13798 } else { 13799 pw.print(",apk,"); 13800 pw.print(ent.apk); 13801 } 13802 } 13803 pw.println(); 13804 } 13805 } 13806 13807 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13808 if (dumpState.onTitlePrinted()) 13809 pw.println(); 13810 if (!checkin) { 13811 pw.println("Features:"); 13812 } 13813 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13814 while (it.hasNext()) { 13815 String name = it.next(); 13816 if (!checkin) { 13817 pw.print(" "); 13818 } else { 13819 pw.print("feat,"); 13820 } 13821 pw.println(name); 13822 } 13823 } 13824 13825 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13826 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13827 : "Activity Resolver Table:", " ", packageName, 13828 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13829 dumpState.setTitlePrinted(true); 13830 } 13831 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13832 : "Receiver Resolver Table:", " ", packageName, 13833 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13834 dumpState.setTitlePrinted(true); 13835 } 13836 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13837 : "Service Resolver Table:", " ", packageName, 13838 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13839 dumpState.setTitlePrinted(true); 13840 } 13841 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13842 : "Provider Resolver Table:", " ", packageName, 13843 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13844 dumpState.setTitlePrinted(true); 13845 } 13846 } 13847 13848 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13849 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13850 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13851 int user = mSettings.mPreferredActivities.keyAt(i); 13852 if (pir.dump(pw, 13853 dumpState.getTitlePrinted() 13854 ? "\nPreferred Activities User " + user + ":" 13855 : "Preferred Activities User " + user + ":", " ", 13856 packageName, true, false)) { 13857 dumpState.setTitlePrinted(true); 13858 } 13859 } 13860 } 13861 13862 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13863 pw.flush(); 13864 FileOutputStream fout = new FileOutputStream(fd); 13865 BufferedOutputStream str = new BufferedOutputStream(fout); 13866 XmlSerializer serializer = new FastXmlSerializer(); 13867 try { 13868 serializer.setOutput(str, "utf-8"); 13869 serializer.startDocument(null, true); 13870 serializer.setFeature( 13871 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13872 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13873 serializer.endDocument(); 13874 serializer.flush(); 13875 } catch (IllegalArgumentException e) { 13876 pw.println("Failed writing: " + e); 13877 } catch (IllegalStateException e) { 13878 pw.println("Failed writing: " + e); 13879 } catch (IOException e) { 13880 pw.println("Failed writing: " + e); 13881 } 13882 } 13883 13884 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13885 pw.println(); 13886 int count = mSettings.mPackages.size(); 13887 if (count == 0) { 13888 pw.println("No domain preferred apps!"); 13889 pw.println(); 13890 } else { 13891 final String prefix = " "; 13892 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13893 if (allPackageSettings.size() == 0) { 13894 pw.println("No domain preferred apps!"); 13895 pw.println(); 13896 } else { 13897 pw.println("Domain preferred apps status:"); 13898 pw.println(); 13899 count = 0; 13900 for (PackageSetting ps : allPackageSettings) { 13901 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13902 if (ivi == null || ivi.getPackageName() == null) continue; 13903 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13904 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13905 pw.println(prefix + "Status: " + ivi.getStatusString()); 13906 pw.println(); 13907 count++; 13908 } 13909 if (count == 0) { 13910 pw.println(prefix + "No domain preferred app status!"); 13911 pw.println(); 13912 } 13913 for (int userId : sUserManager.getUserIds()) { 13914 pw.println("Domain preferred apps for User " + userId + ":"); 13915 pw.println(); 13916 count = 0; 13917 for (PackageSetting ps : allPackageSettings) { 13918 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13919 if (ivi == null || ivi.getPackageName() == null) { 13920 continue; 13921 } 13922 final int status = ps.getDomainVerificationStatusForUser(userId); 13923 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13924 continue; 13925 } 13926 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13927 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13928 String statusStr = IntentFilterVerificationInfo. 13929 getStatusStringFromValue(status); 13930 pw.println(prefix + "Status: " + statusStr); 13931 pw.println(); 13932 count++; 13933 } 13934 if (count == 0) { 13935 pw.println(prefix + "No domain preferred apps!"); 13936 pw.println(); 13937 } 13938 } 13939 } 13940 } 13941 } 13942 13943 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13944 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13945 if (packageName == null) { 13946 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13947 if (iperm == 0) { 13948 if (dumpState.onTitlePrinted()) 13949 pw.println(); 13950 pw.println("AppOp Permissions:"); 13951 } 13952 pw.print(" AppOp Permission "); 13953 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13954 pw.println(":"); 13955 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13956 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13957 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13958 } 13959 } 13960 } 13961 } 13962 13963 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13964 boolean printedSomething = false; 13965 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13966 if (packageName != null && !packageName.equals(p.info.packageName)) { 13967 continue; 13968 } 13969 if (!printedSomething) { 13970 if (dumpState.onTitlePrinted()) 13971 pw.println(); 13972 pw.println("Registered ContentProviders:"); 13973 printedSomething = true; 13974 } 13975 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13976 pw.print(" "); pw.println(p.toString()); 13977 } 13978 printedSomething = false; 13979 for (Map.Entry<String, PackageParser.Provider> entry : 13980 mProvidersByAuthority.entrySet()) { 13981 PackageParser.Provider p = entry.getValue(); 13982 if (packageName != null && !packageName.equals(p.info.packageName)) { 13983 continue; 13984 } 13985 if (!printedSomething) { 13986 if (dumpState.onTitlePrinted()) 13987 pw.println(); 13988 pw.println("ContentProvider Authorities:"); 13989 printedSomething = true; 13990 } 13991 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13992 pw.print(" "); pw.println(p.toString()); 13993 if (p.info != null && p.info.applicationInfo != null) { 13994 final String appInfo = p.info.applicationInfo.toString(); 13995 pw.print(" applicationInfo="); pw.println(appInfo); 13996 } 13997 } 13998 } 13999 14000 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14001 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14002 } 14003 14004 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14005 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14006 } 14007 14008 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14009 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14010 } 14011 14012 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14013 // XXX should handle packageName != null by dumping only install data that 14014 // the given package is involved with. 14015 if (dumpState.onTitlePrinted()) pw.println(); 14016 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14017 } 14018 14019 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14020 if (dumpState.onTitlePrinted()) pw.println(); 14021 mSettings.dumpReadMessagesLPr(pw, dumpState); 14022 14023 pw.println(); 14024 pw.println("Package warning messages:"); 14025 BufferedReader in = null; 14026 String line = null; 14027 try { 14028 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14029 while ((line = in.readLine()) != null) { 14030 if (line.contains("ignored: updated version")) continue; 14031 pw.println(line); 14032 } 14033 } catch (IOException ignored) { 14034 } finally { 14035 IoUtils.closeQuietly(in); 14036 } 14037 } 14038 14039 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14040 BufferedReader in = null; 14041 String line = null; 14042 try { 14043 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14044 while ((line = in.readLine()) != null) { 14045 if (line.contains("ignored: updated version")) continue; 14046 pw.print("msg,"); 14047 pw.println(line); 14048 } 14049 } catch (IOException ignored) { 14050 } finally { 14051 IoUtils.closeQuietly(in); 14052 } 14053 } 14054 } 14055 } 14056 14057 // ------- apps on sdcard specific code ------- 14058 static final boolean DEBUG_SD_INSTALL = false; 14059 14060 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14061 14062 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14063 14064 private boolean mMediaMounted = false; 14065 14066 static String getEncryptKey() { 14067 try { 14068 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14069 SD_ENCRYPTION_KEYSTORE_NAME); 14070 if (sdEncKey == null) { 14071 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14072 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14073 if (sdEncKey == null) { 14074 Slog.e(TAG, "Failed to create encryption keys"); 14075 return null; 14076 } 14077 } 14078 return sdEncKey; 14079 } catch (NoSuchAlgorithmException nsae) { 14080 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14081 return null; 14082 } catch (IOException ioe) { 14083 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14084 return null; 14085 } 14086 } 14087 14088 /* 14089 * Update media status on PackageManager. 14090 */ 14091 @Override 14092 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14093 int callingUid = Binder.getCallingUid(); 14094 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14095 throw new SecurityException("Media status can only be updated by the system"); 14096 } 14097 // reader; this apparently protects mMediaMounted, but should probably 14098 // be a different lock in that case. 14099 synchronized (mPackages) { 14100 Log.i(TAG, "Updating external media status from " 14101 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14102 + (mediaStatus ? "mounted" : "unmounted")); 14103 if (DEBUG_SD_INSTALL) 14104 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14105 + ", mMediaMounted=" + mMediaMounted); 14106 if (mediaStatus == mMediaMounted) { 14107 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14108 : 0, -1); 14109 mHandler.sendMessage(msg); 14110 return; 14111 } 14112 mMediaMounted = mediaStatus; 14113 } 14114 // Queue up an async operation since the package installation may take a 14115 // little while. 14116 mHandler.post(new Runnable() { 14117 public void run() { 14118 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14119 } 14120 }); 14121 } 14122 14123 /** 14124 * Called by MountService when the initial ASECs to scan are available. 14125 * Should block until all the ASEC containers are finished being scanned. 14126 */ 14127 public void scanAvailableAsecs() { 14128 updateExternalMediaStatusInner(true, false, false); 14129 if (mShouldRestoreconData) { 14130 SELinuxMMAC.setRestoreconDone(); 14131 mShouldRestoreconData = false; 14132 } 14133 } 14134 14135 /* 14136 * Collect information of applications on external media, map them against 14137 * existing containers and update information based on current mount status. 14138 * Please note that we always have to report status if reportStatus has been 14139 * set to true especially when unloading packages. 14140 */ 14141 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14142 boolean externalStorage) { 14143 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14144 int[] uidArr = EmptyArray.INT; 14145 14146 final String[] list = PackageHelper.getSecureContainerList(); 14147 if (ArrayUtils.isEmpty(list)) { 14148 Log.i(TAG, "No secure containers found"); 14149 } else { 14150 // Process list of secure containers and categorize them 14151 // as active or stale based on their package internal state. 14152 14153 // reader 14154 synchronized (mPackages) { 14155 for (String cid : list) { 14156 // Leave stages untouched for now; installer service owns them 14157 if (PackageInstallerService.isStageName(cid)) continue; 14158 14159 if (DEBUG_SD_INSTALL) 14160 Log.i(TAG, "Processing container " + cid); 14161 String pkgName = getAsecPackageName(cid); 14162 if (pkgName == null) { 14163 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14164 continue; 14165 } 14166 if (DEBUG_SD_INSTALL) 14167 Log.i(TAG, "Looking for pkg : " + pkgName); 14168 14169 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14170 if (ps == null) { 14171 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14172 continue; 14173 } 14174 14175 /* 14176 * Skip packages that are not external if we're unmounting 14177 * external storage. 14178 */ 14179 if (externalStorage && !isMounted && !isExternal(ps)) { 14180 continue; 14181 } 14182 14183 final AsecInstallArgs args = new AsecInstallArgs(cid, 14184 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14185 // The package status is changed only if the code path 14186 // matches between settings and the container id. 14187 if (ps.codePathString != null 14188 && ps.codePathString.startsWith(args.getCodePath())) { 14189 if (DEBUG_SD_INSTALL) { 14190 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14191 + " at code path: " + ps.codePathString); 14192 } 14193 14194 // We do have a valid package installed on sdcard 14195 processCids.put(args, ps.codePathString); 14196 final int uid = ps.appId; 14197 if (uid != -1) { 14198 uidArr = ArrayUtils.appendInt(uidArr, uid); 14199 } 14200 } else { 14201 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14202 + ps.codePathString); 14203 } 14204 } 14205 } 14206 14207 Arrays.sort(uidArr); 14208 } 14209 14210 // Process packages with valid entries. 14211 if (isMounted) { 14212 if (DEBUG_SD_INSTALL) 14213 Log.i(TAG, "Loading packages"); 14214 loadMediaPackages(processCids, uidArr); 14215 startCleaningPackages(); 14216 mInstallerService.onSecureContainersAvailable(); 14217 } else { 14218 if (DEBUG_SD_INSTALL) 14219 Log.i(TAG, "Unloading packages"); 14220 unloadMediaPackages(processCids, uidArr, reportStatus); 14221 } 14222 } 14223 14224 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14225 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14226 final int size = infos.size(); 14227 final String[] packageNames = new String[size]; 14228 final int[] packageUids = new int[size]; 14229 for (int i = 0; i < size; i++) { 14230 final ApplicationInfo info = infos.get(i); 14231 packageNames[i] = info.packageName; 14232 packageUids[i] = info.uid; 14233 } 14234 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14235 finishedReceiver); 14236 } 14237 14238 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14239 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14240 sendResourcesChangedBroadcast(mediaStatus, replacing, 14241 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14242 } 14243 14244 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14245 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14246 int size = pkgList.length; 14247 if (size > 0) { 14248 // Send broadcasts here 14249 Bundle extras = new Bundle(); 14250 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14251 if (uidArr != null) { 14252 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14253 } 14254 if (replacing) { 14255 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14256 } 14257 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14258 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14259 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14260 } 14261 } 14262 14263 /* 14264 * Look at potentially valid container ids from processCids If package 14265 * information doesn't match the one on record or package scanning fails, 14266 * the cid is added to list of removeCids. We currently don't delete stale 14267 * containers. 14268 */ 14269 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14270 ArrayList<String> pkgList = new ArrayList<String>(); 14271 Set<AsecInstallArgs> keys = processCids.keySet(); 14272 14273 for (AsecInstallArgs args : keys) { 14274 String codePath = processCids.get(args); 14275 if (DEBUG_SD_INSTALL) 14276 Log.i(TAG, "Loading container : " + args.cid); 14277 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14278 try { 14279 // Make sure there are no container errors first. 14280 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14281 Slog.e(TAG, "Failed to mount cid : " + args.cid 14282 + " when installing from sdcard"); 14283 continue; 14284 } 14285 // Check code path here. 14286 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14287 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14288 + " does not match one in settings " + codePath); 14289 continue; 14290 } 14291 // Parse package 14292 int parseFlags = mDefParseFlags; 14293 if (args.isExternalAsec()) { 14294 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14295 } 14296 if (args.isFwdLocked()) { 14297 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14298 } 14299 14300 synchronized (mInstallLock) { 14301 PackageParser.Package pkg = null; 14302 try { 14303 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14304 } catch (PackageManagerException e) { 14305 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14306 } 14307 // Scan the package 14308 if (pkg != null) { 14309 /* 14310 * TODO why is the lock being held? doPostInstall is 14311 * called in other places without the lock. This needs 14312 * to be straightened out. 14313 */ 14314 // writer 14315 synchronized (mPackages) { 14316 retCode = PackageManager.INSTALL_SUCCEEDED; 14317 pkgList.add(pkg.packageName); 14318 // Post process args 14319 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14320 pkg.applicationInfo.uid); 14321 } 14322 } else { 14323 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14324 } 14325 } 14326 14327 } finally { 14328 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14329 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14330 } 14331 } 14332 } 14333 // writer 14334 synchronized (mPackages) { 14335 // If the platform SDK has changed since the last time we booted, 14336 // we need to re-grant app permission to catch any new ones that 14337 // appear. This is really a hack, and means that apps can in some 14338 // cases get permissions that the user didn't initially explicitly 14339 // allow... it would be nice to have some better way to handle 14340 // this situation. 14341 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14342 if (regrantPermissions) 14343 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14344 + mSdkVersion + "; regranting permissions for external storage"); 14345 mSettings.mExternalSdkPlatform = mSdkVersion; 14346 14347 // Make sure group IDs have been assigned, and any permission 14348 // changes in other apps are accounted for 14349 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14350 | (regrantPermissions 14351 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14352 : 0)); 14353 14354 mSettings.updateExternalDatabaseVersion(); 14355 14356 // can downgrade to reader 14357 // Persist settings 14358 mSettings.writeLPr(); 14359 } 14360 // Send a broadcast to let everyone know we are done processing 14361 if (pkgList.size() > 0) { 14362 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14363 } 14364 } 14365 14366 /* 14367 * Utility method to unload a list of specified containers 14368 */ 14369 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14370 // Just unmount all valid containers. 14371 for (AsecInstallArgs arg : cidArgs) { 14372 synchronized (mInstallLock) { 14373 arg.doPostDeleteLI(false); 14374 } 14375 } 14376 } 14377 14378 /* 14379 * Unload packages mounted on external media. This involves deleting package 14380 * data from internal structures, sending broadcasts about diabled packages, 14381 * gc'ing to free up references, unmounting all secure containers 14382 * corresponding to packages on external media, and posting a 14383 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14384 * that we always have to post this message if status has been requested no 14385 * matter what. 14386 */ 14387 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14388 final boolean reportStatus) { 14389 if (DEBUG_SD_INSTALL) 14390 Log.i(TAG, "unloading media packages"); 14391 ArrayList<String> pkgList = new ArrayList<String>(); 14392 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14393 final Set<AsecInstallArgs> keys = processCids.keySet(); 14394 for (AsecInstallArgs args : keys) { 14395 String pkgName = args.getPackageName(); 14396 if (DEBUG_SD_INSTALL) 14397 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14398 // Delete package internally 14399 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14400 synchronized (mInstallLock) { 14401 boolean res = deletePackageLI(pkgName, null, false, null, null, 14402 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14403 if (res) { 14404 pkgList.add(pkgName); 14405 } else { 14406 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14407 failedList.add(args); 14408 } 14409 } 14410 } 14411 14412 // reader 14413 synchronized (mPackages) { 14414 // We didn't update the settings after removing each package; 14415 // write them now for all packages. 14416 mSettings.writeLPr(); 14417 } 14418 14419 // We have to absolutely send UPDATED_MEDIA_STATUS only 14420 // after confirming that all the receivers processed the ordered 14421 // broadcast when packages get disabled, force a gc to clean things up. 14422 // and unload all the containers. 14423 if (pkgList.size() > 0) { 14424 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14425 new IIntentReceiver.Stub() { 14426 public void performReceive(Intent intent, int resultCode, String data, 14427 Bundle extras, boolean ordered, boolean sticky, 14428 int sendingUser) throws RemoteException { 14429 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14430 reportStatus ? 1 : 0, 1, keys); 14431 mHandler.sendMessage(msg); 14432 } 14433 }); 14434 } else { 14435 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14436 keys); 14437 mHandler.sendMessage(msg); 14438 } 14439 } 14440 14441 private void loadPrivatePackages(VolumeInfo vol) { 14442 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14443 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14444 synchronized (mInstallLock) { 14445 synchronized (mPackages) { 14446 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14447 for (PackageSetting ps : packages) { 14448 final PackageParser.Package pkg; 14449 try { 14450 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14451 loaded.add(pkg.applicationInfo); 14452 } catch (PackageManagerException e) { 14453 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14454 } 14455 } 14456 14457 // TODO: regrant any permissions that changed based since original install 14458 14459 mSettings.writeLPr(); 14460 } 14461 } 14462 14463 Slog.d(TAG, "Loaded packages " + loaded); 14464 sendResourcesChangedBroadcast(true, false, loaded, null); 14465 } 14466 14467 private void unloadPrivatePackages(VolumeInfo vol) { 14468 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14469 synchronized (mInstallLock) { 14470 synchronized (mPackages) { 14471 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14472 for (PackageSetting ps : packages) { 14473 if (ps.pkg == null) continue; 14474 14475 final ApplicationInfo info = ps.pkg.applicationInfo; 14476 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14477 if (deletePackageLI(ps.name, null, false, null, null, 14478 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14479 unloaded.add(info); 14480 } else { 14481 Slog.w(TAG, "Failed to unload " + ps.codePath); 14482 } 14483 } 14484 14485 mSettings.writeLPr(); 14486 } 14487 } 14488 14489 Slog.d(TAG, "Unloaded packages " + unloaded); 14490 sendResourcesChangedBroadcast(false, false, unloaded, null); 14491 } 14492 14493 private void unfreezePackage(String packageName) { 14494 synchronized (mPackages) { 14495 final PackageSetting ps = mSettings.mPackages.get(packageName); 14496 if (ps != null) { 14497 ps.frozen = false; 14498 } 14499 } 14500 } 14501 14502 @Override 14503 public int movePackage(final String packageName, final String volumeUuid) { 14504 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14505 14506 final int moveId = mNextMoveId.getAndIncrement(); 14507 try { 14508 movePackageInternal(packageName, volumeUuid, moveId); 14509 } catch (PackageManagerException e) { 14510 Slog.d(TAG, "Failed to move " + packageName, e); 14511 mMoveCallbacks.notifyStatusChanged(moveId, 14512 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14513 } 14514 return moveId; 14515 } 14516 14517 private void movePackageInternal(final String packageName, final String volumeUuid, 14518 final int moveId) throws PackageManagerException { 14519 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14520 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14521 final PackageManager pm = mContext.getPackageManager(); 14522 14523 final boolean currentAsec; 14524 final String currentVolumeUuid; 14525 final File codeFile; 14526 final String installerPackageName; 14527 final String packageAbiOverride; 14528 final int appId; 14529 final String seinfo; 14530 final String label; 14531 14532 // reader 14533 synchronized (mPackages) { 14534 final PackageParser.Package pkg = mPackages.get(packageName); 14535 final PackageSetting ps = mSettings.mPackages.get(packageName); 14536 if (pkg == null || ps == null) { 14537 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14538 } 14539 14540 if (pkg.applicationInfo.isSystemApp()) { 14541 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14542 "Cannot move system application"); 14543 } 14544 14545 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14546 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14547 "Package already moved to " + volumeUuid); 14548 } 14549 14550 final File probe = new File(pkg.codePath); 14551 final File probeOat = new File(probe, "oat"); 14552 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14553 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14554 "Move only supported for modern cluster style installs"); 14555 } 14556 14557 if (ps.frozen) { 14558 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14559 "Failed to move already frozen package"); 14560 } 14561 ps.frozen = true; 14562 14563 currentAsec = pkg.applicationInfo.isForwardLocked() 14564 || pkg.applicationInfo.isExternalAsec(); 14565 currentVolumeUuid = ps.volumeUuid; 14566 codeFile = new File(pkg.codePath); 14567 installerPackageName = ps.installerPackageName; 14568 packageAbiOverride = ps.cpuAbiOverrideString; 14569 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14570 seinfo = pkg.applicationInfo.seinfo; 14571 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14572 } 14573 14574 // Now that we're guarded by frozen state, kill app during move 14575 killApplication(packageName, appId, "move pkg"); 14576 14577 final Bundle extras = new Bundle(); 14578 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14579 extras.putString(Intent.EXTRA_TITLE, label); 14580 mMoveCallbacks.notifyCreated(moveId, extras); 14581 14582 int installFlags; 14583 final boolean moveCompleteApp; 14584 final File measurePath; 14585 14586 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14587 installFlags = INSTALL_INTERNAL; 14588 moveCompleteApp = !currentAsec; 14589 measurePath = Environment.getDataAppDirectory(volumeUuid); 14590 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14591 installFlags = INSTALL_EXTERNAL; 14592 moveCompleteApp = false; 14593 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14594 } else { 14595 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14596 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14597 || !volume.isMountedWritable()) { 14598 unfreezePackage(packageName); 14599 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14600 "Move location not mounted private volume"); 14601 } 14602 14603 Preconditions.checkState(!currentAsec); 14604 14605 installFlags = INSTALL_INTERNAL; 14606 moveCompleteApp = true; 14607 measurePath = Environment.getDataAppDirectory(volumeUuid); 14608 } 14609 14610 final PackageStats stats = new PackageStats(null, -1); 14611 synchronized (mInstaller) { 14612 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14613 unfreezePackage(packageName); 14614 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14615 "Failed to measure package size"); 14616 } 14617 } 14618 14619 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14620 14621 final long startFreeBytes = measurePath.getFreeSpace(); 14622 final long sizeBytes; 14623 if (moveCompleteApp) { 14624 sizeBytes = stats.codeSize + stats.dataSize; 14625 } else { 14626 sizeBytes = stats.codeSize; 14627 } 14628 14629 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14630 unfreezePackage(packageName); 14631 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14632 "Not enough free space to move"); 14633 } 14634 14635 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14636 14637 final CountDownLatch installedLatch = new CountDownLatch(1); 14638 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14639 @Override 14640 public void onUserActionRequired(Intent intent) throws RemoteException { 14641 throw new IllegalStateException(); 14642 } 14643 14644 @Override 14645 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14646 Bundle extras) throws RemoteException { 14647 Slog.d(TAG, "Install result for move: " 14648 + PackageManager.installStatusToString(returnCode, msg)); 14649 14650 installedLatch.countDown(); 14651 14652 // Regardless of success or failure of the move operation, 14653 // always unfreeze the package 14654 unfreezePackage(packageName); 14655 14656 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14657 switch (status) { 14658 case PackageInstaller.STATUS_SUCCESS: 14659 mMoveCallbacks.notifyStatusChanged(moveId, 14660 PackageManager.MOVE_SUCCEEDED); 14661 break; 14662 case PackageInstaller.STATUS_FAILURE_STORAGE: 14663 mMoveCallbacks.notifyStatusChanged(moveId, 14664 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14665 break; 14666 default: 14667 mMoveCallbacks.notifyStatusChanged(moveId, 14668 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14669 break; 14670 } 14671 } 14672 }; 14673 14674 final MoveInfo move; 14675 if (moveCompleteApp) { 14676 // Kick off a thread to report progress estimates 14677 new Thread() { 14678 @Override 14679 public void run() { 14680 while (true) { 14681 try { 14682 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14683 break; 14684 } 14685 } catch (InterruptedException ignored) { 14686 } 14687 14688 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14689 final int progress = 10 + (int) MathUtils.constrain( 14690 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14691 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14692 } 14693 } 14694 }.start(); 14695 14696 final String dataAppName = codeFile.getName(); 14697 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14698 dataAppName, appId, seinfo); 14699 } else { 14700 move = null; 14701 } 14702 14703 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14704 14705 final Message msg = mHandler.obtainMessage(INIT_COPY); 14706 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14707 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14708 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14709 mHandler.sendMessage(msg); 14710 } 14711 14712 @Override 14713 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14715 14716 final int realMoveId = mNextMoveId.getAndIncrement(); 14717 final Bundle extras = new Bundle(); 14718 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14719 mMoveCallbacks.notifyCreated(realMoveId, extras); 14720 14721 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14722 @Override 14723 public void onCreated(int moveId, Bundle extras) { 14724 // Ignored 14725 } 14726 14727 @Override 14728 public void onStatusChanged(int moveId, int status, long estMillis) { 14729 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14730 } 14731 }; 14732 14733 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14734 storage.setPrimaryStorageUuid(volumeUuid, callback); 14735 return realMoveId; 14736 } 14737 14738 @Override 14739 public int getMoveStatus(int moveId) { 14740 mContext.enforceCallingOrSelfPermission( 14741 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14742 return mMoveCallbacks.mLastStatus.get(moveId); 14743 } 14744 14745 @Override 14746 public void registerMoveCallback(IPackageMoveObserver callback) { 14747 mContext.enforceCallingOrSelfPermission( 14748 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14749 mMoveCallbacks.register(callback); 14750 } 14751 14752 @Override 14753 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14754 mContext.enforceCallingOrSelfPermission( 14755 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14756 mMoveCallbacks.unregister(callback); 14757 } 14758 14759 @Override 14760 public boolean setInstallLocation(int loc) { 14761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14762 null); 14763 if (getInstallLocation() == loc) { 14764 return true; 14765 } 14766 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14767 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14768 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14769 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14770 return true; 14771 } 14772 return false; 14773 } 14774 14775 @Override 14776 public int getInstallLocation() { 14777 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14778 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14779 PackageHelper.APP_INSTALL_AUTO); 14780 } 14781 14782 /** Called by UserManagerService */ 14783 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14784 mDirtyUsers.remove(userHandle); 14785 mSettings.removeUserLPw(userHandle); 14786 mPendingBroadcasts.remove(userHandle); 14787 if (mInstaller != null) { 14788 // Technically, we shouldn't be doing this with the package lock 14789 // held. However, this is very rare, and there is already so much 14790 // other disk I/O going on, that we'll let it slide for now. 14791 final StorageManager storage = StorageManager.from(mContext); 14792 final List<VolumeInfo> vols = storage.getVolumes(); 14793 for (VolumeInfo vol : vols) { 14794 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14795 final String volumeUuid = vol.getFsUuid(); 14796 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14797 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14798 } 14799 } 14800 } 14801 mUserNeedsBadging.delete(userHandle); 14802 removeUnusedPackagesLILPw(userManager, userHandle); 14803 } 14804 14805 /** 14806 * We're removing userHandle and would like to remove any downloaded packages 14807 * that are no longer in use by any other user. 14808 * @param userHandle the user being removed 14809 */ 14810 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14811 final boolean DEBUG_CLEAN_APKS = false; 14812 int [] users = userManager.getUserIdsLPr(); 14813 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14814 while (psit.hasNext()) { 14815 PackageSetting ps = psit.next(); 14816 if (ps.pkg == null) { 14817 continue; 14818 } 14819 final String packageName = ps.pkg.packageName; 14820 // Skip over if system app 14821 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14822 continue; 14823 } 14824 if (DEBUG_CLEAN_APKS) { 14825 Slog.i(TAG, "Checking package " + packageName); 14826 } 14827 boolean keep = false; 14828 for (int i = 0; i < users.length; i++) { 14829 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14830 keep = true; 14831 if (DEBUG_CLEAN_APKS) { 14832 Slog.i(TAG, " Keeping package " + packageName + " for user " 14833 + users[i]); 14834 } 14835 break; 14836 } 14837 } 14838 if (!keep) { 14839 if (DEBUG_CLEAN_APKS) { 14840 Slog.i(TAG, " Removing package " + packageName); 14841 } 14842 mHandler.post(new Runnable() { 14843 public void run() { 14844 deletePackageX(packageName, userHandle, 0); 14845 } //end run 14846 }); 14847 } 14848 } 14849 } 14850 14851 /** Called by UserManagerService */ 14852 void createNewUserLILPw(int userHandle, File path) { 14853 if (mInstaller != null) { 14854 mInstaller.createUserConfig(userHandle); 14855 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14856 } 14857 } 14858 14859 void newUserCreatedLILPw(int userHandle) { 14860 // Adding a user requires updating runtime permissions for system apps. 14861 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14862 } 14863 14864 @Override 14865 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14866 mContext.enforceCallingOrSelfPermission( 14867 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14868 "Only package verification agents can read the verifier device identity"); 14869 14870 synchronized (mPackages) { 14871 return mSettings.getVerifierDeviceIdentityLPw(); 14872 } 14873 } 14874 14875 @Override 14876 public void setPermissionEnforced(String permission, boolean enforced) { 14877 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14878 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14879 synchronized (mPackages) { 14880 if (mSettings.mReadExternalStorageEnforced == null 14881 || mSettings.mReadExternalStorageEnforced != enforced) { 14882 mSettings.mReadExternalStorageEnforced = enforced; 14883 mSettings.writeLPr(); 14884 } 14885 } 14886 // kill any non-foreground processes so we restart them and 14887 // grant/revoke the GID. 14888 final IActivityManager am = ActivityManagerNative.getDefault(); 14889 if (am != null) { 14890 final long token = Binder.clearCallingIdentity(); 14891 try { 14892 am.killProcessesBelowForeground("setPermissionEnforcement"); 14893 } catch (RemoteException e) { 14894 } finally { 14895 Binder.restoreCallingIdentity(token); 14896 } 14897 } 14898 } else { 14899 throw new IllegalArgumentException("No selective enforcement for " + permission); 14900 } 14901 } 14902 14903 @Override 14904 @Deprecated 14905 public boolean isPermissionEnforced(String permission) { 14906 return true; 14907 } 14908 14909 @Override 14910 public boolean isStorageLow() { 14911 final long token = Binder.clearCallingIdentity(); 14912 try { 14913 final DeviceStorageMonitorInternal 14914 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14915 if (dsm != null) { 14916 return dsm.isMemoryLow(); 14917 } else { 14918 return false; 14919 } 14920 } finally { 14921 Binder.restoreCallingIdentity(token); 14922 } 14923 } 14924 14925 @Override 14926 public IPackageInstaller getPackageInstaller() { 14927 return mInstallerService; 14928 } 14929 14930 private boolean userNeedsBadging(int userId) { 14931 int index = mUserNeedsBadging.indexOfKey(userId); 14932 if (index < 0) { 14933 final UserInfo userInfo; 14934 final long token = Binder.clearCallingIdentity(); 14935 try { 14936 userInfo = sUserManager.getUserInfo(userId); 14937 } finally { 14938 Binder.restoreCallingIdentity(token); 14939 } 14940 final boolean b; 14941 if (userInfo != null && userInfo.isManagedProfile()) { 14942 b = true; 14943 } else { 14944 b = false; 14945 } 14946 mUserNeedsBadging.put(userId, b); 14947 return b; 14948 } 14949 return mUserNeedsBadging.valueAt(index); 14950 } 14951 14952 @Override 14953 public KeySet getKeySetByAlias(String packageName, String alias) { 14954 if (packageName == null || alias == null) { 14955 return null; 14956 } 14957 synchronized(mPackages) { 14958 final PackageParser.Package pkg = mPackages.get(packageName); 14959 if (pkg == null) { 14960 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14961 throw new IllegalArgumentException("Unknown package: " + packageName); 14962 } 14963 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14964 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14965 } 14966 } 14967 14968 @Override 14969 public KeySet getSigningKeySet(String packageName) { 14970 if (packageName == null) { 14971 return null; 14972 } 14973 synchronized(mPackages) { 14974 final PackageParser.Package pkg = mPackages.get(packageName); 14975 if (pkg == null) { 14976 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14977 throw new IllegalArgumentException("Unknown package: " + packageName); 14978 } 14979 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14980 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14981 throw new SecurityException("May not access signing KeySet of other apps."); 14982 } 14983 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14984 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14985 } 14986 } 14987 14988 @Override 14989 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14990 if (packageName == null || ks == null) { 14991 return false; 14992 } 14993 synchronized(mPackages) { 14994 final PackageParser.Package pkg = mPackages.get(packageName); 14995 if (pkg == null) { 14996 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14997 throw new IllegalArgumentException("Unknown package: " + packageName); 14998 } 14999 IBinder ksh = ks.getToken(); 15000 if (ksh instanceof KeySetHandle) { 15001 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15002 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15003 } 15004 return false; 15005 } 15006 } 15007 15008 @Override 15009 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15010 if (packageName == null || ks == null) { 15011 return false; 15012 } 15013 synchronized(mPackages) { 15014 final PackageParser.Package pkg = mPackages.get(packageName); 15015 if (pkg == null) { 15016 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15017 throw new IllegalArgumentException("Unknown package: " + packageName); 15018 } 15019 IBinder ksh = ks.getToken(); 15020 if (ksh instanceof KeySetHandle) { 15021 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15022 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15023 } 15024 return false; 15025 } 15026 } 15027 15028 public void getUsageStatsIfNoPackageUsageInfo() { 15029 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15030 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15031 if (usm == null) { 15032 throw new IllegalStateException("UsageStatsManager must be initialized"); 15033 } 15034 long now = System.currentTimeMillis(); 15035 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15036 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15037 String packageName = entry.getKey(); 15038 PackageParser.Package pkg = mPackages.get(packageName); 15039 if (pkg == null) { 15040 continue; 15041 } 15042 UsageStats usage = entry.getValue(); 15043 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15044 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15045 } 15046 } 15047 } 15048 15049 /** 15050 * Check and throw if the given before/after packages would be considered a 15051 * downgrade. 15052 */ 15053 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15054 throws PackageManagerException { 15055 if (after.versionCode < before.mVersionCode) { 15056 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15057 "Update version code " + after.versionCode + " is older than current " 15058 + before.mVersionCode); 15059 } else if (after.versionCode == before.mVersionCode) { 15060 if (after.baseRevisionCode < before.baseRevisionCode) { 15061 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15062 "Update base revision code " + after.baseRevisionCode 15063 + " is older than current " + before.baseRevisionCode); 15064 } 15065 15066 if (!ArrayUtils.isEmpty(after.splitNames)) { 15067 for (int i = 0; i < after.splitNames.length; i++) { 15068 final String splitName = after.splitNames[i]; 15069 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15070 if (j != -1) { 15071 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15072 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15073 "Update split " + splitName + " revision code " 15074 + after.splitRevisionCodes[i] + " is older than current " 15075 + before.splitRevisionCodes[j]); 15076 } 15077 } 15078 } 15079 } 15080 } 15081 } 15082 15083 private static class MoveCallbacks extends Handler { 15084 private static final int MSG_CREATED = 1; 15085 private static final int MSG_STATUS_CHANGED = 2; 15086 15087 private final RemoteCallbackList<IPackageMoveObserver> 15088 mCallbacks = new RemoteCallbackList<>(); 15089 15090 private final SparseIntArray mLastStatus = new SparseIntArray(); 15091 15092 public MoveCallbacks(Looper looper) { 15093 super(looper); 15094 } 15095 15096 public void register(IPackageMoveObserver callback) { 15097 mCallbacks.register(callback); 15098 } 15099 15100 public void unregister(IPackageMoveObserver callback) { 15101 mCallbacks.unregister(callback); 15102 } 15103 15104 @Override 15105 public void handleMessage(Message msg) { 15106 final SomeArgs args = (SomeArgs) msg.obj; 15107 final int n = mCallbacks.beginBroadcast(); 15108 for (int i = 0; i < n; i++) { 15109 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15110 try { 15111 invokeCallback(callback, msg.what, args); 15112 } catch (RemoteException ignored) { 15113 } 15114 } 15115 mCallbacks.finishBroadcast(); 15116 args.recycle(); 15117 } 15118 15119 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15120 throws RemoteException { 15121 switch (what) { 15122 case MSG_CREATED: { 15123 callback.onCreated(args.argi1, (Bundle) args.arg2); 15124 break; 15125 } 15126 case MSG_STATUS_CHANGED: { 15127 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15128 break; 15129 } 15130 } 15131 } 15132 15133 private void notifyCreated(int moveId, Bundle extras) { 15134 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15135 15136 final SomeArgs args = SomeArgs.obtain(); 15137 args.argi1 = moveId; 15138 args.arg2 = extras; 15139 obtainMessage(MSG_CREATED, args).sendToTarget(); 15140 } 15141 15142 private void notifyStatusChanged(int moveId, int status) { 15143 notifyStatusChanged(moveId, status, -1); 15144 } 15145 15146 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15147 Slog.v(TAG, "Move " + moveId + " status " + status); 15148 15149 final SomeArgs args = SomeArgs.obtain(); 15150 args.argi1 = moveId; 15151 args.argi2 = status; 15152 args.arg3 = estMillis; 15153 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15154 15155 synchronized (mLastStatus) { 15156 mLastStatus.put(moveId, status); 15157 } 15158 } 15159 } 15160} 15161