PackageManagerService.java revision 4a64b19f239b6bff82a032329ce5781681843044
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.os.storage.VolumeRecord; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArrayMap; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.MathUtils; 175import android.util.PrintStreamPrinter; 176import android.util.Slog; 177import android.util.SparseArray; 178import android.util.SparseBooleanArray; 179import android.util.SparseIntArray; 180import android.util.Xml; 181import android.view.Display; 182 183import dalvik.system.DexFile; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187import libcore.util.EmptyArray; 188 189import com.android.internal.R; 190import com.android.internal.app.IMediaContainerService; 191import com.android.internal.app.ResolverActivity; 192import com.android.internal.content.NativeLibraryHelper; 193import com.android.internal.content.PackageHelper; 194import com.android.internal.os.IParcelFileDescriptorFactory; 195import com.android.internal.os.SomeArgs; 196import com.android.internal.util.ArrayUtils; 197import com.android.internal.util.FastPrintWriter; 198import com.android.internal.util.FastXmlSerializer; 199import com.android.internal.util.IndentingPrintWriter; 200import com.android.internal.util.Preconditions; 201import com.android.server.EventLogTags; 202import com.android.server.FgThread; 203import com.android.server.IntentResolver; 204import com.android.server.LocalServices; 205import com.android.server.ServiceThread; 206import com.android.server.SystemConfig; 207import com.android.server.Watchdog; 208import com.android.server.pm.Settings.DatabaseVersion; 209import com.android.server.storage.DeviceStorageMonitorInternal; 210 211import org.xmlpull.v1.XmlPullParser; 212import org.xmlpull.v1.XmlSerializer; 213 214import java.io.BufferedInputStream; 215import java.io.BufferedOutputStream; 216import java.io.BufferedReader; 217import java.io.ByteArrayInputStream; 218import java.io.ByteArrayOutputStream; 219import java.io.File; 220import java.io.FileDescriptor; 221import java.io.FileNotFoundException; 222import java.io.FileOutputStream; 223import java.io.FileReader; 224import java.io.FilenameFilter; 225import java.io.IOException; 226import java.io.InputStream; 227import java.io.PrintWriter; 228import java.nio.charset.StandardCharsets; 229import java.security.NoSuchAlgorithmException; 230import java.security.PublicKey; 231import java.security.cert.CertificateEncodingException; 232import java.security.cert.CertificateException; 233import java.text.SimpleDateFormat; 234import java.util.ArrayList; 235import java.util.Arrays; 236import java.util.Collection; 237import java.util.Collections; 238import java.util.Comparator; 239import java.util.Date; 240import java.util.Iterator; 241import java.util.List; 242import java.util.Map; 243import java.util.Objects; 244import java.util.Set; 245import java.util.concurrent.CountDownLatch; 246import java.util.concurrent.TimeUnit; 247import java.util.concurrent.atomic.AtomicBoolean; 248import java.util.concurrent.atomic.AtomicInteger; 249import java.util.concurrent.atomic.AtomicLong; 250 251/** 252 * Keep track of all those .apks everywhere. 253 * 254 * This is very central to the platform's security; please run the unit 255 * tests whenever making modifications here: 256 * 257mmm frameworks/base/tests/AndroidTests 258adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 259adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 260 * 261 * {@hide} 262 */ 263public class PackageManagerService extends IPackageManager.Stub { 264 static final String TAG = "PackageManager"; 265 static final boolean DEBUG_SETTINGS = false; 266 static final boolean DEBUG_PREFERRED = false; 267 static final boolean DEBUG_UPGRADE = false; 268 private static final boolean DEBUG_BACKUP = true; 269 private static final boolean DEBUG_INSTALL = false; 270 private static final boolean DEBUG_REMOVE = false; 271 private static final boolean DEBUG_BROADCASTS = false; 272 private static final boolean DEBUG_SHOW_INFO = false; 273 private static final boolean DEBUG_PACKAGE_INFO = false; 274 private static final boolean DEBUG_INTENT_MATCHING = false; 275 private static final boolean DEBUG_PACKAGE_SCANNING = false; 276 private static final boolean DEBUG_VERIFY = false; 277 private static final boolean DEBUG_DEXOPT = false; 278 private static final boolean DEBUG_ABI_SELECTION = false; 279 280 private static final int RADIO_UID = Process.PHONE_UID; 281 private static final int LOG_UID = Process.LOG_UID; 282 private static final int NFC_UID = Process.NFC_UID; 283 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 284 private static final int SHELL_UID = Process.SHELL_UID; 285 286 // Cap the size of permission trees that 3rd party apps can define 287 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 288 289 // Suffix used during package installation when copying/moving 290 // package apks to install directory. 291 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 292 293 static final int SCAN_NO_DEX = 1<<1; 294 static final int SCAN_FORCE_DEX = 1<<2; 295 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 296 static final int SCAN_NEW_INSTALL = 1<<4; 297 static final int SCAN_NO_PATHS = 1<<5; 298 static final int SCAN_UPDATE_TIME = 1<<6; 299 static final int SCAN_DEFER_DEX = 1<<7; 300 static final int SCAN_BOOTING = 1<<8; 301 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 302 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 303 static final int SCAN_REQUIRE_KNOWN = 1<<12; 304 305 static final int REMOVE_CHATTY = 1<<16; 306 307 /** 308 * Timeout (in milliseconds) after which the watchdog should declare that 309 * our handler thread is wedged. The usual default for such things is one 310 * minute but we sometimes do very lengthy I/O operations on this thread, 311 * such as installing multi-gigabyte applications, so ours needs to be longer. 312 */ 313 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 314 315 /** 316 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 317 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 318 * settings entry if available, otherwise we use the hardcoded default. If it's been 319 * more than this long since the last fstrim, we force one during the boot sequence. 320 * 321 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 322 * one gets run at the next available charging+idle time. This final mandatory 323 * no-fstrim check kicks in only of the other scheduling criteria is never met. 324 */ 325 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 326 327 /** 328 * Whether verification is enabled by default. 329 */ 330 private static final boolean DEFAULT_VERIFY_ENABLE = true; 331 332 /** 333 * The default maximum time to wait for the verification agent to return in 334 * milliseconds. 335 */ 336 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 337 338 /** 339 * The default response for package verification timeout. 340 * 341 * This can be either PackageManager.VERIFICATION_ALLOW or 342 * PackageManager.VERIFICATION_REJECT. 343 */ 344 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 345 346 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 347 348 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 349 DEFAULT_CONTAINER_PACKAGE, 350 "com.android.defcontainer.DefaultContainerService"); 351 352 private static final String KILL_APP_REASON_GIDS_CHANGED = 353 "permission grant or revoke changed gids"; 354 355 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 356 "permissions revoked"; 357 358 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 359 360 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 361 362 /** Permission grant: not grant the permission. */ 363 private static final int GRANT_DENIED = 1; 364 365 /** Permission grant: grant the permission as an install permission. */ 366 private static final int GRANT_INSTALL = 2; 367 368 /** Permission grant: grant the permission as a runtime one. */ 369 private static final int GRANT_RUNTIME = 3; 370 371 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 372 private static final int GRANT_UPGRADE = 4; 373 374 final ServiceThread mHandlerThread; 375 376 final PackageHandler mHandler; 377 378 /** 379 * Messages for {@link #mHandler} that need to wait for system ready before 380 * being dispatched. 381 */ 382 private ArrayList<Message> mPostSystemReadyMessages; 383 384 final int mSdkVersion = Build.VERSION.SDK_INT; 385 386 final Context mContext; 387 final boolean mFactoryTest; 388 final boolean mOnlyCore; 389 final boolean mLazyDexOpt; 390 final long mDexOptLRUThresholdInMills; 391 final DisplayMetrics mMetrics; 392 final int mDefParseFlags; 393 final String[] mSeparateProcesses; 394 final boolean mIsUpgrade; 395 396 // This is where all application persistent data goes. 397 final File mAppDataDir; 398 399 // This is where all application persistent data goes for secondary users. 400 final File mUserAppDataDir; 401 402 /** The location for ASEC container files on internal storage. */ 403 final String mAsecInternalPath; 404 405 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 406 // LOCK HELD. Can be called with mInstallLock held. 407 final Installer mInstaller; 408 409 /** Directory where installed third-party apps stored */ 410 final File mAppInstallDir; 411 412 /** 413 * Directory to which applications installed internally have their 414 * 32 bit native libraries copied. 415 */ 416 private File mAppLib32InstallDir; 417 418 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 419 // apps. 420 final File mDrmAppPrivateInstallDir; 421 422 // ---------------------------------------------------------------- 423 424 // Lock for state used when installing and doing other long running 425 // operations. Methods that must be called with this lock held have 426 // the suffix "LI". 427 final Object mInstallLock = new Object(); 428 429 // ---------------------------------------------------------------- 430 431 // Keys are String (package name), values are Package. This also serves 432 // as the lock for the global state. Methods that must be called with 433 // this lock held have the prefix "LP". 434 final ArrayMap<String, PackageParser.Package> mPackages = 435 new ArrayMap<String, PackageParser.Package>(); 436 437 // Tracks available target package names -> overlay package paths. 438 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 439 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 440 441 final Settings mSettings; 442 boolean mRestoredSettings; 443 444 // System configuration read by SystemConfig. 445 final int[] mGlobalGids; 446 final SparseArray<ArraySet<String>> mSystemPermissions; 447 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 448 449 // If mac_permissions.xml was found for seinfo labeling. 450 boolean mFoundPolicyFile; 451 452 // If a recursive restorecon of /data/data/<pkg> is needed. 453 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 454 455 public static final class SharedLibraryEntry { 456 public final String path; 457 public final String apk; 458 459 SharedLibraryEntry(String _path, String _apk) { 460 path = _path; 461 apk = _apk; 462 } 463 } 464 465 // Currently known shared libraries. 466 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 467 new ArrayMap<String, SharedLibraryEntry>(); 468 469 // All available activities, for your resolving pleasure. 470 final ActivityIntentResolver mActivities = 471 new ActivityIntentResolver(); 472 473 // All available receivers, for your resolving pleasure. 474 final ActivityIntentResolver mReceivers = 475 new ActivityIntentResolver(); 476 477 // All available services, for your resolving pleasure. 478 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 479 480 // All available providers, for your resolving pleasure. 481 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 482 483 // Mapping from provider base names (first directory in content URI codePath) 484 // to the provider information. 485 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 486 new ArrayMap<String, PackageParser.Provider>(); 487 488 // Mapping from instrumentation class names to info about them. 489 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 490 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 491 492 // Mapping from permission names to info about them. 493 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 494 new ArrayMap<String, PackageParser.PermissionGroup>(); 495 496 // Packages whose data we have transfered into another package, thus 497 // should no longer exist. 498 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 499 500 // Broadcast actions that are only available to the system. 501 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 502 503 /** List of packages waiting for verification. */ 504 final SparseArray<PackageVerificationState> mPendingVerification 505 = new SparseArray<PackageVerificationState>(); 506 507 /** Set of packages associated with each app op permission. */ 508 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 509 510 final PackageInstallerService mInstallerService; 511 512 private final PackageDexOptimizer mPackageDexOptimizer; 513 514 private AtomicInteger mNextMoveId = new AtomicInteger(); 515 private final MoveCallbacks mMoveCallbacks; 516 517 // Cache of users who need badging. 518 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 519 520 /** Token for keys in mPendingVerification. */ 521 private int mPendingVerificationToken = 0; 522 523 volatile boolean mSystemReady; 524 volatile boolean mSafeMode; 525 volatile boolean mHasSystemUidErrors; 526 527 ApplicationInfo mAndroidApplication; 528 final ActivityInfo mResolveActivity = new ActivityInfo(); 529 final ResolveInfo mResolveInfo = new ResolveInfo(); 530 ComponentName mResolveComponentName; 531 PackageParser.Package mPlatformPackage; 532 ComponentName mCustomResolverComponentName; 533 534 boolean mResolverReplaced = false; 535 536 private final ComponentName mIntentFilterVerifierComponent; 537 private int mIntentFilterVerificationToken = 0; 538 539 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 540 = new SparseArray<IntentFilterVerificationState>(); 541 542 private interface IntentFilterVerifier<T extends IntentFilter> { 543 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 544 T filter, String packageName); 545 void startVerifications(int userId); 546 void receiveVerificationResponse(int verificationId); 547 } 548 549 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 550 private Context mContext; 551 private ComponentName mIntentFilterVerifierComponent; 552 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 553 554 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 555 mContext = context; 556 mIntentFilterVerifierComponent = verifierComponent; 557 } 558 559 private String getDefaultScheme() { 560 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 561 return IntentFilter.SCHEME_HTTP; 562 } 563 564 @Override 565 public void startVerifications(int userId) { 566 // Launch verifications requests 567 int count = mCurrentIntentFilterVerifications.size(); 568 for (int n=0; n<count; n++) { 569 int verificationId = mCurrentIntentFilterVerifications.get(n); 570 final IntentFilterVerificationState ivs = 571 mIntentFilterVerificationStates.get(verificationId); 572 573 String packageName = ivs.getPackageName(); 574 575 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 576 final int filterCount = filters.size(); 577 ArraySet<String> domainsSet = new ArraySet<>(); 578 for (int m=0; m<filterCount; m++) { 579 PackageParser.ActivityIntentInfo filter = filters.get(m); 580 domainsSet.addAll(filter.getHostsList()); 581 } 582 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 583 synchronized (mPackages) { 584 if (mSettings.createIntentFilterVerificationIfNeededLPw( 585 packageName, domainsList) != null) { 586 scheduleWriteSettingsLocked(); 587 } 588 } 589 sendVerificationRequest(userId, verificationId, ivs); 590 } 591 mCurrentIntentFilterVerifications.clear(); 592 } 593 594 private void sendVerificationRequest(int userId, int verificationId, 595 IntentFilterVerificationState ivs) { 596 597 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 598 verificationIntent.putExtra( 599 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 600 verificationId); 601 verificationIntent.putExtra( 602 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 603 getDefaultScheme()); 604 verificationIntent.putExtra( 605 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 606 ivs.getHostsString()); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 609 ivs.getPackageName()); 610 verificationIntent.setComponent(mIntentFilterVerifierComponent); 611 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 612 613 UserHandle user = new UserHandle(userId); 614 mContext.sendBroadcastAsUser(verificationIntent, user); 615 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 616 } 617 618 public void receiveVerificationResponse(int verificationId) { 619 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 620 621 final boolean verified = ivs.isVerified(); 622 623 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 624 final int count = filters.size(); 625 for (int n=0; n<count; n++) { 626 PackageParser.ActivityIntentInfo filter = filters.get(n); 627 filter.setVerified(verified); 628 629 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 630 + verified + " and hosts:" + ivs.getHostsString()); 631 } 632 633 mIntentFilterVerificationStates.remove(verificationId); 634 635 final String packageName = ivs.getPackageName(); 636 IntentFilterVerificationInfo ivi = null; 637 638 synchronized (mPackages) { 639 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 640 } 641 if (ivi == null) { 642 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 643 + verificationId + " packageName:" + packageName); 644 return; 645 } 646 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 647 + verificationId); 648 649 synchronized (mPackages) { 650 if (verified) { 651 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 652 } else { 653 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 654 } 655 scheduleWriteSettingsLocked(); 656 657 final int userId = ivs.getUserId(); 658 if (userId != UserHandle.USER_ALL) { 659 final int userStatus = 660 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 661 662 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 663 boolean needUpdate = false; 664 665 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 666 // already been set by the User thru the Disambiguation dialog 667 switch (userStatus) { 668 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 669 if (verified) { 670 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 671 } else { 672 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 673 } 674 needUpdate = true; 675 break; 676 677 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 678 if (verified) { 679 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 680 needUpdate = true; 681 } 682 break; 683 684 default: 685 // Nothing to do 686 } 687 688 if (needUpdate) { 689 mSettings.updateIntentFilterVerificationStatusLPw( 690 packageName, updatedStatus, userId); 691 scheduleWritePackageRestrictionsLocked(userId); 692 } 693 } 694 } 695 } 696 697 @Override 698 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 699 ActivityIntentInfo filter, String packageName) { 700 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 701 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 702 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 703 return false; 704 } 705 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 706 if (ivs == null) { 707 ivs = createDomainVerificationState(verifierId, userId, verificationId, 708 packageName); 709 } 710 if (!hasValidDomains(filter)) { 711 return false; 712 } 713 ivs.addFilter(filter); 714 return true; 715 } 716 717 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 718 int userId, int verificationId, String packageName) { 719 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 720 verifierId, userId, packageName); 721 ivs.setPendingState(); 722 synchronized (mPackages) { 723 mIntentFilterVerificationStates.append(verificationId, ivs); 724 mCurrentIntentFilterVerifications.add(verificationId); 725 } 726 return ivs; 727 } 728 } 729 730 private static boolean hasValidDomains(ActivityIntentInfo filter) { 731 return hasValidDomains(filter, true); 732 } 733 734 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 735 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 736 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 737 if (!hasHTTPorHTTPS) { 738 if (logging) { 739 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 740 } 741 return false; 742 } 743 return true; 744 } 745 746 private IntentFilterVerifier mIntentFilterVerifier; 747 748 // Set of pending broadcasts for aggregating enable/disable of components. 749 static class PendingPackageBroadcasts { 750 // for each user id, a map of <package name -> components within that package> 751 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 752 753 public PendingPackageBroadcasts() { 754 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 755 } 756 757 public ArrayList<String> get(int userId, String packageName) { 758 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 759 return packages.get(packageName); 760 } 761 762 public void put(int userId, String packageName, ArrayList<String> components) { 763 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 764 packages.put(packageName, components); 765 } 766 767 public void remove(int userId, String packageName) { 768 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 769 if (packages != null) { 770 packages.remove(packageName); 771 } 772 } 773 774 public void remove(int userId) { 775 mUidMap.remove(userId); 776 } 777 778 public int userIdCount() { 779 return mUidMap.size(); 780 } 781 782 public int userIdAt(int n) { 783 return mUidMap.keyAt(n); 784 } 785 786 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 787 return mUidMap.get(userId); 788 } 789 790 public int size() { 791 // total number of pending broadcast entries across all userIds 792 int num = 0; 793 for (int i = 0; i< mUidMap.size(); i++) { 794 num += mUidMap.valueAt(i).size(); 795 } 796 return num; 797 } 798 799 public void clear() { 800 mUidMap.clear(); 801 } 802 803 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 804 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 805 if (map == null) { 806 map = new ArrayMap<String, ArrayList<String>>(); 807 mUidMap.put(userId, map); 808 } 809 return map; 810 } 811 } 812 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 813 814 // Service Connection to remote media container service to copy 815 // package uri's from external media onto secure containers 816 // or internal storage. 817 private IMediaContainerService mContainerService = null; 818 819 static final int SEND_PENDING_BROADCAST = 1; 820 static final int MCS_BOUND = 3; 821 static final int END_COPY = 4; 822 static final int INIT_COPY = 5; 823 static final int MCS_UNBIND = 6; 824 static final int START_CLEANING_PACKAGE = 7; 825 static final int FIND_INSTALL_LOC = 8; 826 static final int POST_INSTALL = 9; 827 static final int MCS_RECONNECT = 10; 828 static final int MCS_GIVE_UP = 11; 829 static final int UPDATED_MEDIA_STATUS = 12; 830 static final int WRITE_SETTINGS = 13; 831 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 832 static final int PACKAGE_VERIFIED = 15; 833 static final int CHECK_PENDING_VERIFICATION = 16; 834 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 835 static final int INTENT_FILTER_VERIFIED = 18; 836 837 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 838 839 // Delay time in millisecs 840 static final int BROADCAST_DELAY = 10 * 1000; 841 842 static UserManagerService sUserManager; 843 844 // Stores a list of users whose package restrictions file needs to be updated 845 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 846 847 final private DefaultContainerConnection mDefContainerConn = 848 new DefaultContainerConnection(); 849 class DefaultContainerConnection implements ServiceConnection { 850 public void onServiceConnected(ComponentName name, IBinder service) { 851 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 852 IMediaContainerService imcs = 853 IMediaContainerService.Stub.asInterface(service); 854 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 855 } 856 857 public void onServiceDisconnected(ComponentName name) { 858 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 859 } 860 }; 861 862 // Recordkeeping of restore-after-install operations that are currently in flight 863 // between the Package Manager and the Backup Manager 864 class PostInstallData { 865 public InstallArgs args; 866 public PackageInstalledInfo res; 867 868 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 869 args = _a; 870 res = _r; 871 } 872 }; 873 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 874 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 875 876 // backup/restore of preferred activity state 877 private static final String TAG_PREFERRED_BACKUP = "pa"; 878 879 private final String mRequiredVerifierPackage; 880 881 private final PackageUsage mPackageUsage = new PackageUsage(); 882 883 private class PackageUsage { 884 private static final int WRITE_INTERVAL 885 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 886 887 private final Object mFileLock = new Object(); 888 private final AtomicLong mLastWritten = new AtomicLong(0); 889 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 890 891 private boolean mIsHistoricalPackageUsageAvailable = true; 892 893 boolean isHistoricalPackageUsageAvailable() { 894 return mIsHistoricalPackageUsageAvailable; 895 } 896 897 void write(boolean force) { 898 if (force) { 899 writeInternal(); 900 return; 901 } 902 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 903 && !DEBUG_DEXOPT) { 904 return; 905 } 906 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 907 new Thread("PackageUsage_DiskWriter") { 908 @Override 909 public void run() { 910 try { 911 writeInternal(); 912 } finally { 913 mBackgroundWriteRunning.set(false); 914 } 915 } 916 }.start(); 917 } 918 } 919 920 private void writeInternal() { 921 synchronized (mPackages) { 922 synchronized (mFileLock) { 923 AtomicFile file = getFile(); 924 FileOutputStream f = null; 925 try { 926 f = file.startWrite(); 927 BufferedOutputStream out = new BufferedOutputStream(f); 928 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 929 StringBuilder sb = new StringBuilder(); 930 for (PackageParser.Package pkg : mPackages.values()) { 931 if (pkg.mLastPackageUsageTimeInMills == 0) { 932 continue; 933 } 934 sb.setLength(0); 935 sb.append(pkg.packageName); 936 sb.append(' '); 937 sb.append((long)pkg.mLastPackageUsageTimeInMills); 938 sb.append('\n'); 939 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 940 } 941 out.flush(); 942 file.finishWrite(f); 943 } catch (IOException e) { 944 if (f != null) { 945 file.failWrite(f); 946 } 947 Log.e(TAG, "Failed to write package usage times", e); 948 } 949 } 950 } 951 mLastWritten.set(SystemClock.elapsedRealtime()); 952 } 953 954 void readLP() { 955 synchronized (mFileLock) { 956 AtomicFile file = getFile(); 957 BufferedInputStream in = null; 958 try { 959 in = new BufferedInputStream(file.openRead()); 960 StringBuffer sb = new StringBuffer(); 961 while (true) { 962 String packageName = readToken(in, sb, ' '); 963 if (packageName == null) { 964 break; 965 } 966 String timeInMillisString = readToken(in, sb, '\n'); 967 if (timeInMillisString == null) { 968 throw new IOException("Failed to find last usage time for package " 969 + packageName); 970 } 971 PackageParser.Package pkg = mPackages.get(packageName); 972 if (pkg == null) { 973 continue; 974 } 975 long timeInMillis; 976 try { 977 timeInMillis = Long.parseLong(timeInMillisString.toString()); 978 } catch (NumberFormatException e) { 979 throw new IOException("Failed to parse " + timeInMillisString 980 + " as a long.", e); 981 } 982 pkg.mLastPackageUsageTimeInMills = timeInMillis; 983 } 984 } catch (FileNotFoundException expected) { 985 mIsHistoricalPackageUsageAvailable = false; 986 } catch (IOException e) { 987 Log.w(TAG, "Failed to read package usage times", e); 988 } finally { 989 IoUtils.closeQuietly(in); 990 } 991 } 992 mLastWritten.set(SystemClock.elapsedRealtime()); 993 } 994 995 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 996 throws IOException { 997 sb.setLength(0); 998 while (true) { 999 int ch = in.read(); 1000 if (ch == -1) { 1001 if (sb.length() == 0) { 1002 return null; 1003 } 1004 throw new IOException("Unexpected EOF"); 1005 } 1006 if (ch == endOfToken) { 1007 return sb.toString(); 1008 } 1009 sb.append((char)ch); 1010 } 1011 } 1012 1013 private AtomicFile getFile() { 1014 File dataDir = Environment.getDataDirectory(); 1015 File systemDir = new File(dataDir, "system"); 1016 File fname = new File(systemDir, "package-usage.list"); 1017 return new AtomicFile(fname); 1018 } 1019 } 1020 1021 class PackageHandler extends Handler { 1022 private boolean mBound = false; 1023 final ArrayList<HandlerParams> mPendingInstalls = 1024 new ArrayList<HandlerParams>(); 1025 1026 private boolean connectToService() { 1027 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1028 " DefaultContainerService"); 1029 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1030 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1031 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1032 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1034 mBound = true; 1035 return true; 1036 } 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1038 return false; 1039 } 1040 1041 private void disconnectService() { 1042 mContainerService = null; 1043 mBound = false; 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1045 mContext.unbindService(mDefContainerConn); 1046 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1047 } 1048 1049 PackageHandler(Looper looper) { 1050 super(looper); 1051 } 1052 1053 public void handleMessage(Message msg) { 1054 try { 1055 doHandleMessage(msg); 1056 } finally { 1057 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1058 } 1059 } 1060 1061 void doHandleMessage(Message msg) { 1062 switch (msg.what) { 1063 case INIT_COPY: { 1064 HandlerParams params = (HandlerParams) msg.obj; 1065 int idx = mPendingInstalls.size(); 1066 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1067 // If a bind was already initiated we dont really 1068 // need to do anything. The pending install 1069 // will be processed later on. 1070 if (!mBound) { 1071 // If this is the only one pending we might 1072 // have to bind to the service again. 1073 if (!connectToService()) { 1074 Slog.e(TAG, "Failed to bind to media container service"); 1075 params.serviceError(); 1076 return; 1077 } else { 1078 // Once we bind to the service, the first 1079 // pending request will be processed. 1080 mPendingInstalls.add(idx, params); 1081 } 1082 } else { 1083 mPendingInstalls.add(idx, params); 1084 // Already bound to the service. Just make 1085 // sure we trigger off processing the first request. 1086 if (idx == 0) { 1087 mHandler.sendEmptyMessage(MCS_BOUND); 1088 } 1089 } 1090 break; 1091 } 1092 case MCS_BOUND: { 1093 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1094 if (msg.obj != null) { 1095 mContainerService = (IMediaContainerService) msg.obj; 1096 } 1097 if (mContainerService == null) { 1098 // Something seriously wrong. Bail out 1099 Slog.e(TAG, "Cannot bind to media container service"); 1100 for (HandlerParams params : mPendingInstalls) { 1101 // Indicate service bind error 1102 params.serviceError(); 1103 } 1104 mPendingInstalls.clear(); 1105 } else if (mPendingInstalls.size() > 0) { 1106 HandlerParams params = mPendingInstalls.get(0); 1107 if (params != null) { 1108 if (params.startCopy()) { 1109 // We are done... look for more work or to 1110 // go idle. 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, 1112 "Checking for more work or unbind..."); 1113 // Delete pending install 1114 if (mPendingInstalls.size() > 0) { 1115 mPendingInstalls.remove(0); 1116 } 1117 if (mPendingInstalls.size() == 0) { 1118 if (mBound) { 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, 1120 "Posting delayed MCS_UNBIND"); 1121 removeMessages(MCS_UNBIND); 1122 Message ubmsg = obtainMessage(MCS_UNBIND); 1123 // Unbind after a little delay, to avoid 1124 // continual thrashing. 1125 sendMessageDelayed(ubmsg, 10000); 1126 } 1127 } else { 1128 // There are more pending requests in queue. 1129 // Just post MCS_BOUND message to trigger processing 1130 // of next pending install. 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Posting MCS_BOUND for next work"); 1133 mHandler.sendEmptyMessage(MCS_BOUND); 1134 } 1135 } 1136 } 1137 } else { 1138 // Should never happen ideally. 1139 Slog.w(TAG, "Empty queue"); 1140 } 1141 break; 1142 } 1143 case MCS_RECONNECT: { 1144 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1145 if (mPendingInstalls.size() > 0) { 1146 if (mBound) { 1147 disconnectService(); 1148 } 1149 if (!connectToService()) { 1150 Slog.e(TAG, "Failed to bind to media container service"); 1151 for (HandlerParams params : mPendingInstalls) { 1152 // Indicate service bind error 1153 params.serviceError(); 1154 } 1155 mPendingInstalls.clear(); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_UNBIND: { 1161 // If there is no actual work left, then time to unbind. 1162 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1163 1164 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1165 if (mBound) { 1166 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1167 1168 disconnectService(); 1169 } 1170 } else if (mPendingInstalls.size() > 0) { 1171 // There are more pending requests in queue. 1172 // Just post MCS_BOUND message to trigger processing 1173 // of next pending install. 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 1177 break; 1178 } 1179 case MCS_GIVE_UP: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1181 mPendingInstalls.remove(0); 1182 break; 1183 } 1184 case SEND_PENDING_BROADCAST: { 1185 String packages[]; 1186 ArrayList<String> components[]; 1187 int size = 0; 1188 int uids[]; 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1190 synchronized (mPackages) { 1191 if (mPendingBroadcasts == null) { 1192 return; 1193 } 1194 size = mPendingBroadcasts.size(); 1195 if (size <= 0) { 1196 // Nothing to be done. Just return 1197 return; 1198 } 1199 packages = new String[size]; 1200 components = new ArrayList[size]; 1201 uids = new int[size]; 1202 int i = 0; // filling out the above arrays 1203 1204 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1205 int packageUserId = mPendingBroadcasts.userIdAt(n); 1206 Iterator<Map.Entry<String, ArrayList<String>>> it 1207 = mPendingBroadcasts.packagesForUserId(packageUserId) 1208 .entrySet().iterator(); 1209 while (it.hasNext() && i < size) { 1210 Map.Entry<String, ArrayList<String>> ent = it.next(); 1211 packages[i] = ent.getKey(); 1212 components[i] = ent.getValue(); 1213 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1214 uids[i] = (ps != null) 1215 ? UserHandle.getUid(packageUserId, ps.appId) 1216 : -1; 1217 i++; 1218 } 1219 } 1220 size = i; 1221 mPendingBroadcasts.clear(); 1222 } 1223 // Send broadcasts 1224 for (int i = 0; i < size; i++) { 1225 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1226 } 1227 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1228 break; 1229 } 1230 case START_CLEANING_PACKAGE: { 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1232 final String packageName = (String)msg.obj; 1233 final int userId = msg.arg1; 1234 final boolean andCode = msg.arg2 != 0; 1235 synchronized (mPackages) { 1236 if (userId == UserHandle.USER_ALL) { 1237 int[] users = sUserManager.getUserIds(); 1238 for (int user : users) { 1239 mSettings.addPackageToCleanLPw( 1240 new PackageCleanItem(user, packageName, andCode)); 1241 } 1242 } else { 1243 mSettings.addPackageToCleanLPw( 1244 new PackageCleanItem(userId, packageName, andCode)); 1245 } 1246 } 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1248 startCleaningPackages(); 1249 } break; 1250 case POST_INSTALL: { 1251 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1252 PostInstallData data = mRunningInstalls.get(msg.arg1); 1253 mRunningInstalls.delete(msg.arg1); 1254 boolean deleteOld = false; 1255 1256 if (data != null) { 1257 InstallArgs args = data.args; 1258 PackageInstalledInfo res = data.res; 1259 1260 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1261 res.removedInfo.sendBroadcast(false, true, false); 1262 Bundle extras = new Bundle(1); 1263 extras.putInt(Intent.EXTRA_UID, res.uid); 1264 1265 // Now that we successfully installed the package, grant runtime 1266 // permissions if requested before broadcasting the install. 1267 if ((args.installFlags 1268 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1269 grantRequestedRuntimePermissions(res.pkg, 1270 args.user.getIdentifier()); 1271 } 1272 1273 // Determine the set of users who are adding this 1274 // package for the first time vs. those who are seeing 1275 // an update. 1276 int[] firstUsers; 1277 int[] updateUsers = new int[0]; 1278 if (res.origUsers == null || res.origUsers.length == 0) { 1279 firstUsers = res.newUsers; 1280 } else { 1281 firstUsers = new int[0]; 1282 for (int i=0; i<res.newUsers.length; i++) { 1283 int user = res.newUsers[i]; 1284 boolean isNew = true; 1285 for (int j=0; j<res.origUsers.length; j++) { 1286 if (res.origUsers[j] == user) { 1287 isNew = false; 1288 break; 1289 } 1290 } 1291 if (isNew) { 1292 int[] newFirst = new int[firstUsers.length+1]; 1293 System.arraycopy(firstUsers, 0, newFirst, 0, 1294 firstUsers.length); 1295 newFirst[firstUsers.length] = user; 1296 firstUsers = newFirst; 1297 } else { 1298 int[] newUpdate = new int[updateUsers.length+1]; 1299 System.arraycopy(updateUsers, 0, newUpdate, 0, 1300 updateUsers.length); 1301 newUpdate[updateUsers.length] = user; 1302 updateUsers = newUpdate; 1303 } 1304 } 1305 } 1306 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1307 res.pkg.applicationInfo.packageName, 1308 extras, null, null, firstUsers); 1309 final boolean update = res.removedInfo.removedPackage != null; 1310 if (update) { 1311 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1312 } 1313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1314 res.pkg.applicationInfo.packageName, 1315 extras, null, null, updateUsers); 1316 if (update) { 1317 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1318 res.pkg.applicationInfo.packageName, 1319 extras, null, null, updateUsers); 1320 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1321 null, null, 1322 res.pkg.applicationInfo.packageName, null, updateUsers); 1323 1324 // treat asec-hosted packages like removable media on upgrade 1325 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1326 if (DEBUG_INSTALL) { 1327 Slog.i(TAG, "upgrading pkg " + res.pkg 1328 + " is ASEC-hosted -> AVAILABLE"); 1329 } 1330 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1331 ArrayList<String> pkgList = new ArrayList<String>(1); 1332 pkgList.add(res.pkg.applicationInfo.packageName); 1333 sendResourcesChangedBroadcast(true, true, 1334 pkgList,uidArray, null); 1335 } 1336 } 1337 if (res.removedInfo.args != null) { 1338 // Remove the replaced package's older resources safely now 1339 deleteOld = true; 1340 } 1341 1342 // Log current value of "unknown sources" setting 1343 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1344 getUnknownSourcesSettings()); 1345 } 1346 // Force a gc to clear up things 1347 Runtime.getRuntime().gc(); 1348 // We delete after a gc for applications on sdcard. 1349 if (deleteOld) { 1350 synchronized (mInstallLock) { 1351 res.removedInfo.args.doPostDeleteLI(true); 1352 } 1353 } 1354 if (args.observer != null) { 1355 try { 1356 Bundle extras = extrasForInstallResult(res); 1357 args.observer.onPackageInstalled(res.name, res.returnCode, 1358 res.returnMsg, extras); 1359 } catch (RemoteException e) { 1360 Slog.i(TAG, "Observer no longer exists."); 1361 } 1362 } 1363 } else { 1364 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1365 } 1366 } break; 1367 case UPDATED_MEDIA_STATUS: { 1368 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1369 boolean reportStatus = msg.arg1 == 1; 1370 boolean doGc = msg.arg2 == 1; 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1372 if (doGc) { 1373 // Force a gc to clear up stale containers. 1374 Runtime.getRuntime().gc(); 1375 } 1376 if (msg.obj != null) { 1377 @SuppressWarnings("unchecked") 1378 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1379 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1380 // Unload containers 1381 unloadAllContainers(args); 1382 } 1383 if (reportStatus) { 1384 try { 1385 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1386 PackageHelper.getMountService().finishMediaUpdate(); 1387 } catch (RemoteException e) { 1388 Log.e(TAG, "MountService not running?"); 1389 } 1390 } 1391 } break; 1392 case WRITE_SETTINGS: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 synchronized (mPackages) { 1395 removeMessages(WRITE_SETTINGS); 1396 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1397 mSettings.writeLPr(); 1398 mDirtyUsers.clear(); 1399 } 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1401 } break; 1402 case WRITE_PACKAGE_RESTRICTIONS: { 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1404 synchronized (mPackages) { 1405 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1406 for (int userId : mDirtyUsers) { 1407 mSettings.writePackageRestrictionsLPr(userId); 1408 } 1409 mDirtyUsers.clear(); 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 } break; 1413 case CHECK_PENDING_VERIFICATION: { 1414 final int verificationId = msg.arg1; 1415 final PackageVerificationState state = mPendingVerification.get(verificationId); 1416 1417 if ((state != null) && !state.timeoutExtended()) { 1418 final InstallArgs args = state.getInstallArgs(); 1419 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1420 1421 Slog.i(TAG, "Verification timed out for " + originUri); 1422 mPendingVerification.remove(verificationId); 1423 1424 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1425 1426 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1427 Slog.i(TAG, "Continuing with installation of " + originUri); 1428 state.setVerifierResponse(Binder.getCallingUid(), 1429 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1430 broadcastPackageVerified(verificationId, originUri, 1431 PackageManager.VERIFICATION_ALLOW, 1432 state.getInstallArgs().getUser()); 1433 try { 1434 ret = args.copyApk(mContainerService, true); 1435 } catch (RemoteException e) { 1436 Slog.e(TAG, "Could not contact the ContainerService"); 1437 } 1438 } else { 1439 broadcastPackageVerified(verificationId, originUri, 1440 PackageManager.VERIFICATION_REJECT, 1441 state.getInstallArgs().getUser()); 1442 } 1443 1444 processPendingInstall(args, ret); 1445 mHandler.sendEmptyMessage(MCS_UNBIND); 1446 } 1447 break; 1448 } 1449 case PACKAGE_VERIFIED: { 1450 final int verificationId = msg.arg1; 1451 1452 final PackageVerificationState state = mPendingVerification.get(verificationId); 1453 if (state == null) { 1454 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1455 break; 1456 } 1457 1458 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1459 1460 state.setVerifierResponse(response.callerUid, response.code); 1461 1462 if (state.isVerificationComplete()) { 1463 mPendingVerification.remove(verificationId); 1464 1465 final InstallArgs args = state.getInstallArgs(); 1466 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1467 1468 int ret; 1469 if (state.isInstallAllowed()) { 1470 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1471 broadcastPackageVerified(verificationId, originUri, 1472 response.code, state.getInstallArgs().getUser()); 1473 try { 1474 ret = args.copyApk(mContainerService, true); 1475 } catch (RemoteException e) { 1476 Slog.e(TAG, "Could not contact the ContainerService"); 1477 } 1478 } else { 1479 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1480 } 1481 1482 processPendingInstall(args, ret); 1483 1484 mHandler.sendEmptyMessage(MCS_UNBIND); 1485 } 1486 1487 break; 1488 } 1489 case START_INTENT_FILTER_VERIFICATIONS: { 1490 int userId = msg.arg1; 1491 int verifierUid = msg.arg2; 1492 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1493 1494 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1495 break; 1496 } 1497 case INTENT_FILTER_VERIFIED: { 1498 final int verificationId = msg.arg1; 1499 1500 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1501 verificationId); 1502 if (state == null) { 1503 Slog.w(TAG, "Invalid IntentFilter verification token " 1504 + verificationId + " received"); 1505 break; 1506 } 1507 1508 final int userId = state.getUserId(); 1509 1510 Slog.d(TAG, "Processing IntentFilter verification with token:" 1511 + verificationId + " and userId:" + userId); 1512 1513 final IntentFilterVerificationResponse response = 1514 (IntentFilterVerificationResponse) msg.obj; 1515 1516 state.setVerifierResponse(response.callerUid, response.code); 1517 1518 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1519 + " and userId:" + userId 1520 + " is settings verifier response with response code:" 1521 + response.code); 1522 1523 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1524 Slog.d(TAG, "Domains failing verification: " 1525 + response.getFailedDomainsString()); 1526 } 1527 1528 if (state.isVerificationComplete()) { 1529 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1530 } else { 1531 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1532 + " was not said to be complete"); 1533 } 1534 1535 break; 1536 } 1537 } 1538 } 1539 } 1540 1541 private StorageEventListener mStorageListener = new StorageEventListener() { 1542 @Override 1543 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1544 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1545 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1546 // TODO: ensure that private directories exist for all active users 1547 // TODO: remove user data whose serial number doesn't match 1548 loadPrivatePackages(vol); 1549 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1550 unloadPrivatePackages(vol); 1551 } 1552 } 1553 1554 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1555 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1556 updateExternalMediaStatus(true, false); 1557 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1558 updateExternalMediaStatus(false, false); 1559 } 1560 } 1561 } 1562 1563 @Override 1564 public void onVolumeForgotten(String fsUuid) { 1565 // TODO: remove all packages hosted on this uuid 1566 } 1567 }; 1568 1569 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1570 if (userId >= UserHandle.USER_OWNER) { 1571 grantRequestedRuntimePermissionsForUser(pkg, userId); 1572 } else if (userId == UserHandle.USER_ALL) { 1573 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1574 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1575 } 1576 } 1577 } 1578 1579 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1580 SettingBase sb = (SettingBase) pkg.mExtras; 1581 if (sb == null) { 1582 return; 1583 } 1584 1585 PermissionsState permissionsState = sb.getPermissionsState(); 1586 1587 for (String permission : pkg.requestedPermissions) { 1588 BasePermission bp = mSettings.mPermissions.get(permission); 1589 if (bp != null && bp.isRuntime()) { 1590 permissionsState.grantRuntimePermission(bp, userId); 1591 } 1592 } 1593 } 1594 1595 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1596 Bundle extras = null; 1597 switch (res.returnCode) { 1598 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1599 extras = new Bundle(); 1600 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1601 res.origPermission); 1602 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1603 res.origPackage); 1604 break; 1605 } 1606 case PackageManager.INSTALL_SUCCEEDED: { 1607 extras = new Bundle(); 1608 extras.putBoolean(Intent.EXTRA_REPLACING, 1609 res.removedInfo != null && res.removedInfo.removedPackage != null); 1610 break; 1611 } 1612 } 1613 return extras; 1614 } 1615 1616 void scheduleWriteSettingsLocked() { 1617 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1618 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1619 } 1620 } 1621 1622 void scheduleWritePackageRestrictionsLocked(int userId) { 1623 if (!sUserManager.exists(userId)) return; 1624 mDirtyUsers.add(userId); 1625 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1626 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1627 } 1628 } 1629 1630 public static PackageManagerService main(Context context, Installer installer, 1631 boolean factoryTest, boolean onlyCore) { 1632 PackageManagerService m = new PackageManagerService(context, installer, 1633 factoryTest, onlyCore); 1634 ServiceManager.addService("package", m); 1635 return m; 1636 } 1637 1638 static String[] splitString(String str, char sep) { 1639 int count = 1; 1640 int i = 0; 1641 while ((i=str.indexOf(sep, i)) >= 0) { 1642 count++; 1643 i++; 1644 } 1645 1646 String[] res = new String[count]; 1647 i=0; 1648 count = 0; 1649 int lastI=0; 1650 while ((i=str.indexOf(sep, i)) >= 0) { 1651 res[count] = str.substring(lastI, i); 1652 count++; 1653 i++; 1654 lastI = i; 1655 } 1656 res[count] = str.substring(lastI, str.length()); 1657 return res; 1658 } 1659 1660 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1661 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1662 Context.DISPLAY_SERVICE); 1663 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1664 } 1665 1666 public PackageManagerService(Context context, Installer installer, 1667 boolean factoryTest, boolean onlyCore) { 1668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1669 SystemClock.uptimeMillis()); 1670 1671 if (mSdkVersion <= 0) { 1672 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1673 } 1674 1675 mContext = context; 1676 mFactoryTest = factoryTest; 1677 mOnlyCore = onlyCore; 1678 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1679 mMetrics = new DisplayMetrics(); 1680 mSettings = new Settings(mPackages); 1681 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1682 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1683 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1684 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1685 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1686 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1687 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1688 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1689 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 1694 // TODO: add a property to control this? 1695 long dexOptLRUThresholdInMinutes; 1696 if (mLazyDexOpt) { 1697 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1698 } else { 1699 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1700 } 1701 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1702 1703 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1704 if (separateProcesses != null && separateProcesses.length() > 0) { 1705 if ("*".equals(separateProcesses)) { 1706 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1707 mSeparateProcesses = null; 1708 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1709 } else { 1710 mDefParseFlags = 0; 1711 mSeparateProcesses = separateProcesses.split(","); 1712 Slog.w(TAG, "Running with debug.separate_processes: " 1713 + separateProcesses); 1714 } 1715 } else { 1716 mDefParseFlags = 0; 1717 mSeparateProcesses = null; 1718 } 1719 1720 mInstaller = installer; 1721 mPackageDexOptimizer = new PackageDexOptimizer(this); 1722 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1723 1724 getDefaultDisplayMetrics(context, mMetrics); 1725 1726 SystemConfig systemConfig = SystemConfig.getInstance(); 1727 mGlobalGids = systemConfig.getGlobalGids(); 1728 mSystemPermissions = systemConfig.getSystemPermissions(); 1729 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1730 1731 synchronized (mInstallLock) { 1732 // writer 1733 synchronized (mPackages) { 1734 mHandlerThread = new ServiceThread(TAG, 1735 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1736 mHandlerThread.start(); 1737 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1738 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1739 1740 File dataDir = Environment.getDataDirectory(); 1741 mAppDataDir = new File(dataDir, "data"); 1742 mAppInstallDir = new File(dataDir, "app"); 1743 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1744 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1745 mUserAppDataDir = new File(dataDir, "user"); 1746 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1747 1748 sUserManager = new UserManagerService(context, this, 1749 mInstallLock, mPackages); 1750 1751 // Propagate permission configuration in to package manager. 1752 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1753 = systemConfig.getPermissions(); 1754 for (int i=0; i<permConfig.size(); i++) { 1755 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1756 BasePermission bp = mSettings.mPermissions.get(perm.name); 1757 if (bp == null) { 1758 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1759 mSettings.mPermissions.put(perm.name, bp); 1760 } 1761 if (perm.gids != null) { 1762 bp.setGids(perm.gids, perm.perUser); 1763 } 1764 } 1765 1766 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1767 for (int i=0; i<libConfig.size(); i++) { 1768 mSharedLibraries.put(libConfig.keyAt(i), 1769 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1770 } 1771 1772 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1773 1774 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1775 mSdkVersion, mOnlyCore); 1776 1777 String customResolverActivity = Resources.getSystem().getString( 1778 R.string.config_customResolverActivity); 1779 if (TextUtils.isEmpty(customResolverActivity)) { 1780 customResolverActivity = null; 1781 } else { 1782 mCustomResolverComponentName = ComponentName.unflattenFromString( 1783 customResolverActivity); 1784 } 1785 1786 long startTime = SystemClock.uptimeMillis(); 1787 1788 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1789 startTime); 1790 1791 // Set flag to monitor and not change apk file paths when 1792 // scanning install directories. 1793 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1794 1795 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1796 1797 /** 1798 * Add everything in the in the boot class path to the 1799 * list of process files because dexopt will have been run 1800 * if necessary during zygote startup. 1801 */ 1802 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1803 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1804 1805 if (bootClassPath != null) { 1806 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1807 for (String element : bootClassPathElements) { 1808 alreadyDexOpted.add(element); 1809 } 1810 } else { 1811 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1812 } 1813 1814 if (systemServerClassPath != null) { 1815 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1816 for (String element : systemServerClassPathElements) { 1817 alreadyDexOpted.add(element); 1818 } 1819 } else { 1820 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1821 } 1822 1823 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1824 final String[] dexCodeInstructionSets = 1825 getDexCodeInstructionSets( 1826 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1827 1828 /** 1829 * Ensure all external libraries have had dexopt run on them. 1830 */ 1831 if (mSharedLibraries.size() > 0) { 1832 // NOTE: For now, we're compiling these system "shared libraries" 1833 // (and framework jars) into all available architectures. It's possible 1834 // to compile them only when we come across an app that uses them (there's 1835 // already logic for that in scanPackageLI) but that adds some complexity. 1836 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1837 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1838 final String lib = libEntry.path; 1839 if (lib == null) { 1840 continue; 1841 } 1842 1843 try { 1844 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1845 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1846 alreadyDexOpted.add(lib); 1847 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1848 } 1849 } catch (FileNotFoundException e) { 1850 Slog.w(TAG, "Library not found: " + lib); 1851 } catch (IOException e) { 1852 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1853 + e.getMessage()); 1854 } 1855 } 1856 } 1857 } 1858 1859 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1860 1861 // Gross hack for now: we know this file doesn't contain any 1862 // code, so don't dexopt it to avoid the resulting log spew. 1863 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1864 1865 // Gross hack for now: we know this file is only part of 1866 // the boot class path for art, so don't dexopt it to 1867 // avoid the resulting log spew. 1868 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1869 1870 /** 1871 * And there are a number of commands implemented in Java, which 1872 * we currently need to do the dexopt on so that they can be 1873 * run from a non-root shell. 1874 */ 1875 String[] frameworkFiles = frameworkDir.list(); 1876 if (frameworkFiles != null) { 1877 // TODO: We could compile these only for the most preferred ABI. We should 1878 // first double check that the dex files for these commands are not referenced 1879 // by other system apps. 1880 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1881 for (int i=0; i<frameworkFiles.length; i++) { 1882 File libPath = new File(frameworkDir, frameworkFiles[i]); 1883 String path = libPath.getPath(); 1884 // Skip the file if we already did it. 1885 if (alreadyDexOpted.contains(path)) { 1886 continue; 1887 } 1888 // Skip the file if it is not a type we want to dexopt. 1889 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1890 continue; 1891 } 1892 try { 1893 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1894 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1895 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1896 } 1897 } catch (FileNotFoundException e) { 1898 Slog.w(TAG, "Jar not found: " + path); 1899 } catch (IOException e) { 1900 Slog.w(TAG, "Exception reading jar: " + path, e); 1901 } 1902 } 1903 } 1904 } 1905 1906 // Collect vendor overlay packages. 1907 // (Do this before scanning any apps.) 1908 // For security and version matching reason, only consider 1909 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1910 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1911 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1912 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1913 1914 // Find base frameworks (resource packages without code). 1915 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1916 | PackageParser.PARSE_IS_SYSTEM_DIR 1917 | PackageParser.PARSE_IS_PRIVILEGED, 1918 scanFlags | SCAN_NO_DEX, 0); 1919 1920 // Collected privileged system packages. 1921 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1922 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1923 | PackageParser.PARSE_IS_SYSTEM_DIR 1924 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1925 1926 // Collect ordinary system packages. 1927 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1928 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1930 1931 // Collect all vendor packages. 1932 File vendorAppDir = new File("/vendor/app"); 1933 try { 1934 vendorAppDir = vendorAppDir.getCanonicalFile(); 1935 } catch (IOException e) { 1936 // failed to look up canonical path, continue with original one 1937 } 1938 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1940 1941 // Collect all OEM packages. 1942 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1943 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1944 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1945 1946 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1947 mInstaller.moveFiles(); 1948 1949 // Prune any system packages that no longer exist. 1950 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1951 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1952 if (!mOnlyCore) { 1953 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1954 while (psit.hasNext()) { 1955 PackageSetting ps = psit.next(); 1956 1957 /* 1958 * If this is not a system app, it can't be a 1959 * disable system app. 1960 */ 1961 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1962 continue; 1963 } 1964 1965 /* 1966 * If the package is scanned, it's not erased. 1967 */ 1968 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1969 if (scannedPkg != null) { 1970 /* 1971 * If the system app is both scanned and in the 1972 * disabled packages list, then it must have been 1973 * added via OTA. Remove it from the currently 1974 * scanned package so the previously user-installed 1975 * application can be scanned. 1976 */ 1977 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1978 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1979 + ps.name + "; removing system app. Last known codePath=" 1980 + ps.codePathString + ", installStatus=" + ps.installStatus 1981 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1982 + scannedPkg.mVersionCode); 1983 removePackageLI(ps, true); 1984 expectingBetter.put(ps.name, ps.codePath); 1985 } 1986 1987 continue; 1988 } 1989 1990 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1991 psit.remove(); 1992 logCriticalInfo(Log.WARN, "System package " + ps.name 1993 + " no longer exists; wiping its data"); 1994 removeDataDirsLI(null, ps.name); 1995 } else { 1996 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1997 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1998 possiblyDeletedUpdatedSystemApps.add(ps.name); 1999 } 2000 } 2001 } 2002 } 2003 2004 //look for any incomplete package installations 2005 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2006 //clean up list 2007 for(int i = 0; i < deletePkgsList.size(); i++) { 2008 //clean up here 2009 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2010 } 2011 //delete tmp files 2012 deleteTempPackageFiles(); 2013 2014 // Remove any shared userIDs that have no associated packages 2015 mSettings.pruneSharedUsersLPw(); 2016 2017 if (!mOnlyCore) { 2018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2019 SystemClock.uptimeMillis()); 2020 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2021 2022 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2023 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2024 2025 /** 2026 * Remove disable package settings for any updated system 2027 * apps that were removed via an OTA. If they're not a 2028 * previously-updated app, remove them completely. 2029 * Otherwise, just revoke their system-level permissions. 2030 */ 2031 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2032 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2033 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2034 2035 String msg; 2036 if (deletedPkg == null) { 2037 msg = "Updated system package " + deletedAppName 2038 + " no longer exists; wiping its data"; 2039 removeDataDirsLI(null, deletedAppName); 2040 } else { 2041 msg = "Updated system app + " + deletedAppName 2042 + " no longer present; removing system privileges for " 2043 + deletedAppName; 2044 2045 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2046 2047 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2048 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2049 } 2050 logCriticalInfo(Log.WARN, msg); 2051 } 2052 2053 /** 2054 * Make sure all system apps that we expected to appear on 2055 * the userdata partition actually showed up. If they never 2056 * appeared, crawl back and revive the system version. 2057 */ 2058 for (int i = 0; i < expectingBetter.size(); i++) { 2059 final String packageName = expectingBetter.keyAt(i); 2060 if (!mPackages.containsKey(packageName)) { 2061 final File scanFile = expectingBetter.valueAt(i); 2062 2063 logCriticalInfo(Log.WARN, "Expected better " + packageName 2064 + " but never showed up; reverting to system"); 2065 2066 final int reparseFlags; 2067 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2068 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR 2070 | PackageParser.PARSE_IS_PRIVILEGED; 2071 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2072 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR; 2074 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR; 2077 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else { 2081 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2082 continue; 2083 } 2084 2085 mSettings.enableSystemPackageLPw(packageName); 2086 2087 try { 2088 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2089 } catch (PackageManagerException e) { 2090 Slog.e(TAG, "Failed to parse original system package: " 2091 + e.getMessage()); 2092 } 2093 } 2094 } 2095 } 2096 2097 // Now that we know all of the shared libraries, update all clients to have 2098 // the correct library paths. 2099 updateAllSharedLibrariesLPw(); 2100 2101 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2102 // NOTE: We ignore potential failures here during a system scan (like 2103 // the rest of the commands above) because there's precious little we 2104 // can do about it. A settings error is reported, though. 2105 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2106 false /* force dexopt */, false /* defer dexopt */); 2107 } 2108 2109 // Now that we know all the packages we are keeping, 2110 // read and update their last usage times. 2111 mPackageUsage.readLP(); 2112 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2114 SystemClock.uptimeMillis()); 2115 Slog.i(TAG, "Time to scan packages: " 2116 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2117 + " seconds"); 2118 2119 // If the platform SDK has changed since the last time we booted, 2120 // we need to re-grant app permission to catch any new ones that 2121 // appear. This is really a hack, and means that apps can in some 2122 // cases get permissions that the user didn't initially explicitly 2123 // allow... it would be nice to have some better way to handle 2124 // this situation. 2125 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2126 != mSdkVersion; 2127 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2128 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2129 + "; regranting permissions for internal storage"); 2130 mSettings.mInternalSdkPlatform = mSdkVersion; 2131 2132 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2133 | (regrantPermissions 2134 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2135 : 0)); 2136 2137 // If this is the first boot, and it is a normal boot, then 2138 // we need to initialize the default preferred apps. 2139 if (!mRestoredSettings && !onlyCore) { 2140 mSettings.readDefaultPreferredAppsLPw(this, 0); 2141 } 2142 2143 // If this is first boot after an OTA, and a normal boot, then 2144 // we need to clear code cache directories. 2145 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2146 if (mIsUpgrade && !onlyCore) { 2147 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2148 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2149 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2150 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2151 } 2152 mSettings.mFingerprint = Build.FINGERPRINT; 2153 } 2154 2155 primeDomainVerificationsLPw(false); 2156 checkDefaultBrowser(); 2157 2158 // All the changes are done during package scanning. 2159 mSettings.updateInternalDatabaseVersion(); 2160 2161 // can downgrade to reader 2162 mSettings.writeLPr(); 2163 2164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2165 SystemClock.uptimeMillis()); 2166 2167 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2168 2169 mInstallerService = new PackageInstallerService(context, this); 2170 2171 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2172 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2173 mIntentFilterVerifierComponent); 2174 2175 } // synchronized (mPackages) 2176 } // synchronized (mInstallLock) 2177 2178 // Now after opening every single application zip, make sure they 2179 // are all flushed. Not really needed, but keeps things nice and 2180 // tidy. 2181 Runtime.getRuntime().gc(); 2182 } 2183 2184 @Override 2185 public boolean isFirstBoot() { 2186 return !mRestoredSettings; 2187 } 2188 2189 @Override 2190 public boolean isOnlyCoreApps() { 2191 return mOnlyCore; 2192 } 2193 2194 @Override 2195 public boolean isUpgrade() { 2196 return mIsUpgrade; 2197 } 2198 2199 private String getRequiredVerifierLPr() { 2200 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2201 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2202 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2203 2204 String requiredVerifier = null; 2205 2206 final int N = receivers.size(); 2207 for (int i = 0; i < N; i++) { 2208 final ResolveInfo info = receivers.get(i); 2209 2210 if (info.activityInfo == null) { 2211 continue; 2212 } 2213 2214 final String packageName = info.activityInfo.packageName; 2215 2216 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2217 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2218 continue; 2219 } 2220 2221 if (requiredVerifier != null) { 2222 throw new RuntimeException("There can be only one required verifier"); 2223 } 2224 2225 requiredVerifier = packageName; 2226 } 2227 2228 return requiredVerifier; 2229 } 2230 2231 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2232 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2233 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2234 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2235 2236 ComponentName verifierComponentName = null; 2237 2238 int priority = -1000; 2239 final int N = receivers.size(); 2240 for (int i = 0; i < N; i++) { 2241 final ResolveInfo info = receivers.get(i); 2242 2243 if (info.activityInfo == null) { 2244 continue; 2245 } 2246 2247 final String packageName = info.activityInfo.packageName; 2248 2249 final PackageSetting ps = mSettings.mPackages.get(packageName); 2250 if (ps == null) { 2251 continue; 2252 } 2253 2254 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2255 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2256 continue; 2257 } 2258 2259 // Select the IntentFilterVerifier with the highest priority 2260 if (priority < info.priority) { 2261 priority = info.priority; 2262 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2263 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2264 " with priority: " + info.priority); 2265 } 2266 } 2267 2268 return verifierComponentName; 2269 } 2270 2271 private void primeDomainVerificationsLPw(boolean logging) { 2272 Slog.d(TAG, "Start priming domain verifications"); 2273 boolean updated = false; 2274 ArraySet<String> allHostsSet = new ArraySet<>(); 2275 for (PackageParser.Package pkg : mPackages.values()) { 2276 final String packageName = pkg.packageName; 2277 if (!hasDomainURLs(pkg)) { 2278 if (logging) { 2279 Slog.d(TAG, "No priming domain verifications for " + 2280 "package with no domain URLs: " + packageName); 2281 } 2282 continue; 2283 } 2284 if (!pkg.isSystemApp()) { 2285 if (logging) { 2286 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2287 packageName); 2288 } 2289 continue; 2290 } 2291 for (PackageParser.Activity a : pkg.activities) { 2292 for (ActivityIntentInfo filter : a.intents) { 2293 if (hasValidDomains(filter, false)) { 2294 allHostsSet.addAll(filter.getHostsList()); 2295 } 2296 } 2297 } 2298 if (allHostsSet.size() == 0) { 2299 allHostsSet.add("*"); 2300 } 2301 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2302 IntentFilterVerificationInfo ivi = 2303 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2304 if (ivi != null) { 2305 // We will always log this 2306 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2307 " with hosts:" + ivi.getDomainsString()); 2308 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2309 updated = true; 2310 } 2311 else { 2312 if (logging) { 2313 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2314 } 2315 } 2316 allHostsSet.clear(); 2317 } 2318 if (updated) { 2319 if (logging) { 2320 Slog.d(TAG, "Will need to write primed domain verifications"); 2321 } 2322 } 2323 Slog.d(TAG, "End priming domain verifications"); 2324 } 2325 2326 private void checkDefaultBrowser() { 2327 final int myUserId = UserHandle.myUserId(); 2328 final String packageName = getDefaultBrowserPackageName(myUserId); 2329 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2330 if (info == null) { 2331 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2332 packageName); 2333 setDefaultBrowserPackageName(null, myUserId); 2334 } 2335 } 2336 2337 @Override 2338 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2339 throws RemoteException { 2340 try { 2341 return super.onTransact(code, data, reply, flags); 2342 } catch (RuntimeException e) { 2343 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2344 Slog.wtf(TAG, "Package Manager Crash", e); 2345 } 2346 throw e; 2347 } 2348 } 2349 2350 void cleanupInstallFailedPackage(PackageSetting ps) { 2351 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2352 2353 removeDataDirsLI(ps.volumeUuid, ps.name); 2354 if (ps.codePath != null) { 2355 if (ps.codePath.isDirectory()) { 2356 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2357 } else { 2358 ps.codePath.delete(); 2359 } 2360 } 2361 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2362 if (ps.resourcePath.isDirectory()) { 2363 FileUtils.deleteContents(ps.resourcePath); 2364 } 2365 ps.resourcePath.delete(); 2366 } 2367 mSettings.removePackageLPw(ps.name); 2368 } 2369 2370 static int[] appendInts(int[] cur, int[] add) { 2371 if (add == null) return cur; 2372 if (cur == null) return add; 2373 final int N = add.length; 2374 for (int i=0; i<N; i++) { 2375 cur = appendInt(cur, add[i]); 2376 } 2377 return cur; 2378 } 2379 2380 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2381 if (!sUserManager.exists(userId)) return null; 2382 final PackageSetting ps = (PackageSetting) p.mExtras; 2383 if (ps == null) { 2384 return null; 2385 } 2386 2387 final PermissionsState permissionsState = ps.getPermissionsState(); 2388 2389 final int[] gids = permissionsState.computeGids(userId); 2390 final Set<String> permissions = permissionsState.getPermissions(userId); 2391 final PackageUserState state = ps.readUserState(userId); 2392 2393 return PackageParser.generatePackageInfo(p, gids, flags, 2394 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2395 } 2396 2397 @Override 2398 public boolean isPackageFrozen(String packageName) { 2399 synchronized (mPackages) { 2400 final PackageSetting ps = mSettings.mPackages.get(packageName); 2401 if (ps != null) { 2402 return ps.frozen; 2403 } 2404 } 2405 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2406 return true; 2407 } 2408 2409 @Override 2410 public boolean isPackageAvailable(String packageName, int userId) { 2411 if (!sUserManager.exists(userId)) return false; 2412 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2413 synchronized (mPackages) { 2414 PackageParser.Package p = mPackages.get(packageName); 2415 if (p != null) { 2416 final PackageSetting ps = (PackageSetting) p.mExtras; 2417 if (ps != null) { 2418 final PackageUserState state = ps.readUserState(userId); 2419 if (state != null) { 2420 return PackageParser.isAvailable(state); 2421 } 2422 } 2423 } 2424 } 2425 return false; 2426 } 2427 2428 @Override 2429 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2430 if (!sUserManager.exists(userId)) return null; 2431 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2432 // reader 2433 synchronized (mPackages) { 2434 PackageParser.Package p = mPackages.get(packageName); 2435 if (DEBUG_PACKAGE_INFO) 2436 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2437 if (p != null) { 2438 return generatePackageInfo(p, flags, userId); 2439 } 2440 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2441 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2442 } 2443 } 2444 return null; 2445 } 2446 2447 @Override 2448 public String[] currentToCanonicalPackageNames(String[] names) { 2449 String[] out = new String[names.length]; 2450 // reader 2451 synchronized (mPackages) { 2452 for (int i=names.length-1; i>=0; i--) { 2453 PackageSetting ps = mSettings.mPackages.get(names[i]); 2454 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2455 } 2456 } 2457 return out; 2458 } 2459 2460 @Override 2461 public String[] canonicalToCurrentPackageNames(String[] names) { 2462 String[] out = new String[names.length]; 2463 // reader 2464 synchronized (mPackages) { 2465 for (int i=names.length-1; i>=0; i--) { 2466 String cur = mSettings.mRenamedPackages.get(names[i]); 2467 out[i] = cur != null ? cur : names[i]; 2468 } 2469 } 2470 return out; 2471 } 2472 2473 @Override 2474 public int getPackageUid(String packageName, int userId) { 2475 if (!sUserManager.exists(userId)) return -1; 2476 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2477 2478 // reader 2479 synchronized (mPackages) { 2480 PackageParser.Package p = mPackages.get(packageName); 2481 if(p != null) { 2482 return UserHandle.getUid(userId, p.applicationInfo.uid); 2483 } 2484 PackageSetting ps = mSettings.mPackages.get(packageName); 2485 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2486 return -1; 2487 } 2488 p = ps.pkg; 2489 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2490 } 2491 } 2492 2493 @Override 2494 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2495 if (!sUserManager.exists(userId)) { 2496 return null; 2497 } 2498 2499 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2500 "getPackageGids"); 2501 2502 // reader 2503 synchronized (mPackages) { 2504 PackageParser.Package p = mPackages.get(packageName); 2505 if (DEBUG_PACKAGE_INFO) { 2506 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2507 } 2508 if (p != null) { 2509 PackageSetting ps = (PackageSetting) p.mExtras; 2510 return ps.getPermissionsState().computeGids(userId); 2511 } 2512 } 2513 2514 return null; 2515 } 2516 2517 static PermissionInfo generatePermissionInfo( 2518 BasePermission bp, int flags) { 2519 if (bp.perm != null) { 2520 return PackageParser.generatePermissionInfo(bp.perm, flags); 2521 } 2522 PermissionInfo pi = new PermissionInfo(); 2523 pi.name = bp.name; 2524 pi.packageName = bp.sourcePackage; 2525 pi.nonLocalizedLabel = bp.name; 2526 pi.protectionLevel = bp.protectionLevel; 2527 return pi; 2528 } 2529 2530 @Override 2531 public PermissionInfo getPermissionInfo(String name, int flags) { 2532 // reader 2533 synchronized (mPackages) { 2534 final BasePermission p = mSettings.mPermissions.get(name); 2535 if (p != null) { 2536 return generatePermissionInfo(p, flags); 2537 } 2538 return null; 2539 } 2540 } 2541 2542 @Override 2543 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2544 // reader 2545 synchronized (mPackages) { 2546 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2547 for (BasePermission p : mSettings.mPermissions.values()) { 2548 if (group == null) { 2549 if (p.perm == null || p.perm.info.group == null) { 2550 out.add(generatePermissionInfo(p, flags)); 2551 } 2552 } else { 2553 if (p.perm != null && group.equals(p.perm.info.group)) { 2554 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2555 } 2556 } 2557 } 2558 2559 if (out.size() > 0) { 2560 return out; 2561 } 2562 return mPermissionGroups.containsKey(group) ? out : null; 2563 } 2564 } 2565 2566 @Override 2567 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2568 // reader 2569 synchronized (mPackages) { 2570 return PackageParser.generatePermissionGroupInfo( 2571 mPermissionGroups.get(name), flags); 2572 } 2573 } 2574 2575 @Override 2576 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2577 // reader 2578 synchronized (mPackages) { 2579 final int N = mPermissionGroups.size(); 2580 ArrayList<PermissionGroupInfo> out 2581 = new ArrayList<PermissionGroupInfo>(N); 2582 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2583 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2584 } 2585 return out; 2586 } 2587 } 2588 2589 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2590 int userId) { 2591 if (!sUserManager.exists(userId)) return null; 2592 PackageSetting ps = mSettings.mPackages.get(packageName); 2593 if (ps != null) { 2594 if (ps.pkg == null) { 2595 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2596 flags, userId); 2597 if (pInfo != null) { 2598 return pInfo.applicationInfo; 2599 } 2600 return null; 2601 } 2602 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2603 ps.readUserState(userId), userId); 2604 } 2605 return null; 2606 } 2607 2608 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2609 int userId) { 2610 if (!sUserManager.exists(userId)) return null; 2611 PackageSetting ps = mSettings.mPackages.get(packageName); 2612 if (ps != null) { 2613 PackageParser.Package pkg = ps.pkg; 2614 if (pkg == null) { 2615 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2616 return null; 2617 } 2618 // Only data remains, so we aren't worried about code paths 2619 pkg = new PackageParser.Package(packageName); 2620 pkg.applicationInfo.packageName = packageName; 2621 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2622 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2623 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2624 packageName, userId).getAbsolutePath(); 2625 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2626 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2627 } 2628 return generatePackageInfo(pkg, flags, userId); 2629 } 2630 return null; 2631 } 2632 2633 @Override 2634 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2635 if (!sUserManager.exists(userId)) return null; 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2637 // writer 2638 synchronized (mPackages) { 2639 PackageParser.Package p = mPackages.get(packageName); 2640 if (DEBUG_PACKAGE_INFO) Log.v( 2641 TAG, "getApplicationInfo " + packageName 2642 + ": " + p); 2643 if (p != null) { 2644 PackageSetting ps = mSettings.mPackages.get(packageName); 2645 if (ps == null) return null; 2646 // Note: isEnabledLP() does not apply here - always return info 2647 return PackageParser.generateApplicationInfo( 2648 p, flags, ps.readUserState(userId), userId); 2649 } 2650 if ("android".equals(packageName)||"system".equals(packageName)) { 2651 return mAndroidApplication; 2652 } 2653 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2654 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2655 } 2656 } 2657 return null; 2658 } 2659 2660 @Override 2661 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2662 final IPackageDataObserver observer) { 2663 mContext.enforceCallingOrSelfPermission( 2664 android.Manifest.permission.CLEAR_APP_CACHE, null); 2665 // Queue up an async operation since clearing cache may take a little while. 2666 mHandler.post(new Runnable() { 2667 public void run() { 2668 mHandler.removeCallbacks(this); 2669 int retCode = -1; 2670 synchronized (mInstallLock) { 2671 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2672 if (retCode < 0) { 2673 Slog.w(TAG, "Couldn't clear application caches"); 2674 } 2675 } 2676 if (observer != null) { 2677 try { 2678 observer.onRemoveCompleted(null, (retCode >= 0)); 2679 } catch (RemoteException e) { 2680 Slog.w(TAG, "RemoveException when invoking call back"); 2681 } 2682 } 2683 } 2684 }); 2685 } 2686 2687 @Override 2688 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2689 final IntentSender pi) { 2690 mContext.enforceCallingOrSelfPermission( 2691 android.Manifest.permission.CLEAR_APP_CACHE, null); 2692 // Queue up an async operation since clearing cache may take a little while. 2693 mHandler.post(new Runnable() { 2694 public void run() { 2695 mHandler.removeCallbacks(this); 2696 int retCode = -1; 2697 synchronized (mInstallLock) { 2698 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2699 if (retCode < 0) { 2700 Slog.w(TAG, "Couldn't clear application caches"); 2701 } 2702 } 2703 if(pi != null) { 2704 try { 2705 // Callback via pending intent 2706 int code = (retCode >= 0) ? 1 : 0; 2707 pi.sendIntent(null, code, null, 2708 null, null); 2709 } catch (SendIntentException e1) { 2710 Slog.i(TAG, "Failed to send pending intent"); 2711 } 2712 } 2713 } 2714 }); 2715 } 2716 2717 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2718 synchronized (mInstallLock) { 2719 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2720 throw new IOException("Failed to free enough space"); 2721 } 2722 } 2723 } 2724 2725 @Override 2726 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2727 if (!sUserManager.exists(userId)) return null; 2728 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2729 synchronized (mPackages) { 2730 PackageParser.Activity a = mActivities.mActivities.get(component); 2731 2732 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2733 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2734 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2735 if (ps == null) return null; 2736 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2737 userId); 2738 } 2739 if (mResolveComponentName.equals(component)) { 2740 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2741 new PackageUserState(), userId); 2742 } 2743 } 2744 return null; 2745 } 2746 2747 @Override 2748 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2749 String resolvedType) { 2750 synchronized (mPackages) { 2751 PackageParser.Activity a = mActivities.mActivities.get(component); 2752 if (a == null) { 2753 return false; 2754 } 2755 for (int i=0; i<a.intents.size(); i++) { 2756 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2757 intent.getData(), intent.getCategories(), TAG) >= 0) { 2758 return true; 2759 } 2760 } 2761 return false; 2762 } 2763 } 2764 2765 @Override 2766 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2767 if (!sUserManager.exists(userId)) return null; 2768 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2769 synchronized (mPackages) { 2770 PackageParser.Activity a = mReceivers.mActivities.get(component); 2771 if (DEBUG_PACKAGE_INFO) Log.v( 2772 TAG, "getReceiverInfo " + component + ": " + a); 2773 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2774 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2775 if (ps == null) return null; 2776 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2777 userId); 2778 } 2779 } 2780 return null; 2781 } 2782 2783 @Override 2784 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2785 if (!sUserManager.exists(userId)) return null; 2786 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2787 synchronized (mPackages) { 2788 PackageParser.Service s = mServices.mServices.get(component); 2789 if (DEBUG_PACKAGE_INFO) Log.v( 2790 TAG, "getServiceInfo " + component + ": " + s); 2791 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2792 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2793 if (ps == null) return null; 2794 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2795 userId); 2796 } 2797 } 2798 return null; 2799 } 2800 2801 @Override 2802 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2803 if (!sUserManager.exists(userId)) return null; 2804 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2805 synchronized (mPackages) { 2806 PackageParser.Provider p = mProviders.mProviders.get(component); 2807 if (DEBUG_PACKAGE_INFO) Log.v( 2808 TAG, "getProviderInfo " + component + ": " + p); 2809 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2810 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2811 if (ps == null) return null; 2812 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2813 userId); 2814 } 2815 } 2816 return null; 2817 } 2818 2819 @Override 2820 public String[] getSystemSharedLibraryNames() { 2821 Set<String> libSet; 2822 synchronized (mPackages) { 2823 libSet = mSharedLibraries.keySet(); 2824 int size = libSet.size(); 2825 if (size > 0) { 2826 String[] libs = new String[size]; 2827 libSet.toArray(libs); 2828 return libs; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 /** 2835 * @hide 2836 */ 2837 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2838 synchronized (mPackages) { 2839 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2840 if (lib != null && lib.apk != null) { 2841 return mPackages.get(lib.apk); 2842 } 2843 } 2844 return null; 2845 } 2846 2847 @Override 2848 public FeatureInfo[] getSystemAvailableFeatures() { 2849 Collection<FeatureInfo> featSet; 2850 synchronized (mPackages) { 2851 featSet = mAvailableFeatures.values(); 2852 int size = featSet.size(); 2853 if (size > 0) { 2854 FeatureInfo[] features = new FeatureInfo[size+1]; 2855 featSet.toArray(features); 2856 FeatureInfo fi = new FeatureInfo(); 2857 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2858 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2859 features[size] = fi; 2860 return features; 2861 } 2862 } 2863 return null; 2864 } 2865 2866 @Override 2867 public boolean hasSystemFeature(String name) { 2868 synchronized (mPackages) { 2869 return mAvailableFeatures.containsKey(name); 2870 } 2871 } 2872 2873 private void checkValidCaller(int uid, int userId) { 2874 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2875 return; 2876 2877 throw new SecurityException("Caller uid=" + uid 2878 + " is not privileged to communicate with user=" + userId); 2879 } 2880 2881 @Override 2882 public int checkPermission(String permName, String pkgName, int userId) { 2883 if (!sUserManager.exists(userId)) { 2884 return PackageManager.PERMISSION_DENIED; 2885 } 2886 2887 synchronized (mPackages) { 2888 final PackageParser.Package p = mPackages.get(pkgName); 2889 if (p != null && p.mExtras != null) { 2890 final PackageSetting ps = (PackageSetting) p.mExtras; 2891 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2892 return PackageManager.PERMISSION_GRANTED; 2893 } 2894 } 2895 } 2896 2897 return PackageManager.PERMISSION_DENIED; 2898 } 2899 2900 @Override 2901 public int checkUidPermission(String permName, int uid) { 2902 final int userId = UserHandle.getUserId(uid); 2903 2904 if (!sUserManager.exists(userId)) { 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 synchronized (mPackages) { 2909 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2910 if (obj != null) { 2911 final SettingBase ps = (SettingBase) obj; 2912 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2913 return PackageManager.PERMISSION_GRANTED; 2914 } 2915 } else { 2916 ArraySet<String> perms = mSystemPermissions.get(uid); 2917 if (perms != null && perms.contains(permName)) { 2918 return PackageManager.PERMISSION_GRANTED; 2919 } 2920 } 2921 } 2922 2923 return PackageManager.PERMISSION_DENIED; 2924 } 2925 2926 /** 2927 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2928 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2929 * @param checkShell TODO(yamasani): 2930 * @param message the message to log on security exception 2931 */ 2932 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2933 boolean checkShell, String message) { 2934 if (userId < 0) { 2935 throw new IllegalArgumentException("Invalid userId " + userId); 2936 } 2937 if (checkShell) { 2938 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2939 } 2940 if (userId == UserHandle.getUserId(callingUid)) return; 2941 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2942 if (requireFullPermission) { 2943 mContext.enforceCallingOrSelfPermission( 2944 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2945 } else { 2946 try { 2947 mContext.enforceCallingOrSelfPermission( 2948 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2949 } catch (SecurityException se) { 2950 mContext.enforceCallingOrSelfPermission( 2951 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2952 } 2953 } 2954 } 2955 } 2956 2957 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2958 if (callingUid == Process.SHELL_UID) { 2959 if (userHandle >= 0 2960 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2961 throw new SecurityException("Shell does not have permission to access user " 2962 + userHandle); 2963 } else if (userHandle < 0) { 2964 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2965 + Debug.getCallers(3)); 2966 } 2967 } 2968 } 2969 2970 private BasePermission findPermissionTreeLP(String permName) { 2971 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2972 if (permName.startsWith(bp.name) && 2973 permName.length() > bp.name.length() && 2974 permName.charAt(bp.name.length()) == '.') { 2975 return bp; 2976 } 2977 } 2978 return null; 2979 } 2980 2981 private BasePermission checkPermissionTreeLP(String permName) { 2982 if (permName != null) { 2983 BasePermission bp = findPermissionTreeLP(permName); 2984 if (bp != null) { 2985 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2986 return bp; 2987 } 2988 throw new SecurityException("Calling uid " 2989 + Binder.getCallingUid() 2990 + " is not allowed to add to permission tree " 2991 + bp.name + " owned by uid " + bp.uid); 2992 } 2993 } 2994 throw new SecurityException("No permission tree found for " + permName); 2995 } 2996 2997 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2998 if (s1 == null) { 2999 return s2 == null; 3000 } 3001 if (s2 == null) { 3002 return false; 3003 } 3004 if (s1.getClass() != s2.getClass()) { 3005 return false; 3006 } 3007 return s1.equals(s2); 3008 } 3009 3010 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3011 if (pi1.icon != pi2.icon) return false; 3012 if (pi1.logo != pi2.logo) return false; 3013 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3014 if (!compareStrings(pi1.name, pi2.name)) return false; 3015 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3016 // We'll take care of setting this one. 3017 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3018 // These are not currently stored in settings. 3019 //if (!compareStrings(pi1.group, pi2.group)) return false; 3020 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3021 //if (pi1.labelRes != pi2.labelRes) return false; 3022 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3023 return true; 3024 } 3025 3026 int permissionInfoFootprint(PermissionInfo info) { 3027 int size = info.name.length(); 3028 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3029 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3030 return size; 3031 } 3032 3033 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3034 int size = 0; 3035 for (BasePermission perm : mSettings.mPermissions.values()) { 3036 if (perm.uid == tree.uid) { 3037 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3038 } 3039 } 3040 return size; 3041 } 3042 3043 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3044 // We calculate the max size of permissions defined by this uid and throw 3045 // if that plus the size of 'info' would exceed our stated maximum. 3046 if (tree.uid != Process.SYSTEM_UID) { 3047 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3048 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3049 throw new SecurityException("Permission tree size cap exceeded"); 3050 } 3051 } 3052 } 3053 3054 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3055 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3056 throw new SecurityException("Label must be specified in permission"); 3057 } 3058 BasePermission tree = checkPermissionTreeLP(info.name); 3059 BasePermission bp = mSettings.mPermissions.get(info.name); 3060 boolean added = bp == null; 3061 boolean changed = true; 3062 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3063 if (added) { 3064 enforcePermissionCapLocked(info, tree); 3065 bp = new BasePermission(info.name, tree.sourcePackage, 3066 BasePermission.TYPE_DYNAMIC); 3067 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3068 throw new SecurityException( 3069 "Not allowed to modify non-dynamic permission " 3070 + info.name); 3071 } else { 3072 if (bp.protectionLevel == fixedLevel 3073 && bp.perm.owner.equals(tree.perm.owner) 3074 && bp.uid == tree.uid 3075 && comparePermissionInfos(bp.perm.info, info)) { 3076 changed = false; 3077 } 3078 } 3079 bp.protectionLevel = fixedLevel; 3080 info = new PermissionInfo(info); 3081 info.protectionLevel = fixedLevel; 3082 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3083 bp.perm.info.packageName = tree.perm.info.packageName; 3084 bp.uid = tree.uid; 3085 if (added) { 3086 mSettings.mPermissions.put(info.name, bp); 3087 } 3088 if (changed) { 3089 if (!async) { 3090 mSettings.writeLPr(); 3091 } else { 3092 scheduleWriteSettingsLocked(); 3093 } 3094 } 3095 return added; 3096 } 3097 3098 @Override 3099 public boolean addPermission(PermissionInfo info) { 3100 synchronized (mPackages) { 3101 return addPermissionLocked(info, false); 3102 } 3103 } 3104 3105 @Override 3106 public boolean addPermissionAsync(PermissionInfo info) { 3107 synchronized (mPackages) { 3108 return addPermissionLocked(info, true); 3109 } 3110 } 3111 3112 @Override 3113 public void removePermission(String name) { 3114 synchronized (mPackages) { 3115 checkPermissionTreeLP(name); 3116 BasePermission bp = mSettings.mPermissions.get(name); 3117 if (bp != null) { 3118 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3119 throw new SecurityException( 3120 "Not allowed to modify non-dynamic permission " 3121 + name); 3122 } 3123 mSettings.mPermissions.remove(name); 3124 mSettings.writeLPr(); 3125 } 3126 } 3127 } 3128 3129 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3130 BasePermission bp) { 3131 int index = pkg.requestedPermissions.indexOf(bp.name); 3132 if (index == -1) { 3133 throw new SecurityException("Package " + pkg.packageName 3134 + " has not requested permission " + bp.name); 3135 } 3136 if (!bp.isRuntime()) { 3137 throw new SecurityException("Permission " + bp.name 3138 + " is not a changeable permission type"); 3139 } 3140 } 3141 3142 @Override 3143 public void grantPermission(String packageName, String name, int userId) { 3144 if (!sUserManager.exists(userId)) { 3145 return; 3146 } 3147 3148 mContext.enforceCallingOrSelfPermission( 3149 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3150 "grantPermission"); 3151 3152 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3153 "grantPermission"); 3154 3155 boolean gidsChanged = false; 3156 final SettingBase sb; 3157 3158 synchronized (mPackages) { 3159 final PackageParser.Package pkg = mPackages.get(packageName); 3160 if (pkg == null) { 3161 throw new IllegalArgumentException("Unknown package: " + packageName); 3162 } 3163 3164 final BasePermission bp = mSettings.mPermissions.get(name); 3165 if (bp == null) { 3166 throw new IllegalArgumentException("Unknown permission: " + name); 3167 } 3168 3169 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3170 3171 sb = (SettingBase) pkg.mExtras; 3172 if (sb == null) { 3173 throw new IllegalArgumentException("Unknown package: " + packageName); 3174 } 3175 3176 final PermissionsState permissionsState = sb.getPermissionsState(); 3177 3178 final int result = permissionsState.grantRuntimePermission(bp, userId); 3179 switch (result) { 3180 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3181 return; 3182 } 3183 3184 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3185 gidsChanged = true; 3186 } 3187 break; 3188 } 3189 3190 // Not critical if that is lost - app has to request again. 3191 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3192 } 3193 3194 if (gidsChanged) { 3195 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3196 } 3197 } 3198 3199 @Override 3200 public void revokePermission(String packageName, String name, int userId) { 3201 if (!sUserManager.exists(userId)) { 3202 return; 3203 } 3204 3205 mContext.enforceCallingOrSelfPermission( 3206 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3207 "revokePermission"); 3208 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3210 "revokePermission"); 3211 3212 final SettingBase sb; 3213 3214 synchronized (mPackages) { 3215 final PackageParser.Package pkg = mPackages.get(packageName); 3216 if (pkg == null) { 3217 throw new IllegalArgumentException("Unknown package: " + packageName); 3218 } 3219 3220 final BasePermission bp = mSettings.mPermissions.get(name); 3221 if (bp == null) { 3222 throw new IllegalArgumentException("Unknown permission: " + name); 3223 } 3224 3225 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3226 3227 sb = (SettingBase) pkg.mExtras; 3228 if (sb == null) { 3229 throw new IllegalArgumentException("Unknown package: " + packageName); 3230 } 3231 3232 final PermissionsState permissionsState = sb.getPermissionsState(); 3233 3234 if (permissionsState.revokeRuntimePermission(bp, userId) == 3235 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3236 return; 3237 } 3238 3239 // Critical, after this call all should never have the permission. 3240 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3241 } 3242 3243 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3244 } 3245 3246 @Override 3247 public boolean isProtectedBroadcast(String actionName) { 3248 synchronized (mPackages) { 3249 return mProtectedBroadcasts.contains(actionName); 3250 } 3251 } 3252 3253 @Override 3254 public int checkSignatures(String pkg1, String pkg2) { 3255 synchronized (mPackages) { 3256 final PackageParser.Package p1 = mPackages.get(pkg1); 3257 final PackageParser.Package p2 = mPackages.get(pkg2); 3258 if (p1 == null || p1.mExtras == null 3259 || p2 == null || p2.mExtras == null) { 3260 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3261 } 3262 return compareSignatures(p1.mSignatures, p2.mSignatures); 3263 } 3264 } 3265 3266 @Override 3267 public int checkUidSignatures(int uid1, int uid2) { 3268 // Map to base uids. 3269 uid1 = UserHandle.getAppId(uid1); 3270 uid2 = UserHandle.getAppId(uid2); 3271 // reader 3272 synchronized (mPackages) { 3273 Signature[] s1; 3274 Signature[] s2; 3275 Object obj = mSettings.getUserIdLPr(uid1); 3276 if (obj != null) { 3277 if (obj instanceof SharedUserSetting) { 3278 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3279 } else if (obj instanceof PackageSetting) { 3280 s1 = ((PackageSetting)obj).signatures.mSignatures; 3281 } else { 3282 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3283 } 3284 } else { 3285 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3286 } 3287 obj = mSettings.getUserIdLPr(uid2); 3288 if (obj != null) { 3289 if (obj instanceof SharedUserSetting) { 3290 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3291 } else if (obj instanceof PackageSetting) { 3292 s2 = ((PackageSetting)obj).signatures.mSignatures; 3293 } else { 3294 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3295 } 3296 } else { 3297 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3298 } 3299 return compareSignatures(s1, s2); 3300 } 3301 } 3302 3303 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3304 final long identity = Binder.clearCallingIdentity(); 3305 try { 3306 if (sb instanceof SharedUserSetting) { 3307 SharedUserSetting sus = (SharedUserSetting) sb; 3308 final int packageCount = sus.packages.size(); 3309 for (int i = 0; i < packageCount; i++) { 3310 PackageSetting susPs = sus.packages.valueAt(i); 3311 if (userId == UserHandle.USER_ALL) { 3312 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3313 } else { 3314 final int uid = UserHandle.getUid(userId, susPs.appId); 3315 killUid(uid, reason); 3316 } 3317 } 3318 } else if (sb instanceof PackageSetting) { 3319 PackageSetting ps = (PackageSetting) sb; 3320 if (userId == UserHandle.USER_ALL) { 3321 killApplication(ps.pkg.packageName, ps.appId, reason); 3322 } else { 3323 final int uid = UserHandle.getUid(userId, ps.appId); 3324 killUid(uid, reason); 3325 } 3326 } 3327 } finally { 3328 Binder.restoreCallingIdentity(identity); 3329 } 3330 } 3331 3332 private static void killUid(int uid, String reason) { 3333 IActivityManager am = ActivityManagerNative.getDefault(); 3334 if (am != null) { 3335 try { 3336 am.killUid(uid, reason); 3337 } catch (RemoteException e) { 3338 /* ignore - same process */ 3339 } 3340 } 3341 } 3342 3343 /** 3344 * Compares two sets of signatures. Returns: 3345 * <br /> 3346 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3347 * <br /> 3348 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3349 * <br /> 3350 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3351 * <br /> 3352 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3353 * <br /> 3354 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3355 */ 3356 static int compareSignatures(Signature[] s1, Signature[] s2) { 3357 if (s1 == null) { 3358 return s2 == null 3359 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3360 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3361 } 3362 3363 if (s2 == null) { 3364 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3365 } 3366 3367 if (s1.length != s2.length) { 3368 return PackageManager.SIGNATURE_NO_MATCH; 3369 } 3370 3371 // Since both signature sets are of size 1, we can compare without HashSets. 3372 if (s1.length == 1) { 3373 return s1[0].equals(s2[0]) ? 3374 PackageManager.SIGNATURE_MATCH : 3375 PackageManager.SIGNATURE_NO_MATCH; 3376 } 3377 3378 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3379 for (Signature sig : s1) { 3380 set1.add(sig); 3381 } 3382 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3383 for (Signature sig : s2) { 3384 set2.add(sig); 3385 } 3386 // Make sure s2 contains all signatures in s1. 3387 if (set1.equals(set2)) { 3388 return PackageManager.SIGNATURE_MATCH; 3389 } 3390 return PackageManager.SIGNATURE_NO_MATCH; 3391 } 3392 3393 /** 3394 * If the database version for this type of package (internal storage or 3395 * external storage) is less than the version where package signatures 3396 * were updated, return true. 3397 */ 3398 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3399 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3400 DatabaseVersion.SIGNATURE_END_ENTITY)) 3401 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3402 DatabaseVersion.SIGNATURE_END_ENTITY)); 3403 } 3404 3405 /** 3406 * Used for backward compatibility to make sure any packages with 3407 * certificate chains get upgraded to the new style. {@code existingSigs} 3408 * will be in the old format (since they were stored on disk from before the 3409 * system upgrade) and {@code scannedSigs} will be in the newer format. 3410 */ 3411 private int compareSignaturesCompat(PackageSignatures existingSigs, 3412 PackageParser.Package scannedPkg) { 3413 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3414 return PackageManager.SIGNATURE_NO_MATCH; 3415 } 3416 3417 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3418 for (Signature sig : existingSigs.mSignatures) { 3419 existingSet.add(sig); 3420 } 3421 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3422 for (Signature sig : scannedPkg.mSignatures) { 3423 try { 3424 Signature[] chainSignatures = sig.getChainSignatures(); 3425 for (Signature chainSig : chainSignatures) { 3426 scannedCompatSet.add(chainSig); 3427 } 3428 } catch (CertificateEncodingException e) { 3429 scannedCompatSet.add(sig); 3430 } 3431 } 3432 /* 3433 * Make sure the expanded scanned set contains all signatures in the 3434 * existing one. 3435 */ 3436 if (scannedCompatSet.equals(existingSet)) { 3437 // Migrate the old signatures to the new scheme. 3438 existingSigs.assignSignatures(scannedPkg.mSignatures); 3439 // The new KeySets will be re-added later in the scanning process. 3440 synchronized (mPackages) { 3441 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3442 } 3443 return PackageManager.SIGNATURE_MATCH; 3444 } 3445 return PackageManager.SIGNATURE_NO_MATCH; 3446 } 3447 3448 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3449 if (isExternal(scannedPkg)) { 3450 return mSettings.isExternalDatabaseVersionOlderThan( 3451 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3452 } else { 3453 return mSettings.isInternalDatabaseVersionOlderThan( 3454 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3455 } 3456 } 3457 3458 private int compareSignaturesRecover(PackageSignatures existingSigs, 3459 PackageParser.Package scannedPkg) { 3460 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3461 return PackageManager.SIGNATURE_NO_MATCH; 3462 } 3463 3464 String msg = null; 3465 try { 3466 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3467 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3468 + scannedPkg.packageName); 3469 return PackageManager.SIGNATURE_MATCH; 3470 } 3471 } catch (CertificateException e) { 3472 msg = e.getMessage(); 3473 } 3474 3475 logCriticalInfo(Log.INFO, 3476 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3477 return PackageManager.SIGNATURE_NO_MATCH; 3478 } 3479 3480 @Override 3481 public String[] getPackagesForUid(int uid) { 3482 uid = UserHandle.getAppId(uid); 3483 // reader 3484 synchronized (mPackages) { 3485 Object obj = mSettings.getUserIdLPr(uid); 3486 if (obj instanceof SharedUserSetting) { 3487 final SharedUserSetting sus = (SharedUserSetting) obj; 3488 final int N = sus.packages.size(); 3489 final String[] res = new String[N]; 3490 final Iterator<PackageSetting> it = sus.packages.iterator(); 3491 int i = 0; 3492 while (it.hasNext()) { 3493 res[i++] = it.next().name; 3494 } 3495 return res; 3496 } else if (obj instanceof PackageSetting) { 3497 final PackageSetting ps = (PackageSetting) obj; 3498 return new String[] { ps.name }; 3499 } 3500 } 3501 return null; 3502 } 3503 3504 @Override 3505 public String getNameForUid(int uid) { 3506 // reader 3507 synchronized (mPackages) { 3508 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3509 if (obj instanceof SharedUserSetting) { 3510 final SharedUserSetting sus = (SharedUserSetting) obj; 3511 return sus.name + ":" + sus.userId; 3512 } else if (obj instanceof PackageSetting) { 3513 final PackageSetting ps = (PackageSetting) obj; 3514 return ps.name; 3515 } 3516 } 3517 return null; 3518 } 3519 3520 @Override 3521 public int getUidForSharedUser(String sharedUserName) { 3522 if(sharedUserName == null) { 3523 return -1; 3524 } 3525 // reader 3526 synchronized (mPackages) { 3527 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3528 if (suid == null) { 3529 return -1; 3530 } 3531 return suid.userId; 3532 } 3533 } 3534 3535 @Override 3536 public int getFlagsForUid(int uid) { 3537 synchronized (mPackages) { 3538 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3539 if (obj instanceof SharedUserSetting) { 3540 final SharedUserSetting sus = (SharedUserSetting) obj; 3541 return sus.pkgFlags; 3542 } else if (obj instanceof PackageSetting) { 3543 final PackageSetting ps = (PackageSetting) obj; 3544 return ps.pkgFlags; 3545 } 3546 } 3547 return 0; 3548 } 3549 3550 @Override 3551 public int getPrivateFlagsForUid(int uid) { 3552 synchronized (mPackages) { 3553 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3554 if (obj instanceof SharedUserSetting) { 3555 final SharedUserSetting sus = (SharedUserSetting) obj; 3556 return sus.pkgPrivateFlags; 3557 } else if (obj instanceof PackageSetting) { 3558 final PackageSetting ps = (PackageSetting) obj; 3559 return ps.pkgPrivateFlags; 3560 } 3561 } 3562 return 0; 3563 } 3564 3565 @Override 3566 public boolean isUidPrivileged(int uid) { 3567 uid = UserHandle.getAppId(uid); 3568 // reader 3569 synchronized (mPackages) { 3570 Object obj = mSettings.getUserIdLPr(uid); 3571 if (obj instanceof SharedUserSetting) { 3572 final SharedUserSetting sus = (SharedUserSetting) obj; 3573 final Iterator<PackageSetting> it = sus.packages.iterator(); 3574 while (it.hasNext()) { 3575 if (it.next().isPrivileged()) { 3576 return true; 3577 } 3578 } 3579 } else if (obj instanceof PackageSetting) { 3580 final PackageSetting ps = (PackageSetting) obj; 3581 return ps.isPrivileged(); 3582 } 3583 } 3584 return false; 3585 } 3586 3587 @Override 3588 public String[] getAppOpPermissionPackages(String permissionName) { 3589 synchronized (mPackages) { 3590 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3591 if (pkgs == null) { 3592 return null; 3593 } 3594 return pkgs.toArray(new String[pkgs.size()]); 3595 } 3596 } 3597 3598 @Override 3599 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3600 int flags, int userId) { 3601 if (!sUserManager.exists(userId)) return null; 3602 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3603 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3604 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3605 } 3606 3607 @Override 3608 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3609 IntentFilter filter, int match, ComponentName activity) { 3610 final int userId = UserHandle.getCallingUserId(); 3611 if (DEBUG_PREFERRED) { 3612 Log.v(TAG, "setLastChosenActivity intent=" + intent 3613 + " resolvedType=" + resolvedType 3614 + " flags=" + flags 3615 + " filter=" + filter 3616 + " match=" + match 3617 + " activity=" + activity); 3618 filter.dump(new PrintStreamPrinter(System.out), " "); 3619 } 3620 intent.setComponent(null); 3621 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3622 // Find any earlier preferred or last chosen entries and nuke them 3623 findPreferredActivity(intent, resolvedType, 3624 flags, query, 0, false, true, false, userId); 3625 // Add the new activity as the last chosen for this filter 3626 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3627 "Setting last chosen"); 3628 } 3629 3630 @Override 3631 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3632 final int userId = UserHandle.getCallingUserId(); 3633 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3634 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3635 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3636 false, false, false, userId); 3637 } 3638 3639 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3640 int flags, List<ResolveInfo> query, int userId) { 3641 if (query != null) { 3642 final int N = query.size(); 3643 if (N == 1) { 3644 return query.get(0); 3645 } else if (N > 1) { 3646 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3647 // If there is more than one activity with the same priority, 3648 // then let the user decide between them. 3649 ResolveInfo r0 = query.get(0); 3650 ResolveInfo r1 = query.get(1); 3651 if (DEBUG_INTENT_MATCHING || debug) { 3652 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3653 + r1.activityInfo.name + "=" + r1.priority); 3654 } 3655 // If the first activity has a higher priority, or a different 3656 // default, then it is always desireable to pick it. 3657 if (r0.priority != r1.priority 3658 || r0.preferredOrder != r1.preferredOrder 3659 || r0.isDefault != r1.isDefault) { 3660 return query.get(0); 3661 } 3662 // If we have saved a preference for a preferred activity for 3663 // this Intent, use that. 3664 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3665 flags, query, r0.priority, true, false, debug, userId); 3666 if (ri != null) { 3667 return ri; 3668 } 3669 if (userId != 0) { 3670 ri = new ResolveInfo(mResolveInfo); 3671 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3672 ri.activityInfo.applicationInfo = new ApplicationInfo( 3673 ri.activityInfo.applicationInfo); 3674 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3675 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3676 return ri; 3677 } 3678 return mResolveInfo; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3685 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3686 final int N = query.size(); 3687 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3688 .get(userId); 3689 // Get the list of persistent preferred activities that handle the intent 3690 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3691 List<PersistentPreferredActivity> pprefs = ppir != null 3692 ? ppir.queryIntent(intent, resolvedType, 3693 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3694 : null; 3695 if (pprefs != null && pprefs.size() > 0) { 3696 final int M = pprefs.size(); 3697 for (int i=0; i<M; i++) { 3698 final PersistentPreferredActivity ppa = pprefs.get(i); 3699 if (DEBUG_PREFERRED || debug) { 3700 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3701 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3702 + "\n component=" + ppa.mComponent); 3703 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3704 } 3705 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3706 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3707 if (DEBUG_PREFERRED || debug) { 3708 Slog.v(TAG, "Found persistent preferred activity:"); 3709 if (ai != null) { 3710 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3711 } else { 3712 Slog.v(TAG, " null"); 3713 } 3714 } 3715 if (ai == null) { 3716 // This previously registered persistent preferred activity 3717 // component is no longer known. Ignore it and do NOT remove it. 3718 continue; 3719 } 3720 for (int j=0; j<N; j++) { 3721 final ResolveInfo ri = query.get(j); 3722 if (!ri.activityInfo.applicationInfo.packageName 3723 .equals(ai.applicationInfo.packageName)) { 3724 continue; 3725 } 3726 if (!ri.activityInfo.name.equals(ai.name)) { 3727 continue; 3728 } 3729 // Found a persistent preference that can handle the intent. 3730 if (DEBUG_PREFERRED || debug) { 3731 Slog.v(TAG, "Returning persistent preferred activity: " + 3732 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3733 } 3734 return ri; 3735 } 3736 } 3737 } 3738 return null; 3739 } 3740 3741 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3742 List<ResolveInfo> query, int priority, boolean always, 3743 boolean removeMatches, boolean debug, int userId) { 3744 if (!sUserManager.exists(userId)) return null; 3745 // writer 3746 synchronized (mPackages) { 3747 if (intent.getSelector() != null) { 3748 intent = intent.getSelector(); 3749 } 3750 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3751 3752 // Try to find a matching persistent preferred activity. 3753 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3754 debug, userId); 3755 3756 // If a persistent preferred activity matched, use it. 3757 if (pri != null) { 3758 return pri; 3759 } 3760 3761 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3762 // Get the list of preferred activities that handle the intent 3763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3764 List<PreferredActivity> prefs = pir != null 3765 ? pir.queryIntent(intent, resolvedType, 3766 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3767 : null; 3768 if (prefs != null && prefs.size() > 0) { 3769 boolean changed = false; 3770 try { 3771 // First figure out how good the original match set is. 3772 // We will only allow preferred activities that came 3773 // from the same match quality. 3774 int match = 0; 3775 3776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3777 3778 final int N = query.size(); 3779 for (int j=0; j<N; j++) { 3780 final ResolveInfo ri = query.get(j); 3781 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3782 + ": 0x" + Integer.toHexString(match)); 3783 if (ri.match > match) { 3784 match = ri.match; 3785 } 3786 } 3787 3788 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3789 + Integer.toHexString(match)); 3790 3791 match &= IntentFilter.MATCH_CATEGORY_MASK; 3792 final int M = prefs.size(); 3793 for (int i=0; i<M; i++) { 3794 final PreferredActivity pa = prefs.get(i); 3795 if (DEBUG_PREFERRED || debug) { 3796 Slog.v(TAG, "Checking PreferredActivity ds=" 3797 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3798 + "\n component=" + pa.mPref.mComponent); 3799 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3800 } 3801 if (pa.mPref.mMatch != match) { 3802 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3803 + Integer.toHexString(pa.mPref.mMatch)); 3804 continue; 3805 } 3806 // If it's not an "always" type preferred activity and that's what we're 3807 // looking for, skip it. 3808 if (always && !pa.mPref.mAlways) { 3809 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3810 continue; 3811 } 3812 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3813 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3814 if (DEBUG_PREFERRED || debug) { 3815 Slog.v(TAG, "Found preferred activity:"); 3816 if (ai != null) { 3817 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3818 } else { 3819 Slog.v(TAG, " null"); 3820 } 3821 } 3822 if (ai == null) { 3823 // This previously registered preferred activity 3824 // component is no longer known. Most likely an update 3825 // to the app was installed and in the new version this 3826 // component no longer exists. Clean it up by removing 3827 // it from the preferred activities list, and skip it. 3828 Slog.w(TAG, "Removing dangling preferred activity: " 3829 + pa.mPref.mComponent); 3830 pir.removeFilter(pa); 3831 changed = true; 3832 continue; 3833 } 3834 for (int j=0; j<N; j++) { 3835 final ResolveInfo ri = query.get(j); 3836 if (!ri.activityInfo.applicationInfo.packageName 3837 .equals(ai.applicationInfo.packageName)) { 3838 continue; 3839 } 3840 if (!ri.activityInfo.name.equals(ai.name)) { 3841 continue; 3842 } 3843 3844 if (removeMatches) { 3845 pir.removeFilter(pa); 3846 changed = true; 3847 if (DEBUG_PREFERRED) { 3848 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3849 } 3850 break; 3851 } 3852 3853 // Okay we found a previously set preferred or last chosen app. 3854 // If the result set is different from when this 3855 // was created, we need to clear it and re-ask the 3856 // user their preference, if we're looking for an "always" type entry. 3857 if (always && !pa.mPref.sameSet(query)) { 3858 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3859 + intent + " type " + resolvedType); 3860 if (DEBUG_PREFERRED) { 3861 Slog.v(TAG, "Removing preferred activity since set changed " 3862 + pa.mPref.mComponent); 3863 } 3864 pir.removeFilter(pa); 3865 // Re-add the filter as a "last chosen" entry (!always) 3866 PreferredActivity lastChosen = new PreferredActivity( 3867 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3868 pir.addFilter(lastChosen); 3869 changed = true; 3870 return null; 3871 } 3872 3873 // Yay! Either the set matched or we're looking for the last chosen 3874 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3875 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3876 return ri; 3877 } 3878 } 3879 } finally { 3880 if (changed) { 3881 if (DEBUG_PREFERRED) { 3882 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3883 } 3884 scheduleWritePackageRestrictionsLocked(userId); 3885 } 3886 } 3887 } 3888 } 3889 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3890 return null; 3891 } 3892 3893 /* 3894 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3895 */ 3896 @Override 3897 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3898 int targetUserId) { 3899 mContext.enforceCallingOrSelfPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3901 List<CrossProfileIntentFilter> matches = 3902 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3903 if (matches != null) { 3904 int size = matches.size(); 3905 for (int i = 0; i < size; i++) { 3906 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3907 } 3908 } 3909 return false; 3910 } 3911 3912 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3913 String resolvedType, int userId) { 3914 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3915 if (resolver != null) { 3916 return resolver.queryIntent(intent, resolvedType, false, userId); 3917 } 3918 return null; 3919 } 3920 3921 @Override 3922 public List<ResolveInfo> queryIntentActivities(Intent intent, 3923 String resolvedType, int flags, int userId) { 3924 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3925 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3926 ComponentName comp = intent.getComponent(); 3927 if (comp == null) { 3928 if (intent.getSelector() != null) { 3929 intent = intent.getSelector(); 3930 comp = intent.getComponent(); 3931 } 3932 } 3933 3934 if (comp != null) { 3935 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3936 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3937 if (ai != null) { 3938 final ResolveInfo ri = new ResolveInfo(); 3939 ri.activityInfo = ai; 3940 list.add(ri); 3941 } 3942 return list; 3943 } 3944 3945 // reader 3946 synchronized (mPackages) { 3947 final String pkgName = intent.getPackage(); 3948 if (pkgName == null) { 3949 List<CrossProfileIntentFilter> matchingFilters = 3950 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3951 // Check for results that need to skip the current profile. 3952 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3953 resolvedType, flags, userId); 3954 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3955 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3956 result.add(resolveInfo); 3957 return filterIfNotPrimaryUser(result, userId); 3958 } 3959 3960 // Check for results in the current profile. 3961 List<ResolveInfo> result = mActivities.queryIntent( 3962 intent, resolvedType, flags, userId); 3963 3964 // Check for cross profile results. 3965 resolveInfo = queryCrossProfileIntents( 3966 matchingFilters, intent, resolvedType, flags, userId); 3967 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3968 result.add(resolveInfo); 3969 Collections.sort(result, mResolvePrioritySorter); 3970 } 3971 result = filterIfNotPrimaryUser(result, userId); 3972 if (result.size() > 1 && hasWebURI(intent)) { 3973 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3974 } 3975 return result; 3976 } 3977 final PackageParser.Package pkg = mPackages.get(pkgName); 3978 if (pkg != null) { 3979 return filterIfNotPrimaryUser( 3980 mActivities.queryIntentForPackage( 3981 intent, resolvedType, flags, pkg.activities, userId), 3982 userId); 3983 } 3984 return new ArrayList<ResolveInfo>(); 3985 } 3986 } 3987 3988 private boolean isUserEnabled(int userId) { 3989 long callingId = Binder.clearCallingIdentity(); 3990 try { 3991 UserInfo userInfo = sUserManager.getUserInfo(userId); 3992 return userInfo != null && userInfo.isEnabled(); 3993 } finally { 3994 Binder.restoreCallingIdentity(callingId); 3995 } 3996 } 3997 3998 /** 3999 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4000 * 4001 * @return filtered list 4002 */ 4003 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4004 if (userId == UserHandle.USER_OWNER) { 4005 return resolveInfos; 4006 } 4007 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4008 ResolveInfo info = resolveInfos.get(i); 4009 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4010 resolveInfos.remove(i); 4011 } 4012 } 4013 return resolveInfos; 4014 } 4015 4016 private static boolean hasWebURI(Intent intent) { 4017 if (intent.getData() == null) { 4018 return false; 4019 } 4020 final String scheme = intent.getScheme(); 4021 if (TextUtils.isEmpty(scheme)) { 4022 return false; 4023 } 4024 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4025 } 4026 4027 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4028 int flags, List<ResolveInfo> candidates) { 4029 if (DEBUG_PREFERRED) { 4030 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4031 candidates.size()); 4032 } 4033 4034 final int userId = UserHandle.getCallingUserId(); 4035 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4036 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4037 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4038 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4039 4040 synchronized (mPackages) { 4041 final int count = candidates.size(); 4042 // First, try to use the domain prefered App 4043 for (int n=0; n<count; n++) { 4044 ResolveInfo info = candidates.get(n); 4045 String packageName = info.activityInfo.packageName; 4046 PackageSetting ps = mSettings.mPackages.get(packageName); 4047 if (ps != null) { 4048 // Add to the special match all list (Browser use case) 4049 if (info.handleAllWebDataURI) { 4050 matchAllList.add(info); 4051 continue; 4052 } 4053 // Try to get the status from User settings first 4054 int status = getDomainVerificationStatusLPr(ps, userId); 4055 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4056 result.add(info); 4057 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4058 neverList.add(info); 4059 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4060 undefinedList.add(info); 4061 } 4062 } 4063 } 4064 // If there is nothing selected, add all candidates and remove the ones that the User 4065 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4066 // also remove any Browser Apps ones. 4067 // If there is still none after this pass, add all undefined one and Browser Apps and 4068 // let the User decide with the Disambiguation dialog if there are several ones. 4069 if (result.size() == 0) { 4070 result.addAll(candidates); 4071 } 4072 result.removeAll(neverList); 4073 result.removeAll(matchAllList); 4074 if (result.size() == 0) { 4075 result.addAll(undefinedList); 4076 if ((flags & MATCH_ALL) != 0) { 4077 result.addAll(matchAllList); 4078 } else { 4079 // Try to add the Default Browser if we can 4080 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4081 UserHandle.myUserId()); 4082 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4083 boolean defaultBrowserFound = false; 4084 final int browserCount = matchAllList.size(); 4085 for (int n=0; n<browserCount; n++) { 4086 ResolveInfo browser = matchAllList.get(n); 4087 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4088 result.add(browser); 4089 defaultBrowserFound = true; 4090 break; 4091 } 4092 } 4093 if (!defaultBrowserFound) { 4094 result.addAll(matchAllList); 4095 } 4096 } else { 4097 result.addAll(matchAllList); 4098 } 4099 } 4100 } 4101 } 4102 if (DEBUG_PREFERRED) { 4103 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4104 result.size()); 4105 } 4106 return result; 4107 } 4108 4109 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4110 int status = ps.getDomainVerificationStatusForUser(userId); 4111 // if none available, get the master status 4112 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4113 if (ps.getIntentFilterVerificationInfo() != null) { 4114 status = ps.getIntentFilterVerificationInfo().getStatus(); 4115 } 4116 } 4117 return status; 4118 } 4119 4120 private ResolveInfo querySkipCurrentProfileIntents( 4121 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4122 int flags, int sourceUserId) { 4123 if (matchingFilters != null) { 4124 int size = matchingFilters.size(); 4125 for (int i = 0; i < size; i ++) { 4126 CrossProfileIntentFilter filter = matchingFilters.get(i); 4127 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4128 // Checking if there are activities in the target user that can handle the 4129 // intent. 4130 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4131 flags, sourceUserId); 4132 if (resolveInfo != null) { 4133 return resolveInfo; 4134 } 4135 } 4136 } 4137 } 4138 return null; 4139 } 4140 4141 // Return matching ResolveInfo if any for skip current profile intent filters. 4142 private ResolveInfo queryCrossProfileIntents( 4143 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4144 int flags, int sourceUserId) { 4145 if (matchingFilters != null) { 4146 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4147 // match the same intent. For performance reasons, it is better not to 4148 // run queryIntent twice for the same userId 4149 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4150 int size = matchingFilters.size(); 4151 for (int i = 0; i < size; i++) { 4152 CrossProfileIntentFilter filter = matchingFilters.get(i); 4153 int targetUserId = filter.getTargetUserId(); 4154 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4155 && !alreadyTriedUserIds.get(targetUserId)) { 4156 // Checking if there are activities in the target user that can handle the 4157 // intent. 4158 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4159 flags, sourceUserId); 4160 if (resolveInfo != null) return resolveInfo; 4161 alreadyTriedUserIds.put(targetUserId, true); 4162 } 4163 } 4164 } 4165 return null; 4166 } 4167 4168 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4169 String resolvedType, int flags, int sourceUserId) { 4170 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4171 resolvedType, flags, filter.getTargetUserId()); 4172 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4173 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4174 } 4175 return null; 4176 } 4177 4178 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4179 int sourceUserId, int targetUserId) { 4180 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4181 String className; 4182 if (targetUserId == UserHandle.USER_OWNER) { 4183 className = FORWARD_INTENT_TO_USER_OWNER; 4184 } else { 4185 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4186 } 4187 ComponentName forwardingActivityComponentName = new ComponentName( 4188 mAndroidApplication.packageName, className); 4189 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4190 sourceUserId); 4191 if (targetUserId == UserHandle.USER_OWNER) { 4192 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4193 forwardingResolveInfo.noResourceId = true; 4194 } 4195 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4196 forwardingResolveInfo.priority = 0; 4197 forwardingResolveInfo.preferredOrder = 0; 4198 forwardingResolveInfo.match = 0; 4199 forwardingResolveInfo.isDefault = true; 4200 forwardingResolveInfo.filter = filter; 4201 forwardingResolveInfo.targetUserId = targetUserId; 4202 return forwardingResolveInfo; 4203 } 4204 4205 @Override 4206 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4207 Intent[] specifics, String[] specificTypes, Intent intent, 4208 String resolvedType, int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4211 false, "query intent activity options"); 4212 final String resultsAction = intent.getAction(); 4213 4214 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4215 | PackageManager.GET_RESOLVED_FILTER, userId); 4216 4217 if (DEBUG_INTENT_MATCHING) { 4218 Log.v(TAG, "Query " + intent + ": " + results); 4219 } 4220 4221 int specificsPos = 0; 4222 int N; 4223 4224 // todo: note that the algorithm used here is O(N^2). This 4225 // isn't a problem in our current environment, but if we start running 4226 // into situations where we have more than 5 or 10 matches then this 4227 // should probably be changed to something smarter... 4228 4229 // First we go through and resolve each of the specific items 4230 // that were supplied, taking care of removing any corresponding 4231 // duplicate items in the generic resolve list. 4232 if (specifics != null) { 4233 for (int i=0; i<specifics.length; i++) { 4234 final Intent sintent = specifics[i]; 4235 if (sintent == null) { 4236 continue; 4237 } 4238 4239 if (DEBUG_INTENT_MATCHING) { 4240 Log.v(TAG, "Specific #" + i + ": " + sintent); 4241 } 4242 4243 String action = sintent.getAction(); 4244 if (resultsAction != null && resultsAction.equals(action)) { 4245 // If this action was explicitly requested, then don't 4246 // remove things that have it. 4247 action = null; 4248 } 4249 4250 ResolveInfo ri = null; 4251 ActivityInfo ai = null; 4252 4253 ComponentName comp = sintent.getComponent(); 4254 if (comp == null) { 4255 ri = resolveIntent( 4256 sintent, 4257 specificTypes != null ? specificTypes[i] : null, 4258 flags, userId); 4259 if (ri == null) { 4260 continue; 4261 } 4262 if (ri == mResolveInfo) { 4263 // ACK! Must do something better with this. 4264 } 4265 ai = ri.activityInfo; 4266 comp = new ComponentName(ai.applicationInfo.packageName, 4267 ai.name); 4268 } else { 4269 ai = getActivityInfo(comp, flags, userId); 4270 if (ai == null) { 4271 continue; 4272 } 4273 } 4274 4275 // Look for any generic query activities that are duplicates 4276 // of this specific one, and remove them from the results. 4277 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4278 N = results.size(); 4279 int j; 4280 for (j=specificsPos; j<N; j++) { 4281 ResolveInfo sri = results.get(j); 4282 if ((sri.activityInfo.name.equals(comp.getClassName()) 4283 && sri.activityInfo.applicationInfo.packageName.equals( 4284 comp.getPackageName())) 4285 || (action != null && sri.filter.matchAction(action))) { 4286 results.remove(j); 4287 if (DEBUG_INTENT_MATCHING) Log.v( 4288 TAG, "Removing duplicate item from " + j 4289 + " due to specific " + specificsPos); 4290 if (ri == null) { 4291 ri = sri; 4292 } 4293 j--; 4294 N--; 4295 } 4296 } 4297 4298 // Add this specific item to its proper place. 4299 if (ri == null) { 4300 ri = new ResolveInfo(); 4301 ri.activityInfo = ai; 4302 } 4303 results.add(specificsPos, ri); 4304 ri.specificIndex = i; 4305 specificsPos++; 4306 } 4307 } 4308 4309 // Now we go through the remaining generic results and remove any 4310 // duplicate actions that are found here. 4311 N = results.size(); 4312 for (int i=specificsPos; i<N-1; i++) { 4313 final ResolveInfo rii = results.get(i); 4314 if (rii.filter == null) { 4315 continue; 4316 } 4317 4318 // Iterate over all of the actions of this result's intent 4319 // filter... typically this should be just one. 4320 final Iterator<String> it = rii.filter.actionsIterator(); 4321 if (it == null) { 4322 continue; 4323 } 4324 while (it.hasNext()) { 4325 final String action = it.next(); 4326 if (resultsAction != null && resultsAction.equals(action)) { 4327 // If this action was explicitly requested, then don't 4328 // remove things that have it. 4329 continue; 4330 } 4331 for (int j=i+1; j<N; j++) { 4332 final ResolveInfo rij = results.get(j); 4333 if (rij.filter != null && rij.filter.hasAction(action)) { 4334 results.remove(j); 4335 if (DEBUG_INTENT_MATCHING) Log.v( 4336 TAG, "Removing duplicate item from " + j 4337 + " due to action " + action + " at " + i); 4338 j--; 4339 N--; 4340 } 4341 } 4342 } 4343 4344 // If the caller didn't request filter information, drop it now 4345 // so we don't have to marshall/unmarshall it. 4346 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4347 rii.filter = null; 4348 } 4349 } 4350 4351 // Filter out the caller activity if so requested. 4352 if (caller != null) { 4353 N = results.size(); 4354 for (int i=0; i<N; i++) { 4355 ActivityInfo ainfo = results.get(i).activityInfo; 4356 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4357 && caller.getClassName().equals(ainfo.name)) { 4358 results.remove(i); 4359 break; 4360 } 4361 } 4362 } 4363 4364 // If the caller didn't request filter information, 4365 // drop them now so we don't have to 4366 // marshall/unmarshall it. 4367 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4368 N = results.size(); 4369 for (int i=0; i<N; i++) { 4370 results.get(i).filter = null; 4371 } 4372 } 4373 4374 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4375 return results; 4376 } 4377 4378 @Override 4379 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4380 int userId) { 4381 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4382 ComponentName comp = intent.getComponent(); 4383 if (comp == null) { 4384 if (intent.getSelector() != null) { 4385 intent = intent.getSelector(); 4386 comp = intent.getComponent(); 4387 } 4388 } 4389 if (comp != null) { 4390 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4391 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4392 if (ai != null) { 4393 ResolveInfo ri = new ResolveInfo(); 4394 ri.activityInfo = ai; 4395 list.add(ri); 4396 } 4397 return list; 4398 } 4399 4400 // reader 4401 synchronized (mPackages) { 4402 String pkgName = intent.getPackage(); 4403 if (pkgName == null) { 4404 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4405 } 4406 final PackageParser.Package pkg = mPackages.get(pkgName); 4407 if (pkg != null) { 4408 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4409 userId); 4410 } 4411 return null; 4412 } 4413 } 4414 4415 @Override 4416 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4417 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4418 if (!sUserManager.exists(userId)) return null; 4419 if (query != null) { 4420 if (query.size() >= 1) { 4421 // If there is more than one service with the same priority, 4422 // just arbitrarily pick the first one. 4423 return query.get(0); 4424 } 4425 } 4426 return null; 4427 } 4428 4429 @Override 4430 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4431 int userId) { 4432 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4433 ComponentName comp = intent.getComponent(); 4434 if (comp == null) { 4435 if (intent.getSelector() != null) { 4436 intent = intent.getSelector(); 4437 comp = intent.getComponent(); 4438 } 4439 } 4440 if (comp != null) { 4441 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4442 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4443 if (si != null) { 4444 final ResolveInfo ri = new ResolveInfo(); 4445 ri.serviceInfo = si; 4446 list.add(ri); 4447 } 4448 return list; 4449 } 4450 4451 // reader 4452 synchronized (mPackages) { 4453 String pkgName = intent.getPackage(); 4454 if (pkgName == null) { 4455 return mServices.queryIntent(intent, resolvedType, flags, userId); 4456 } 4457 final PackageParser.Package pkg = mPackages.get(pkgName); 4458 if (pkg != null) { 4459 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4460 userId); 4461 } 4462 return null; 4463 } 4464 } 4465 4466 @Override 4467 public List<ResolveInfo> queryIntentContentProviders( 4468 Intent intent, String resolvedType, int flags, int userId) { 4469 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4470 ComponentName comp = intent.getComponent(); 4471 if (comp == null) { 4472 if (intent.getSelector() != null) { 4473 intent = intent.getSelector(); 4474 comp = intent.getComponent(); 4475 } 4476 } 4477 if (comp != null) { 4478 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4479 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4480 if (pi != null) { 4481 final ResolveInfo ri = new ResolveInfo(); 4482 ri.providerInfo = pi; 4483 list.add(ri); 4484 } 4485 return list; 4486 } 4487 4488 // reader 4489 synchronized (mPackages) { 4490 String pkgName = intent.getPackage(); 4491 if (pkgName == null) { 4492 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4493 } 4494 final PackageParser.Package pkg = mPackages.get(pkgName); 4495 if (pkg != null) { 4496 return mProviders.queryIntentForPackage( 4497 intent, resolvedType, flags, pkg.providers, userId); 4498 } 4499 return null; 4500 } 4501 } 4502 4503 @Override 4504 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4505 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4506 4507 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4508 4509 // writer 4510 synchronized (mPackages) { 4511 ArrayList<PackageInfo> list; 4512 if (listUninstalled) { 4513 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4514 for (PackageSetting ps : mSettings.mPackages.values()) { 4515 PackageInfo pi; 4516 if (ps.pkg != null) { 4517 pi = generatePackageInfo(ps.pkg, flags, userId); 4518 } else { 4519 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4520 } 4521 if (pi != null) { 4522 list.add(pi); 4523 } 4524 } 4525 } else { 4526 list = new ArrayList<PackageInfo>(mPackages.size()); 4527 for (PackageParser.Package p : mPackages.values()) { 4528 PackageInfo pi = generatePackageInfo(p, flags, userId); 4529 if (pi != null) { 4530 list.add(pi); 4531 } 4532 } 4533 } 4534 4535 return new ParceledListSlice<PackageInfo>(list); 4536 } 4537 } 4538 4539 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4540 String[] permissions, boolean[] tmp, int flags, int userId) { 4541 int numMatch = 0; 4542 final PermissionsState permissionsState = ps.getPermissionsState(); 4543 for (int i=0; i<permissions.length; i++) { 4544 final String permission = permissions[i]; 4545 if (permissionsState.hasPermission(permission, userId)) { 4546 tmp[i] = true; 4547 numMatch++; 4548 } else { 4549 tmp[i] = false; 4550 } 4551 } 4552 if (numMatch == 0) { 4553 return; 4554 } 4555 PackageInfo pi; 4556 if (ps.pkg != null) { 4557 pi = generatePackageInfo(ps.pkg, flags, userId); 4558 } else { 4559 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4560 } 4561 // The above might return null in cases of uninstalled apps or install-state 4562 // skew across users/profiles. 4563 if (pi != null) { 4564 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4565 if (numMatch == permissions.length) { 4566 pi.requestedPermissions = permissions; 4567 } else { 4568 pi.requestedPermissions = new String[numMatch]; 4569 numMatch = 0; 4570 for (int i=0; i<permissions.length; i++) { 4571 if (tmp[i]) { 4572 pi.requestedPermissions[numMatch] = permissions[i]; 4573 numMatch++; 4574 } 4575 } 4576 } 4577 } 4578 list.add(pi); 4579 } 4580 } 4581 4582 @Override 4583 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4584 String[] permissions, int flags, int userId) { 4585 if (!sUserManager.exists(userId)) return null; 4586 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4587 4588 // writer 4589 synchronized (mPackages) { 4590 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4591 boolean[] tmpBools = new boolean[permissions.length]; 4592 if (listUninstalled) { 4593 for (PackageSetting ps : mSettings.mPackages.values()) { 4594 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4595 } 4596 } else { 4597 for (PackageParser.Package pkg : mPackages.values()) { 4598 PackageSetting ps = (PackageSetting)pkg.mExtras; 4599 if (ps != null) { 4600 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4601 userId); 4602 } 4603 } 4604 } 4605 4606 return new ParceledListSlice<PackageInfo>(list); 4607 } 4608 } 4609 4610 @Override 4611 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4612 if (!sUserManager.exists(userId)) return null; 4613 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4614 4615 // writer 4616 synchronized (mPackages) { 4617 ArrayList<ApplicationInfo> list; 4618 if (listUninstalled) { 4619 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4620 for (PackageSetting ps : mSettings.mPackages.values()) { 4621 ApplicationInfo ai; 4622 if (ps.pkg != null) { 4623 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4624 ps.readUserState(userId), userId); 4625 } else { 4626 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4627 } 4628 if (ai != null) { 4629 list.add(ai); 4630 } 4631 } 4632 } else { 4633 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4634 for (PackageParser.Package p : mPackages.values()) { 4635 if (p.mExtras != null) { 4636 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4637 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4638 if (ai != null) { 4639 list.add(ai); 4640 } 4641 } 4642 } 4643 } 4644 4645 return new ParceledListSlice<ApplicationInfo>(list); 4646 } 4647 } 4648 4649 public List<ApplicationInfo> getPersistentApplications(int flags) { 4650 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4651 4652 // reader 4653 synchronized (mPackages) { 4654 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4655 final int userId = UserHandle.getCallingUserId(); 4656 while (i.hasNext()) { 4657 final PackageParser.Package p = i.next(); 4658 if (p.applicationInfo != null 4659 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4660 && (!mSafeMode || isSystemApp(p))) { 4661 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4662 if (ps != null) { 4663 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4664 ps.readUserState(userId), userId); 4665 if (ai != null) { 4666 finalList.add(ai); 4667 } 4668 } 4669 } 4670 } 4671 } 4672 4673 return finalList; 4674 } 4675 4676 @Override 4677 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4678 if (!sUserManager.exists(userId)) return null; 4679 // reader 4680 synchronized (mPackages) { 4681 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4682 PackageSetting ps = provider != null 4683 ? mSettings.mPackages.get(provider.owner.packageName) 4684 : null; 4685 return ps != null 4686 && mSettings.isEnabledLPr(provider.info, flags, userId) 4687 && (!mSafeMode || (provider.info.applicationInfo.flags 4688 &ApplicationInfo.FLAG_SYSTEM) != 0) 4689 ? PackageParser.generateProviderInfo(provider, flags, 4690 ps.readUserState(userId), userId) 4691 : null; 4692 } 4693 } 4694 4695 /** 4696 * @deprecated 4697 */ 4698 @Deprecated 4699 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4700 // reader 4701 synchronized (mPackages) { 4702 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4703 .entrySet().iterator(); 4704 final int userId = UserHandle.getCallingUserId(); 4705 while (i.hasNext()) { 4706 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4707 PackageParser.Provider p = entry.getValue(); 4708 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4709 4710 if (ps != null && p.syncable 4711 && (!mSafeMode || (p.info.applicationInfo.flags 4712 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4713 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4714 ps.readUserState(userId), userId); 4715 if (info != null) { 4716 outNames.add(entry.getKey()); 4717 outInfo.add(info); 4718 } 4719 } 4720 } 4721 } 4722 } 4723 4724 @Override 4725 public List<ProviderInfo> queryContentProviders(String processName, 4726 int uid, int flags) { 4727 ArrayList<ProviderInfo> finalList = null; 4728 // reader 4729 synchronized (mPackages) { 4730 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4731 final int userId = processName != null ? 4732 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4733 while (i.hasNext()) { 4734 final PackageParser.Provider p = i.next(); 4735 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4736 if (ps != null && p.info.authority != null 4737 && (processName == null 4738 || (p.info.processName.equals(processName) 4739 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4740 && mSettings.isEnabledLPr(p.info, flags, userId) 4741 && (!mSafeMode 4742 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4743 if (finalList == null) { 4744 finalList = new ArrayList<ProviderInfo>(3); 4745 } 4746 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4747 ps.readUserState(userId), userId); 4748 if (info != null) { 4749 finalList.add(info); 4750 } 4751 } 4752 } 4753 } 4754 4755 if (finalList != null) { 4756 Collections.sort(finalList, mProviderInitOrderSorter); 4757 } 4758 4759 return finalList; 4760 } 4761 4762 @Override 4763 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4764 int flags) { 4765 // reader 4766 synchronized (mPackages) { 4767 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4768 return PackageParser.generateInstrumentationInfo(i, flags); 4769 } 4770 } 4771 4772 @Override 4773 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4774 int flags) { 4775 ArrayList<InstrumentationInfo> finalList = 4776 new ArrayList<InstrumentationInfo>(); 4777 4778 // reader 4779 synchronized (mPackages) { 4780 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4781 while (i.hasNext()) { 4782 final PackageParser.Instrumentation p = i.next(); 4783 if (targetPackage == null 4784 || targetPackage.equals(p.info.targetPackage)) { 4785 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4786 flags); 4787 if (ii != null) { 4788 finalList.add(ii); 4789 } 4790 } 4791 } 4792 } 4793 4794 return finalList; 4795 } 4796 4797 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4798 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4799 if (overlays == null) { 4800 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4801 return; 4802 } 4803 for (PackageParser.Package opkg : overlays.values()) { 4804 // Not much to do if idmap fails: we already logged the error 4805 // and we certainly don't want to abort installation of pkg simply 4806 // because an overlay didn't fit properly. For these reasons, 4807 // ignore the return value of createIdmapForPackagePairLI. 4808 createIdmapForPackagePairLI(pkg, opkg); 4809 } 4810 } 4811 4812 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4813 PackageParser.Package opkg) { 4814 if (!opkg.mTrustedOverlay) { 4815 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4816 opkg.baseCodePath + ": overlay not trusted"); 4817 return false; 4818 } 4819 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4820 if (overlaySet == null) { 4821 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4822 opkg.baseCodePath + " but target package has no known overlays"); 4823 return false; 4824 } 4825 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4826 // TODO: generate idmap for split APKs 4827 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4828 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4829 + opkg.baseCodePath); 4830 return false; 4831 } 4832 PackageParser.Package[] overlayArray = 4833 overlaySet.values().toArray(new PackageParser.Package[0]); 4834 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4835 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4836 return p1.mOverlayPriority - p2.mOverlayPriority; 4837 } 4838 }; 4839 Arrays.sort(overlayArray, cmp); 4840 4841 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4842 int i = 0; 4843 for (PackageParser.Package p : overlayArray) { 4844 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4845 } 4846 return true; 4847 } 4848 4849 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4850 final File[] files = dir.listFiles(); 4851 if (ArrayUtils.isEmpty(files)) { 4852 Log.d(TAG, "No files in app dir " + dir); 4853 return; 4854 } 4855 4856 if (DEBUG_PACKAGE_SCANNING) { 4857 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4858 + " flags=0x" + Integer.toHexString(parseFlags)); 4859 } 4860 4861 for (File file : files) { 4862 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4863 && !PackageInstallerService.isStageName(file.getName()); 4864 if (!isPackage) { 4865 // Ignore entries which are not packages 4866 continue; 4867 } 4868 try { 4869 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4870 scanFlags, currentTime, null); 4871 } catch (PackageManagerException e) { 4872 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4873 4874 // Delete invalid userdata apps 4875 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4876 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4877 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4878 if (file.isDirectory()) { 4879 mInstaller.rmPackageDir(file.getAbsolutePath()); 4880 } else { 4881 file.delete(); 4882 } 4883 } 4884 } 4885 } 4886 } 4887 4888 private static File getSettingsProblemFile() { 4889 File dataDir = Environment.getDataDirectory(); 4890 File systemDir = new File(dataDir, "system"); 4891 File fname = new File(systemDir, "uiderrors.txt"); 4892 return fname; 4893 } 4894 4895 static void reportSettingsProblem(int priority, String msg) { 4896 logCriticalInfo(priority, msg); 4897 } 4898 4899 static void logCriticalInfo(int priority, String msg) { 4900 Slog.println(priority, TAG, msg); 4901 EventLogTags.writePmCriticalInfo(msg); 4902 try { 4903 File fname = getSettingsProblemFile(); 4904 FileOutputStream out = new FileOutputStream(fname, true); 4905 PrintWriter pw = new FastPrintWriter(out); 4906 SimpleDateFormat formatter = new SimpleDateFormat(); 4907 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4908 pw.println(dateString + ": " + msg); 4909 pw.close(); 4910 FileUtils.setPermissions( 4911 fname.toString(), 4912 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4913 -1, -1); 4914 } catch (java.io.IOException e) { 4915 } 4916 } 4917 4918 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4919 PackageParser.Package pkg, File srcFile, int parseFlags) 4920 throws PackageManagerException { 4921 if (ps != null 4922 && ps.codePath.equals(srcFile) 4923 && ps.timeStamp == srcFile.lastModified() 4924 && !isCompatSignatureUpdateNeeded(pkg) 4925 && !isRecoverSignatureUpdateNeeded(pkg)) { 4926 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4927 if (ps.signatures.mSignatures != null 4928 && ps.signatures.mSignatures.length != 0 4929 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4930 // Optimization: reuse the existing cached certificates 4931 // if the package appears to be unchanged. 4932 pkg.mSignatures = ps.signatures.mSignatures; 4933 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4934 synchronized (mPackages) { 4935 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4936 } 4937 return; 4938 } 4939 4940 Slog.w(TAG, "PackageSetting for " + ps.name 4941 + " is missing signatures. Collecting certs again to recover them."); 4942 } else { 4943 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4944 } 4945 4946 try { 4947 pp.collectCertificates(pkg, parseFlags); 4948 pp.collectManifestDigest(pkg); 4949 } catch (PackageParserException e) { 4950 throw PackageManagerException.from(e); 4951 } 4952 } 4953 4954 /* 4955 * Scan a package and return the newly parsed package. 4956 * Returns null in case of errors and the error code is stored in mLastScanError 4957 */ 4958 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4959 long currentTime, UserHandle user) throws PackageManagerException { 4960 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4961 parseFlags |= mDefParseFlags; 4962 PackageParser pp = new PackageParser(); 4963 pp.setSeparateProcesses(mSeparateProcesses); 4964 pp.setOnlyCoreApps(mOnlyCore); 4965 pp.setDisplayMetrics(mMetrics); 4966 4967 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4968 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4969 } 4970 4971 final PackageParser.Package pkg; 4972 try { 4973 pkg = pp.parsePackage(scanFile, parseFlags); 4974 } catch (PackageParserException e) { 4975 throw PackageManagerException.from(e); 4976 } 4977 4978 PackageSetting ps = null; 4979 PackageSetting updatedPkg; 4980 // reader 4981 synchronized (mPackages) { 4982 // Look to see if we already know about this package. 4983 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4984 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4985 // This package has been renamed to its original name. Let's 4986 // use that. 4987 ps = mSettings.peekPackageLPr(oldName); 4988 } 4989 // If there was no original package, see one for the real package name. 4990 if (ps == null) { 4991 ps = mSettings.peekPackageLPr(pkg.packageName); 4992 } 4993 // Check to see if this package could be hiding/updating a system 4994 // package. Must look for it either under the original or real 4995 // package name depending on our state. 4996 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4997 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4998 } 4999 boolean updatedPkgBetter = false; 5000 // First check if this is a system package that may involve an update 5001 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5002 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5003 // it needs to drop FLAG_PRIVILEGED. 5004 if (locationIsPrivileged(scanFile)) { 5005 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5006 } else { 5007 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5008 } 5009 5010 if (ps != null && !ps.codePath.equals(scanFile)) { 5011 // The path has changed from what was last scanned... check the 5012 // version of the new path against what we have stored to determine 5013 // what to do. 5014 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5015 if (pkg.mVersionCode <= ps.versionCode) { 5016 // The system package has been updated and the code path does not match 5017 // Ignore entry. Skip it. 5018 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5019 + " ignored: updated version " + ps.versionCode 5020 + " better than this " + pkg.mVersionCode); 5021 if (!updatedPkg.codePath.equals(scanFile)) { 5022 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5023 + ps.name + " changing from " + updatedPkg.codePathString 5024 + " to " + scanFile); 5025 updatedPkg.codePath = scanFile; 5026 updatedPkg.codePathString = scanFile.toString(); 5027 updatedPkg.resourcePath = scanFile; 5028 updatedPkg.resourcePathString = scanFile.toString(); 5029 } 5030 updatedPkg.pkg = pkg; 5031 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5032 } else { 5033 // The current app on the system partition is better than 5034 // what we have updated to on the data partition; switch 5035 // back to the system partition version. 5036 // At this point, its safely assumed that package installation for 5037 // apps in system partition will go through. If not there won't be a working 5038 // version of the app 5039 // writer 5040 synchronized (mPackages) { 5041 // Just remove the loaded entries from package lists. 5042 mPackages.remove(ps.name); 5043 } 5044 5045 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5046 + " reverting from " + ps.codePathString 5047 + ": new version " + pkg.mVersionCode 5048 + " better than installed " + ps.versionCode); 5049 5050 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5051 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5052 synchronized (mInstallLock) { 5053 args.cleanUpResourcesLI(); 5054 } 5055 synchronized (mPackages) { 5056 mSettings.enableSystemPackageLPw(ps.name); 5057 } 5058 updatedPkgBetter = true; 5059 } 5060 } 5061 } 5062 5063 if (updatedPkg != null) { 5064 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5065 // initially 5066 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5067 5068 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5069 // flag set initially 5070 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5071 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5072 } 5073 } 5074 5075 // Verify certificates against what was last scanned 5076 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5077 5078 /* 5079 * A new system app appeared, but we already had a non-system one of the 5080 * same name installed earlier. 5081 */ 5082 boolean shouldHideSystemApp = false; 5083 if (updatedPkg == null && ps != null 5084 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5085 /* 5086 * Check to make sure the signatures match first. If they don't, 5087 * wipe the installed application and its data. 5088 */ 5089 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5090 != PackageManager.SIGNATURE_MATCH) { 5091 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5092 + " signatures don't match existing userdata copy; removing"); 5093 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5094 ps = null; 5095 } else { 5096 /* 5097 * If the newly-added system app is an older version than the 5098 * already installed version, hide it. It will be scanned later 5099 * and re-added like an update. 5100 */ 5101 if (pkg.mVersionCode <= ps.versionCode) { 5102 shouldHideSystemApp = true; 5103 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5104 + " but new version " + pkg.mVersionCode + " better than installed " 5105 + ps.versionCode + "; hiding system"); 5106 } else { 5107 /* 5108 * The newly found system app is a newer version that the 5109 * one previously installed. Simply remove the 5110 * already-installed application and replace it with our own 5111 * while keeping the application data. 5112 */ 5113 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5114 + " reverting from " + ps.codePathString + ": new version " 5115 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5116 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5117 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5118 synchronized (mInstallLock) { 5119 args.cleanUpResourcesLI(); 5120 } 5121 } 5122 } 5123 } 5124 5125 // The apk is forward locked (not public) if its code and resources 5126 // are kept in different files. (except for app in either system or 5127 // vendor path). 5128 // TODO grab this value from PackageSettings 5129 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5130 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5131 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5132 } 5133 } 5134 5135 // TODO: extend to support forward-locked splits 5136 String resourcePath = null; 5137 String baseResourcePath = null; 5138 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5139 if (ps != null && ps.resourcePathString != null) { 5140 resourcePath = ps.resourcePathString; 5141 baseResourcePath = ps.resourcePathString; 5142 } else { 5143 // Should not happen at all. Just log an error. 5144 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5145 } 5146 } else { 5147 resourcePath = pkg.codePath; 5148 baseResourcePath = pkg.baseCodePath; 5149 } 5150 5151 // Set application objects path explicitly. 5152 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5153 pkg.applicationInfo.setCodePath(pkg.codePath); 5154 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5155 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5156 pkg.applicationInfo.setResourcePath(resourcePath); 5157 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5158 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5159 5160 // Note that we invoke the following method only if we are about to unpack an application 5161 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5162 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5163 5164 /* 5165 * If the system app should be overridden by a previously installed 5166 * data, hide the system app now and let the /data/app scan pick it up 5167 * again. 5168 */ 5169 if (shouldHideSystemApp) { 5170 synchronized (mPackages) { 5171 /* 5172 * We have to grant systems permissions before we hide, because 5173 * grantPermissions will assume the package update is trying to 5174 * expand its permissions. 5175 */ 5176 grantPermissionsLPw(pkg, true, pkg.packageName); 5177 mSettings.disableSystemPackageLPw(pkg.packageName); 5178 } 5179 } 5180 5181 return scannedPkg; 5182 } 5183 5184 private static String fixProcessName(String defProcessName, 5185 String processName, int uid) { 5186 if (processName == null) { 5187 return defProcessName; 5188 } 5189 return processName; 5190 } 5191 5192 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5193 throws PackageManagerException { 5194 if (pkgSetting.signatures.mSignatures != null) { 5195 // Already existing package. Make sure signatures match 5196 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5197 == PackageManager.SIGNATURE_MATCH; 5198 if (!match) { 5199 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5200 == PackageManager.SIGNATURE_MATCH; 5201 } 5202 if (!match) { 5203 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5204 == PackageManager.SIGNATURE_MATCH; 5205 } 5206 if (!match) { 5207 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5208 + pkg.packageName + " signatures do not match the " 5209 + "previously installed version; ignoring!"); 5210 } 5211 } 5212 5213 // Check for shared user signatures 5214 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5215 // Already existing package. Make sure signatures match 5216 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5217 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5218 if (!match) { 5219 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5220 == PackageManager.SIGNATURE_MATCH; 5221 } 5222 if (!match) { 5223 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5224 == PackageManager.SIGNATURE_MATCH; 5225 } 5226 if (!match) { 5227 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5228 "Package " + pkg.packageName 5229 + " has no signatures that match those in shared user " 5230 + pkgSetting.sharedUser.name + "; ignoring!"); 5231 } 5232 } 5233 } 5234 5235 /** 5236 * Enforces that only the system UID or root's UID can call a method exposed 5237 * via Binder. 5238 * 5239 * @param message used as message if SecurityException is thrown 5240 * @throws SecurityException if the caller is not system or root 5241 */ 5242 private static final void enforceSystemOrRoot(String message) { 5243 final int uid = Binder.getCallingUid(); 5244 if (uid != Process.SYSTEM_UID && uid != 0) { 5245 throw new SecurityException(message); 5246 } 5247 } 5248 5249 @Override 5250 public void performBootDexOpt() { 5251 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5252 5253 // Before everything else, see whether we need to fstrim. 5254 try { 5255 IMountService ms = PackageHelper.getMountService(); 5256 if (ms != null) { 5257 final boolean isUpgrade = isUpgrade(); 5258 boolean doTrim = isUpgrade; 5259 if (doTrim) { 5260 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5261 } else { 5262 final long interval = android.provider.Settings.Global.getLong( 5263 mContext.getContentResolver(), 5264 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5265 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5266 if (interval > 0) { 5267 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5268 if (timeSinceLast > interval) { 5269 doTrim = true; 5270 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5271 + "; running immediately"); 5272 } 5273 } 5274 } 5275 if (doTrim) { 5276 if (!isFirstBoot()) { 5277 try { 5278 ActivityManagerNative.getDefault().showBootMessage( 5279 mContext.getResources().getString( 5280 R.string.android_upgrading_fstrim), true); 5281 } catch (RemoteException e) { 5282 } 5283 } 5284 ms.runMaintenance(); 5285 } 5286 } else { 5287 Slog.e(TAG, "Mount service unavailable!"); 5288 } 5289 } catch (RemoteException e) { 5290 // Can't happen; MountService is local 5291 } 5292 5293 final ArraySet<PackageParser.Package> pkgs; 5294 synchronized (mPackages) { 5295 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5296 } 5297 5298 if (pkgs != null) { 5299 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5300 // in case the device runs out of space. 5301 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5302 // Give priority to core apps. 5303 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5304 PackageParser.Package pkg = it.next(); 5305 if (pkg.coreApp) { 5306 if (DEBUG_DEXOPT) { 5307 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5308 } 5309 sortedPkgs.add(pkg); 5310 it.remove(); 5311 } 5312 } 5313 // Give priority to system apps that listen for pre boot complete. 5314 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5315 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5316 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5317 PackageParser.Package pkg = it.next(); 5318 if (pkgNames.contains(pkg.packageName)) { 5319 if (DEBUG_DEXOPT) { 5320 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5321 } 5322 sortedPkgs.add(pkg); 5323 it.remove(); 5324 } 5325 } 5326 // Give priority to system apps. 5327 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5328 PackageParser.Package pkg = it.next(); 5329 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5330 if (DEBUG_DEXOPT) { 5331 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5332 } 5333 sortedPkgs.add(pkg); 5334 it.remove(); 5335 } 5336 } 5337 // Give priority to updated system apps. 5338 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5339 PackageParser.Package pkg = it.next(); 5340 if (pkg.isUpdatedSystemApp()) { 5341 if (DEBUG_DEXOPT) { 5342 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5343 } 5344 sortedPkgs.add(pkg); 5345 it.remove(); 5346 } 5347 } 5348 // Give priority to apps that listen for boot complete. 5349 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5350 pkgNames = getPackageNamesForIntent(intent); 5351 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5352 PackageParser.Package pkg = it.next(); 5353 if (pkgNames.contains(pkg.packageName)) { 5354 if (DEBUG_DEXOPT) { 5355 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5356 } 5357 sortedPkgs.add(pkg); 5358 it.remove(); 5359 } 5360 } 5361 // Filter out packages that aren't recently used. 5362 filterRecentlyUsedApps(pkgs); 5363 // Add all remaining apps. 5364 for (PackageParser.Package pkg : pkgs) { 5365 if (DEBUG_DEXOPT) { 5366 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5367 } 5368 sortedPkgs.add(pkg); 5369 } 5370 5371 // If we want to be lazy, filter everything that wasn't recently used. 5372 if (mLazyDexOpt) { 5373 filterRecentlyUsedApps(sortedPkgs); 5374 } 5375 5376 int i = 0; 5377 int total = sortedPkgs.size(); 5378 File dataDir = Environment.getDataDirectory(); 5379 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5380 if (lowThreshold == 0) { 5381 throw new IllegalStateException("Invalid low memory threshold"); 5382 } 5383 for (PackageParser.Package pkg : sortedPkgs) { 5384 long usableSpace = dataDir.getUsableSpace(); 5385 if (usableSpace < lowThreshold) { 5386 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5387 break; 5388 } 5389 performBootDexOpt(pkg, ++i, total); 5390 } 5391 } 5392 } 5393 5394 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5395 // Filter out packages that aren't recently used. 5396 // 5397 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5398 // should do a full dexopt. 5399 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5400 int total = pkgs.size(); 5401 int skipped = 0; 5402 long now = System.currentTimeMillis(); 5403 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5404 PackageParser.Package pkg = i.next(); 5405 long then = pkg.mLastPackageUsageTimeInMills; 5406 if (then + mDexOptLRUThresholdInMills < now) { 5407 if (DEBUG_DEXOPT) { 5408 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5409 ((then == 0) ? "never" : new Date(then))); 5410 } 5411 i.remove(); 5412 skipped++; 5413 } 5414 } 5415 if (DEBUG_DEXOPT) { 5416 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5417 } 5418 } 5419 } 5420 5421 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5422 List<ResolveInfo> ris = null; 5423 try { 5424 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5425 intent, null, 0, UserHandle.USER_OWNER); 5426 } catch (RemoteException e) { 5427 } 5428 ArraySet<String> pkgNames = new ArraySet<String>(); 5429 if (ris != null) { 5430 for (ResolveInfo ri : ris) { 5431 pkgNames.add(ri.activityInfo.packageName); 5432 } 5433 } 5434 return pkgNames; 5435 } 5436 5437 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5438 if (DEBUG_DEXOPT) { 5439 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5440 } 5441 if (!isFirstBoot()) { 5442 try { 5443 ActivityManagerNative.getDefault().showBootMessage( 5444 mContext.getResources().getString(R.string.android_upgrading_apk, 5445 curr, total), true); 5446 } catch (RemoteException e) { 5447 } 5448 } 5449 PackageParser.Package p = pkg; 5450 synchronized (mInstallLock) { 5451 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5452 false /* force dex */, false /* defer */, true /* include dependencies */); 5453 } 5454 } 5455 5456 @Override 5457 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5458 return performDexOpt(packageName, instructionSet, false); 5459 } 5460 5461 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5462 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5463 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5464 if (!dexopt && !updateUsage) { 5465 // We aren't going to dexopt or update usage, so bail early. 5466 return false; 5467 } 5468 PackageParser.Package p; 5469 final String targetInstructionSet; 5470 synchronized (mPackages) { 5471 p = mPackages.get(packageName); 5472 if (p == null) { 5473 return false; 5474 } 5475 if (updateUsage) { 5476 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5477 } 5478 mPackageUsage.write(false); 5479 if (!dexopt) { 5480 // We aren't going to dexopt, so bail early. 5481 return false; 5482 } 5483 5484 targetInstructionSet = instructionSet != null ? instructionSet : 5485 getPrimaryInstructionSet(p.applicationInfo); 5486 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5487 return false; 5488 } 5489 } 5490 5491 synchronized (mInstallLock) { 5492 final String[] instructionSets = new String[] { targetInstructionSet }; 5493 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5494 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5495 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5496 } 5497 } 5498 5499 public ArraySet<String> getPackagesThatNeedDexOpt() { 5500 ArraySet<String> pkgs = null; 5501 synchronized (mPackages) { 5502 for (PackageParser.Package p : mPackages.values()) { 5503 if (DEBUG_DEXOPT) { 5504 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5505 } 5506 if (!p.mDexOptPerformed.isEmpty()) { 5507 continue; 5508 } 5509 if (pkgs == null) { 5510 pkgs = new ArraySet<String>(); 5511 } 5512 pkgs.add(p.packageName); 5513 } 5514 } 5515 return pkgs; 5516 } 5517 5518 public void shutdown() { 5519 mPackageUsage.write(true); 5520 } 5521 5522 @Override 5523 public void forceDexOpt(String packageName) { 5524 enforceSystemOrRoot("forceDexOpt"); 5525 5526 PackageParser.Package pkg; 5527 synchronized (mPackages) { 5528 pkg = mPackages.get(packageName); 5529 if (pkg == null) { 5530 throw new IllegalArgumentException("Missing package: " + packageName); 5531 } 5532 } 5533 5534 synchronized (mInstallLock) { 5535 final String[] instructionSets = new String[] { 5536 getPrimaryInstructionSet(pkg.applicationInfo) }; 5537 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5538 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5539 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5540 throw new IllegalStateException("Failed to dexopt: " + res); 5541 } 5542 } 5543 } 5544 5545 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5546 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5547 Slog.w(TAG, "Unable to update from " + oldPkg.name 5548 + " to " + newPkg.packageName 5549 + ": old package not in system partition"); 5550 return false; 5551 } else if (mPackages.get(oldPkg.name) != null) { 5552 Slog.w(TAG, "Unable to update from " + oldPkg.name 5553 + " to " + newPkg.packageName 5554 + ": old package still exists"); 5555 return false; 5556 } 5557 return true; 5558 } 5559 5560 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5561 int[] users = sUserManager.getUserIds(); 5562 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5563 if (res < 0) { 5564 return res; 5565 } 5566 for (int user : users) { 5567 if (user != 0) { 5568 res = mInstaller.createUserData(volumeUuid, packageName, 5569 UserHandle.getUid(user, uid), user, seinfo); 5570 if (res < 0) { 5571 return res; 5572 } 5573 } 5574 } 5575 return res; 5576 } 5577 5578 private int removeDataDirsLI(String volumeUuid, String packageName) { 5579 int[] users = sUserManager.getUserIds(); 5580 int res = 0; 5581 for (int user : users) { 5582 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5583 if (resInner < 0) { 5584 res = resInner; 5585 } 5586 } 5587 5588 return res; 5589 } 5590 5591 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5592 int[] users = sUserManager.getUserIds(); 5593 int res = 0; 5594 for (int user : users) { 5595 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5596 if (resInner < 0) { 5597 res = resInner; 5598 } 5599 } 5600 return res; 5601 } 5602 5603 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5604 PackageParser.Package changingLib) { 5605 if (file.path != null) { 5606 usesLibraryFiles.add(file.path); 5607 return; 5608 } 5609 PackageParser.Package p = mPackages.get(file.apk); 5610 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5611 // If we are doing this while in the middle of updating a library apk, 5612 // then we need to make sure to use that new apk for determining the 5613 // dependencies here. (We haven't yet finished committing the new apk 5614 // to the package manager state.) 5615 if (p == null || p.packageName.equals(changingLib.packageName)) { 5616 p = changingLib; 5617 } 5618 } 5619 if (p != null) { 5620 usesLibraryFiles.addAll(p.getAllCodePaths()); 5621 } 5622 } 5623 5624 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5625 PackageParser.Package changingLib) throws PackageManagerException { 5626 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5627 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5628 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5629 for (int i=0; i<N; i++) { 5630 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5631 if (file == null) { 5632 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5633 "Package " + pkg.packageName + " requires unavailable shared library " 5634 + pkg.usesLibraries.get(i) + "; failing!"); 5635 } 5636 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5637 } 5638 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5639 for (int i=0; i<N; i++) { 5640 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5641 if (file == null) { 5642 Slog.w(TAG, "Package " + pkg.packageName 5643 + " desires unavailable shared library " 5644 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5645 } else { 5646 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5647 } 5648 } 5649 N = usesLibraryFiles.size(); 5650 if (N > 0) { 5651 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5652 } else { 5653 pkg.usesLibraryFiles = null; 5654 } 5655 } 5656 } 5657 5658 private static boolean hasString(List<String> list, List<String> which) { 5659 if (list == null) { 5660 return false; 5661 } 5662 for (int i=list.size()-1; i>=0; i--) { 5663 for (int j=which.size()-1; j>=0; j--) { 5664 if (which.get(j).equals(list.get(i))) { 5665 return true; 5666 } 5667 } 5668 } 5669 return false; 5670 } 5671 5672 private void updateAllSharedLibrariesLPw() { 5673 for (PackageParser.Package pkg : mPackages.values()) { 5674 try { 5675 updateSharedLibrariesLPw(pkg, null); 5676 } catch (PackageManagerException e) { 5677 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5678 } 5679 } 5680 } 5681 5682 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5683 PackageParser.Package changingPkg) { 5684 ArrayList<PackageParser.Package> res = null; 5685 for (PackageParser.Package pkg : mPackages.values()) { 5686 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5687 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5688 if (res == null) { 5689 res = new ArrayList<PackageParser.Package>(); 5690 } 5691 res.add(pkg); 5692 try { 5693 updateSharedLibrariesLPw(pkg, changingPkg); 5694 } catch (PackageManagerException e) { 5695 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5696 } 5697 } 5698 } 5699 return res; 5700 } 5701 5702 /** 5703 * Derive the value of the {@code cpuAbiOverride} based on the provided 5704 * value and an optional stored value from the package settings. 5705 */ 5706 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5707 String cpuAbiOverride = null; 5708 5709 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5710 cpuAbiOverride = null; 5711 } else if (abiOverride != null) { 5712 cpuAbiOverride = abiOverride; 5713 } else if (settings != null) { 5714 cpuAbiOverride = settings.cpuAbiOverrideString; 5715 } 5716 5717 return cpuAbiOverride; 5718 } 5719 5720 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5721 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5722 boolean success = false; 5723 try { 5724 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5725 currentTime, user); 5726 success = true; 5727 return res; 5728 } finally { 5729 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5730 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5731 } 5732 } 5733 } 5734 5735 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5736 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5737 final File scanFile = new File(pkg.codePath); 5738 if (pkg.applicationInfo.getCodePath() == null || 5739 pkg.applicationInfo.getResourcePath() == null) { 5740 // Bail out. The resource and code paths haven't been set. 5741 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5742 "Code and resource paths haven't been set correctly"); 5743 } 5744 5745 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5746 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5747 } else { 5748 // Only allow system apps to be flagged as core apps. 5749 pkg.coreApp = false; 5750 } 5751 5752 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5753 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5754 } 5755 5756 if (mCustomResolverComponentName != null && 5757 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5758 setUpCustomResolverActivity(pkg); 5759 } 5760 5761 if (pkg.packageName.equals("android")) { 5762 synchronized (mPackages) { 5763 if (mAndroidApplication != null) { 5764 Slog.w(TAG, "*************************************************"); 5765 Slog.w(TAG, "Core android package being redefined. Skipping."); 5766 Slog.w(TAG, " file=" + scanFile); 5767 Slog.w(TAG, "*************************************************"); 5768 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5769 "Core android package being redefined. Skipping."); 5770 } 5771 5772 // Set up information for our fall-back user intent resolution activity. 5773 mPlatformPackage = pkg; 5774 pkg.mVersionCode = mSdkVersion; 5775 mAndroidApplication = pkg.applicationInfo; 5776 5777 if (!mResolverReplaced) { 5778 mResolveActivity.applicationInfo = mAndroidApplication; 5779 mResolveActivity.name = ResolverActivity.class.getName(); 5780 mResolveActivity.packageName = mAndroidApplication.packageName; 5781 mResolveActivity.processName = "system:ui"; 5782 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5783 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5784 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5785 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5786 mResolveActivity.exported = true; 5787 mResolveActivity.enabled = true; 5788 mResolveInfo.activityInfo = mResolveActivity; 5789 mResolveInfo.priority = 0; 5790 mResolveInfo.preferredOrder = 0; 5791 mResolveInfo.match = 0; 5792 mResolveComponentName = new ComponentName( 5793 mAndroidApplication.packageName, mResolveActivity.name); 5794 } 5795 } 5796 } 5797 5798 if (DEBUG_PACKAGE_SCANNING) { 5799 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5800 Log.d(TAG, "Scanning package " + pkg.packageName); 5801 } 5802 5803 if (mPackages.containsKey(pkg.packageName) 5804 || mSharedLibraries.containsKey(pkg.packageName)) { 5805 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5806 "Application package " + pkg.packageName 5807 + " already installed. Skipping duplicate."); 5808 } 5809 5810 // If we're only installing presumed-existing packages, require that the 5811 // scanned APK is both already known and at the path previously established 5812 // for it. Previously unknown packages we pick up normally, but if we have an 5813 // a priori expectation about this package's install presence, enforce it. 5814 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5815 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5816 if (known != null) { 5817 if (DEBUG_PACKAGE_SCANNING) { 5818 Log.d(TAG, "Examining " + pkg.codePath 5819 + " and requiring known paths " + known.codePathString 5820 + " & " + known.resourcePathString); 5821 } 5822 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5823 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5824 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5825 "Application package " + pkg.packageName 5826 + " found at " + pkg.applicationInfo.getCodePath() 5827 + " but expected at " + known.codePathString + "; ignoring."); 5828 } 5829 } 5830 } 5831 5832 // Initialize package source and resource directories 5833 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5834 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5835 5836 SharedUserSetting suid = null; 5837 PackageSetting pkgSetting = null; 5838 5839 if (!isSystemApp(pkg)) { 5840 // Only system apps can use these features. 5841 pkg.mOriginalPackages = null; 5842 pkg.mRealPackage = null; 5843 pkg.mAdoptPermissions = null; 5844 } 5845 5846 // writer 5847 synchronized (mPackages) { 5848 if (pkg.mSharedUserId != null) { 5849 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5850 if (suid == null) { 5851 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5852 "Creating application package " + pkg.packageName 5853 + " for shared user failed"); 5854 } 5855 if (DEBUG_PACKAGE_SCANNING) { 5856 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5857 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5858 + "): packages=" + suid.packages); 5859 } 5860 } 5861 5862 // Check if we are renaming from an original package name. 5863 PackageSetting origPackage = null; 5864 String realName = null; 5865 if (pkg.mOriginalPackages != null) { 5866 // This package may need to be renamed to a previously 5867 // installed name. Let's check on that... 5868 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5869 if (pkg.mOriginalPackages.contains(renamed)) { 5870 // This package had originally been installed as the 5871 // original name, and we have already taken care of 5872 // transitioning to the new one. Just update the new 5873 // one to continue using the old name. 5874 realName = pkg.mRealPackage; 5875 if (!pkg.packageName.equals(renamed)) { 5876 // Callers into this function may have already taken 5877 // care of renaming the package; only do it here if 5878 // it is not already done. 5879 pkg.setPackageName(renamed); 5880 } 5881 5882 } else { 5883 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5884 if ((origPackage = mSettings.peekPackageLPr( 5885 pkg.mOriginalPackages.get(i))) != null) { 5886 // We do have the package already installed under its 5887 // original name... should we use it? 5888 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5889 // New package is not compatible with original. 5890 origPackage = null; 5891 continue; 5892 } else if (origPackage.sharedUser != null) { 5893 // Make sure uid is compatible between packages. 5894 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5895 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5896 + " to " + pkg.packageName + ": old uid " 5897 + origPackage.sharedUser.name 5898 + " differs from " + pkg.mSharedUserId); 5899 origPackage = null; 5900 continue; 5901 } 5902 } else { 5903 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5904 + pkg.packageName + " to old name " + origPackage.name); 5905 } 5906 break; 5907 } 5908 } 5909 } 5910 } 5911 5912 if (mTransferedPackages.contains(pkg.packageName)) { 5913 Slog.w(TAG, "Package " + pkg.packageName 5914 + " was transferred to another, but its .apk remains"); 5915 } 5916 5917 // Just create the setting, don't add it yet. For already existing packages 5918 // the PkgSetting exists already and doesn't have to be created. 5919 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5920 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5921 pkg.applicationInfo.primaryCpuAbi, 5922 pkg.applicationInfo.secondaryCpuAbi, 5923 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5924 user, false); 5925 if (pkgSetting == null) { 5926 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5927 "Creating application package " + pkg.packageName + " failed"); 5928 } 5929 5930 if (pkgSetting.origPackage != null) { 5931 // If we are first transitioning from an original package, 5932 // fix up the new package's name now. We need to do this after 5933 // looking up the package under its new name, so getPackageLP 5934 // can take care of fiddling things correctly. 5935 pkg.setPackageName(origPackage.name); 5936 5937 // File a report about this. 5938 String msg = "New package " + pkgSetting.realName 5939 + " renamed to replace old package " + pkgSetting.name; 5940 reportSettingsProblem(Log.WARN, msg); 5941 5942 // Make a note of it. 5943 mTransferedPackages.add(origPackage.name); 5944 5945 // No longer need to retain this. 5946 pkgSetting.origPackage = null; 5947 } 5948 5949 if (realName != null) { 5950 // Make a note of it. 5951 mTransferedPackages.add(pkg.packageName); 5952 } 5953 5954 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5955 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5956 } 5957 5958 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5959 // Check all shared libraries and map to their actual file path. 5960 // We only do this here for apps not on a system dir, because those 5961 // are the only ones that can fail an install due to this. We 5962 // will take care of the system apps by updating all of their 5963 // library paths after the scan is done. 5964 updateSharedLibrariesLPw(pkg, null); 5965 } 5966 5967 if (mFoundPolicyFile) { 5968 SELinuxMMAC.assignSeinfoValue(pkg); 5969 } 5970 5971 pkg.applicationInfo.uid = pkgSetting.appId; 5972 pkg.mExtras = pkgSetting; 5973 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5974 try { 5975 verifySignaturesLP(pkgSetting, pkg); 5976 // We just determined the app is signed correctly, so bring 5977 // over the latest parsed certs. 5978 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5979 } catch (PackageManagerException e) { 5980 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5981 throw e; 5982 } 5983 // The signature has changed, but this package is in the system 5984 // image... let's recover! 5985 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5986 // However... if this package is part of a shared user, but it 5987 // doesn't match the signature of the shared user, let's fail. 5988 // What this means is that you can't change the signatures 5989 // associated with an overall shared user, which doesn't seem all 5990 // that unreasonable. 5991 if (pkgSetting.sharedUser != null) { 5992 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5993 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5994 throw new PackageManagerException( 5995 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5996 "Signature mismatch for shared user : " 5997 + pkgSetting.sharedUser); 5998 } 5999 } 6000 // File a report about this. 6001 String msg = "System package " + pkg.packageName 6002 + " signature changed; retaining data."; 6003 reportSettingsProblem(Log.WARN, msg); 6004 } 6005 } else { 6006 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6007 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6008 + pkg.packageName + " upgrade keys do not match the " 6009 + "previously installed version"); 6010 } else { 6011 // We just determined the app is signed correctly, so bring 6012 // over the latest parsed certs. 6013 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6014 } 6015 } 6016 // Verify that this new package doesn't have any content providers 6017 // that conflict with existing packages. Only do this if the 6018 // package isn't already installed, since we don't want to break 6019 // things that are installed. 6020 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6021 final int N = pkg.providers.size(); 6022 int i; 6023 for (i=0; i<N; i++) { 6024 PackageParser.Provider p = pkg.providers.get(i); 6025 if (p.info.authority != null) { 6026 String names[] = p.info.authority.split(";"); 6027 for (int j = 0; j < names.length; j++) { 6028 if (mProvidersByAuthority.containsKey(names[j])) { 6029 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6030 final String otherPackageName = 6031 ((other != null && other.getComponentName() != null) ? 6032 other.getComponentName().getPackageName() : "?"); 6033 throw new PackageManagerException( 6034 INSTALL_FAILED_CONFLICTING_PROVIDER, 6035 "Can't install because provider name " + names[j] 6036 + " (in package " + pkg.applicationInfo.packageName 6037 + ") is already used by " + otherPackageName); 6038 } 6039 } 6040 } 6041 } 6042 } 6043 6044 if (pkg.mAdoptPermissions != null) { 6045 // This package wants to adopt ownership of permissions from 6046 // another package. 6047 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6048 final String origName = pkg.mAdoptPermissions.get(i); 6049 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6050 if (orig != null) { 6051 if (verifyPackageUpdateLPr(orig, pkg)) { 6052 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6053 + pkg.packageName); 6054 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6055 } 6056 } 6057 } 6058 } 6059 } 6060 6061 final String pkgName = pkg.packageName; 6062 6063 final long scanFileTime = scanFile.lastModified(); 6064 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6065 pkg.applicationInfo.processName = fixProcessName( 6066 pkg.applicationInfo.packageName, 6067 pkg.applicationInfo.processName, 6068 pkg.applicationInfo.uid); 6069 6070 File dataPath; 6071 if (mPlatformPackage == pkg) { 6072 // The system package is special. 6073 dataPath = new File(Environment.getDataDirectory(), "system"); 6074 6075 pkg.applicationInfo.dataDir = dataPath.getPath(); 6076 6077 } else { 6078 // This is a normal package, need to make its data directory. 6079 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6080 UserHandle.USER_OWNER); 6081 6082 boolean uidError = false; 6083 if (dataPath.exists()) { 6084 int currentUid = 0; 6085 try { 6086 StructStat stat = Os.stat(dataPath.getPath()); 6087 currentUid = stat.st_uid; 6088 } catch (ErrnoException e) { 6089 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6090 } 6091 6092 // If we have mismatched owners for the data path, we have a problem. 6093 if (currentUid != pkg.applicationInfo.uid) { 6094 boolean recovered = false; 6095 if (currentUid == 0) { 6096 // The directory somehow became owned by root. Wow. 6097 // This is probably because the system was stopped while 6098 // installd was in the middle of messing with its libs 6099 // directory. Ask installd to fix that. 6100 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6101 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6102 if (ret >= 0) { 6103 recovered = true; 6104 String msg = "Package " + pkg.packageName 6105 + " unexpectedly changed to uid 0; recovered to " + 6106 + pkg.applicationInfo.uid; 6107 reportSettingsProblem(Log.WARN, msg); 6108 } 6109 } 6110 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6111 || (scanFlags&SCAN_BOOTING) != 0)) { 6112 // If this is a system app, we can at least delete its 6113 // current data so the application will still work. 6114 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6115 if (ret >= 0) { 6116 // TODO: Kill the processes first 6117 // Old data gone! 6118 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6119 ? "System package " : "Third party package "; 6120 String msg = prefix + pkg.packageName 6121 + " has changed from uid: " 6122 + currentUid + " to " 6123 + pkg.applicationInfo.uid + "; old data erased"; 6124 reportSettingsProblem(Log.WARN, msg); 6125 recovered = true; 6126 6127 // And now re-install the app. 6128 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6129 pkg.applicationInfo.seinfo); 6130 if (ret == -1) { 6131 // Ack should not happen! 6132 msg = prefix + pkg.packageName 6133 + " could not have data directory re-created after delete."; 6134 reportSettingsProblem(Log.WARN, msg); 6135 throw new PackageManagerException( 6136 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6137 } 6138 } 6139 if (!recovered) { 6140 mHasSystemUidErrors = true; 6141 } 6142 } else if (!recovered) { 6143 // If we allow this install to proceed, we will be broken. 6144 // Abort, abort! 6145 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6146 "scanPackageLI"); 6147 } 6148 if (!recovered) { 6149 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6150 + pkg.applicationInfo.uid + "/fs_" 6151 + currentUid; 6152 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6153 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6154 String msg = "Package " + pkg.packageName 6155 + " has mismatched uid: " 6156 + currentUid + " on disk, " 6157 + pkg.applicationInfo.uid + " in settings"; 6158 // writer 6159 synchronized (mPackages) { 6160 mSettings.mReadMessages.append(msg); 6161 mSettings.mReadMessages.append('\n'); 6162 uidError = true; 6163 if (!pkgSetting.uidError) { 6164 reportSettingsProblem(Log.ERROR, msg); 6165 } 6166 } 6167 } 6168 } 6169 pkg.applicationInfo.dataDir = dataPath.getPath(); 6170 if (mShouldRestoreconData) { 6171 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6172 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6173 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6174 } 6175 } else { 6176 if (DEBUG_PACKAGE_SCANNING) { 6177 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6178 Log.v(TAG, "Want this data dir: " + dataPath); 6179 } 6180 //invoke installer to do the actual installation 6181 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6182 pkg.applicationInfo.seinfo); 6183 if (ret < 0) { 6184 // Error from installer 6185 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6186 "Unable to create data dirs [errorCode=" + ret + "]"); 6187 } 6188 6189 if (dataPath.exists()) { 6190 pkg.applicationInfo.dataDir = dataPath.getPath(); 6191 } else { 6192 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6193 pkg.applicationInfo.dataDir = null; 6194 } 6195 } 6196 6197 pkgSetting.uidError = uidError; 6198 } 6199 6200 final String path = scanFile.getPath(); 6201 final String codePath = pkg.applicationInfo.getCodePath(); 6202 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6203 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6204 setBundledAppAbisAndRoots(pkg, pkgSetting); 6205 6206 // If we haven't found any native libraries for the app, check if it has 6207 // renderscript code. We'll need to force the app to 32 bit if it has 6208 // renderscript bitcode. 6209 if (pkg.applicationInfo.primaryCpuAbi == null 6210 && pkg.applicationInfo.secondaryCpuAbi == null 6211 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6212 NativeLibraryHelper.Handle handle = null; 6213 try { 6214 handle = NativeLibraryHelper.Handle.create(scanFile); 6215 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6216 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6217 } 6218 } catch (IOException ioe) { 6219 Slog.w(TAG, "Error scanning system app : " + ioe); 6220 } finally { 6221 IoUtils.closeQuietly(handle); 6222 } 6223 } 6224 6225 setNativeLibraryPaths(pkg); 6226 } else { 6227 // TODO: We can probably be smarter about this stuff. For installed apps, 6228 // we can calculate this information at install time once and for all. For 6229 // system apps, we can probably assume that this information doesn't change 6230 // after the first boot scan. As things stand, we do lots of unnecessary work. 6231 6232 // Give ourselves some initial paths; we'll come back for another 6233 // pass once we've determined ABI below. 6234 setNativeLibraryPaths(pkg); 6235 6236 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6237 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6238 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6239 6240 NativeLibraryHelper.Handle handle = null; 6241 try { 6242 handle = NativeLibraryHelper.Handle.create(scanFile); 6243 // TODO(multiArch): This can be null for apps that didn't go through the 6244 // usual installation process. We can calculate it again, like we 6245 // do during install time. 6246 // 6247 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6248 // unnecessary. 6249 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6250 6251 // Null out the abis so that they can be recalculated. 6252 pkg.applicationInfo.primaryCpuAbi = null; 6253 pkg.applicationInfo.secondaryCpuAbi = null; 6254 if (isMultiArch(pkg.applicationInfo)) { 6255 // Warn if we've set an abiOverride for multi-lib packages.. 6256 // By definition, we need to copy both 32 and 64 bit libraries for 6257 // such packages. 6258 if (pkg.cpuAbiOverride != null 6259 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6260 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6261 } 6262 6263 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6264 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6265 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6266 if (isAsec) { 6267 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6268 } else { 6269 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6270 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6271 useIsaSpecificSubdirs); 6272 } 6273 } 6274 6275 maybeThrowExceptionForMultiArchCopy( 6276 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6277 6278 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6279 if (isAsec) { 6280 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6281 } else { 6282 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6283 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6284 useIsaSpecificSubdirs); 6285 } 6286 } 6287 6288 maybeThrowExceptionForMultiArchCopy( 6289 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6290 6291 if (abi64 >= 0) { 6292 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6293 } 6294 6295 if (abi32 >= 0) { 6296 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6297 if (abi64 >= 0) { 6298 pkg.applicationInfo.secondaryCpuAbi = abi; 6299 } else { 6300 pkg.applicationInfo.primaryCpuAbi = abi; 6301 } 6302 } 6303 } else { 6304 String[] abiList = (cpuAbiOverride != null) ? 6305 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6306 6307 // Enable gross and lame hacks for apps that are built with old 6308 // SDK tools. We must scan their APKs for renderscript bitcode and 6309 // not launch them if it's present. Don't bother checking on devices 6310 // that don't have 64 bit support. 6311 boolean needsRenderScriptOverride = false; 6312 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6313 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6314 abiList = Build.SUPPORTED_32_BIT_ABIS; 6315 needsRenderScriptOverride = true; 6316 } 6317 6318 final int copyRet; 6319 if (isAsec) { 6320 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6321 } else { 6322 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6323 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6324 } 6325 6326 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6327 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6328 "Error unpackaging native libs for app, errorCode=" + copyRet); 6329 } 6330 6331 if (copyRet >= 0) { 6332 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6333 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6334 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6335 } else if (needsRenderScriptOverride) { 6336 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6337 } 6338 } 6339 } catch (IOException ioe) { 6340 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6341 } finally { 6342 IoUtils.closeQuietly(handle); 6343 } 6344 6345 // Now that we've calculated the ABIs and determined if it's an internal app, 6346 // we will go ahead and populate the nativeLibraryPath. 6347 setNativeLibraryPaths(pkg); 6348 6349 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6350 final int[] userIds = sUserManager.getUserIds(); 6351 synchronized (mInstallLock) { 6352 // Create a native library symlink only if we have native libraries 6353 // and if the native libraries are 32 bit libraries. We do not provide 6354 // this symlink for 64 bit libraries. 6355 if (pkg.applicationInfo.primaryCpuAbi != null && 6356 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6357 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6358 for (int userId : userIds) { 6359 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6360 nativeLibPath, userId) < 0) { 6361 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6362 "Failed linking native library dir (user=" + userId + ")"); 6363 } 6364 } 6365 } 6366 } 6367 } 6368 6369 // This is a special case for the "system" package, where the ABI is 6370 // dictated by the zygote configuration (and init.rc). We should keep track 6371 // of this ABI so that we can deal with "normal" applications that run under 6372 // the same UID correctly. 6373 if (mPlatformPackage == pkg) { 6374 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6375 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6376 } 6377 6378 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6379 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6380 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6381 // Copy the derived override back to the parsed package, so that we can 6382 // update the package settings accordingly. 6383 pkg.cpuAbiOverride = cpuAbiOverride; 6384 6385 if (DEBUG_ABI_SELECTION) { 6386 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6387 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6388 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6389 } 6390 6391 // Push the derived path down into PackageSettings so we know what to 6392 // clean up at uninstall time. 6393 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6394 6395 if (DEBUG_ABI_SELECTION) { 6396 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6397 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6398 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6399 } 6400 6401 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6402 // We don't do this here during boot because we can do it all 6403 // at once after scanning all existing packages. 6404 // 6405 // We also do this *before* we perform dexopt on this package, so that 6406 // we can avoid redundant dexopts, and also to make sure we've got the 6407 // code and package path correct. 6408 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6409 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6410 } 6411 6412 if ((scanFlags & SCAN_NO_DEX) == 0) { 6413 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6414 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6415 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6416 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6417 } 6418 } 6419 if (mFactoryTest && pkg.requestedPermissions.contains( 6420 android.Manifest.permission.FACTORY_TEST)) { 6421 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6422 } 6423 6424 ArrayList<PackageParser.Package> clientLibPkgs = null; 6425 6426 // writer 6427 synchronized (mPackages) { 6428 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6429 // Only system apps can add new shared libraries. 6430 if (pkg.libraryNames != null) { 6431 for (int i=0; i<pkg.libraryNames.size(); i++) { 6432 String name = pkg.libraryNames.get(i); 6433 boolean allowed = false; 6434 if (pkg.isUpdatedSystemApp()) { 6435 // New library entries can only be added through the 6436 // system image. This is important to get rid of a lot 6437 // of nasty edge cases: for example if we allowed a non- 6438 // system update of the app to add a library, then uninstalling 6439 // the update would make the library go away, and assumptions 6440 // we made such as through app install filtering would now 6441 // have allowed apps on the device which aren't compatible 6442 // with it. Better to just have the restriction here, be 6443 // conservative, and create many fewer cases that can negatively 6444 // impact the user experience. 6445 final PackageSetting sysPs = mSettings 6446 .getDisabledSystemPkgLPr(pkg.packageName); 6447 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6448 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6449 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6450 allowed = true; 6451 allowed = true; 6452 break; 6453 } 6454 } 6455 } 6456 } else { 6457 allowed = true; 6458 } 6459 if (allowed) { 6460 if (!mSharedLibraries.containsKey(name)) { 6461 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6462 } else if (!name.equals(pkg.packageName)) { 6463 Slog.w(TAG, "Package " + pkg.packageName + " library " 6464 + name + " already exists; skipping"); 6465 } 6466 } else { 6467 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6468 + name + " that is not declared on system image; skipping"); 6469 } 6470 } 6471 if ((scanFlags&SCAN_BOOTING) == 0) { 6472 // If we are not booting, we need to update any applications 6473 // that are clients of our shared library. If we are booting, 6474 // this will all be done once the scan is complete. 6475 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6476 } 6477 } 6478 } 6479 } 6480 6481 // We also need to dexopt any apps that are dependent on this library. Note that 6482 // if these fail, we should abort the install since installing the library will 6483 // result in some apps being broken. 6484 if (clientLibPkgs != null) { 6485 if ((scanFlags & SCAN_NO_DEX) == 0) { 6486 for (int i = 0; i < clientLibPkgs.size(); i++) { 6487 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6488 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6489 null /* instruction sets */, forceDex, 6490 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6491 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6492 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6493 "scanPackageLI failed to dexopt clientLibPkgs"); 6494 } 6495 } 6496 } 6497 } 6498 6499 // Also need to kill any apps that are dependent on the library. 6500 if (clientLibPkgs != null) { 6501 for (int i=0; i<clientLibPkgs.size(); i++) { 6502 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6503 killApplication(clientPkg.applicationInfo.packageName, 6504 clientPkg.applicationInfo.uid, "update lib"); 6505 } 6506 } 6507 6508 // writer 6509 synchronized (mPackages) { 6510 // We don't expect installation to fail beyond this point 6511 6512 // Add the new setting to mSettings 6513 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6514 // Add the new setting to mPackages 6515 mPackages.put(pkg.applicationInfo.packageName, pkg); 6516 // Make sure we don't accidentally delete its data. 6517 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6518 while (iter.hasNext()) { 6519 PackageCleanItem item = iter.next(); 6520 if (pkgName.equals(item.packageName)) { 6521 iter.remove(); 6522 } 6523 } 6524 6525 // Take care of first install / last update times. 6526 if (currentTime != 0) { 6527 if (pkgSetting.firstInstallTime == 0) { 6528 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6529 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6530 pkgSetting.lastUpdateTime = currentTime; 6531 } 6532 } else if (pkgSetting.firstInstallTime == 0) { 6533 // We need *something*. Take time time stamp of the file. 6534 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6535 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6536 if (scanFileTime != pkgSetting.timeStamp) { 6537 // A package on the system image has changed; consider this 6538 // to be an update. 6539 pkgSetting.lastUpdateTime = scanFileTime; 6540 } 6541 } 6542 6543 // Add the package's KeySets to the global KeySetManagerService 6544 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6545 try { 6546 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6547 if (pkg.mKeySetMapping != null) { 6548 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6549 if (pkg.mUpgradeKeySets != null) { 6550 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6551 } 6552 } 6553 } catch (NullPointerException e) { 6554 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6555 } catch (IllegalArgumentException e) { 6556 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6557 } 6558 6559 int N = pkg.providers.size(); 6560 StringBuilder r = null; 6561 int i; 6562 for (i=0; i<N; i++) { 6563 PackageParser.Provider p = pkg.providers.get(i); 6564 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6565 p.info.processName, pkg.applicationInfo.uid); 6566 mProviders.addProvider(p); 6567 p.syncable = p.info.isSyncable; 6568 if (p.info.authority != null) { 6569 String names[] = p.info.authority.split(";"); 6570 p.info.authority = null; 6571 for (int j = 0; j < names.length; j++) { 6572 if (j == 1 && p.syncable) { 6573 // We only want the first authority for a provider to possibly be 6574 // syncable, so if we already added this provider using a different 6575 // authority clear the syncable flag. We copy the provider before 6576 // changing it because the mProviders object contains a reference 6577 // to a provider that we don't want to change. 6578 // Only do this for the second authority since the resulting provider 6579 // object can be the same for all future authorities for this provider. 6580 p = new PackageParser.Provider(p); 6581 p.syncable = false; 6582 } 6583 if (!mProvidersByAuthority.containsKey(names[j])) { 6584 mProvidersByAuthority.put(names[j], p); 6585 if (p.info.authority == null) { 6586 p.info.authority = names[j]; 6587 } else { 6588 p.info.authority = p.info.authority + ";" + names[j]; 6589 } 6590 if (DEBUG_PACKAGE_SCANNING) { 6591 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6592 Log.d(TAG, "Registered content provider: " + names[j] 6593 + ", className = " + p.info.name + ", isSyncable = " 6594 + p.info.isSyncable); 6595 } 6596 } else { 6597 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6598 Slog.w(TAG, "Skipping provider name " + names[j] + 6599 " (in package " + pkg.applicationInfo.packageName + 6600 "): name already used by " 6601 + ((other != null && other.getComponentName() != null) 6602 ? other.getComponentName().getPackageName() : "?")); 6603 } 6604 } 6605 } 6606 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6607 if (r == null) { 6608 r = new StringBuilder(256); 6609 } else { 6610 r.append(' '); 6611 } 6612 r.append(p.info.name); 6613 } 6614 } 6615 if (r != null) { 6616 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6617 } 6618 6619 N = pkg.services.size(); 6620 r = null; 6621 for (i=0; i<N; i++) { 6622 PackageParser.Service s = pkg.services.get(i); 6623 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6624 s.info.processName, pkg.applicationInfo.uid); 6625 mServices.addService(s); 6626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6627 if (r == null) { 6628 r = new StringBuilder(256); 6629 } else { 6630 r.append(' '); 6631 } 6632 r.append(s.info.name); 6633 } 6634 } 6635 if (r != null) { 6636 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6637 } 6638 6639 N = pkg.receivers.size(); 6640 r = null; 6641 for (i=0; i<N; i++) { 6642 PackageParser.Activity a = pkg.receivers.get(i); 6643 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6644 a.info.processName, pkg.applicationInfo.uid); 6645 mReceivers.addActivity(a, "receiver"); 6646 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6647 if (r == null) { 6648 r = new StringBuilder(256); 6649 } else { 6650 r.append(' '); 6651 } 6652 r.append(a.info.name); 6653 } 6654 } 6655 if (r != null) { 6656 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6657 } 6658 6659 N = pkg.activities.size(); 6660 r = null; 6661 for (i=0; i<N; i++) { 6662 PackageParser.Activity a = pkg.activities.get(i); 6663 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6664 a.info.processName, pkg.applicationInfo.uid); 6665 mActivities.addActivity(a, "activity"); 6666 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6667 if (r == null) { 6668 r = new StringBuilder(256); 6669 } else { 6670 r.append(' '); 6671 } 6672 r.append(a.info.name); 6673 } 6674 } 6675 if (r != null) { 6676 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6677 } 6678 6679 N = pkg.permissionGroups.size(); 6680 r = null; 6681 for (i=0; i<N; i++) { 6682 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6683 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6684 if (cur == null) { 6685 mPermissionGroups.put(pg.info.name, pg); 6686 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6687 if (r == null) { 6688 r = new StringBuilder(256); 6689 } else { 6690 r.append(' '); 6691 } 6692 r.append(pg.info.name); 6693 } 6694 } else { 6695 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6696 + pg.info.packageName + " ignored: original from " 6697 + cur.info.packageName); 6698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6699 if (r == null) { 6700 r = new StringBuilder(256); 6701 } else { 6702 r.append(' '); 6703 } 6704 r.append("DUP:"); 6705 r.append(pg.info.name); 6706 } 6707 } 6708 } 6709 if (r != null) { 6710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6711 } 6712 6713 N = pkg.permissions.size(); 6714 r = null; 6715 for (i=0; i<N; i++) { 6716 PackageParser.Permission p = pkg.permissions.get(i); 6717 6718 // Now that permission groups have a special meaning, we ignore permission 6719 // groups for legacy apps to prevent unexpected behavior. In particular, 6720 // permissions for one app being granted to someone just becuase they happen 6721 // to be in a group defined by another app (before this had no implications). 6722 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6723 p.group = mPermissionGroups.get(p.info.group); 6724 // Warn for a permission in an unknown group. 6725 if (p.info.group != null && p.group == null) { 6726 Slog.w(TAG, "Permission " + p.info.name + " from package " 6727 + p.info.packageName + " in an unknown group " + p.info.group); 6728 } 6729 } 6730 6731 ArrayMap<String, BasePermission> permissionMap = 6732 p.tree ? mSettings.mPermissionTrees 6733 : mSettings.mPermissions; 6734 BasePermission bp = permissionMap.get(p.info.name); 6735 6736 // Allow system apps to redefine non-system permissions 6737 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6738 final boolean currentOwnerIsSystem = (bp.perm != null 6739 && isSystemApp(bp.perm.owner)); 6740 if (isSystemApp(p.owner)) { 6741 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6742 // It's a built-in permission and no owner, take ownership now 6743 bp.packageSetting = pkgSetting; 6744 bp.perm = p; 6745 bp.uid = pkg.applicationInfo.uid; 6746 bp.sourcePackage = p.info.packageName; 6747 } else if (!currentOwnerIsSystem) { 6748 String msg = "New decl " + p.owner + " of permission " 6749 + p.info.name + " is system; overriding " + bp.sourcePackage; 6750 reportSettingsProblem(Log.WARN, msg); 6751 bp = null; 6752 } 6753 } 6754 } 6755 6756 if (bp == null) { 6757 bp = new BasePermission(p.info.name, p.info.packageName, 6758 BasePermission.TYPE_NORMAL); 6759 permissionMap.put(p.info.name, bp); 6760 } 6761 6762 if (bp.perm == null) { 6763 if (bp.sourcePackage == null 6764 || bp.sourcePackage.equals(p.info.packageName)) { 6765 BasePermission tree = findPermissionTreeLP(p.info.name); 6766 if (tree == null 6767 || tree.sourcePackage.equals(p.info.packageName)) { 6768 bp.packageSetting = pkgSetting; 6769 bp.perm = p; 6770 bp.uid = pkg.applicationInfo.uid; 6771 bp.sourcePackage = p.info.packageName; 6772 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6773 if (r == null) { 6774 r = new StringBuilder(256); 6775 } else { 6776 r.append(' '); 6777 } 6778 r.append(p.info.name); 6779 } 6780 } else { 6781 Slog.w(TAG, "Permission " + p.info.name + " from package " 6782 + p.info.packageName + " ignored: base tree " 6783 + tree.name + " is from package " 6784 + tree.sourcePackage); 6785 } 6786 } else { 6787 Slog.w(TAG, "Permission " + p.info.name + " from package " 6788 + p.info.packageName + " ignored: original from " 6789 + bp.sourcePackage); 6790 } 6791 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6792 if (r == null) { 6793 r = new StringBuilder(256); 6794 } else { 6795 r.append(' '); 6796 } 6797 r.append("DUP:"); 6798 r.append(p.info.name); 6799 } 6800 if (bp.perm == p) { 6801 bp.protectionLevel = p.info.protectionLevel; 6802 } 6803 } 6804 6805 if (r != null) { 6806 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6807 } 6808 6809 N = pkg.instrumentation.size(); 6810 r = null; 6811 for (i=0; i<N; i++) { 6812 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6813 a.info.packageName = pkg.applicationInfo.packageName; 6814 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6815 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6816 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6817 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6818 a.info.dataDir = pkg.applicationInfo.dataDir; 6819 6820 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6821 // need other information about the application, like the ABI and what not ? 6822 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6823 mInstrumentation.put(a.getComponentName(), a); 6824 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6825 if (r == null) { 6826 r = new StringBuilder(256); 6827 } else { 6828 r.append(' '); 6829 } 6830 r.append(a.info.name); 6831 } 6832 } 6833 if (r != null) { 6834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6835 } 6836 6837 if (pkg.protectedBroadcasts != null) { 6838 N = pkg.protectedBroadcasts.size(); 6839 for (i=0; i<N; i++) { 6840 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6841 } 6842 } 6843 6844 pkgSetting.setTimeStamp(scanFileTime); 6845 6846 // Create idmap files for pairs of (packages, overlay packages). 6847 // Note: "android", ie framework-res.apk, is handled by native layers. 6848 if (pkg.mOverlayTarget != null) { 6849 // This is an overlay package. 6850 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6851 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6852 mOverlays.put(pkg.mOverlayTarget, 6853 new ArrayMap<String, PackageParser.Package>()); 6854 } 6855 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6856 map.put(pkg.packageName, pkg); 6857 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6858 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6859 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6860 "scanPackageLI failed to createIdmap"); 6861 } 6862 } 6863 } else if (mOverlays.containsKey(pkg.packageName) && 6864 !pkg.packageName.equals("android")) { 6865 // This is a regular package, with one or more known overlay packages. 6866 createIdmapsForPackageLI(pkg); 6867 } 6868 } 6869 6870 return pkg; 6871 } 6872 6873 /** 6874 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6875 * i.e, so that all packages can be run inside a single process if required. 6876 * 6877 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6878 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6879 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6880 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6881 * updating a package that belongs to a shared user. 6882 * 6883 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6884 * adds unnecessary complexity. 6885 */ 6886 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6887 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6888 String requiredInstructionSet = null; 6889 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6890 requiredInstructionSet = VMRuntime.getInstructionSet( 6891 scannedPackage.applicationInfo.primaryCpuAbi); 6892 } 6893 6894 PackageSetting requirer = null; 6895 for (PackageSetting ps : packagesForUser) { 6896 // If packagesForUser contains scannedPackage, we skip it. This will happen 6897 // when scannedPackage is an update of an existing package. Without this check, 6898 // we will never be able to change the ABI of any package belonging to a shared 6899 // user, even if it's compatible with other packages. 6900 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6901 if (ps.primaryCpuAbiString == null) { 6902 continue; 6903 } 6904 6905 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6906 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6907 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6908 // this but there's not much we can do. 6909 String errorMessage = "Instruction set mismatch, " 6910 + ((requirer == null) ? "[caller]" : requirer) 6911 + " requires " + requiredInstructionSet + " whereas " + ps 6912 + " requires " + instructionSet; 6913 Slog.w(TAG, errorMessage); 6914 } 6915 6916 if (requiredInstructionSet == null) { 6917 requiredInstructionSet = instructionSet; 6918 requirer = ps; 6919 } 6920 } 6921 } 6922 6923 if (requiredInstructionSet != null) { 6924 String adjustedAbi; 6925 if (requirer != null) { 6926 // requirer != null implies that either scannedPackage was null or that scannedPackage 6927 // did not require an ABI, in which case we have to adjust scannedPackage to match 6928 // the ABI of the set (which is the same as requirer's ABI) 6929 adjustedAbi = requirer.primaryCpuAbiString; 6930 if (scannedPackage != null) { 6931 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6932 } 6933 } else { 6934 // requirer == null implies that we're updating all ABIs in the set to 6935 // match scannedPackage. 6936 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6937 } 6938 6939 for (PackageSetting ps : packagesForUser) { 6940 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6941 if (ps.primaryCpuAbiString != null) { 6942 continue; 6943 } 6944 6945 ps.primaryCpuAbiString = adjustedAbi; 6946 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6947 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6948 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6949 6950 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6951 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6952 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6953 ps.primaryCpuAbiString = null; 6954 ps.pkg.applicationInfo.primaryCpuAbi = null; 6955 return; 6956 } else { 6957 mInstaller.rmdex(ps.codePathString, 6958 getDexCodeInstructionSet(getPreferredInstructionSet())); 6959 } 6960 } 6961 } 6962 } 6963 } 6964 } 6965 6966 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6967 synchronized (mPackages) { 6968 mResolverReplaced = true; 6969 // Set up information for custom user intent resolution activity. 6970 mResolveActivity.applicationInfo = pkg.applicationInfo; 6971 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6972 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6973 mResolveActivity.processName = pkg.applicationInfo.packageName; 6974 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6975 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6976 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6977 mResolveActivity.theme = 0; 6978 mResolveActivity.exported = true; 6979 mResolveActivity.enabled = true; 6980 mResolveInfo.activityInfo = mResolveActivity; 6981 mResolveInfo.priority = 0; 6982 mResolveInfo.preferredOrder = 0; 6983 mResolveInfo.match = 0; 6984 mResolveComponentName = mCustomResolverComponentName; 6985 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6986 mResolveComponentName); 6987 } 6988 } 6989 6990 private static String calculateBundledApkRoot(final String codePathString) { 6991 final File codePath = new File(codePathString); 6992 final File codeRoot; 6993 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6994 codeRoot = Environment.getRootDirectory(); 6995 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6996 codeRoot = Environment.getOemDirectory(); 6997 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6998 codeRoot = Environment.getVendorDirectory(); 6999 } else { 7000 // Unrecognized code path; take its top real segment as the apk root: 7001 // e.g. /something/app/blah.apk => /something 7002 try { 7003 File f = codePath.getCanonicalFile(); 7004 File parent = f.getParentFile(); // non-null because codePath is a file 7005 File tmp; 7006 while ((tmp = parent.getParentFile()) != null) { 7007 f = parent; 7008 parent = tmp; 7009 } 7010 codeRoot = f; 7011 Slog.w(TAG, "Unrecognized code path " 7012 + codePath + " - using " + codeRoot); 7013 } catch (IOException e) { 7014 // Can't canonicalize the code path -- shenanigans? 7015 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7016 return Environment.getRootDirectory().getPath(); 7017 } 7018 } 7019 return codeRoot.getPath(); 7020 } 7021 7022 /** 7023 * Derive and set the location of native libraries for the given package, 7024 * which varies depending on where and how the package was installed. 7025 */ 7026 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7027 final ApplicationInfo info = pkg.applicationInfo; 7028 final String codePath = pkg.codePath; 7029 final File codeFile = new File(codePath); 7030 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7031 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7032 7033 info.nativeLibraryRootDir = null; 7034 info.nativeLibraryRootRequiresIsa = false; 7035 info.nativeLibraryDir = null; 7036 info.secondaryNativeLibraryDir = null; 7037 7038 if (isApkFile(codeFile)) { 7039 // Monolithic install 7040 if (bundledApp) { 7041 // If "/system/lib64/apkname" exists, assume that is the per-package 7042 // native library directory to use; otherwise use "/system/lib/apkname". 7043 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7044 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7045 getPrimaryInstructionSet(info)); 7046 7047 // This is a bundled system app so choose the path based on the ABI. 7048 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7049 // is just the default path. 7050 final String apkName = deriveCodePathName(codePath); 7051 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7052 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7053 apkName).getAbsolutePath(); 7054 7055 if (info.secondaryCpuAbi != null) { 7056 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7057 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7058 secondaryLibDir, apkName).getAbsolutePath(); 7059 } 7060 } else if (asecApp) { 7061 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7062 .getAbsolutePath(); 7063 } else { 7064 final String apkName = deriveCodePathName(codePath); 7065 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7066 .getAbsolutePath(); 7067 } 7068 7069 info.nativeLibraryRootRequiresIsa = false; 7070 info.nativeLibraryDir = info.nativeLibraryRootDir; 7071 } else { 7072 // Cluster install 7073 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7074 info.nativeLibraryRootRequiresIsa = true; 7075 7076 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7077 getPrimaryInstructionSet(info)).getAbsolutePath(); 7078 7079 if (info.secondaryCpuAbi != null) { 7080 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7081 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7082 } 7083 } 7084 } 7085 7086 /** 7087 * Calculate the abis and roots for a bundled app. These can uniquely 7088 * be determined from the contents of the system partition, i.e whether 7089 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7090 * of this information, and instead assume that the system was built 7091 * sensibly. 7092 */ 7093 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7094 PackageSetting pkgSetting) { 7095 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7096 7097 // If "/system/lib64/apkname" exists, assume that is the per-package 7098 // native library directory to use; otherwise use "/system/lib/apkname". 7099 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7100 setBundledAppAbi(pkg, apkRoot, apkName); 7101 // pkgSetting might be null during rescan following uninstall of updates 7102 // to a bundled app, so accommodate that possibility. The settings in 7103 // that case will be established later from the parsed package. 7104 // 7105 // If the settings aren't null, sync them up with what we've just derived. 7106 // note that apkRoot isn't stored in the package settings. 7107 if (pkgSetting != null) { 7108 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7109 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7110 } 7111 } 7112 7113 /** 7114 * Deduces the ABI of a bundled app and sets the relevant fields on the 7115 * parsed pkg object. 7116 * 7117 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7118 * under which system libraries are installed. 7119 * @param apkName the name of the installed package. 7120 */ 7121 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7122 final File codeFile = new File(pkg.codePath); 7123 7124 final boolean has64BitLibs; 7125 final boolean has32BitLibs; 7126 if (isApkFile(codeFile)) { 7127 // Monolithic install 7128 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7129 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7130 } else { 7131 // Cluster install 7132 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7133 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7134 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7135 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7136 has64BitLibs = (new File(rootDir, isa)).exists(); 7137 } else { 7138 has64BitLibs = false; 7139 } 7140 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7141 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7142 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7143 has32BitLibs = (new File(rootDir, isa)).exists(); 7144 } else { 7145 has32BitLibs = false; 7146 } 7147 } 7148 7149 if (has64BitLibs && !has32BitLibs) { 7150 // The package has 64 bit libs, but not 32 bit libs. Its primary 7151 // ABI should be 64 bit. We can safely assume here that the bundled 7152 // native libraries correspond to the most preferred ABI in the list. 7153 7154 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7155 pkg.applicationInfo.secondaryCpuAbi = null; 7156 } else if (has32BitLibs && !has64BitLibs) { 7157 // The package has 32 bit libs but not 64 bit libs. Its primary 7158 // ABI should be 32 bit. 7159 7160 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7161 pkg.applicationInfo.secondaryCpuAbi = null; 7162 } else if (has32BitLibs && has64BitLibs) { 7163 // The application has both 64 and 32 bit bundled libraries. We check 7164 // here that the app declares multiArch support, and warn if it doesn't. 7165 // 7166 // We will be lenient here and record both ABIs. The primary will be the 7167 // ABI that's higher on the list, i.e, a device that's configured to prefer 7168 // 64 bit apps will see a 64 bit primary ABI, 7169 7170 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7171 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7172 } 7173 7174 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7175 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7176 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7177 } else { 7178 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7179 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7180 } 7181 } else { 7182 pkg.applicationInfo.primaryCpuAbi = null; 7183 pkg.applicationInfo.secondaryCpuAbi = null; 7184 } 7185 } 7186 7187 private void killApplication(String pkgName, int appId, String reason) { 7188 // Request the ActivityManager to kill the process(only for existing packages) 7189 // so that we do not end up in a confused state while the user is still using the older 7190 // version of the application while the new one gets installed. 7191 IActivityManager am = ActivityManagerNative.getDefault(); 7192 if (am != null) { 7193 try { 7194 am.killApplicationWithAppId(pkgName, appId, reason); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 } 7199 7200 void removePackageLI(PackageSetting ps, boolean chatty) { 7201 if (DEBUG_INSTALL) { 7202 if (chatty) 7203 Log.d(TAG, "Removing package " + ps.name); 7204 } 7205 7206 // writer 7207 synchronized (mPackages) { 7208 mPackages.remove(ps.name); 7209 final PackageParser.Package pkg = ps.pkg; 7210 if (pkg != null) { 7211 cleanPackageDataStructuresLILPw(pkg, chatty); 7212 } 7213 } 7214 } 7215 7216 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7217 if (DEBUG_INSTALL) { 7218 if (chatty) 7219 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7220 } 7221 7222 // writer 7223 synchronized (mPackages) { 7224 mPackages.remove(pkg.applicationInfo.packageName); 7225 cleanPackageDataStructuresLILPw(pkg, chatty); 7226 } 7227 } 7228 7229 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7230 int N = pkg.providers.size(); 7231 StringBuilder r = null; 7232 int i; 7233 for (i=0; i<N; i++) { 7234 PackageParser.Provider p = pkg.providers.get(i); 7235 mProviders.removeProvider(p); 7236 if (p.info.authority == null) { 7237 7238 /* There was another ContentProvider with this authority when 7239 * this app was installed so this authority is null, 7240 * Ignore it as we don't have to unregister the provider. 7241 */ 7242 continue; 7243 } 7244 String names[] = p.info.authority.split(";"); 7245 for (int j = 0; j < names.length; j++) { 7246 if (mProvidersByAuthority.get(names[j]) == p) { 7247 mProvidersByAuthority.remove(names[j]); 7248 if (DEBUG_REMOVE) { 7249 if (chatty) 7250 Log.d(TAG, "Unregistered content provider: " + names[j] 7251 + ", className = " + p.info.name + ", isSyncable = " 7252 + p.info.isSyncable); 7253 } 7254 } 7255 } 7256 if (DEBUG_REMOVE && chatty) { 7257 if (r == null) { 7258 r = new StringBuilder(256); 7259 } else { 7260 r.append(' '); 7261 } 7262 r.append(p.info.name); 7263 } 7264 } 7265 if (r != null) { 7266 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7267 } 7268 7269 N = pkg.services.size(); 7270 r = null; 7271 for (i=0; i<N; i++) { 7272 PackageParser.Service s = pkg.services.get(i); 7273 mServices.removeService(s); 7274 if (chatty) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(s.info.name); 7281 } 7282 } 7283 if (r != null) { 7284 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7285 } 7286 7287 N = pkg.receivers.size(); 7288 r = null; 7289 for (i=0; i<N; i++) { 7290 PackageParser.Activity a = pkg.receivers.get(i); 7291 mReceivers.removeActivity(a, "receiver"); 7292 if (DEBUG_REMOVE && chatty) { 7293 if (r == null) { 7294 r = new StringBuilder(256); 7295 } else { 7296 r.append(' '); 7297 } 7298 r.append(a.info.name); 7299 } 7300 } 7301 if (r != null) { 7302 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7303 } 7304 7305 N = pkg.activities.size(); 7306 r = null; 7307 for (i=0; i<N; i++) { 7308 PackageParser.Activity a = pkg.activities.get(i); 7309 mActivities.removeActivity(a, "activity"); 7310 if (DEBUG_REMOVE && chatty) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append(a.info.name); 7317 } 7318 } 7319 if (r != null) { 7320 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7321 } 7322 7323 N = pkg.permissions.size(); 7324 r = null; 7325 for (i=0; i<N; i++) { 7326 PackageParser.Permission p = pkg.permissions.get(i); 7327 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7328 if (bp == null) { 7329 bp = mSettings.mPermissionTrees.get(p.info.name); 7330 } 7331 if (bp != null && bp.perm == p) { 7332 bp.perm = null; 7333 if (DEBUG_REMOVE && chatty) { 7334 if (r == null) { 7335 r = new StringBuilder(256); 7336 } else { 7337 r.append(' '); 7338 } 7339 r.append(p.info.name); 7340 } 7341 } 7342 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7343 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7344 if (appOpPerms != null) { 7345 appOpPerms.remove(pkg.packageName); 7346 } 7347 } 7348 } 7349 if (r != null) { 7350 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7351 } 7352 7353 N = pkg.requestedPermissions.size(); 7354 r = null; 7355 for (i=0; i<N; i++) { 7356 String perm = pkg.requestedPermissions.get(i); 7357 BasePermission bp = mSettings.mPermissions.get(perm); 7358 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7359 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7360 if (appOpPerms != null) { 7361 appOpPerms.remove(pkg.packageName); 7362 if (appOpPerms.isEmpty()) { 7363 mAppOpPermissionPackages.remove(perm); 7364 } 7365 } 7366 } 7367 } 7368 if (r != null) { 7369 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7370 } 7371 7372 N = pkg.instrumentation.size(); 7373 r = null; 7374 for (i=0; i<N; i++) { 7375 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7376 mInstrumentation.remove(a.getComponentName()); 7377 if (DEBUG_REMOVE && chatty) { 7378 if (r == null) { 7379 r = new StringBuilder(256); 7380 } else { 7381 r.append(' '); 7382 } 7383 r.append(a.info.name); 7384 } 7385 } 7386 if (r != null) { 7387 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7388 } 7389 7390 r = null; 7391 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7392 // Only system apps can hold shared libraries. 7393 if (pkg.libraryNames != null) { 7394 for (i=0; i<pkg.libraryNames.size(); i++) { 7395 String name = pkg.libraryNames.get(i); 7396 SharedLibraryEntry cur = mSharedLibraries.get(name); 7397 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7398 mSharedLibraries.remove(name); 7399 if (DEBUG_REMOVE && chatty) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append(name); 7406 } 7407 } 7408 } 7409 } 7410 } 7411 if (r != null) { 7412 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7413 } 7414 } 7415 7416 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7417 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7418 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7419 return true; 7420 } 7421 } 7422 return false; 7423 } 7424 7425 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7426 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7427 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7428 7429 private void updatePermissionsLPw(String changingPkg, 7430 PackageParser.Package pkgInfo, int flags) { 7431 // Make sure there are no dangling permission trees. 7432 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7433 while (it.hasNext()) { 7434 final BasePermission bp = it.next(); 7435 if (bp.packageSetting == null) { 7436 // We may not yet have parsed the package, so just see if 7437 // we still know about its settings. 7438 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7439 } 7440 if (bp.packageSetting == null) { 7441 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7442 + " from package " + bp.sourcePackage); 7443 it.remove(); 7444 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7445 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7446 Slog.i(TAG, "Removing old permission tree: " + bp.name 7447 + " from package " + bp.sourcePackage); 7448 flags |= UPDATE_PERMISSIONS_ALL; 7449 it.remove(); 7450 } 7451 } 7452 } 7453 7454 // Make sure all dynamic permissions have been assigned to a package, 7455 // and make sure there are no dangling permissions. 7456 it = mSettings.mPermissions.values().iterator(); 7457 while (it.hasNext()) { 7458 final BasePermission bp = it.next(); 7459 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7460 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7461 + bp.name + " pkg=" + bp.sourcePackage 7462 + " info=" + bp.pendingInfo); 7463 if (bp.packageSetting == null && bp.pendingInfo != null) { 7464 final BasePermission tree = findPermissionTreeLP(bp.name); 7465 if (tree != null && tree.perm != null) { 7466 bp.packageSetting = tree.packageSetting; 7467 bp.perm = new PackageParser.Permission(tree.perm.owner, 7468 new PermissionInfo(bp.pendingInfo)); 7469 bp.perm.info.packageName = tree.perm.info.packageName; 7470 bp.perm.info.name = bp.name; 7471 bp.uid = tree.uid; 7472 } 7473 } 7474 } 7475 if (bp.packageSetting == null) { 7476 // We may not yet have parsed the package, so just see if 7477 // we still know about its settings. 7478 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7479 } 7480 if (bp.packageSetting == null) { 7481 Slog.w(TAG, "Removing dangling permission: " + bp.name 7482 + " from package " + bp.sourcePackage); 7483 it.remove(); 7484 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7485 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7486 Slog.i(TAG, "Removing old permission: " + bp.name 7487 + " from package " + bp.sourcePackage); 7488 flags |= UPDATE_PERMISSIONS_ALL; 7489 it.remove(); 7490 } 7491 } 7492 } 7493 7494 // Now update the permissions for all packages, in particular 7495 // replace the granted permissions of the system packages. 7496 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7497 for (PackageParser.Package pkg : mPackages.values()) { 7498 if (pkg != pkgInfo) { 7499 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7500 changingPkg); 7501 } 7502 } 7503 } 7504 7505 if (pkgInfo != null) { 7506 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7507 } 7508 } 7509 7510 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7511 String packageOfInterest) { 7512 // IMPORTANT: There are two types of permissions: install and runtime. 7513 // Install time permissions are granted when the app is installed to 7514 // all device users and users added in the future. Runtime permissions 7515 // are granted at runtime explicitly to specific users. Normal and signature 7516 // protected permissions are install time permissions. Dangerous permissions 7517 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7518 // otherwise they are runtime permissions. This function does not manage 7519 // runtime permissions except for the case an app targeting Lollipop MR1 7520 // being upgraded to target a newer SDK, in which case dangerous permissions 7521 // are transformed from install time to runtime ones. 7522 7523 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7524 if (ps == null) { 7525 return; 7526 } 7527 7528 PermissionsState permissionsState = ps.getPermissionsState(); 7529 PermissionsState origPermissions = permissionsState; 7530 7531 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7532 7533 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7534 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7535 7536 boolean changedInstallPermission = false; 7537 7538 if (replace) { 7539 ps.installPermissionsFixed = false; 7540 if (!ps.isSharedUser()) { 7541 origPermissions = new PermissionsState(permissionsState); 7542 permissionsState.reset(); 7543 } 7544 } 7545 7546 permissionsState.setGlobalGids(mGlobalGids); 7547 7548 final int N = pkg.requestedPermissions.size(); 7549 for (int i=0; i<N; i++) { 7550 final String name = pkg.requestedPermissions.get(i); 7551 final BasePermission bp = mSettings.mPermissions.get(name); 7552 7553 if (DEBUG_INSTALL) { 7554 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7555 } 7556 7557 if (bp == null || bp.packageSetting == null) { 7558 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7559 Slog.w(TAG, "Unknown permission " + name 7560 + " in package " + pkg.packageName); 7561 } 7562 continue; 7563 } 7564 7565 final String perm = bp.name; 7566 boolean allowedSig = false; 7567 int grant = GRANT_DENIED; 7568 7569 // Keep track of app op permissions. 7570 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7571 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7572 if (pkgs == null) { 7573 pkgs = new ArraySet<>(); 7574 mAppOpPermissionPackages.put(bp.name, pkgs); 7575 } 7576 pkgs.add(pkg.packageName); 7577 } 7578 7579 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7580 switch (level) { 7581 case PermissionInfo.PROTECTION_NORMAL: { 7582 // For all apps normal permissions are install time ones. 7583 grant = GRANT_INSTALL; 7584 } break; 7585 7586 case PermissionInfo.PROTECTION_DANGEROUS: { 7587 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7588 // For legacy apps dangerous permissions are install time ones. 7589 grant = GRANT_INSTALL; 7590 } else if (ps.isSystem()) { 7591 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7592 if (origPermissions.hasInstallPermission(bp.name)) { 7593 // If a system app had an install permission, then the app was 7594 // upgraded and we grant the permissions as runtime to all users. 7595 grant = GRANT_UPGRADE; 7596 upgradeUserIds = currentUserIds; 7597 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7598 // If users changed since the last permissions update for a 7599 // system app, we grant the permission as runtime to the new users. 7600 grant = GRANT_UPGRADE; 7601 upgradeUserIds = currentUserIds; 7602 for (int userId : updatedUserIds) { 7603 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7604 } 7605 } else { 7606 // Otherwise, we grant the permission as runtime if the app 7607 // already had it, i.e. we preserve runtime permissions. 7608 grant = GRANT_RUNTIME; 7609 } 7610 } else if (origPermissions.hasInstallPermission(bp.name)) { 7611 // For legacy apps that became modern, install becomes runtime. 7612 grant = GRANT_UPGRADE; 7613 upgradeUserIds = currentUserIds; 7614 } else if (replace) { 7615 // For upgraded modern apps keep runtime permissions unchanged. 7616 grant = GRANT_RUNTIME; 7617 } 7618 } break; 7619 7620 case PermissionInfo.PROTECTION_SIGNATURE: { 7621 // For all apps signature permissions are install time ones. 7622 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7623 if (allowedSig) { 7624 grant = GRANT_INSTALL; 7625 } 7626 } break; 7627 } 7628 7629 if (DEBUG_INSTALL) { 7630 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7631 } 7632 7633 if (grant != GRANT_DENIED) { 7634 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7635 // If this is an existing, non-system package, then 7636 // we can't add any new permissions to it. 7637 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7638 // Except... if this is a permission that was added 7639 // to the platform (note: need to only do this when 7640 // updating the platform). 7641 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7642 grant = GRANT_DENIED; 7643 } 7644 } 7645 } 7646 7647 switch (grant) { 7648 case GRANT_INSTALL: { 7649 // Grant an install permission. 7650 if (permissionsState.grantInstallPermission(bp) != 7651 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7652 changedInstallPermission = true; 7653 } 7654 } break; 7655 7656 case GRANT_RUNTIME: { 7657 // Grant previously granted runtime permissions. 7658 for (int userId : UserManagerService.getInstance().getUserIds()) { 7659 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7660 if (permissionsState.grantRuntimePermission(bp, userId) == 7661 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7662 // If we cannot put the permission as it was, we have to write. 7663 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7664 changedRuntimePermissionUserIds, userId); 7665 } 7666 } 7667 } 7668 } break; 7669 7670 case GRANT_UPGRADE: { 7671 // Grant runtime permissions for a previously held install permission. 7672 permissionsState.revokeInstallPermission(bp); 7673 for (int userId : upgradeUserIds) { 7674 if (permissionsState.grantRuntimePermission(bp, userId) != 7675 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7676 // If we granted the permission, we have to write. 7677 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7678 changedRuntimePermissionUserIds, userId); 7679 } 7680 } 7681 } break; 7682 7683 default: { 7684 if (packageOfInterest == null 7685 || packageOfInterest.equals(pkg.packageName)) { 7686 Slog.w(TAG, "Not granting permission " + perm 7687 + " to package " + pkg.packageName 7688 + " because it was previously installed without"); 7689 } 7690 } break; 7691 } 7692 } else { 7693 if (permissionsState.revokeInstallPermission(bp) != 7694 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7695 changedInstallPermission = true; 7696 Slog.i(TAG, "Un-granting permission " + perm 7697 + " from package " + pkg.packageName 7698 + " (protectionLevel=" + bp.protectionLevel 7699 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7700 + ")"); 7701 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7702 // Don't print warning for app op permissions, since it is fine for them 7703 // not to be granted, there is a UI for the user to decide. 7704 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7705 Slog.w(TAG, "Not granting permission " + perm 7706 + " to package " + pkg.packageName 7707 + " (protectionLevel=" + bp.protectionLevel 7708 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7709 + ")"); 7710 } 7711 } 7712 } 7713 } 7714 7715 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7716 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7717 // This is the first that we have heard about this package, so the 7718 // permissions we have now selected are fixed until explicitly 7719 // changed. 7720 ps.installPermissionsFixed = true; 7721 } 7722 7723 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7724 7725 // Persist the runtime permissions state for users with changes. 7726 for (int userId : changedRuntimePermissionUserIds) { 7727 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7728 } 7729 } 7730 7731 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7732 boolean allowed = false; 7733 final int NP = PackageParser.NEW_PERMISSIONS.length; 7734 for (int ip=0; ip<NP; ip++) { 7735 final PackageParser.NewPermissionInfo npi 7736 = PackageParser.NEW_PERMISSIONS[ip]; 7737 if (npi.name.equals(perm) 7738 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7739 allowed = true; 7740 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7741 + pkg.packageName); 7742 break; 7743 } 7744 } 7745 return allowed; 7746 } 7747 7748 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7749 BasePermission bp, PermissionsState origPermissions) { 7750 boolean allowed; 7751 allowed = (compareSignatures( 7752 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7753 == PackageManager.SIGNATURE_MATCH) 7754 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7755 == PackageManager.SIGNATURE_MATCH); 7756 if (!allowed && (bp.protectionLevel 7757 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7758 if (isSystemApp(pkg)) { 7759 // For updated system applications, a system permission 7760 // is granted only if it had been defined by the original application. 7761 if (pkg.isUpdatedSystemApp()) { 7762 final PackageSetting sysPs = mSettings 7763 .getDisabledSystemPkgLPr(pkg.packageName); 7764 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7765 // If the original was granted this permission, we take 7766 // that grant decision as read and propagate it to the 7767 // update. 7768 if (sysPs.isPrivileged()) { 7769 allowed = true; 7770 } 7771 } else { 7772 // The system apk may have been updated with an older 7773 // version of the one on the data partition, but which 7774 // granted a new system permission that it didn't have 7775 // before. In this case we do want to allow the app to 7776 // now get the new permission if the ancestral apk is 7777 // privileged to get it. 7778 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7779 for (int j=0; 7780 j<sysPs.pkg.requestedPermissions.size(); j++) { 7781 if (perm.equals( 7782 sysPs.pkg.requestedPermissions.get(j))) { 7783 allowed = true; 7784 break; 7785 } 7786 } 7787 } 7788 } 7789 } else { 7790 allowed = isPrivilegedApp(pkg); 7791 } 7792 } 7793 } 7794 if (!allowed && (bp.protectionLevel 7795 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7796 // For development permissions, a development permission 7797 // is granted only if it was already granted. 7798 allowed = origPermissions.hasInstallPermission(perm); 7799 } 7800 return allowed; 7801 } 7802 7803 final class ActivityIntentResolver 7804 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7806 boolean defaultOnly, int userId) { 7807 if (!sUserManager.exists(userId)) return null; 7808 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7809 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7810 } 7811 7812 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7813 int userId) { 7814 if (!sUserManager.exists(userId)) return null; 7815 mFlags = flags; 7816 return super.queryIntent(intent, resolvedType, 7817 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7818 } 7819 7820 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7821 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7822 if (!sUserManager.exists(userId)) return null; 7823 if (packageActivities == null) { 7824 return null; 7825 } 7826 mFlags = flags; 7827 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7828 final int N = packageActivities.size(); 7829 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7830 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7831 7832 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7833 for (int i = 0; i < N; ++i) { 7834 intentFilters = packageActivities.get(i).intents; 7835 if (intentFilters != null && intentFilters.size() > 0) { 7836 PackageParser.ActivityIntentInfo[] array = 7837 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7838 intentFilters.toArray(array); 7839 listCut.add(array); 7840 } 7841 } 7842 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7843 } 7844 7845 public final void addActivity(PackageParser.Activity a, String type) { 7846 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7847 mActivities.put(a.getComponentName(), a); 7848 if (DEBUG_SHOW_INFO) 7849 Log.v( 7850 TAG, " " + type + " " + 7851 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7852 if (DEBUG_SHOW_INFO) 7853 Log.v(TAG, " Class=" + a.info.name); 7854 final int NI = a.intents.size(); 7855 for (int j=0; j<NI; j++) { 7856 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7857 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7858 intent.setPriority(0); 7859 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7860 + a.className + " with priority > 0, forcing to 0"); 7861 } 7862 if (DEBUG_SHOW_INFO) { 7863 Log.v(TAG, " IntentFilter:"); 7864 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7865 } 7866 if (!intent.debugCheck()) { 7867 Log.w(TAG, "==> For Activity " + a.info.name); 7868 } 7869 addFilter(intent); 7870 } 7871 } 7872 7873 public final void removeActivity(PackageParser.Activity a, String type) { 7874 mActivities.remove(a.getComponentName()); 7875 if (DEBUG_SHOW_INFO) { 7876 Log.v(TAG, " " + type + " " 7877 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7878 : a.info.name) + ":"); 7879 Log.v(TAG, " Class=" + a.info.name); 7880 } 7881 final int NI = a.intents.size(); 7882 for (int j=0; j<NI; j++) { 7883 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7884 if (DEBUG_SHOW_INFO) { 7885 Log.v(TAG, " IntentFilter:"); 7886 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7887 } 7888 removeFilter(intent); 7889 } 7890 } 7891 7892 @Override 7893 protected boolean allowFilterResult( 7894 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7895 ActivityInfo filterAi = filter.activity.info; 7896 for (int i=dest.size()-1; i>=0; i--) { 7897 ActivityInfo destAi = dest.get(i).activityInfo; 7898 if (destAi.name == filterAi.name 7899 && destAi.packageName == filterAi.packageName) { 7900 return false; 7901 } 7902 } 7903 return true; 7904 } 7905 7906 @Override 7907 protected ActivityIntentInfo[] newArray(int size) { 7908 return new ActivityIntentInfo[size]; 7909 } 7910 7911 @Override 7912 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7913 if (!sUserManager.exists(userId)) return true; 7914 PackageParser.Package p = filter.activity.owner; 7915 if (p != null) { 7916 PackageSetting ps = (PackageSetting)p.mExtras; 7917 if (ps != null) { 7918 // System apps are never considered stopped for purposes of 7919 // filtering, because there may be no way for the user to 7920 // actually re-launch them. 7921 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7922 && ps.getStopped(userId); 7923 } 7924 } 7925 return false; 7926 } 7927 7928 @Override 7929 protected boolean isPackageForFilter(String packageName, 7930 PackageParser.ActivityIntentInfo info) { 7931 return packageName.equals(info.activity.owner.packageName); 7932 } 7933 7934 @Override 7935 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7936 int match, int userId) { 7937 if (!sUserManager.exists(userId)) return null; 7938 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7939 return null; 7940 } 7941 final PackageParser.Activity activity = info.activity; 7942 if (mSafeMode && (activity.info.applicationInfo.flags 7943 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7944 return null; 7945 } 7946 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7947 if (ps == null) { 7948 return null; 7949 } 7950 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7951 ps.readUserState(userId), userId); 7952 if (ai == null) { 7953 return null; 7954 } 7955 final ResolveInfo res = new ResolveInfo(); 7956 res.activityInfo = ai; 7957 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7958 res.filter = info; 7959 } 7960 if (info != null) { 7961 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7962 } 7963 res.priority = info.getPriority(); 7964 res.preferredOrder = activity.owner.mPreferredOrder; 7965 //System.out.println("Result: " + res.activityInfo.className + 7966 // " = " + res.priority); 7967 res.match = match; 7968 res.isDefault = info.hasDefault; 7969 res.labelRes = info.labelRes; 7970 res.nonLocalizedLabel = info.nonLocalizedLabel; 7971 if (userNeedsBadging(userId)) { 7972 res.noResourceId = true; 7973 } else { 7974 res.icon = info.icon; 7975 } 7976 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7977 return res; 7978 } 7979 7980 @Override 7981 protected void sortResults(List<ResolveInfo> results) { 7982 Collections.sort(results, mResolvePrioritySorter); 7983 } 7984 7985 @Override 7986 protected void dumpFilter(PrintWriter out, String prefix, 7987 PackageParser.ActivityIntentInfo filter) { 7988 out.print(prefix); out.print( 7989 Integer.toHexString(System.identityHashCode(filter.activity))); 7990 out.print(' '); 7991 filter.activity.printComponentShortName(out); 7992 out.print(" filter "); 7993 out.println(Integer.toHexString(System.identityHashCode(filter))); 7994 } 7995 7996 @Override 7997 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7998 return filter.activity; 7999 } 8000 8001 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8002 PackageParser.Activity activity = (PackageParser.Activity)label; 8003 out.print(prefix); out.print( 8004 Integer.toHexString(System.identityHashCode(activity))); 8005 out.print(' '); 8006 activity.printComponentShortName(out); 8007 if (count > 1) { 8008 out.print(" ("); out.print(count); out.print(" filters)"); 8009 } 8010 out.println(); 8011 } 8012 8013// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8014// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8015// final List<ResolveInfo> retList = Lists.newArrayList(); 8016// while (i.hasNext()) { 8017// final ResolveInfo resolveInfo = i.next(); 8018// if (isEnabledLP(resolveInfo.activityInfo)) { 8019// retList.add(resolveInfo); 8020// } 8021// } 8022// return retList; 8023// } 8024 8025 // Keys are String (activity class name), values are Activity. 8026 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8027 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8028 private int mFlags; 8029 } 8030 8031 private final class ServiceIntentResolver 8032 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8033 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8034 boolean defaultOnly, int userId) { 8035 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8036 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8037 } 8038 8039 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8040 int userId) { 8041 if (!sUserManager.exists(userId)) return null; 8042 mFlags = flags; 8043 return super.queryIntent(intent, resolvedType, 8044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8045 } 8046 8047 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8048 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8049 if (!sUserManager.exists(userId)) return null; 8050 if (packageServices == null) { 8051 return null; 8052 } 8053 mFlags = flags; 8054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8055 final int N = packageServices.size(); 8056 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8057 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8058 8059 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8060 for (int i = 0; i < N; ++i) { 8061 intentFilters = packageServices.get(i).intents; 8062 if (intentFilters != null && intentFilters.size() > 0) { 8063 PackageParser.ServiceIntentInfo[] array = 8064 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8065 intentFilters.toArray(array); 8066 listCut.add(array); 8067 } 8068 } 8069 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8070 } 8071 8072 public final void addService(PackageParser.Service s) { 8073 mServices.put(s.getComponentName(), s); 8074 if (DEBUG_SHOW_INFO) { 8075 Log.v(TAG, " " 8076 + (s.info.nonLocalizedLabel != null 8077 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8078 Log.v(TAG, " Class=" + s.info.name); 8079 } 8080 final int NI = s.intents.size(); 8081 int j; 8082 for (j=0; j<NI; j++) { 8083 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8084 if (DEBUG_SHOW_INFO) { 8085 Log.v(TAG, " IntentFilter:"); 8086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8087 } 8088 if (!intent.debugCheck()) { 8089 Log.w(TAG, "==> For Service " + s.info.name); 8090 } 8091 addFilter(intent); 8092 } 8093 } 8094 8095 public final void removeService(PackageParser.Service s) { 8096 mServices.remove(s.getComponentName()); 8097 if (DEBUG_SHOW_INFO) { 8098 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8099 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8100 Log.v(TAG, " Class=" + s.info.name); 8101 } 8102 final int NI = s.intents.size(); 8103 int j; 8104 for (j=0; j<NI; j++) { 8105 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8106 if (DEBUG_SHOW_INFO) { 8107 Log.v(TAG, " IntentFilter:"); 8108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8109 } 8110 removeFilter(intent); 8111 } 8112 } 8113 8114 @Override 8115 protected boolean allowFilterResult( 8116 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8117 ServiceInfo filterSi = filter.service.info; 8118 for (int i=dest.size()-1; i>=0; i--) { 8119 ServiceInfo destAi = dest.get(i).serviceInfo; 8120 if (destAi.name == filterSi.name 8121 && destAi.packageName == filterSi.packageName) { 8122 return false; 8123 } 8124 } 8125 return true; 8126 } 8127 8128 @Override 8129 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8130 return new PackageParser.ServiceIntentInfo[size]; 8131 } 8132 8133 @Override 8134 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8135 if (!sUserManager.exists(userId)) return true; 8136 PackageParser.Package p = filter.service.owner; 8137 if (p != null) { 8138 PackageSetting ps = (PackageSetting)p.mExtras; 8139 if (ps != null) { 8140 // System apps are never considered stopped for purposes of 8141 // filtering, because there may be no way for the user to 8142 // actually re-launch them. 8143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8144 && ps.getStopped(userId); 8145 } 8146 } 8147 return false; 8148 } 8149 8150 @Override 8151 protected boolean isPackageForFilter(String packageName, 8152 PackageParser.ServiceIntentInfo info) { 8153 return packageName.equals(info.service.owner.packageName); 8154 } 8155 8156 @Override 8157 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8158 int match, int userId) { 8159 if (!sUserManager.exists(userId)) return null; 8160 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8161 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8162 return null; 8163 } 8164 final PackageParser.Service service = info.service; 8165 if (mSafeMode && (service.info.applicationInfo.flags 8166 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8167 return null; 8168 } 8169 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8170 if (ps == null) { 8171 return null; 8172 } 8173 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8174 ps.readUserState(userId), userId); 8175 if (si == null) { 8176 return null; 8177 } 8178 final ResolveInfo res = new ResolveInfo(); 8179 res.serviceInfo = si; 8180 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8181 res.filter = filter; 8182 } 8183 res.priority = info.getPriority(); 8184 res.preferredOrder = service.owner.mPreferredOrder; 8185 res.match = match; 8186 res.isDefault = info.hasDefault; 8187 res.labelRes = info.labelRes; 8188 res.nonLocalizedLabel = info.nonLocalizedLabel; 8189 res.icon = info.icon; 8190 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8191 return res; 8192 } 8193 8194 @Override 8195 protected void sortResults(List<ResolveInfo> results) { 8196 Collections.sort(results, mResolvePrioritySorter); 8197 } 8198 8199 @Override 8200 protected void dumpFilter(PrintWriter out, String prefix, 8201 PackageParser.ServiceIntentInfo filter) { 8202 out.print(prefix); out.print( 8203 Integer.toHexString(System.identityHashCode(filter.service))); 8204 out.print(' '); 8205 filter.service.printComponentShortName(out); 8206 out.print(" filter "); 8207 out.println(Integer.toHexString(System.identityHashCode(filter))); 8208 } 8209 8210 @Override 8211 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8212 return filter.service; 8213 } 8214 8215 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8216 PackageParser.Service service = (PackageParser.Service)label; 8217 out.print(prefix); out.print( 8218 Integer.toHexString(System.identityHashCode(service))); 8219 out.print(' '); 8220 service.printComponentShortName(out); 8221 if (count > 1) { 8222 out.print(" ("); out.print(count); out.print(" filters)"); 8223 } 8224 out.println(); 8225 } 8226 8227// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8228// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8229// final List<ResolveInfo> retList = Lists.newArrayList(); 8230// while (i.hasNext()) { 8231// final ResolveInfo resolveInfo = (ResolveInfo) i; 8232// if (isEnabledLP(resolveInfo.serviceInfo)) { 8233// retList.add(resolveInfo); 8234// } 8235// } 8236// return retList; 8237// } 8238 8239 // Keys are String (activity class name), values are Activity. 8240 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8241 = new ArrayMap<ComponentName, PackageParser.Service>(); 8242 private int mFlags; 8243 }; 8244 8245 private final class ProviderIntentResolver 8246 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8247 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8248 boolean defaultOnly, int userId) { 8249 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8250 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8251 } 8252 8253 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8254 int userId) { 8255 if (!sUserManager.exists(userId)) 8256 return null; 8257 mFlags = flags; 8258 return super.queryIntent(intent, resolvedType, 8259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8260 } 8261 8262 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8263 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8264 if (!sUserManager.exists(userId)) 8265 return null; 8266 if (packageProviders == null) { 8267 return null; 8268 } 8269 mFlags = flags; 8270 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8271 final int N = packageProviders.size(); 8272 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8273 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8274 8275 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8276 for (int i = 0; i < N; ++i) { 8277 intentFilters = packageProviders.get(i).intents; 8278 if (intentFilters != null && intentFilters.size() > 0) { 8279 PackageParser.ProviderIntentInfo[] array = 8280 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8281 intentFilters.toArray(array); 8282 listCut.add(array); 8283 } 8284 } 8285 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8286 } 8287 8288 public final void addProvider(PackageParser.Provider p) { 8289 if (mProviders.containsKey(p.getComponentName())) { 8290 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8291 return; 8292 } 8293 8294 mProviders.put(p.getComponentName(), p); 8295 if (DEBUG_SHOW_INFO) { 8296 Log.v(TAG, " " 8297 + (p.info.nonLocalizedLabel != null 8298 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8299 Log.v(TAG, " Class=" + p.info.name); 8300 } 8301 final int NI = p.intents.size(); 8302 int j; 8303 for (j = 0; j < NI; j++) { 8304 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8305 if (DEBUG_SHOW_INFO) { 8306 Log.v(TAG, " IntentFilter:"); 8307 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8308 } 8309 if (!intent.debugCheck()) { 8310 Log.w(TAG, "==> For Provider " + p.info.name); 8311 } 8312 addFilter(intent); 8313 } 8314 } 8315 8316 public final void removeProvider(PackageParser.Provider p) { 8317 mProviders.remove(p.getComponentName()); 8318 if (DEBUG_SHOW_INFO) { 8319 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8320 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8321 Log.v(TAG, " Class=" + p.info.name); 8322 } 8323 final int NI = p.intents.size(); 8324 int j; 8325 for (j = 0; j < NI; j++) { 8326 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8327 if (DEBUG_SHOW_INFO) { 8328 Log.v(TAG, " IntentFilter:"); 8329 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8330 } 8331 removeFilter(intent); 8332 } 8333 } 8334 8335 @Override 8336 protected boolean allowFilterResult( 8337 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8338 ProviderInfo filterPi = filter.provider.info; 8339 for (int i = dest.size() - 1; i >= 0; i--) { 8340 ProviderInfo destPi = dest.get(i).providerInfo; 8341 if (destPi.name == filterPi.name 8342 && destPi.packageName == filterPi.packageName) { 8343 return false; 8344 } 8345 } 8346 return true; 8347 } 8348 8349 @Override 8350 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8351 return new PackageParser.ProviderIntentInfo[size]; 8352 } 8353 8354 @Override 8355 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8356 if (!sUserManager.exists(userId)) 8357 return true; 8358 PackageParser.Package p = filter.provider.owner; 8359 if (p != null) { 8360 PackageSetting ps = (PackageSetting) p.mExtras; 8361 if (ps != null) { 8362 // System apps are never considered stopped for purposes of 8363 // filtering, because there may be no way for the user to 8364 // actually re-launch them. 8365 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8366 && ps.getStopped(userId); 8367 } 8368 } 8369 return false; 8370 } 8371 8372 @Override 8373 protected boolean isPackageForFilter(String packageName, 8374 PackageParser.ProviderIntentInfo info) { 8375 return packageName.equals(info.provider.owner.packageName); 8376 } 8377 8378 @Override 8379 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8380 int match, int userId) { 8381 if (!sUserManager.exists(userId)) 8382 return null; 8383 final PackageParser.ProviderIntentInfo info = filter; 8384 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8385 return null; 8386 } 8387 final PackageParser.Provider provider = info.provider; 8388 if (mSafeMode && (provider.info.applicationInfo.flags 8389 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8390 return null; 8391 } 8392 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8393 if (ps == null) { 8394 return null; 8395 } 8396 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8397 ps.readUserState(userId), userId); 8398 if (pi == null) { 8399 return null; 8400 } 8401 final ResolveInfo res = new ResolveInfo(); 8402 res.providerInfo = pi; 8403 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8404 res.filter = filter; 8405 } 8406 res.priority = info.getPriority(); 8407 res.preferredOrder = provider.owner.mPreferredOrder; 8408 res.match = match; 8409 res.isDefault = info.hasDefault; 8410 res.labelRes = info.labelRes; 8411 res.nonLocalizedLabel = info.nonLocalizedLabel; 8412 res.icon = info.icon; 8413 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8414 return res; 8415 } 8416 8417 @Override 8418 protected void sortResults(List<ResolveInfo> results) { 8419 Collections.sort(results, mResolvePrioritySorter); 8420 } 8421 8422 @Override 8423 protected void dumpFilter(PrintWriter out, String prefix, 8424 PackageParser.ProviderIntentInfo filter) { 8425 out.print(prefix); 8426 out.print( 8427 Integer.toHexString(System.identityHashCode(filter.provider))); 8428 out.print(' '); 8429 filter.provider.printComponentShortName(out); 8430 out.print(" filter "); 8431 out.println(Integer.toHexString(System.identityHashCode(filter))); 8432 } 8433 8434 @Override 8435 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8436 return filter.provider; 8437 } 8438 8439 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8440 PackageParser.Provider provider = (PackageParser.Provider)label; 8441 out.print(prefix); out.print( 8442 Integer.toHexString(System.identityHashCode(provider))); 8443 out.print(' '); 8444 provider.printComponentShortName(out); 8445 if (count > 1) { 8446 out.print(" ("); out.print(count); out.print(" filters)"); 8447 } 8448 out.println(); 8449 } 8450 8451 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8452 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8453 private int mFlags; 8454 }; 8455 8456 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8457 new Comparator<ResolveInfo>() { 8458 public int compare(ResolveInfo r1, ResolveInfo r2) { 8459 int v1 = r1.priority; 8460 int v2 = r2.priority; 8461 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8462 if (v1 != v2) { 8463 return (v1 > v2) ? -1 : 1; 8464 } 8465 v1 = r1.preferredOrder; 8466 v2 = r2.preferredOrder; 8467 if (v1 != v2) { 8468 return (v1 > v2) ? -1 : 1; 8469 } 8470 if (r1.isDefault != r2.isDefault) { 8471 return r1.isDefault ? -1 : 1; 8472 } 8473 v1 = r1.match; 8474 v2 = r2.match; 8475 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8476 if (v1 != v2) { 8477 return (v1 > v2) ? -1 : 1; 8478 } 8479 if (r1.system != r2.system) { 8480 return r1.system ? -1 : 1; 8481 } 8482 return 0; 8483 } 8484 }; 8485 8486 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8487 new Comparator<ProviderInfo>() { 8488 public int compare(ProviderInfo p1, ProviderInfo p2) { 8489 final int v1 = p1.initOrder; 8490 final int v2 = p2.initOrder; 8491 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8492 } 8493 }; 8494 8495 final void sendPackageBroadcast(final String action, final String pkg, 8496 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8497 final int[] userIds) { 8498 mHandler.post(new Runnable() { 8499 @Override 8500 public void run() { 8501 try { 8502 final IActivityManager am = ActivityManagerNative.getDefault(); 8503 if (am == null) return; 8504 final int[] resolvedUserIds; 8505 if (userIds == null) { 8506 resolvedUserIds = am.getRunningUserIds(); 8507 } else { 8508 resolvedUserIds = userIds; 8509 } 8510 for (int id : resolvedUserIds) { 8511 final Intent intent = new Intent(action, 8512 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8513 if (extras != null) { 8514 intent.putExtras(extras); 8515 } 8516 if (targetPkg != null) { 8517 intent.setPackage(targetPkg); 8518 } 8519 // Modify the UID when posting to other users 8520 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8521 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8522 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8523 intent.putExtra(Intent.EXTRA_UID, uid); 8524 } 8525 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8526 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8527 if (DEBUG_BROADCASTS) { 8528 RuntimeException here = new RuntimeException("here"); 8529 here.fillInStackTrace(); 8530 Slog.d(TAG, "Sending to user " + id + ": " 8531 + intent.toShortString(false, true, false, false) 8532 + " " + intent.getExtras(), here); 8533 } 8534 am.broadcastIntent(null, intent, null, finishedReceiver, 8535 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8536 finishedReceiver != null, false, id); 8537 } 8538 } catch (RemoteException ex) { 8539 } 8540 } 8541 }); 8542 } 8543 8544 /** 8545 * Check if the external storage media is available. This is true if there 8546 * is a mounted external storage medium or if the external storage is 8547 * emulated. 8548 */ 8549 private boolean isExternalMediaAvailable() { 8550 return mMediaMounted || Environment.isExternalStorageEmulated(); 8551 } 8552 8553 @Override 8554 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8555 // writer 8556 synchronized (mPackages) { 8557 if (!isExternalMediaAvailable()) { 8558 // If the external storage is no longer mounted at this point, 8559 // the caller may not have been able to delete all of this 8560 // packages files and can not delete any more. Bail. 8561 return null; 8562 } 8563 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8564 if (lastPackage != null) { 8565 pkgs.remove(lastPackage); 8566 } 8567 if (pkgs.size() > 0) { 8568 return pkgs.get(0); 8569 } 8570 } 8571 return null; 8572 } 8573 8574 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8575 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8576 userId, andCode ? 1 : 0, packageName); 8577 if (mSystemReady) { 8578 msg.sendToTarget(); 8579 } else { 8580 if (mPostSystemReadyMessages == null) { 8581 mPostSystemReadyMessages = new ArrayList<>(); 8582 } 8583 mPostSystemReadyMessages.add(msg); 8584 } 8585 } 8586 8587 void startCleaningPackages() { 8588 // reader 8589 synchronized (mPackages) { 8590 if (!isExternalMediaAvailable()) { 8591 return; 8592 } 8593 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8594 return; 8595 } 8596 } 8597 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8598 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8599 IActivityManager am = ActivityManagerNative.getDefault(); 8600 if (am != null) { 8601 try { 8602 am.startService(null, intent, null, UserHandle.USER_OWNER); 8603 } catch (RemoteException e) { 8604 } 8605 } 8606 } 8607 8608 @Override 8609 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8610 int installFlags, String installerPackageName, VerificationParams verificationParams, 8611 String packageAbiOverride) { 8612 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8613 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8614 } 8615 8616 @Override 8617 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8618 int installFlags, String installerPackageName, VerificationParams verificationParams, 8619 String packageAbiOverride, int userId) { 8620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8621 8622 final int callingUid = Binder.getCallingUid(); 8623 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8624 8625 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8626 try { 8627 if (observer != null) { 8628 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8629 } 8630 } catch (RemoteException re) { 8631 } 8632 return; 8633 } 8634 8635 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8636 installFlags |= PackageManager.INSTALL_FROM_ADB; 8637 8638 } else { 8639 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8640 // about installerPackageName. 8641 8642 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8643 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8644 } 8645 8646 UserHandle user; 8647 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8648 user = UserHandle.ALL; 8649 } else { 8650 user = new UserHandle(userId); 8651 } 8652 8653 // Only system components can circumvent runtime permissions when installing. 8654 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8655 && mContext.checkCallingOrSelfPermission(Manifest.permission 8656 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8657 throw new SecurityException("You need the " 8658 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8659 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8660 } 8661 8662 verificationParams.setInstallerUid(callingUid); 8663 8664 final File originFile = new File(originPath); 8665 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8666 8667 final Message msg = mHandler.obtainMessage(INIT_COPY); 8668 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8669 null, verificationParams, user, packageAbiOverride); 8670 mHandler.sendMessage(msg); 8671 } 8672 8673 void installStage(String packageName, File stagedDir, String stagedCid, 8674 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8675 String installerPackageName, int installerUid, UserHandle user) { 8676 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8677 params.referrerUri, installerUid, null); 8678 8679 final OriginInfo origin; 8680 if (stagedDir != null) { 8681 origin = OriginInfo.fromStagedFile(stagedDir); 8682 } else { 8683 origin = OriginInfo.fromStagedContainer(stagedCid); 8684 } 8685 8686 final Message msg = mHandler.obtainMessage(INIT_COPY); 8687 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8688 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8689 mHandler.sendMessage(msg); 8690 } 8691 8692 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8693 Bundle extras = new Bundle(1); 8694 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8695 8696 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8697 packageName, extras, null, null, new int[] {userId}); 8698 try { 8699 IActivityManager am = ActivityManagerNative.getDefault(); 8700 final boolean isSystem = 8701 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8702 if (isSystem && am.isUserRunning(userId, false)) { 8703 // The just-installed/enabled app is bundled on the system, so presumed 8704 // to be able to run automatically without needing an explicit launch. 8705 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8706 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8707 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8708 .setPackage(packageName); 8709 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8710 android.app.AppOpsManager.OP_NONE, false, false, userId); 8711 } 8712 } catch (RemoteException e) { 8713 // shouldn't happen 8714 Slog.w(TAG, "Unable to bootstrap installed package", e); 8715 } 8716 } 8717 8718 @Override 8719 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8720 int userId) { 8721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8722 PackageSetting pkgSetting; 8723 final int uid = Binder.getCallingUid(); 8724 enforceCrossUserPermission(uid, userId, true, true, 8725 "setApplicationHiddenSetting for user " + userId); 8726 8727 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8728 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8729 return false; 8730 } 8731 8732 long callingId = Binder.clearCallingIdentity(); 8733 try { 8734 boolean sendAdded = false; 8735 boolean sendRemoved = false; 8736 // writer 8737 synchronized (mPackages) { 8738 pkgSetting = mSettings.mPackages.get(packageName); 8739 if (pkgSetting == null) { 8740 return false; 8741 } 8742 if (pkgSetting.getHidden(userId) != hidden) { 8743 pkgSetting.setHidden(hidden, userId); 8744 mSettings.writePackageRestrictionsLPr(userId); 8745 if (hidden) { 8746 sendRemoved = true; 8747 } else { 8748 sendAdded = true; 8749 } 8750 } 8751 } 8752 if (sendAdded) { 8753 sendPackageAddedForUser(packageName, pkgSetting, userId); 8754 return true; 8755 } 8756 if (sendRemoved) { 8757 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8758 "hiding pkg"); 8759 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8760 } 8761 } finally { 8762 Binder.restoreCallingIdentity(callingId); 8763 } 8764 return false; 8765 } 8766 8767 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8768 int userId) { 8769 final PackageRemovedInfo info = new PackageRemovedInfo(); 8770 info.removedPackage = packageName; 8771 info.removedUsers = new int[] {userId}; 8772 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8773 info.sendBroadcast(false, false, false); 8774 } 8775 8776 /** 8777 * Returns true if application is not found or there was an error. Otherwise it returns 8778 * the hidden state of the package for the given user. 8779 */ 8780 @Override 8781 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8783 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8784 false, "getApplicationHidden for user " + userId); 8785 PackageSetting pkgSetting; 8786 long callingId = Binder.clearCallingIdentity(); 8787 try { 8788 // writer 8789 synchronized (mPackages) { 8790 pkgSetting = mSettings.mPackages.get(packageName); 8791 if (pkgSetting == null) { 8792 return true; 8793 } 8794 return pkgSetting.getHidden(userId); 8795 } 8796 } finally { 8797 Binder.restoreCallingIdentity(callingId); 8798 } 8799 } 8800 8801 /** 8802 * @hide 8803 */ 8804 @Override 8805 public int installExistingPackageAsUser(String packageName, int userId) { 8806 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8807 null); 8808 PackageSetting pkgSetting; 8809 final int uid = Binder.getCallingUid(); 8810 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8811 + userId); 8812 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8813 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8814 } 8815 8816 long callingId = Binder.clearCallingIdentity(); 8817 try { 8818 boolean sendAdded = false; 8819 8820 // writer 8821 synchronized (mPackages) { 8822 pkgSetting = mSettings.mPackages.get(packageName); 8823 if (pkgSetting == null) { 8824 return PackageManager.INSTALL_FAILED_INVALID_URI; 8825 } 8826 if (!pkgSetting.getInstalled(userId)) { 8827 pkgSetting.setInstalled(true, userId); 8828 pkgSetting.setHidden(false, userId); 8829 mSettings.writePackageRestrictionsLPr(userId); 8830 sendAdded = true; 8831 } 8832 } 8833 8834 if (sendAdded) { 8835 sendPackageAddedForUser(packageName, pkgSetting, userId); 8836 } 8837 } finally { 8838 Binder.restoreCallingIdentity(callingId); 8839 } 8840 8841 return PackageManager.INSTALL_SUCCEEDED; 8842 } 8843 8844 boolean isUserRestricted(int userId, String restrictionKey) { 8845 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8846 if (restrictions.getBoolean(restrictionKey, false)) { 8847 Log.w(TAG, "User is restricted: " + restrictionKey); 8848 return true; 8849 } 8850 return false; 8851 } 8852 8853 @Override 8854 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8855 mContext.enforceCallingOrSelfPermission( 8856 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8857 "Only package verification agents can verify applications"); 8858 8859 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8860 final PackageVerificationResponse response = new PackageVerificationResponse( 8861 verificationCode, Binder.getCallingUid()); 8862 msg.arg1 = id; 8863 msg.obj = response; 8864 mHandler.sendMessage(msg); 8865 } 8866 8867 @Override 8868 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8869 long millisecondsToDelay) { 8870 mContext.enforceCallingOrSelfPermission( 8871 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8872 "Only package verification agents can extend verification timeouts"); 8873 8874 final PackageVerificationState state = mPendingVerification.get(id); 8875 final PackageVerificationResponse response = new PackageVerificationResponse( 8876 verificationCodeAtTimeout, Binder.getCallingUid()); 8877 8878 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8879 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8880 } 8881 if (millisecondsToDelay < 0) { 8882 millisecondsToDelay = 0; 8883 } 8884 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8885 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8886 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8887 } 8888 8889 if ((state != null) && !state.timeoutExtended()) { 8890 state.extendTimeout(); 8891 8892 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8893 msg.arg1 = id; 8894 msg.obj = response; 8895 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8896 } 8897 } 8898 8899 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8900 int verificationCode, UserHandle user) { 8901 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8902 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8903 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8904 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8905 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8906 8907 mContext.sendBroadcastAsUser(intent, user, 8908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8909 } 8910 8911 private ComponentName matchComponentForVerifier(String packageName, 8912 List<ResolveInfo> receivers) { 8913 ActivityInfo targetReceiver = null; 8914 8915 final int NR = receivers.size(); 8916 for (int i = 0; i < NR; i++) { 8917 final ResolveInfo info = receivers.get(i); 8918 if (info.activityInfo == null) { 8919 continue; 8920 } 8921 8922 if (packageName.equals(info.activityInfo.packageName)) { 8923 targetReceiver = info.activityInfo; 8924 break; 8925 } 8926 } 8927 8928 if (targetReceiver == null) { 8929 return null; 8930 } 8931 8932 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8933 } 8934 8935 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8936 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8937 if (pkgInfo.verifiers.length == 0) { 8938 return null; 8939 } 8940 8941 final int N = pkgInfo.verifiers.length; 8942 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8943 for (int i = 0; i < N; i++) { 8944 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8945 8946 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8947 receivers); 8948 if (comp == null) { 8949 continue; 8950 } 8951 8952 final int verifierUid = getUidForVerifier(verifierInfo); 8953 if (verifierUid == -1) { 8954 continue; 8955 } 8956 8957 if (DEBUG_VERIFY) { 8958 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8959 + " with the correct signature"); 8960 } 8961 sufficientVerifiers.add(comp); 8962 verificationState.addSufficientVerifier(verifierUid); 8963 } 8964 8965 return sufficientVerifiers; 8966 } 8967 8968 private int getUidForVerifier(VerifierInfo verifierInfo) { 8969 synchronized (mPackages) { 8970 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8971 if (pkg == null) { 8972 return -1; 8973 } else if (pkg.mSignatures.length != 1) { 8974 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8975 + " has more than one signature; ignoring"); 8976 return -1; 8977 } 8978 8979 /* 8980 * If the public key of the package's signature does not match 8981 * our expected public key, then this is a different package and 8982 * we should skip. 8983 */ 8984 8985 final byte[] expectedPublicKey; 8986 try { 8987 final Signature verifierSig = pkg.mSignatures[0]; 8988 final PublicKey publicKey = verifierSig.getPublicKey(); 8989 expectedPublicKey = publicKey.getEncoded(); 8990 } catch (CertificateException e) { 8991 return -1; 8992 } 8993 8994 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8995 8996 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8997 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8998 + " does not have the expected public key; ignoring"); 8999 return -1; 9000 } 9001 9002 return pkg.applicationInfo.uid; 9003 } 9004 } 9005 9006 @Override 9007 public void finishPackageInstall(int token) { 9008 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9009 9010 if (DEBUG_INSTALL) { 9011 Slog.v(TAG, "BM finishing package install for " + token); 9012 } 9013 9014 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9015 mHandler.sendMessage(msg); 9016 } 9017 9018 /** 9019 * Get the verification agent timeout. 9020 * 9021 * @return verification timeout in milliseconds 9022 */ 9023 private long getVerificationTimeout() { 9024 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9025 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9026 DEFAULT_VERIFICATION_TIMEOUT); 9027 } 9028 9029 /** 9030 * Get the default verification agent response code. 9031 * 9032 * @return default verification response code 9033 */ 9034 private int getDefaultVerificationResponse() { 9035 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9036 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9037 DEFAULT_VERIFICATION_RESPONSE); 9038 } 9039 9040 /** 9041 * Check whether or not package verification has been enabled. 9042 * 9043 * @return true if verification should be performed 9044 */ 9045 private boolean isVerificationEnabled(int userId, int installFlags) { 9046 if (!DEFAULT_VERIFY_ENABLE) { 9047 return false; 9048 } 9049 9050 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9051 9052 // Check if installing from ADB 9053 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9054 // Do not run verification in a test harness environment 9055 if (ActivityManager.isRunningInTestHarness()) { 9056 return false; 9057 } 9058 if (ensureVerifyAppsEnabled) { 9059 return true; 9060 } 9061 // Check if the developer does not want package verification for ADB installs 9062 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9063 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9064 return false; 9065 } 9066 } 9067 9068 if (ensureVerifyAppsEnabled) { 9069 return true; 9070 } 9071 9072 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9073 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9074 } 9075 9076 @Override 9077 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9078 throws RemoteException { 9079 mContext.enforceCallingOrSelfPermission( 9080 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9081 "Only intentfilter verification agents can verify applications"); 9082 9083 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9084 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9085 Binder.getCallingUid(), verificationCode, failedDomains); 9086 msg.arg1 = id; 9087 msg.obj = response; 9088 mHandler.sendMessage(msg); 9089 } 9090 9091 @Override 9092 public int getIntentVerificationStatus(String packageName, int userId) { 9093 synchronized (mPackages) { 9094 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9095 } 9096 } 9097 9098 @Override 9099 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9100 boolean result = false; 9101 synchronized (mPackages) { 9102 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9103 } 9104 scheduleWritePackageRestrictionsLocked(userId); 9105 return result; 9106 } 9107 9108 @Override 9109 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9110 synchronized (mPackages) { 9111 return mSettings.getIntentFilterVerificationsLPr(packageName); 9112 } 9113 } 9114 9115 @Override 9116 public List<IntentFilter> getAllIntentFilters(String packageName) { 9117 if (TextUtils.isEmpty(packageName)) { 9118 return Collections.<IntentFilter>emptyList(); 9119 } 9120 synchronized (mPackages) { 9121 PackageParser.Package pkg = mPackages.get(packageName); 9122 if (pkg == null || pkg.activities == null) { 9123 return Collections.<IntentFilter>emptyList(); 9124 } 9125 final int count = pkg.activities.size(); 9126 ArrayList<IntentFilter> result = new ArrayList<>(); 9127 for (int n=0; n<count; n++) { 9128 PackageParser.Activity activity = pkg.activities.get(n); 9129 if (activity.intents != null || activity.intents.size() > 0) { 9130 result.addAll(activity.intents); 9131 } 9132 } 9133 return result; 9134 } 9135 } 9136 9137 @Override 9138 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9139 synchronized (mPackages) { 9140 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9141 result |= updateIntentVerificationStatus(packageName, 9142 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9143 UserHandle.myUserId()); 9144 return result; 9145 } 9146 } 9147 9148 @Override 9149 public String getDefaultBrowserPackageName(int userId) { 9150 synchronized (mPackages) { 9151 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9152 } 9153 } 9154 9155 /** 9156 * Get the "allow unknown sources" setting. 9157 * 9158 * @return the current "allow unknown sources" setting 9159 */ 9160 private int getUnknownSourcesSettings() { 9161 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9162 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9163 -1); 9164 } 9165 9166 @Override 9167 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9168 final int uid = Binder.getCallingUid(); 9169 // writer 9170 synchronized (mPackages) { 9171 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9172 if (targetPackageSetting == null) { 9173 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9174 } 9175 9176 PackageSetting installerPackageSetting; 9177 if (installerPackageName != null) { 9178 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9179 if (installerPackageSetting == null) { 9180 throw new IllegalArgumentException("Unknown installer package: " 9181 + installerPackageName); 9182 } 9183 } else { 9184 installerPackageSetting = null; 9185 } 9186 9187 Signature[] callerSignature; 9188 Object obj = mSettings.getUserIdLPr(uid); 9189 if (obj != null) { 9190 if (obj instanceof SharedUserSetting) { 9191 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9192 } else if (obj instanceof PackageSetting) { 9193 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9194 } else { 9195 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9196 } 9197 } else { 9198 throw new SecurityException("Unknown calling uid " + uid); 9199 } 9200 9201 // Verify: can't set installerPackageName to a package that is 9202 // not signed with the same cert as the caller. 9203 if (installerPackageSetting != null) { 9204 if (compareSignatures(callerSignature, 9205 installerPackageSetting.signatures.mSignatures) 9206 != PackageManager.SIGNATURE_MATCH) { 9207 throw new SecurityException( 9208 "Caller does not have same cert as new installer package " 9209 + installerPackageName); 9210 } 9211 } 9212 9213 // Verify: if target already has an installer package, it must 9214 // be signed with the same cert as the caller. 9215 if (targetPackageSetting.installerPackageName != null) { 9216 PackageSetting setting = mSettings.mPackages.get( 9217 targetPackageSetting.installerPackageName); 9218 // If the currently set package isn't valid, then it's always 9219 // okay to change it. 9220 if (setting != null) { 9221 if (compareSignatures(callerSignature, 9222 setting.signatures.mSignatures) 9223 != PackageManager.SIGNATURE_MATCH) { 9224 throw new SecurityException( 9225 "Caller does not have same cert as old installer package " 9226 + targetPackageSetting.installerPackageName); 9227 } 9228 } 9229 } 9230 9231 // Okay! 9232 targetPackageSetting.installerPackageName = installerPackageName; 9233 scheduleWriteSettingsLocked(); 9234 } 9235 } 9236 9237 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9238 // Queue up an async operation since the package installation may take a little while. 9239 mHandler.post(new Runnable() { 9240 public void run() { 9241 mHandler.removeCallbacks(this); 9242 // Result object to be returned 9243 PackageInstalledInfo res = new PackageInstalledInfo(); 9244 res.returnCode = currentStatus; 9245 res.uid = -1; 9246 res.pkg = null; 9247 res.removedInfo = new PackageRemovedInfo(); 9248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9249 args.doPreInstall(res.returnCode); 9250 synchronized (mInstallLock) { 9251 installPackageLI(args, res); 9252 } 9253 args.doPostInstall(res.returnCode, res.uid); 9254 } 9255 9256 // A restore should be performed at this point if (a) the install 9257 // succeeded, (b) the operation is not an update, and (c) the new 9258 // package has not opted out of backup participation. 9259 final boolean update = res.removedInfo.removedPackage != null; 9260 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9261 boolean doRestore = !update 9262 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9263 9264 // Set up the post-install work request bookkeeping. This will be used 9265 // and cleaned up by the post-install event handling regardless of whether 9266 // there's a restore pass performed. Token values are >= 1. 9267 int token; 9268 if (mNextInstallToken < 0) mNextInstallToken = 1; 9269 token = mNextInstallToken++; 9270 9271 PostInstallData data = new PostInstallData(args, res); 9272 mRunningInstalls.put(token, data); 9273 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9274 9275 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9276 // Pass responsibility to the Backup Manager. It will perform a 9277 // restore if appropriate, then pass responsibility back to the 9278 // Package Manager to run the post-install observer callbacks 9279 // and broadcasts. 9280 IBackupManager bm = IBackupManager.Stub.asInterface( 9281 ServiceManager.getService(Context.BACKUP_SERVICE)); 9282 if (bm != null) { 9283 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9284 + " to BM for possible restore"); 9285 try { 9286 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9287 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9288 } else { 9289 doRestore = false; 9290 } 9291 } catch (RemoteException e) { 9292 // can't happen; the backup manager is local 9293 } catch (Exception e) { 9294 Slog.e(TAG, "Exception trying to enqueue restore", e); 9295 doRestore = false; 9296 } 9297 } else { 9298 Slog.e(TAG, "Backup Manager not found!"); 9299 doRestore = false; 9300 } 9301 } 9302 9303 if (!doRestore) { 9304 // No restore possible, or the Backup Manager was mysteriously not 9305 // available -- just fire the post-install work request directly. 9306 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9307 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9308 mHandler.sendMessage(msg); 9309 } 9310 } 9311 }); 9312 } 9313 9314 private abstract class HandlerParams { 9315 private static final int MAX_RETRIES = 4; 9316 9317 /** 9318 * Number of times startCopy() has been attempted and had a non-fatal 9319 * error. 9320 */ 9321 private int mRetries = 0; 9322 9323 /** User handle for the user requesting the information or installation. */ 9324 private final UserHandle mUser; 9325 9326 HandlerParams(UserHandle user) { 9327 mUser = user; 9328 } 9329 9330 UserHandle getUser() { 9331 return mUser; 9332 } 9333 9334 final boolean startCopy() { 9335 boolean res; 9336 try { 9337 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9338 9339 if (++mRetries > MAX_RETRIES) { 9340 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9341 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9342 handleServiceError(); 9343 return false; 9344 } else { 9345 handleStartCopy(); 9346 res = true; 9347 } 9348 } catch (RemoteException e) { 9349 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9350 mHandler.sendEmptyMessage(MCS_RECONNECT); 9351 res = false; 9352 } 9353 handleReturnCode(); 9354 return res; 9355 } 9356 9357 final void serviceError() { 9358 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9359 handleServiceError(); 9360 handleReturnCode(); 9361 } 9362 9363 abstract void handleStartCopy() throws RemoteException; 9364 abstract void handleServiceError(); 9365 abstract void handleReturnCode(); 9366 } 9367 9368 class MeasureParams extends HandlerParams { 9369 private final PackageStats mStats; 9370 private boolean mSuccess; 9371 9372 private final IPackageStatsObserver mObserver; 9373 9374 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9375 super(new UserHandle(stats.userHandle)); 9376 mObserver = observer; 9377 mStats = stats; 9378 } 9379 9380 @Override 9381 public String toString() { 9382 return "MeasureParams{" 9383 + Integer.toHexString(System.identityHashCode(this)) 9384 + " " + mStats.packageName + "}"; 9385 } 9386 9387 @Override 9388 void handleStartCopy() throws RemoteException { 9389 synchronized (mInstallLock) { 9390 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9391 } 9392 9393 if (mSuccess) { 9394 final boolean mounted; 9395 if (Environment.isExternalStorageEmulated()) { 9396 mounted = true; 9397 } else { 9398 final String status = Environment.getExternalStorageState(); 9399 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9400 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9401 } 9402 9403 if (mounted) { 9404 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9405 9406 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9407 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9408 9409 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9410 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9411 9412 // Always subtract cache size, since it's a subdirectory 9413 mStats.externalDataSize -= mStats.externalCacheSize; 9414 9415 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9416 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9417 9418 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9419 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9420 } 9421 } 9422 } 9423 9424 @Override 9425 void handleReturnCode() { 9426 if (mObserver != null) { 9427 try { 9428 mObserver.onGetStatsCompleted(mStats, mSuccess); 9429 } catch (RemoteException e) { 9430 Slog.i(TAG, "Observer no longer exists."); 9431 } 9432 } 9433 } 9434 9435 @Override 9436 void handleServiceError() { 9437 Slog.e(TAG, "Could not measure application " + mStats.packageName 9438 + " external storage"); 9439 } 9440 } 9441 9442 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9443 throws RemoteException { 9444 long result = 0; 9445 for (File path : paths) { 9446 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9447 } 9448 return result; 9449 } 9450 9451 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9452 for (File path : paths) { 9453 try { 9454 mcs.clearDirectory(path.getAbsolutePath()); 9455 } catch (RemoteException e) { 9456 } 9457 } 9458 } 9459 9460 static class OriginInfo { 9461 /** 9462 * Location where install is coming from, before it has been 9463 * copied/renamed into place. This could be a single monolithic APK 9464 * file, or a cluster directory. This location may be untrusted. 9465 */ 9466 final File file; 9467 final String cid; 9468 9469 /** 9470 * Flag indicating that {@link #file} or {@link #cid} has already been 9471 * staged, meaning downstream users don't need to defensively copy the 9472 * contents. 9473 */ 9474 final boolean staged; 9475 9476 /** 9477 * Flag indicating that {@link #file} or {@link #cid} is an already 9478 * installed app that is being moved. 9479 */ 9480 final boolean existing; 9481 9482 final String resolvedPath; 9483 final File resolvedFile; 9484 9485 static OriginInfo fromNothing() { 9486 return new OriginInfo(null, null, false, false); 9487 } 9488 9489 static OriginInfo fromUntrustedFile(File file) { 9490 return new OriginInfo(file, null, false, false); 9491 } 9492 9493 static OriginInfo fromExistingFile(File file) { 9494 return new OriginInfo(file, null, false, true); 9495 } 9496 9497 static OriginInfo fromStagedFile(File file) { 9498 return new OriginInfo(file, null, true, false); 9499 } 9500 9501 static OriginInfo fromStagedContainer(String cid) { 9502 return new OriginInfo(null, cid, true, false); 9503 } 9504 9505 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9506 this.file = file; 9507 this.cid = cid; 9508 this.staged = staged; 9509 this.existing = existing; 9510 9511 if (cid != null) { 9512 resolvedPath = PackageHelper.getSdDir(cid); 9513 resolvedFile = new File(resolvedPath); 9514 } else if (file != null) { 9515 resolvedPath = file.getAbsolutePath(); 9516 resolvedFile = file; 9517 } else { 9518 resolvedPath = null; 9519 resolvedFile = null; 9520 } 9521 } 9522 } 9523 9524 class MoveInfo { 9525 final int moveId; 9526 final String fromUuid; 9527 final String toUuid; 9528 final String packageName; 9529 final String dataAppName; 9530 final int appId; 9531 final String seinfo; 9532 9533 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9534 String dataAppName, int appId, String seinfo) { 9535 this.moveId = moveId; 9536 this.fromUuid = fromUuid; 9537 this.toUuid = toUuid; 9538 this.packageName = packageName; 9539 this.dataAppName = dataAppName; 9540 this.appId = appId; 9541 this.seinfo = seinfo; 9542 } 9543 } 9544 9545 class InstallParams extends HandlerParams { 9546 final OriginInfo origin; 9547 final MoveInfo move; 9548 final IPackageInstallObserver2 observer; 9549 int installFlags; 9550 final String installerPackageName; 9551 final String volumeUuid; 9552 final VerificationParams verificationParams; 9553 private InstallArgs mArgs; 9554 private int mRet; 9555 final String packageAbiOverride; 9556 9557 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9558 int installFlags, String installerPackageName, String volumeUuid, 9559 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9560 super(user); 9561 this.origin = origin; 9562 this.move = move; 9563 this.observer = observer; 9564 this.installFlags = installFlags; 9565 this.installerPackageName = installerPackageName; 9566 this.volumeUuid = volumeUuid; 9567 this.verificationParams = verificationParams; 9568 this.packageAbiOverride = packageAbiOverride; 9569 } 9570 9571 @Override 9572 public String toString() { 9573 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9574 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9575 } 9576 9577 public ManifestDigest getManifestDigest() { 9578 if (verificationParams == null) { 9579 return null; 9580 } 9581 return verificationParams.getManifestDigest(); 9582 } 9583 9584 private int installLocationPolicy(PackageInfoLite pkgLite) { 9585 String packageName = pkgLite.packageName; 9586 int installLocation = pkgLite.installLocation; 9587 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9588 // reader 9589 synchronized (mPackages) { 9590 PackageParser.Package pkg = mPackages.get(packageName); 9591 if (pkg != null) { 9592 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9593 // Check for downgrading. 9594 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9595 try { 9596 checkDowngrade(pkg, pkgLite); 9597 } catch (PackageManagerException e) { 9598 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9599 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9600 } 9601 } 9602 // Check for updated system application. 9603 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9604 if (onSd) { 9605 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9606 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9607 } 9608 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9609 } else { 9610 if (onSd) { 9611 // Install flag overrides everything. 9612 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9613 } 9614 // If current upgrade specifies particular preference 9615 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9616 // Application explicitly specified internal. 9617 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9618 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9619 // App explictly prefers external. Let policy decide 9620 } else { 9621 // Prefer previous location 9622 if (isExternal(pkg)) { 9623 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9624 } 9625 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9626 } 9627 } 9628 } else { 9629 // Invalid install. Return error code 9630 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9631 } 9632 } 9633 } 9634 // All the special cases have been taken care of. 9635 // Return result based on recommended install location. 9636 if (onSd) { 9637 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9638 } 9639 return pkgLite.recommendedInstallLocation; 9640 } 9641 9642 /* 9643 * Invoke remote method to get package information and install 9644 * location values. Override install location based on default 9645 * policy if needed and then create install arguments based 9646 * on the install location. 9647 */ 9648 public void handleStartCopy() throws RemoteException { 9649 int ret = PackageManager.INSTALL_SUCCEEDED; 9650 9651 // If we're already staged, we've firmly committed to an install location 9652 if (origin.staged) { 9653 if (origin.file != null) { 9654 installFlags |= PackageManager.INSTALL_INTERNAL; 9655 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9656 } else if (origin.cid != null) { 9657 installFlags |= PackageManager.INSTALL_EXTERNAL; 9658 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9659 } else { 9660 throw new IllegalStateException("Invalid stage location"); 9661 } 9662 } 9663 9664 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9665 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9666 9667 PackageInfoLite pkgLite = null; 9668 9669 if (onInt && onSd) { 9670 // Check if both bits are set. 9671 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9672 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9673 } else { 9674 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9675 packageAbiOverride); 9676 9677 /* 9678 * If we have too little free space, try to free cache 9679 * before giving up. 9680 */ 9681 if (!origin.staged && pkgLite.recommendedInstallLocation 9682 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9683 // TODO: focus freeing disk space on the target device 9684 final StorageManager storage = StorageManager.from(mContext); 9685 final long lowThreshold = storage.getStorageLowBytes( 9686 Environment.getDataDirectory()); 9687 9688 final long sizeBytes = mContainerService.calculateInstalledSize( 9689 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9690 9691 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9692 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9693 installFlags, packageAbiOverride); 9694 } 9695 9696 /* 9697 * The cache free must have deleted the file we 9698 * downloaded to install. 9699 * 9700 * TODO: fix the "freeCache" call to not delete 9701 * the file we care about. 9702 */ 9703 if (pkgLite.recommendedInstallLocation 9704 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9705 pkgLite.recommendedInstallLocation 9706 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9707 } 9708 } 9709 } 9710 9711 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9712 int loc = pkgLite.recommendedInstallLocation; 9713 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9714 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9715 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9716 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9717 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9718 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9719 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9720 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9721 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9722 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9723 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9724 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9725 } else { 9726 // Override with defaults if needed. 9727 loc = installLocationPolicy(pkgLite); 9728 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9729 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9730 } else if (!onSd && !onInt) { 9731 // Override install location with flags 9732 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9733 // Set the flag to install on external media. 9734 installFlags |= PackageManager.INSTALL_EXTERNAL; 9735 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9736 } else { 9737 // Make sure the flag for installing on external 9738 // media is unset 9739 installFlags |= PackageManager.INSTALL_INTERNAL; 9740 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9741 } 9742 } 9743 } 9744 } 9745 9746 final InstallArgs args = createInstallArgs(this); 9747 mArgs = args; 9748 9749 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9750 /* 9751 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9752 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9753 */ 9754 int userIdentifier = getUser().getIdentifier(); 9755 if (userIdentifier == UserHandle.USER_ALL 9756 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9757 userIdentifier = UserHandle.USER_OWNER; 9758 } 9759 9760 /* 9761 * Determine if we have any installed package verifiers. If we 9762 * do, then we'll defer to them to verify the packages. 9763 */ 9764 final int requiredUid = mRequiredVerifierPackage == null ? -1 9765 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9766 if (!origin.existing && requiredUid != -1 9767 && isVerificationEnabled(userIdentifier, installFlags)) { 9768 final Intent verification = new Intent( 9769 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9770 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9771 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9772 PACKAGE_MIME_TYPE); 9773 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9774 9775 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9776 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9777 0 /* TODO: Which userId? */); 9778 9779 if (DEBUG_VERIFY) { 9780 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9781 + verification.toString() + " with " + pkgLite.verifiers.length 9782 + " optional verifiers"); 9783 } 9784 9785 final int verificationId = mPendingVerificationToken++; 9786 9787 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9788 9789 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9790 installerPackageName); 9791 9792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9793 installFlags); 9794 9795 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9796 pkgLite.packageName); 9797 9798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9799 pkgLite.versionCode); 9800 9801 if (verificationParams != null) { 9802 if (verificationParams.getVerificationURI() != null) { 9803 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9804 verificationParams.getVerificationURI()); 9805 } 9806 if (verificationParams.getOriginatingURI() != null) { 9807 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9808 verificationParams.getOriginatingURI()); 9809 } 9810 if (verificationParams.getReferrer() != null) { 9811 verification.putExtra(Intent.EXTRA_REFERRER, 9812 verificationParams.getReferrer()); 9813 } 9814 if (verificationParams.getOriginatingUid() >= 0) { 9815 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9816 verificationParams.getOriginatingUid()); 9817 } 9818 if (verificationParams.getInstallerUid() >= 0) { 9819 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9820 verificationParams.getInstallerUid()); 9821 } 9822 } 9823 9824 final PackageVerificationState verificationState = new PackageVerificationState( 9825 requiredUid, args); 9826 9827 mPendingVerification.append(verificationId, verificationState); 9828 9829 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9830 receivers, verificationState); 9831 9832 /* 9833 * If any sufficient verifiers were listed in the package 9834 * manifest, attempt to ask them. 9835 */ 9836 if (sufficientVerifiers != null) { 9837 final int N = sufficientVerifiers.size(); 9838 if (N == 0) { 9839 Slog.i(TAG, "Additional verifiers required, but none installed."); 9840 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9841 } else { 9842 for (int i = 0; i < N; i++) { 9843 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9844 9845 final Intent sufficientIntent = new Intent(verification); 9846 sufficientIntent.setComponent(verifierComponent); 9847 9848 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9849 } 9850 } 9851 } 9852 9853 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9854 mRequiredVerifierPackage, receivers); 9855 if (ret == PackageManager.INSTALL_SUCCEEDED 9856 && mRequiredVerifierPackage != null) { 9857 /* 9858 * Send the intent to the required verification agent, 9859 * but only start the verification timeout after the 9860 * target BroadcastReceivers have run. 9861 */ 9862 verification.setComponent(requiredVerifierComponent); 9863 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9864 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9865 new BroadcastReceiver() { 9866 @Override 9867 public void onReceive(Context context, Intent intent) { 9868 final Message msg = mHandler 9869 .obtainMessage(CHECK_PENDING_VERIFICATION); 9870 msg.arg1 = verificationId; 9871 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9872 } 9873 }, null, 0, null, null); 9874 9875 /* 9876 * We don't want the copy to proceed until verification 9877 * succeeds, so null out this field. 9878 */ 9879 mArgs = null; 9880 } 9881 } else { 9882 /* 9883 * No package verification is enabled, so immediately start 9884 * the remote call to initiate copy using temporary file. 9885 */ 9886 ret = args.copyApk(mContainerService, true); 9887 } 9888 } 9889 9890 mRet = ret; 9891 } 9892 9893 @Override 9894 void handleReturnCode() { 9895 // If mArgs is null, then MCS couldn't be reached. When it 9896 // reconnects, it will try again to install. At that point, this 9897 // will succeed. 9898 if (mArgs != null) { 9899 processPendingInstall(mArgs, mRet); 9900 } 9901 } 9902 9903 @Override 9904 void handleServiceError() { 9905 mArgs = createInstallArgs(this); 9906 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9907 } 9908 9909 public boolean isForwardLocked() { 9910 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9911 } 9912 } 9913 9914 /** 9915 * Used during creation of InstallArgs 9916 * 9917 * @param installFlags package installation flags 9918 * @return true if should be installed on external storage 9919 */ 9920 private static boolean installOnExternalAsec(int installFlags) { 9921 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9922 return false; 9923 } 9924 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9925 return true; 9926 } 9927 return false; 9928 } 9929 9930 /** 9931 * Used during creation of InstallArgs 9932 * 9933 * @param installFlags package installation flags 9934 * @return true if should be installed as forward locked 9935 */ 9936 private static boolean installForwardLocked(int installFlags) { 9937 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9938 } 9939 9940 private InstallArgs createInstallArgs(InstallParams params) { 9941 if (params.move != null) { 9942 return new MoveInstallArgs(params); 9943 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9944 return new AsecInstallArgs(params); 9945 } else { 9946 return new FileInstallArgs(params); 9947 } 9948 } 9949 9950 /** 9951 * Create args that describe an existing installed package. Typically used 9952 * when cleaning up old installs, or used as a move source. 9953 */ 9954 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9955 String resourcePath, String[] instructionSets) { 9956 final boolean isInAsec; 9957 if (installOnExternalAsec(installFlags)) { 9958 /* Apps on SD card are always in ASEC containers. */ 9959 isInAsec = true; 9960 } else if (installForwardLocked(installFlags) 9961 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9962 /* 9963 * Forward-locked apps are only in ASEC containers if they're the 9964 * new style 9965 */ 9966 isInAsec = true; 9967 } else { 9968 isInAsec = false; 9969 } 9970 9971 if (isInAsec) { 9972 return new AsecInstallArgs(codePath, instructionSets, 9973 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9974 } else { 9975 return new FileInstallArgs(codePath, resourcePath, instructionSets); 9976 } 9977 } 9978 9979 static abstract class InstallArgs { 9980 /** @see InstallParams#origin */ 9981 final OriginInfo origin; 9982 /** @see InstallParams#move */ 9983 final MoveInfo move; 9984 9985 final IPackageInstallObserver2 observer; 9986 // Always refers to PackageManager flags only 9987 final int installFlags; 9988 final String installerPackageName; 9989 final String volumeUuid; 9990 final ManifestDigest manifestDigest; 9991 final UserHandle user; 9992 final String abiOverride; 9993 9994 // The list of instruction sets supported by this app. This is currently 9995 // only used during the rmdex() phase to clean up resources. We can get rid of this 9996 // if we move dex files under the common app path. 9997 /* nullable */ String[] instructionSets; 9998 9999 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10000 int installFlags, String installerPackageName, String volumeUuid, 10001 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10002 String abiOverride) { 10003 this.origin = origin; 10004 this.move = move; 10005 this.installFlags = installFlags; 10006 this.observer = observer; 10007 this.installerPackageName = installerPackageName; 10008 this.volumeUuid = volumeUuid; 10009 this.manifestDigest = manifestDigest; 10010 this.user = user; 10011 this.instructionSets = instructionSets; 10012 this.abiOverride = abiOverride; 10013 } 10014 10015 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10016 abstract int doPreInstall(int status); 10017 10018 /** 10019 * Rename package into final resting place. All paths on the given 10020 * scanned package should be updated to reflect the rename. 10021 */ 10022 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10023 abstract int doPostInstall(int status, int uid); 10024 10025 /** @see PackageSettingBase#codePathString */ 10026 abstract String getCodePath(); 10027 /** @see PackageSettingBase#resourcePathString */ 10028 abstract String getResourcePath(); 10029 10030 // Need installer lock especially for dex file removal. 10031 abstract void cleanUpResourcesLI(); 10032 abstract boolean doPostDeleteLI(boolean delete); 10033 10034 /** 10035 * Called before the source arguments are copied. This is used mostly 10036 * for MoveParams when it needs to read the source file to put it in the 10037 * destination. 10038 */ 10039 int doPreCopy() { 10040 return PackageManager.INSTALL_SUCCEEDED; 10041 } 10042 10043 /** 10044 * Called after the source arguments are copied. This is used mostly for 10045 * MoveParams when it needs to read the source file to put it in the 10046 * destination. 10047 * 10048 * @return 10049 */ 10050 int doPostCopy(int uid) { 10051 return PackageManager.INSTALL_SUCCEEDED; 10052 } 10053 10054 protected boolean isFwdLocked() { 10055 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10056 } 10057 10058 protected boolean isExternalAsec() { 10059 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10060 } 10061 10062 UserHandle getUser() { 10063 return user; 10064 } 10065 } 10066 10067 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10068 if (!allCodePaths.isEmpty()) { 10069 if (instructionSets == null) { 10070 throw new IllegalStateException("instructionSet == null"); 10071 } 10072 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10073 for (String codePath : allCodePaths) { 10074 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10075 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10076 if (retCode < 0) { 10077 Slog.w(TAG, "Couldn't remove dex file for package: " 10078 + " at location " + codePath + ", retcode=" + retCode); 10079 // we don't consider this to be a failure of the core package deletion 10080 } 10081 } 10082 } 10083 } 10084 } 10085 10086 /** 10087 * Logic to handle installation of non-ASEC applications, including copying 10088 * and renaming logic. 10089 */ 10090 class FileInstallArgs extends InstallArgs { 10091 private File codeFile; 10092 private File resourceFile; 10093 10094 // Example topology: 10095 // /data/app/com.example/base.apk 10096 // /data/app/com.example/split_foo.apk 10097 // /data/app/com.example/lib/arm/libfoo.so 10098 // /data/app/com.example/lib/arm64/libfoo.so 10099 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10100 10101 /** New install */ 10102 FileInstallArgs(InstallParams params) { 10103 super(params.origin, params.move, params.observer, params.installFlags, 10104 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10105 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10106 if (isFwdLocked()) { 10107 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10108 } 10109 } 10110 10111 /** Existing install */ 10112 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10113 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10114 null); 10115 this.codeFile = (codePath != null) ? new File(codePath) : null; 10116 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10117 } 10118 10119 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10120 if (origin.staged) { 10121 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10122 codeFile = origin.file; 10123 resourceFile = origin.file; 10124 return PackageManager.INSTALL_SUCCEEDED; 10125 } 10126 10127 try { 10128 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10129 codeFile = tempDir; 10130 resourceFile = tempDir; 10131 } catch (IOException e) { 10132 Slog.w(TAG, "Failed to create copy file: " + e); 10133 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10134 } 10135 10136 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10137 @Override 10138 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10139 if (!FileUtils.isValidExtFilename(name)) { 10140 throw new IllegalArgumentException("Invalid filename: " + name); 10141 } 10142 try { 10143 final File file = new File(codeFile, name); 10144 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10145 O_RDWR | O_CREAT, 0644); 10146 Os.chmod(file.getAbsolutePath(), 0644); 10147 return new ParcelFileDescriptor(fd); 10148 } catch (ErrnoException e) { 10149 throw new RemoteException("Failed to open: " + e.getMessage()); 10150 } 10151 } 10152 }; 10153 10154 int ret = PackageManager.INSTALL_SUCCEEDED; 10155 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10156 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10157 Slog.e(TAG, "Failed to copy package"); 10158 return ret; 10159 } 10160 10161 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10162 NativeLibraryHelper.Handle handle = null; 10163 try { 10164 handle = NativeLibraryHelper.Handle.create(codeFile); 10165 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10166 abiOverride); 10167 } catch (IOException e) { 10168 Slog.e(TAG, "Copying native libraries failed", e); 10169 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10170 } finally { 10171 IoUtils.closeQuietly(handle); 10172 } 10173 10174 return ret; 10175 } 10176 10177 int doPreInstall(int status) { 10178 if (status != PackageManager.INSTALL_SUCCEEDED) { 10179 cleanUp(); 10180 } 10181 return status; 10182 } 10183 10184 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10185 if (status != PackageManager.INSTALL_SUCCEEDED) { 10186 cleanUp(); 10187 return false; 10188 } 10189 10190 final File targetDir = codeFile.getParentFile(); 10191 final File beforeCodeFile = codeFile; 10192 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10193 10194 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10195 try { 10196 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10197 } catch (ErrnoException e) { 10198 Slog.d(TAG, "Failed to rename", e); 10199 return false; 10200 } 10201 10202 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10203 Slog.d(TAG, "Failed to restorecon"); 10204 return false; 10205 } 10206 10207 // Reflect the rename internally 10208 codeFile = afterCodeFile; 10209 resourceFile = afterCodeFile; 10210 10211 // Reflect the rename in scanned details 10212 pkg.codePath = afterCodeFile.getAbsolutePath(); 10213 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10214 pkg.baseCodePath); 10215 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10216 pkg.splitCodePaths); 10217 10218 // Reflect the rename in app info 10219 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10220 pkg.applicationInfo.setCodePath(pkg.codePath); 10221 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10222 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10223 pkg.applicationInfo.setResourcePath(pkg.codePath); 10224 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10225 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10226 10227 return true; 10228 } 10229 10230 int doPostInstall(int status, int uid) { 10231 if (status != PackageManager.INSTALL_SUCCEEDED) { 10232 cleanUp(); 10233 } 10234 return status; 10235 } 10236 10237 @Override 10238 String getCodePath() { 10239 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10240 } 10241 10242 @Override 10243 String getResourcePath() { 10244 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10245 } 10246 10247 private boolean cleanUp() { 10248 if (codeFile == null || !codeFile.exists()) { 10249 return false; 10250 } 10251 10252 if (codeFile.isDirectory()) { 10253 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10254 } else { 10255 codeFile.delete(); 10256 } 10257 10258 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10259 resourceFile.delete(); 10260 } 10261 10262 return true; 10263 } 10264 10265 void cleanUpResourcesLI() { 10266 // Try enumerating all code paths before deleting 10267 List<String> allCodePaths = Collections.EMPTY_LIST; 10268 if (codeFile != null && codeFile.exists()) { 10269 try { 10270 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10271 allCodePaths = pkg.getAllCodePaths(); 10272 } catch (PackageParserException e) { 10273 // Ignored; we tried our best 10274 } 10275 } 10276 10277 cleanUp(); 10278 removeDexFiles(allCodePaths, instructionSets); 10279 } 10280 10281 boolean doPostDeleteLI(boolean delete) { 10282 // XXX err, shouldn't we respect the delete flag? 10283 cleanUpResourcesLI(); 10284 return true; 10285 } 10286 } 10287 10288 private boolean isAsecExternal(String cid) { 10289 final String asecPath = PackageHelper.getSdFilesystem(cid); 10290 return !asecPath.startsWith(mAsecInternalPath); 10291 } 10292 10293 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10294 PackageManagerException { 10295 if (copyRet < 0) { 10296 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10297 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10298 throw new PackageManagerException(copyRet, message); 10299 } 10300 } 10301 } 10302 10303 /** 10304 * Extract the MountService "container ID" from the full code path of an 10305 * .apk. 10306 */ 10307 static String cidFromCodePath(String fullCodePath) { 10308 int eidx = fullCodePath.lastIndexOf("/"); 10309 String subStr1 = fullCodePath.substring(0, eidx); 10310 int sidx = subStr1.lastIndexOf("/"); 10311 return subStr1.substring(sidx+1, eidx); 10312 } 10313 10314 /** 10315 * Logic to handle installation of ASEC applications, including copying and 10316 * renaming logic. 10317 */ 10318 class AsecInstallArgs extends InstallArgs { 10319 static final String RES_FILE_NAME = "pkg.apk"; 10320 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10321 10322 String cid; 10323 String packagePath; 10324 String resourcePath; 10325 10326 /** New install */ 10327 AsecInstallArgs(InstallParams params) { 10328 super(params.origin, params.move, params.observer, params.installFlags, 10329 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10330 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10331 } 10332 10333 /** Existing install */ 10334 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10335 boolean isExternal, boolean isForwardLocked) { 10336 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10337 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10338 instructionSets, null); 10339 // Hackily pretend we're still looking at a full code path 10340 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10341 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10342 } 10343 10344 // Extract cid from fullCodePath 10345 int eidx = fullCodePath.lastIndexOf("/"); 10346 String subStr1 = fullCodePath.substring(0, eidx); 10347 int sidx = subStr1.lastIndexOf("/"); 10348 cid = subStr1.substring(sidx+1, eidx); 10349 setMountPath(subStr1); 10350 } 10351 10352 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10353 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10354 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10355 instructionSets, null); 10356 this.cid = cid; 10357 setMountPath(PackageHelper.getSdDir(cid)); 10358 } 10359 10360 void createCopyFile() { 10361 cid = mInstallerService.allocateExternalStageCidLegacy(); 10362 } 10363 10364 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10365 if (origin.staged) { 10366 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10367 cid = origin.cid; 10368 setMountPath(PackageHelper.getSdDir(cid)); 10369 return PackageManager.INSTALL_SUCCEEDED; 10370 } 10371 10372 if (temp) { 10373 createCopyFile(); 10374 } else { 10375 /* 10376 * Pre-emptively destroy the container since it's destroyed if 10377 * copying fails due to it existing anyway. 10378 */ 10379 PackageHelper.destroySdDir(cid); 10380 } 10381 10382 final String newMountPath = imcs.copyPackageToContainer( 10383 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10384 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10385 10386 if (newMountPath != null) { 10387 setMountPath(newMountPath); 10388 return PackageManager.INSTALL_SUCCEEDED; 10389 } else { 10390 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10391 } 10392 } 10393 10394 @Override 10395 String getCodePath() { 10396 return packagePath; 10397 } 10398 10399 @Override 10400 String getResourcePath() { 10401 return resourcePath; 10402 } 10403 10404 int doPreInstall(int status) { 10405 if (status != PackageManager.INSTALL_SUCCEEDED) { 10406 // Destroy container 10407 PackageHelper.destroySdDir(cid); 10408 } else { 10409 boolean mounted = PackageHelper.isContainerMounted(cid); 10410 if (!mounted) { 10411 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10412 Process.SYSTEM_UID); 10413 if (newMountPath != null) { 10414 setMountPath(newMountPath); 10415 } else { 10416 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10417 } 10418 } 10419 } 10420 return status; 10421 } 10422 10423 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10424 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10425 String newMountPath = null; 10426 if (PackageHelper.isContainerMounted(cid)) { 10427 // Unmount the container 10428 if (!PackageHelper.unMountSdDir(cid)) { 10429 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10430 return false; 10431 } 10432 } 10433 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10434 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10435 " which might be stale. Will try to clean up."); 10436 // Clean up the stale container and proceed to recreate. 10437 if (!PackageHelper.destroySdDir(newCacheId)) { 10438 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10439 return false; 10440 } 10441 // Successfully cleaned up stale container. Try to rename again. 10442 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10443 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10444 + " inspite of cleaning it up."); 10445 return false; 10446 } 10447 } 10448 if (!PackageHelper.isContainerMounted(newCacheId)) { 10449 Slog.w(TAG, "Mounting container " + newCacheId); 10450 newMountPath = PackageHelper.mountSdDir(newCacheId, 10451 getEncryptKey(), Process.SYSTEM_UID); 10452 } else { 10453 newMountPath = PackageHelper.getSdDir(newCacheId); 10454 } 10455 if (newMountPath == null) { 10456 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10457 return false; 10458 } 10459 Log.i(TAG, "Succesfully renamed " + cid + 10460 " to " + newCacheId + 10461 " at new path: " + newMountPath); 10462 cid = newCacheId; 10463 10464 final File beforeCodeFile = new File(packagePath); 10465 setMountPath(newMountPath); 10466 final File afterCodeFile = new File(packagePath); 10467 10468 // Reflect the rename in scanned details 10469 pkg.codePath = afterCodeFile.getAbsolutePath(); 10470 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10471 pkg.baseCodePath); 10472 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10473 pkg.splitCodePaths); 10474 10475 // Reflect the rename in app info 10476 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10477 pkg.applicationInfo.setCodePath(pkg.codePath); 10478 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10479 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10480 pkg.applicationInfo.setResourcePath(pkg.codePath); 10481 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10482 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10483 10484 return true; 10485 } 10486 10487 private void setMountPath(String mountPath) { 10488 final File mountFile = new File(mountPath); 10489 10490 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10491 if (monolithicFile.exists()) { 10492 packagePath = monolithicFile.getAbsolutePath(); 10493 if (isFwdLocked()) { 10494 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10495 } else { 10496 resourcePath = packagePath; 10497 } 10498 } else { 10499 packagePath = mountFile.getAbsolutePath(); 10500 resourcePath = packagePath; 10501 } 10502 } 10503 10504 int doPostInstall(int status, int uid) { 10505 if (status != PackageManager.INSTALL_SUCCEEDED) { 10506 cleanUp(); 10507 } else { 10508 final int groupOwner; 10509 final String protectedFile; 10510 if (isFwdLocked()) { 10511 groupOwner = UserHandle.getSharedAppGid(uid); 10512 protectedFile = RES_FILE_NAME; 10513 } else { 10514 groupOwner = -1; 10515 protectedFile = null; 10516 } 10517 10518 if (uid < Process.FIRST_APPLICATION_UID 10519 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10520 Slog.e(TAG, "Failed to finalize " + cid); 10521 PackageHelper.destroySdDir(cid); 10522 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10523 } 10524 10525 boolean mounted = PackageHelper.isContainerMounted(cid); 10526 if (!mounted) { 10527 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10528 } 10529 } 10530 return status; 10531 } 10532 10533 private void cleanUp() { 10534 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10535 10536 // Destroy secure container 10537 PackageHelper.destroySdDir(cid); 10538 } 10539 10540 private List<String> getAllCodePaths() { 10541 final File codeFile = new File(getCodePath()); 10542 if (codeFile != null && codeFile.exists()) { 10543 try { 10544 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10545 return pkg.getAllCodePaths(); 10546 } catch (PackageParserException e) { 10547 // Ignored; we tried our best 10548 } 10549 } 10550 return Collections.EMPTY_LIST; 10551 } 10552 10553 void cleanUpResourcesLI() { 10554 // Enumerate all code paths before deleting 10555 cleanUpResourcesLI(getAllCodePaths()); 10556 } 10557 10558 private void cleanUpResourcesLI(List<String> allCodePaths) { 10559 cleanUp(); 10560 removeDexFiles(allCodePaths, instructionSets); 10561 } 10562 10563 String getPackageName() { 10564 return getAsecPackageName(cid); 10565 } 10566 10567 boolean doPostDeleteLI(boolean delete) { 10568 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10569 final List<String> allCodePaths = getAllCodePaths(); 10570 boolean mounted = PackageHelper.isContainerMounted(cid); 10571 if (mounted) { 10572 // Unmount first 10573 if (PackageHelper.unMountSdDir(cid)) { 10574 mounted = false; 10575 } 10576 } 10577 if (!mounted && delete) { 10578 cleanUpResourcesLI(allCodePaths); 10579 } 10580 return !mounted; 10581 } 10582 10583 @Override 10584 int doPreCopy() { 10585 if (isFwdLocked()) { 10586 if (!PackageHelper.fixSdPermissions(cid, 10587 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10588 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10589 } 10590 } 10591 10592 return PackageManager.INSTALL_SUCCEEDED; 10593 } 10594 10595 @Override 10596 int doPostCopy(int uid) { 10597 if (isFwdLocked()) { 10598 if (uid < Process.FIRST_APPLICATION_UID 10599 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10600 RES_FILE_NAME)) { 10601 Slog.e(TAG, "Failed to finalize " + cid); 10602 PackageHelper.destroySdDir(cid); 10603 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10604 } 10605 } 10606 10607 return PackageManager.INSTALL_SUCCEEDED; 10608 } 10609 } 10610 10611 /** 10612 * Logic to handle movement of existing installed applications. 10613 */ 10614 class MoveInstallArgs extends InstallArgs { 10615 private File codeFile; 10616 private File resourceFile; 10617 10618 /** New install */ 10619 MoveInstallArgs(InstallParams params) { 10620 super(params.origin, params.move, params.observer, params.installFlags, 10621 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10622 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10623 } 10624 10625 int copyApk(IMediaContainerService imcs, boolean temp) { 10626 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10627 + move.toUuid); 10628 synchronized (mInstaller) { 10629 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10630 move.dataAppName, move.appId, move.seinfo) != 0) { 10631 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10632 } 10633 } 10634 10635 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10636 resourceFile = codeFile; 10637 Slog.d(TAG, "codeFile after move is " + codeFile); 10638 10639 return PackageManager.INSTALL_SUCCEEDED; 10640 } 10641 10642 int doPreInstall(int status) { 10643 if (status != PackageManager.INSTALL_SUCCEEDED) { 10644 cleanUp(); 10645 } 10646 return status; 10647 } 10648 10649 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10650 if (status != PackageManager.INSTALL_SUCCEEDED) { 10651 cleanUp(); 10652 return false; 10653 } 10654 10655 // Reflect the move in app info 10656 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10657 pkg.applicationInfo.setCodePath(pkg.codePath); 10658 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10659 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10660 pkg.applicationInfo.setResourcePath(pkg.codePath); 10661 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10662 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10663 10664 return true; 10665 } 10666 10667 int doPostInstall(int status, int uid) { 10668 if (status != PackageManager.INSTALL_SUCCEEDED) { 10669 cleanUp(); 10670 } 10671 return status; 10672 } 10673 10674 @Override 10675 String getCodePath() { 10676 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10677 } 10678 10679 @Override 10680 String getResourcePath() { 10681 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10682 } 10683 10684 private boolean cleanUp() { 10685 if (codeFile == null || !codeFile.exists()) { 10686 return false; 10687 } 10688 10689 if (codeFile.isDirectory()) { 10690 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10691 } else { 10692 codeFile.delete(); 10693 } 10694 10695 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10696 resourceFile.delete(); 10697 } 10698 10699 return true; 10700 } 10701 10702 void cleanUpResourcesLI() { 10703 cleanUp(); 10704 } 10705 10706 boolean doPostDeleteLI(boolean delete) { 10707 // XXX err, shouldn't we respect the delete flag? 10708 cleanUpResourcesLI(); 10709 return true; 10710 } 10711 } 10712 10713 static String getAsecPackageName(String packageCid) { 10714 int idx = packageCid.lastIndexOf("-"); 10715 if (idx == -1) { 10716 return packageCid; 10717 } 10718 return packageCid.substring(0, idx); 10719 } 10720 10721 // Utility method used to create code paths based on package name and available index. 10722 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10723 String idxStr = ""; 10724 int idx = 1; 10725 // Fall back to default value of idx=1 if prefix is not 10726 // part of oldCodePath 10727 if (oldCodePath != null) { 10728 String subStr = oldCodePath; 10729 // Drop the suffix right away 10730 if (suffix != null && subStr.endsWith(suffix)) { 10731 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10732 } 10733 // If oldCodePath already contains prefix find out the 10734 // ending index to either increment or decrement. 10735 int sidx = subStr.lastIndexOf(prefix); 10736 if (sidx != -1) { 10737 subStr = subStr.substring(sidx + prefix.length()); 10738 if (subStr != null) { 10739 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10740 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10741 } 10742 try { 10743 idx = Integer.parseInt(subStr); 10744 if (idx <= 1) { 10745 idx++; 10746 } else { 10747 idx--; 10748 } 10749 } catch(NumberFormatException e) { 10750 } 10751 } 10752 } 10753 } 10754 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10755 return prefix + idxStr; 10756 } 10757 10758 private File getNextCodePath(File targetDir, String packageName) { 10759 int suffix = 1; 10760 File result; 10761 do { 10762 result = new File(targetDir, packageName + "-" + suffix); 10763 suffix++; 10764 } while (result.exists()); 10765 return result; 10766 } 10767 10768 // Utility method that returns the relative package path with respect 10769 // to the installation directory. Like say for /data/data/com.test-1.apk 10770 // string com.test-1 is returned. 10771 static String deriveCodePathName(String codePath) { 10772 if (codePath == null) { 10773 return null; 10774 } 10775 final File codeFile = new File(codePath); 10776 final String name = codeFile.getName(); 10777 if (codeFile.isDirectory()) { 10778 return name; 10779 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10780 final int lastDot = name.lastIndexOf('.'); 10781 return name.substring(0, lastDot); 10782 } else { 10783 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10784 return null; 10785 } 10786 } 10787 10788 class PackageInstalledInfo { 10789 String name; 10790 int uid; 10791 // The set of users that originally had this package installed. 10792 int[] origUsers; 10793 // The set of users that now have this package installed. 10794 int[] newUsers; 10795 PackageParser.Package pkg; 10796 int returnCode; 10797 String returnMsg; 10798 PackageRemovedInfo removedInfo; 10799 10800 public void setError(int code, String msg) { 10801 returnCode = code; 10802 returnMsg = msg; 10803 Slog.w(TAG, msg); 10804 } 10805 10806 public void setError(String msg, PackageParserException e) { 10807 returnCode = e.error; 10808 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10809 Slog.w(TAG, msg, e); 10810 } 10811 10812 public void setError(String msg, PackageManagerException e) { 10813 returnCode = e.error; 10814 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10815 Slog.w(TAG, msg, e); 10816 } 10817 10818 // In some error cases we want to convey more info back to the observer 10819 String origPackage; 10820 String origPermission; 10821 } 10822 10823 /* 10824 * Install a non-existing package. 10825 */ 10826 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10827 UserHandle user, String installerPackageName, String volumeUuid, 10828 PackageInstalledInfo res) { 10829 // Remember this for later, in case we need to rollback this install 10830 String pkgName = pkg.packageName; 10831 10832 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10833 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10834 UserHandle.USER_OWNER).exists(); 10835 synchronized(mPackages) { 10836 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10837 // A package with the same name is already installed, though 10838 // it has been renamed to an older name. The package we 10839 // are trying to install should be installed as an update to 10840 // the existing one, but that has not been requested, so bail. 10841 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10842 + " without first uninstalling package running as " 10843 + mSettings.mRenamedPackages.get(pkgName)); 10844 return; 10845 } 10846 if (mPackages.containsKey(pkgName)) { 10847 // Don't allow installation over an existing package with the same name. 10848 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10849 + " without first uninstalling."); 10850 return; 10851 } 10852 } 10853 10854 try { 10855 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10856 System.currentTimeMillis(), user); 10857 10858 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10859 // delete the partially installed application. the data directory will have to be 10860 // restored if it was already existing 10861 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10862 // remove package from internal structures. Note that we want deletePackageX to 10863 // delete the package data and cache directories that it created in 10864 // scanPackageLocked, unless those directories existed before we even tried to 10865 // install. 10866 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10867 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10868 res.removedInfo, true); 10869 } 10870 10871 } catch (PackageManagerException e) { 10872 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10873 } 10874 } 10875 10876 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10877 // Upgrade keysets are being used. Determine if new package has a superset of the 10878 // required keys. 10879 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10880 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10881 for (int i = 0; i < upgradeKeySets.length; i++) { 10882 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10883 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10884 return true; 10885 } 10886 } 10887 return false; 10888 } 10889 10890 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10891 UserHandle user, String installerPackageName, String volumeUuid, 10892 PackageInstalledInfo res) { 10893 final PackageParser.Package oldPackage; 10894 final String pkgName = pkg.packageName; 10895 final int[] allUsers; 10896 final boolean[] perUserInstalled; 10897 final boolean weFroze; 10898 10899 // First find the old package info and check signatures 10900 synchronized(mPackages) { 10901 oldPackage = mPackages.get(pkgName); 10902 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10903 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10904 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10905 // default to original signature matching 10906 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10907 != PackageManager.SIGNATURE_MATCH) { 10908 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10909 "New package has a different signature: " + pkgName); 10910 return; 10911 } 10912 } else { 10913 if(!checkUpgradeKeySetLP(ps, pkg)) { 10914 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10915 "New package not signed by keys specified by upgrade-keysets: " 10916 + pkgName); 10917 return; 10918 } 10919 } 10920 10921 // In case of rollback, remember per-user/profile install state 10922 allUsers = sUserManager.getUserIds(); 10923 perUserInstalled = new boolean[allUsers.length]; 10924 for (int i = 0; i < allUsers.length; i++) { 10925 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10926 } 10927 10928 // Mark the app as frozen to prevent launching during the upgrade 10929 // process, and then kill all running instances 10930 if (!ps.frozen) { 10931 ps.frozen = true; 10932 weFroze = true; 10933 } else { 10934 weFroze = false; 10935 } 10936 } 10937 10938 // Now that we're guarded by frozen state, kill app during upgrade 10939 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 10940 10941 try { 10942 boolean sysPkg = (isSystemApp(oldPackage)); 10943 if (sysPkg) { 10944 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10945 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10946 } else { 10947 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10948 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10949 } 10950 } finally { 10951 // Regardless of success or failure of upgrade steps above, always 10952 // unfreeze the package if we froze it 10953 if (weFroze) { 10954 unfreezePackage(pkgName); 10955 } 10956 } 10957 } 10958 10959 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10960 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10961 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10962 String volumeUuid, PackageInstalledInfo res) { 10963 String pkgName = deletedPackage.packageName; 10964 boolean deletedPkg = true; 10965 boolean updatedSettings = false; 10966 10967 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10968 + deletedPackage); 10969 long origUpdateTime; 10970 if (pkg.mExtras != null) { 10971 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10972 } else { 10973 origUpdateTime = 0; 10974 } 10975 10976 // First delete the existing package while retaining the data directory 10977 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10978 res.removedInfo, true)) { 10979 // If the existing package wasn't successfully deleted 10980 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10981 deletedPkg = false; 10982 } else { 10983 // Successfully deleted the old package; proceed with replace. 10984 10985 // If deleted package lived in a container, give users a chance to 10986 // relinquish resources before killing. 10987 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10988 if (DEBUG_INSTALL) { 10989 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10990 } 10991 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10992 final ArrayList<String> pkgList = new ArrayList<String>(1); 10993 pkgList.add(deletedPackage.applicationInfo.packageName); 10994 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10995 } 10996 10997 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10998 try { 10999 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11000 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11001 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11002 perUserInstalled, res, user); 11003 updatedSettings = true; 11004 } catch (PackageManagerException e) { 11005 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11006 } 11007 } 11008 11009 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11010 // remove package from internal structures. Note that we want deletePackageX to 11011 // delete the package data and cache directories that it created in 11012 // scanPackageLocked, unless those directories existed before we even tried to 11013 // install. 11014 if(updatedSettings) { 11015 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11016 deletePackageLI( 11017 pkgName, null, true, allUsers, perUserInstalled, 11018 PackageManager.DELETE_KEEP_DATA, 11019 res.removedInfo, true); 11020 } 11021 // Since we failed to install the new package we need to restore the old 11022 // package that we deleted. 11023 if (deletedPkg) { 11024 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11025 File restoreFile = new File(deletedPackage.codePath); 11026 // Parse old package 11027 boolean oldExternal = isExternal(deletedPackage); 11028 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11029 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11030 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11031 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11032 try { 11033 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11034 } catch (PackageManagerException e) { 11035 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11036 + e.getMessage()); 11037 return; 11038 } 11039 // Restore of old package succeeded. Update permissions. 11040 // writer 11041 synchronized (mPackages) { 11042 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11043 UPDATE_PERMISSIONS_ALL); 11044 // can downgrade to reader 11045 mSettings.writeLPr(); 11046 } 11047 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11048 } 11049 } 11050 } 11051 11052 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11053 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11054 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11055 String volumeUuid, PackageInstalledInfo res) { 11056 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11057 + ", old=" + deletedPackage); 11058 boolean disabledSystem = false; 11059 boolean updatedSettings = false; 11060 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11061 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11062 != 0) { 11063 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11064 } 11065 String packageName = deletedPackage.packageName; 11066 if (packageName == null) { 11067 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11068 "Attempt to delete null packageName."); 11069 return; 11070 } 11071 PackageParser.Package oldPkg; 11072 PackageSetting oldPkgSetting; 11073 // reader 11074 synchronized (mPackages) { 11075 oldPkg = mPackages.get(packageName); 11076 oldPkgSetting = mSettings.mPackages.get(packageName); 11077 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11078 (oldPkgSetting == null)) { 11079 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11080 "Couldn't find package:" + packageName + " information"); 11081 return; 11082 } 11083 } 11084 11085 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11086 res.removedInfo.removedPackage = packageName; 11087 // Remove existing system package 11088 removePackageLI(oldPkgSetting, true); 11089 // writer 11090 synchronized (mPackages) { 11091 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11092 if (!disabledSystem && deletedPackage != null) { 11093 // We didn't need to disable the .apk as a current system package, 11094 // which means we are replacing another update that is already 11095 // installed. We need to make sure to delete the older one's .apk. 11096 res.removedInfo.args = createInstallArgsForExisting(0, 11097 deletedPackage.applicationInfo.getCodePath(), 11098 deletedPackage.applicationInfo.getResourcePath(), 11099 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11100 } else { 11101 res.removedInfo.args = null; 11102 } 11103 } 11104 11105 // Successfully disabled the old package. Now proceed with re-installation 11106 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11107 11108 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11109 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11110 11111 PackageParser.Package newPackage = null; 11112 try { 11113 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11114 if (newPackage.mExtras != null) { 11115 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11116 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11117 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11118 11119 // is the update attempting to change shared user? that isn't going to work... 11120 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11121 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11122 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11123 + " to " + newPkgSetting.sharedUser); 11124 updatedSettings = true; 11125 } 11126 } 11127 11128 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11129 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11130 perUserInstalled, res, user); 11131 updatedSettings = true; 11132 } 11133 11134 } catch (PackageManagerException e) { 11135 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11136 } 11137 11138 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11139 // Re installation failed. Restore old information 11140 // Remove new pkg information 11141 if (newPackage != null) { 11142 removeInstalledPackageLI(newPackage, true); 11143 } 11144 // Add back the old system package 11145 try { 11146 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11147 } catch (PackageManagerException e) { 11148 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11149 } 11150 // Restore the old system information in Settings 11151 synchronized (mPackages) { 11152 if (disabledSystem) { 11153 mSettings.enableSystemPackageLPw(packageName); 11154 } 11155 if (updatedSettings) { 11156 mSettings.setInstallerPackageName(packageName, 11157 oldPkgSetting.installerPackageName); 11158 } 11159 mSettings.writeLPr(); 11160 } 11161 } 11162 } 11163 11164 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11165 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11166 UserHandle user) { 11167 String pkgName = newPackage.packageName; 11168 synchronized (mPackages) { 11169 //write settings. the installStatus will be incomplete at this stage. 11170 //note that the new package setting would have already been 11171 //added to mPackages. It hasn't been persisted yet. 11172 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11173 mSettings.writeLPr(); 11174 } 11175 11176 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11177 11178 synchronized (mPackages) { 11179 updatePermissionsLPw(newPackage.packageName, newPackage, 11180 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11181 ? UPDATE_PERMISSIONS_ALL : 0)); 11182 // For system-bundled packages, we assume that installing an upgraded version 11183 // of the package implies that the user actually wants to run that new code, 11184 // so we enable the package. 11185 PackageSetting ps = mSettings.mPackages.get(pkgName); 11186 if (ps != null) { 11187 if (isSystemApp(newPackage)) { 11188 // NB: implicit assumption that system package upgrades apply to all users 11189 if (DEBUG_INSTALL) { 11190 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11191 } 11192 if (res.origUsers != null) { 11193 for (int userHandle : res.origUsers) { 11194 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11195 userHandle, installerPackageName); 11196 } 11197 } 11198 // Also convey the prior install/uninstall state 11199 if (allUsers != null && perUserInstalled != null) { 11200 for (int i = 0; i < allUsers.length; i++) { 11201 if (DEBUG_INSTALL) { 11202 Slog.d(TAG, " user " + allUsers[i] 11203 + " => " + perUserInstalled[i]); 11204 } 11205 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11206 } 11207 // these install state changes will be persisted in the 11208 // upcoming call to mSettings.writeLPr(). 11209 } 11210 } 11211 // It's implied that when a user requests installation, they want the app to be 11212 // installed and enabled. 11213 int userId = user.getIdentifier(); 11214 if (userId != UserHandle.USER_ALL) { 11215 ps.setInstalled(true, userId); 11216 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11217 } 11218 } 11219 res.name = pkgName; 11220 res.uid = newPackage.applicationInfo.uid; 11221 res.pkg = newPackage; 11222 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11223 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11224 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11225 //to update install status 11226 mSettings.writeLPr(); 11227 } 11228 } 11229 11230 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11231 final int installFlags = args.installFlags; 11232 final String installerPackageName = args.installerPackageName; 11233 final String volumeUuid = args.volumeUuid; 11234 final File tmpPackageFile = new File(args.getCodePath()); 11235 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11236 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11237 || (args.volumeUuid != null)); 11238 boolean replace = false; 11239 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11240 // Result object to be returned 11241 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11242 11243 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11244 // Retrieve PackageSettings and parse package 11245 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11246 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11247 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11248 PackageParser pp = new PackageParser(); 11249 pp.setSeparateProcesses(mSeparateProcesses); 11250 pp.setDisplayMetrics(mMetrics); 11251 11252 final PackageParser.Package pkg; 11253 try { 11254 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11255 } catch (PackageParserException e) { 11256 res.setError("Failed parse during installPackageLI", e); 11257 return; 11258 } 11259 11260 // Mark that we have an install time CPU ABI override. 11261 pkg.cpuAbiOverride = args.abiOverride; 11262 11263 String pkgName = res.name = pkg.packageName; 11264 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11265 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11266 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11267 return; 11268 } 11269 } 11270 11271 try { 11272 pp.collectCertificates(pkg, parseFlags); 11273 pp.collectManifestDigest(pkg); 11274 } catch (PackageParserException e) { 11275 res.setError("Failed collect during installPackageLI", e); 11276 return; 11277 } 11278 11279 /* If the installer passed in a manifest digest, compare it now. */ 11280 if (args.manifestDigest != null) { 11281 if (DEBUG_INSTALL) { 11282 final String parsedManifest = pkg.manifestDigest == null ? "null" 11283 : pkg.manifestDigest.toString(); 11284 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11285 + parsedManifest); 11286 } 11287 11288 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11289 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11290 return; 11291 } 11292 } else if (DEBUG_INSTALL) { 11293 final String parsedManifest = pkg.manifestDigest == null 11294 ? "null" : pkg.manifestDigest.toString(); 11295 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11296 } 11297 11298 // Get rid of all references to package scan path via parser. 11299 pp = null; 11300 String oldCodePath = null; 11301 boolean systemApp = false; 11302 synchronized (mPackages) { 11303 // Check if installing already existing package 11304 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11305 String oldName = mSettings.mRenamedPackages.get(pkgName); 11306 if (pkg.mOriginalPackages != null 11307 && pkg.mOriginalPackages.contains(oldName) 11308 && mPackages.containsKey(oldName)) { 11309 // This package is derived from an original package, 11310 // and this device has been updating from that original 11311 // name. We must continue using the original name, so 11312 // rename the new package here. 11313 pkg.setPackageName(oldName); 11314 pkgName = pkg.packageName; 11315 replace = true; 11316 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11317 + oldName + " pkgName=" + pkgName); 11318 } else if (mPackages.containsKey(pkgName)) { 11319 // This package, under its official name, already exists 11320 // on the device; we should replace it. 11321 replace = true; 11322 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11323 } 11324 } 11325 11326 PackageSetting ps = mSettings.mPackages.get(pkgName); 11327 if (ps != null) { 11328 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11329 11330 // Quick sanity check that we're signed correctly if updating; 11331 // we'll check this again later when scanning, but we want to 11332 // bail early here before tripping over redefined permissions. 11333 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11334 try { 11335 verifySignaturesLP(ps, pkg); 11336 } catch (PackageManagerException e) { 11337 res.setError(e.error, e.getMessage()); 11338 return; 11339 } 11340 } else { 11341 if (!checkUpgradeKeySetLP(ps, pkg)) { 11342 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11343 + pkg.packageName + " upgrade keys do not match the " 11344 + "previously installed version"); 11345 return; 11346 } 11347 } 11348 11349 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11350 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11351 systemApp = (ps.pkg.applicationInfo.flags & 11352 ApplicationInfo.FLAG_SYSTEM) != 0; 11353 } 11354 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11355 } 11356 11357 // Check whether the newly-scanned package wants to define an already-defined perm 11358 int N = pkg.permissions.size(); 11359 for (int i = N-1; i >= 0; i--) { 11360 PackageParser.Permission perm = pkg.permissions.get(i); 11361 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11362 if (bp != null) { 11363 // If the defining package is signed with our cert, it's okay. This 11364 // also includes the "updating the same package" case, of course. 11365 // "updating same package" could also involve key-rotation. 11366 final boolean sigsOk; 11367 if (!bp.sourcePackage.equals(pkg.packageName) 11368 || !(bp.packageSetting instanceof PackageSetting) 11369 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11370 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11371 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11372 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11373 } else { 11374 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11375 } 11376 if (!sigsOk) { 11377 // If the owning package is the system itself, we log but allow 11378 // install to proceed; we fail the install on all other permission 11379 // redefinitions. 11380 if (!bp.sourcePackage.equals("android")) { 11381 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11382 + pkg.packageName + " attempting to redeclare permission " 11383 + perm.info.name + " already owned by " + bp.sourcePackage); 11384 res.origPermission = perm.info.name; 11385 res.origPackage = bp.sourcePackage; 11386 return; 11387 } else { 11388 Slog.w(TAG, "Package " + pkg.packageName 11389 + " attempting to redeclare system permission " 11390 + perm.info.name + "; ignoring new declaration"); 11391 pkg.permissions.remove(i); 11392 } 11393 } 11394 } 11395 } 11396 11397 } 11398 11399 if (systemApp && onExternal) { 11400 // Disable updates to system apps on sdcard 11401 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11402 "Cannot install updates to system apps on sdcard"); 11403 return; 11404 } 11405 11406 if (args.move != null) { 11407 // We did an in-place move, so dex is ready to roll 11408 scanFlags |= SCAN_NO_DEX; 11409 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11410 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11411 scanFlags |= SCAN_NO_DEX; 11412 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11413 int result = mPackageDexOptimizer 11414 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11415 false /* defer */, false /* inclDependencies */); 11416 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11417 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11418 return; 11419 } 11420 } 11421 11422 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11423 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11424 return; 11425 } 11426 11427 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11428 11429 if (replace) { 11430 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11431 installerPackageName, volumeUuid, res); 11432 } else { 11433 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11434 args.user, installerPackageName, volumeUuid, res); 11435 } 11436 synchronized (mPackages) { 11437 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11438 if (ps != null) { 11439 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11440 } 11441 } 11442 } 11443 11444 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11445 if (mIntentFilterVerifierComponent == null) { 11446 Slog.d(TAG, "No IntentFilter verification will not be done as " 11447 + "there is no IntentFilterVerifier available!"); 11448 return; 11449 } 11450 11451 final int verifierUid = getPackageUid( 11452 mIntentFilterVerifierComponent.getPackageName(), 11453 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11454 11455 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11456 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11457 msg.obj = pkg; 11458 msg.arg1 = userId; 11459 msg.arg2 = verifierUid; 11460 11461 mHandler.sendMessage(msg); 11462 } 11463 11464 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11465 PackageParser.Package pkg) { 11466 int size = pkg.activities.size(); 11467 if (size == 0) { 11468 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11469 return; 11470 } 11471 11472 final boolean hasDomainURLs = hasDomainURLs(pkg); 11473 if (!hasDomainURLs) { 11474 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11475 return; 11476 } 11477 11478 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11479 + " Activities needs verification ..."); 11480 11481 final int verificationId = mIntentFilterVerificationToken++; 11482 int count = 0; 11483 final String packageName = pkg.packageName; 11484 ArrayList<String> allHosts = new ArrayList<>(); 11485 11486 synchronized (mPackages) { 11487 for (PackageParser.Activity a : pkg.activities) { 11488 for (ActivityIntentInfo filter : a.intents) { 11489 boolean needsFilterVerification = filter.needsVerification(); 11490 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11491 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11492 mIntentFilterVerifier.addOneIntentFilterVerification( 11493 verifierUid, userId, verificationId, filter, packageName); 11494 count++; 11495 } else if (!needsFilterVerification) { 11496 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11497 if (hasValidDomains(filter)) { 11498 ArrayList<String> hosts = filter.getHostsList(); 11499 if (hosts.size() > 0) { 11500 allHosts.addAll(hosts); 11501 } else { 11502 if (allHosts.isEmpty()) { 11503 allHosts.add("*"); 11504 } 11505 } 11506 } 11507 } else { 11508 Slog.d(TAG, "Verification already done for IntentFilter:" 11509 + filter.toString()); 11510 } 11511 } 11512 } 11513 } 11514 11515 if (count > 0) { 11516 mIntentFilterVerifier.startVerifications(userId); 11517 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11518 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11519 } else { 11520 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11521 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11522 packageName, allHosts) != null) { 11523 scheduleWriteSettingsLocked(); 11524 } 11525 } 11526 } 11527 11528 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11529 final ComponentName cn = filter.activity.getComponentName(); 11530 final String packageName = cn.getPackageName(); 11531 11532 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11533 packageName); 11534 if (ivi == null) { 11535 return true; 11536 } 11537 int status = ivi.getStatus(); 11538 switch (status) { 11539 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11540 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11541 return true; 11542 11543 default: 11544 // Nothing to do 11545 return false; 11546 } 11547 } 11548 11549 private static boolean isMultiArch(PackageSetting ps) { 11550 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11551 } 11552 11553 private static boolean isMultiArch(ApplicationInfo info) { 11554 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11555 } 11556 11557 private static boolean isExternal(PackageParser.Package pkg) { 11558 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11559 } 11560 11561 private static boolean isExternal(PackageSetting ps) { 11562 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11563 } 11564 11565 private static boolean isExternal(ApplicationInfo info) { 11566 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11567 } 11568 11569 private static boolean isSystemApp(PackageParser.Package pkg) { 11570 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11571 } 11572 11573 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11574 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11575 } 11576 11577 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11578 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11579 } 11580 11581 private static boolean isSystemApp(PackageSetting ps) { 11582 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11583 } 11584 11585 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11586 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11587 } 11588 11589 private int packageFlagsToInstallFlags(PackageSetting ps) { 11590 int installFlags = 0; 11591 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11592 // This existing package was an external ASEC install when we have 11593 // the external flag without a UUID 11594 installFlags |= PackageManager.INSTALL_EXTERNAL; 11595 } 11596 if (ps.isForwardLocked()) { 11597 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11598 } 11599 return installFlags; 11600 } 11601 11602 private void deleteTempPackageFiles() { 11603 final FilenameFilter filter = new FilenameFilter() { 11604 public boolean accept(File dir, String name) { 11605 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11606 } 11607 }; 11608 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11609 file.delete(); 11610 } 11611 } 11612 11613 @Override 11614 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11615 int flags) { 11616 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11617 flags); 11618 } 11619 11620 @Override 11621 public void deletePackage(final String packageName, 11622 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11623 mContext.enforceCallingOrSelfPermission( 11624 android.Manifest.permission.DELETE_PACKAGES, null); 11625 final int uid = Binder.getCallingUid(); 11626 if (UserHandle.getUserId(uid) != userId) { 11627 mContext.enforceCallingPermission( 11628 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11629 "deletePackage for user " + userId); 11630 } 11631 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11632 try { 11633 observer.onPackageDeleted(packageName, 11634 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11635 } catch (RemoteException re) { 11636 } 11637 return; 11638 } 11639 11640 boolean uninstallBlocked = false; 11641 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11642 int[] users = sUserManager.getUserIds(); 11643 for (int i = 0; i < users.length; ++i) { 11644 if (getBlockUninstallForUser(packageName, users[i])) { 11645 uninstallBlocked = true; 11646 break; 11647 } 11648 } 11649 } else { 11650 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11651 } 11652 if (uninstallBlocked) { 11653 try { 11654 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11655 null); 11656 } catch (RemoteException re) { 11657 } 11658 return; 11659 } 11660 11661 if (DEBUG_REMOVE) { 11662 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11663 } 11664 // Queue up an async operation since the package deletion may take a little while. 11665 mHandler.post(new Runnable() { 11666 public void run() { 11667 mHandler.removeCallbacks(this); 11668 final int returnCode = deletePackageX(packageName, userId, flags); 11669 if (observer != null) { 11670 try { 11671 observer.onPackageDeleted(packageName, returnCode, null); 11672 } catch (RemoteException e) { 11673 Log.i(TAG, "Observer no longer exists."); 11674 } //end catch 11675 } //end if 11676 } //end run 11677 }); 11678 } 11679 11680 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11681 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11682 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11683 try { 11684 if (dpm != null) { 11685 if (dpm.isDeviceOwner(packageName)) { 11686 return true; 11687 } 11688 int[] users; 11689 if (userId == UserHandle.USER_ALL) { 11690 users = sUserManager.getUserIds(); 11691 } else { 11692 users = new int[]{userId}; 11693 } 11694 for (int i = 0; i < users.length; ++i) { 11695 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11696 return true; 11697 } 11698 } 11699 } 11700 } catch (RemoteException e) { 11701 } 11702 return false; 11703 } 11704 11705 /** 11706 * This method is an internal method that could be get invoked either 11707 * to delete an installed package or to clean up a failed installation. 11708 * After deleting an installed package, a broadcast is sent to notify any 11709 * listeners that the package has been installed. For cleaning up a failed 11710 * installation, the broadcast is not necessary since the package's 11711 * installation wouldn't have sent the initial broadcast either 11712 * The key steps in deleting a package are 11713 * deleting the package information in internal structures like mPackages, 11714 * deleting the packages base directories through installd 11715 * updating mSettings to reflect current status 11716 * persisting settings for later use 11717 * sending a broadcast if necessary 11718 */ 11719 private int deletePackageX(String packageName, int userId, int flags) { 11720 final PackageRemovedInfo info = new PackageRemovedInfo(); 11721 final boolean res; 11722 11723 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11724 ? UserHandle.ALL : new UserHandle(userId); 11725 11726 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11727 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11728 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11729 } 11730 11731 boolean removedForAllUsers = false; 11732 boolean systemUpdate = false; 11733 11734 // for the uninstall-updates case and restricted profiles, remember the per- 11735 // userhandle installed state 11736 int[] allUsers; 11737 boolean[] perUserInstalled; 11738 synchronized (mPackages) { 11739 PackageSetting ps = mSettings.mPackages.get(packageName); 11740 allUsers = sUserManager.getUserIds(); 11741 perUserInstalled = new boolean[allUsers.length]; 11742 for (int i = 0; i < allUsers.length; i++) { 11743 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11744 } 11745 } 11746 11747 synchronized (mInstallLock) { 11748 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11749 res = deletePackageLI(packageName, removeForUser, 11750 true, allUsers, perUserInstalled, 11751 flags | REMOVE_CHATTY, info, true); 11752 systemUpdate = info.isRemovedPackageSystemUpdate; 11753 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11754 removedForAllUsers = true; 11755 } 11756 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11757 + " removedForAllUsers=" + removedForAllUsers); 11758 } 11759 11760 if (res) { 11761 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11762 11763 // If the removed package was a system update, the old system package 11764 // was re-enabled; we need to broadcast this information 11765 if (systemUpdate) { 11766 Bundle extras = new Bundle(1); 11767 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11768 ? info.removedAppId : info.uid); 11769 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11770 11771 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11772 extras, null, null, null); 11773 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11774 extras, null, null, null); 11775 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11776 null, packageName, null, null); 11777 } 11778 } 11779 // Force a gc here. 11780 Runtime.getRuntime().gc(); 11781 // Delete the resources here after sending the broadcast to let 11782 // other processes clean up before deleting resources. 11783 if (info.args != null) { 11784 synchronized (mInstallLock) { 11785 info.args.doPostDeleteLI(true); 11786 } 11787 } 11788 11789 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11790 } 11791 11792 class PackageRemovedInfo { 11793 String removedPackage; 11794 int uid = -1; 11795 int removedAppId = -1; 11796 int[] removedUsers = null; 11797 boolean isRemovedPackageSystemUpdate = false; 11798 // Clean up resources deleted packages. 11799 InstallArgs args = null; 11800 11801 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11802 Bundle extras = new Bundle(1); 11803 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11804 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11805 if (replacing) { 11806 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11807 } 11808 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11809 if (removedPackage != null) { 11810 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11811 extras, null, null, removedUsers); 11812 if (fullRemove && !replacing) { 11813 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11814 extras, null, null, removedUsers); 11815 } 11816 } 11817 if (removedAppId >= 0) { 11818 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11819 removedUsers); 11820 } 11821 } 11822 } 11823 11824 /* 11825 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11826 * flag is not set, the data directory is removed as well. 11827 * make sure this flag is set for partially installed apps. If not its meaningless to 11828 * delete a partially installed application. 11829 */ 11830 private void removePackageDataLI(PackageSetting ps, 11831 int[] allUserHandles, boolean[] perUserInstalled, 11832 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11833 String packageName = ps.name; 11834 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11835 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11836 // Retrieve object to delete permissions for shared user later on 11837 final PackageSetting deletedPs; 11838 // reader 11839 synchronized (mPackages) { 11840 deletedPs = mSettings.mPackages.get(packageName); 11841 if (outInfo != null) { 11842 outInfo.removedPackage = packageName; 11843 outInfo.removedUsers = deletedPs != null 11844 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11845 : null; 11846 } 11847 } 11848 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11849 removeDataDirsLI(ps.volumeUuid, packageName); 11850 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11851 } 11852 // writer 11853 synchronized (mPackages) { 11854 if (deletedPs != null) { 11855 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11856 if (outInfo != null) { 11857 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11858 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11859 } 11860 updatePermissionsLPw(deletedPs.name, null, 0); 11861 if (deletedPs.sharedUser != null) { 11862 // Remove permissions associated with package. Since runtime 11863 // permissions are per user we have to kill the removed package 11864 // or packages running under the shared user of the removed 11865 // package if revoking the permissions requested only by the removed 11866 // package is successful and this causes a change in gids. 11867 for (int userId : UserManagerService.getInstance().getUserIds()) { 11868 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11869 userId); 11870 if (userIdToKill == UserHandle.USER_ALL 11871 || userIdToKill >= UserHandle.USER_OWNER) { 11872 // If gids changed for this user, kill all affected packages. 11873 mHandler.post(new Runnable() { 11874 @Override 11875 public void run() { 11876 // This has to happen with no lock held. 11877 killSettingPackagesForUser(deletedPs, userIdToKill, 11878 KILL_APP_REASON_GIDS_CHANGED); 11879 } 11880 }); 11881 break; 11882 } 11883 } 11884 } 11885 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11886 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11887 } 11888 // make sure to preserve per-user disabled state if this removal was just 11889 // a downgrade of a system app to the factory package 11890 if (allUserHandles != null && perUserInstalled != null) { 11891 if (DEBUG_REMOVE) { 11892 Slog.d(TAG, "Propagating install state across downgrade"); 11893 } 11894 for (int i = 0; i < allUserHandles.length; i++) { 11895 if (DEBUG_REMOVE) { 11896 Slog.d(TAG, " user " + allUserHandles[i] 11897 + " => " + perUserInstalled[i]); 11898 } 11899 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11900 } 11901 } 11902 } 11903 // can downgrade to reader 11904 if (writeSettings) { 11905 // Save settings now 11906 mSettings.writeLPr(); 11907 } 11908 } 11909 if (outInfo != null) { 11910 // A user ID was deleted here. Go through all users and remove it 11911 // from KeyStore. 11912 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11913 } 11914 } 11915 11916 static boolean locationIsPrivileged(File path) { 11917 try { 11918 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11919 .getCanonicalPath(); 11920 return path.getCanonicalPath().startsWith(privilegedAppDir); 11921 } catch (IOException e) { 11922 Slog.e(TAG, "Unable to access code path " + path); 11923 } 11924 return false; 11925 } 11926 11927 /* 11928 * Tries to delete system package. 11929 */ 11930 private boolean deleteSystemPackageLI(PackageSetting newPs, 11931 int[] allUserHandles, boolean[] perUserInstalled, 11932 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11933 final boolean applyUserRestrictions 11934 = (allUserHandles != null) && (perUserInstalled != null); 11935 PackageSetting disabledPs = null; 11936 // Confirm if the system package has been updated 11937 // An updated system app can be deleted. This will also have to restore 11938 // the system pkg from system partition 11939 // reader 11940 synchronized (mPackages) { 11941 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11942 } 11943 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11944 + " disabledPs=" + disabledPs); 11945 if (disabledPs == null) { 11946 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11947 return false; 11948 } else if (DEBUG_REMOVE) { 11949 Slog.d(TAG, "Deleting system pkg from data partition"); 11950 } 11951 if (DEBUG_REMOVE) { 11952 if (applyUserRestrictions) { 11953 Slog.d(TAG, "Remembering install states:"); 11954 for (int i = 0; i < allUserHandles.length; i++) { 11955 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11956 } 11957 } 11958 } 11959 // Delete the updated package 11960 outInfo.isRemovedPackageSystemUpdate = true; 11961 if (disabledPs.versionCode < newPs.versionCode) { 11962 // Delete data for downgrades 11963 flags &= ~PackageManager.DELETE_KEEP_DATA; 11964 } else { 11965 // Preserve data by setting flag 11966 flags |= PackageManager.DELETE_KEEP_DATA; 11967 } 11968 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11969 allUserHandles, perUserInstalled, outInfo, writeSettings); 11970 if (!ret) { 11971 return false; 11972 } 11973 // writer 11974 synchronized (mPackages) { 11975 // Reinstate the old system package 11976 mSettings.enableSystemPackageLPw(newPs.name); 11977 // Remove any native libraries from the upgraded package. 11978 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11979 } 11980 // Install the system package 11981 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11982 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11983 if (locationIsPrivileged(disabledPs.codePath)) { 11984 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11985 } 11986 11987 final PackageParser.Package newPkg; 11988 try { 11989 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11990 } catch (PackageManagerException e) { 11991 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11992 return false; 11993 } 11994 11995 // writer 11996 synchronized (mPackages) { 11997 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11998 updatePermissionsLPw(newPkg.packageName, newPkg, 11999 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12000 if (applyUserRestrictions) { 12001 if (DEBUG_REMOVE) { 12002 Slog.d(TAG, "Propagating install state across reinstall"); 12003 } 12004 for (int i = 0; i < allUserHandles.length; i++) { 12005 if (DEBUG_REMOVE) { 12006 Slog.d(TAG, " user " + allUserHandles[i] 12007 + " => " + perUserInstalled[i]); 12008 } 12009 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12010 } 12011 // Regardless of writeSettings we need to ensure that this restriction 12012 // state propagation is persisted 12013 mSettings.writeAllUsersPackageRestrictionsLPr(); 12014 } 12015 // can downgrade to reader here 12016 if (writeSettings) { 12017 mSettings.writeLPr(); 12018 } 12019 } 12020 return true; 12021 } 12022 12023 private boolean deleteInstalledPackageLI(PackageSetting ps, 12024 boolean deleteCodeAndResources, int flags, 12025 int[] allUserHandles, boolean[] perUserInstalled, 12026 PackageRemovedInfo outInfo, boolean writeSettings) { 12027 if (outInfo != null) { 12028 outInfo.uid = ps.appId; 12029 } 12030 12031 // Delete package data from internal structures and also remove data if flag is set 12032 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12033 12034 // Delete application code and resources 12035 if (deleteCodeAndResources && (outInfo != null)) { 12036 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12038 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12039 } 12040 return true; 12041 } 12042 12043 @Override 12044 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12045 int userId) { 12046 mContext.enforceCallingOrSelfPermission( 12047 android.Manifest.permission.DELETE_PACKAGES, null); 12048 synchronized (mPackages) { 12049 PackageSetting ps = mSettings.mPackages.get(packageName); 12050 if (ps == null) { 12051 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12052 return false; 12053 } 12054 if (!ps.getInstalled(userId)) { 12055 // Can't block uninstall for an app that is not installed or enabled. 12056 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12057 return false; 12058 } 12059 ps.setBlockUninstall(blockUninstall, userId); 12060 mSettings.writePackageRestrictionsLPr(userId); 12061 } 12062 return true; 12063 } 12064 12065 @Override 12066 public boolean getBlockUninstallForUser(String packageName, int userId) { 12067 synchronized (mPackages) { 12068 PackageSetting ps = mSettings.mPackages.get(packageName); 12069 if (ps == null) { 12070 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12071 return false; 12072 } 12073 return ps.getBlockUninstall(userId); 12074 } 12075 } 12076 12077 /* 12078 * This method handles package deletion in general 12079 */ 12080 private boolean deletePackageLI(String packageName, UserHandle user, 12081 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12082 int flags, PackageRemovedInfo outInfo, 12083 boolean writeSettings) { 12084 if (packageName == null) { 12085 Slog.w(TAG, "Attempt to delete null packageName."); 12086 return false; 12087 } 12088 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12089 PackageSetting ps; 12090 boolean dataOnly = false; 12091 int removeUser = -1; 12092 int appId = -1; 12093 synchronized (mPackages) { 12094 ps = mSettings.mPackages.get(packageName); 12095 if (ps == null) { 12096 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12097 return false; 12098 } 12099 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12100 && user.getIdentifier() != UserHandle.USER_ALL) { 12101 // The caller is asking that the package only be deleted for a single 12102 // user. To do this, we just mark its uninstalled state and delete 12103 // its data. If this is a system app, we only allow this to happen if 12104 // they have set the special DELETE_SYSTEM_APP which requests different 12105 // semantics than normal for uninstalling system apps. 12106 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12107 ps.setUserState(user.getIdentifier(), 12108 COMPONENT_ENABLED_STATE_DEFAULT, 12109 false, //installed 12110 true, //stopped 12111 true, //notLaunched 12112 false, //hidden 12113 null, null, null, 12114 false, // blockUninstall 12115 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12116 if (!isSystemApp(ps)) { 12117 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12118 // Other user still have this package installed, so all 12119 // we need to do is clear this user's data and save that 12120 // it is uninstalled. 12121 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12122 removeUser = user.getIdentifier(); 12123 appId = ps.appId; 12124 scheduleWritePackageRestrictionsLocked(removeUser); 12125 } else { 12126 // We need to set it back to 'installed' so the uninstall 12127 // broadcasts will be sent correctly. 12128 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12129 ps.setInstalled(true, user.getIdentifier()); 12130 } 12131 } else { 12132 // This is a system app, so we assume that the 12133 // other users still have this package installed, so all 12134 // we need to do is clear this user's data and save that 12135 // it is uninstalled. 12136 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12137 removeUser = user.getIdentifier(); 12138 appId = ps.appId; 12139 scheduleWritePackageRestrictionsLocked(removeUser); 12140 } 12141 } 12142 } 12143 12144 if (removeUser >= 0) { 12145 // From above, we determined that we are deleting this only 12146 // for a single user. Continue the work here. 12147 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12148 if (outInfo != null) { 12149 outInfo.removedPackage = packageName; 12150 outInfo.removedAppId = appId; 12151 outInfo.removedUsers = new int[] {removeUser}; 12152 } 12153 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12154 removeKeystoreDataIfNeeded(removeUser, appId); 12155 schedulePackageCleaning(packageName, removeUser, false); 12156 synchronized (mPackages) { 12157 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12158 scheduleWritePackageRestrictionsLocked(removeUser); 12159 } 12160 } 12161 return true; 12162 } 12163 12164 if (dataOnly) { 12165 // Delete application data first 12166 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12167 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12168 return true; 12169 } 12170 12171 boolean ret = false; 12172 if (isSystemApp(ps)) { 12173 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12174 // When an updated system application is deleted we delete the existing resources as well and 12175 // fall back to existing code in system partition 12176 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12177 flags, outInfo, writeSettings); 12178 } else { 12179 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12180 // Kill application pre-emptively especially for apps on sd. 12181 killApplication(packageName, ps.appId, "uninstall pkg"); 12182 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12183 allUserHandles, perUserInstalled, 12184 outInfo, writeSettings); 12185 } 12186 12187 return ret; 12188 } 12189 12190 private final class ClearStorageConnection implements ServiceConnection { 12191 IMediaContainerService mContainerService; 12192 12193 @Override 12194 public void onServiceConnected(ComponentName name, IBinder service) { 12195 synchronized (this) { 12196 mContainerService = IMediaContainerService.Stub.asInterface(service); 12197 notifyAll(); 12198 } 12199 } 12200 12201 @Override 12202 public void onServiceDisconnected(ComponentName name) { 12203 } 12204 } 12205 12206 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12207 final boolean mounted; 12208 if (Environment.isExternalStorageEmulated()) { 12209 mounted = true; 12210 } else { 12211 final String status = Environment.getExternalStorageState(); 12212 12213 mounted = status.equals(Environment.MEDIA_MOUNTED) 12214 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12215 } 12216 12217 if (!mounted) { 12218 return; 12219 } 12220 12221 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12222 int[] users; 12223 if (userId == UserHandle.USER_ALL) { 12224 users = sUserManager.getUserIds(); 12225 } else { 12226 users = new int[] { userId }; 12227 } 12228 final ClearStorageConnection conn = new ClearStorageConnection(); 12229 if (mContext.bindServiceAsUser( 12230 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12231 try { 12232 for (int curUser : users) { 12233 long timeout = SystemClock.uptimeMillis() + 5000; 12234 synchronized (conn) { 12235 long now = SystemClock.uptimeMillis(); 12236 while (conn.mContainerService == null && now < timeout) { 12237 try { 12238 conn.wait(timeout - now); 12239 } catch (InterruptedException e) { 12240 } 12241 } 12242 } 12243 if (conn.mContainerService == null) { 12244 return; 12245 } 12246 12247 final UserEnvironment userEnv = new UserEnvironment(curUser); 12248 clearDirectory(conn.mContainerService, 12249 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12250 if (allData) { 12251 clearDirectory(conn.mContainerService, 12252 userEnv.buildExternalStorageAppDataDirs(packageName)); 12253 clearDirectory(conn.mContainerService, 12254 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12255 } 12256 } 12257 } finally { 12258 mContext.unbindService(conn); 12259 } 12260 } 12261 } 12262 12263 @Override 12264 public void clearApplicationUserData(final String packageName, 12265 final IPackageDataObserver observer, final int userId) { 12266 mContext.enforceCallingOrSelfPermission( 12267 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12268 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12269 // Queue up an async operation since the package deletion may take a little while. 12270 mHandler.post(new Runnable() { 12271 public void run() { 12272 mHandler.removeCallbacks(this); 12273 final boolean succeeded; 12274 synchronized (mInstallLock) { 12275 succeeded = clearApplicationUserDataLI(packageName, userId); 12276 } 12277 clearExternalStorageDataSync(packageName, userId, true); 12278 if (succeeded) { 12279 // invoke DeviceStorageMonitor's update method to clear any notifications 12280 DeviceStorageMonitorInternal 12281 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12282 if (dsm != null) { 12283 dsm.checkMemory(); 12284 } 12285 } 12286 if(observer != null) { 12287 try { 12288 observer.onRemoveCompleted(packageName, succeeded); 12289 } catch (RemoteException e) { 12290 Log.i(TAG, "Observer no longer exists."); 12291 } 12292 } //end if observer 12293 } //end run 12294 }); 12295 } 12296 12297 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12298 if (packageName == null) { 12299 Slog.w(TAG, "Attempt to delete null packageName."); 12300 return false; 12301 } 12302 12303 // Try finding details about the requested package 12304 PackageParser.Package pkg; 12305 synchronized (mPackages) { 12306 pkg = mPackages.get(packageName); 12307 if (pkg == null) { 12308 final PackageSetting ps = mSettings.mPackages.get(packageName); 12309 if (ps != null) { 12310 pkg = ps.pkg; 12311 } 12312 } 12313 } 12314 12315 if (pkg == null) { 12316 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12317 } 12318 12319 // Always delete data directories for package, even if we found no other 12320 // record of app. This helps users recover from UID mismatches without 12321 // resorting to a full data wipe. 12322 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12323 if (retCode < 0) { 12324 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12325 return false; 12326 } 12327 12328 if (pkg == null) { 12329 return false; 12330 } 12331 12332 if (pkg != null && pkg.applicationInfo != null) { 12333 final int appId = pkg.applicationInfo.uid; 12334 removeKeystoreDataIfNeeded(userId, appId); 12335 } 12336 12337 // Create a native library symlink only if we have native libraries 12338 // and if the native libraries are 32 bit libraries. We do not provide 12339 // this symlink for 64 bit libraries. 12340 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12341 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12342 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12343 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12344 nativeLibPath, userId) < 0) { 12345 Slog.w(TAG, "Failed linking native library dir"); 12346 return false; 12347 } 12348 } 12349 12350 return true; 12351 } 12352 12353 /** 12354 * Remove entries from the keystore daemon. Will only remove it if the 12355 * {@code appId} is valid. 12356 */ 12357 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12358 if (appId < 0) { 12359 return; 12360 } 12361 12362 final KeyStore keyStore = KeyStore.getInstance(); 12363 if (keyStore != null) { 12364 if (userId == UserHandle.USER_ALL) { 12365 for (final int individual : sUserManager.getUserIds()) { 12366 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12367 } 12368 } else { 12369 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12370 } 12371 } else { 12372 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12373 } 12374 } 12375 12376 @Override 12377 public void deleteApplicationCacheFiles(final String packageName, 12378 final IPackageDataObserver observer) { 12379 mContext.enforceCallingOrSelfPermission( 12380 android.Manifest.permission.DELETE_CACHE_FILES, null); 12381 // Queue up an async operation since the package deletion may take a little while. 12382 final int userId = UserHandle.getCallingUserId(); 12383 mHandler.post(new Runnable() { 12384 public void run() { 12385 mHandler.removeCallbacks(this); 12386 final boolean succeded; 12387 synchronized (mInstallLock) { 12388 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12389 } 12390 clearExternalStorageDataSync(packageName, userId, false); 12391 if(observer != null) { 12392 try { 12393 observer.onRemoveCompleted(packageName, succeded); 12394 } catch (RemoteException e) { 12395 Log.i(TAG, "Observer no longer exists."); 12396 } 12397 } //end if observer 12398 } //end run 12399 }); 12400 } 12401 12402 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12403 if (packageName == null) { 12404 Slog.w(TAG, "Attempt to delete null packageName."); 12405 return false; 12406 } 12407 PackageParser.Package p; 12408 synchronized (mPackages) { 12409 p = mPackages.get(packageName); 12410 } 12411 if (p == null) { 12412 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12413 return false; 12414 } 12415 final ApplicationInfo applicationInfo = p.applicationInfo; 12416 if (applicationInfo == null) { 12417 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12418 return false; 12419 } 12420 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12421 if (retCode < 0) { 12422 Slog.w(TAG, "Couldn't remove cache files for package: " 12423 + packageName + " u" + userId); 12424 return false; 12425 } 12426 return true; 12427 } 12428 12429 @Override 12430 public void getPackageSizeInfo(final String packageName, int userHandle, 12431 final IPackageStatsObserver observer) { 12432 mContext.enforceCallingOrSelfPermission( 12433 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12434 if (packageName == null) { 12435 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12436 } 12437 12438 PackageStats stats = new PackageStats(packageName, userHandle); 12439 12440 /* 12441 * Queue up an async operation since the package measurement may take a 12442 * little while. 12443 */ 12444 Message msg = mHandler.obtainMessage(INIT_COPY); 12445 msg.obj = new MeasureParams(stats, observer); 12446 mHandler.sendMessage(msg); 12447 } 12448 12449 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12450 PackageStats pStats) { 12451 if (packageName == null) { 12452 Slog.w(TAG, "Attempt to get size of null packageName."); 12453 return false; 12454 } 12455 PackageParser.Package p; 12456 boolean dataOnly = false; 12457 String libDirRoot = null; 12458 String asecPath = null; 12459 PackageSetting ps = null; 12460 synchronized (mPackages) { 12461 p = mPackages.get(packageName); 12462 ps = mSettings.mPackages.get(packageName); 12463 if(p == null) { 12464 dataOnly = true; 12465 if((ps == null) || (ps.pkg == null)) { 12466 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12467 return false; 12468 } 12469 p = ps.pkg; 12470 } 12471 if (ps != null) { 12472 libDirRoot = ps.legacyNativeLibraryPathString; 12473 } 12474 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12475 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12476 if (secureContainerId != null) { 12477 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12478 } 12479 } 12480 } 12481 String publicSrcDir = null; 12482 if(!dataOnly) { 12483 final ApplicationInfo applicationInfo = p.applicationInfo; 12484 if (applicationInfo == null) { 12485 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12486 return false; 12487 } 12488 if (p.isForwardLocked()) { 12489 publicSrcDir = applicationInfo.getBaseResourcePath(); 12490 } 12491 } 12492 // TODO: extend to measure size of split APKs 12493 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12494 // not just the first level. 12495 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12496 // just the primary. 12497 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12498 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12499 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12500 if (res < 0) { 12501 return false; 12502 } 12503 12504 // Fix-up for forward-locked applications in ASEC containers. 12505 if (!isExternal(p)) { 12506 pStats.codeSize += pStats.externalCodeSize; 12507 pStats.externalCodeSize = 0L; 12508 } 12509 12510 return true; 12511 } 12512 12513 12514 @Override 12515 public void addPackageToPreferred(String packageName) { 12516 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12517 } 12518 12519 @Override 12520 public void removePackageFromPreferred(String packageName) { 12521 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12522 } 12523 12524 @Override 12525 public List<PackageInfo> getPreferredPackages(int flags) { 12526 return new ArrayList<PackageInfo>(); 12527 } 12528 12529 private int getUidTargetSdkVersionLockedLPr(int uid) { 12530 Object obj = mSettings.getUserIdLPr(uid); 12531 if (obj instanceof SharedUserSetting) { 12532 final SharedUserSetting sus = (SharedUserSetting) obj; 12533 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12534 final Iterator<PackageSetting> it = sus.packages.iterator(); 12535 while (it.hasNext()) { 12536 final PackageSetting ps = it.next(); 12537 if (ps.pkg != null) { 12538 int v = ps.pkg.applicationInfo.targetSdkVersion; 12539 if (v < vers) vers = v; 12540 } 12541 } 12542 return vers; 12543 } else if (obj instanceof PackageSetting) { 12544 final PackageSetting ps = (PackageSetting) obj; 12545 if (ps.pkg != null) { 12546 return ps.pkg.applicationInfo.targetSdkVersion; 12547 } 12548 } 12549 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12550 } 12551 12552 @Override 12553 public void addPreferredActivity(IntentFilter filter, int match, 12554 ComponentName[] set, ComponentName activity, int userId) { 12555 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12556 "Adding preferred"); 12557 } 12558 12559 private void addPreferredActivityInternal(IntentFilter filter, int match, 12560 ComponentName[] set, ComponentName activity, boolean always, int userId, 12561 String opname) { 12562 // writer 12563 int callingUid = Binder.getCallingUid(); 12564 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12565 if (filter.countActions() == 0) { 12566 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12567 return; 12568 } 12569 synchronized (mPackages) { 12570 if (mContext.checkCallingOrSelfPermission( 12571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12572 != PackageManager.PERMISSION_GRANTED) { 12573 if (getUidTargetSdkVersionLockedLPr(callingUid) 12574 < Build.VERSION_CODES.FROYO) { 12575 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12576 + callingUid); 12577 return; 12578 } 12579 mContext.enforceCallingOrSelfPermission( 12580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12581 } 12582 12583 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12584 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12585 + userId + ":"); 12586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12587 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12588 scheduleWritePackageRestrictionsLocked(userId); 12589 } 12590 } 12591 12592 @Override 12593 public void replacePreferredActivity(IntentFilter filter, int match, 12594 ComponentName[] set, ComponentName activity, int userId) { 12595 if (filter.countActions() != 1) { 12596 throw new IllegalArgumentException( 12597 "replacePreferredActivity expects filter to have only 1 action."); 12598 } 12599 if (filter.countDataAuthorities() != 0 12600 || filter.countDataPaths() != 0 12601 || filter.countDataSchemes() > 1 12602 || filter.countDataTypes() != 0) { 12603 throw new IllegalArgumentException( 12604 "replacePreferredActivity expects filter to have no data authorities, " + 12605 "paths, or types; and at most one scheme."); 12606 } 12607 12608 final int callingUid = Binder.getCallingUid(); 12609 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12610 synchronized (mPackages) { 12611 if (mContext.checkCallingOrSelfPermission( 12612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12613 != PackageManager.PERMISSION_GRANTED) { 12614 if (getUidTargetSdkVersionLockedLPr(callingUid) 12615 < Build.VERSION_CODES.FROYO) { 12616 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12617 + Binder.getCallingUid()); 12618 return; 12619 } 12620 mContext.enforceCallingOrSelfPermission( 12621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12622 } 12623 12624 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12625 if (pir != null) { 12626 // Get all of the existing entries that exactly match this filter. 12627 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12628 if (existing != null && existing.size() == 1) { 12629 PreferredActivity cur = existing.get(0); 12630 if (DEBUG_PREFERRED) { 12631 Slog.i(TAG, "Checking replace of preferred:"); 12632 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12633 if (!cur.mPref.mAlways) { 12634 Slog.i(TAG, " -- CUR; not mAlways!"); 12635 } else { 12636 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12637 Slog.i(TAG, " -- CUR: mSet=" 12638 + Arrays.toString(cur.mPref.mSetComponents)); 12639 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12640 Slog.i(TAG, " -- NEW: mMatch=" 12641 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12642 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12643 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12644 } 12645 } 12646 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12647 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12648 && cur.mPref.sameSet(set)) { 12649 // Setting the preferred activity to what it happens to be already 12650 if (DEBUG_PREFERRED) { 12651 Slog.i(TAG, "Replacing with same preferred activity " 12652 + cur.mPref.mShortComponent + " for user " 12653 + userId + ":"); 12654 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12655 } 12656 return; 12657 } 12658 } 12659 12660 if (existing != null) { 12661 if (DEBUG_PREFERRED) { 12662 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12663 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12664 } 12665 for (int i = 0; i < existing.size(); i++) { 12666 PreferredActivity pa = existing.get(i); 12667 if (DEBUG_PREFERRED) { 12668 Slog.i(TAG, "Removing existing preferred activity " 12669 + pa.mPref.mComponent + ":"); 12670 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12671 } 12672 pir.removeFilter(pa); 12673 } 12674 } 12675 } 12676 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12677 "Replacing preferred"); 12678 } 12679 } 12680 12681 @Override 12682 public void clearPackagePreferredActivities(String packageName) { 12683 final int uid = Binder.getCallingUid(); 12684 // writer 12685 synchronized (mPackages) { 12686 PackageParser.Package pkg = mPackages.get(packageName); 12687 if (pkg == null || pkg.applicationInfo.uid != uid) { 12688 if (mContext.checkCallingOrSelfPermission( 12689 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12690 != PackageManager.PERMISSION_GRANTED) { 12691 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12692 < Build.VERSION_CODES.FROYO) { 12693 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12694 + Binder.getCallingUid()); 12695 return; 12696 } 12697 mContext.enforceCallingOrSelfPermission( 12698 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12699 } 12700 } 12701 12702 int user = UserHandle.getCallingUserId(); 12703 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12704 scheduleWritePackageRestrictionsLocked(user); 12705 } 12706 } 12707 } 12708 12709 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12710 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12711 ArrayList<PreferredActivity> removed = null; 12712 boolean changed = false; 12713 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12714 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12715 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12716 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12717 continue; 12718 } 12719 Iterator<PreferredActivity> it = pir.filterIterator(); 12720 while (it.hasNext()) { 12721 PreferredActivity pa = it.next(); 12722 // Mark entry for removal only if it matches the package name 12723 // and the entry is of type "always". 12724 if (packageName == null || 12725 (pa.mPref.mComponent.getPackageName().equals(packageName) 12726 && pa.mPref.mAlways)) { 12727 if (removed == null) { 12728 removed = new ArrayList<PreferredActivity>(); 12729 } 12730 removed.add(pa); 12731 } 12732 } 12733 if (removed != null) { 12734 for (int j=0; j<removed.size(); j++) { 12735 PreferredActivity pa = removed.get(j); 12736 pir.removeFilter(pa); 12737 } 12738 changed = true; 12739 } 12740 } 12741 return changed; 12742 } 12743 12744 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12745 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12746 if (userId == UserHandle.USER_ALL) { 12747 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12748 for (int oneUserId : sUserManager.getUserIds()) { 12749 scheduleWritePackageRestrictionsLocked(oneUserId); 12750 } 12751 } else { 12752 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12753 scheduleWritePackageRestrictionsLocked(userId); 12754 } 12755 } 12756 12757 @Override 12758 public void resetPreferredActivities(int userId) { 12759 /* TODO: Actually use userId. Why is it being passed in? */ 12760 mContext.enforceCallingOrSelfPermission( 12761 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12762 // writer 12763 synchronized (mPackages) { 12764 int user = UserHandle.getCallingUserId(); 12765 clearPackagePreferredActivitiesLPw(null, user); 12766 mSettings.readDefaultPreferredAppsLPw(this, user); 12767 scheduleWritePackageRestrictionsLocked(user); 12768 } 12769 } 12770 12771 @Override 12772 public int getPreferredActivities(List<IntentFilter> outFilters, 12773 List<ComponentName> outActivities, String packageName) { 12774 12775 int num = 0; 12776 final int userId = UserHandle.getCallingUserId(); 12777 // reader 12778 synchronized (mPackages) { 12779 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12780 if (pir != null) { 12781 final Iterator<PreferredActivity> it = pir.filterIterator(); 12782 while (it.hasNext()) { 12783 final PreferredActivity pa = it.next(); 12784 if (packageName == null 12785 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12786 && pa.mPref.mAlways)) { 12787 if (outFilters != null) { 12788 outFilters.add(new IntentFilter(pa)); 12789 } 12790 if (outActivities != null) { 12791 outActivities.add(pa.mPref.mComponent); 12792 } 12793 } 12794 } 12795 } 12796 } 12797 12798 return num; 12799 } 12800 12801 @Override 12802 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12803 int userId) { 12804 int callingUid = Binder.getCallingUid(); 12805 if (callingUid != Process.SYSTEM_UID) { 12806 throw new SecurityException( 12807 "addPersistentPreferredActivity can only be run by the system"); 12808 } 12809 if (filter.countActions() == 0) { 12810 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12811 return; 12812 } 12813 synchronized (mPackages) { 12814 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12815 " :"); 12816 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12817 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12818 new PersistentPreferredActivity(filter, activity)); 12819 scheduleWritePackageRestrictionsLocked(userId); 12820 } 12821 } 12822 12823 @Override 12824 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12825 int callingUid = Binder.getCallingUid(); 12826 if (callingUid != Process.SYSTEM_UID) { 12827 throw new SecurityException( 12828 "clearPackagePersistentPreferredActivities can only be run by the system"); 12829 } 12830 ArrayList<PersistentPreferredActivity> removed = null; 12831 boolean changed = false; 12832 synchronized (mPackages) { 12833 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12834 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12835 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12836 .valueAt(i); 12837 if (userId != thisUserId) { 12838 continue; 12839 } 12840 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12841 while (it.hasNext()) { 12842 PersistentPreferredActivity ppa = it.next(); 12843 // Mark entry for removal only if it matches the package name. 12844 if (ppa.mComponent.getPackageName().equals(packageName)) { 12845 if (removed == null) { 12846 removed = new ArrayList<PersistentPreferredActivity>(); 12847 } 12848 removed.add(ppa); 12849 } 12850 } 12851 if (removed != null) { 12852 for (int j=0; j<removed.size(); j++) { 12853 PersistentPreferredActivity ppa = removed.get(j); 12854 ppir.removeFilter(ppa); 12855 } 12856 changed = true; 12857 } 12858 } 12859 12860 if (changed) { 12861 scheduleWritePackageRestrictionsLocked(userId); 12862 } 12863 } 12864 } 12865 12866 /** 12867 * Non-Binder method, support for the backup/restore mechanism: write the 12868 * full set of preferred activities in its canonical XML format. Returns true 12869 * on success; false otherwise. 12870 */ 12871 @Override 12872 public byte[] getPreferredActivityBackup(int userId) { 12873 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12874 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12875 } 12876 12877 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12878 try { 12879 final XmlSerializer serializer = new FastXmlSerializer(); 12880 serializer.setOutput(dataStream, "utf-8"); 12881 serializer.startDocument(null, true); 12882 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12883 12884 synchronized (mPackages) { 12885 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12886 } 12887 12888 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12889 serializer.endDocument(); 12890 serializer.flush(); 12891 } catch (Exception e) { 12892 if (DEBUG_BACKUP) { 12893 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12894 } 12895 return null; 12896 } 12897 12898 return dataStream.toByteArray(); 12899 } 12900 12901 @Override 12902 public void restorePreferredActivities(byte[] backup, int userId) { 12903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12904 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12905 } 12906 12907 try { 12908 final XmlPullParser parser = Xml.newPullParser(); 12909 parser.setInput(new ByteArrayInputStream(backup), null); 12910 12911 int type; 12912 while ((type = parser.next()) != XmlPullParser.START_TAG 12913 && type != XmlPullParser.END_DOCUMENT) { 12914 } 12915 if (type != XmlPullParser.START_TAG) { 12916 // oops didn't find a start tag?! 12917 if (DEBUG_BACKUP) { 12918 Slog.e(TAG, "Didn't find start tag during restore"); 12919 } 12920 return; 12921 } 12922 12923 // this is supposed to be TAG_PREFERRED_BACKUP 12924 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12925 if (DEBUG_BACKUP) { 12926 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12927 } 12928 return; 12929 } 12930 12931 // skip interfering stuff, then we're aligned with the backing implementation 12932 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12933 synchronized (mPackages) { 12934 mSettings.readPreferredActivitiesLPw(parser, userId); 12935 } 12936 } catch (Exception e) { 12937 if (DEBUG_BACKUP) { 12938 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12939 } 12940 } 12941 } 12942 12943 @Override 12944 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12945 int sourceUserId, int targetUserId, int flags) { 12946 mContext.enforceCallingOrSelfPermission( 12947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12948 int callingUid = Binder.getCallingUid(); 12949 enforceOwnerRights(ownerPackage, callingUid); 12950 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12951 if (intentFilter.countActions() == 0) { 12952 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12953 return; 12954 } 12955 synchronized (mPackages) { 12956 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12957 ownerPackage, targetUserId, flags); 12958 CrossProfileIntentResolver resolver = 12959 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12960 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12961 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12962 if (existing != null) { 12963 int size = existing.size(); 12964 for (int i = 0; i < size; i++) { 12965 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12966 return; 12967 } 12968 } 12969 } 12970 resolver.addFilter(newFilter); 12971 scheduleWritePackageRestrictionsLocked(sourceUserId); 12972 } 12973 } 12974 12975 @Override 12976 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12977 mContext.enforceCallingOrSelfPermission( 12978 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12979 int callingUid = Binder.getCallingUid(); 12980 enforceOwnerRights(ownerPackage, callingUid); 12981 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12982 synchronized (mPackages) { 12983 CrossProfileIntentResolver resolver = 12984 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12985 ArraySet<CrossProfileIntentFilter> set = 12986 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12987 for (CrossProfileIntentFilter filter : set) { 12988 if (filter.getOwnerPackage().equals(ownerPackage)) { 12989 resolver.removeFilter(filter); 12990 } 12991 } 12992 scheduleWritePackageRestrictionsLocked(sourceUserId); 12993 } 12994 } 12995 12996 // Enforcing that callingUid is owning pkg on userId 12997 private void enforceOwnerRights(String pkg, int callingUid) { 12998 // The system owns everything. 12999 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13000 return; 13001 } 13002 int callingUserId = UserHandle.getUserId(callingUid); 13003 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13004 if (pi == null) { 13005 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13006 + callingUserId); 13007 } 13008 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13009 throw new SecurityException("Calling uid " + callingUid 13010 + " does not own package " + pkg); 13011 } 13012 } 13013 13014 @Override 13015 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13016 Intent intent = new Intent(Intent.ACTION_MAIN); 13017 intent.addCategory(Intent.CATEGORY_HOME); 13018 13019 final int callingUserId = UserHandle.getCallingUserId(); 13020 List<ResolveInfo> list = queryIntentActivities(intent, null, 13021 PackageManager.GET_META_DATA, callingUserId); 13022 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13023 true, false, false, callingUserId); 13024 13025 allHomeCandidates.clear(); 13026 if (list != null) { 13027 for (ResolveInfo ri : list) { 13028 allHomeCandidates.add(ri); 13029 } 13030 } 13031 return (preferred == null || preferred.activityInfo == null) 13032 ? null 13033 : new ComponentName(preferred.activityInfo.packageName, 13034 preferred.activityInfo.name); 13035 } 13036 13037 @Override 13038 public void setApplicationEnabledSetting(String appPackageName, 13039 int newState, int flags, int userId, String callingPackage) { 13040 if (!sUserManager.exists(userId)) return; 13041 if (callingPackage == null) { 13042 callingPackage = Integer.toString(Binder.getCallingUid()); 13043 } 13044 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13045 } 13046 13047 @Override 13048 public void setComponentEnabledSetting(ComponentName componentName, 13049 int newState, int flags, int userId) { 13050 if (!sUserManager.exists(userId)) return; 13051 setEnabledSetting(componentName.getPackageName(), 13052 componentName.getClassName(), newState, flags, userId, null); 13053 } 13054 13055 private void setEnabledSetting(final String packageName, String className, int newState, 13056 final int flags, int userId, String callingPackage) { 13057 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13058 || newState == COMPONENT_ENABLED_STATE_ENABLED 13059 || newState == COMPONENT_ENABLED_STATE_DISABLED 13060 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13061 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13062 throw new IllegalArgumentException("Invalid new component state: " 13063 + newState); 13064 } 13065 PackageSetting pkgSetting; 13066 final int uid = Binder.getCallingUid(); 13067 final int permission = mContext.checkCallingOrSelfPermission( 13068 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13069 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13070 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13071 boolean sendNow = false; 13072 boolean isApp = (className == null); 13073 String componentName = isApp ? packageName : className; 13074 int packageUid = -1; 13075 ArrayList<String> components; 13076 13077 // writer 13078 synchronized (mPackages) { 13079 pkgSetting = mSettings.mPackages.get(packageName); 13080 if (pkgSetting == null) { 13081 if (className == null) { 13082 throw new IllegalArgumentException( 13083 "Unknown package: " + packageName); 13084 } 13085 throw new IllegalArgumentException( 13086 "Unknown component: " + packageName 13087 + "/" + className); 13088 } 13089 // Allow root and verify that userId is not being specified by a different user 13090 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13091 throw new SecurityException( 13092 "Permission Denial: attempt to change component state from pid=" 13093 + Binder.getCallingPid() 13094 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13095 } 13096 if (className == null) { 13097 // We're dealing with an application/package level state change 13098 if (pkgSetting.getEnabled(userId) == newState) { 13099 // Nothing to do 13100 return; 13101 } 13102 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13103 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13104 // Don't care about who enables an app. 13105 callingPackage = null; 13106 } 13107 pkgSetting.setEnabled(newState, userId, callingPackage); 13108 // pkgSetting.pkg.mSetEnabled = newState; 13109 } else { 13110 // We're dealing with a component level state change 13111 // First, verify that this is a valid class name. 13112 PackageParser.Package pkg = pkgSetting.pkg; 13113 if (pkg == null || !pkg.hasComponentClassName(className)) { 13114 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13115 throw new IllegalArgumentException("Component class " + className 13116 + " does not exist in " + packageName); 13117 } else { 13118 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13119 + className + " does not exist in " + packageName); 13120 } 13121 } 13122 switch (newState) { 13123 case COMPONENT_ENABLED_STATE_ENABLED: 13124 if (!pkgSetting.enableComponentLPw(className, userId)) { 13125 return; 13126 } 13127 break; 13128 case COMPONENT_ENABLED_STATE_DISABLED: 13129 if (!pkgSetting.disableComponentLPw(className, userId)) { 13130 return; 13131 } 13132 break; 13133 case COMPONENT_ENABLED_STATE_DEFAULT: 13134 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13135 return; 13136 } 13137 break; 13138 default: 13139 Slog.e(TAG, "Invalid new component state: " + newState); 13140 return; 13141 } 13142 } 13143 scheduleWritePackageRestrictionsLocked(userId); 13144 components = mPendingBroadcasts.get(userId, packageName); 13145 final boolean newPackage = components == null; 13146 if (newPackage) { 13147 components = new ArrayList<String>(); 13148 } 13149 if (!components.contains(componentName)) { 13150 components.add(componentName); 13151 } 13152 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13153 sendNow = true; 13154 // Purge entry from pending broadcast list if another one exists already 13155 // since we are sending one right away. 13156 mPendingBroadcasts.remove(userId, packageName); 13157 } else { 13158 if (newPackage) { 13159 mPendingBroadcasts.put(userId, packageName, components); 13160 } 13161 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13162 // Schedule a message 13163 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13164 } 13165 } 13166 } 13167 13168 long callingId = Binder.clearCallingIdentity(); 13169 try { 13170 if (sendNow) { 13171 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13172 sendPackageChangedBroadcast(packageName, 13173 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13174 } 13175 } finally { 13176 Binder.restoreCallingIdentity(callingId); 13177 } 13178 } 13179 13180 private void sendPackageChangedBroadcast(String packageName, 13181 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13182 if (DEBUG_INSTALL) 13183 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13184 + componentNames); 13185 Bundle extras = new Bundle(4); 13186 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13187 String nameList[] = new String[componentNames.size()]; 13188 componentNames.toArray(nameList); 13189 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13190 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13191 extras.putInt(Intent.EXTRA_UID, packageUid); 13192 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13193 new int[] {UserHandle.getUserId(packageUid)}); 13194 } 13195 13196 @Override 13197 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13198 if (!sUserManager.exists(userId)) return; 13199 final int uid = Binder.getCallingUid(); 13200 final int permission = mContext.checkCallingOrSelfPermission( 13201 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13202 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13203 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13204 // writer 13205 synchronized (mPackages) { 13206 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13207 allowedByPermission, uid, userId)) { 13208 scheduleWritePackageRestrictionsLocked(userId); 13209 } 13210 } 13211 } 13212 13213 @Override 13214 public String getInstallerPackageName(String packageName) { 13215 // reader 13216 synchronized (mPackages) { 13217 return mSettings.getInstallerPackageNameLPr(packageName); 13218 } 13219 } 13220 13221 @Override 13222 public int getApplicationEnabledSetting(String packageName, int userId) { 13223 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13224 int uid = Binder.getCallingUid(); 13225 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13226 // reader 13227 synchronized (mPackages) { 13228 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13229 } 13230 } 13231 13232 @Override 13233 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13234 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13235 int uid = Binder.getCallingUid(); 13236 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13237 // reader 13238 synchronized (mPackages) { 13239 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13240 } 13241 } 13242 13243 @Override 13244 public void enterSafeMode() { 13245 enforceSystemOrRoot("Only the system can request entering safe mode"); 13246 13247 if (!mSystemReady) { 13248 mSafeMode = true; 13249 } 13250 } 13251 13252 @Override 13253 public void systemReady() { 13254 mSystemReady = true; 13255 13256 // Read the compatibilty setting when the system is ready. 13257 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13258 mContext.getContentResolver(), 13259 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13260 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13261 if (DEBUG_SETTINGS) { 13262 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13263 } 13264 13265 synchronized (mPackages) { 13266 // Verify that all of the preferred activity components actually 13267 // exist. It is possible for applications to be updated and at 13268 // that point remove a previously declared activity component that 13269 // had been set as a preferred activity. We try to clean this up 13270 // the next time we encounter that preferred activity, but it is 13271 // possible for the user flow to never be able to return to that 13272 // situation so here we do a sanity check to make sure we haven't 13273 // left any junk around. 13274 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13275 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13276 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13277 removed.clear(); 13278 for (PreferredActivity pa : pir.filterSet()) { 13279 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13280 removed.add(pa); 13281 } 13282 } 13283 if (removed.size() > 0) { 13284 for (int r=0; r<removed.size(); r++) { 13285 PreferredActivity pa = removed.get(r); 13286 Slog.w(TAG, "Removing dangling preferred activity: " 13287 + pa.mPref.mComponent); 13288 pir.removeFilter(pa); 13289 } 13290 mSettings.writePackageRestrictionsLPr( 13291 mSettings.mPreferredActivities.keyAt(i)); 13292 } 13293 } 13294 } 13295 sUserManager.systemReady(); 13296 13297 // Kick off any messages waiting for system ready 13298 if (mPostSystemReadyMessages != null) { 13299 for (Message msg : mPostSystemReadyMessages) { 13300 msg.sendToTarget(); 13301 } 13302 mPostSystemReadyMessages = null; 13303 } 13304 13305 // Watch for external volumes that come and go over time 13306 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13307 storage.registerListener(mStorageListener); 13308 13309 mInstallerService.systemReady(); 13310 } 13311 13312 @Override 13313 public boolean isSafeMode() { 13314 return mSafeMode; 13315 } 13316 13317 @Override 13318 public boolean hasSystemUidErrors() { 13319 return mHasSystemUidErrors; 13320 } 13321 13322 static String arrayToString(int[] array) { 13323 StringBuffer buf = new StringBuffer(128); 13324 buf.append('['); 13325 if (array != null) { 13326 for (int i=0; i<array.length; i++) { 13327 if (i > 0) buf.append(", "); 13328 buf.append(array[i]); 13329 } 13330 } 13331 buf.append(']'); 13332 return buf.toString(); 13333 } 13334 13335 static class DumpState { 13336 public static final int DUMP_LIBS = 1 << 0; 13337 public static final int DUMP_FEATURES = 1 << 1; 13338 public static final int DUMP_RESOLVERS = 1 << 2; 13339 public static final int DUMP_PERMISSIONS = 1 << 3; 13340 public static final int DUMP_PACKAGES = 1 << 4; 13341 public static final int DUMP_SHARED_USERS = 1 << 5; 13342 public static final int DUMP_MESSAGES = 1 << 6; 13343 public static final int DUMP_PROVIDERS = 1 << 7; 13344 public static final int DUMP_VERIFIERS = 1 << 8; 13345 public static final int DUMP_PREFERRED = 1 << 9; 13346 public static final int DUMP_PREFERRED_XML = 1 << 10; 13347 public static final int DUMP_KEYSETS = 1 << 11; 13348 public static final int DUMP_VERSION = 1 << 12; 13349 public static final int DUMP_INSTALLS = 1 << 13; 13350 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13351 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13352 13353 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13354 13355 private int mTypes; 13356 13357 private int mOptions; 13358 13359 private boolean mTitlePrinted; 13360 13361 private SharedUserSetting mSharedUser; 13362 13363 public boolean isDumping(int type) { 13364 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13365 return true; 13366 } 13367 13368 return (mTypes & type) != 0; 13369 } 13370 13371 public void setDump(int type) { 13372 mTypes |= type; 13373 } 13374 13375 public boolean isOptionEnabled(int option) { 13376 return (mOptions & option) != 0; 13377 } 13378 13379 public void setOptionEnabled(int option) { 13380 mOptions |= option; 13381 } 13382 13383 public boolean onTitlePrinted() { 13384 final boolean printed = mTitlePrinted; 13385 mTitlePrinted = true; 13386 return printed; 13387 } 13388 13389 public boolean getTitlePrinted() { 13390 return mTitlePrinted; 13391 } 13392 13393 public void setTitlePrinted(boolean enabled) { 13394 mTitlePrinted = enabled; 13395 } 13396 13397 public SharedUserSetting getSharedUser() { 13398 return mSharedUser; 13399 } 13400 13401 public void setSharedUser(SharedUserSetting user) { 13402 mSharedUser = user; 13403 } 13404 } 13405 13406 @Override 13407 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13408 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13409 != PackageManager.PERMISSION_GRANTED) { 13410 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13411 + Binder.getCallingPid() 13412 + ", uid=" + Binder.getCallingUid() 13413 + " without permission " 13414 + android.Manifest.permission.DUMP); 13415 return; 13416 } 13417 13418 DumpState dumpState = new DumpState(); 13419 boolean fullPreferred = false; 13420 boolean checkin = false; 13421 13422 String packageName = null; 13423 13424 int opti = 0; 13425 while (opti < args.length) { 13426 String opt = args[opti]; 13427 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13428 break; 13429 } 13430 opti++; 13431 13432 if ("-a".equals(opt)) { 13433 // Right now we only know how to print all. 13434 } else if ("-h".equals(opt)) { 13435 pw.println("Package manager dump options:"); 13436 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13437 pw.println(" --checkin: dump for a checkin"); 13438 pw.println(" -f: print details of intent filters"); 13439 pw.println(" -h: print this help"); 13440 pw.println(" cmd may be one of:"); 13441 pw.println(" l[ibraries]: list known shared libraries"); 13442 pw.println(" f[ibraries]: list device features"); 13443 pw.println(" k[eysets]: print known keysets"); 13444 pw.println(" r[esolvers]: dump intent resolvers"); 13445 pw.println(" perm[issions]: dump permissions"); 13446 pw.println(" pref[erred]: print preferred package settings"); 13447 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13448 pw.println(" prov[iders]: dump content providers"); 13449 pw.println(" p[ackages]: dump installed packages"); 13450 pw.println(" s[hared-users]: dump shared user IDs"); 13451 pw.println(" m[essages]: print collected runtime messages"); 13452 pw.println(" v[erifiers]: print package verifier info"); 13453 pw.println(" version: print database version info"); 13454 pw.println(" write: write current settings now"); 13455 pw.println(" <package.name>: info about given package"); 13456 pw.println(" installs: details about install sessions"); 13457 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13458 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13459 return; 13460 } else if ("--checkin".equals(opt)) { 13461 checkin = true; 13462 } else if ("-f".equals(opt)) { 13463 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13464 } else { 13465 pw.println("Unknown argument: " + opt + "; use -h for help"); 13466 } 13467 } 13468 13469 // Is the caller requesting to dump a particular piece of data? 13470 if (opti < args.length) { 13471 String cmd = args[opti]; 13472 opti++; 13473 // Is this a package name? 13474 if ("android".equals(cmd) || cmd.contains(".")) { 13475 packageName = cmd; 13476 // When dumping a single package, we always dump all of its 13477 // filter information since the amount of data will be reasonable. 13478 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13479 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13480 dumpState.setDump(DumpState.DUMP_LIBS); 13481 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13482 dumpState.setDump(DumpState.DUMP_FEATURES); 13483 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13484 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13485 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13486 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13487 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13488 dumpState.setDump(DumpState.DUMP_PREFERRED); 13489 } else if ("preferred-xml".equals(cmd)) { 13490 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13491 if (opti < args.length && "--full".equals(args[opti])) { 13492 fullPreferred = true; 13493 opti++; 13494 } 13495 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13496 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13497 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13498 dumpState.setDump(DumpState.DUMP_PACKAGES); 13499 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13500 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13501 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13502 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13503 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13504 dumpState.setDump(DumpState.DUMP_MESSAGES); 13505 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13506 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13507 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13508 || "intent-filter-verifiers".equals(cmd)) { 13509 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13510 } else if ("version".equals(cmd)) { 13511 dumpState.setDump(DumpState.DUMP_VERSION); 13512 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13513 dumpState.setDump(DumpState.DUMP_KEYSETS); 13514 } else if ("installs".equals(cmd)) { 13515 dumpState.setDump(DumpState.DUMP_INSTALLS); 13516 } else if ("write".equals(cmd)) { 13517 synchronized (mPackages) { 13518 mSettings.writeLPr(); 13519 pw.println("Settings written."); 13520 return; 13521 } 13522 } 13523 } 13524 13525 if (checkin) { 13526 pw.println("vers,1"); 13527 } 13528 13529 // reader 13530 synchronized (mPackages) { 13531 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13532 if (!checkin) { 13533 if (dumpState.onTitlePrinted()) 13534 pw.println(); 13535 pw.println("Database versions:"); 13536 pw.print(" SDK Version:"); 13537 pw.print(" internal="); 13538 pw.print(mSettings.mInternalSdkPlatform); 13539 pw.print(" external="); 13540 pw.println(mSettings.mExternalSdkPlatform); 13541 pw.print(" DB Version:"); 13542 pw.print(" internal="); 13543 pw.print(mSettings.mInternalDatabaseVersion); 13544 pw.print(" external="); 13545 pw.println(mSettings.mExternalDatabaseVersion); 13546 } 13547 } 13548 13549 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13550 if (!checkin) { 13551 if (dumpState.onTitlePrinted()) 13552 pw.println(); 13553 pw.println("Verifiers:"); 13554 pw.print(" Required: "); 13555 pw.print(mRequiredVerifierPackage); 13556 pw.print(" (uid="); 13557 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13558 pw.println(")"); 13559 } else if (mRequiredVerifierPackage != null) { 13560 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13561 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13562 } 13563 } 13564 13565 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13566 packageName == null) { 13567 if (mIntentFilterVerifierComponent != null) { 13568 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13569 if (!checkin) { 13570 if (dumpState.onTitlePrinted()) 13571 pw.println(); 13572 pw.println("Intent Filter Verifier:"); 13573 pw.print(" Using: "); 13574 pw.print(verifierPackageName); 13575 pw.print(" (uid="); 13576 pw.print(getPackageUid(verifierPackageName, 0)); 13577 pw.println(")"); 13578 } else if (verifierPackageName != null) { 13579 pw.print("ifv,"); pw.print(verifierPackageName); 13580 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13581 } 13582 } else { 13583 pw.println(); 13584 pw.println("No Intent Filter Verifier available!"); 13585 } 13586 } 13587 13588 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13589 boolean printedHeader = false; 13590 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13591 while (it.hasNext()) { 13592 String name = it.next(); 13593 SharedLibraryEntry ent = mSharedLibraries.get(name); 13594 if (!checkin) { 13595 if (!printedHeader) { 13596 if (dumpState.onTitlePrinted()) 13597 pw.println(); 13598 pw.println("Libraries:"); 13599 printedHeader = true; 13600 } 13601 pw.print(" "); 13602 } else { 13603 pw.print("lib,"); 13604 } 13605 pw.print(name); 13606 if (!checkin) { 13607 pw.print(" -> "); 13608 } 13609 if (ent.path != null) { 13610 if (!checkin) { 13611 pw.print("(jar) "); 13612 pw.print(ent.path); 13613 } else { 13614 pw.print(",jar,"); 13615 pw.print(ent.path); 13616 } 13617 } else { 13618 if (!checkin) { 13619 pw.print("(apk) "); 13620 pw.print(ent.apk); 13621 } else { 13622 pw.print(",apk,"); 13623 pw.print(ent.apk); 13624 } 13625 } 13626 pw.println(); 13627 } 13628 } 13629 13630 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13631 if (dumpState.onTitlePrinted()) 13632 pw.println(); 13633 if (!checkin) { 13634 pw.println("Features:"); 13635 } 13636 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13637 while (it.hasNext()) { 13638 String name = it.next(); 13639 if (!checkin) { 13640 pw.print(" "); 13641 } else { 13642 pw.print("feat,"); 13643 } 13644 pw.println(name); 13645 } 13646 } 13647 13648 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13649 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13650 : "Activity Resolver Table:", " ", packageName, 13651 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13652 dumpState.setTitlePrinted(true); 13653 } 13654 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13655 : "Receiver Resolver Table:", " ", packageName, 13656 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13657 dumpState.setTitlePrinted(true); 13658 } 13659 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13660 : "Service Resolver Table:", " ", packageName, 13661 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13662 dumpState.setTitlePrinted(true); 13663 } 13664 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13665 : "Provider Resolver Table:", " ", packageName, 13666 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13667 dumpState.setTitlePrinted(true); 13668 } 13669 } 13670 13671 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13672 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13673 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13674 int user = mSettings.mPreferredActivities.keyAt(i); 13675 if (pir.dump(pw, 13676 dumpState.getTitlePrinted() 13677 ? "\nPreferred Activities User " + user + ":" 13678 : "Preferred Activities User " + user + ":", " ", 13679 packageName, true, false)) { 13680 dumpState.setTitlePrinted(true); 13681 } 13682 } 13683 } 13684 13685 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13686 pw.flush(); 13687 FileOutputStream fout = new FileOutputStream(fd); 13688 BufferedOutputStream str = new BufferedOutputStream(fout); 13689 XmlSerializer serializer = new FastXmlSerializer(); 13690 try { 13691 serializer.setOutput(str, "utf-8"); 13692 serializer.startDocument(null, true); 13693 serializer.setFeature( 13694 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13695 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13696 serializer.endDocument(); 13697 serializer.flush(); 13698 } catch (IllegalArgumentException e) { 13699 pw.println("Failed writing: " + e); 13700 } catch (IllegalStateException e) { 13701 pw.println("Failed writing: " + e); 13702 } catch (IOException e) { 13703 pw.println("Failed writing: " + e); 13704 } 13705 } 13706 13707 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13708 pw.println(); 13709 int count = mSettings.mPackages.size(); 13710 if (count == 0) { 13711 pw.println("No domain preferred apps!"); 13712 pw.println(); 13713 } else { 13714 final String prefix = " "; 13715 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13716 if (allPackageSettings.size() == 0) { 13717 pw.println("No domain preferred apps!"); 13718 pw.println(); 13719 } else { 13720 pw.println("Domain preferred apps status:"); 13721 pw.println(); 13722 count = 0; 13723 for (PackageSetting ps : allPackageSettings) { 13724 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13725 if (ivi == null || ivi.getPackageName() == null) continue; 13726 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13727 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13728 pw.println(prefix + "Status: " + ivi.getStatusString()); 13729 pw.println(); 13730 count++; 13731 } 13732 if (count == 0) { 13733 pw.println(prefix + "No domain preferred app status!"); 13734 pw.println(); 13735 } 13736 for (int userId : sUserManager.getUserIds()) { 13737 pw.println("Domain preferred apps for User " + userId + ":"); 13738 pw.println(); 13739 count = 0; 13740 for (PackageSetting ps : allPackageSettings) { 13741 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13742 if (ivi == null || ivi.getPackageName() == null) { 13743 continue; 13744 } 13745 final int status = ps.getDomainVerificationStatusForUser(userId); 13746 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13747 continue; 13748 } 13749 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13750 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13751 String statusStr = IntentFilterVerificationInfo. 13752 getStatusStringFromValue(status); 13753 pw.println(prefix + "Status: " + statusStr); 13754 pw.println(); 13755 count++; 13756 } 13757 if (count == 0) { 13758 pw.println(prefix + "No domain preferred apps!"); 13759 pw.println(); 13760 } 13761 } 13762 } 13763 } 13764 } 13765 13766 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13767 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13768 if (packageName == null) { 13769 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13770 if (iperm == 0) { 13771 if (dumpState.onTitlePrinted()) 13772 pw.println(); 13773 pw.println("AppOp Permissions:"); 13774 } 13775 pw.print(" AppOp Permission "); 13776 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13777 pw.println(":"); 13778 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13779 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13780 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13781 } 13782 } 13783 } 13784 } 13785 13786 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13787 boolean printedSomething = false; 13788 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13789 if (packageName != null && !packageName.equals(p.info.packageName)) { 13790 continue; 13791 } 13792 if (!printedSomething) { 13793 if (dumpState.onTitlePrinted()) 13794 pw.println(); 13795 pw.println("Registered ContentProviders:"); 13796 printedSomething = true; 13797 } 13798 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13799 pw.print(" "); pw.println(p.toString()); 13800 } 13801 printedSomething = false; 13802 for (Map.Entry<String, PackageParser.Provider> entry : 13803 mProvidersByAuthority.entrySet()) { 13804 PackageParser.Provider p = entry.getValue(); 13805 if (packageName != null && !packageName.equals(p.info.packageName)) { 13806 continue; 13807 } 13808 if (!printedSomething) { 13809 if (dumpState.onTitlePrinted()) 13810 pw.println(); 13811 pw.println("ContentProvider Authorities:"); 13812 printedSomething = true; 13813 } 13814 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13815 pw.print(" "); pw.println(p.toString()); 13816 if (p.info != null && p.info.applicationInfo != null) { 13817 final String appInfo = p.info.applicationInfo.toString(); 13818 pw.print(" applicationInfo="); pw.println(appInfo); 13819 } 13820 } 13821 } 13822 13823 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13824 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13825 } 13826 13827 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13828 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13829 } 13830 13831 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13832 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13833 } 13834 13835 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13836 // XXX should handle packageName != null by dumping only install data that 13837 // the given package is involved with. 13838 if (dumpState.onTitlePrinted()) pw.println(); 13839 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13840 } 13841 13842 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13843 if (dumpState.onTitlePrinted()) pw.println(); 13844 mSettings.dumpReadMessagesLPr(pw, dumpState); 13845 13846 pw.println(); 13847 pw.println("Package warning messages:"); 13848 BufferedReader in = null; 13849 String line = null; 13850 try { 13851 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13852 while ((line = in.readLine()) != null) { 13853 if (line.contains("ignored: updated version")) continue; 13854 pw.println(line); 13855 } 13856 } catch (IOException ignored) { 13857 } finally { 13858 IoUtils.closeQuietly(in); 13859 } 13860 } 13861 13862 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13863 BufferedReader in = null; 13864 String line = null; 13865 try { 13866 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13867 while ((line = in.readLine()) != null) { 13868 if (line.contains("ignored: updated version")) continue; 13869 pw.print("msg,"); 13870 pw.println(line); 13871 } 13872 } catch (IOException ignored) { 13873 } finally { 13874 IoUtils.closeQuietly(in); 13875 } 13876 } 13877 } 13878 } 13879 13880 // ------- apps on sdcard specific code ------- 13881 static final boolean DEBUG_SD_INSTALL = false; 13882 13883 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13884 13885 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13886 13887 private boolean mMediaMounted = false; 13888 13889 static String getEncryptKey() { 13890 try { 13891 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13892 SD_ENCRYPTION_KEYSTORE_NAME); 13893 if (sdEncKey == null) { 13894 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13895 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13896 if (sdEncKey == null) { 13897 Slog.e(TAG, "Failed to create encryption keys"); 13898 return null; 13899 } 13900 } 13901 return sdEncKey; 13902 } catch (NoSuchAlgorithmException nsae) { 13903 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13904 return null; 13905 } catch (IOException ioe) { 13906 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13907 return null; 13908 } 13909 } 13910 13911 /* 13912 * Update media status on PackageManager. 13913 */ 13914 @Override 13915 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13916 int callingUid = Binder.getCallingUid(); 13917 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13918 throw new SecurityException("Media status can only be updated by the system"); 13919 } 13920 // reader; this apparently protects mMediaMounted, but should probably 13921 // be a different lock in that case. 13922 synchronized (mPackages) { 13923 Log.i(TAG, "Updating external media status from " 13924 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13925 + (mediaStatus ? "mounted" : "unmounted")); 13926 if (DEBUG_SD_INSTALL) 13927 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13928 + ", mMediaMounted=" + mMediaMounted); 13929 if (mediaStatus == mMediaMounted) { 13930 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13931 : 0, -1); 13932 mHandler.sendMessage(msg); 13933 return; 13934 } 13935 mMediaMounted = mediaStatus; 13936 } 13937 // Queue up an async operation since the package installation may take a 13938 // little while. 13939 mHandler.post(new Runnable() { 13940 public void run() { 13941 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13942 } 13943 }); 13944 } 13945 13946 /** 13947 * Called by MountService when the initial ASECs to scan are available. 13948 * Should block until all the ASEC containers are finished being scanned. 13949 */ 13950 public void scanAvailableAsecs() { 13951 updateExternalMediaStatusInner(true, false, false); 13952 if (mShouldRestoreconData) { 13953 SELinuxMMAC.setRestoreconDone(); 13954 mShouldRestoreconData = false; 13955 } 13956 } 13957 13958 /* 13959 * Collect information of applications on external media, map them against 13960 * existing containers and update information based on current mount status. 13961 * Please note that we always have to report status if reportStatus has been 13962 * set to true especially when unloading packages. 13963 */ 13964 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13965 boolean externalStorage) { 13966 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13967 int[] uidArr = EmptyArray.INT; 13968 13969 final String[] list = PackageHelper.getSecureContainerList(); 13970 if (ArrayUtils.isEmpty(list)) { 13971 Log.i(TAG, "No secure containers found"); 13972 } else { 13973 // Process list of secure containers and categorize them 13974 // as active or stale based on their package internal state. 13975 13976 // reader 13977 synchronized (mPackages) { 13978 for (String cid : list) { 13979 // Leave stages untouched for now; installer service owns them 13980 if (PackageInstallerService.isStageName(cid)) continue; 13981 13982 if (DEBUG_SD_INSTALL) 13983 Log.i(TAG, "Processing container " + cid); 13984 String pkgName = getAsecPackageName(cid); 13985 if (pkgName == null) { 13986 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13987 continue; 13988 } 13989 if (DEBUG_SD_INSTALL) 13990 Log.i(TAG, "Looking for pkg : " + pkgName); 13991 13992 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13993 if (ps == null) { 13994 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13995 continue; 13996 } 13997 13998 /* 13999 * Skip packages that are not external if we're unmounting 14000 * external storage. 14001 */ 14002 if (externalStorage && !isMounted && !isExternal(ps)) { 14003 continue; 14004 } 14005 14006 final AsecInstallArgs args = new AsecInstallArgs(cid, 14007 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14008 // The package status is changed only if the code path 14009 // matches between settings and the container id. 14010 if (ps.codePathString != null 14011 && ps.codePathString.startsWith(args.getCodePath())) { 14012 if (DEBUG_SD_INSTALL) { 14013 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14014 + " at code path: " + ps.codePathString); 14015 } 14016 14017 // We do have a valid package installed on sdcard 14018 processCids.put(args, ps.codePathString); 14019 final int uid = ps.appId; 14020 if (uid != -1) { 14021 uidArr = ArrayUtils.appendInt(uidArr, uid); 14022 } 14023 } else { 14024 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14025 + ps.codePathString); 14026 } 14027 } 14028 } 14029 14030 Arrays.sort(uidArr); 14031 } 14032 14033 // Process packages with valid entries. 14034 if (isMounted) { 14035 if (DEBUG_SD_INSTALL) 14036 Log.i(TAG, "Loading packages"); 14037 loadMediaPackages(processCids, uidArr); 14038 startCleaningPackages(); 14039 mInstallerService.onSecureContainersAvailable(); 14040 } else { 14041 if (DEBUG_SD_INSTALL) 14042 Log.i(TAG, "Unloading packages"); 14043 unloadMediaPackages(processCids, uidArr, reportStatus); 14044 } 14045 } 14046 14047 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14048 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14049 final int size = infos.size(); 14050 final String[] packageNames = new String[size]; 14051 final int[] packageUids = new int[size]; 14052 for (int i = 0; i < size; i++) { 14053 final ApplicationInfo info = infos.get(i); 14054 packageNames[i] = info.packageName; 14055 packageUids[i] = info.uid; 14056 } 14057 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14058 finishedReceiver); 14059 } 14060 14061 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14062 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14063 sendResourcesChangedBroadcast(mediaStatus, replacing, 14064 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14065 } 14066 14067 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14068 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14069 int size = pkgList.length; 14070 if (size > 0) { 14071 // Send broadcasts here 14072 Bundle extras = new Bundle(); 14073 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14074 if (uidArr != null) { 14075 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14076 } 14077 if (replacing) { 14078 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14079 } 14080 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14081 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14082 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14083 } 14084 } 14085 14086 /* 14087 * Look at potentially valid container ids from processCids If package 14088 * information doesn't match the one on record or package scanning fails, 14089 * the cid is added to list of removeCids. We currently don't delete stale 14090 * containers. 14091 */ 14092 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14093 ArrayList<String> pkgList = new ArrayList<String>(); 14094 Set<AsecInstallArgs> keys = processCids.keySet(); 14095 14096 for (AsecInstallArgs args : keys) { 14097 String codePath = processCids.get(args); 14098 if (DEBUG_SD_INSTALL) 14099 Log.i(TAG, "Loading container : " + args.cid); 14100 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14101 try { 14102 // Make sure there are no container errors first. 14103 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14104 Slog.e(TAG, "Failed to mount cid : " + args.cid 14105 + " when installing from sdcard"); 14106 continue; 14107 } 14108 // Check code path here. 14109 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14110 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14111 + " does not match one in settings " + codePath); 14112 continue; 14113 } 14114 // Parse package 14115 int parseFlags = mDefParseFlags; 14116 if (args.isExternalAsec()) { 14117 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14118 } 14119 if (args.isFwdLocked()) { 14120 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14121 } 14122 14123 synchronized (mInstallLock) { 14124 PackageParser.Package pkg = null; 14125 try { 14126 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14127 } catch (PackageManagerException e) { 14128 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14129 } 14130 // Scan the package 14131 if (pkg != null) { 14132 /* 14133 * TODO why is the lock being held? doPostInstall is 14134 * called in other places without the lock. This needs 14135 * to be straightened out. 14136 */ 14137 // writer 14138 synchronized (mPackages) { 14139 retCode = PackageManager.INSTALL_SUCCEEDED; 14140 pkgList.add(pkg.packageName); 14141 // Post process args 14142 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14143 pkg.applicationInfo.uid); 14144 } 14145 } else { 14146 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14147 } 14148 } 14149 14150 } finally { 14151 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14152 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14153 } 14154 } 14155 } 14156 // writer 14157 synchronized (mPackages) { 14158 // If the platform SDK has changed since the last time we booted, 14159 // we need to re-grant app permission to catch any new ones that 14160 // appear. This is really a hack, and means that apps can in some 14161 // cases get permissions that the user didn't initially explicitly 14162 // allow... it would be nice to have some better way to handle 14163 // this situation. 14164 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14165 if (regrantPermissions) 14166 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14167 + mSdkVersion + "; regranting permissions for external storage"); 14168 mSettings.mExternalSdkPlatform = mSdkVersion; 14169 14170 // Make sure group IDs have been assigned, and any permission 14171 // changes in other apps are accounted for 14172 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14173 | (regrantPermissions 14174 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14175 : 0)); 14176 14177 mSettings.updateExternalDatabaseVersion(); 14178 14179 // can downgrade to reader 14180 // Persist settings 14181 mSettings.writeLPr(); 14182 } 14183 // Send a broadcast to let everyone know we are done processing 14184 if (pkgList.size() > 0) { 14185 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14186 } 14187 } 14188 14189 /* 14190 * Utility method to unload a list of specified containers 14191 */ 14192 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14193 // Just unmount all valid containers. 14194 for (AsecInstallArgs arg : cidArgs) { 14195 synchronized (mInstallLock) { 14196 arg.doPostDeleteLI(false); 14197 } 14198 } 14199 } 14200 14201 /* 14202 * Unload packages mounted on external media. This involves deleting package 14203 * data from internal structures, sending broadcasts about diabled packages, 14204 * gc'ing to free up references, unmounting all secure containers 14205 * corresponding to packages on external media, and posting a 14206 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14207 * that we always have to post this message if status has been requested no 14208 * matter what. 14209 */ 14210 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14211 final boolean reportStatus) { 14212 if (DEBUG_SD_INSTALL) 14213 Log.i(TAG, "unloading media packages"); 14214 ArrayList<String> pkgList = new ArrayList<String>(); 14215 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14216 final Set<AsecInstallArgs> keys = processCids.keySet(); 14217 for (AsecInstallArgs args : keys) { 14218 String pkgName = args.getPackageName(); 14219 if (DEBUG_SD_INSTALL) 14220 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14221 // Delete package internally 14222 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14223 synchronized (mInstallLock) { 14224 boolean res = deletePackageLI(pkgName, null, false, null, null, 14225 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14226 if (res) { 14227 pkgList.add(pkgName); 14228 } else { 14229 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14230 failedList.add(args); 14231 } 14232 } 14233 } 14234 14235 // reader 14236 synchronized (mPackages) { 14237 // We didn't update the settings after removing each package; 14238 // write them now for all packages. 14239 mSettings.writeLPr(); 14240 } 14241 14242 // We have to absolutely send UPDATED_MEDIA_STATUS only 14243 // after confirming that all the receivers processed the ordered 14244 // broadcast when packages get disabled, force a gc to clean things up. 14245 // and unload all the containers. 14246 if (pkgList.size() > 0) { 14247 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14248 new IIntentReceiver.Stub() { 14249 public void performReceive(Intent intent, int resultCode, String data, 14250 Bundle extras, boolean ordered, boolean sticky, 14251 int sendingUser) throws RemoteException { 14252 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14253 reportStatus ? 1 : 0, 1, keys); 14254 mHandler.sendMessage(msg); 14255 } 14256 }); 14257 } else { 14258 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14259 keys); 14260 mHandler.sendMessage(msg); 14261 } 14262 } 14263 14264 private void loadPrivatePackages(VolumeInfo vol) { 14265 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14266 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14267 synchronized (mInstallLock) { 14268 synchronized (mPackages) { 14269 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14270 for (PackageSetting ps : packages) { 14271 final PackageParser.Package pkg; 14272 try { 14273 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14274 loaded.add(pkg.applicationInfo); 14275 } catch (PackageManagerException e) { 14276 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14277 } 14278 } 14279 14280 // TODO: regrant any permissions that changed based since original install 14281 14282 mSettings.writeLPr(); 14283 } 14284 } 14285 14286 Slog.d(TAG, "Loaded packages " + loaded); 14287 sendResourcesChangedBroadcast(true, false, loaded, null); 14288 } 14289 14290 private void unloadPrivatePackages(VolumeInfo vol) { 14291 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14292 synchronized (mInstallLock) { 14293 synchronized (mPackages) { 14294 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14295 for (PackageSetting ps : packages) { 14296 if (ps.pkg == null) continue; 14297 14298 final ApplicationInfo info = ps.pkg.applicationInfo; 14299 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14300 if (deletePackageLI(ps.name, null, false, null, null, 14301 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14302 unloaded.add(info); 14303 } else { 14304 Slog.w(TAG, "Failed to unload " + ps.codePath); 14305 } 14306 } 14307 14308 mSettings.writeLPr(); 14309 } 14310 } 14311 14312 Slog.d(TAG, "Unloaded packages " + unloaded); 14313 sendResourcesChangedBroadcast(false, false, unloaded, null); 14314 } 14315 14316 private void unfreezePackage(String packageName) { 14317 synchronized (mPackages) { 14318 final PackageSetting ps = mSettings.mPackages.get(packageName); 14319 if (ps != null) { 14320 ps.frozen = false; 14321 } 14322 } 14323 } 14324 14325 @Override 14326 public int movePackage(final String packageName, final String volumeUuid) { 14327 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14328 14329 final int moveId = mNextMoveId.getAndIncrement(); 14330 try { 14331 movePackageInternal(packageName, volumeUuid, moveId); 14332 } catch (PackageManagerException e) { 14333 Slog.d(TAG, "Failed to move " + packageName, e); 14334 mMoveCallbacks.notifyStatusChanged(moveId, 14335 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14336 } 14337 return moveId; 14338 } 14339 14340 private void movePackageInternal(final String packageName, final String volumeUuid, 14341 final int moveId) throws PackageManagerException { 14342 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14343 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14344 final PackageManager pm = mContext.getPackageManager(); 14345 14346 final boolean currentAsec; 14347 final String currentVolumeUuid; 14348 final File codeFile; 14349 final String installerPackageName; 14350 final String packageAbiOverride; 14351 final int appId; 14352 final String seinfo; 14353 final String label; 14354 14355 // reader 14356 synchronized (mPackages) { 14357 final PackageParser.Package pkg = mPackages.get(packageName); 14358 final PackageSetting ps = mSettings.mPackages.get(packageName); 14359 if (pkg == null || ps == null) { 14360 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14361 } 14362 14363 if (pkg.applicationInfo.isSystemApp()) { 14364 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14365 "Cannot move system application"); 14366 } 14367 14368 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14369 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14370 "Package already moved to " + volumeUuid); 14371 } 14372 14373 final File probe = new File(pkg.codePath); 14374 final File probeOat = new File(probe, "oat"); 14375 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14376 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14377 "Move only supported for modern cluster style installs"); 14378 } 14379 14380 if (ps.frozen) { 14381 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14382 "Failed to move already frozen package"); 14383 } 14384 ps.frozen = true; 14385 14386 currentAsec = pkg.applicationInfo.isForwardLocked() 14387 || pkg.applicationInfo.isExternalAsec(); 14388 currentVolumeUuid = ps.volumeUuid; 14389 codeFile = new File(pkg.codePath); 14390 installerPackageName = ps.installerPackageName; 14391 packageAbiOverride = ps.cpuAbiOverrideString; 14392 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14393 seinfo = pkg.applicationInfo.seinfo; 14394 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14395 } 14396 14397 // Now that we're guarded by frozen state, kill app during move 14398 killApplication(packageName, appId, "move pkg"); 14399 14400 final Bundle extras = new Bundle(); 14401 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14402 extras.putString(Intent.EXTRA_TITLE, label); 14403 mMoveCallbacks.notifyCreated(moveId, extras); 14404 14405 int installFlags; 14406 final boolean moveCompleteApp; 14407 final File measurePath; 14408 14409 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14410 installFlags = INSTALL_INTERNAL; 14411 moveCompleteApp = !currentAsec; 14412 measurePath = Environment.getDataAppDirectory(volumeUuid); 14413 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14414 installFlags = INSTALL_EXTERNAL; 14415 moveCompleteApp = false; 14416 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14417 } else { 14418 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14419 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14420 || !volume.isMountedWritable()) { 14421 unfreezePackage(packageName); 14422 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14423 "Move location not mounted private volume"); 14424 } 14425 14426 Preconditions.checkState(!currentAsec); 14427 14428 installFlags = INSTALL_INTERNAL; 14429 moveCompleteApp = true; 14430 measurePath = Environment.getDataAppDirectory(volumeUuid); 14431 } 14432 14433 final PackageStats stats = new PackageStats(null, -1); 14434 synchronized (mInstaller) { 14435 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14436 unfreezePackage(packageName); 14437 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14438 "Failed to measure package size"); 14439 } 14440 } 14441 14442 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14443 14444 final long startFreeBytes = measurePath.getFreeSpace(); 14445 final long sizeBytes; 14446 if (moveCompleteApp) { 14447 sizeBytes = stats.codeSize + stats.dataSize; 14448 } else { 14449 sizeBytes = stats.codeSize; 14450 } 14451 14452 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14453 unfreezePackage(packageName); 14454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14455 "Not enough free space to move"); 14456 } 14457 14458 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14459 14460 final CountDownLatch installedLatch = new CountDownLatch(1); 14461 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14462 @Override 14463 public void onUserActionRequired(Intent intent) throws RemoteException { 14464 throw new IllegalStateException(); 14465 } 14466 14467 @Override 14468 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14469 Bundle extras) throws RemoteException { 14470 Slog.d(TAG, "Install result for move: " 14471 + PackageManager.installStatusToString(returnCode, msg)); 14472 14473 installedLatch.countDown(); 14474 14475 // Regardless of success or failure of the move operation, 14476 // always unfreeze the package 14477 unfreezePackage(packageName); 14478 14479 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14480 switch (status) { 14481 case PackageInstaller.STATUS_SUCCESS: 14482 mMoveCallbacks.notifyStatusChanged(moveId, 14483 PackageManager.MOVE_SUCCEEDED); 14484 break; 14485 case PackageInstaller.STATUS_FAILURE_STORAGE: 14486 mMoveCallbacks.notifyStatusChanged(moveId, 14487 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14488 break; 14489 default: 14490 mMoveCallbacks.notifyStatusChanged(moveId, 14491 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14492 break; 14493 } 14494 } 14495 }; 14496 14497 final MoveInfo move; 14498 if (moveCompleteApp) { 14499 // Kick off a thread to report progress estimates 14500 new Thread() { 14501 @Override 14502 public void run() { 14503 while (true) { 14504 try { 14505 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14506 break; 14507 } 14508 } catch (InterruptedException ignored) { 14509 } 14510 14511 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14512 final int progress = 10 + (int) MathUtils.constrain( 14513 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14514 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14515 } 14516 } 14517 }.start(); 14518 14519 final String dataAppName = codeFile.getName(); 14520 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14521 dataAppName, appId, seinfo); 14522 } else { 14523 move = null; 14524 } 14525 14526 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14527 14528 final Message msg = mHandler.obtainMessage(INIT_COPY); 14529 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14530 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14531 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14532 mHandler.sendMessage(msg); 14533 } 14534 14535 @Override 14536 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14538 14539 final int realMoveId = mNextMoveId.getAndIncrement(); 14540 final Bundle extras = new Bundle(); 14541 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14542 mMoveCallbacks.notifyCreated(realMoveId, extras); 14543 14544 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14545 @Override 14546 public void onCreated(int moveId, Bundle extras) { 14547 // Ignored 14548 } 14549 14550 @Override 14551 public void onStatusChanged(int moveId, int status, long estMillis) { 14552 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14553 } 14554 }; 14555 14556 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14557 storage.setPrimaryStorageUuid(volumeUuid, callback); 14558 return realMoveId; 14559 } 14560 14561 @Override 14562 public int getMoveStatus(int moveId) { 14563 mContext.enforceCallingOrSelfPermission( 14564 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14565 return mMoveCallbacks.mLastStatus.get(moveId); 14566 } 14567 14568 @Override 14569 public void registerMoveCallback(IPackageMoveObserver callback) { 14570 mContext.enforceCallingOrSelfPermission( 14571 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14572 mMoveCallbacks.register(callback); 14573 } 14574 14575 @Override 14576 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14577 mContext.enforceCallingOrSelfPermission( 14578 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14579 mMoveCallbacks.unregister(callback); 14580 } 14581 14582 @Override 14583 public boolean setInstallLocation(int loc) { 14584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14585 null); 14586 if (getInstallLocation() == loc) { 14587 return true; 14588 } 14589 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14590 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14591 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14592 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14593 return true; 14594 } 14595 return false; 14596 } 14597 14598 @Override 14599 public int getInstallLocation() { 14600 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14601 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14602 PackageHelper.APP_INSTALL_AUTO); 14603 } 14604 14605 /** Called by UserManagerService */ 14606 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14607 mDirtyUsers.remove(userHandle); 14608 mSettings.removeUserLPw(userHandle); 14609 mPendingBroadcasts.remove(userHandle); 14610 if (mInstaller != null) { 14611 // Technically, we shouldn't be doing this with the package lock 14612 // held. However, this is very rare, and there is already so much 14613 // other disk I/O going on, that we'll let it slide for now. 14614 final StorageManager storage = StorageManager.from(mContext); 14615 final List<VolumeInfo> vols = storage.getVolumes(); 14616 for (VolumeInfo vol : vols) { 14617 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14618 final String volumeUuid = vol.getFsUuid(); 14619 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14620 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14621 } 14622 } 14623 } 14624 mUserNeedsBadging.delete(userHandle); 14625 removeUnusedPackagesLILPw(userManager, userHandle); 14626 } 14627 14628 /** 14629 * We're removing userHandle and would like to remove any downloaded packages 14630 * that are no longer in use by any other user. 14631 * @param userHandle the user being removed 14632 */ 14633 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14634 final boolean DEBUG_CLEAN_APKS = false; 14635 int [] users = userManager.getUserIdsLPr(); 14636 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14637 while (psit.hasNext()) { 14638 PackageSetting ps = psit.next(); 14639 if (ps.pkg == null) { 14640 continue; 14641 } 14642 final String packageName = ps.pkg.packageName; 14643 // Skip over if system app 14644 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14645 continue; 14646 } 14647 if (DEBUG_CLEAN_APKS) { 14648 Slog.i(TAG, "Checking package " + packageName); 14649 } 14650 boolean keep = false; 14651 for (int i = 0; i < users.length; i++) { 14652 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14653 keep = true; 14654 if (DEBUG_CLEAN_APKS) { 14655 Slog.i(TAG, " Keeping package " + packageName + " for user " 14656 + users[i]); 14657 } 14658 break; 14659 } 14660 } 14661 if (!keep) { 14662 if (DEBUG_CLEAN_APKS) { 14663 Slog.i(TAG, " Removing package " + packageName); 14664 } 14665 mHandler.post(new Runnable() { 14666 public void run() { 14667 deletePackageX(packageName, userHandle, 0); 14668 } //end run 14669 }); 14670 } 14671 } 14672 } 14673 14674 /** Called by UserManagerService */ 14675 void createNewUserLILPw(int userHandle, File path) { 14676 if (mInstaller != null) { 14677 mInstaller.createUserConfig(userHandle); 14678 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14679 } 14680 } 14681 14682 void newUserCreatedLILPw(int userHandle) { 14683 // Adding a user requires updating runtime permissions for system apps. 14684 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14685 } 14686 14687 @Override 14688 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14689 mContext.enforceCallingOrSelfPermission( 14690 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14691 "Only package verification agents can read the verifier device identity"); 14692 14693 synchronized (mPackages) { 14694 return mSettings.getVerifierDeviceIdentityLPw(); 14695 } 14696 } 14697 14698 @Override 14699 public void setPermissionEnforced(String permission, boolean enforced) { 14700 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14701 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14702 synchronized (mPackages) { 14703 if (mSettings.mReadExternalStorageEnforced == null 14704 || mSettings.mReadExternalStorageEnforced != enforced) { 14705 mSettings.mReadExternalStorageEnforced = enforced; 14706 mSettings.writeLPr(); 14707 } 14708 } 14709 // kill any non-foreground processes so we restart them and 14710 // grant/revoke the GID. 14711 final IActivityManager am = ActivityManagerNative.getDefault(); 14712 if (am != null) { 14713 final long token = Binder.clearCallingIdentity(); 14714 try { 14715 am.killProcessesBelowForeground("setPermissionEnforcement"); 14716 } catch (RemoteException e) { 14717 } finally { 14718 Binder.restoreCallingIdentity(token); 14719 } 14720 } 14721 } else { 14722 throw new IllegalArgumentException("No selective enforcement for " + permission); 14723 } 14724 } 14725 14726 @Override 14727 @Deprecated 14728 public boolean isPermissionEnforced(String permission) { 14729 return true; 14730 } 14731 14732 @Override 14733 public boolean isStorageLow() { 14734 final long token = Binder.clearCallingIdentity(); 14735 try { 14736 final DeviceStorageMonitorInternal 14737 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14738 if (dsm != null) { 14739 return dsm.isMemoryLow(); 14740 } else { 14741 return false; 14742 } 14743 } finally { 14744 Binder.restoreCallingIdentity(token); 14745 } 14746 } 14747 14748 @Override 14749 public IPackageInstaller getPackageInstaller() { 14750 return mInstallerService; 14751 } 14752 14753 private boolean userNeedsBadging(int userId) { 14754 int index = mUserNeedsBadging.indexOfKey(userId); 14755 if (index < 0) { 14756 final UserInfo userInfo; 14757 final long token = Binder.clearCallingIdentity(); 14758 try { 14759 userInfo = sUserManager.getUserInfo(userId); 14760 } finally { 14761 Binder.restoreCallingIdentity(token); 14762 } 14763 final boolean b; 14764 if (userInfo != null && userInfo.isManagedProfile()) { 14765 b = true; 14766 } else { 14767 b = false; 14768 } 14769 mUserNeedsBadging.put(userId, b); 14770 return b; 14771 } 14772 return mUserNeedsBadging.valueAt(index); 14773 } 14774 14775 @Override 14776 public KeySet getKeySetByAlias(String packageName, String alias) { 14777 if (packageName == null || alias == null) { 14778 return null; 14779 } 14780 synchronized(mPackages) { 14781 final PackageParser.Package pkg = mPackages.get(packageName); 14782 if (pkg == null) { 14783 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14784 throw new IllegalArgumentException("Unknown package: " + packageName); 14785 } 14786 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14787 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14788 } 14789 } 14790 14791 @Override 14792 public KeySet getSigningKeySet(String packageName) { 14793 if (packageName == null) { 14794 return null; 14795 } 14796 synchronized(mPackages) { 14797 final PackageParser.Package pkg = mPackages.get(packageName); 14798 if (pkg == null) { 14799 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14800 throw new IllegalArgumentException("Unknown package: " + packageName); 14801 } 14802 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14803 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14804 throw new SecurityException("May not access signing KeySet of other apps."); 14805 } 14806 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14807 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14808 } 14809 } 14810 14811 @Override 14812 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14813 if (packageName == null || ks == null) { 14814 return false; 14815 } 14816 synchronized(mPackages) { 14817 final PackageParser.Package pkg = mPackages.get(packageName); 14818 if (pkg == null) { 14819 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14820 throw new IllegalArgumentException("Unknown package: " + packageName); 14821 } 14822 IBinder ksh = ks.getToken(); 14823 if (ksh instanceof KeySetHandle) { 14824 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14825 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14826 } 14827 return false; 14828 } 14829 } 14830 14831 @Override 14832 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14833 if (packageName == null || ks == null) { 14834 return false; 14835 } 14836 synchronized(mPackages) { 14837 final PackageParser.Package pkg = mPackages.get(packageName); 14838 if (pkg == null) { 14839 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14840 throw new IllegalArgumentException("Unknown package: " + packageName); 14841 } 14842 IBinder ksh = ks.getToken(); 14843 if (ksh instanceof KeySetHandle) { 14844 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14845 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14846 } 14847 return false; 14848 } 14849 } 14850 14851 public void getUsageStatsIfNoPackageUsageInfo() { 14852 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14853 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14854 if (usm == null) { 14855 throw new IllegalStateException("UsageStatsManager must be initialized"); 14856 } 14857 long now = System.currentTimeMillis(); 14858 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14859 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14860 String packageName = entry.getKey(); 14861 PackageParser.Package pkg = mPackages.get(packageName); 14862 if (pkg == null) { 14863 continue; 14864 } 14865 UsageStats usage = entry.getValue(); 14866 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14867 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14868 } 14869 } 14870 } 14871 14872 /** 14873 * Check and throw if the given before/after packages would be considered a 14874 * downgrade. 14875 */ 14876 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14877 throws PackageManagerException { 14878 if (after.versionCode < before.mVersionCode) { 14879 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14880 "Update version code " + after.versionCode + " is older than current " 14881 + before.mVersionCode); 14882 } else if (after.versionCode == before.mVersionCode) { 14883 if (after.baseRevisionCode < before.baseRevisionCode) { 14884 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14885 "Update base revision code " + after.baseRevisionCode 14886 + " is older than current " + before.baseRevisionCode); 14887 } 14888 14889 if (!ArrayUtils.isEmpty(after.splitNames)) { 14890 for (int i = 0; i < after.splitNames.length; i++) { 14891 final String splitName = after.splitNames[i]; 14892 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14893 if (j != -1) { 14894 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14895 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14896 "Update split " + splitName + " revision code " 14897 + after.splitRevisionCodes[i] + " is older than current " 14898 + before.splitRevisionCodes[j]); 14899 } 14900 } 14901 } 14902 } 14903 } 14904 } 14905 14906 private static class MoveCallbacks extends Handler { 14907 private static final int MSG_CREATED = 1; 14908 private static final int MSG_STATUS_CHANGED = 2; 14909 14910 private final RemoteCallbackList<IPackageMoveObserver> 14911 mCallbacks = new RemoteCallbackList<>(); 14912 14913 private final SparseIntArray mLastStatus = new SparseIntArray(); 14914 14915 public MoveCallbacks(Looper looper) { 14916 super(looper); 14917 } 14918 14919 public void register(IPackageMoveObserver callback) { 14920 mCallbacks.register(callback); 14921 } 14922 14923 public void unregister(IPackageMoveObserver callback) { 14924 mCallbacks.unregister(callback); 14925 } 14926 14927 @Override 14928 public void handleMessage(Message msg) { 14929 final SomeArgs args = (SomeArgs) msg.obj; 14930 final int n = mCallbacks.beginBroadcast(); 14931 for (int i = 0; i < n; i++) { 14932 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14933 try { 14934 invokeCallback(callback, msg.what, args); 14935 } catch (RemoteException ignored) { 14936 } 14937 } 14938 mCallbacks.finishBroadcast(); 14939 args.recycle(); 14940 } 14941 14942 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14943 throws RemoteException { 14944 switch (what) { 14945 case MSG_CREATED: { 14946 callback.onCreated(args.argi1, (Bundle) args.arg2); 14947 break; 14948 } 14949 case MSG_STATUS_CHANGED: { 14950 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14951 break; 14952 } 14953 } 14954 } 14955 14956 private void notifyCreated(int moveId, Bundle extras) { 14957 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 14958 14959 final SomeArgs args = SomeArgs.obtain(); 14960 args.argi1 = moveId; 14961 args.arg2 = extras; 14962 obtainMessage(MSG_CREATED, args).sendToTarget(); 14963 } 14964 14965 private void notifyStatusChanged(int moveId, int status) { 14966 notifyStatusChanged(moveId, status, -1); 14967 } 14968 14969 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14970 Slog.v(TAG, "Move " + moveId + " status " + status); 14971 14972 final SomeArgs args = SomeArgs.obtain(); 14973 args.argi1 = moveId; 14974 args.argi2 = status; 14975 args.arg3 = estMillis; 14976 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14977 14978 synchronized (mLastStatus) { 14979 mLastStatus.put(moveId, status); 14980 } 14981 } 14982 } 14983} 14984