PackageManagerService.java revision 9f7e39fc9d278642a29df48daf44dceff11acd17
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.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.text.format.DateUtils; 165import android.util.ArrayMap; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.util.SparseIntArray; 178import android.util.Xml; 179import android.view.Display; 180 181import dalvik.system.DexFile; 182import dalvik.system.VMRuntime; 183 184import libcore.io.IoUtils; 185import libcore.util.EmptyArray; 186 187import com.android.internal.R; 188import com.android.internal.app.IMediaContainerService; 189import com.android.internal.app.ResolverActivity; 190import com.android.internal.content.NativeLibraryHelper; 191import com.android.internal.content.PackageHelper; 192import com.android.internal.os.IParcelFileDescriptorFactory; 193import com.android.internal.os.SomeArgs; 194import com.android.internal.util.ArrayUtils; 195import com.android.internal.util.FastPrintWriter; 196import com.android.internal.util.FastXmlSerializer; 197import com.android.internal.util.IndentingPrintWriter; 198import com.android.internal.util.Preconditions; 199import com.android.server.EventLogTags; 200import com.android.server.FgThread; 201import com.android.server.IntentResolver; 202import com.android.server.LocalServices; 203import com.android.server.ServiceThread; 204import com.android.server.SystemConfig; 205import com.android.server.Watchdog; 206import com.android.server.pm.Settings.DatabaseVersion; 207import com.android.server.storage.DeviceStorageMonitorInternal; 208 209import org.xmlpull.v1.XmlPullParser; 210import org.xmlpull.v1.XmlSerializer; 211 212import java.io.BufferedInputStream; 213import java.io.BufferedOutputStream; 214import java.io.BufferedReader; 215import java.io.ByteArrayInputStream; 216import java.io.ByteArrayOutputStream; 217import java.io.File; 218import java.io.FileDescriptor; 219import java.io.FileNotFoundException; 220import java.io.FileOutputStream; 221import java.io.FileReader; 222import java.io.FilenameFilter; 223import java.io.IOException; 224import java.io.InputStream; 225import java.io.PrintWriter; 226import java.nio.charset.StandardCharsets; 227import java.security.NoSuchAlgorithmException; 228import java.security.PublicKey; 229import java.security.cert.CertificateEncodingException; 230import java.security.cert.CertificateException; 231import java.text.SimpleDateFormat; 232import java.util.ArrayList; 233import java.util.Arrays; 234import java.util.Collection; 235import java.util.Collections; 236import java.util.Comparator; 237import java.util.Date; 238import java.util.Iterator; 239import java.util.List; 240import java.util.Map; 241import java.util.Objects; 242import java.util.Set; 243import java.util.concurrent.atomic.AtomicBoolean; 244import java.util.concurrent.atomic.AtomicInteger; 245import java.util.concurrent.atomic.AtomicLong; 246 247/** 248 * Keep track of all those .apks everywhere. 249 * 250 * This is very central to the platform's security; please run the unit 251 * tests whenever making modifications here: 252 * 253mmm frameworks/base/tests/AndroidTests 254adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 255adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 256 * 257 * {@hide} 258 */ 259public class PackageManagerService extends IPackageManager.Stub { 260 static final String TAG = "PackageManager"; 261 static final boolean DEBUG_SETTINGS = false; 262 static final boolean DEBUG_PREFERRED = false; 263 static final boolean DEBUG_UPGRADE = false; 264 private static final boolean DEBUG_BACKUP = true; 265 private static final boolean DEBUG_INSTALL = false; 266 private static final boolean DEBUG_REMOVE = false; 267 private static final boolean DEBUG_BROADCASTS = false; 268 private static final boolean DEBUG_SHOW_INFO = false; 269 private static final boolean DEBUG_PACKAGE_INFO = false; 270 private static final boolean DEBUG_INTENT_MATCHING = false; 271 private static final boolean DEBUG_PACKAGE_SCANNING = false; 272 private static final boolean DEBUG_VERIFY = false; 273 private static final boolean DEBUG_DEXOPT = false; 274 private static final boolean DEBUG_ABI_SELECTION = false; 275 276 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 277 278 private static final int RADIO_UID = Process.PHONE_UID; 279 private static final int LOG_UID = Process.LOG_UID; 280 private static final int NFC_UID = Process.NFC_UID; 281 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 282 private static final int SHELL_UID = Process.SHELL_UID; 283 284 // Cap the size of permission trees that 3rd party apps can define 285 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 286 287 // Suffix used during package installation when copying/moving 288 // package apks to install directory. 289 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 290 291 static final int SCAN_NO_DEX = 1<<1; 292 static final int SCAN_FORCE_DEX = 1<<2; 293 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 294 static final int SCAN_NEW_INSTALL = 1<<4; 295 static final int SCAN_NO_PATHS = 1<<5; 296 static final int SCAN_UPDATE_TIME = 1<<6; 297 static final int SCAN_DEFER_DEX = 1<<7; 298 static final int SCAN_BOOTING = 1<<8; 299 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 300 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 301 static final int SCAN_REPLACING = 1<<11; 302 static final int SCAN_REQUIRE_KNOWN = 1<<12; 303 304 static final int REMOVE_CHATTY = 1<<16; 305 306 /** 307 * Timeout (in milliseconds) after which the watchdog should declare that 308 * our handler thread is wedged. The usual default for such things is one 309 * minute but we sometimes do very lengthy I/O operations on this thread, 310 * such as installing multi-gigabyte applications, so ours needs to be longer. 311 */ 312 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 313 314 /** 315 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 316 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 317 * settings entry if available, otherwise we use the hardcoded default. If it's been 318 * more than this long since the last fstrim, we force one during the boot sequence. 319 * 320 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 321 * one gets run at the next available charging+idle time. This final mandatory 322 * no-fstrim check kicks in only of the other scheduling criteria is never met. 323 */ 324 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 325 326 /** 327 * Whether verification is enabled by default. 328 */ 329 private static final boolean DEFAULT_VERIFY_ENABLE = true; 330 331 /** 332 * The default maximum time to wait for the verification agent to return in 333 * milliseconds. 334 */ 335 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 336 337 /** 338 * The default response for package verification timeout. 339 * 340 * This can be either PackageManager.VERIFICATION_ALLOW or 341 * PackageManager.VERIFICATION_REJECT. 342 */ 343 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 344 345 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 346 347 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 348 DEFAULT_CONTAINER_PACKAGE, 349 "com.android.defcontainer.DefaultContainerService"); 350 351 private static final String KILL_APP_REASON_GIDS_CHANGED = 352 "permission grant or revoke changed gids"; 353 354 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 355 "permissions revoked"; 356 357 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 358 359 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 360 361 /** Permission grant: not grant the permission. */ 362 private static final int GRANT_DENIED = 1; 363 364 /** Permission grant: grant the permission as an install permission. */ 365 private static final int GRANT_INSTALL = 2; 366 367 /** Permission grant: grant the permission as a runtime one. */ 368 private static final int GRANT_RUNTIME = 3; 369 370 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 371 private static final int GRANT_UPGRADE = 4; 372 373 final ServiceThread mHandlerThread; 374 375 final PackageHandler mHandler; 376 377 /** 378 * Messages for {@link #mHandler} that need to wait for system ready before 379 * being dispatched. 380 */ 381 private ArrayList<Message> mPostSystemReadyMessages; 382 383 final int mSdkVersion = Build.VERSION.SDK_INT; 384 385 final Context mContext; 386 final boolean mFactoryTest; 387 final boolean mOnlyCore; 388 final boolean mLazyDexOpt; 389 final long mDexOptLRUThresholdInMills; 390 final DisplayMetrics mMetrics; 391 final int mDefParseFlags; 392 final String[] mSeparateProcesses; 393 final boolean mIsUpgrade; 394 395 // This is where all application persistent data goes. 396 final File mAppDataDir; 397 398 // This is where all application persistent data goes for secondary users. 399 final File mUserAppDataDir; 400 401 /** The location for ASEC container files on internal storage. */ 402 final String mAsecInternalPath; 403 404 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 405 // LOCK HELD. Can be called with mInstallLock held. 406 final Installer mInstaller; 407 408 /** Directory where installed third-party apps stored */ 409 final File mAppInstallDir; 410 411 /** 412 * Directory to which applications installed internally have their 413 * 32 bit native libraries copied. 414 */ 415 private File mAppLib32InstallDir; 416 417 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 418 // apps. 419 final File mDrmAppPrivateInstallDir; 420 421 // ---------------------------------------------------------------- 422 423 // Lock for state used when installing and doing other long running 424 // operations. Methods that must be called with this lock held have 425 // the suffix "LI". 426 final Object mInstallLock = new Object(); 427 428 // ---------------------------------------------------------------- 429 430 // Keys are String (package name), values are Package. This also serves 431 // as the lock for the global state. Methods that must be called with 432 // this lock held have the prefix "LP". 433 final ArrayMap<String, PackageParser.Package> mPackages = 434 new ArrayMap<String, PackageParser.Package>(); 435 436 // Tracks available target package names -> overlay package paths. 437 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 438 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 439 440 final Settings mSettings; 441 boolean mRestoredSettings; 442 443 // System configuration read by SystemConfig. 444 final int[] mGlobalGids; 445 final SparseArray<ArraySet<String>> mSystemPermissions; 446 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 447 448 // If mac_permissions.xml was found for seinfo labeling. 449 boolean mFoundPolicyFile; 450 451 // If a recursive restorecon of /data/data/<pkg> is needed. 452 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 453 454 public static final class SharedLibraryEntry { 455 public final String path; 456 public final String apk; 457 458 SharedLibraryEntry(String _path, String _apk) { 459 path = _path; 460 apk = _apk; 461 } 462 } 463 464 // Currently known shared libraries. 465 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 466 new ArrayMap<String, SharedLibraryEntry>(); 467 468 // All available activities, for your resolving pleasure. 469 final ActivityIntentResolver mActivities = 470 new ActivityIntentResolver(); 471 472 // All available receivers, for your resolving pleasure. 473 final ActivityIntentResolver mReceivers = 474 new ActivityIntentResolver(); 475 476 // All available services, for your resolving pleasure. 477 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 478 479 // All available providers, for your resolving pleasure. 480 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 481 482 // Mapping from provider base names (first directory in content URI codePath) 483 // to the provider information. 484 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 485 new ArrayMap<String, PackageParser.Provider>(); 486 487 // Mapping from instrumentation class names to info about them. 488 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 489 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 490 491 // Mapping from permission names to info about them. 492 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 493 new ArrayMap<String, PackageParser.PermissionGroup>(); 494 495 // Packages whose data we have transfered into another package, thus 496 // should no longer exist. 497 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 498 499 // Broadcast actions that are only available to the system. 500 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 501 502 /** List of packages waiting for verification. */ 503 final SparseArray<PackageVerificationState> mPendingVerification 504 = new SparseArray<PackageVerificationState>(); 505 506 /** Set of packages associated with each app op permission. */ 507 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 508 509 final PackageInstallerService mInstallerService; 510 511 private final PackageDexOptimizer mPackageDexOptimizer; 512 513 private AtomicInteger mNextMoveId = new AtomicInteger(); 514 private final MoveCallbacks mMoveCallbacks; 515 516 // Cache of users who need badging. 517 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 518 519 /** Token for keys in mPendingVerification. */ 520 private int mPendingVerificationToken = 0; 521 522 volatile boolean mSystemReady; 523 volatile boolean mSafeMode; 524 volatile boolean mHasSystemUidErrors; 525 526 ApplicationInfo mAndroidApplication; 527 final ActivityInfo mResolveActivity = new ActivityInfo(); 528 final ResolveInfo mResolveInfo = new ResolveInfo(); 529 ComponentName mResolveComponentName; 530 PackageParser.Package mPlatformPackage; 531 ComponentName mCustomResolverComponentName; 532 533 boolean mResolverReplaced = false; 534 535 private final ComponentName mIntentFilterVerifierComponent; 536 private int mIntentFilterVerificationToken = 0; 537 538 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 539 = new SparseArray<IntentFilterVerificationState>(); 540 541 private interface IntentFilterVerifier<T extends IntentFilter> { 542 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 543 T filter, String packageName); 544 void startVerifications(int userId); 545 void receiveVerificationResponse(int verificationId); 546 } 547 548 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 549 private Context mContext; 550 private ComponentName mIntentFilterVerifierComponent; 551 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 552 553 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 554 mContext = context; 555 mIntentFilterVerifierComponent = verifierComponent; 556 } 557 558 private String getDefaultScheme() { 559 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 560 return IntentFilter.SCHEME_HTTP; 561 } 562 563 @Override 564 public void startVerifications(int userId) { 565 // Launch verifications requests 566 int count = mCurrentIntentFilterVerifications.size(); 567 for (int n=0; n<count; n++) { 568 int verificationId = mCurrentIntentFilterVerifications.get(n); 569 final IntentFilterVerificationState ivs = 570 mIntentFilterVerificationStates.get(verificationId); 571 572 String packageName = ivs.getPackageName(); 573 574 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 575 final int filterCount = filters.size(); 576 ArraySet<String> domainsSet = new ArraySet<>(); 577 for (int m=0; m<filterCount; m++) { 578 PackageParser.ActivityIntentInfo filter = filters.get(m); 579 domainsSet.addAll(filter.getHostsList()); 580 } 581 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 582 synchronized (mPackages) { 583 if (mSettings.createIntentFilterVerificationIfNeededLPw( 584 packageName, domainsList) != null) { 585 scheduleWriteSettingsLocked(); 586 } 587 } 588 sendVerificationRequest(userId, verificationId, ivs); 589 } 590 mCurrentIntentFilterVerifications.clear(); 591 } 592 593 private void sendVerificationRequest(int userId, int verificationId, 594 IntentFilterVerificationState ivs) { 595 596 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 599 verificationId); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 602 getDefaultScheme()); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 605 ivs.getHostsString()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 608 ivs.getPackageName()); 609 verificationIntent.setComponent(mIntentFilterVerifierComponent); 610 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 611 612 UserHandle user = new UserHandle(userId); 613 mContext.sendBroadcastAsUser(verificationIntent, user); 614 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 615 } 616 617 public void receiveVerificationResponse(int verificationId) { 618 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 619 620 final boolean verified = ivs.isVerified(); 621 622 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 623 final int count = filters.size(); 624 for (int n=0; n<count; n++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(n); 626 filter.setVerified(verified); 627 628 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 629 + verified + " and hosts:" + ivs.getHostsString()); 630 } 631 632 mIntentFilterVerificationStates.remove(verificationId); 633 634 final String packageName = ivs.getPackageName(); 635 IntentFilterVerificationInfo ivi = null; 636 637 synchronized (mPackages) { 638 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 639 } 640 if (ivi == null) { 641 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 642 + verificationId + " packageName:" + packageName); 643 return; 644 } 645 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 646 + verificationId); 647 648 synchronized (mPackages) { 649 if (verified) { 650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 651 } else { 652 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 653 } 654 scheduleWriteSettingsLocked(); 655 656 final int userId = ivs.getUserId(); 657 if (userId != UserHandle.USER_ALL) { 658 final int userStatus = 659 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 660 661 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 662 boolean needUpdate = false; 663 664 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 665 // already been set by the User thru the Disambiguation dialog 666 switch (userStatus) { 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 } else { 671 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 672 } 673 needUpdate = true; 674 break; 675 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 needUpdate = true; 680 } 681 break; 682 683 default: 684 // Nothing to do 685 } 686 687 if (needUpdate) { 688 mSettings.updateIntentFilterVerificationStatusLPw( 689 packageName, updatedStatus, userId); 690 scheduleWritePackageRestrictionsLocked(userId); 691 } 692 } 693 } 694 } 695 696 @Override 697 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 698 ActivityIntentInfo filter, String packageName) { 699 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 700 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 701 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 702 return false; 703 } 704 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 705 if (ivs == null) { 706 ivs = createDomainVerificationState(verifierId, userId, verificationId, 707 packageName); 708 } 709 if (!hasValidDomains(filter)) { 710 return false; 711 } 712 ivs.addFilter(filter); 713 return true; 714 } 715 716 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 717 int userId, int verificationId, String packageName) { 718 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 719 verifierId, userId, packageName); 720 ivs.setPendingState(); 721 synchronized (mPackages) { 722 mIntentFilterVerificationStates.append(verificationId, ivs); 723 mCurrentIntentFilterVerifications.add(verificationId); 724 } 725 return ivs; 726 } 727 } 728 729 private static boolean hasValidDomains(ActivityIntentInfo filter) { 730 return hasValidDomains(filter, true); 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 734 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 735 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 736 if (!hasHTTPorHTTPS) { 737 if (logging) { 738 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 739 } 740 return false; 741 } 742 return true; 743 } 744 745 private IntentFilterVerifier mIntentFilterVerifier; 746 747 // Set of pending broadcasts for aggregating enable/disable of components. 748 static class PendingPackageBroadcasts { 749 // for each user id, a map of <package name -> components within that package> 750 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 751 752 public PendingPackageBroadcasts() { 753 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 754 } 755 756 public ArrayList<String> get(int userId, String packageName) { 757 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 758 return packages.get(packageName); 759 } 760 761 public void put(int userId, String packageName, ArrayList<String> components) { 762 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 763 packages.put(packageName, components); 764 } 765 766 public void remove(int userId, String packageName) { 767 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 768 if (packages != null) { 769 packages.remove(packageName); 770 } 771 } 772 773 public void remove(int userId) { 774 mUidMap.remove(userId); 775 } 776 777 public int userIdCount() { 778 return mUidMap.size(); 779 } 780 781 public int userIdAt(int n) { 782 return mUidMap.keyAt(n); 783 } 784 785 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 786 return mUidMap.get(userId); 787 } 788 789 public int size() { 790 // total number of pending broadcast entries across all userIds 791 int num = 0; 792 for (int i = 0; i< mUidMap.size(); i++) { 793 num += mUidMap.valueAt(i).size(); 794 } 795 return num; 796 } 797 798 public void clear() { 799 mUidMap.clear(); 800 } 801 802 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 803 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 804 if (map == null) { 805 map = new ArrayMap<String, ArrayList<String>>(); 806 mUidMap.put(userId, map); 807 } 808 return map; 809 } 810 } 811 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 812 813 // Service Connection to remote media container service to copy 814 // package uri's from external media onto secure containers 815 // or internal storage. 816 private IMediaContainerService mContainerService = null; 817 818 static final int SEND_PENDING_BROADCAST = 1; 819 static final int MCS_BOUND = 3; 820 static final int END_COPY = 4; 821 static final int INIT_COPY = 5; 822 static final int MCS_UNBIND = 6; 823 static final int START_CLEANING_PACKAGE = 7; 824 static final int FIND_INSTALL_LOC = 8; 825 static final int POST_INSTALL = 9; 826 static final int MCS_RECONNECT = 10; 827 static final int MCS_GIVE_UP = 11; 828 static final int UPDATED_MEDIA_STATUS = 12; 829 static final int WRITE_SETTINGS = 13; 830 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 831 static final int PACKAGE_VERIFIED = 15; 832 static final int CHECK_PENDING_VERIFICATION = 16; 833 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 834 static final int INTENT_FILTER_VERIFIED = 18; 835 836 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 837 838 // Delay time in millisecs 839 static final int BROADCAST_DELAY = 10 * 1000; 840 841 static UserManagerService sUserManager; 842 843 // Stores a list of users whose package restrictions file needs to be updated 844 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 845 846 final private DefaultContainerConnection mDefContainerConn = 847 new DefaultContainerConnection(); 848 class DefaultContainerConnection implements ServiceConnection { 849 public void onServiceConnected(ComponentName name, IBinder service) { 850 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 851 IMediaContainerService imcs = 852 IMediaContainerService.Stub.asInterface(service); 853 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 854 } 855 856 public void onServiceDisconnected(ComponentName name) { 857 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 858 } 859 }; 860 861 // Recordkeeping of restore-after-install operations that are currently in flight 862 // between the Package Manager and the Backup Manager 863 class PostInstallData { 864 public InstallArgs args; 865 public PackageInstalledInfo res; 866 867 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 868 args = _a; 869 res = _r; 870 } 871 }; 872 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 873 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 874 875 // backup/restore of preferred activity state 876 private static final String TAG_PREFERRED_BACKUP = "pa"; 877 878 private final String mRequiredVerifierPackage; 879 880 private final PackageUsage mPackageUsage = new PackageUsage(); 881 882 private class PackageUsage { 883 private static final int WRITE_INTERVAL 884 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 885 886 private final Object mFileLock = new Object(); 887 private final AtomicLong mLastWritten = new AtomicLong(0); 888 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 889 890 private boolean mIsHistoricalPackageUsageAvailable = true; 891 892 boolean isHistoricalPackageUsageAvailable() { 893 return mIsHistoricalPackageUsageAvailable; 894 } 895 896 void write(boolean force) { 897 if (force) { 898 writeInternal(); 899 return; 900 } 901 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 902 && !DEBUG_DEXOPT) { 903 return; 904 } 905 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 906 new Thread("PackageUsage_DiskWriter") { 907 @Override 908 public void run() { 909 try { 910 writeInternal(); 911 } finally { 912 mBackgroundWriteRunning.set(false); 913 } 914 } 915 }.start(); 916 } 917 } 918 919 private void writeInternal() { 920 synchronized (mPackages) { 921 synchronized (mFileLock) { 922 AtomicFile file = getFile(); 923 FileOutputStream f = null; 924 try { 925 f = file.startWrite(); 926 BufferedOutputStream out = new BufferedOutputStream(f); 927 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 928 StringBuilder sb = new StringBuilder(); 929 for (PackageParser.Package pkg : mPackages.values()) { 930 if (pkg.mLastPackageUsageTimeInMills == 0) { 931 continue; 932 } 933 sb.setLength(0); 934 sb.append(pkg.packageName); 935 sb.append(' '); 936 sb.append((long)pkg.mLastPackageUsageTimeInMills); 937 sb.append('\n'); 938 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 939 } 940 out.flush(); 941 file.finishWrite(f); 942 } catch (IOException e) { 943 if (f != null) { 944 file.failWrite(f); 945 } 946 Log.e(TAG, "Failed to write package usage times", e); 947 } 948 } 949 } 950 mLastWritten.set(SystemClock.elapsedRealtime()); 951 } 952 953 void readLP() { 954 synchronized (mFileLock) { 955 AtomicFile file = getFile(); 956 BufferedInputStream in = null; 957 try { 958 in = new BufferedInputStream(file.openRead()); 959 StringBuffer sb = new StringBuffer(); 960 while (true) { 961 String packageName = readToken(in, sb, ' '); 962 if (packageName == null) { 963 break; 964 } 965 String timeInMillisString = readToken(in, sb, '\n'); 966 if (timeInMillisString == null) { 967 throw new IOException("Failed to find last usage time for package " 968 + packageName); 969 } 970 PackageParser.Package pkg = mPackages.get(packageName); 971 if (pkg == null) { 972 continue; 973 } 974 long timeInMillis; 975 try { 976 timeInMillis = Long.parseLong(timeInMillisString.toString()); 977 } catch (NumberFormatException e) { 978 throw new IOException("Failed to parse " + timeInMillisString 979 + " as a long.", e); 980 } 981 pkg.mLastPackageUsageTimeInMills = timeInMillis; 982 } 983 } catch (FileNotFoundException expected) { 984 mIsHistoricalPackageUsageAvailable = false; 985 } catch (IOException e) { 986 Log.w(TAG, "Failed to read package usage times", e); 987 } finally { 988 IoUtils.closeQuietly(in); 989 } 990 } 991 mLastWritten.set(SystemClock.elapsedRealtime()); 992 } 993 994 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 995 throws IOException { 996 sb.setLength(0); 997 while (true) { 998 int ch = in.read(); 999 if (ch == -1) { 1000 if (sb.length() == 0) { 1001 return null; 1002 } 1003 throw new IOException("Unexpected EOF"); 1004 } 1005 if (ch == endOfToken) { 1006 return sb.toString(); 1007 } 1008 sb.append((char)ch); 1009 } 1010 } 1011 1012 private AtomicFile getFile() { 1013 File dataDir = Environment.getDataDirectory(); 1014 File systemDir = new File(dataDir, "system"); 1015 File fname = new File(systemDir, "package-usage.list"); 1016 return new AtomicFile(fname); 1017 } 1018 } 1019 1020 class PackageHandler extends Handler { 1021 private boolean mBound = false; 1022 final ArrayList<HandlerParams> mPendingInstalls = 1023 new ArrayList<HandlerParams>(); 1024 1025 private boolean connectToService() { 1026 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1027 " DefaultContainerService"); 1028 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1029 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1030 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1031 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1033 mBound = true; 1034 return true; 1035 } 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 return false; 1038 } 1039 1040 private void disconnectService() { 1041 mContainerService = null; 1042 mBound = false; 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1044 mContext.unbindService(mDefContainerConn); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 } 1047 1048 PackageHandler(Looper looper) { 1049 super(looper); 1050 } 1051 1052 public void handleMessage(Message msg) { 1053 try { 1054 doHandleMessage(msg); 1055 } finally { 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 } 1059 1060 void doHandleMessage(Message msg) { 1061 switch (msg.what) { 1062 case INIT_COPY: { 1063 HandlerParams params = (HandlerParams) msg.obj; 1064 int idx = mPendingInstalls.size(); 1065 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1066 // If a bind was already initiated we dont really 1067 // need to do anything. The pending install 1068 // will be processed later on. 1069 if (!mBound) { 1070 // If this is the only one pending we might 1071 // have to bind to the service again. 1072 if (!connectToService()) { 1073 Slog.e(TAG, "Failed to bind to media container service"); 1074 params.serviceError(); 1075 return; 1076 } else { 1077 // Once we bind to the service, the first 1078 // pending request will be processed. 1079 mPendingInstalls.add(idx, params); 1080 } 1081 } else { 1082 mPendingInstalls.add(idx, params); 1083 // Already bound to the service. Just make 1084 // sure we trigger off processing the first request. 1085 if (idx == 0) { 1086 mHandler.sendEmptyMessage(MCS_BOUND); 1087 } 1088 } 1089 break; 1090 } 1091 case MCS_BOUND: { 1092 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1093 if (msg.obj != null) { 1094 mContainerService = (IMediaContainerService) msg.obj; 1095 } 1096 if (mContainerService == null) { 1097 // Something seriously wrong. Bail out 1098 Slog.e(TAG, "Cannot bind to media container service"); 1099 for (HandlerParams params : mPendingInstalls) { 1100 // Indicate service bind error 1101 params.serviceError(); 1102 } 1103 mPendingInstalls.clear(); 1104 } else if (mPendingInstalls.size() > 0) { 1105 HandlerParams params = mPendingInstalls.get(0); 1106 if (params != null) { 1107 if (params.startCopy()) { 1108 // We are done... look for more work or to 1109 // go idle. 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, 1111 "Checking for more work or unbind..."); 1112 // Delete pending install 1113 if (mPendingInstalls.size() > 0) { 1114 mPendingInstalls.remove(0); 1115 } 1116 if (mPendingInstalls.size() == 0) { 1117 if (mBound) { 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Posting delayed MCS_UNBIND"); 1120 removeMessages(MCS_UNBIND); 1121 Message ubmsg = obtainMessage(MCS_UNBIND); 1122 // Unbind after a little delay, to avoid 1123 // continual thrashing. 1124 sendMessageDelayed(ubmsg, 10000); 1125 } 1126 } else { 1127 // There are more pending requests in queue. 1128 // Just post MCS_BOUND message to trigger processing 1129 // of next pending install. 1130 if (DEBUG_SD_INSTALL) Log.i(TAG, 1131 "Posting MCS_BOUND for next work"); 1132 mHandler.sendEmptyMessage(MCS_BOUND); 1133 } 1134 } 1135 } 1136 } else { 1137 // Should never happen ideally. 1138 Slog.w(TAG, "Empty queue"); 1139 } 1140 break; 1141 } 1142 case MCS_RECONNECT: { 1143 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1144 if (mPendingInstalls.size() > 0) { 1145 if (mBound) { 1146 disconnectService(); 1147 } 1148 if (!connectToService()) { 1149 Slog.e(TAG, "Failed to bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_UNBIND: { 1160 // If there is no actual work left, then time to unbind. 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1162 1163 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1164 if (mBound) { 1165 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1166 1167 disconnectService(); 1168 } 1169 } else if (mPendingInstalls.size() > 0) { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 1176 break; 1177 } 1178 case MCS_GIVE_UP: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1180 mPendingInstalls.remove(0); 1181 break; 1182 } 1183 case SEND_PENDING_BROADCAST: { 1184 String packages[]; 1185 ArrayList<String> components[]; 1186 int size = 0; 1187 int uids[]; 1188 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1189 synchronized (mPackages) { 1190 if (mPendingBroadcasts == null) { 1191 return; 1192 } 1193 size = mPendingBroadcasts.size(); 1194 if (size <= 0) { 1195 // Nothing to be done. Just return 1196 return; 1197 } 1198 packages = new String[size]; 1199 components = new ArrayList[size]; 1200 uids = new int[size]; 1201 int i = 0; // filling out the above arrays 1202 1203 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1204 int packageUserId = mPendingBroadcasts.userIdAt(n); 1205 Iterator<Map.Entry<String, ArrayList<String>>> it 1206 = mPendingBroadcasts.packagesForUserId(packageUserId) 1207 .entrySet().iterator(); 1208 while (it.hasNext() && i < size) { 1209 Map.Entry<String, ArrayList<String>> ent = it.next(); 1210 packages[i] = ent.getKey(); 1211 components[i] = ent.getValue(); 1212 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1213 uids[i] = (ps != null) 1214 ? UserHandle.getUid(packageUserId, ps.appId) 1215 : -1; 1216 i++; 1217 } 1218 } 1219 size = i; 1220 mPendingBroadcasts.clear(); 1221 } 1222 // Send broadcasts 1223 for (int i = 0; i < size; i++) { 1224 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 break; 1228 } 1229 case START_CLEANING_PACKAGE: { 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 final String packageName = (String)msg.obj; 1232 final int userId = msg.arg1; 1233 final boolean andCode = msg.arg2 != 0; 1234 synchronized (mPackages) { 1235 if (userId == UserHandle.USER_ALL) { 1236 int[] users = sUserManager.getUserIds(); 1237 for (int user : users) { 1238 mSettings.addPackageToCleanLPw( 1239 new PackageCleanItem(user, packageName, andCode)); 1240 } 1241 } else { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(userId, packageName, andCode)); 1244 } 1245 } 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 startCleaningPackages(); 1248 } break; 1249 case POST_INSTALL: { 1250 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1251 PostInstallData data = mRunningInstalls.get(msg.arg1); 1252 mRunningInstalls.delete(msg.arg1); 1253 boolean deleteOld = false; 1254 1255 if (data != null) { 1256 InstallArgs args = data.args; 1257 PackageInstalledInfo res = data.res; 1258 1259 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1260 res.removedInfo.sendBroadcast(false, true, false); 1261 Bundle extras = new Bundle(1); 1262 extras.putInt(Intent.EXTRA_UID, res.uid); 1263 1264 // Now that we successfully installed the package, grant runtime 1265 // permissions if requested before broadcasting the install. 1266 if ((args.installFlags 1267 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1268 grantRequestedRuntimePermissions(res.pkg, 1269 args.user.getIdentifier()); 1270 } 1271 1272 // Determine the set of users who are adding this 1273 // package for the first time vs. those who are seeing 1274 // an update. 1275 int[] firstUsers; 1276 int[] updateUsers = new int[0]; 1277 if (res.origUsers == null || res.origUsers.length == 0) { 1278 firstUsers = res.newUsers; 1279 } else { 1280 firstUsers = new int[0]; 1281 for (int i=0; i<res.newUsers.length; i++) { 1282 int user = res.newUsers[i]; 1283 boolean isNew = true; 1284 for (int j=0; j<res.origUsers.length; j++) { 1285 if (res.origUsers[j] == user) { 1286 isNew = false; 1287 break; 1288 } 1289 } 1290 if (isNew) { 1291 int[] newFirst = new int[firstUsers.length+1]; 1292 System.arraycopy(firstUsers, 0, newFirst, 0, 1293 firstUsers.length); 1294 newFirst[firstUsers.length] = user; 1295 firstUsers = newFirst; 1296 } else { 1297 int[] newUpdate = new int[updateUsers.length+1]; 1298 System.arraycopy(updateUsers, 0, newUpdate, 0, 1299 updateUsers.length); 1300 newUpdate[updateUsers.length] = user; 1301 updateUsers = newUpdate; 1302 } 1303 } 1304 } 1305 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1306 res.pkg.applicationInfo.packageName, 1307 extras, null, null, firstUsers); 1308 final boolean update = res.removedInfo.removedPackage != null; 1309 if (update) { 1310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1311 } 1312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1313 res.pkg.applicationInfo.packageName, 1314 extras, null, null, updateUsers); 1315 if (update) { 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1320 null, null, 1321 res.pkg.applicationInfo.packageName, null, updateUsers); 1322 1323 // treat asec-hosted packages like removable media on upgrade 1324 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1325 if (DEBUG_INSTALL) { 1326 Slog.i(TAG, "upgrading pkg " + res.pkg 1327 + " is ASEC-hosted -> AVAILABLE"); 1328 } 1329 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1330 ArrayList<String> pkgList = new ArrayList<String>(1); 1331 pkgList.add(res.pkg.applicationInfo.packageName); 1332 sendResourcesChangedBroadcast(true, true, 1333 pkgList,uidArray, null); 1334 } 1335 } 1336 if (res.removedInfo.args != null) { 1337 // Remove the replaced package's older resources safely now 1338 deleteOld = true; 1339 } 1340 1341 // Log current value of "unknown sources" setting 1342 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1343 getUnknownSourcesSettings()); 1344 } 1345 // Force a gc to clear up things 1346 Runtime.getRuntime().gc(); 1347 // We delete after a gc for applications on sdcard. 1348 if (deleteOld) { 1349 synchronized (mInstallLock) { 1350 res.removedInfo.args.doPostDeleteLI(true); 1351 } 1352 } 1353 if (args.observer != null) { 1354 try { 1355 Bundle extras = extrasForInstallResult(res); 1356 args.observer.onPackageInstalled(res.name, res.returnCode, 1357 res.returnMsg, extras); 1358 } catch (RemoteException e) { 1359 Slog.i(TAG, "Observer no longer exists."); 1360 } 1361 } 1362 } else { 1363 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1364 } 1365 } break; 1366 case UPDATED_MEDIA_STATUS: { 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1368 boolean reportStatus = msg.arg1 == 1; 1369 boolean doGc = msg.arg2 == 1; 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1371 if (doGc) { 1372 // Force a gc to clear up stale containers. 1373 Runtime.getRuntime().gc(); 1374 } 1375 if (msg.obj != null) { 1376 @SuppressWarnings("unchecked") 1377 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1379 // Unload containers 1380 unloadAllContainers(args); 1381 } 1382 if (reportStatus) { 1383 try { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1385 PackageHelper.getMountService().finishMediaUpdate(); 1386 } catch (RemoteException e) { 1387 Log.e(TAG, "MountService not running?"); 1388 } 1389 } 1390 } break; 1391 case WRITE_SETTINGS: { 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1393 synchronized (mPackages) { 1394 removeMessages(WRITE_SETTINGS); 1395 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1396 mSettings.writeLPr(); 1397 mDirtyUsers.clear(); 1398 } 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } break; 1401 case WRITE_PACKAGE_RESTRICTIONS: { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1403 synchronized (mPackages) { 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 for (int userId : mDirtyUsers) { 1406 mSettings.writePackageRestrictionsLPr(userId); 1407 } 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case CHECK_PENDING_VERIFICATION: { 1413 final int verificationId = msg.arg1; 1414 final PackageVerificationState state = mPendingVerification.get(verificationId); 1415 1416 if ((state != null) && !state.timeoutExtended()) { 1417 final InstallArgs args = state.getInstallArgs(); 1418 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1419 1420 Slog.i(TAG, "Verification timed out for " + originUri); 1421 mPendingVerification.remove(verificationId); 1422 1423 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1424 1425 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1426 Slog.i(TAG, "Continuing with installation of " + originUri); 1427 state.setVerifierResponse(Binder.getCallingUid(), 1428 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1429 broadcastPackageVerified(verificationId, originUri, 1430 PackageManager.VERIFICATION_ALLOW, 1431 state.getInstallArgs().getUser()); 1432 try { 1433 ret = args.copyApk(mContainerService, true); 1434 } catch (RemoteException e) { 1435 Slog.e(TAG, "Could not contact the ContainerService"); 1436 } 1437 } else { 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_REJECT, 1440 state.getInstallArgs().getUser()); 1441 } 1442 1443 processPendingInstall(args, ret); 1444 mHandler.sendEmptyMessage(MCS_UNBIND); 1445 } 1446 break; 1447 } 1448 case PACKAGE_VERIFIED: { 1449 final int verificationId = msg.arg1; 1450 1451 final PackageVerificationState state = mPendingVerification.get(verificationId); 1452 if (state == null) { 1453 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1454 break; 1455 } 1456 1457 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1458 1459 state.setVerifierResponse(response.callerUid, response.code); 1460 1461 if (state.isVerificationComplete()) { 1462 mPendingVerification.remove(verificationId); 1463 1464 final InstallArgs args = state.getInstallArgs(); 1465 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1466 1467 int ret; 1468 if (state.isInstallAllowed()) { 1469 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1470 broadcastPackageVerified(verificationId, originUri, 1471 response.code, state.getInstallArgs().getUser()); 1472 try { 1473 ret = args.copyApk(mContainerService, true); 1474 } catch (RemoteException e) { 1475 Slog.e(TAG, "Could not contact the ContainerService"); 1476 } 1477 } else { 1478 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1479 } 1480 1481 processPendingInstall(args, ret); 1482 1483 mHandler.sendEmptyMessage(MCS_UNBIND); 1484 } 1485 1486 break; 1487 } 1488 case START_INTENT_FILTER_VERIFICATIONS: { 1489 int userId = msg.arg1; 1490 int verifierUid = msg.arg2; 1491 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1492 1493 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1494 break; 1495 } 1496 case INTENT_FILTER_VERIFIED: { 1497 final int verificationId = msg.arg1; 1498 1499 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1500 verificationId); 1501 if (state == null) { 1502 Slog.w(TAG, "Invalid IntentFilter verification token " 1503 + verificationId + " received"); 1504 break; 1505 } 1506 1507 final int userId = state.getUserId(); 1508 1509 Slog.d(TAG, "Processing IntentFilter verification with token:" 1510 + verificationId + " and userId:" + userId); 1511 1512 final IntentFilterVerificationResponse response = 1513 (IntentFilterVerificationResponse) msg.obj; 1514 1515 state.setVerifierResponse(response.callerUid, response.code); 1516 1517 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1518 + " and userId:" + userId 1519 + " is settings verifier response with response code:" 1520 + response.code); 1521 1522 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1523 Slog.d(TAG, "Domains failing verification: " 1524 + response.getFailedDomainsString()); 1525 } 1526 1527 if (state.isVerificationComplete()) { 1528 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1529 } else { 1530 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1531 + " was not said to be complete"); 1532 } 1533 1534 break; 1535 } 1536 } 1537 } 1538 } 1539 1540 private StorageEventListener mStorageListener = new StorageEventListener() { 1541 @Override 1542 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1543 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1544 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1545 // TODO: ensure that private directories exist for all active users 1546 // TODO: remove user data whose serial number doesn't match 1547 loadPrivatePackages(vol); 1548 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1549 unloadPrivatePackages(vol); 1550 } 1551 } 1552 1553 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1554 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1555 updateExternalMediaStatus(true, false); 1556 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1557 updateExternalMediaStatus(false, false); 1558 } 1559 } 1560 } 1561 }; 1562 1563 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1564 if (userId >= UserHandle.USER_OWNER) { 1565 grantRequestedRuntimePermissionsForUser(pkg, userId); 1566 } else if (userId == UserHandle.USER_ALL) { 1567 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1568 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1569 } 1570 } 1571 } 1572 1573 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1574 SettingBase sb = (SettingBase) pkg.mExtras; 1575 if (sb == null) { 1576 return; 1577 } 1578 1579 PermissionsState permissionsState = sb.getPermissionsState(); 1580 1581 for (String permission : pkg.requestedPermissions) { 1582 BasePermission bp = mSettings.mPermissions.get(permission); 1583 if (bp != null && bp.isRuntime()) { 1584 permissionsState.grantRuntimePermission(bp, userId); 1585 } 1586 } 1587 } 1588 1589 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1590 Bundle extras = null; 1591 switch (res.returnCode) { 1592 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1593 extras = new Bundle(); 1594 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1595 res.origPermission); 1596 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1597 res.origPackage); 1598 break; 1599 } 1600 } 1601 return extras; 1602 } 1603 1604 void scheduleWriteSettingsLocked() { 1605 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1606 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1607 } 1608 } 1609 1610 void scheduleWritePackageRestrictionsLocked(int userId) { 1611 if (!sUserManager.exists(userId)) return; 1612 mDirtyUsers.add(userId); 1613 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1614 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1615 } 1616 } 1617 1618 public static PackageManagerService main(Context context, Installer installer, 1619 boolean factoryTest, boolean onlyCore) { 1620 PackageManagerService m = new PackageManagerService(context, installer, 1621 factoryTest, onlyCore); 1622 ServiceManager.addService("package", m); 1623 return m; 1624 } 1625 1626 static String[] splitString(String str, char sep) { 1627 int count = 1; 1628 int i = 0; 1629 while ((i=str.indexOf(sep, i)) >= 0) { 1630 count++; 1631 i++; 1632 } 1633 1634 String[] res = new String[count]; 1635 i=0; 1636 count = 0; 1637 int lastI=0; 1638 while ((i=str.indexOf(sep, i)) >= 0) { 1639 res[count] = str.substring(lastI, i); 1640 count++; 1641 i++; 1642 lastI = i; 1643 } 1644 res[count] = str.substring(lastI, str.length()); 1645 return res; 1646 } 1647 1648 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1649 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1650 Context.DISPLAY_SERVICE); 1651 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1652 } 1653 1654 public PackageManagerService(Context context, Installer installer, 1655 boolean factoryTest, boolean onlyCore) { 1656 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1657 SystemClock.uptimeMillis()); 1658 1659 if (mSdkVersion <= 0) { 1660 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1661 } 1662 1663 mContext = context; 1664 mFactoryTest = factoryTest; 1665 mOnlyCore = onlyCore; 1666 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1667 mMetrics = new DisplayMetrics(); 1668 mSettings = new Settings(mPackages); 1669 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1670 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1671 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1674 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1675 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1676 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1677 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 1682 // TODO: add a property to control this? 1683 long dexOptLRUThresholdInMinutes; 1684 if (mLazyDexOpt) { 1685 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1686 } else { 1687 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1688 } 1689 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1690 1691 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1692 if (separateProcesses != null && separateProcesses.length() > 0) { 1693 if ("*".equals(separateProcesses)) { 1694 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1695 mSeparateProcesses = null; 1696 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1697 } else { 1698 mDefParseFlags = 0; 1699 mSeparateProcesses = separateProcesses.split(","); 1700 Slog.w(TAG, "Running with debug.separate_processes: " 1701 + separateProcesses); 1702 } 1703 } else { 1704 mDefParseFlags = 0; 1705 mSeparateProcesses = null; 1706 } 1707 1708 mInstaller = installer; 1709 mPackageDexOptimizer = new PackageDexOptimizer(this); 1710 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1711 1712 getDefaultDisplayMetrics(context, mMetrics); 1713 1714 SystemConfig systemConfig = SystemConfig.getInstance(); 1715 mGlobalGids = systemConfig.getGlobalGids(); 1716 mSystemPermissions = systemConfig.getSystemPermissions(); 1717 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1718 1719 synchronized (mInstallLock) { 1720 // writer 1721 synchronized (mPackages) { 1722 mHandlerThread = new ServiceThread(TAG, 1723 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1724 mHandlerThread.start(); 1725 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1726 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1727 1728 File dataDir = Environment.getDataDirectory(); 1729 mAppDataDir = new File(dataDir, "data"); 1730 mAppInstallDir = new File(dataDir, "app"); 1731 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1732 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1733 mUserAppDataDir = new File(dataDir, "user"); 1734 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1735 1736 sUserManager = new UserManagerService(context, this, 1737 mInstallLock, mPackages); 1738 1739 // Propagate permission configuration in to package manager. 1740 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1741 = systemConfig.getPermissions(); 1742 for (int i=0; i<permConfig.size(); i++) { 1743 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1744 BasePermission bp = mSettings.mPermissions.get(perm.name); 1745 if (bp == null) { 1746 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1747 mSettings.mPermissions.put(perm.name, bp); 1748 } 1749 if (perm.gids != null) { 1750 bp.setGids(perm.gids, perm.perUser); 1751 } 1752 } 1753 1754 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1755 for (int i=0; i<libConfig.size(); i++) { 1756 mSharedLibraries.put(libConfig.keyAt(i), 1757 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1758 } 1759 1760 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1761 1762 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1763 mSdkVersion, mOnlyCore); 1764 1765 String customResolverActivity = Resources.getSystem().getString( 1766 R.string.config_customResolverActivity); 1767 if (TextUtils.isEmpty(customResolverActivity)) { 1768 customResolverActivity = null; 1769 } else { 1770 mCustomResolverComponentName = ComponentName.unflattenFromString( 1771 customResolverActivity); 1772 } 1773 1774 long startTime = SystemClock.uptimeMillis(); 1775 1776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1777 startTime); 1778 1779 // Set flag to monitor and not change apk file paths when 1780 // scanning install directories. 1781 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1782 1783 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1784 1785 /** 1786 * Add everything in the in the boot class path to the 1787 * list of process files because dexopt will have been run 1788 * if necessary during zygote startup. 1789 */ 1790 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1791 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1792 1793 if (bootClassPath != null) { 1794 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1795 for (String element : bootClassPathElements) { 1796 alreadyDexOpted.add(element); 1797 } 1798 } else { 1799 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1800 } 1801 1802 if (systemServerClassPath != null) { 1803 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1804 for (String element : systemServerClassPathElements) { 1805 alreadyDexOpted.add(element); 1806 } 1807 } else { 1808 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1809 } 1810 1811 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1812 final String[] dexCodeInstructionSets = 1813 getDexCodeInstructionSets( 1814 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1815 1816 /** 1817 * Ensure all external libraries have had dexopt run on them. 1818 */ 1819 if (mSharedLibraries.size() > 0) { 1820 // NOTE: For now, we're compiling these system "shared libraries" 1821 // (and framework jars) into all available architectures. It's possible 1822 // to compile them only when we come across an app that uses them (there's 1823 // already logic for that in scanPackageLI) but that adds some complexity. 1824 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1825 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1826 final String lib = libEntry.path; 1827 if (lib == null) { 1828 continue; 1829 } 1830 1831 try { 1832 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1833 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1834 alreadyDexOpted.add(lib); 1835 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1836 } 1837 } catch (FileNotFoundException e) { 1838 Slog.w(TAG, "Library not found: " + lib); 1839 } catch (IOException e) { 1840 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1841 + e.getMessage()); 1842 } 1843 } 1844 } 1845 } 1846 1847 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1848 1849 // Gross hack for now: we know this file doesn't contain any 1850 // code, so don't dexopt it to avoid the resulting log spew. 1851 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1852 1853 // Gross hack for now: we know this file is only part of 1854 // the boot class path for art, so don't dexopt it to 1855 // avoid the resulting log spew. 1856 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1857 1858 /** 1859 * And there are a number of commands implemented in Java, which 1860 * we currently need to do the dexopt on so that they can be 1861 * run from a non-root shell. 1862 */ 1863 String[] frameworkFiles = frameworkDir.list(); 1864 if (frameworkFiles != null) { 1865 // TODO: We could compile these only for the most preferred ABI. We should 1866 // first double check that the dex files for these commands are not referenced 1867 // by other system apps. 1868 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1869 for (int i=0; i<frameworkFiles.length; i++) { 1870 File libPath = new File(frameworkDir, frameworkFiles[i]); 1871 String path = libPath.getPath(); 1872 // Skip the file if we already did it. 1873 if (alreadyDexOpted.contains(path)) { 1874 continue; 1875 } 1876 // Skip the file if it is not a type we want to dexopt. 1877 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1878 continue; 1879 } 1880 try { 1881 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1882 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1883 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1884 } 1885 } catch (FileNotFoundException e) { 1886 Slog.w(TAG, "Jar not found: " + path); 1887 } catch (IOException e) { 1888 Slog.w(TAG, "Exception reading jar: " + path, e); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Collect vendor overlay packages. 1895 // (Do this before scanning any apps.) 1896 // For security and version matching reason, only consider 1897 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1898 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1899 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1900 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1901 1902 // Find base frameworks (resource packages without code). 1903 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1904 | PackageParser.PARSE_IS_SYSTEM_DIR 1905 | PackageParser.PARSE_IS_PRIVILEGED, 1906 scanFlags | SCAN_NO_DEX, 0); 1907 1908 // Collected privileged system packages. 1909 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1910 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1911 | PackageParser.PARSE_IS_SYSTEM_DIR 1912 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1913 1914 // Collect ordinary system packages. 1915 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1916 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1918 1919 // Collect all vendor packages. 1920 File vendorAppDir = new File("/vendor/app"); 1921 try { 1922 vendorAppDir = vendorAppDir.getCanonicalFile(); 1923 } catch (IOException e) { 1924 // failed to look up canonical path, continue with original one 1925 } 1926 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1927 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1928 1929 // Collect all OEM packages. 1930 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1931 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1935 mInstaller.moveFiles(); 1936 1937 // Prune any system packages that no longer exist. 1938 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1939 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1940 if (!mOnlyCore) { 1941 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1942 while (psit.hasNext()) { 1943 PackageSetting ps = psit.next(); 1944 1945 /* 1946 * If this is not a system app, it can't be a 1947 * disable system app. 1948 */ 1949 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1950 continue; 1951 } 1952 1953 /* 1954 * If the package is scanned, it's not erased. 1955 */ 1956 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1957 if (scannedPkg != null) { 1958 /* 1959 * If the system app is both scanned and in the 1960 * disabled packages list, then it must have been 1961 * added via OTA. Remove it from the currently 1962 * scanned package so the previously user-installed 1963 * application can be scanned. 1964 */ 1965 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1966 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1967 + ps.name + "; removing system app. Last known codePath=" 1968 + ps.codePathString + ", installStatus=" + ps.installStatus 1969 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1970 + scannedPkg.mVersionCode); 1971 removePackageLI(ps, true); 1972 expectingBetter.put(ps.name, ps.codePath); 1973 } 1974 1975 continue; 1976 } 1977 1978 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1979 psit.remove(); 1980 logCriticalInfo(Log.WARN, "System package " + ps.name 1981 + " no longer exists; wiping its data"); 1982 removeDataDirsLI(null, ps.name); 1983 } else { 1984 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1985 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1986 possiblyDeletedUpdatedSystemApps.add(ps.name); 1987 } 1988 } 1989 } 1990 } 1991 1992 //look for any incomplete package installations 1993 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1994 //clean up list 1995 for(int i = 0; i < deletePkgsList.size(); i++) { 1996 //clean up here 1997 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1998 } 1999 //delete tmp files 2000 deleteTempPackageFiles(); 2001 2002 // Remove any shared userIDs that have no associated packages 2003 mSettings.pruneSharedUsersLPw(); 2004 2005 if (!mOnlyCore) { 2006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2007 SystemClock.uptimeMillis()); 2008 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2009 2010 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2011 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2012 2013 /** 2014 * Remove disable package settings for any updated system 2015 * apps that were removed via an OTA. If they're not a 2016 * previously-updated app, remove them completely. 2017 * Otherwise, just revoke their system-level permissions. 2018 */ 2019 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2020 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2021 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2022 2023 String msg; 2024 if (deletedPkg == null) { 2025 msg = "Updated system package " + deletedAppName 2026 + " no longer exists; wiping its data"; 2027 removeDataDirsLI(null, deletedAppName); 2028 } else { 2029 msg = "Updated system app + " + deletedAppName 2030 + " no longer present; removing system privileges for " 2031 + deletedAppName; 2032 2033 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2034 2035 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2036 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2037 } 2038 logCriticalInfo(Log.WARN, msg); 2039 } 2040 2041 /** 2042 * Make sure all system apps that we expected to appear on 2043 * the userdata partition actually showed up. If they never 2044 * appeared, crawl back and revive the system version. 2045 */ 2046 for (int i = 0; i < expectingBetter.size(); i++) { 2047 final String packageName = expectingBetter.keyAt(i); 2048 if (!mPackages.containsKey(packageName)) { 2049 final File scanFile = expectingBetter.valueAt(i); 2050 2051 logCriticalInfo(Log.WARN, "Expected better " + packageName 2052 + " but never showed up; reverting to system"); 2053 2054 final int reparseFlags; 2055 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2056 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2057 | PackageParser.PARSE_IS_SYSTEM_DIR 2058 | PackageParser.PARSE_IS_PRIVILEGED; 2059 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2060 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR; 2062 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2063 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR; 2065 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2066 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR; 2068 } else { 2069 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2070 continue; 2071 } 2072 2073 mSettings.enableSystemPackageLPw(packageName); 2074 2075 try { 2076 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2077 } catch (PackageManagerException e) { 2078 Slog.e(TAG, "Failed to parse original system package: " 2079 + e.getMessage()); 2080 } 2081 } 2082 } 2083 } 2084 2085 // Now that we know all of the shared libraries, update all clients to have 2086 // the correct library paths. 2087 updateAllSharedLibrariesLPw(); 2088 2089 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2090 // NOTE: We ignore potential failures here during a system scan (like 2091 // the rest of the commands above) because there's precious little we 2092 // can do about it. A settings error is reported, though. 2093 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2094 false /* force dexopt */, false /* defer dexopt */); 2095 } 2096 2097 // Now that we know all the packages we are keeping, 2098 // read and update their last usage times. 2099 mPackageUsage.readLP(); 2100 2101 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2102 SystemClock.uptimeMillis()); 2103 Slog.i(TAG, "Time to scan packages: " 2104 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2105 + " seconds"); 2106 2107 // If the platform SDK has changed since the last time we booted, 2108 // we need to re-grant app permission to catch any new ones that 2109 // appear. This is really a hack, and means that apps can in some 2110 // cases get permissions that the user didn't initially explicitly 2111 // allow... it would be nice to have some better way to handle 2112 // this situation. 2113 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2114 != mSdkVersion; 2115 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2116 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2117 + "; regranting permissions for internal storage"); 2118 mSettings.mInternalSdkPlatform = mSdkVersion; 2119 2120 // For now runtime permissions are toggled via a system property. 2121 if (!RUNTIME_PERMISSIONS_ENABLED) { 2122 // Remove the runtime permissions state if the feature 2123 // was disabled by flipping the system property. 2124 mSettings.deleteRuntimePermissionsFiles(); 2125 } 2126 2127 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2128 | (regrantPermissions 2129 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2130 : 0)); 2131 2132 // If this is the first boot, and it is a normal boot, then 2133 // we need to initialize the default preferred apps. 2134 if (!mRestoredSettings && !onlyCore) { 2135 mSettings.readDefaultPreferredAppsLPw(this, 0); 2136 } 2137 2138 // If this is first boot after an OTA, and a normal boot, then 2139 // we need to clear code cache directories. 2140 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2141 if (mIsUpgrade && !onlyCore) { 2142 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2143 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2144 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2145 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2146 } 2147 mSettings.mFingerprint = Build.FINGERPRINT; 2148 } 2149 2150 // All the changes are done during package scanning. 2151 mSettings.updateInternalDatabaseVersion(); 2152 2153 // can downgrade to reader 2154 mSettings.writeLPr(); 2155 2156 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2157 SystemClock.uptimeMillis()); 2158 2159 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2160 2161 mInstallerService = new PackageInstallerService(context, this); 2162 2163 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2164 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2165 mIntentFilterVerifierComponent); 2166 2167 primeDomainVerificationsLPw(false); 2168 2169 } // synchronized (mPackages) 2170 } // synchronized (mInstallLock) 2171 2172 // Now after opening every single application zip, make sure they 2173 // are all flushed. Not really needed, but keeps things nice and 2174 // tidy. 2175 Runtime.getRuntime().gc(); 2176 } 2177 2178 @Override 2179 public boolean isFirstBoot() { 2180 return !mRestoredSettings; 2181 } 2182 2183 @Override 2184 public boolean isOnlyCoreApps() { 2185 return mOnlyCore; 2186 } 2187 2188 @Override 2189 public boolean isUpgrade() { 2190 return mIsUpgrade; 2191 } 2192 2193 private String getRequiredVerifierLPr() { 2194 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2195 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2196 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2197 2198 String requiredVerifier = null; 2199 2200 final int N = receivers.size(); 2201 for (int i = 0; i < N; i++) { 2202 final ResolveInfo info = receivers.get(i); 2203 2204 if (info.activityInfo == null) { 2205 continue; 2206 } 2207 2208 final String packageName = info.activityInfo.packageName; 2209 2210 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2211 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2212 continue; 2213 } 2214 2215 if (requiredVerifier != null) { 2216 throw new RuntimeException("There can be only one required verifier"); 2217 } 2218 2219 requiredVerifier = packageName; 2220 } 2221 2222 return requiredVerifier; 2223 } 2224 2225 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2226 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2227 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2228 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2229 2230 ComponentName verifierComponentName = null; 2231 2232 int priority = -1000; 2233 final int N = receivers.size(); 2234 for (int i = 0; i < N; i++) { 2235 final ResolveInfo info = receivers.get(i); 2236 2237 if (info.activityInfo == null) { 2238 continue; 2239 } 2240 2241 final String packageName = info.activityInfo.packageName; 2242 2243 final PackageSetting ps = mSettings.mPackages.get(packageName); 2244 if (ps == null) { 2245 continue; 2246 } 2247 2248 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2249 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2250 continue; 2251 } 2252 2253 // Select the IntentFilterVerifier with the highest priority 2254 if (priority < info.priority) { 2255 priority = info.priority; 2256 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2257 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2258 " with priority: " + info.priority); 2259 } 2260 } 2261 2262 return verifierComponentName; 2263 } 2264 2265 private void primeDomainVerificationsLPw(boolean logging) { 2266 Slog.d(TAG, "Start priming domain verification"); 2267 boolean updated = false; 2268 ArrayList<String> allHosts = new ArrayList<>(); 2269 for (PackageParser.Package pkg : mPackages.values()) { 2270 final String packageName = pkg.packageName; 2271 if (!hasDomainURLs(pkg)) { 2272 if (logging) { 2273 Slog.d(TAG, "No priming domain verifications for " + 2274 "package with no domain URLs: " + packageName); 2275 } 2276 continue; 2277 } 2278 if (!pkg.isSystemApp()) { 2279 if (logging) { 2280 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2281 packageName); 2282 } 2283 continue; 2284 } 2285 for (PackageParser.Activity a : pkg.activities) { 2286 for (ActivityIntentInfo filter : a.intents) { 2287 if (hasValidDomains(filter, false)) { 2288 allHosts.addAll(filter.getHostsList()); 2289 } 2290 } 2291 } 2292 if (allHosts.size() == 0) { 2293 allHosts.add("*"); 2294 } 2295 IntentFilterVerificationInfo ivi = 2296 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2297 if (ivi != null) { 2298 // We will always log this 2299 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2300 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2301 updated = true; 2302 } 2303 else { 2304 if (logging) { 2305 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2306 } 2307 } 2308 allHosts.clear(); 2309 } 2310 if (updated) { 2311 scheduleWriteSettingsLocked(); 2312 } 2313 Slog.d(TAG, "End priming domain verification"); 2314 } 2315 2316 @Override 2317 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2318 throws RemoteException { 2319 try { 2320 return super.onTransact(code, data, reply, flags); 2321 } catch (RuntimeException e) { 2322 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2323 Slog.wtf(TAG, "Package Manager Crash", e); 2324 } 2325 throw e; 2326 } 2327 } 2328 2329 void cleanupInstallFailedPackage(PackageSetting ps) { 2330 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2331 2332 removeDataDirsLI(ps.volumeUuid, ps.name); 2333 if (ps.codePath != null) { 2334 if (ps.codePath.isDirectory()) { 2335 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2336 } else { 2337 ps.codePath.delete(); 2338 } 2339 } 2340 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2341 if (ps.resourcePath.isDirectory()) { 2342 FileUtils.deleteContents(ps.resourcePath); 2343 } 2344 ps.resourcePath.delete(); 2345 } 2346 mSettings.removePackageLPw(ps.name); 2347 } 2348 2349 static int[] appendInts(int[] cur, int[] add) { 2350 if (add == null) return cur; 2351 if (cur == null) return add; 2352 final int N = add.length; 2353 for (int i=0; i<N; i++) { 2354 cur = appendInt(cur, add[i]); 2355 } 2356 return cur; 2357 } 2358 2359 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2360 if (!sUserManager.exists(userId)) return null; 2361 final PackageSetting ps = (PackageSetting) p.mExtras; 2362 if (ps == null) { 2363 return null; 2364 } 2365 2366 final PermissionsState permissionsState = ps.getPermissionsState(); 2367 2368 final int[] gids = permissionsState.computeGids(userId); 2369 final Set<String> permissions = permissionsState.getPermissions(userId); 2370 final PackageUserState state = ps.readUserState(userId); 2371 2372 return PackageParser.generatePackageInfo(p, gids, flags, 2373 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2374 } 2375 2376 @Override 2377 public boolean isPackageAvailable(String packageName, int userId) { 2378 if (!sUserManager.exists(userId)) return false; 2379 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2380 synchronized (mPackages) { 2381 PackageParser.Package p = mPackages.get(packageName); 2382 if (p != null) { 2383 final PackageSetting ps = (PackageSetting) p.mExtras; 2384 if (ps != null) { 2385 final PackageUserState state = ps.readUserState(userId); 2386 if (state != null) { 2387 return PackageParser.isAvailable(state); 2388 } 2389 } 2390 } 2391 } 2392 return false; 2393 } 2394 2395 @Override 2396 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2397 if (!sUserManager.exists(userId)) return null; 2398 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2399 // reader 2400 synchronized (mPackages) { 2401 PackageParser.Package p = mPackages.get(packageName); 2402 if (DEBUG_PACKAGE_INFO) 2403 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2404 if (p != null) { 2405 return generatePackageInfo(p, flags, userId); 2406 } 2407 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2408 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2409 } 2410 } 2411 return null; 2412 } 2413 2414 @Override 2415 public String[] currentToCanonicalPackageNames(String[] names) { 2416 String[] out = new String[names.length]; 2417 // reader 2418 synchronized (mPackages) { 2419 for (int i=names.length-1; i>=0; i--) { 2420 PackageSetting ps = mSettings.mPackages.get(names[i]); 2421 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2422 } 2423 } 2424 return out; 2425 } 2426 2427 @Override 2428 public String[] canonicalToCurrentPackageNames(String[] names) { 2429 String[] out = new String[names.length]; 2430 // reader 2431 synchronized (mPackages) { 2432 for (int i=names.length-1; i>=0; i--) { 2433 String cur = mSettings.mRenamedPackages.get(names[i]); 2434 out[i] = cur != null ? cur : names[i]; 2435 } 2436 } 2437 return out; 2438 } 2439 2440 @Override 2441 public int getPackageUid(String packageName, int userId) { 2442 if (!sUserManager.exists(userId)) return -1; 2443 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2444 2445 // reader 2446 synchronized (mPackages) { 2447 PackageParser.Package p = mPackages.get(packageName); 2448 if(p != null) { 2449 return UserHandle.getUid(userId, p.applicationInfo.uid); 2450 } 2451 PackageSetting ps = mSettings.mPackages.get(packageName); 2452 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2453 return -1; 2454 } 2455 p = ps.pkg; 2456 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2457 } 2458 } 2459 2460 @Override 2461 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2462 if (!sUserManager.exists(userId)) { 2463 return null; 2464 } 2465 2466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2467 "getPackageGids"); 2468 2469 // reader 2470 synchronized (mPackages) { 2471 PackageParser.Package p = mPackages.get(packageName); 2472 if (DEBUG_PACKAGE_INFO) { 2473 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2474 } 2475 if (p != null) { 2476 PackageSetting ps = (PackageSetting) p.mExtras; 2477 return ps.getPermissionsState().computeGids(userId); 2478 } 2479 } 2480 2481 return null; 2482 } 2483 2484 static PermissionInfo generatePermissionInfo( 2485 BasePermission bp, int flags) { 2486 if (bp.perm != null) { 2487 return PackageParser.generatePermissionInfo(bp.perm, flags); 2488 } 2489 PermissionInfo pi = new PermissionInfo(); 2490 pi.name = bp.name; 2491 pi.packageName = bp.sourcePackage; 2492 pi.nonLocalizedLabel = bp.name; 2493 pi.protectionLevel = bp.protectionLevel; 2494 return pi; 2495 } 2496 2497 @Override 2498 public PermissionInfo getPermissionInfo(String name, int flags) { 2499 // reader 2500 synchronized (mPackages) { 2501 final BasePermission p = mSettings.mPermissions.get(name); 2502 if (p != null) { 2503 return generatePermissionInfo(p, flags); 2504 } 2505 return null; 2506 } 2507 } 2508 2509 @Override 2510 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2511 // reader 2512 synchronized (mPackages) { 2513 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2514 for (BasePermission p : mSettings.mPermissions.values()) { 2515 if (group == null) { 2516 if (p.perm == null || p.perm.info.group == null) { 2517 out.add(generatePermissionInfo(p, flags)); 2518 } 2519 } else { 2520 if (p.perm != null && group.equals(p.perm.info.group)) { 2521 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2522 } 2523 } 2524 } 2525 2526 if (out.size() > 0) { 2527 return out; 2528 } 2529 return mPermissionGroups.containsKey(group) ? out : null; 2530 } 2531 } 2532 2533 @Override 2534 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2535 // reader 2536 synchronized (mPackages) { 2537 return PackageParser.generatePermissionGroupInfo( 2538 mPermissionGroups.get(name), flags); 2539 } 2540 } 2541 2542 @Override 2543 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2544 // reader 2545 synchronized (mPackages) { 2546 final int N = mPermissionGroups.size(); 2547 ArrayList<PermissionGroupInfo> out 2548 = new ArrayList<PermissionGroupInfo>(N); 2549 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2550 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2551 } 2552 return out; 2553 } 2554 } 2555 2556 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2557 int userId) { 2558 if (!sUserManager.exists(userId)) return null; 2559 PackageSetting ps = mSettings.mPackages.get(packageName); 2560 if (ps != null) { 2561 if (ps.pkg == null) { 2562 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2563 flags, userId); 2564 if (pInfo != null) { 2565 return pInfo.applicationInfo; 2566 } 2567 return null; 2568 } 2569 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2570 ps.readUserState(userId), userId); 2571 } 2572 return null; 2573 } 2574 2575 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2576 int userId) { 2577 if (!sUserManager.exists(userId)) return null; 2578 PackageSetting ps = mSettings.mPackages.get(packageName); 2579 if (ps != null) { 2580 PackageParser.Package pkg = ps.pkg; 2581 if (pkg == null) { 2582 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2583 return null; 2584 } 2585 // Only data remains, so we aren't worried about code paths 2586 pkg = new PackageParser.Package(packageName); 2587 pkg.applicationInfo.packageName = packageName; 2588 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2589 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2590 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2591 packageName, userId).getAbsolutePath(); 2592 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2593 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2594 } 2595 return generatePackageInfo(pkg, flags, userId); 2596 } 2597 return null; 2598 } 2599 2600 @Override 2601 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2602 if (!sUserManager.exists(userId)) return null; 2603 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2604 // writer 2605 synchronized (mPackages) { 2606 PackageParser.Package p = mPackages.get(packageName); 2607 if (DEBUG_PACKAGE_INFO) Log.v( 2608 TAG, "getApplicationInfo " + packageName 2609 + ": " + p); 2610 if (p != null) { 2611 PackageSetting ps = mSettings.mPackages.get(packageName); 2612 if (ps == null) return null; 2613 // Note: isEnabledLP() does not apply here - always return info 2614 return PackageParser.generateApplicationInfo( 2615 p, flags, ps.readUserState(userId), userId); 2616 } 2617 if ("android".equals(packageName)||"system".equals(packageName)) { 2618 return mAndroidApplication; 2619 } 2620 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2621 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2622 } 2623 } 2624 return null; 2625 } 2626 2627 @Override 2628 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2629 final IPackageDataObserver observer) { 2630 mContext.enforceCallingOrSelfPermission( 2631 android.Manifest.permission.CLEAR_APP_CACHE, null); 2632 // Queue up an async operation since clearing cache may take a little while. 2633 mHandler.post(new Runnable() { 2634 public void run() { 2635 mHandler.removeCallbacks(this); 2636 int retCode = -1; 2637 synchronized (mInstallLock) { 2638 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2639 if (retCode < 0) { 2640 Slog.w(TAG, "Couldn't clear application caches"); 2641 } 2642 } 2643 if (observer != null) { 2644 try { 2645 observer.onRemoveCompleted(null, (retCode >= 0)); 2646 } catch (RemoteException e) { 2647 Slog.w(TAG, "RemoveException when invoking call back"); 2648 } 2649 } 2650 } 2651 }); 2652 } 2653 2654 @Override 2655 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2656 final IntentSender pi) { 2657 mContext.enforceCallingOrSelfPermission( 2658 android.Manifest.permission.CLEAR_APP_CACHE, null); 2659 // Queue up an async operation since clearing cache may take a little while. 2660 mHandler.post(new Runnable() { 2661 public void run() { 2662 mHandler.removeCallbacks(this); 2663 int retCode = -1; 2664 synchronized (mInstallLock) { 2665 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2666 if (retCode < 0) { 2667 Slog.w(TAG, "Couldn't clear application caches"); 2668 } 2669 } 2670 if(pi != null) { 2671 try { 2672 // Callback via pending intent 2673 int code = (retCode >= 0) ? 1 : 0; 2674 pi.sendIntent(null, code, null, 2675 null, null); 2676 } catch (SendIntentException e1) { 2677 Slog.i(TAG, "Failed to send pending intent"); 2678 } 2679 } 2680 } 2681 }); 2682 } 2683 2684 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2685 synchronized (mInstallLock) { 2686 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2687 throw new IOException("Failed to free enough space"); 2688 } 2689 } 2690 } 2691 2692 @Override 2693 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2694 if (!sUserManager.exists(userId)) return null; 2695 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2696 synchronized (mPackages) { 2697 PackageParser.Activity a = mActivities.mActivities.get(component); 2698 2699 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2700 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2701 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2702 if (ps == null) return null; 2703 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2704 userId); 2705 } 2706 if (mResolveComponentName.equals(component)) { 2707 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2708 new PackageUserState(), userId); 2709 } 2710 } 2711 return null; 2712 } 2713 2714 @Override 2715 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2716 String resolvedType) { 2717 synchronized (mPackages) { 2718 PackageParser.Activity a = mActivities.mActivities.get(component); 2719 if (a == null) { 2720 return false; 2721 } 2722 for (int i=0; i<a.intents.size(); i++) { 2723 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2724 intent.getData(), intent.getCategories(), TAG) >= 0) { 2725 return true; 2726 } 2727 } 2728 return false; 2729 } 2730 } 2731 2732 @Override 2733 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2734 if (!sUserManager.exists(userId)) return null; 2735 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2736 synchronized (mPackages) { 2737 PackageParser.Activity a = mReceivers.mActivities.get(component); 2738 if (DEBUG_PACKAGE_INFO) Log.v( 2739 TAG, "getReceiverInfo " + component + ": " + a); 2740 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2741 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2742 if (ps == null) return null; 2743 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2744 userId); 2745 } 2746 } 2747 return null; 2748 } 2749 2750 @Override 2751 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2752 if (!sUserManager.exists(userId)) return null; 2753 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2754 synchronized (mPackages) { 2755 PackageParser.Service s = mServices.mServices.get(component); 2756 if (DEBUG_PACKAGE_INFO) Log.v( 2757 TAG, "getServiceInfo " + component + ": " + s); 2758 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2759 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2760 if (ps == null) return null; 2761 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2762 userId); 2763 } 2764 } 2765 return null; 2766 } 2767 2768 @Override 2769 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2770 if (!sUserManager.exists(userId)) return null; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2772 synchronized (mPackages) { 2773 PackageParser.Provider p = mProviders.mProviders.get(component); 2774 if (DEBUG_PACKAGE_INFO) Log.v( 2775 TAG, "getProviderInfo " + component + ": " + p); 2776 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2777 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2778 if (ps == null) return null; 2779 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2780 userId); 2781 } 2782 } 2783 return null; 2784 } 2785 2786 @Override 2787 public String[] getSystemSharedLibraryNames() { 2788 Set<String> libSet; 2789 synchronized (mPackages) { 2790 libSet = mSharedLibraries.keySet(); 2791 int size = libSet.size(); 2792 if (size > 0) { 2793 String[] libs = new String[size]; 2794 libSet.toArray(libs); 2795 return libs; 2796 } 2797 } 2798 return null; 2799 } 2800 2801 /** 2802 * @hide 2803 */ 2804 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2805 synchronized (mPackages) { 2806 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2807 if (lib != null && lib.apk != null) { 2808 return mPackages.get(lib.apk); 2809 } 2810 } 2811 return null; 2812 } 2813 2814 @Override 2815 public FeatureInfo[] getSystemAvailableFeatures() { 2816 Collection<FeatureInfo> featSet; 2817 synchronized (mPackages) { 2818 featSet = mAvailableFeatures.values(); 2819 int size = featSet.size(); 2820 if (size > 0) { 2821 FeatureInfo[] features = new FeatureInfo[size+1]; 2822 featSet.toArray(features); 2823 FeatureInfo fi = new FeatureInfo(); 2824 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2825 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2826 features[size] = fi; 2827 return features; 2828 } 2829 } 2830 return null; 2831 } 2832 2833 @Override 2834 public boolean hasSystemFeature(String name) { 2835 synchronized (mPackages) { 2836 return mAvailableFeatures.containsKey(name); 2837 } 2838 } 2839 2840 private void checkValidCaller(int uid, int userId) { 2841 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2842 return; 2843 2844 throw new SecurityException("Caller uid=" + uid 2845 + " is not privileged to communicate with user=" + userId); 2846 } 2847 2848 @Override 2849 public int checkPermission(String permName, String pkgName, int userId) { 2850 if (!sUserManager.exists(userId)) { 2851 return PackageManager.PERMISSION_DENIED; 2852 } 2853 2854 synchronized (mPackages) { 2855 final PackageParser.Package p = mPackages.get(pkgName); 2856 if (p != null && p.mExtras != null) { 2857 final PackageSetting ps = (PackageSetting) p.mExtras; 2858 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2859 return PackageManager.PERMISSION_GRANTED; 2860 } 2861 } 2862 } 2863 2864 return PackageManager.PERMISSION_DENIED; 2865 } 2866 2867 @Override 2868 public int checkUidPermission(String permName, int uid) { 2869 final int userId = UserHandle.getUserId(uid); 2870 2871 if (!sUserManager.exists(userId)) { 2872 return PackageManager.PERMISSION_DENIED; 2873 } 2874 2875 synchronized (mPackages) { 2876 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2877 if (obj != null) { 2878 final SettingBase ps = (SettingBase) obj; 2879 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2880 return PackageManager.PERMISSION_GRANTED; 2881 } 2882 } else { 2883 ArraySet<String> perms = mSystemPermissions.get(uid); 2884 if (perms != null && perms.contains(permName)) { 2885 return PackageManager.PERMISSION_GRANTED; 2886 } 2887 } 2888 } 2889 2890 return PackageManager.PERMISSION_DENIED; 2891 } 2892 2893 /** 2894 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2895 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2896 * @param checkShell TODO(yamasani): 2897 * @param message the message to log on security exception 2898 */ 2899 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2900 boolean checkShell, String message) { 2901 if (userId < 0) { 2902 throw new IllegalArgumentException("Invalid userId " + userId); 2903 } 2904 if (checkShell) { 2905 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2906 } 2907 if (userId == UserHandle.getUserId(callingUid)) return; 2908 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2909 if (requireFullPermission) { 2910 mContext.enforceCallingOrSelfPermission( 2911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2912 } else { 2913 try { 2914 mContext.enforceCallingOrSelfPermission( 2915 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2916 } catch (SecurityException se) { 2917 mContext.enforceCallingOrSelfPermission( 2918 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2919 } 2920 } 2921 } 2922 } 2923 2924 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2925 if (callingUid == Process.SHELL_UID) { 2926 if (userHandle >= 0 2927 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2928 throw new SecurityException("Shell does not have permission to access user " 2929 + userHandle); 2930 } else if (userHandle < 0) { 2931 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2932 + Debug.getCallers(3)); 2933 } 2934 } 2935 } 2936 2937 private BasePermission findPermissionTreeLP(String permName) { 2938 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2939 if (permName.startsWith(bp.name) && 2940 permName.length() > bp.name.length() && 2941 permName.charAt(bp.name.length()) == '.') { 2942 return bp; 2943 } 2944 } 2945 return null; 2946 } 2947 2948 private BasePermission checkPermissionTreeLP(String permName) { 2949 if (permName != null) { 2950 BasePermission bp = findPermissionTreeLP(permName); 2951 if (bp != null) { 2952 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2953 return bp; 2954 } 2955 throw new SecurityException("Calling uid " 2956 + Binder.getCallingUid() 2957 + " is not allowed to add to permission tree " 2958 + bp.name + " owned by uid " + bp.uid); 2959 } 2960 } 2961 throw new SecurityException("No permission tree found for " + permName); 2962 } 2963 2964 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2965 if (s1 == null) { 2966 return s2 == null; 2967 } 2968 if (s2 == null) { 2969 return false; 2970 } 2971 if (s1.getClass() != s2.getClass()) { 2972 return false; 2973 } 2974 return s1.equals(s2); 2975 } 2976 2977 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2978 if (pi1.icon != pi2.icon) return false; 2979 if (pi1.logo != pi2.logo) return false; 2980 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2981 if (!compareStrings(pi1.name, pi2.name)) return false; 2982 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2983 // We'll take care of setting this one. 2984 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2985 // These are not currently stored in settings. 2986 //if (!compareStrings(pi1.group, pi2.group)) return false; 2987 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2988 //if (pi1.labelRes != pi2.labelRes) return false; 2989 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2990 return true; 2991 } 2992 2993 int permissionInfoFootprint(PermissionInfo info) { 2994 int size = info.name.length(); 2995 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2996 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2997 return size; 2998 } 2999 3000 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3001 int size = 0; 3002 for (BasePermission perm : mSettings.mPermissions.values()) { 3003 if (perm.uid == tree.uid) { 3004 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3005 } 3006 } 3007 return size; 3008 } 3009 3010 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3011 // We calculate the max size of permissions defined by this uid and throw 3012 // if that plus the size of 'info' would exceed our stated maximum. 3013 if (tree.uid != Process.SYSTEM_UID) { 3014 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3015 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3016 throw new SecurityException("Permission tree size cap exceeded"); 3017 } 3018 } 3019 } 3020 3021 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3022 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3023 throw new SecurityException("Label must be specified in permission"); 3024 } 3025 BasePermission tree = checkPermissionTreeLP(info.name); 3026 BasePermission bp = mSettings.mPermissions.get(info.name); 3027 boolean added = bp == null; 3028 boolean changed = true; 3029 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3030 if (added) { 3031 enforcePermissionCapLocked(info, tree); 3032 bp = new BasePermission(info.name, tree.sourcePackage, 3033 BasePermission.TYPE_DYNAMIC); 3034 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3035 throw new SecurityException( 3036 "Not allowed to modify non-dynamic permission " 3037 + info.name); 3038 } else { 3039 if (bp.protectionLevel == fixedLevel 3040 && bp.perm.owner.equals(tree.perm.owner) 3041 && bp.uid == tree.uid 3042 && comparePermissionInfos(bp.perm.info, info)) { 3043 changed = false; 3044 } 3045 } 3046 bp.protectionLevel = fixedLevel; 3047 info = new PermissionInfo(info); 3048 info.protectionLevel = fixedLevel; 3049 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3050 bp.perm.info.packageName = tree.perm.info.packageName; 3051 bp.uid = tree.uid; 3052 if (added) { 3053 mSettings.mPermissions.put(info.name, bp); 3054 } 3055 if (changed) { 3056 if (!async) { 3057 mSettings.writeLPr(); 3058 } else { 3059 scheduleWriteSettingsLocked(); 3060 } 3061 } 3062 return added; 3063 } 3064 3065 @Override 3066 public boolean addPermission(PermissionInfo info) { 3067 synchronized (mPackages) { 3068 return addPermissionLocked(info, false); 3069 } 3070 } 3071 3072 @Override 3073 public boolean addPermissionAsync(PermissionInfo info) { 3074 synchronized (mPackages) { 3075 return addPermissionLocked(info, true); 3076 } 3077 } 3078 3079 @Override 3080 public void removePermission(String name) { 3081 synchronized (mPackages) { 3082 checkPermissionTreeLP(name); 3083 BasePermission bp = mSettings.mPermissions.get(name); 3084 if (bp != null) { 3085 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3086 throw new SecurityException( 3087 "Not allowed to modify non-dynamic permission " 3088 + name); 3089 } 3090 mSettings.mPermissions.remove(name); 3091 mSettings.writeLPr(); 3092 } 3093 } 3094 } 3095 3096 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3097 BasePermission bp) { 3098 int index = pkg.requestedPermissions.indexOf(bp.name); 3099 if (index == -1) { 3100 throw new SecurityException("Package " + pkg.packageName 3101 + " has not requested permission " + bp.name); 3102 } 3103 if (!bp.isRuntime()) { 3104 throw new SecurityException("Permission " + bp.name 3105 + " is not a changeable permission type"); 3106 } 3107 } 3108 3109 @Override 3110 public boolean grantPermission(String packageName, String name, int userId) { 3111 if (!RUNTIME_PERMISSIONS_ENABLED) { 3112 return false; 3113 } 3114 3115 if (!sUserManager.exists(userId)) { 3116 return false; 3117 } 3118 3119 mContext.enforceCallingOrSelfPermission( 3120 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3121 "grantPermission"); 3122 3123 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3124 "grantPermission"); 3125 3126 boolean gidsChanged = false; 3127 final SettingBase sb; 3128 3129 synchronized (mPackages) { 3130 final PackageParser.Package pkg = mPackages.get(packageName); 3131 if (pkg == null) { 3132 throw new IllegalArgumentException("Unknown package: " + packageName); 3133 } 3134 3135 final BasePermission bp = mSettings.mPermissions.get(name); 3136 if (bp == null) { 3137 throw new IllegalArgumentException("Unknown permission: " + name); 3138 } 3139 3140 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3141 3142 sb = (SettingBase) pkg.mExtras; 3143 if (sb == null) { 3144 throw new IllegalArgumentException("Unknown package: " + packageName); 3145 } 3146 3147 final PermissionsState permissionsState = sb.getPermissionsState(); 3148 3149 final int result = permissionsState.grantRuntimePermission(bp, userId); 3150 switch (result) { 3151 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3152 return false; 3153 } 3154 3155 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3156 gidsChanged = true; 3157 } break; 3158 } 3159 3160 // Not critical if that is lost - app has to request again. 3161 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3162 } 3163 3164 if (gidsChanged) { 3165 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3166 } 3167 3168 return true; 3169 } 3170 3171 @Override 3172 public boolean revokePermission(String packageName, String name, int userId) { 3173 if (!RUNTIME_PERMISSIONS_ENABLED) { 3174 return false; 3175 } 3176 3177 if (!sUserManager.exists(userId)) { 3178 return false; 3179 } 3180 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3183 "revokePermission"); 3184 3185 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3186 "revokePermission"); 3187 3188 final SettingBase sb; 3189 3190 synchronized (mPackages) { 3191 final PackageParser.Package pkg = mPackages.get(packageName); 3192 if (pkg == null) { 3193 throw new IllegalArgumentException("Unknown package: " + packageName); 3194 } 3195 3196 final BasePermission bp = mSettings.mPermissions.get(name); 3197 if (bp == null) { 3198 throw new IllegalArgumentException("Unknown permission: " + name); 3199 } 3200 3201 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3202 3203 sb = (SettingBase) pkg.mExtras; 3204 if (sb == null) { 3205 throw new IllegalArgumentException("Unknown package: " + packageName); 3206 } 3207 3208 final PermissionsState permissionsState = sb.getPermissionsState(); 3209 3210 if (permissionsState.revokeRuntimePermission(bp, userId) == 3211 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3212 return false; 3213 } 3214 3215 // Critical, after this call all should never have the permission. 3216 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3217 } 3218 3219 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3220 3221 return true; 3222 } 3223 3224 @Override 3225 public boolean isProtectedBroadcast(String actionName) { 3226 synchronized (mPackages) { 3227 return mProtectedBroadcasts.contains(actionName); 3228 } 3229 } 3230 3231 @Override 3232 public int checkSignatures(String pkg1, String pkg2) { 3233 synchronized (mPackages) { 3234 final PackageParser.Package p1 = mPackages.get(pkg1); 3235 final PackageParser.Package p2 = mPackages.get(pkg2); 3236 if (p1 == null || p1.mExtras == null 3237 || p2 == null || p2.mExtras == null) { 3238 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3239 } 3240 return compareSignatures(p1.mSignatures, p2.mSignatures); 3241 } 3242 } 3243 3244 @Override 3245 public int checkUidSignatures(int uid1, int uid2) { 3246 // Map to base uids. 3247 uid1 = UserHandle.getAppId(uid1); 3248 uid2 = UserHandle.getAppId(uid2); 3249 // reader 3250 synchronized (mPackages) { 3251 Signature[] s1; 3252 Signature[] s2; 3253 Object obj = mSettings.getUserIdLPr(uid1); 3254 if (obj != null) { 3255 if (obj instanceof SharedUserSetting) { 3256 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3257 } else if (obj instanceof PackageSetting) { 3258 s1 = ((PackageSetting)obj).signatures.mSignatures; 3259 } else { 3260 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3261 } 3262 } else { 3263 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3264 } 3265 obj = mSettings.getUserIdLPr(uid2); 3266 if (obj != null) { 3267 if (obj instanceof SharedUserSetting) { 3268 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3269 } else if (obj instanceof PackageSetting) { 3270 s2 = ((PackageSetting)obj).signatures.mSignatures; 3271 } else { 3272 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3273 } 3274 } else { 3275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3276 } 3277 return compareSignatures(s1, s2); 3278 } 3279 } 3280 3281 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3282 final long identity = Binder.clearCallingIdentity(); 3283 try { 3284 if (sb instanceof SharedUserSetting) { 3285 SharedUserSetting sus = (SharedUserSetting) sb; 3286 final int packageCount = sus.packages.size(); 3287 for (int i = 0; i < packageCount; i++) { 3288 PackageSetting susPs = sus.packages.valueAt(i); 3289 if (userId == UserHandle.USER_ALL) { 3290 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3291 } else { 3292 final int uid = UserHandle.getUid(userId, susPs.appId); 3293 killUid(uid, reason); 3294 } 3295 } 3296 } else if (sb instanceof PackageSetting) { 3297 PackageSetting ps = (PackageSetting) sb; 3298 if (userId == UserHandle.USER_ALL) { 3299 killApplication(ps.pkg.packageName, ps.appId, reason); 3300 } else { 3301 final int uid = UserHandle.getUid(userId, ps.appId); 3302 killUid(uid, reason); 3303 } 3304 } 3305 } finally { 3306 Binder.restoreCallingIdentity(identity); 3307 } 3308 } 3309 3310 private static void killUid(int uid, String reason) { 3311 IActivityManager am = ActivityManagerNative.getDefault(); 3312 if (am != null) { 3313 try { 3314 am.killUid(uid, reason); 3315 } catch (RemoteException e) { 3316 /* ignore - same process */ 3317 } 3318 } 3319 } 3320 3321 /** 3322 * Compares two sets of signatures. Returns: 3323 * <br /> 3324 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3325 * <br /> 3326 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3327 * <br /> 3328 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3329 * <br /> 3330 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3331 * <br /> 3332 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3333 */ 3334 static int compareSignatures(Signature[] s1, Signature[] s2) { 3335 if (s1 == null) { 3336 return s2 == null 3337 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3338 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3339 } 3340 3341 if (s2 == null) { 3342 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3343 } 3344 3345 if (s1.length != s2.length) { 3346 return PackageManager.SIGNATURE_NO_MATCH; 3347 } 3348 3349 // Since both signature sets are of size 1, we can compare without HashSets. 3350 if (s1.length == 1) { 3351 return s1[0].equals(s2[0]) ? 3352 PackageManager.SIGNATURE_MATCH : 3353 PackageManager.SIGNATURE_NO_MATCH; 3354 } 3355 3356 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3357 for (Signature sig : s1) { 3358 set1.add(sig); 3359 } 3360 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3361 for (Signature sig : s2) { 3362 set2.add(sig); 3363 } 3364 // Make sure s2 contains all signatures in s1. 3365 if (set1.equals(set2)) { 3366 return PackageManager.SIGNATURE_MATCH; 3367 } 3368 return PackageManager.SIGNATURE_NO_MATCH; 3369 } 3370 3371 /** 3372 * If the database version for this type of package (internal storage or 3373 * external storage) is less than the version where package signatures 3374 * were updated, return true. 3375 */ 3376 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3377 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3378 DatabaseVersion.SIGNATURE_END_ENTITY)) 3379 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3380 DatabaseVersion.SIGNATURE_END_ENTITY)); 3381 } 3382 3383 /** 3384 * Used for backward compatibility to make sure any packages with 3385 * certificate chains get upgraded to the new style. {@code existingSigs} 3386 * will be in the old format (since they were stored on disk from before the 3387 * system upgrade) and {@code scannedSigs} will be in the newer format. 3388 */ 3389 private int compareSignaturesCompat(PackageSignatures existingSigs, 3390 PackageParser.Package scannedPkg) { 3391 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3392 return PackageManager.SIGNATURE_NO_MATCH; 3393 } 3394 3395 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3396 for (Signature sig : existingSigs.mSignatures) { 3397 existingSet.add(sig); 3398 } 3399 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3400 for (Signature sig : scannedPkg.mSignatures) { 3401 try { 3402 Signature[] chainSignatures = sig.getChainSignatures(); 3403 for (Signature chainSig : chainSignatures) { 3404 scannedCompatSet.add(chainSig); 3405 } 3406 } catch (CertificateEncodingException e) { 3407 scannedCompatSet.add(sig); 3408 } 3409 } 3410 /* 3411 * Make sure the expanded scanned set contains all signatures in the 3412 * existing one. 3413 */ 3414 if (scannedCompatSet.equals(existingSet)) { 3415 // Migrate the old signatures to the new scheme. 3416 existingSigs.assignSignatures(scannedPkg.mSignatures); 3417 // The new KeySets will be re-added later in the scanning process. 3418 synchronized (mPackages) { 3419 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3420 } 3421 return PackageManager.SIGNATURE_MATCH; 3422 } 3423 return PackageManager.SIGNATURE_NO_MATCH; 3424 } 3425 3426 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3427 if (isExternal(scannedPkg)) { 3428 return mSettings.isExternalDatabaseVersionOlderThan( 3429 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3430 } else { 3431 return mSettings.isInternalDatabaseVersionOlderThan( 3432 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3433 } 3434 } 3435 3436 private int compareSignaturesRecover(PackageSignatures existingSigs, 3437 PackageParser.Package scannedPkg) { 3438 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3439 return PackageManager.SIGNATURE_NO_MATCH; 3440 } 3441 3442 String msg = null; 3443 try { 3444 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3445 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3446 + scannedPkg.packageName); 3447 return PackageManager.SIGNATURE_MATCH; 3448 } 3449 } catch (CertificateException e) { 3450 msg = e.getMessage(); 3451 } 3452 3453 logCriticalInfo(Log.INFO, 3454 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3455 return PackageManager.SIGNATURE_NO_MATCH; 3456 } 3457 3458 @Override 3459 public String[] getPackagesForUid(int uid) { 3460 uid = UserHandle.getAppId(uid); 3461 // reader 3462 synchronized (mPackages) { 3463 Object obj = mSettings.getUserIdLPr(uid); 3464 if (obj instanceof SharedUserSetting) { 3465 final SharedUserSetting sus = (SharedUserSetting) obj; 3466 final int N = sus.packages.size(); 3467 final String[] res = new String[N]; 3468 final Iterator<PackageSetting> it = sus.packages.iterator(); 3469 int i = 0; 3470 while (it.hasNext()) { 3471 res[i++] = it.next().name; 3472 } 3473 return res; 3474 } else if (obj instanceof PackageSetting) { 3475 final PackageSetting ps = (PackageSetting) obj; 3476 return new String[] { ps.name }; 3477 } 3478 } 3479 return null; 3480 } 3481 3482 @Override 3483 public String getNameForUid(int uid) { 3484 // reader 3485 synchronized (mPackages) { 3486 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3487 if (obj instanceof SharedUserSetting) { 3488 final SharedUserSetting sus = (SharedUserSetting) obj; 3489 return sus.name + ":" + sus.userId; 3490 } else if (obj instanceof PackageSetting) { 3491 final PackageSetting ps = (PackageSetting) obj; 3492 return ps.name; 3493 } 3494 } 3495 return null; 3496 } 3497 3498 @Override 3499 public int getUidForSharedUser(String sharedUserName) { 3500 if(sharedUserName == null) { 3501 return -1; 3502 } 3503 // reader 3504 synchronized (mPackages) { 3505 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3506 if (suid == null) { 3507 return -1; 3508 } 3509 return suid.userId; 3510 } 3511 } 3512 3513 @Override 3514 public int getFlagsForUid(int uid) { 3515 synchronized (mPackages) { 3516 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3517 if (obj instanceof SharedUserSetting) { 3518 final SharedUserSetting sus = (SharedUserSetting) obj; 3519 return sus.pkgFlags; 3520 } else if (obj instanceof PackageSetting) { 3521 final PackageSetting ps = (PackageSetting) obj; 3522 return ps.pkgFlags; 3523 } 3524 } 3525 return 0; 3526 } 3527 3528 @Override 3529 public int getPrivateFlagsForUid(int uid) { 3530 synchronized (mPackages) { 3531 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3532 if (obj instanceof SharedUserSetting) { 3533 final SharedUserSetting sus = (SharedUserSetting) obj; 3534 return sus.pkgPrivateFlags; 3535 } else if (obj instanceof PackageSetting) { 3536 final PackageSetting ps = (PackageSetting) obj; 3537 return ps.pkgPrivateFlags; 3538 } 3539 } 3540 return 0; 3541 } 3542 3543 @Override 3544 public boolean isUidPrivileged(int uid) { 3545 uid = UserHandle.getAppId(uid); 3546 // reader 3547 synchronized (mPackages) { 3548 Object obj = mSettings.getUserIdLPr(uid); 3549 if (obj instanceof SharedUserSetting) { 3550 final SharedUserSetting sus = (SharedUserSetting) obj; 3551 final Iterator<PackageSetting> it = sus.packages.iterator(); 3552 while (it.hasNext()) { 3553 if (it.next().isPrivileged()) { 3554 return true; 3555 } 3556 } 3557 } else if (obj instanceof PackageSetting) { 3558 final PackageSetting ps = (PackageSetting) obj; 3559 return ps.isPrivileged(); 3560 } 3561 } 3562 return false; 3563 } 3564 3565 @Override 3566 public String[] getAppOpPermissionPackages(String permissionName) { 3567 synchronized (mPackages) { 3568 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3569 if (pkgs == null) { 3570 return null; 3571 } 3572 return pkgs.toArray(new String[pkgs.size()]); 3573 } 3574 } 3575 3576 @Override 3577 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3578 int flags, int userId) { 3579 if (!sUserManager.exists(userId)) return null; 3580 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3581 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3582 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3583 } 3584 3585 @Override 3586 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3587 IntentFilter filter, int match, ComponentName activity) { 3588 final int userId = UserHandle.getCallingUserId(); 3589 if (DEBUG_PREFERRED) { 3590 Log.v(TAG, "setLastChosenActivity intent=" + intent 3591 + " resolvedType=" + resolvedType 3592 + " flags=" + flags 3593 + " filter=" + filter 3594 + " match=" + match 3595 + " activity=" + activity); 3596 filter.dump(new PrintStreamPrinter(System.out), " "); 3597 } 3598 intent.setComponent(null); 3599 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3600 // Find any earlier preferred or last chosen entries and nuke them 3601 findPreferredActivity(intent, resolvedType, 3602 flags, query, 0, false, true, false, userId); 3603 // Add the new activity as the last chosen for this filter 3604 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3605 "Setting last chosen"); 3606 } 3607 3608 @Override 3609 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3610 final int userId = UserHandle.getCallingUserId(); 3611 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3612 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3613 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3614 false, false, false, userId); 3615 } 3616 3617 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3618 int flags, List<ResolveInfo> query, int userId) { 3619 if (query != null) { 3620 final int N = query.size(); 3621 if (N == 1) { 3622 return query.get(0); 3623 } else if (N > 1) { 3624 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3625 // If there is more than one activity with the same priority, 3626 // then let the user decide between them. 3627 ResolveInfo r0 = query.get(0); 3628 ResolveInfo r1 = query.get(1); 3629 if (DEBUG_INTENT_MATCHING || debug) { 3630 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3631 + r1.activityInfo.name + "=" + r1.priority); 3632 } 3633 // If the first activity has a higher priority, or a different 3634 // default, then it is always desireable to pick it. 3635 if (r0.priority != r1.priority 3636 || r0.preferredOrder != r1.preferredOrder 3637 || r0.isDefault != r1.isDefault) { 3638 return query.get(0); 3639 } 3640 // If we have saved a preference for a preferred activity for 3641 // this Intent, use that. 3642 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3643 flags, query, r0.priority, true, false, debug, userId); 3644 if (ri != null) { 3645 return ri; 3646 } 3647 if (userId != 0) { 3648 ri = new ResolveInfo(mResolveInfo); 3649 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3650 ri.activityInfo.applicationInfo = new ApplicationInfo( 3651 ri.activityInfo.applicationInfo); 3652 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3653 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3654 return ri; 3655 } 3656 return mResolveInfo; 3657 } 3658 } 3659 return null; 3660 } 3661 3662 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3663 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3664 final int N = query.size(); 3665 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3666 .get(userId); 3667 // Get the list of persistent preferred activities that handle the intent 3668 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3669 List<PersistentPreferredActivity> pprefs = ppir != null 3670 ? ppir.queryIntent(intent, resolvedType, 3671 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3672 : null; 3673 if (pprefs != null && pprefs.size() > 0) { 3674 final int M = pprefs.size(); 3675 for (int i=0; i<M; i++) { 3676 final PersistentPreferredActivity ppa = pprefs.get(i); 3677 if (DEBUG_PREFERRED || debug) { 3678 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3679 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3680 + "\n component=" + ppa.mComponent); 3681 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3682 } 3683 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3684 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3685 if (DEBUG_PREFERRED || debug) { 3686 Slog.v(TAG, "Found persistent preferred activity:"); 3687 if (ai != null) { 3688 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3689 } else { 3690 Slog.v(TAG, " null"); 3691 } 3692 } 3693 if (ai == null) { 3694 // This previously registered persistent preferred activity 3695 // component is no longer known. Ignore it and do NOT remove it. 3696 continue; 3697 } 3698 for (int j=0; j<N; j++) { 3699 final ResolveInfo ri = query.get(j); 3700 if (!ri.activityInfo.applicationInfo.packageName 3701 .equals(ai.applicationInfo.packageName)) { 3702 continue; 3703 } 3704 if (!ri.activityInfo.name.equals(ai.name)) { 3705 continue; 3706 } 3707 // Found a persistent preference that can handle the intent. 3708 if (DEBUG_PREFERRED || debug) { 3709 Slog.v(TAG, "Returning persistent preferred activity: " + 3710 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3711 } 3712 return ri; 3713 } 3714 } 3715 } 3716 return null; 3717 } 3718 3719 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3720 List<ResolveInfo> query, int priority, boolean always, 3721 boolean removeMatches, boolean debug, int userId) { 3722 if (!sUserManager.exists(userId)) return null; 3723 // writer 3724 synchronized (mPackages) { 3725 if (intent.getSelector() != null) { 3726 intent = intent.getSelector(); 3727 } 3728 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3729 3730 // Try to find a matching persistent preferred activity. 3731 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3732 debug, userId); 3733 3734 // If a persistent preferred activity matched, use it. 3735 if (pri != null) { 3736 return pri; 3737 } 3738 3739 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3740 // Get the list of preferred activities that handle the intent 3741 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3742 List<PreferredActivity> prefs = pir != null 3743 ? pir.queryIntent(intent, resolvedType, 3744 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3745 : null; 3746 if (prefs != null && prefs.size() > 0) { 3747 boolean changed = false; 3748 try { 3749 // First figure out how good the original match set is. 3750 // We will only allow preferred activities that came 3751 // from the same match quality. 3752 int match = 0; 3753 3754 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3755 3756 final int N = query.size(); 3757 for (int j=0; j<N; j++) { 3758 final ResolveInfo ri = query.get(j); 3759 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3760 + ": 0x" + Integer.toHexString(match)); 3761 if (ri.match > match) { 3762 match = ri.match; 3763 } 3764 } 3765 3766 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3767 + Integer.toHexString(match)); 3768 3769 match &= IntentFilter.MATCH_CATEGORY_MASK; 3770 final int M = prefs.size(); 3771 for (int i=0; i<M; i++) { 3772 final PreferredActivity pa = prefs.get(i); 3773 if (DEBUG_PREFERRED || debug) { 3774 Slog.v(TAG, "Checking PreferredActivity ds=" 3775 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3776 + "\n component=" + pa.mPref.mComponent); 3777 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3778 } 3779 if (pa.mPref.mMatch != match) { 3780 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3781 + Integer.toHexString(pa.mPref.mMatch)); 3782 continue; 3783 } 3784 // If it's not an "always" type preferred activity and that's what we're 3785 // looking for, skip it. 3786 if (always && !pa.mPref.mAlways) { 3787 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3788 continue; 3789 } 3790 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3791 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3792 if (DEBUG_PREFERRED || debug) { 3793 Slog.v(TAG, "Found preferred activity:"); 3794 if (ai != null) { 3795 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3796 } else { 3797 Slog.v(TAG, " null"); 3798 } 3799 } 3800 if (ai == null) { 3801 // This previously registered preferred activity 3802 // component is no longer known. Most likely an update 3803 // to the app was installed and in the new version this 3804 // component no longer exists. Clean it up by removing 3805 // it from the preferred activities list, and skip it. 3806 Slog.w(TAG, "Removing dangling preferred activity: " 3807 + pa.mPref.mComponent); 3808 pir.removeFilter(pa); 3809 changed = true; 3810 continue; 3811 } 3812 for (int j=0; j<N; j++) { 3813 final ResolveInfo ri = query.get(j); 3814 if (!ri.activityInfo.applicationInfo.packageName 3815 .equals(ai.applicationInfo.packageName)) { 3816 continue; 3817 } 3818 if (!ri.activityInfo.name.equals(ai.name)) { 3819 continue; 3820 } 3821 3822 if (removeMatches) { 3823 pir.removeFilter(pa); 3824 changed = true; 3825 if (DEBUG_PREFERRED) { 3826 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3827 } 3828 break; 3829 } 3830 3831 // Okay we found a previously set preferred or last chosen app. 3832 // If the result set is different from when this 3833 // was created, we need to clear it and re-ask the 3834 // user their preference, if we're looking for an "always" type entry. 3835 if (always && !pa.mPref.sameSet(query)) { 3836 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3837 + intent + " type " + resolvedType); 3838 if (DEBUG_PREFERRED) { 3839 Slog.v(TAG, "Removing preferred activity since set changed " 3840 + pa.mPref.mComponent); 3841 } 3842 pir.removeFilter(pa); 3843 // Re-add the filter as a "last chosen" entry (!always) 3844 PreferredActivity lastChosen = new PreferredActivity( 3845 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3846 pir.addFilter(lastChosen); 3847 changed = true; 3848 return null; 3849 } 3850 3851 // Yay! Either the set matched or we're looking for the last chosen 3852 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3853 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3854 return ri; 3855 } 3856 } 3857 } finally { 3858 if (changed) { 3859 if (DEBUG_PREFERRED) { 3860 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3861 } 3862 scheduleWritePackageRestrictionsLocked(userId); 3863 } 3864 } 3865 } 3866 } 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3868 return null; 3869 } 3870 3871 /* 3872 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3873 */ 3874 @Override 3875 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3876 int targetUserId) { 3877 mContext.enforceCallingOrSelfPermission( 3878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3879 List<CrossProfileIntentFilter> matches = 3880 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3881 if (matches != null) { 3882 int size = matches.size(); 3883 for (int i = 0; i < size; i++) { 3884 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3885 } 3886 } 3887 return false; 3888 } 3889 3890 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3891 String resolvedType, int userId) { 3892 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3893 if (resolver != null) { 3894 return resolver.queryIntent(intent, resolvedType, false, userId); 3895 } 3896 return null; 3897 } 3898 3899 @Override 3900 public List<ResolveInfo> queryIntentActivities(Intent intent, 3901 String resolvedType, int flags, int userId) { 3902 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3903 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3904 ComponentName comp = intent.getComponent(); 3905 if (comp == null) { 3906 if (intent.getSelector() != null) { 3907 intent = intent.getSelector(); 3908 comp = intent.getComponent(); 3909 } 3910 } 3911 3912 if (comp != null) { 3913 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3914 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3915 if (ai != null) { 3916 final ResolveInfo ri = new ResolveInfo(); 3917 ri.activityInfo = ai; 3918 list.add(ri); 3919 } 3920 return list; 3921 } 3922 3923 // reader 3924 synchronized (mPackages) { 3925 final String pkgName = intent.getPackage(); 3926 if (pkgName == null) { 3927 List<CrossProfileIntentFilter> matchingFilters = 3928 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3929 // Check for results that need to skip the current profile. 3930 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3931 resolvedType, flags, userId); 3932 if (resolveInfo != null) { 3933 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3934 result.add(resolveInfo); 3935 return filterIfNotPrimaryUser(result, userId); 3936 } 3937 // Check for cross profile results. 3938 resolveInfo = queryCrossProfileIntents( 3939 matchingFilters, intent, resolvedType, flags, userId); 3940 3941 // Check for results in the current profile. 3942 List<ResolveInfo> result = mActivities.queryIntent( 3943 intent, resolvedType, flags, userId); 3944 if (resolveInfo != null) { 3945 result.add(resolveInfo); 3946 Collections.sort(result, mResolvePrioritySorter); 3947 } 3948 result = filterIfNotPrimaryUser(result, userId); 3949 if (result.size() > 1 && hasWebURI(intent)) { 3950 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3951 } 3952 return result; 3953 } 3954 final PackageParser.Package pkg = mPackages.get(pkgName); 3955 if (pkg != null) { 3956 return filterIfNotPrimaryUser( 3957 mActivities.queryIntentForPackage( 3958 intent, resolvedType, flags, pkg.activities, userId), 3959 userId); 3960 } 3961 return new ArrayList<ResolveInfo>(); 3962 } 3963 } 3964 3965 /** 3966 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3967 * 3968 * @return filtered list 3969 */ 3970 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3971 if (userId == UserHandle.USER_OWNER) { 3972 return resolveInfos; 3973 } 3974 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3975 ResolveInfo info = resolveInfos.get(i); 3976 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3977 resolveInfos.remove(i); 3978 } 3979 } 3980 return resolveInfos; 3981 } 3982 3983 private static boolean hasWebURI(Intent intent) { 3984 if (intent.getData() == null) { 3985 return false; 3986 } 3987 final String scheme = intent.getScheme(); 3988 if (TextUtils.isEmpty(scheme)) { 3989 return false; 3990 } 3991 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 3992 } 3993 3994 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 3995 int flags, List<ResolveInfo> candidates) { 3996 if (DEBUG_PREFERRED) { 3997 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3998 candidates.size()); 3999 } 4000 4001 final int userId = UserHandle.getCallingUserId(); 4002 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4003 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4004 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4005 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4006 4007 synchronized (mPackages) { 4008 final int count = candidates.size(); 4009 // First, try to use the domain prefered App 4010 for (int n=0; n<count; n++) { 4011 ResolveInfo info = candidates.get(n); 4012 String packageName = info.activityInfo.packageName; 4013 PackageSetting ps = mSettings.mPackages.get(packageName); 4014 if (ps != null) { 4015 // Add to the special match all list (Browser use case) 4016 if (info.handleAllWebDataURI) { 4017 matchAllList.add(info); 4018 continue; 4019 } 4020 // Try to get the status from User settings first 4021 int status = getDomainVerificationStatusLPr(ps, userId); 4022 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4023 result.add(info); 4024 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4025 neverList.add(info); 4026 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4027 undefinedList.add(info); 4028 } 4029 } 4030 } 4031 // If there is nothing selected, add all candidates and remove the ones that the User 4032 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4033 // also remove any Browser Apps ones. 4034 // If there is still none after this pass, add all undefined one and Browser Apps and 4035 // let the User decide with the Disambiguation dialog if there are several ones. 4036 if (result.size() == 0) { 4037 result.addAll(candidates); 4038 } 4039 result.removeAll(neverList); 4040 result.removeAll(matchAllList); 4041 if (result.size() == 0) { 4042 result.addAll(undefinedList); 4043 if ((flags & MATCH_ALL) != 0) { 4044 result.addAll(matchAllList); 4045 } else { 4046 // Try to add the Default Browser if we can 4047 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4048 UserHandle.myUserId()); 4049 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4050 boolean defaultBrowserFound = false; 4051 final int browserCount = matchAllList.size(); 4052 for (int n=0; n<browserCount; n++) { 4053 ResolveInfo browser = matchAllList.get(n); 4054 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4055 result.add(browser); 4056 defaultBrowserFound = true; 4057 break; 4058 } 4059 } 4060 if (!defaultBrowserFound) { 4061 result.addAll(matchAllList); 4062 } 4063 } else { 4064 result.addAll(matchAllList); 4065 } 4066 } 4067 } 4068 } 4069 if (DEBUG_PREFERRED) { 4070 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4071 result.size()); 4072 } 4073 return result; 4074 } 4075 4076 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4077 int status = ps.getDomainVerificationStatusForUser(userId); 4078 // if none available, get the master status 4079 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4080 if (ps.getIntentFilterVerificationInfo() != null) { 4081 status = ps.getIntentFilterVerificationInfo().getStatus(); 4082 } 4083 } 4084 return status; 4085 } 4086 4087 private ResolveInfo querySkipCurrentProfileIntents( 4088 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4089 int flags, int sourceUserId) { 4090 if (matchingFilters != null) { 4091 int size = matchingFilters.size(); 4092 for (int i = 0; i < size; i ++) { 4093 CrossProfileIntentFilter filter = matchingFilters.get(i); 4094 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4095 // Checking if there are activities in the target user that can handle the 4096 // intent. 4097 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4098 flags, sourceUserId); 4099 if (resolveInfo != null) { 4100 return resolveInfo; 4101 } 4102 } 4103 } 4104 } 4105 return null; 4106 } 4107 4108 // Return matching ResolveInfo if any for skip current profile intent filters. 4109 private ResolveInfo queryCrossProfileIntents( 4110 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4111 int flags, int sourceUserId) { 4112 if (matchingFilters != null) { 4113 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4114 // match the same intent. For performance reasons, it is better not to 4115 // run queryIntent twice for the same userId 4116 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4117 int size = matchingFilters.size(); 4118 for (int i = 0; i < size; i++) { 4119 CrossProfileIntentFilter filter = matchingFilters.get(i); 4120 int targetUserId = filter.getTargetUserId(); 4121 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4122 && !alreadyTriedUserIds.get(targetUserId)) { 4123 // Checking if there are activities in the target user that can handle the 4124 // intent. 4125 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4126 flags, sourceUserId); 4127 if (resolveInfo != null) return resolveInfo; 4128 alreadyTriedUserIds.put(targetUserId, true); 4129 } 4130 } 4131 } 4132 return null; 4133 } 4134 4135 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4136 String resolvedType, int flags, int sourceUserId) { 4137 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4138 resolvedType, flags, filter.getTargetUserId()); 4139 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4140 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4141 } 4142 return null; 4143 } 4144 4145 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4146 int sourceUserId, int targetUserId) { 4147 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4148 String className; 4149 if (targetUserId == UserHandle.USER_OWNER) { 4150 className = FORWARD_INTENT_TO_USER_OWNER; 4151 } else { 4152 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4153 } 4154 ComponentName forwardingActivityComponentName = new ComponentName( 4155 mAndroidApplication.packageName, className); 4156 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4157 sourceUserId); 4158 if (targetUserId == UserHandle.USER_OWNER) { 4159 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4160 forwardingResolveInfo.noResourceId = true; 4161 } 4162 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4163 forwardingResolveInfo.priority = 0; 4164 forwardingResolveInfo.preferredOrder = 0; 4165 forwardingResolveInfo.match = 0; 4166 forwardingResolveInfo.isDefault = true; 4167 forwardingResolveInfo.filter = filter; 4168 forwardingResolveInfo.targetUserId = targetUserId; 4169 return forwardingResolveInfo; 4170 } 4171 4172 @Override 4173 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4174 Intent[] specifics, String[] specificTypes, Intent intent, 4175 String resolvedType, int flags, int userId) { 4176 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4177 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4178 false, "query intent activity options"); 4179 final String resultsAction = intent.getAction(); 4180 4181 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4182 | PackageManager.GET_RESOLVED_FILTER, userId); 4183 4184 if (DEBUG_INTENT_MATCHING) { 4185 Log.v(TAG, "Query " + intent + ": " + results); 4186 } 4187 4188 int specificsPos = 0; 4189 int N; 4190 4191 // todo: note that the algorithm used here is O(N^2). This 4192 // isn't a problem in our current environment, but if we start running 4193 // into situations where we have more than 5 or 10 matches then this 4194 // should probably be changed to something smarter... 4195 4196 // First we go through and resolve each of the specific items 4197 // that were supplied, taking care of removing any corresponding 4198 // duplicate items in the generic resolve list. 4199 if (specifics != null) { 4200 for (int i=0; i<specifics.length; i++) { 4201 final Intent sintent = specifics[i]; 4202 if (sintent == null) { 4203 continue; 4204 } 4205 4206 if (DEBUG_INTENT_MATCHING) { 4207 Log.v(TAG, "Specific #" + i + ": " + sintent); 4208 } 4209 4210 String action = sintent.getAction(); 4211 if (resultsAction != null && resultsAction.equals(action)) { 4212 // If this action was explicitly requested, then don't 4213 // remove things that have it. 4214 action = null; 4215 } 4216 4217 ResolveInfo ri = null; 4218 ActivityInfo ai = null; 4219 4220 ComponentName comp = sintent.getComponent(); 4221 if (comp == null) { 4222 ri = resolveIntent( 4223 sintent, 4224 specificTypes != null ? specificTypes[i] : null, 4225 flags, userId); 4226 if (ri == null) { 4227 continue; 4228 } 4229 if (ri == mResolveInfo) { 4230 // ACK! Must do something better with this. 4231 } 4232 ai = ri.activityInfo; 4233 comp = new ComponentName(ai.applicationInfo.packageName, 4234 ai.name); 4235 } else { 4236 ai = getActivityInfo(comp, flags, userId); 4237 if (ai == null) { 4238 continue; 4239 } 4240 } 4241 4242 // Look for any generic query activities that are duplicates 4243 // of this specific one, and remove them from the results. 4244 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4245 N = results.size(); 4246 int j; 4247 for (j=specificsPos; j<N; j++) { 4248 ResolveInfo sri = results.get(j); 4249 if ((sri.activityInfo.name.equals(comp.getClassName()) 4250 && sri.activityInfo.applicationInfo.packageName.equals( 4251 comp.getPackageName())) 4252 || (action != null && sri.filter.matchAction(action))) { 4253 results.remove(j); 4254 if (DEBUG_INTENT_MATCHING) Log.v( 4255 TAG, "Removing duplicate item from " + j 4256 + " due to specific " + specificsPos); 4257 if (ri == null) { 4258 ri = sri; 4259 } 4260 j--; 4261 N--; 4262 } 4263 } 4264 4265 // Add this specific item to its proper place. 4266 if (ri == null) { 4267 ri = new ResolveInfo(); 4268 ri.activityInfo = ai; 4269 } 4270 results.add(specificsPos, ri); 4271 ri.specificIndex = i; 4272 specificsPos++; 4273 } 4274 } 4275 4276 // Now we go through the remaining generic results and remove any 4277 // duplicate actions that are found here. 4278 N = results.size(); 4279 for (int i=specificsPos; i<N-1; i++) { 4280 final ResolveInfo rii = results.get(i); 4281 if (rii.filter == null) { 4282 continue; 4283 } 4284 4285 // Iterate over all of the actions of this result's intent 4286 // filter... typically this should be just one. 4287 final Iterator<String> it = rii.filter.actionsIterator(); 4288 if (it == null) { 4289 continue; 4290 } 4291 while (it.hasNext()) { 4292 final String action = it.next(); 4293 if (resultsAction != null && resultsAction.equals(action)) { 4294 // If this action was explicitly requested, then don't 4295 // remove things that have it. 4296 continue; 4297 } 4298 for (int j=i+1; j<N; j++) { 4299 final ResolveInfo rij = results.get(j); 4300 if (rij.filter != null && rij.filter.hasAction(action)) { 4301 results.remove(j); 4302 if (DEBUG_INTENT_MATCHING) Log.v( 4303 TAG, "Removing duplicate item from " + j 4304 + " due to action " + action + " at " + i); 4305 j--; 4306 N--; 4307 } 4308 } 4309 } 4310 4311 // If the caller didn't request filter information, drop it now 4312 // so we don't have to marshall/unmarshall it. 4313 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4314 rii.filter = null; 4315 } 4316 } 4317 4318 // Filter out the caller activity if so requested. 4319 if (caller != null) { 4320 N = results.size(); 4321 for (int i=0; i<N; i++) { 4322 ActivityInfo ainfo = results.get(i).activityInfo; 4323 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4324 && caller.getClassName().equals(ainfo.name)) { 4325 results.remove(i); 4326 break; 4327 } 4328 } 4329 } 4330 4331 // If the caller didn't request filter information, 4332 // drop them now so we don't have to 4333 // marshall/unmarshall it. 4334 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4335 N = results.size(); 4336 for (int i=0; i<N; i++) { 4337 results.get(i).filter = null; 4338 } 4339 } 4340 4341 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4342 return results; 4343 } 4344 4345 @Override 4346 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4347 int userId) { 4348 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4349 ComponentName comp = intent.getComponent(); 4350 if (comp == null) { 4351 if (intent.getSelector() != null) { 4352 intent = intent.getSelector(); 4353 comp = intent.getComponent(); 4354 } 4355 } 4356 if (comp != null) { 4357 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4358 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4359 if (ai != null) { 4360 ResolveInfo ri = new ResolveInfo(); 4361 ri.activityInfo = ai; 4362 list.add(ri); 4363 } 4364 return list; 4365 } 4366 4367 // reader 4368 synchronized (mPackages) { 4369 String pkgName = intent.getPackage(); 4370 if (pkgName == null) { 4371 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4372 } 4373 final PackageParser.Package pkg = mPackages.get(pkgName); 4374 if (pkg != null) { 4375 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4376 userId); 4377 } 4378 return null; 4379 } 4380 } 4381 4382 @Override 4383 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4384 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4385 if (!sUserManager.exists(userId)) return null; 4386 if (query != null) { 4387 if (query.size() >= 1) { 4388 // If there is more than one service with the same priority, 4389 // just arbitrarily pick the first one. 4390 return query.get(0); 4391 } 4392 } 4393 return null; 4394 } 4395 4396 @Override 4397 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4398 int userId) { 4399 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4400 ComponentName comp = intent.getComponent(); 4401 if (comp == null) { 4402 if (intent.getSelector() != null) { 4403 intent = intent.getSelector(); 4404 comp = intent.getComponent(); 4405 } 4406 } 4407 if (comp != null) { 4408 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4409 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4410 if (si != null) { 4411 final ResolveInfo ri = new ResolveInfo(); 4412 ri.serviceInfo = si; 4413 list.add(ri); 4414 } 4415 return list; 4416 } 4417 4418 // reader 4419 synchronized (mPackages) { 4420 String pkgName = intent.getPackage(); 4421 if (pkgName == null) { 4422 return mServices.queryIntent(intent, resolvedType, flags, userId); 4423 } 4424 final PackageParser.Package pkg = mPackages.get(pkgName); 4425 if (pkg != null) { 4426 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4427 userId); 4428 } 4429 return null; 4430 } 4431 } 4432 4433 @Override 4434 public List<ResolveInfo> queryIntentContentProviders( 4435 Intent intent, String resolvedType, int flags, int userId) { 4436 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4437 ComponentName comp = intent.getComponent(); 4438 if (comp == null) { 4439 if (intent.getSelector() != null) { 4440 intent = intent.getSelector(); 4441 comp = intent.getComponent(); 4442 } 4443 } 4444 if (comp != null) { 4445 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4446 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4447 if (pi != null) { 4448 final ResolveInfo ri = new ResolveInfo(); 4449 ri.providerInfo = pi; 4450 list.add(ri); 4451 } 4452 return list; 4453 } 4454 4455 // reader 4456 synchronized (mPackages) { 4457 String pkgName = intent.getPackage(); 4458 if (pkgName == null) { 4459 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4460 } 4461 final PackageParser.Package pkg = mPackages.get(pkgName); 4462 if (pkg != null) { 4463 return mProviders.queryIntentForPackage( 4464 intent, resolvedType, flags, pkg.providers, userId); 4465 } 4466 return null; 4467 } 4468 } 4469 4470 @Override 4471 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4472 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4473 4474 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4475 4476 // writer 4477 synchronized (mPackages) { 4478 ArrayList<PackageInfo> list; 4479 if (listUninstalled) { 4480 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4481 for (PackageSetting ps : mSettings.mPackages.values()) { 4482 PackageInfo pi; 4483 if (ps.pkg != null) { 4484 pi = generatePackageInfo(ps.pkg, flags, userId); 4485 } else { 4486 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4487 } 4488 if (pi != null) { 4489 list.add(pi); 4490 } 4491 } 4492 } else { 4493 list = new ArrayList<PackageInfo>(mPackages.size()); 4494 for (PackageParser.Package p : mPackages.values()) { 4495 PackageInfo pi = generatePackageInfo(p, flags, userId); 4496 if (pi != null) { 4497 list.add(pi); 4498 } 4499 } 4500 } 4501 4502 return new ParceledListSlice<PackageInfo>(list); 4503 } 4504 } 4505 4506 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4507 String[] permissions, boolean[] tmp, int flags, int userId) { 4508 int numMatch = 0; 4509 final PermissionsState permissionsState = ps.getPermissionsState(); 4510 for (int i=0; i<permissions.length; i++) { 4511 final String permission = permissions[i]; 4512 if (permissionsState.hasPermission(permission, userId)) { 4513 tmp[i] = true; 4514 numMatch++; 4515 } else { 4516 tmp[i] = false; 4517 } 4518 } 4519 if (numMatch == 0) { 4520 return; 4521 } 4522 PackageInfo pi; 4523 if (ps.pkg != null) { 4524 pi = generatePackageInfo(ps.pkg, flags, userId); 4525 } else { 4526 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4527 } 4528 // The above might return null in cases of uninstalled apps or install-state 4529 // skew across users/profiles. 4530 if (pi != null) { 4531 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4532 if (numMatch == permissions.length) { 4533 pi.requestedPermissions = permissions; 4534 } else { 4535 pi.requestedPermissions = new String[numMatch]; 4536 numMatch = 0; 4537 for (int i=0; i<permissions.length; i++) { 4538 if (tmp[i]) { 4539 pi.requestedPermissions[numMatch] = permissions[i]; 4540 numMatch++; 4541 } 4542 } 4543 } 4544 } 4545 list.add(pi); 4546 } 4547 } 4548 4549 @Override 4550 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4551 String[] permissions, int flags, int userId) { 4552 if (!sUserManager.exists(userId)) return null; 4553 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4554 4555 // writer 4556 synchronized (mPackages) { 4557 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4558 boolean[] tmpBools = new boolean[permissions.length]; 4559 if (listUninstalled) { 4560 for (PackageSetting ps : mSettings.mPackages.values()) { 4561 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4562 } 4563 } else { 4564 for (PackageParser.Package pkg : mPackages.values()) { 4565 PackageSetting ps = (PackageSetting)pkg.mExtras; 4566 if (ps != null) { 4567 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4568 userId); 4569 } 4570 } 4571 } 4572 4573 return new ParceledListSlice<PackageInfo>(list); 4574 } 4575 } 4576 4577 @Override 4578 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4579 if (!sUserManager.exists(userId)) return null; 4580 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4581 4582 // writer 4583 synchronized (mPackages) { 4584 ArrayList<ApplicationInfo> list; 4585 if (listUninstalled) { 4586 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4587 for (PackageSetting ps : mSettings.mPackages.values()) { 4588 ApplicationInfo ai; 4589 if (ps.pkg != null) { 4590 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4591 ps.readUserState(userId), userId); 4592 } else { 4593 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4594 } 4595 if (ai != null) { 4596 list.add(ai); 4597 } 4598 } 4599 } else { 4600 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4601 for (PackageParser.Package p : mPackages.values()) { 4602 if (p.mExtras != null) { 4603 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4604 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4605 if (ai != null) { 4606 list.add(ai); 4607 } 4608 } 4609 } 4610 } 4611 4612 return new ParceledListSlice<ApplicationInfo>(list); 4613 } 4614 } 4615 4616 public List<ApplicationInfo> getPersistentApplications(int flags) { 4617 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4618 4619 // reader 4620 synchronized (mPackages) { 4621 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4622 final int userId = UserHandle.getCallingUserId(); 4623 while (i.hasNext()) { 4624 final PackageParser.Package p = i.next(); 4625 if (p.applicationInfo != null 4626 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4627 && (!mSafeMode || isSystemApp(p))) { 4628 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4629 if (ps != null) { 4630 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4631 ps.readUserState(userId), userId); 4632 if (ai != null) { 4633 finalList.add(ai); 4634 } 4635 } 4636 } 4637 } 4638 } 4639 4640 return finalList; 4641 } 4642 4643 @Override 4644 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4645 if (!sUserManager.exists(userId)) return null; 4646 // reader 4647 synchronized (mPackages) { 4648 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4649 PackageSetting ps = provider != null 4650 ? mSettings.mPackages.get(provider.owner.packageName) 4651 : null; 4652 return ps != null 4653 && mSettings.isEnabledLPr(provider.info, flags, userId) 4654 && (!mSafeMode || (provider.info.applicationInfo.flags 4655 &ApplicationInfo.FLAG_SYSTEM) != 0) 4656 ? PackageParser.generateProviderInfo(provider, flags, 4657 ps.readUserState(userId), userId) 4658 : null; 4659 } 4660 } 4661 4662 /** 4663 * @deprecated 4664 */ 4665 @Deprecated 4666 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4667 // reader 4668 synchronized (mPackages) { 4669 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4670 .entrySet().iterator(); 4671 final int userId = UserHandle.getCallingUserId(); 4672 while (i.hasNext()) { 4673 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4674 PackageParser.Provider p = entry.getValue(); 4675 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4676 4677 if (ps != null && p.syncable 4678 && (!mSafeMode || (p.info.applicationInfo.flags 4679 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4680 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4681 ps.readUserState(userId), userId); 4682 if (info != null) { 4683 outNames.add(entry.getKey()); 4684 outInfo.add(info); 4685 } 4686 } 4687 } 4688 } 4689 } 4690 4691 @Override 4692 public List<ProviderInfo> queryContentProviders(String processName, 4693 int uid, int flags) { 4694 ArrayList<ProviderInfo> finalList = null; 4695 // reader 4696 synchronized (mPackages) { 4697 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4698 final int userId = processName != null ? 4699 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4700 while (i.hasNext()) { 4701 final PackageParser.Provider p = i.next(); 4702 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4703 if (ps != null && p.info.authority != null 4704 && (processName == null 4705 || (p.info.processName.equals(processName) 4706 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4707 && mSettings.isEnabledLPr(p.info, flags, userId) 4708 && (!mSafeMode 4709 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4710 if (finalList == null) { 4711 finalList = new ArrayList<ProviderInfo>(3); 4712 } 4713 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4714 ps.readUserState(userId), userId); 4715 if (info != null) { 4716 finalList.add(info); 4717 } 4718 } 4719 } 4720 } 4721 4722 if (finalList != null) { 4723 Collections.sort(finalList, mProviderInitOrderSorter); 4724 } 4725 4726 return finalList; 4727 } 4728 4729 @Override 4730 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4731 int flags) { 4732 // reader 4733 synchronized (mPackages) { 4734 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4735 return PackageParser.generateInstrumentationInfo(i, flags); 4736 } 4737 } 4738 4739 @Override 4740 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4741 int flags) { 4742 ArrayList<InstrumentationInfo> finalList = 4743 new ArrayList<InstrumentationInfo>(); 4744 4745 // reader 4746 synchronized (mPackages) { 4747 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4748 while (i.hasNext()) { 4749 final PackageParser.Instrumentation p = i.next(); 4750 if (targetPackage == null 4751 || targetPackage.equals(p.info.targetPackage)) { 4752 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4753 flags); 4754 if (ii != null) { 4755 finalList.add(ii); 4756 } 4757 } 4758 } 4759 } 4760 4761 return finalList; 4762 } 4763 4764 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4765 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4766 if (overlays == null) { 4767 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4768 return; 4769 } 4770 for (PackageParser.Package opkg : overlays.values()) { 4771 // Not much to do if idmap fails: we already logged the error 4772 // and we certainly don't want to abort installation of pkg simply 4773 // because an overlay didn't fit properly. For these reasons, 4774 // ignore the return value of createIdmapForPackagePairLI. 4775 createIdmapForPackagePairLI(pkg, opkg); 4776 } 4777 } 4778 4779 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4780 PackageParser.Package opkg) { 4781 if (!opkg.mTrustedOverlay) { 4782 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4783 opkg.baseCodePath + ": overlay not trusted"); 4784 return false; 4785 } 4786 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4787 if (overlaySet == null) { 4788 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4789 opkg.baseCodePath + " but target package has no known overlays"); 4790 return false; 4791 } 4792 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4793 // TODO: generate idmap for split APKs 4794 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4795 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4796 + opkg.baseCodePath); 4797 return false; 4798 } 4799 PackageParser.Package[] overlayArray = 4800 overlaySet.values().toArray(new PackageParser.Package[0]); 4801 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4802 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4803 return p1.mOverlayPriority - p2.mOverlayPriority; 4804 } 4805 }; 4806 Arrays.sort(overlayArray, cmp); 4807 4808 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4809 int i = 0; 4810 for (PackageParser.Package p : overlayArray) { 4811 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4812 } 4813 return true; 4814 } 4815 4816 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4817 final File[] files = dir.listFiles(); 4818 if (ArrayUtils.isEmpty(files)) { 4819 Log.d(TAG, "No files in app dir " + dir); 4820 return; 4821 } 4822 4823 if (DEBUG_PACKAGE_SCANNING) { 4824 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4825 + " flags=0x" + Integer.toHexString(parseFlags)); 4826 } 4827 4828 for (File file : files) { 4829 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4830 && !PackageInstallerService.isStageName(file.getName()); 4831 if (!isPackage) { 4832 // Ignore entries which are not packages 4833 continue; 4834 } 4835 try { 4836 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4837 scanFlags, currentTime, null); 4838 } catch (PackageManagerException e) { 4839 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4840 4841 // Delete invalid userdata apps 4842 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4843 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4844 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4845 if (file.isDirectory()) { 4846 mInstaller.rmPackageDir(file.getAbsolutePath()); 4847 } else { 4848 file.delete(); 4849 } 4850 } 4851 } 4852 } 4853 } 4854 4855 private static File getSettingsProblemFile() { 4856 File dataDir = Environment.getDataDirectory(); 4857 File systemDir = new File(dataDir, "system"); 4858 File fname = new File(systemDir, "uiderrors.txt"); 4859 return fname; 4860 } 4861 4862 static void reportSettingsProblem(int priority, String msg) { 4863 logCriticalInfo(priority, msg); 4864 } 4865 4866 static void logCriticalInfo(int priority, String msg) { 4867 Slog.println(priority, TAG, msg); 4868 EventLogTags.writePmCriticalInfo(msg); 4869 try { 4870 File fname = getSettingsProblemFile(); 4871 FileOutputStream out = new FileOutputStream(fname, true); 4872 PrintWriter pw = new FastPrintWriter(out); 4873 SimpleDateFormat formatter = new SimpleDateFormat(); 4874 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4875 pw.println(dateString + ": " + msg); 4876 pw.close(); 4877 FileUtils.setPermissions( 4878 fname.toString(), 4879 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4880 -1, -1); 4881 } catch (java.io.IOException e) { 4882 } 4883 } 4884 4885 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4886 PackageParser.Package pkg, File srcFile, int parseFlags) 4887 throws PackageManagerException { 4888 if (ps != null 4889 && ps.codePath.equals(srcFile) 4890 && ps.timeStamp == srcFile.lastModified() 4891 && !isCompatSignatureUpdateNeeded(pkg) 4892 && !isRecoverSignatureUpdateNeeded(pkg)) { 4893 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4894 if (ps.signatures.mSignatures != null 4895 && ps.signatures.mSignatures.length != 0 4896 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4897 // Optimization: reuse the existing cached certificates 4898 // if the package appears to be unchanged. 4899 pkg.mSignatures = ps.signatures.mSignatures; 4900 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4901 synchronized (mPackages) { 4902 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4903 } 4904 return; 4905 } 4906 4907 Slog.w(TAG, "PackageSetting for " + ps.name 4908 + " is missing signatures. Collecting certs again to recover them."); 4909 } else { 4910 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4911 } 4912 4913 try { 4914 pp.collectCertificates(pkg, parseFlags); 4915 pp.collectManifestDigest(pkg); 4916 } catch (PackageParserException e) { 4917 throw PackageManagerException.from(e); 4918 } 4919 } 4920 4921 /* 4922 * Scan a package and return the newly parsed package. 4923 * Returns null in case of errors and the error code is stored in mLastScanError 4924 */ 4925 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4926 long currentTime, UserHandle user) throws PackageManagerException { 4927 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4928 parseFlags |= mDefParseFlags; 4929 PackageParser pp = new PackageParser(); 4930 pp.setSeparateProcesses(mSeparateProcesses); 4931 pp.setOnlyCoreApps(mOnlyCore); 4932 pp.setDisplayMetrics(mMetrics); 4933 4934 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4935 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4936 } 4937 4938 final PackageParser.Package pkg; 4939 try { 4940 pkg = pp.parsePackage(scanFile, parseFlags); 4941 } catch (PackageParserException e) { 4942 throw PackageManagerException.from(e); 4943 } 4944 4945 PackageSetting ps = null; 4946 PackageSetting updatedPkg; 4947 // reader 4948 synchronized (mPackages) { 4949 // Look to see if we already know about this package. 4950 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4951 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4952 // This package has been renamed to its original name. Let's 4953 // use that. 4954 ps = mSettings.peekPackageLPr(oldName); 4955 } 4956 // If there was no original package, see one for the real package name. 4957 if (ps == null) { 4958 ps = mSettings.peekPackageLPr(pkg.packageName); 4959 } 4960 // Check to see if this package could be hiding/updating a system 4961 // package. Must look for it either under the original or real 4962 // package name depending on our state. 4963 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4964 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4965 } 4966 boolean updatedPkgBetter = false; 4967 // First check if this is a system package that may involve an update 4968 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4969 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4970 // it needs to drop FLAG_PRIVILEGED. 4971 if (locationIsPrivileged(scanFile)) { 4972 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4973 } else { 4974 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4975 } 4976 4977 if (ps != null && !ps.codePath.equals(scanFile)) { 4978 // The path has changed from what was last scanned... check the 4979 // version of the new path against what we have stored to determine 4980 // what to do. 4981 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4982 if (pkg.mVersionCode <= ps.versionCode) { 4983 // The system package has been updated and the code path does not match 4984 // Ignore entry. Skip it. 4985 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4986 + " ignored: updated version " + ps.versionCode 4987 + " better than this " + pkg.mVersionCode); 4988 if (!updatedPkg.codePath.equals(scanFile)) { 4989 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4990 + ps.name + " changing from " + updatedPkg.codePathString 4991 + " to " + scanFile); 4992 updatedPkg.codePath = scanFile; 4993 updatedPkg.codePathString = scanFile.toString(); 4994 updatedPkg.resourcePath = scanFile; 4995 updatedPkg.resourcePathString = scanFile.toString(); 4996 } 4997 updatedPkg.pkg = pkg; 4998 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4999 } else { 5000 // The current app on the system partition is better than 5001 // what we have updated to on the data partition; switch 5002 // back to the system partition version. 5003 // At this point, its safely assumed that package installation for 5004 // apps in system partition will go through. If not there won't be a working 5005 // version of the app 5006 // writer 5007 synchronized (mPackages) { 5008 // Just remove the loaded entries from package lists. 5009 mPackages.remove(ps.name); 5010 } 5011 5012 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5013 + " reverting from " + ps.codePathString 5014 + ": new version " + pkg.mVersionCode 5015 + " better than installed " + ps.versionCode); 5016 5017 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5018 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5019 getAppDexInstructionSets(ps)); 5020 synchronized (mInstallLock) { 5021 args.cleanUpResourcesLI(); 5022 } 5023 synchronized (mPackages) { 5024 mSettings.enableSystemPackageLPw(ps.name); 5025 } 5026 updatedPkgBetter = true; 5027 } 5028 } 5029 } 5030 5031 if (updatedPkg != null) { 5032 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5033 // initially 5034 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5035 5036 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5037 // flag set initially 5038 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5039 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5040 } 5041 } 5042 5043 // Verify certificates against what was last scanned 5044 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5045 5046 /* 5047 * A new system app appeared, but we already had a non-system one of the 5048 * same name installed earlier. 5049 */ 5050 boolean shouldHideSystemApp = false; 5051 if (updatedPkg == null && ps != null 5052 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5053 /* 5054 * Check to make sure the signatures match first. If they don't, 5055 * wipe the installed application and its data. 5056 */ 5057 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5058 != PackageManager.SIGNATURE_MATCH) { 5059 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5060 + " signatures don't match existing userdata copy; removing"); 5061 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5062 ps = null; 5063 } else { 5064 /* 5065 * If the newly-added system app is an older version than the 5066 * already installed version, hide it. It will be scanned later 5067 * and re-added like an update. 5068 */ 5069 if (pkg.mVersionCode <= ps.versionCode) { 5070 shouldHideSystemApp = true; 5071 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5072 + " but new version " + pkg.mVersionCode + " better than installed " 5073 + ps.versionCode + "; hiding system"); 5074 } else { 5075 /* 5076 * The newly found system app is a newer version that the 5077 * one previously installed. Simply remove the 5078 * already-installed application and replace it with our own 5079 * while keeping the application data. 5080 */ 5081 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5082 + " reverting from " + ps.codePathString + ": new version " 5083 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5084 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5085 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5086 getAppDexInstructionSets(ps)); 5087 synchronized (mInstallLock) { 5088 args.cleanUpResourcesLI(); 5089 } 5090 } 5091 } 5092 } 5093 5094 // The apk is forward locked (not public) if its code and resources 5095 // are kept in different files. (except for app in either system or 5096 // vendor path). 5097 // TODO grab this value from PackageSettings 5098 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5099 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5100 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5101 } 5102 } 5103 5104 // TODO: extend to support forward-locked splits 5105 String resourcePath = null; 5106 String baseResourcePath = null; 5107 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5108 if (ps != null && ps.resourcePathString != null) { 5109 resourcePath = ps.resourcePathString; 5110 baseResourcePath = ps.resourcePathString; 5111 } else { 5112 // Should not happen at all. Just log an error. 5113 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5114 } 5115 } else { 5116 resourcePath = pkg.codePath; 5117 baseResourcePath = pkg.baseCodePath; 5118 } 5119 5120 // Set application objects path explicitly. 5121 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5122 pkg.applicationInfo.setCodePath(pkg.codePath); 5123 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5124 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5125 pkg.applicationInfo.setResourcePath(resourcePath); 5126 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5127 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5128 5129 // Note that we invoke the following method only if we are about to unpack an application 5130 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5131 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5132 5133 /* 5134 * If the system app should be overridden by a previously installed 5135 * data, hide the system app now and let the /data/app scan pick it up 5136 * again. 5137 */ 5138 if (shouldHideSystemApp) { 5139 synchronized (mPackages) { 5140 /* 5141 * We have to grant systems permissions before we hide, because 5142 * grantPermissions will assume the package update is trying to 5143 * expand its permissions. 5144 */ 5145 grantPermissionsLPw(pkg, true, pkg.packageName); 5146 mSettings.disableSystemPackageLPw(pkg.packageName); 5147 } 5148 } 5149 5150 return scannedPkg; 5151 } 5152 5153 private static String fixProcessName(String defProcessName, 5154 String processName, int uid) { 5155 if (processName == null) { 5156 return defProcessName; 5157 } 5158 return processName; 5159 } 5160 5161 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5162 throws PackageManagerException { 5163 if (pkgSetting.signatures.mSignatures != null) { 5164 // Already existing package. Make sure signatures match 5165 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5166 == PackageManager.SIGNATURE_MATCH; 5167 if (!match) { 5168 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5169 == PackageManager.SIGNATURE_MATCH; 5170 } 5171 if (!match) { 5172 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5173 == PackageManager.SIGNATURE_MATCH; 5174 } 5175 if (!match) { 5176 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5177 + pkg.packageName + " signatures do not match the " 5178 + "previously installed version; ignoring!"); 5179 } 5180 } 5181 5182 // Check for shared user signatures 5183 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5184 // Already existing package. Make sure signatures match 5185 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5186 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5187 if (!match) { 5188 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5189 == PackageManager.SIGNATURE_MATCH; 5190 } 5191 if (!match) { 5192 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5193 == PackageManager.SIGNATURE_MATCH; 5194 } 5195 if (!match) { 5196 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5197 "Package " + pkg.packageName 5198 + " has no signatures that match those in shared user " 5199 + pkgSetting.sharedUser.name + "; ignoring!"); 5200 } 5201 } 5202 } 5203 5204 /** 5205 * Enforces that only the system UID or root's UID can call a method exposed 5206 * via Binder. 5207 * 5208 * @param message used as message if SecurityException is thrown 5209 * @throws SecurityException if the caller is not system or root 5210 */ 5211 private static final void enforceSystemOrRoot(String message) { 5212 final int uid = Binder.getCallingUid(); 5213 if (uid != Process.SYSTEM_UID && uid != 0) { 5214 throw new SecurityException(message); 5215 } 5216 } 5217 5218 @Override 5219 public void performBootDexOpt() { 5220 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5221 5222 // Before everything else, see whether we need to fstrim. 5223 try { 5224 IMountService ms = PackageHelper.getMountService(); 5225 if (ms != null) { 5226 final boolean isUpgrade = isUpgrade(); 5227 boolean doTrim = isUpgrade; 5228 if (doTrim) { 5229 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5230 } else { 5231 final long interval = android.provider.Settings.Global.getLong( 5232 mContext.getContentResolver(), 5233 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5234 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5235 if (interval > 0) { 5236 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5237 if (timeSinceLast > interval) { 5238 doTrim = true; 5239 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5240 + "; running immediately"); 5241 } 5242 } 5243 } 5244 if (doTrim) { 5245 if (!isFirstBoot()) { 5246 try { 5247 ActivityManagerNative.getDefault().showBootMessage( 5248 mContext.getResources().getString( 5249 R.string.android_upgrading_fstrim), true); 5250 } catch (RemoteException e) { 5251 } 5252 } 5253 ms.runMaintenance(); 5254 } 5255 } else { 5256 Slog.e(TAG, "Mount service unavailable!"); 5257 } 5258 } catch (RemoteException e) { 5259 // Can't happen; MountService is local 5260 } 5261 5262 final ArraySet<PackageParser.Package> pkgs; 5263 synchronized (mPackages) { 5264 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5265 } 5266 5267 if (pkgs != null) { 5268 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5269 // in case the device runs out of space. 5270 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5271 // Give priority to core apps. 5272 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5273 PackageParser.Package pkg = it.next(); 5274 if (pkg.coreApp) { 5275 if (DEBUG_DEXOPT) { 5276 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5277 } 5278 sortedPkgs.add(pkg); 5279 it.remove(); 5280 } 5281 } 5282 // Give priority to system apps that listen for pre boot complete. 5283 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5284 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5285 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5286 PackageParser.Package pkg = it.next(); 5287 if (pkgNames.contains(pkg.packageName)) { 5288 if (DEBUG_DEXOPT) { 5289 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5290 } 5291 sortedPkgs.add(pkg); 5292 it.remove(); 5293 } 5294 } 5295 // Give priority to system apps. 5296 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5297 PackageParser.Package pkg = it.next(); 5298 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5299 if (DEBUG_DEXOPT) { 5300 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5301 } 5302 sortedPkgs.add(pkg); 5303 it.remove(); 5304 } 5305 } 5306 // Give priority to updated system apps. 5307 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5308 PackageParser.Package pkg = it.next(); 5309 if (pkg.isUpdatedSystemApp()) { 5310 if (DEBUG_DEXOPT) { 5311 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5312 } 5313 sortedPkgs.add(pkg); 5314 it.remove(); 5315 } 5316 } 5317 // Give priority to apps that listen for boot complete. 5318 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5319 pkgNames = getPackageNamesForIntent(intent); 5320 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5321 PackageParser.Package pkg = it.next(); 5322 if (pkgNames.contains(pkg.packageName)) { 5323 if (DEBUG_DEXOPT) { 5324 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5325 } 5326 sortedPkgs.add(pkg); 5327 it.remove(); 5328 } 5329 } 5330 // Filter out packages that aren't recently used. 5331 filterRecentlyUsedApps(pkgs); 5332 // Add all remaining apps. 5333 for (PackageParser.Package pkg : pkgs) { 5334 if (DEBUG_DEXOPT) { 5335 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5336 } 5337 sortedPkgs.add(pkg); 5338 } 5339 5340 // If we want to be lazy, filter everything that wasn't recently used. 5341 if (mLazyDexOpt) { 5342 filterRecentlyUsedApps(sortedPkgs); 5343 } 5344 5345 int i = 0; 5346 int total = sortedPkgs.size(); 5347 File dataDir = Environment.getDataDirectory(); 5348 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5349 if (lowThreshold == 0) { 5350 throw new IllegalStateException("Invalid low memory threshold"); 5351 } 5352 for (PackageParser.Package pkg : sortedPkgs) { 5353 long usableSpace = dataDir.getUsableSpace(); 5354 if (usableSpace < lowThreshold) { 5355 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5356 break; 5357 } 5358 performBootDexOpt(pkg, ++i, total); 5359 } 5360 } 5361 } 5362 5363 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5364 // Filter out packages that aren't recently used. 5365 // 5366 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5367 // should do a full dexopt. 5368 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5369 int total = pkgs.size(); 5370 int skipped = 0; 5371 long now = System.currentTimeMillis(); 5372 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5373 PackageParser.Package pkg = i.next(); 5374 long then = pkg.mLastPackageUsageTimeInMills; 5375 if (then + mDexOptLRUThresholdInMills < now) { 5376 if (DEBUG_DEXOPT) { 5377 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5378 ((then == 0) ? "never" : new Date(then))); 5379 } 5380 i.remove(); 5381 skipped++; 5382 } 5383 } 5384 if (DEBUG_DEXOPT) { 5385 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5386 } 5387 } 5388 } 5389 5390 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5391 List<ResolveInfo> ris = null; 5392 try { 5393 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5394 intent, null, 0, UserHandle.USER_OWNER); 5395 } catch (RemoteException e) { 5396 } 5397 ArraySet<String> pkgNames = new ArraySet<String>(); 5398 if (ris != null) { 5399 for (ResolveInfo ri : ris) { 5400 pkgNames.add(ri.activityInfo.packageName); 5401 } 5402 } 5403 return pkgNames; 5404 } 5405 5406 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5407 if (DEBUG_DEXOPT) { 5408 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5409 } 5410 if (!isFirstBoot()) { 5411 try { 5412 ActivityManagerNative.getDefault().showBootMessage( 5413 mContext.getResources().getString(R.string.android_upgrading_apk, 5414 curr, total), true); 5415 } catch (RemoteException e) { 5416 } 5417 } 5418 PackageParser.Package p = pkg; 5419 synchronized (mInstallLock) { 5420 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5421 false /* force dex */, false /* defer */, true /* include dependencies */); 5422 } 5423 } 5424 5425 @Override 5426 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5427 return performDexOpt(packageName, instructionSet, false); 5428 } 5429 5430 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5431 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5432 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5433 if (!dexopt && !updateUsage) { 5434 // We aren't going to dexopt or update usage, so bail early. 5435 return false; 5436 } 5437 PackageParser.Package p; 5438 final String targetInstructionSet; 5439 synchronized (mPackages) { 5440 p = mPackages.get(packageName); 5441 if (p == null) { 5442 return false; 5443 } 5444 if (updateUsage) { 5445 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5446 } 5447 mPackageUsage.write(false); 5448 if (!dexopt) { 5449 // We aren't going to dexopt, so bail early. 5450 return false; 5451 } 5452 5453 targetInstructionSet = instructionSet != null ? instructionSet : 5454 getPrimaryInstructionSet(p.applicationInfo); 5455 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5456 return false; 5457 } 5458 } 5459 5460 synchronized (mInstallLock) { 5461 final String[] instructionSets = new String[] { targetInstructionSet }; 5462 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5463 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5464 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5465 } 5466 } 5467 5468 public ArraySet<String> getPackagesThatNeedDexOpt() { 5469 ArraySet<String> pkgs = null; 5470 synchronized (mPackages) { 5471 for (PackageParser.Package p : mPackages.values()) { 5472 if (DEBUG_DEXOPT) { 5473 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5474 } 5475 if (!p.mDexOptPerformed.isEmpty()) { 5476 continue; 5477 } 5478 if (pkgs == null) { 5479 pkgs = new ArraySet<String>(); 5480 } 5481 pkgs.add(p.packageName); 5482 } 5483 } 5484 return pkgs; 5485 } 5486 5487 public void shutdown() { 5488 mPackageUsage.write(true); 5489 } 5490 5491 @Override 5492 public void forceDexOpt(String packageName) { 5493 enforceSystemOrRoot("forceDexOpt"); 5494 5495 PackageParser.Package pkg; 5496 synchronized (mPackages) { 5497 pkg = mPackages.get(packageName); 5498 if (pkg == null) { 5499 throw new IllegalArgumentException("Missing package: " + packageName); 5500 } 5501 } 5502 5503 synchronized (mInstallLock) { 5504 final String[] instructionSets = new String[] { 5505 getPrimaryInstructionSet(pkg.applicationInfo) }; 5506 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5507 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5508 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5509 throw new IllegalStateException("Failed to dexopt: " + res); 5510 } 5511 } 5512 } 5513 5514 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5515 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5516 Slog.w(TAG, "Unable to update from " + oldPkg.name 5517 + " to " + newPkg.packageName 5518 + ": old package not in system partition"); 5519 return false; 5520 } else if (mPackages.get(oldPkg.name) != null) { 5521 Slog.w(TAG, "Unable to update from " + oldPkg.name 5522 + " to " + newPkg.packageName 5523 + ": old package still exists"); 5524 return false; 5525 } 5526 return true; 5527 } 5528 5529 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5530 int[] users = sUserManager.getUserIds(); 5531 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5532 if (res < 0) { 5533 return res; 5534 } 5535 for (int user : users) { 5536 if (user != 0) { 5537 res = mInstaller.createUserData(volumeUuid, packageName, 5538 UserHandle.getUid(user, uid), user, seinfo); 5539 if (res < 0) { 5540 return res; 5541 } 5542 } 5543 } 5544 return res; 5545 } 5546 5547 private int removeDataDirsLI(String volumeUuid, String packageName) { 5548 int[] users = sUserManager.getUserIds(); 5549 int res = 0; 5550 for (int user : users) { 5551 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5552 if (resInner < 0) { 5553 res = resInner; 5554 } 5555 } 5556 5557 return res; 5558 } 5559 5560 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5561 int[] users = sUserManager.getUserIds(); 5562 int res = 0; 5563 for (int user : users) { 5564 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5565 if (resInner < 0) { 5566 res = resInner; 5567 } 5568 } 5569 return res; 5570 } 5571 5572 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5573 PackageParser.Package changingLib) { 5574 if (file.path != null) { 5575 usesLibraryFiles.add(file.path); 5576 return; 5577 } 5578 PackageParser.Package p = mPackages.get(file.apk); 5579 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5580 // If we are doing this while in the middle of updating a library apk, 5581 // then we need to make sure to use that new apk for determining the 5582 // dependencies here. (We haven't yet finished committing the new apk 5583 // to the package manager state.) 5584 if (p == null || p.packageName.equals(changingLib.packageName)) { 5585 p = changingLib; 5586 } 5587 } 5588 if (p != null) { 5589 usesLibraryFiles.addAll(p.getAllCodePaths()); 5590 } 5591 } 5592 5593 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5594 PackageParser.Package changingLib) throws PackageManagerException { 5595 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5596 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5597 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5598 for (int i=0; i<N; i++) { 5599 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5600 if (file == null) { 5601 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5602 "Package " + pkg.packageName + " requires unavailable shared library " 5603 + pkg.usesLibraries.get(i) + "; failing!"); 5604 } 5605 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5606 } 5607 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5608 for (int i=0; i<N; i++) { 5609 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5610 if (file == null) { 5611 Slog.w(TAG, "Package " + pkg.packageName 5612 + " desires unavailable shared library " 5613 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5614 } else { 5615 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5616 } 5617 } 5618 N = usesLibraryFiles.size(); 5619 if (N > 0) { 5620 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5621 } else { 5622 pkg.usesLibraryFiles = null; 5623 } 5624 } 5625 } 5626 5627 private static boolean hasString(List<String> list, List<String> which) { 5628 if (list == null) { 5629 return false; 5630 } 5631 for (int i=list.size()-1; i>=0; i--) { 5632 for (int j=which.size()-1; j>=0; j--) { 5633 if (which.get(j).equals(list.get(i))) { 5634 return true; 5635 } 5636 } 5637 } 5638 return false; 5639 } 5640 5641 private void updateAllSharedLibrariesLPw() { 5642 for (PackageParser.Package pkg : mPackages.values()) { 5643 try { 5644 updateSharedLibrariesLPw(pkg, null); 5645 } catch (PackageManagerException e) { 5646 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5647 } 5648 } 5649 } 5650 5651 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5652 PackageParser.Package changingPkg) { 5653 ArrayList<PackageParser.Package> res = null; 5654 for (PackageParser.Package pkg : mPackages.values()) { 5655 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5656 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5657 if (res == null) { 5658 res = new ArrayList<PackageParser.Package>(); 5659 } 5660 res.add(pkg); 5661 try { 5662 updateSharedLibrariesLPw(pkg, changingPkg); 5663 } catch (PackageManagerException e) { 5664 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5665 } 5666 } 5667 } 5668 return res; 5669 } 5670 5671 /** 5672 * Derive the value of the {@code cpuAbiOverride} based on the provided 5673 * value and an optional stored value from the package settings. 5674 */ 5675 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5676 String cpuAbiOverride = null; 5677 5678 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5679 cpuAbiOverride = null; 5680 } else if (abiOverride != null) { 5681 cpuAbiOverride = abiOverride; 5682 } else if (settings != null) { 5683 cpuAbiOverride = settings.cpuAbiOverrideString; 5684 } 5685 5686 return cpuAbiOverride; 5687 } 5688 5689 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5690 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5691 boolean success = false; 5692 try { 5693 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5694 currentTime, user); 5695 success = true; 5696 return res; 5697 } finally { 5698 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5699 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5700 } 5701 } 5702 } 5703 5704 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5705 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5706 final File scanFile = new File(pkg.codePath); 5707 if (pkg.applicationInfo.getCodePath() == null || 5708 pkg.applicationInfo.getResourcePath() == null) { 5709 // Bail out. The resource and code paths haven't been set. 5710 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5711 "Code and resource paths haven't been set correctly"); 5712 } 5713 5714 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5715 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5716 } else { 5717 // Only allow system apps to be flagged as core apps. 5718 pkg.coreApp = false; 5719 } 5720 5721 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5722 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5723 } 5724 5725 if (mCustomResolverComponentName != null && 5726 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5727 setUpCustomResolverActivity(pkg); 5728 } 5729 5730 if (pkg.packageName.equals("android")) { 5731 synchronized (mPackages) { 5732 if (mAndroidApplication != null) { 5733 Slog.w(TAG, "*************************************************"); 5734 Slog.w(TAG, "Core android package being redefined. Skipping."); 5735 Slog.w(TAG, " file=" + scanFile); 5736 Slog.w(TAG, "*************************************************"); 5737 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5738 "Core android package being redefined. Skipping."); 5739 } 5740 5741 // Set up information for our fall-back user intent resolution activity. 5742 mPlatformPackage = pkg; 5743 pkg.mVersionCode = mSdkVersion; 5744 mAndroidApplication = pkg.applicationInfo; 5745 5746 if (!mResolverReplaced) { 5747 mResolveActivity.applicationInfo = mAndroidApplication; 5748 mResolveActivity.name = ResolverActivity.class.getName(); 5749 mResolveActivity.packageName = mAndroidApplication.packageName; 5750 mResolveActivity.processName = "system:ui"; 5751 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5752 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5753 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5754 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5755 mResolveActivity.exported = true; 5756 mResolveActivity.enabled = true; 5757 mResolveInfo.activityInfo = mResolveActivity; 5758 mResolveInfo.priority = 0; 5759 mResolveInfo.preferredOrder = 0; 5760 mResolveInfo.match = 0; 5761 mResolveComponentName = new ComponentName( 5762 mAndroidApplication.packageName, mResolveActivity.name); 5763 } 5764 } 5765 } 5766 5767 if (DEBUG_PACKAGE_SCANNING) { 5768 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5769 Log.d(TAG, "Scanning package " + pkg.packageName); 5770 } 5771 5772 if (mPackages.containsKey(pkg.packageName) 5773 || mSharedLibraries.containsKey(pkg.packageName)) { 5774 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5775 "Application package " + pkg.packageName 5776 + " already installed. Skipping duplicate."); 5777 } 5778 5779 // If we're only installing presumed-existing packages, require that the 5780 // scanned APK is both already known and at the path previously established 5781 // for it. Previously unknown packages we pick up normally, but if we have an 5782 // a priori expectation about this package's install presence, enforce it. 5783 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5784 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5785 if (known != null) { 5786 if (DEBUG_PACKAGE_SCANNING) { 5787 Log.d(TAG, "Examining " + pkg.codePath 5788 + " and requiring known paths " + known.codePathString 5789 + " & " + known.resourcePathString); 5790 } 5791 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5792 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5793 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5794 "Application package " + pkg.packageName 5795 + " found at " + pkg.applicationInfo.getCodePath() 5796 + " but expected at " + known.codePathString + "; ignoring."); 5797 } 5798 } 5799 } 5800 5801 // Initialize package source and resource directories 5802 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5803 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5804 5805 SharedUserSetting suid = null; 5806 PackageSetting pkgSetting = null; 5807 5808 if (!isSystemApp(pkg)) { 5809 // Only system apps can use these features. 5810 pkg.mOriginalPackages = null; 5811 pkg.mRealPackage = null; 5812 pkg.mAdoptPermissions = null; 5813 } 5814 5815 // writer 5816 synchronized (mPackages) { 5817 if (pkg.mSharedUserId != null) { 5818 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5819 if (suid == null) { 5820 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5821 "Creating application package " + pkg.packageName 5822 + " for shared user failed"); 5823 } 5824 if (DEBUG_PACKAGE_SCANNING) { 5825 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5826 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5827 + "): packages=" + suid.packages); 5828 } 5829 } 5830 5831 // Check if we are renaming from an original package name. 5832 PackageSetting origPackage = null; 5833 String realName = null; 5834 if (pkg.mOriginalPackages != null) { 5835 // This package may need to be renamed to a previously 5836 // installed name. Let's check on that... 5837 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5838 if (pkg.mOriginalPackages.contains(renamed)) { 5839 // This package had originally been installed as the 5840 // original name, and we have already taken care of 5841 // transitioning to the new one. Just update the new 5842 // one to continue using the old name. 5843 realName = pkg.mRealPackage; 5844 if (!pkg.packageName.equals(renamed)) { 5845 // Callers into this function may have already taken 5846 // care of renaming the package; only do it here if 5847 // it is not already done. 5848 pkg.setPackageName(renamed); 5849 } 5850 5851 } else { 5852 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5853 if ((origPackage = mSettings.peekPackageLPr( 5854 pkg.mOriginalPackages.get(i))) != null) { 5855 // We do have the package already installed under its 5856 // original name... should we use it? 5857 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5858 // New package is not compatible with original. 5859 origPackage = null; 5860 continue; 5861 } else if (origPackage.sharedUser != null) { 5862 // Make sure uid is compatible between packages. 5863 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5864 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5865 + " to " + pkg.packageName + ": old uid " 5866 + origPackage.sharedUser.name 5867 + " differs from " + pkg.mSharedUserId); 5868 origPackage = null; 5869 continue; 5870 } 5871 } else { 5872 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5873 + pkg.packageName + " to old name " + origPackage.name); 5874 } 5875 break; 5876 } 5877 } 5878 } 5879 } 5880 5881 if (mTransferedPackages.contains(pkg.packageName)) { 5882 Slog.w(TAG, "Package " + pkg.packageName 5883 + " was transferred to another, but its .apk remains"); 5884 } 5885 5886 // Just create the setting, don't add it yet. For already existing packages 5887 // the PkgSetting exists already and doesn't have to be created. 5888 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5889 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5890 pkg.applicationInfo.primaryCpuAbi, 5891 pkg.applicationInfo.secondaryCpuAbi, 5892 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5893 user, false); 5894 if (pkgSetting == null) { 5895 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5896 "Creating application package " + pkg.packageName + " failed"); 5897 } 5898 5899 if (pkgSetting.origPackage != null) { 5900 // If we are first transitioning from an original package, 5901 // fix up the new package's name now. We need to do this after 5902 // looking up the package under its new name, so getPackageLP 5903 // can take care of fiddling things correctly. 5904 pkg.setPackageName(origPackage.name); 5905 5906 // File a report about this. 5907 String msg = "New package " + pkgSetting.realName 5908 + " renamed to replace old package " + pkgSetting.name; 5909 reportSettingsProblem(Log.WARN, msg); 5910 5911 // Make a note of it. 5912 mTransferedPackages.add(origPackage.name); 5913 5914 // No longer need to retain this. 5915 pkgSetting.origPackage = null; 5916 } 5917 5918 if (realName != null) { 5919 // Make a note of it. 5920 mTransferedPackages.add(pkg.packageName); 5921 } 5922 5923 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5924 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5925 } 5926 5927 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5928 // Check all shared libraries and map to their actual file path. 5929 // We only do this here for apps not on a system dir, because those 5930 // are the only ones that can fail an install due to this. We 5931 // will take care of the system apps by updating all of their 5932 // library paths after the scan is done. 5933 updateSharedLibrariesLPw(pkg, null); 5934 } 5935 5936 if (mFoundPolicyFile) { 5937 SELinuxMMAC.assignSeinfoValue(pkg); 5938 } 5939 5940 pkg.applicationInfo.uid = pkgSetting.appId; 5941 pkg.mExtras = pkgSetting; 5942 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5943 try { 5944 verifySignaturesLP(pkgSetting, pkg); 5945 // We just determined the app is signed correctly, so bring 5946 // over the latest parsed certs. 5947 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5948 } catch (PackageManagerException e) { 5949 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5950 throw e; 5951 } 5952 // The signature has changed, but this package is in the system 5953 // image... let's recover! 5954 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5955 // However... if this package is part of a shared user, but it 5956 // doesn't match the signature of the shared user, let's fail. 5957 // What this means is that you can't change the signatures 5958 // associated with an overall shared user, which doesn't seem all 5959 // that unreasonable. 5960 if (pkgSetting.sharedUser != null) { 5961 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5962 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5963 throw new PackageManagerException( 5964 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5965 "Signature mismatch for shared user : " 5966 + pkgSetting.sharedUser); 5967 } 5968 } 5969 // File a report about this. 5970 String msg = "System package " + pkg.packageName 5971 + " signature changed; retaining data."; 5972 reportSettingsProblem(Log.WARN, msg); 5973 } 5974 } else { 5975 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5976 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5977 + pkg.packageName + " upgrade keys do not match the " 5978 + "previously installed version"); 5979 } else { 5980 // We just determined the app is signed correctly, so bring 5981 // over the latest parsed certs. 5982 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5983 } 5984 } 5985 // Verify that this new package doesn't have any content providers 5986 // that conflict with existing packages. Only do this if the 5987 // package isn't already installed, since we don't want to break 5988 // things that are installed. 5989 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5990 final int N = pkg.providers.size(); 5991 int i; 5992 for (i=0; i<N; i++) { 5993 PackageParser.Provider p = pkg.providers.get(i); 5994 if (p.info.authority != null) { 5995 String names[] = p.info.authority.split(";"); 5996 for (int j = 0; j < names.length; j++) { 5997 if (mProvidersByAuthority.containsKey(names[j])) { 5998 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5999 final String otherPackageName = 6000 ((other != null && other.getComponentName() != null) ? 6001 other.getComponentName().getPackageName() : "?"); 6002 throw new PackageManagerException( 6003 INSTALL_FAILED_CONFLICTING_PROVIDER, 6004 "Can't install because provider name " + names[j] 6005 + " (in package " + pkg.applicationInfo.packageName 6006 + ") is already used by " + otherPackageName); 6007 } 6008 } 6009 } 6010 } 6011 } 6012 6013 if (pkg.mAdoptPermissions != null) { 6014 // This package wants to adopt ownership of permissions from 6015 // another package. 6016 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6017 final String origName = pkg.mAdoptPermissions.get(i); 6018 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6019 if (orig != null) { 6020 if (verifyPackageUpdateLPr(orig, pkg)) { 6021 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6022 + pkg.packageName); 6023 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6024 } 6025 } 6026 } 6027 } 6028 } 6029 6030 final String pkgName = pkg.packageName; 6031 6032 final long scanFileTime = scanFile.lastModified(); 6033 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6034 pkg.applicationInfo.processName = fixProcessName( 6035 pkg.applicationInfo.packageName, 6036 pkg.applicationInfo.processName, 6037 pkg.applicationInfo.uid); 6038 6039 File dataPath; 6040 if (mPlatformPackage == pkg) { 6041 // The system package is special. 6042 dataPath = new File(Environment.getDataDirectory(), "system"); 6043 6044 pkg.applicationInfo.dataDir = dataPath.getPath(); 6045 6046 } else { 6047 // This is a normal package, need to make its data directory. 6048 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6049 UserHandle.USER_OWNER); 6050 6051 boolean uidError = false; 6052 if (dataPath.exists()) { 6053 int currentUid = 0; 6054 try { 6055 StructStat stat = Os.stat(dataPath.getPath()); 6056 currentUid = stat.st_uid; 6057 } catch (ErrnoException e) { 6058 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6059 } 6060 6061 // If we have mismatched owners for the data path, we have a problem. 6062 if (currentUid != pkg.applicationInfo.uid) { 6063 boolean recovered = false; 6064 if (currentUid == 0) { 6065 // The directory somehow became owned by root. Wow. 6066 // This is probably because the system was stopped while 6067 // installd was in the middle of messing with its libs 6068 // directory. Ask installd to fix that. 6069 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6070 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6071 if (ret >= 0) { 6072 recovered = true; 6073 String msg = "Package " + pkg.packageName 6074 + " unexpectedly changed to uid 0; recovered to " + 6075 + pkg.applicationInfo.uid; 6076 reportSettingsProblem(Log.WARN, msg); 6077 } 6078 } 6079 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6080 || (scanFlags&SCAN_BOOTING) != 0)) { 6081 // If this is a system app, we can at least delete its 6082 // current data so the application will still work. 6083 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6084 if (ret >= 0) { 6085 // TODO: Kill the processes first 6086 // Old data gone! 6087 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6088 ? "System package " : "Third party package "; 6089 String msg = prefix + pkg.packageName 6090 + " has changed from uid: " 6091 + currentUid + " to " 6092 + pkg.applicationInfo.uid + "; old data erased"; 6093 reportSettingsProblem(Log.WARN, msg); 6094 recovered = true; 6095 6096 // And now re-install the app. 6097 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6098 pkg.applicationInfo.seinfo); 6099 if (ret == -1) { 6100 // Ack should not happen! 6101 msg = prefix + pkg.packageName 6102 + " could not have data directory re-created after delete."; 6103 reportSettingsProblem(Log.WARN, msg); 6104 throw new PackageManagerException( 6105 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6106 } 6107 } 6108 if (!recovered) { 6109 mHasSystemUidErrors = true; 6110 } 6111 } else if (!recovered) { 6112 // If we allow this install to proceed, we will be broken. 6113 // Abort, abort! 6114 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6115 "scanPackageLI"); 6116 } 6117 if (!recovered) { 6118 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6119 + pkg.applicationInfo.uid + "/fs_" 6120 + currentUid; 6121 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6122 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6123 String msg = "Package " + pkg.packageName 6124 + " has mismatched uid: " 6125 + currentUid + " on disk, " 6126 + pkg.applicationInfo.uid + " in settings"; 6127 // writer 6128 synchronized (mPackages) { 6129 mSettings.mReadMessages.append(msg); 6130 mSettings.mReadMessages.append('\n'); 6131 uidError = true; 6132 if (!pkgSetting.uidError) { 6133 reportSettingsProblem(Log.ERROR, msg); 6134 } 6135 } 6136 } 6137 } 6138 pkg.applicationInfo.dataDir = dataPath.getPath(); 6139 if (mShouldRestoreconData) { 6140 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6141 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6142 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6143 } 6144 } else { 6145 if (DEBUG_PACKAGE_SCANNING) { 6146 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6147 Log.v(TAG, "Want this data dir: " + dataPath); 6148 } 6149 //invoke installer to do the actual installation 6150 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6151 pkg.applicationInfo.seinfo); 6152 if (ret < 0) { 6153 // Error from installer 6154 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6155 "Unable to create data dirs [errorCode=" + ret + "]"); 6156 } 6157 6158 if (dataPath.exists()) { 6159 pkg.applicationInfo.dataDir = dataPath.getPath(); 6160 } else { 6161 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6162 pkg.applicationInfo.dataDir = null; 6163 } 6164 } 6165 6166 pkgSetting.uidError = uidError; 6167 } 6168 6169 final String path = scanFile.getPath(); 6170 final String codePath = pkg.applicationInfo.getCodePath(); 6171 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6172 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6173 setBundledAppAbisAndRoots(pkg, pkgSetting); 6174 6175 // If we haven't found any native libraries for the app, check if it has 6176 // renderscript code. We'll need to force the app to 32 bit if it has 6177 // renderscript bitcode. 6178 if (pkg.applicationInfo.primaryCpuAbi == null 6179 && pkg.applicationInfo.secondaryCpuAbi == null 6180 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6181 NativeLibraryHelper.Handle handle = null; 6182 try { 6183 handle = NativeLibraryHelper.Handle.create(scanFile); 6184 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6185 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6186 } 6187 } catch (IOException ioe) { 6188 Slog.w(TAG, "Error scanning system app : " + ioe); 6189 } finally { 6190 IoUtils.closeQuietly(handle); 6191 } 6192 } 6193 6194 setNativeLibraryPaths(pkg); 6195 } else { 6196 // TODO: We can probably be smarter about this stuff. For installed apps, 6197 // we can calculate this information at install time once and for all. For 6198 // system apps, we can probably assume that this information doesn't change 6199 // after the first boot scan. As things stand, we do lots of unnecessary work. 6200 6201 // Give ourselves some initial paths; we'll come back for another 6202 // pass once we've determined ABI below. 6203 setNativeLibraryPaths(pkg); 6204 6205 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6206 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6207 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6208 6209 NativeLibraryHelper.Handle handle = null; 6210 try { 6211 handle = NativeLibraryHelper.Handle.create(scanFile); 6212 // TODO(multiArch): This can be null for apps that didn't go through the 6213 // usual installation process. We can calculate it again, like we 6214 // do during install time. 6215 // 6216 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6217 // unnecessary. 6218 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6219 6220 // Null out the abis so that they can be recalculated. 6221 pkg.applicationInfo.primaryCpuAbi = null; 6222 pkg.applicationInfo.secondaryCpuAbi = null; 6223 if (isMultiArch(pkg.applicationInfo)) { 6224 // Warn if we've set an abiOverride for multi-lib packages.. 6225 // By definition, we need to copy both 32 and 64 bit libraries for 6226 // such packages. 6227 if (pkg.cpuAbiOverride != null 6228 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6229 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6230 } 6231 6232 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6233 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6234 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6235 if (isAsec) { 6236 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6237 } else { 6238 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6239 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6240 useIsaSpecificSubdirs); 6241 } 6242 } 6243 6244 maybeThrowExceptionForMultiArchCopy( 6245 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6246 6247 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6248 if (isAsec) { 6249 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6250 } else { 6251 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6252 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6253 useIsaSpecificSubdirs); 6254 } 6255 } 6256 6257 maybeThrowExceptionForMultiArchCopy( 6258 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6259 6260 if (abi64 >= 0) { 6261 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6262 } 6263 6264 if (abi32 >= 0) { 6265 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6266 if (abi64 >= 0) { 6267 pkg.applicationInfo.secondaryCpuAbi = abi; 6268 } else { 6269 pkg.applicationInfo.primaryCpuAbi = abi; 6270 } 6271 } 6272 } else { 6273 String[] abiList = (cpuAbiOverride != null) ? 6274 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6275 6276 // Enable gross and lame hacks for apps that are built with old 6277 // SDK tools. We must scan their APKs for renderscript bitcode and 6278 // not launch them if it's present. Don't bother checking on devices 6279 // that don't have 64 bit support. 6280 boolean needsRenderScriptOverride = false; 6281 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6282 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6283 abiList = Build.SUPPORTED_32_BIT_ABIS; 6284 needsRenderScriptOverride = true; 6285 } 6286 6287 final int copyRet; 6288 if (isAsec) { 6289 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6290 } else { 6291 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6292 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6293 } 6294 6295 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6296 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6297 "Error unpackaging native libs for app, errorCode=" + copyRet); 6298 } 6299 6300 if (copyRet >= 0) { 6301 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6302 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6303 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6304 } else if (needsRenderScriptOverride) { 6305 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6306 } 6307 } 6308 } catch (IOException ioe) { 6309 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6310 } finally { 6311 IoUtils.closeQuietly(handle); 6312 } 6313 6314 // Now that we've calculated the ABIs and determined if it's an internal app, 6315 // we will go ahead and populate the nativeLibraryPath. 6316 setNativeLibraryPaths(pkg); 6317 6318 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6319 final int[] userIds = sUserManager.getUserIds(); 6320 synchronized (mInstallLock) { 6321 // Create a native library symlink only if we have native libraries 6322 // and if the native libraries are 32 bit libraries. We do not provide 6323 // this symlink for 64 bit libraries. 6324 if (pkg.applicationInfo.primaryCpuAbi != null && 6325 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6326 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6327 for (int userId : userIds) { 6328 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6329 nativeLibPath, userId) < 0) { 6330 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6331 "Failed linking native library dir (user=" + userId + ")"); 6332 } 6333 } 6334 } 6335 } 6336 } 6337 6338 // This is a special case for the "system" package, where the ABI is 6339 // dictated by the zygote configuration (and init.rc). We should keep track 6340 // of this ABI so that we can deal with "normal" applications that run under 6341 // the same UID correctly. 6342 if (mPlatformPackage == pkg) { 6343 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6344 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6345 } 6346 6347 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6348 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6349 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6350 // Copy the derived override back to the parsed package, so that we can 6351 // update the package settings accordingly. 6352 pkg.cpuAbiOverride = cpuAbiOverride; 6353 6354 if (DEBUG_ABI_SELECTION) { 6355 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6356 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6357 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6358 } 6359 6360 // Push the derived path down into PackageSettings so we know what to 6361 // clean up at uninstall time. 6362 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6363 6364 if (DEBUG_ABI_SELECTION) { 6365 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6366 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6367 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6368 } 6369 6370 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6371 // We don't do this here during boot because we can do it all 6372 // at once after scanning all existing packages. 6373 // 6374 // We also do this *before* we perform dexopt on this package, so that 6375 // we can avoid redundant dexopts, and also to make sure we've got the 6376 // code and package path correct. 6377 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6378 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6379 } 6380 6381 if ((scanFlags & SCAN_NO_DEX) == 0) { 6382 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6383 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6384 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6385 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6386 } 6387 } 6388 if (mFactoryTest && pkg.requestedPermissions.contains( 6389 android.Manifest.permission.FACTORY_TEST)) { 6390 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6391 } 6392 6393 ArrayList<PackageParser.Package> clientLibPkgs = null; 6394 6395 // writer 6396 synchronized (mPackages) { 6397 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6398 // Only system apps can add new shared libraries. 6399 if (pkg.libraryNames != null) { 6400 for (int i=0; i<pkg.libraryNames.size(); i++) { 6401 String name = pkg.libraryNames.get(i); 6402 boolean allowed = false; 6403 if (pkg.isUpdatedSystemApp()) { 6404 // New library entries can only be added through the 6405 // system image. This is important to get rid of a lot 6406 // of nasty edge cases: for example if we allowed a non- 6407 // system update of the app to add a library, then uninstalling 6408 // the update would make the library go away, and assumptions 6409 // we made such as through app install filtering would now 6410 // have allowed apps on the device which aren't compatible 6411 // with it. Better to just have the restriction here, be 6412 // conservative, and create many fewer cases that can negatively 6413 // impact the user experience. 6414 final PackageSetting sysPs = mSettings 6415 .getDisabledSystemPkgLPr(pkg.packageName); 6416 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6417 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6418 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6419 allowed = true; 6420 allowed = true; 6421 break; 6422 } 6423 } 6424 } 6425 } else { 6426 allowed = true; 6427 } 6428 if (allowed) { 6429 if (!mSharedLibraries.containsKey(name)) { 6430 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6431 } else if (!name.equals(pkg.packageName)) { 6432 Slog.w(TAG, "Package " + pkg.packageName + " library " 6433 + name + " already exists; skipping"); 6434 } 6435 } else { 6436 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6437 + name + " that is not declared on system image; skipping"); 6438 } 6439 } 6440 if ((scanFlags&SCAN_BOOTING) == 0) { 6441 // If we are not booting, we need to update any applications 6442 // that are clients of our shared library. If we are booting, 6443 // this will all be done once the scan is complete. 6444 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6445 } 6446 } 6447 } 6448 } 6449 6450 // We also need to dexopt any apps that are dependent on this library. Note that 6451 // if these fail, we should abort the install since installing the library will 6452 // result in some apps being broken. 6453 if (clientLibPkgs != null) { 6454 if ((scanFlags & SCAN_NO_DEX) == 0) { 6455 for (int i = 0; i < clientLibPkgs.size(); i++) { 6456 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6457 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6458 null /* instruction sets */, forceDex, 6459 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6460 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6461 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6462 "scanPackageLI failed to dexopt clientLibPkgs"); 6463 } 6464 } 6465 } 6466 } 6467 6468 // Request the ActivityManager to kill the process(only for existing packages) 6469 // so that we do not end up in a confused state while the user is still using the older 6470 // version of the application while the new one gets installed. 6471 if ((scanFlags & SCAN_REPLACING) != 0) { 6472 killApplication(pkg.applicationInfo.packageName, 6473 pkg.applicationInfo.uid, "update pkg"); 6474 } 6475 6476 // Also need to kill any apps that are dependent on the library. 6477 if (clientLibPkgs != null) { 6478 for (int i=0; i<clientLibPkgs.size(); i++) { 6479 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6480 killApplication(clientPkg.applicationInfo.packageName, 6481 clientPkg.applicationInfo.uid, "update lib"); 6482 } 6483 } 6484 6485 // writer 6486 synchronized (mPackages) { 6487 // We don't expect installation to fail beyond this point 6488 6489 // Add the new setting to mSettings 6490 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6491 // Add the new setting to mPackages 6492 mPackages.put(pkg.applicationInfo.packageName, pkg); 6493 // Make sure we don't accidentally delete its data. 6494 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6495 while (iter.hasNext()) { 6496 PackageCleanItem item = iter.next(); 6497 if (pkgName.equals(item.packageName)) { 6498 iter.remove(); 6499 } 6500 } 6501 6502 // Take care of first install / last update times. 6503 if (currentTime != 0) { 6504 if (pkgSetting.firstInstallTime == 0) { 6505 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6506 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6507 pkgSetting.lastUpdateTime = currentTime; 6508 } 6509 } else if (pkgSetting.firstInstallTime == 0) { 6510 // We need *something*. Take time time stamp of the file. 6511 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6512 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6513 if (scanFileTime != pkgSetting.timeStamp) { 6514 // A package on the system image has changed; consider this 6515 // to be an update. 6516 pkgSetting.lastUpdateTime = scanFileTime; 6517 } 6518 } 6519 6520 // Add the package's KeySets to the global KeySetManagerService 6521 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6522 try { 6523 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6524 if (pkg.mKeySetMapping != null) { 6525 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6526 if (pkg.mUpgradeKeySets != null) { 6527 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6528 } 6529 } 6530 } catch (NullPointerException e) { 6531 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6532 } catch (IllegalArgumentException e) { 6533 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6534 } 6535 6536 int N = pkg.providers.size(); 6537 StringBuilder r = null; 6538 int i; 6539 for (i=0; i<N; i++) { 6540 PackageParser.Provider p = pkg.providers.get(i); 6541 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6542 p.info.processName, pkg.applicationInfo.uid); 6543 mProviders.addProvider(p); 6544 p.syncable = p.info.isSyncable; 6545 if (p.info.authority != null) { 6546 String names[] = p.info.authority.split(";"); 6547 p.info.authority = null; 6548 for (int j = 0; j < names.length; j++) { 6549 if (j == 1 && p.syncable) { 6550 // We only want the first authority for a provider to possibly be 6551 // syncable, so if we already added this provider using a different 6552 // authority clear the syncable flag. We copy the provider before 6553 // changing it because the mProviders object contains a reference 6554 // to a provider that we don't want to change. 6555 // Only do this for the second authority since the resulting provider 6556 // object can be the same for all future authorities for this provider. 6557 p = new PackageParser.Provider(p); 6558 p.syncable = false; 6559 } 6560 if (!mProvidersByAuthority.containsKey(names[j])) { 6561 mProvidersByAuthority.put(names[j], p); 6562 if (p.info.authority == null) { 6563 p.info.authority = names[j]; 6564 } else { 6565 p.info.authority = p.info.authority + ";" + names[j]; 6566 } 6567 if (DEBUG_PACKAGE_SCANNING) { 6568 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6569 Log.d(TAG, "Registered content provider: " + names[j] 6570 + ", className = " + p.info.name + ", isSyncable = " 6571 + p.info.isSyncable); 6572 } 6573 } else { 6574 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6575 Slog.w(TAG, "Skipping provider name " + names[j] + 6576 " (in package " + pkg.applicationInfo.packageName + 6577 "): name already used by " 6578 + ((other != null && other.getComponentName() != null) 6579 ? other.getComponentName().getPackageName() : "?")); 6580 } 6581 } 6582 } 6583 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6584 if (r == null) { 6585 r = new StringBuilder(256); 6586 } else { 6587 r.append(' '); 6588 } 6589 r.append(p.info.name); 6590 } 6591 } 6592 if (r != null) { 6593 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6594 } 6595 6596 N = pkg.services.size(); 6597 r = null; 6598 for (i=0; i<N; i++) { 6599 PackageParser.Service s = pkg.services.get(i); 6600 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6601 s.info.processName, pkg.applicationInfo.uid); 6602 mServices.addService(s); 6603 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6604 if (r == null) { 6605 r = new StringBuilder(256); 6606 } else { 6607 r.append(' '); 6608 } 6609 r.append(s.info.name); 6610 } 6611 } 6612 if (r != null) { 6613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6614 } 6615 6616 N = pkg.receivers.size(); 6617 r = null; 6618 for (i=0; i<N; i++) { 6619 PackageParser.Activity a = pkg.receivers.get(i); 6620 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6621 a.info.processName, pkg.applicationInfo.uid); 6622 mReceivers.addActivity(a, "receiver"); 6623 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6624 if (r == null) { 6625 r = new StringBuilder(256); 6626 } else { 6627 r.append(' '); 6628 } 6629 r.append(a.info.name); 6630 } 6631 } 6632 if (r != null) { 6633 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6634 } 6635 6636 N = pkg.activities.size(); 6637 r = null; 6638 for (i=0; i<N; i++) { 6639 PackageParser.Activity a = pkg.activities.get(i); 6640 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6641 a.info.processName, pkg.applicationInfo.uid); 6642 mActivities.addActivity(a, "activity"); 6643 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6644 if (r == null) { 6645 r = new StringBuilder(256); 6646 } else { 6647 r.append(' '); 6648 } 6649 r.append(a.info.name); 6650 } 6651 } 6652 if (r != null) { 6653 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6654 } 6655 6656 N = pkg.permissionGroups.size(); 6657 r = null; 6658 for (i=0; i<N; i++) { 6659 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6660 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6661 if (cur == null) { 6662 mPermissionGroups.put(pg.info.name, pg); 6663 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6664 if (r == null) { 6665 r = new StringBuilder(256); 6666 } else { 6667 r.append(' '); 6668 } 6669 r.append(pg.info.name); 6670 } 6671 } else { 6672 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6673 + pg.info.packageName + " ignored: original from " 6674 + cur.info.packageName); 6675 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6676 if (r == null) { 6677 r = new StringBuilder(256); 6678 } else { 6679 r.append(' '); 6680 } 6681 r.append("DUP:"); 6682 r.append(pg.info.name); 6683 } 6684 } 6685 } 6686 if (r != null) { 6687 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6688 } 6689 6690 N = pkg.permissions.size(); 6691 r = null; 6692 for (i=0; i<N; i++) { 6693 PackageParser.Permission p = pkg.permissions.get(i); 6694 6695 // Now that permission groups have a special meaning, we ignore permission 6696 // groups for legacy apps to prevent unexpected behavior. In particular, 6697 // permissions for one app being granted to someone just becuase they happen 6698 // to be in a group defined by another app (before this had no implications). 6699 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6700 p.group = mPermissionGroups.get(p.info.group); 6701 // Warn for a permission in an unknown group. 6702 if (p.info.group != null && p.group == null) { 6703 Slog.w(TAG, "Permission " + p.info.name + " from package " 6704 + p.info.packageName + " in an unknown group " + p.info.group); 6705 } 6706 } 6707 6708 ArrayMap<String, BasePermission> permissionMap = 6709 p.tree ? mSettings.mPermissionTrees 6710 : mSettings.mPermissions; 6711 BasePermission bp = permissionMap.get(p.info.name); 6712 6713 // Allow system apps to redefine non-system permissions 6714 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6715 final boolean currentOwnerIsSystem = (bp.perm != null 6716 && isSystemApp(bp.perm.owner)); 6717 if (isSystemApp(p.owner)) { 6718 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6719 // It's a built-in permission and no owner, take ownership now 6720 bp.packageSetting = pkgSetting; 6721 bp.perm = p; 6722 bp.uid = pkg.applicationInfo.uid; 6723 bp.sourcePackage = p.info.packageName; 6724 } else if (!currentOwnerIsSystem) { 6725 String msg = "New decl " + p.owner + " of permission " 6726 + p.info.name + " is system; overriding " + bp.sourcePackage; 6727 reportSettingsProblem(Log.WARN, msg); 6728 bp = null; 6729 } 6730 } 6731 } 6732 6733 if (bp == null) { 6734 bp = new BasePermission(p.info.name, p.info.packageName, 6735 BasePermission.TYPE_NORMAL); 6736 permissionMap.put(p.info.name, bp); 6737 } 6738 6739 if (bp.perm == null) { 6740 if (bp.sourcePackage == null 6741 || bp.sourcePackage.equals(p.info.packageName)) { 6742 BasePermission tree = findPermissionTreeLP(p.info.name); 6743 if (tree == null 6744 || tree.sourcePackage.equals(p.info.packageName)) { 6745 bp.packageSetting = pkgSetting; 6746 bp.perm = p; 6747 bp.uid = pkg.applicationInfo.uid; 6748 bp.sourcePackage = p.info.packageName; 6749 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6750 if (r == null) { 6751 r = new StringBuilder(256); 6752 } else { 6753 r.append(' '); 6754 } 6755 r.append(p.info.name); 6756 } 6757 } else { 6758 Slog.w(TAG, "Permission " + p.info.name + " from package " 6759 + p.info.packageName + " ignored: base tree " 6760 + tree.name + " is from package " 6761 + tree.sourcePackage); 6762 } 6763 } else { 6764 Slog.w(TAG, "Permission " + p.info.name + " from package " 6765 + p.info.packageName + " ignored: original from " 6766 + bp.sourcePackage); 6767 } 6768 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6769 if (r == null) { 6770 r = new StringBuilder(256); 6771 } else { 6772 r.append(' '); 6773 } 6774 r.append("DUP:"); 6775 r.append(p.info.name); 6776 } 6777 if (bp.perm == p) { 6778 bp.protectionLevel = p.info.protectionLevel; 6779 } 6780 } 6781 6782 if (r != null) { 6783 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6784 } 6785 6786 N = pkg.instrumentation.size(); 6787 r = null; 6788 for (i=0; i<N; i++) { 6789 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6790 a.info.packageName = pkg.applicationInfo.packageName; 6791 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6792 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6793 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6794 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6795 a.info.dataDir = pkg.applicationInfo.dataDir; 6796 6797 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6798 // need other information about the application, like the ABI and what not ? 6799 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6800 mInstrumentation.put(a.getComponentName(), a); 6801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6802 if (r == null) { 6803 r = new StringBuilder(256); 6804 } else { 6805 r.append(' '); 6806 } 6807 r.append(a.info.name); 6808 } 6809 } 6810 if (r != null) { 6811 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6812 } 6813 6814 if (pkg.protectedBroadcasts != null) { 6815 N = pkg.protectedBroadcasts.size(); 6816 for (i=0; i<N; i++) { 6817 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6818 } 6819 } 6820 6821 pkgSetting.setTimeStamp(scanFileTime); 6822 6823 // Create idmap files for pairs of (packages, overlay packages). 6824 // Note: "android", ie framework-res.apk, is handled by native layers. 6825 if (pkg.mOverlayTarget != null) { 6826 // This is an overlay package. 6827 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6828 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6829 mOverlays.put(pkg.mOverlayTarget, 6830 new ArrayMap<String, PackageParser.Package>()); 6831 } 6832 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6833 map.put(pkg.packageName, pkg); 6834 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6835 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6836 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6837 "scanPackageLI failed to createIdmap"); 6838 } 6839 } 6840 } else if (mOverlays.containsKey(pkg.packageName) && 6841 !pkg.packageName.equals("android")) { 6842 // This is a regular package, with one or more known overlay packages. 6843 createIdmapsForPackageLI(pkg); 6844 } 6845 } 6846 6847 return pkg; 6848 } 6849 6850 /** 6851 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6852 * i.e, so that all packages can be run inside a single process if required. 6853 * 6854 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6855 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6856 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6857 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6858 * updating a package that belongs to a shared user. 6859 * 6860 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6861 * adds unnecessary complexity. 6862 */ 6863 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6864 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6865 String requiredInstructionSet = null; 6866 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6867 requiredInstructionSet = VMRuntime.getInstructionSet( 6868 scannedPackage.applicationInfo.primaryCpuAbi); 6869 } 6870 6871 PackageSetting requirer = null; 6872 for (PackageSetting ps : packagesForUser) { 6873 // If packagesForUser contains scannedPackage, we skip it. This will happen 6874 // when scannedPackage is an update of an existing package. Without this check, 6875 // we will never be able to change the ABI of any package belonging to a shared 6876 // user, even if it's compatible with other packages. 6877 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6878 if (ps.primaryCpuAbiString == null) { 6879 continue; 6880 } 6881 6882 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6883 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6884 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6885 // this but there's not much we can do. 6886 String errorMessage = "Instruction set mismatch, " 6887 + ((requirer == null) ? "[caller]" : requirer) 6888 + " requires " + requiredInstructionSet + " whereas " + ps 6889 + " requires " + instructionSet; 6890 Slog.w(TAG, errorMessage); 6891 } 6892 6893 if (requiredInstructionSet == null) { 6894 requiredInstructionSet = instructionSet; 6895 requirer = ps; 6896 } 6897 } 6898 } 6899 6900 if (requiredInstructionSet != null) { 6901 String adjustedAbi; 6902 if (requirer != null) { 6903 // requirer != null implies that either scannedPackage was null or that scannedPackage 6904 // did not require an ABI, in which case we have to adjust scannedPackage to match 6905 // the ABI of the set (which is the same as requirer's ABI) 6906 adjustedAbi = requirer.primaryCpuAbiString; 6907 if (scannedPackage != null) { 6908 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6909 } 6910 } else { 6911 // requirer == null implies that we're updating all ABIs in the set to 6912 // match scannedPackage. 6913 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6914 } 6915 6916 for (PackageSetting ps : packagesForUser) { 6917 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6918 if (ps.primaryCpuAbiString != null) { 6919 continue; 6920 } 6921 6922 ps.primaryCpuAbiString = adjustedAbi; 6923 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6924 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6925 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6926 6927 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6928 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6929 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6930 ps.primaryCpuAbiString = null; 6931 ps.pkg.applicationInfo.primaryCpuAbi = null; 6932 return; 6933 } else { 6934 mInstaller.rmdex(ps.codePathString, 6935 getDexCodeInstructionSet(getPreferredInstructionSet())); 6936 } 6937 } 6938 } 6939 } 6940 } 6941 } 6942 6943 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6944 synchronized (mPackages) { 6945 mResolverReplaced = true; 6946 // Set up information for custom user intent resolution activity. 6947 mResolveActivity.applicationInfo = pkg.applicationInfo; 6948 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6949 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6950 mResolveActivity.processName = pkg.applicationInfo.packageName; 6951 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6952 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6953 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6954 mResolveActivity.theme = 0; 6955 mResolveActivity.exported = true; 6956 mResolveActivity.enabled = true; 6957 mResolveInfo.activityInfo = mResolveActivity; 6958 mResolveInfo.priority = 0; 6959 mResolveInfo.preferredOrder = 0; 6960 mResolveInfo.match = 0; 6961 mResolveComponentName = mCustomResolverComponentName; 6962 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6963 mResolveComponentName); 6964 } 6965 } 6966 6967 private static String calculateBundledApkRoot(final String codePathString) { 6968 final File codePath = new File(codePathString); 6969 final File codeRoot; 6970 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6971 codeRoot = Environment.getRootDirectory(); 6972 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6973 codeRoot = Environment.getOemDirectory(); 6974 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6975 codeRoot = Environment.getVendorDirectory(); 6976 } else { 6977 // Unrecognized code path; take its top real segment as the apk root: 6978 // e.g. /something/app/blah.apk => /something 6979 try { 6980 File f = codePath.getCanonicalFile(); 6981 File parent = f.getParentFile(); // non-null because codePath is a file 6982 File tmp; 6983 while ((tmp = parent.getParentFile()) != null) { 6984 f = parent; 6985 parent = tmp; 6986 } 6987 codeRoot = f; 6988 Slog.w(TAG, "Unrecognized code path " 6989 + codePath + " - using " + codeRoot); 6990 } catch (IOException e) { 6991 // Can't canonicalize the code path -- shenanigans? 6992 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6993 return Environment.getRootDirectory().getPath(); 6994 } 6995 } 6996 return codeRoot.getPath(); 6997 } 6998 6999 /** 7000 * Derive and set the location of native libraries for the given package, 7001 * which varies depending on where and how the package was installed. 7002 */ 7003 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7004 final ApplicationInfo info = pkg.applicationInfo; 7005 final String codePath = pkg.codePath; 7006 final File codeFile = new File(codePath); 7007 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7008 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7009 7010 info.nativeLibraryRootDir = null; 7011 info.nativeLibraryRootRequiresIsa = false; 7012 info.nativeLibraryDir = null; 7013 info.secondaryNativeLibraryDir = null; 7014 7015 if (isApkFile(codeFile)) { 7016 // Monolithic install 7017 if (bundledApp) { 7018 // If "/system/lib64/apkname" exists, assume that is the per-package 7019 // native library directory to use; otherwise use "/system/lib/apkname". 7020 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7021 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7022 getPrimaryInstructionSet(info)); 7023 7024 // This is a bundled system app so choose the path based on the ABI. 7025 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7026 // is just the default path. 7027 final String apkName = deriveCodePathName(codePath); 7028 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7029 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7030 apkName).getAbsolutePath(); 7031 7032 if (info.secondaryCpuAbi != null) { 7033 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7034 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7035 secondaryLibDir, apkName).getAbsolutePath(); 7036 } 7037 } else if (asecApp) { 7038 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7039 .getAbsolutePath(); 7040 } else { 7041 final String apkName = deriveCodePathName(codePath); 7042 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7043 .getAbsolutePath(); 7044 } 7045 7046 info.nativeLibraryRootRequiresIsa = false; 7047 info.nativeLibraryDir = info.nativeLibraryRootDir; 7048 } else { 7049 // Cluster install 7050 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7051 info.nativeLibraryRootRequiresIsa = true; 7052 7053 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7054 getPrimaryInstructionSet(info)).getAbsolutePath(); 7055 7056 if (info.secondaryCpuAbi != null) { 7057 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7058 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7059 } 7060 } 7061 } 7062 7063 /** 7064 * Calculate the abis and roots for a bundled app. These can uniquely 7065 * be determined from the contents of the system partition, i.e whether 7066 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7067 * of this information, and instead assume that the system was built 7068 * sensibly. 7069 */ 7070 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7071 PackageSetting pkgSetting) { 7072 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7073 7074 // If "/system/lib64/apkname" exists, assume that is the per-package 7075 // native library directory to use; otherwise use "/system/lib/apkname". 7076 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7077 setBundledAppAbi(pkg, apkRoot, apkName); 7078 // pkgSetting might be null during rescan following uninstall of updates 7079 // to a bundled app, so accommodate that possibility. The settings in 7080 // that case will be established later from the parsed package. 7081 // 7082 // If the settings aren't null, sync them up with what we've just derived. 7083 // note that apkRoot isn't stored in the package settings. 7084 if (pkgSetting != null) { 7085 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7086 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7087 } 7088 } 7089 7090 /** 7091 * Deduces the ABI of a bundled app and sets the relevant fields on the 7092 * parsed pkg object. 7093 * 7094 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7095 * under which system libraries are installed. 7096 * @param apkName the name of the installed package. 7097 */ 7098 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7099 final File codeFile = new File(pkg.codePath); 7100 7101 final boolean has64BitLibs; 7102 final boolean has32BitLibs; 7103 if (isApkFile(codeFile)) { 7104 // Monolithic install 7105 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7106 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7107 } else { 7108 // Cluster install 7109 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7110 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7111 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7112 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7113 has64BitLibs = (new File(rootDir, isa)).exists(); 7114 } else { 7115 has64BitLibs = false; 7116 } 7117 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7118 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7119 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7120 has32BitLibs = (new File(rootDir, isa)).exists(); 7121 } else { 7122 has32BitLibs = false; 7123 } 7124 } 7125 7126 if (has64BitLibs && !has32BitLibs) { 7127 // The package has 64 bit libs, but not 32 bit libs. Its primary 7128 // ABI should be 64 bit. We can safely assume here that the bundled 7129 // native libraries correspond to the most preferred ABI in the list. 7130 7131 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7132 pkg.applicationInfo.secondaryCpuAbi = null; 7133 } else if (has32BitLibs && !has64BitLibs) { 7134 // The package has 32 bit libs but not 64 bit libs. Its primary 7135 // ABI should be 32 bit. 7136 7137 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7138 pkg.applicationInfo.secondaryCpuAbi = null; 7139 } else if (has32BitLibs && has64BitLibs) { 7140 // The application has both 64 and 32 bit bundled libraries. We check 7141 // here that the app declares multiArch support, and warn if it doesn't. 7142 // 7143 // We will be lenient here and record both ABIs. The primary will be the 7144 // ABI that's higher on the list, i.e, a device that's configured to prefer 7145 // 64 bit apps will see a 64 bit primary ABI, 7146 7147 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7148 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7149 } 7150 7151 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7152 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7153 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7154 } else { 7155 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7156 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7157 } 7158 } else { 7159 pkg.applicationInfo.primaryCpuAbi = null; 7160 pkg.applicationInfo.secondaryCpuAbi = null; 7161 } 7162 } 7163 7164 private void killApplication(String pkgName, int appId, String reason) { 7165 // Request the ActivityManager to kill the process(only for existing packages) 7166 // so that we do not end up in a confused state while the user is still using the older 7167 // version of the application while the new one gets installed. 7168 IActivityManager am = ActivityManagerNative.getDefault(); 7169 if (am != null) { 7170 try { 7171 am.killApplicationWithAppId(pkgName, appId, reason); 7172 } catch (RemoteException e) { 7173 } 7174 } 7175 } 7176 7177 void removePackageLI(PackageSetting ps, boolean chatty) { 7178 if (DEBUG_INSTALL) { 7179 if (chatty) 7180 Log.d(TAG, "Removing package " + ps.name); 7181 } 7182 7183 // writer 7184 synchronized (mPackages) { 7185 mPackages.remove(ps.name); 7186 final PackageParser.Package pkg = ps.pkg; 7187 if (pkg != null) { 7188 cleanPackageDataStructuresLILPw(pkg, chatty); 7189 } 7190 } 7191 } 7192 7193 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7194 if (DEBUG_INSTALL) { 7195 if (chatty) 7196 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7197 } 7198 7199 // writer 7200 synchronized (mPackages) { 7201 mPackages.remove(pkg.applicationInfo.packageName); 7202 cleanPackageDataStructuresLILPw(pkg, chatty); 7203 } 7204 } 7205 7206 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7207 int N = pkg.providers.size(); 7208 StringBuilder r = null; 7209 int i; 7210 for (i=0; i<N; i++) { 7211 PackageParser.Provider p = pkg.providers.get(i); 7212 mProviders.removeProvider(p); 7213 if (p.info.authority == null) { 7214 7215 /* There was another ContentProvider with this authority when 7216 * this app was installed so this authority is null, 7217 * Ignore it as we don't have to unregister the provider. 7218 */ 7219 continue; 7220 } 7221 String names[] = p.info.authority.split(";"); 7222 for (int j = 0; j < names.length; j++) { 7223 if (mProvidersByAuthority.get(names[j]) == p) { 7224 mProvidersByAuthority.remove(names[j]); 7225 if (DEBUG_REMOVE) { 7226 if (chatty) 7227 Log.d(TAG, "Unregistered content provider: " + names[j] 7228 + ", className = " + p.info.name + ", isSyncable = " 7229 + p.info.isSyncable); 7230 } 7231 } 7232 } 7233 if (DEBUG_REMOVE && chatty) { 7234 if (r == null) { 7235 r = new StringBuilder(256); 7236 } else { 7237 r.append(' '); 7238 } 7239 r.append(p.info.name); 7240 } 7241 } 7242 if (r != null) { 7243 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7244 } 7245 7246 N = pkg.services.size(); 7247 r = null; 7248 for (i=0; i<N; i++) { 7249 PackageParser.Service s = pkg.services.get(i); 7250 mServices.removeService(s); 7251 if (chatty) { 7252 if (r == null) { 7253 r = new StringBuilder(256); 7254 } else { 7255 r.append(' '); 7256 } 7257 r.append(s.info.name); 7258 } 7259 } 7260 if (r != null) { 7261 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7262 } 7263 7264 N = pkg.receivers.size(); 7265 r = null; 7266 for (i=0; i<N; i++) { 7267 PackageParser.Activity a = pkg.receivers.get(i); 7268 mReceivers.removeActivity(a, "receiver"); 7269 if (DEBUG_REMOVE && chatty) { 7270 if (r == null) { 7271 r = new StringBuilder(256); 7272 } else { 7273 r.append(' '); 7274 } 7275 r.append(a.info.name); 7276 } 7277 } 7278 if (r != null) { 7279 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7280 } 7281 7282 N = pkg.activities.size(); 7283 r = null; 7284 for (i=0; i<N; i++) { 7285 PackageParser.Activity a = pkg.activities.get(i); 7286 mActivities.removeActivity(a, "activity"); 7287 if (DEBUG_REMOVE && chatty) { 7288 if (r == null) { 7289 r = new StringBuilder(256); 7290 } else { 7291 r.append(' '); 7292 } 7293 r.append(a.info.name); 7294 } 7295 } 7296 if (r != null) { 7297 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7298 } 7299 7300 N = pkg.permissions.size(); 7301 r = null; 7302 for (i=0; i<N; i++) { 7303 PackageParser.Permission p = pkg.permissions.get(i); 7304 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7305 if (bp == null) { 7306 bp = mSettings.mPermissionTrees.get(p.info.name); 7307 } 7308 if (bp != null && bp.perm == p) { 7309 bp.perm = null; 7310 if (DEBUG_REMOVE && chatty) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append(p.info.name); 7317 } 7318 } 7319 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7320 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7321 if (appOpPerms != null) { 7322 appOpPerms.remove(pkg.packageName); 7323 } 7324 } 7325 } 7326 if (r != null) { 7327 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7328 } 7329 7330 N = pkg.requestedPermissions.size(); 7331 r = null; 7332 for (i=0; i<N; i++) { 7333 String perm = pkg.requestedPermissions.get(i); 7334 BasePermission bp = mSettings.mPermissions.get(perm); 7335 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7336 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7337 if (appOpPerms != null) { 7338 appOpPerms.remove(pkg.packageName); 7339 if (appOpPerms.isEmpty()) { 7340 mAppOpPermissionPackages.remove(perm); 7341 } 7342 } 7343 } 7344 } 7345 if (r != null) { 7346 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7347 } 7348 7349 N = pkg.instrumentation.size(); 7350 r = null; 7351 for (i=0; i<N; i++) { 7352 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7353 mInstrumentation.remove(a.getComponentName()); 7354 if (DEBUG_REMOVE && chatty) { 7355 if (r == null) { 7356 r = new StringBuilder(256); 7357 } else { 7358 r.append(' '); 7359 } 7360 r.append(a.info.name); 7361 } 7362 } 7363 if (r != null) { 7364 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7365 } 7366 7367 r = null; 7368 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7369 // Only system apps can hold shared libraries. 7370 if (pkg.libraryNames != null) { 7371 for (i=0; i<pkg.libraryNames.size(); i++) { 7372 String name = pkg.libraryNames.get(i); 7373 SharedLibraryEntry cur = mSharedLibraries.get(name); 7374 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7375 mSharedLibraries.remove(name); 7376 if (DEBUG_REMOVE && chatty) { 7377 if (r == null) { 7378 r = new StringBuilder(256); 7379 } else { 7380 r.append(' '); 7381 } 7382 r.append(name); 7383 } 7384 } 7385 } 7386 } 7387 } 7388 if (r != null) { 7389 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7390 } 7391 } 7392 7393 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7394 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7395 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7396 return true; 7397 } 7398 } 7399 return false; 7400 } 7401 7402 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7403 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7404 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7405 7406 private void updatePermissionsLPw(String changingPkg, 7407 PackageParser.Package pkgInfo, int flags) { 7408 // Make sure there are no dangling permission trees. 7409 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7410 while (it.hasNext()) { 7411 final BasePermission bp = it.next(); 7412 if (bp.packageSetting == null) { 7413 // We may not yet have parsed the package, so just see if 7414 // we still know about its settings. 7415 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7416 } 7417 if (bp.packageSetting == null) { 7418 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7419 + " from package " + bp.sourcePackage); 7420 it.remove(); 7421 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7422 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7423 Slog.i(TAG, "Removing old permission tree: " + bp.name 7424 + " from package " + bp.sourcePackage); 7425 flags |= UPDATE_PERMISSIONS_ALL; 7426 it.remove(); 7427 } 7428 } 7429 } 7430 7431 // Make sure all dynamic permissions have been assigned to a package, 7432 // and make sure there are no dangling permissions. 7433 it = mSettings.mPermissions.values().iterator(); 7434 while (it.hasNext()) { 7435 final BasePermission bp = it.next(); 7436 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7437 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7438 + bp.name + " pkg=" + bp.sourcePackage 7439 + " info=" + bp.pendingInfo); 7440 if (bp.packageSetting == null && bp.pendingInfo != null) { 7441 final BasePermission tree = findPermissionTreeLP(bp.name); 7442 if (tree != null && tree.perm != null) { 7443 bp.packageSetting = tree.packageSetting; 7444 bp.perm = new PackageParser.Permission(tree.perm.owner, 7445 new PermissionInfo(bp.pendingInfo)); 7446 bp.perm.info.packageName = tree.perm.info.packageName; 7447 bp.perm.info.name = bp.name; 7448 bp.uid = tree.uid; 7449 } 7450 } 7451 } 7452 if (bp.packageSetting == null) { 7453 // We may not yet have parsed the package, so just see if 7454 // we still know about its settings. 7455 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7456 } 7457 if (bp.packageSetting == null) { 7458 Slog.w(TAG, "Removing dangling permission: " + bp.name 7459 + " from package " + bp.sourcePackage); 7460 it.remove(); 7461 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7462 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7463 Slog.i(TAG, "Removing old permission: " + bp.name 7464 + " from package " + bp.sourcePackage); 7465 flags |= UPDATE_PERMISSIONS_ALL; 7466 it.remove(); 7467 } 7468 } 7469 } 7470 7471 // Now update the permissions for all packages, in particular 7472 // replace the granted permissions of the system packages. 7473 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7474 for (PackageParser.Package pkg : mPackages.values()) { 7475 if (pkg != pkgInfo) { 7476 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7477 changingPkg); 7478 } 7479 } 7480 } 7481 7482 if (pkgInfo != null) { 7483 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7484 } 7485 } 7486 7487 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7488 String packageOfInterest) { 7489 // IMPORTANT: There are two types of permissions: install and runtime. 7490 // Install time permissions are granted when the app is installed to 7491 // all device users and users added in the future. Runtime permissions 7492 // are granted at runtime explicitly to specific users. Normal and signature 7493 // protected permissions are install time permissions. Dangerous permissions 7494 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7495 // otherwise they are runtime permissions. This function does not manage 7496 // runtime permissions except for the case an app targeting Lollipop MR1 7497 // being upgraded to target a newer SDK, in which case dangerous permissions 7498 // are transformed from install time to runtime ones. 7499 7500 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7501 if (ps == null) { 7502 return; 7503 } 7504 7505 PermissionsState permissionsState = ps.getPermissionsState(); 7506 PermissionsState origPermissions = permissionsState; 7507 7508 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7509 7510 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7511 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7512 7513 boolean changedInstallPermission = false; 7514 7515 if (replace) { 7516 ps.installPermissionsFixed = false; 7517 if (!ps.isSharedUser()) { 7518 origPermissions = new PermissionsState(permissionsState); 7519 permissionsState.reset(); 7520 } 7521 } 7522 7523 permissionsState.setGlobalGids(mGlobalGids); 7524 7525 final int N = pkg.requestedPermissions.size(); 7526 for (int i=0; i<N; i++) { 7527 final String name = pkg.requestedPermissions.get(i); 7528 final BasePermission bp = mSettings.mPermissions.get(name); 7529 7530 if (DEBUG_INSTALL) { 7531 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7532 } 7533 7534 if (bp == null || bp.packageSetting == null) { 7535 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7536 Slog.w(TAG, "Unknown permission " + name 7537 + " in package " + pkg.packageName); 7538 } 7539 continue; 7540 } 7541 7542 final String perm = bp.name; 7543 boolean allowedSig = false; 7544 int grant = GRANT_DENIED; 7545 7546 // Keep track of app op permissions. 7547 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7548 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7549 if (pkgs == null) { 7550 pkgs = new ArraySet<>(); 7551 mAppOpPermissionPackages.put(bp.name, pkgs); 7552 } 7553 pkgs.add(pkg.packageName); 7554 } 7555 7556 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7557 switch (level) { 7558 case PermissionInfo.PROTECTION_NORMAL: { 7559 // For all apps normal permissions are install time ones. 7560 grant = GRANT_INSTALL; 7561 } break; 7562 7563 case PermissionInfo.PROTECTION_DANGEROUS: { 7564 if (!RUNTIME_PERMISSIONS_ENABLED 7565 || pkg.applicationInfo.targetSdkVersion 7566 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7567 // For legacy apps dangerous permissions are install time ones. 7568 grant = GRANT_INSTALL; 7569 } else if (ps.isSystem()) { 7570 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7571 if (origPermissions.hasInstallPermission(bp.name)) { 7572 // If a system app had an install permission, then the app was 7573 // upgraded and we grant the permissions as runtime to all users. 7574 grant = GRANT_UPGRADE; 7575 upgradeUserIds = currentUserIds; 7576 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7577 // If users changed since the last permissions update for a 7578 // system app, we grant the permission as runtime to the new users. 7579 grant = GRANT_UPGRADE; 7580 upgradeUserIds = currentUserIds; 7581 for (int userId : updatedUserIds) { 7582 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7583 } 7584 } else { 7585 // Otherwise, we grant the permission as runtime if the app 7586 // already had it, i.e. we preserve runtime permissions. 7587 grant = GRANT_RUNTIME; 7588 } 7589 } else if (origPermissions.hasInstallPermission(bp.name)) { 7590 // For legacy apps that became modern, install becomes runtime. 7591 grant = GRANT_UPGRADE; 7592 upgradeUserIds = currentUserIds; 7593 } else if (replace) { 7594 // For upgraded modern apps keep runtime permissions unchanged. 7595 grant = GRANT_RUNTIME; 7596 } 7597 } break; 7598 7599 case PermissionInfo.PROTECTION_SIGNATURE: { 7600 // For all apps signature permissions are install time ones. 7601 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7602 if (allowedSig) { 7603 grant = GRANT_INSTALL; 7604 } 7605 } break; 7606 } 7607 7608 if (DEBUG_INSTALL) { 7609 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7610 } 7611 7612 if (grant != GRANT_DENIED) { 7613 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7614 // If this is an existing, non-system package, then 7615 // we can't add any new permissions to it. 7616 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7617 // Except... if this is a permission that was added 7618 // to the platform (note: need to only do this when 7619 // updating the platform). 7620 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7621 grant = GRANT_DENIED; 7622 } 7623 } 7624 } 7625 7626 switch (grant) { 7627 case GRANT_INSTALL: { 7628 // Grant an install permission. 7629 if (permissionsState.grantInstallPermission(bp) != 7630 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7631 changedInstallPermission = true; 7632 } 7633 } break; 7634 7635 case GRANT_RUNTIME: { 7636 // Grant previously granted runtime permissions. 7637 for (int userId : UserManagerService.getInstance().getUserIds()) { 7638 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7639 if (permissionsState.grantRuntimePermission(bp, userId) == 7640 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7641 // If we cannot put the permission as it was, we have to write. 7642 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7643 changedRuntimePermissionUserIds, userId); 7644 } 7645 } 7646 } 7647 } break; 7648 7649 case GRANT_UPGRADE: { 7650 // Grant runtime permissions for a previously held install permission. 7651 permissionsState.revokeInstallPermission(bp); 7652 for (int userId : upgradeUserIds) { 7653 if (permissionsState.grantRuntimePermission(bp, userId) != 7654 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7655 // If we granted the permission, we have to write. 7656 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7657 changedRuntimePermissionUserIds, userId); 7658 } 7659 } 7660 } break; 7661 7662 default: { 7663 if (packageOfInterest == null 7664 || packageOfInterest.equals(pkg.packageName)) { 7665 Slog.w(TAG, "Not granting permission " + perm 7666 + " to package " + pkg.packageName 7667 + " because it was previously installed without"); 7668 } 7669 } break; 7670 } 7671 } else { 7672 if (permissionsState.revokeInstallPermission(bp) != 7673 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7674 changedInstallPermission = true; 7675 Slog.i(TAG, "Un-granting permission " + perm 7676 + " from package " + pkg.packageName 7677 + " (protectionLevel=" + bp.protectionLevel 7678 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7679 + ")"); 7680 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7681 // Don't print warning for app op permissions, since it is fine for them 7682 // not to be granted, there is a UI for the user to decide. 7683 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7684 Slog.w(TAG, "Not granting permission " + perm 7685 + " to package " + pkg.packageName 7686 + " (protectionLevel=" + bp.protectionLevel 7687 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7688 + ")"); 7689 } 7690 } 7691 } 7692 } 7693 7694 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7695 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7696 // This is the first that we have heard about this package, so the 7697 // permissions we have now selected are fixed until explicitly 7698 // changed. 7699 ps.installPermissionsFixed = true; 7700 } 7701 7702 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7703 7704 // Persist the runtime permissions state for users with changes. 7705 if (RUNTIME_PERMISSIONS_ENABLED) { 7706 for (int userId : changedRuntimePermissionUserIds) { 7707 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7708 } 7709 } 7710 } 7711 7712 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7713 boolean allowed = false; 7714 final int NP = PackageParser.NEW_PERMISSIONS.length; 7715 for (int ip=0; ip<NP; ip++) { 7716 final PackageParser.NewPermissionInfo npi 7717 = PackageParser.NEW_PERMISSIONS[ip]; 7718 if (npi.name.equals(perm) 7719 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7720 allowed = true; 7721 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7722 + pkg.packageName); 7723 break; 7724 } 7725 } 7726 return allowed; 7727 } 7728 7729 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7730 BasePermission bp, PermissionsState origPermissions) { 7731 boolean allowed; 7732 allowed = (compareSignatures( 7733 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7734 == PackageManager.SIGNATURE_MATCH) 7735 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7736 == PackageManager.SIGNATURE_MATCH); 7737 if (!allowed && (bp.protectionLevel 7738 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7739 if (isSystemApp(pkg)) { 7740 // For updated system applications, a system permission 7741 // is granted only if it had been defined by the original application. 7742 if (pkg.isUpdatedSystemApp()) { 7743 final PackageSetting sysPs = mSettings 7744 .getDisabledSystemPkgLPr(pkg.packageName); 7745 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7746 // If the original was granted this permission, we take 7747 // that grant decision as read and propagate it to the 7748 // update. 7749 if (sysPs.isPrivileged()) { 7750 allowed = true; 7751 } 7752 } else { 7753 // The system apk may have been updated with an older 7754 // version of the one on the data partition, but which 7755 // granted a new system permission that it didn't have 7756 // before. In this case we do want to allow the app to 7757 // now get the new permission if the ancestral apk is 7758 // privileged to get it. 7759 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7760 for (int j=0; 7761 j<sysPs.pkg.requestedPermissions.size(); j++) { 7762 if (perm.equals( 7763 sysPs.pkg.requestedPermissions.get(j))) { 7764 allowed = true; 7765 break; 7766 } 7767 } 7768 } 7769 } 7770 } else { 7771 allowed = isPrivilegedApp(pkg); 7772 } 7773 } 7774 } 7775 if (!allowed && (bp.protectionLevel 7776 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7777 // For development permissions, a development permission 7778 // is granted only if it was already granted. 7779 allowed = origPermissions.hasInstallPermission(perm); 7780 } 7781 return allowed; 7782 } 7783 7784 final class ActivityIntentResolver 7785 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7786 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7787 boolean defaultOnly, int userId) { 7788 if (!sUserManager.exists(userId)) return null; 7789 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7790 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7791 } 7792 7793 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7794 int userId) { 7795 if (!sUserManager.exists(userId)) return null; 7796 mFlags = flags; 7797 return super.queryIntent(intent, resolvedType, 7798 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7799 } 7800 7801 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7802 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7803 if (!sUserManager.exists(userId)) return null; 7804 if (packageActivities == null) { 7805 return null; 7806 } 7807 mFlags = flags; 7808 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7809 final int N = packageActivities.size(); 7810 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7811 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7812 7813 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7814 for (int i = 0; i < N; ++i) { 7815 intentFilters = packageActivities.get(i).intents; 7816 if (intentFilters != null && intentFilters.size() > 0) { 7817 PackageParser.ActivityIntentInfo[] array = 7818 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7819 intentFilters.toArray(array); 7820 listCut.add(array); 7821 } 7822 } 7823 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7824 } 7825 7826 public final void addActivity(PackageParser.Activity a, String type) { 7827 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7828 mActivities.put(a.getComponentName(), a); 7829 if (DEBUG_SHOW_INFO) 7830 Log.v( 7831 TAG, " " + type + " " + 7832 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7833 if (DEBUG_SHOW_INFO) 7834 Log.v(TAG, " Class=" + a.info.name); 7835 final int NI = a.intents.size(); 7836 for (int j=0; j<NI; j++) { 7837 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7838 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7839 intent.setPriority(0); 7840 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7841 + a.className + " with priority > 0, forcing to 0"); 7842 } 7843 if (DEBUG_SHOW_INFO) { 7844 Log.v(TAG, " IntentFilter:"); 7845 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7846 } 7847 if (!intent.debugCheck()) { 7848 Log.w(TAG, "==> For Activity " + a.info.name); 7849 } 7850 addFilter(intent); 7851 } 7852 } 7853 7854 public final void removeActivity(PackageParser.Activity a, String type) { 7855 mActivities.remove(a.getComponentName()); 7856 if (DEBUG_SHOW_INFO) { 7857 Log.v(TAG, " " + type + " " 7858 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7859 : a.info.name) + ":"); 7860 Log.v(TAG, " Class=" + a.info.name); 7861 } 7862 final int NI = a.intents.size(); 7863 for (int j=0; j<NI; j++) { 7864 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7865 if (DEBUG_SHOW_INFO) { 7866 Log.v(TAG, " IntentFilter:"); 7867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7868 } 7869 removeFilter(intent); 7870 } 7871 } 7872 7873 @Override 7874 protected boolean allowFilterResult( 7875 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7876 ActivityInfo filterAi = filter.activity.info; 7877 for (int i=dest.size()-1; i>=0; i--) { 7878 ActivityInfo destAi = dest.get(i).activityInfo; 7879 if (destAi.name == filterAi.name 7880 && destAi.packageName == filterAi.packageName) { 7881 return false; 7882 } 7883 } 7884 return true; 7885 } 7886 7887 @Override 7888 protected ActivityIntentInfo[] newArray(int size) { 7889 return new ActivityIntentInfo[size]; 7890 } 7891 7892 @Override 7893 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7894 if (!sUserManager.exists(userId)) return true; 7895 PackageParser.Package p = filter.activity.owner; 7896 if (p != null) { 7897 PackageSetting ps = (PackageSetting)p.mExtras; 7898 if (ps != null) { 7899 // System apps are never considered stopped for purposes of 7900 // filtering, because there may be no way for the user to 7901 // actually re-launch them. 7902 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7903 && ps.getStopped(userId); 7904 } 7905 } 7906 return false; 7907 } 7908 7909 @Override 7910 protected boolean isPackageForFilter(String packageName, 7911 PackageParser.ActivityIntentInfo info) { 7912 return packageName.equals(info.activity.owner.packageName); 7913 } 7914 7915 @Override 7916 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7917 int match, int userId) { 7918 if (!sUserManager.exists(userId)) return null; 7919 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7920 return null; 7921 } 7922 final PackageParser.Activity activity = info.activity; 7923 if (mSafeMode && (activity.info.applicationInfo.flags 7924 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7925 return null; 7926 } 7927 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7928 if (ps == null) { 7929 return null; 7930 } 7931 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7932 ps.readUserState(userId), userId); 7933 if (ai == null) { 7934 return null; 7935 } 7936 final ResolveInfo res = new ResolveInfo(); 7937 res.activityInfo = ai; 7938 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7939 res.filter = info; 7940 } 7941 if (info != null) { 7942 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7943 } 7944 res.priority = info.getPriority(); 7945 res.preferredOrder = activity.owner.mPreferredOrder; 7946 //System.out.println("Result: " + res.activityInfo.className + 7947 // " = " + res.priority); 7948 res.match = match; 7949 res.isDefault = info.hasDefault; 7950 res.labelRes = info.labelRes; 7951 res.nonLocalizedLabel = info.nonLocalizedLabel; 7952 if (userNeedsBadging(userId)) { 7953 res.noResourceId = true; 7954 } else { 7955 res.icon = info.icon; 7956 } 7957 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7958 return res; 7959 } 7960 7961 @Override 7962 protected void sortResults(List<ResolveInfo> results) { 7963 Collections.sort(results, mResolvePrioritySorter); 7964 } 7965 7966 @Override 7967 protected void dumpFilter(PrintWriter out, String prefix, 7968 PackageParser.ActivityIntentInfo filter) { 7969 out.print(prefix); out.print( 7970 Integer.toHexString(System.identityHashCode(filter.activity))); 7971 out.print(' '); 7972 filter.activity.printComponentShortName(out); 7973 out.print(" filter "); 7974 out.println(Integer.toHexString(System.identityHashCode(filter))); 7975 } 7976 7977 @Override 7978 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7979 return filter.activity; 7980 } 7981 7982 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7983 PackageParser.Activity activity = (PackageParser.Activity)label; 7984 out.print(prefix); out.print( 7985 Integer.toHexString(System.identityHashCode(activity))); 7986 out.print(' '); 7987 activity.printComponentShortName(out); 7988 if (count > 1) { 7989 out.print(" ("); out.print(count); out.print(" filters)"); 7990 } 7991 out.println(); 7992 } 7993 7994// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7995// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7996// final List<ResolveInfo> retList = Lists.newArrayList(); 7997// while (i.hasNext()) { 7998// final ResolveInfo resolveInfo = i.next(); 7999// if (isEnabledLP(resolveInfo.activityInfo)) { 8000// retList.add(resolveInfo); 8001// } 8002// } 8003// return retList; 8004// } 8005 8006 // Keys are String (activity class name), values are Activity. 8007 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8008 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8009 private int mFlags; 8010 } 8011 8012 private final class ServiceIntentResolver 8013 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8014 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8015 boolean defaultOnly, int userId) { 8016 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8017 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8018 } 8019 8020 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8021 int userId) { 8022 if (!sUserManager.exists(userId)) return null; 8023 mFlags = flags; 8024 return super.queryIntent(intent, resolvedType, 8025 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8026 } 8027 8028 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8029 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8030 if (!sUserManager.exists(userId)) return null; 8031 if (packageServices == null) { 8032 return null; 8033 } 8034 mFlags = flags; 8035 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8036 final int N = packageServices.size(); 8037 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8038 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8039 8040 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8041 for (int i = 0; i < N; ++i) { 8042 intentFilters = packageServices.get(i).intents; 8043 if (intentFilters != null && intentFilters.size() > 0) { 8044 PackageParser.ServiceIntentInfo[] array = 8045 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8046 intentFilters.toArray(array); 8047 listCut.add(array); 8048 } 8049 } 8050 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8051 } 8052 8053 public final void addService(PackageParser.Service s) { 8054 mServices.put(s.getComponentName(), s); 8055 if (DEBUG_SHOW_INFO) { 8056 Log.v(TAG, " " 8057 + (s.info.nonLocalizedLabel != null 8058 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8059 Log.v(TAG, " Class=" + s.info.name); 8060 } 8061 final int NI = s.intents.size(); 8062 int j; 8063 for (j=0; j<NI; j++) { 8064 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8065 if (DEBUG_SHOW_INFO) { 8066 Log.v(TAG, " IntentFilter:"); 8067 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8068 } 8069 if (!intent.debugCheck()) { 8070 Log.w(TAG, "==> For Service " + s.info.name); 8071 } 8072 addFilter(intent); 8073 } 8074 } 8075 8076 public final void removeService(PackageParser.Service s) { 8077 mServices.remove(s.getComponentName()); 8078 if (DEBUG_SHOW_INFO) { 8079 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8080 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8081 Log.v(TAG, " Class=" + s.info.name); 8082 } 8083 final int NI = s.intents.size(); 8084 int j; 8085 for (j=0; j<NI; j++) { 8086 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8087 if (DEBUG_SHOW_INFO) { 8088 Log.v(TAG, " IntentFilter:"); 8089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8090 } 8091 removeFilter(intent); 8092 } 8093 } 8094 8095 @Override 8096 protected boolean allowFilterResult( 8097 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8098 ServiceInfo filterSi = filter.service.info; 8099 for (int i=dest.size()-1; i>=0; i--) { 8100 ServiceInfo destAi = dest.get(i).serviceInfo; 8101 if (destAi.name == filterSi.name 8102 && destAi.packageName == filterSi.packageName) { 8103 return false; 8104 } 8105 } 8106 return true; 8107 } 8108 8109 @Override 8110 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8111 return new PackageParser.ServiceIntentInfo[size]; 8112 } 8113 8114 @Override 8115 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8116 if (!sUserManager.exists(userId)) return true; 8117 PackageParser.Package p = filter.service.owner; 8118 if (p != null) { 8119 PackageSetting ps = (PackageSetting)p.mExtras; 8120 if (ps != null) { 8121 // System apps are never considered stopped for purposes of 8122 // filtering, because there may be no way for the user to 8123 // actually re-launch them. 8124 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8125 && ps.getStopped(userId); 8126 } 8127 } 8128 return false; 8129 } 8130 8131 @Override 8132 protected boolean isPackageForFilter(String packageName, 8133 PackageParser.ServiceIntentInfo info) { 8134 return packageName.equals(info.service.owner.packageName); 8135 } 8136 8137 @Override 8138 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8139 int match, int userId) { 8140 if (!sUserManager.exists(userId)) return null; 8141 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8142 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8143 return null; 8144 } 8145 final PackageParser.Service service = info.service; 8146 if (mSafeMode && (service.info.applicationInfo.flags 8147 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8148 return null; 8149 } 8150 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8151 if (ps == null) { 8152 return null; 8153 } 8154 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8155 ps.readUserState(userId), userId); 8156 if (si == null) { 8157 return null; 8158 } 8159 final ResolveInfo res = new ResolveInfo(); 8160 res.serviceInfo = si; 8161 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8162 res.filter = filter; 8163 } 8164 res.priority = info.getPriority(); 8165 res.preferredOrder = service.owner.mPreferredOrder; 8166 res.match = match; 8167 res.isDefault = info.hasDefault; 8168 res.labelRes = info.labelRes; 8169 res.nonLocalizedLabel = info.nonLocalizedLabel; 8170 res.icon = info.icon; 8171 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8172 return res; 8173 } 8174 8175 @Override 8176 protected void sortResults(List<ResolveInfo> results) { 8177 Collections.sort(results, mResolvePrioritySorter); 8178 } 8179 8180 @Override 8181 protected void dumpFilter(PrintWriter out, String prefix, 8182 PackageParser.ServiceIntentInfo filter) { 8183 out.print(prefix); out.print( 8184 Integer.toHexString(System.identityHashCode(filter.service))); 8185 out.print(' '); 8186 filter.service.printComponentShortName(out); 8187 out.print(" filter "); 8188 out.println(Integer.toHexString(System.identityHashCode(filter))); 8189 } 8190 8191 @Override 8192 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8193 return filter.service; 8194 } 8195 8196 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8197 PackageParser.Service service = (PackageParser.Service)label; 8198 out.print(prefix); out.print( 8199 Integer.toHexString(System.identityHashCode(service))); 8200 out.print(' '); 8201 service.printComponentShortName(out); 8202 if (count > 1) { 8203 out.print(" ("); out.print(count); out.print(" filters)"); 8204 } 8205 out.println(); 8206 } 8207 8208// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8209// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8210// final List<ResolveInfo> retList = Lists.newArrayList(); 8211// while (i.hasNext()) { 8212// final ResolveInfo resolveInfo = (ResolveInfo) i; 8213// if (isEnabledLP(resolveInfo.serviceInfo)) { 8214// retList.add(resolveInfo); 8215// } 8216// } 8217// return retList; 8218// } 8219 8220 // Keys are String (activity class name), values are Activity. 8221 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8222 = new ArrayMap<ComponentName, PackageParser.Service>(); 8223 private int mFlags; 8224 }; 8225 8226 private final class ProviderIntentResolver 8227 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8228 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8229 boolean defaultOnly, int userId) { 8230 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8231 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8232 } 8233 8234 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8235 int userId) { 8236 if (!sUserManager.exists(userId)) 8237 return null; 8238 mFlags = flags; 8239 return super.queryIntent(intent, resolvedType, 8240 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8241 } 8242 8243 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8244 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8245 if (!sUserManager.exists(userId)) 8246 return null; 8247 if (packageProviders == null) { 8248 return null; 8249 } 8250 mFlags = flags; 8251 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8252 final int N = packageProviders.size(); 8253 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8254 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8255 8256 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8257 for (int i = 0; i < N; ++i) { 8258 intentFilters = packageProviders.get(i).intents; 8259 if (intentFilters != null && intentFilters.size() > 0) { 8260 PackageParser.ProviderIntentInfo[] array = 8261 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8262 intentFilters.toArray(array); 8263 listCut.add(array); 8264 } 8265 } 8266 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8267 } 8268 8269 public final void addProvider(PackageParser.Provider p) { 8270 if (mProviders.containsKey(p.getComponentName())) { 8271 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8272 return; 8273 } 8274 8275 mProviders.put(p.getComponentName(), p); 8276 if (DEBUG_SHOW_INFO) { 8277 Log.v(TAG, " " 8278 + (p.info.nonLocalizedLabel != null 8279 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8280 Log.v(TAG, " Class=" + p.info.name); 8281 } 8282 final int NI = p.intents.size(); 8283 int j; 8284 for (j = 0; j < NI; j++) { 8285 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8286 if (DEBUG_SHOW_INFO) { 8287 Log.v(TAG, " IntentFilter:"); 8288 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8289 } 8290 if (!intent.debugCheck()) { 8291 Log.w(TAG, "==> For Provider " + p.info.name); 8292 } 8293 addFilter(intent); 8294 } 8295 } 8296 8297 public final void removeProvider(PackageParser.Provider p) { 8298 mProviders.remove(p.getComponentName()); 8299 if (DEBUG_SHOW_INFO) { 8300 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8301 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8302 Log.v(TAG, " Class=" + p.info.name); 8303 } 8304 final int NI = p.intents.size(); 8305 int j; 8306 for (j = 0; j < NI; j++) { 8307 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8308 if (DEBUG_SHOW_INFO) { 8309 Log.v(TAG, " IntentFilter:"); 8310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8311 } 8312 removeFilter(intent); 8313 } 8314 } 8315 8316 @Override 8317 protected boolean allowFilterResult( 8318 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8319 ProviderInfo filterPi = filter.provider.info; 8320 for (int i = dest.size() - 1; i >= 0; i--) { 8321 ProviderInfo destPi = dest.get(i).providerInfo; 8322 if (destPi.name == filterPi.name 8323 && destPi.packageName == filterPi.packageName) { 8324 return false; 8325 } 8326 } 8327 return true; 8328 } 8329 8330 @Override 8331 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8332 return new PackageParser.ProviderIntentInfo[size]; 8333 } 8334 8335 @Override 8336 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8337 if (!sUserManager.exists(userId)) 8338 return true; 8339 PackageParser.Package p = filter.provider.owner; 8340 if (p != null) { 8341 PackageSetting ps = (PackageSetting) p.mExtras; 8342 if (ps != null) { 8343 // System apps are never considered stopped for purposes of 8344 // filtering, because there may be no way for the user to 8345 // actually re-launch them. 8346 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8347 && ps.getStopped(userId); 8348 } 8349 } 8350 return false; 8351 } 8352 8353 @Override 8354 protected boolean isPackageForFilter(String packageName, 8355 PackageParser.ProviderIntentInfo info) { 8356 return packageName.equals(info.provider.owner.packageName); 8357 } 8358 8359 @Override 8360 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8361 int match, int userId) { 8362 if (!sUserManager.exists(userId)) 8363 return null; 8364 final PackageParser.ProviderIntentInfo info = filter; 8365 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8366 return null; 8367 } 8368 final PackageParser.Provider provider = info.provider; 8369 if (mSafeMode && (provider.info.applicationInfo.flags 8370 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8371 return null; 8372 } 8373 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8374 if (ps == null) { 8375 return null; 8376 } 8377 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8378 ps.readUserState(userId), userId); 8379 if (pi == null) { 8380 return null; 8381 } 8382 final ResolveInfo res = new ResolveInfo(); 8383 res.providerInfo = pi; 8384 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8385 res.filter = filter; 8386 } 8387 res.priority = info.getPriority(); 8388 res.preferredOrder = provider.owner.mPreferredOrder; 8389 res.match = match; 8390 res.isDefault = info.hasDefault; 8391 res.labelRes = info.labelRes; 8392 res.nonLocalizedLabel = info.nonLocalizedLabel; 8393 res.icon = info.icon; 8394 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8395 return res; 8396 } 8397 8398 @Override 8399 protected void sortResults(List<ResolveInfo> results) { 8400 Collections.sort(results, mResolvePrioritySorter); 8401 } 8402 8403 @Override 8404 protected void dumpFilter(PrintWriter out, String prefix, 8405 PackageParser.ProviderIntentInfo filter) { 8406 out.print(prefix); 8407 out.print( 8408 Integer.toHexString(System.identityHashCode(filter.provider))); 8409 out.print(' '); 8410 filter.provider.printComponentShortName(out); 8411 out.print(" filter "); 8412 out.println(Integer.toHexString(System.identityHashCode(filter))); 8413 } 8414 8415 @Override 8416 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8417 return filter.provider; 8418 } 8419 8420 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8421 PackageParser.Provider provider = (PackageParser.Provider)label; 8422 out.print(prefix); out.print( 8423 Integer.toHexString(System.identityHashCode(provider))); 8424 out.print(' '); 8425 provider.printComponentShortName(out); 8426 if (count > 1) { 8427 out.print(" ("); out.print(count); out.print(" filters)"); 8428 } 8429 out.println(); 8430 } 8431 8432 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8433 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8434 private int mFlags; 8435 }; 8436 8437 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8438 new Comparator<ResolveInfo>() { 8439 public int compare(ResolveInfo r1, ResolveInfo r2) { 8440 int v1 = r1.priority; 8441 int v2 = r2.priority; 8442 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8443 if (v1 != v2) { 8444 return (v1 > v2) ? -1 : 1; 8445 } 8446 v1 = r1.preferredOrder; 8447 v2 = r2.preferredOrder; 8448 if (v1 != v2) { 8449 return (v1 > v2) ? -1 : 1; 8450 } 8451 if (r1.isDefault != r2.isDefault) { 8452 return r1.isDefault ? -1 : 1; 8453 } 8454 v1 = r1.match; 8455 v2 = r2.match; 8456 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8457 if (v1 != v2) { 8458 return (v1 > v2) ? -1 : 1; 8459 } 8460 if (r1.system != r2.system) { 8461 return r1.system ? -1 : 1; 8462 } 8463 return 0; 8464 } 8465 }; 8466 8467 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8468 new Comparator<ProviderInfo>() { 8469 public int compare(ProviderInfo p1, ProviderInfo p2) { 8470 final int v1 = p1.initOrder; 8471 final int v2 = p2.initOrder; 8472 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8473 } 8474 }; 8475 8476 static final void sendPackageBroadcast(String action, String pkg, 8477 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8478 int[] userIds) { 8479 IActivityManager am = ActivityManagerNative.getDefault(); 8480 if (am != null) { 8481 try { 8482 if (userIds == null) { 8483 userIds = am.getRunningUserIds(); 8484 } 8485 for (int id : userIds) { 8486 final Intent intent = new Intent(action, 8487 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8488 if (extras != null) { 8489 intent.putExtras(extras); 8490 } 8491 if (targetPkg != null) { 8492 intent.setPackage(targetPkg); 8493 } 8494 // Modify the UID when posting to other users 8495 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8496 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8497 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8498 intent.putExtra(Intent.EXTRA_UID, uid); 8499 } 8500 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8501 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8502 if (DEBUG_BROADCASTS) { 8503 RuntimeException here = new RuntimeException("here"); 8504 here.fillInStackTrace(); 8505 Slog.d(TAG, "Sending to user " + id + ": " 8506 + intent.toShortString(false, true, false, false) 8507 + " " + intent.getExtras(), here); 8508 } 8509 am.broadcastIntent(null, intent, null, finishedReceiver, 8510 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8511 finishedReceiver != null, false, id); 8512 } 8513 } catch (RemoteException ex) { 8514 } 8515 } 8516 } 8517 8518 /** 8519 * Check if the external storage media is available. This is true if there 8520 * is a mounted external storage medium or if the external storage is 8521 * emulated. 8522 */ 8523 private boolean isExternalMediaAvailable() { 8524 return mMediaMounted || Environment.isExternalStorageEmulated(); 8525 } 8526 8527 @Override 8528 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8529 // writer 8530 synchronized (mPackages) { 8531 if (!isExternalMediaAvailable()) { 8532 // If the external storage is no longer mounted at this point, 8533 // the caller may not have been able to delete all of this 8534 // packages files and can not delete any more. Bail. 8535 return null; 8536 } 8537 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8538 if (lastPackage != null) { 8539 pkgs.remove(lastPackage); 8540 } 8541 if (pkgs.size() > 0) { 8542 return pkgs.get(0); 8543 } 8544 } 8545 return null; 8546 } 8547 8548 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8549 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8550 userId, andCode ? 1 : 0, packageName); 8551 if (mSystemReady) { 8552 msg.sendToTarget(); 8553 } else { 8554 if (mPostSystemReadyMessages == null) { 8555 mPostSystemReadyMessages = new ArrayList<>(); 8556 } 8557 mPostSystemReadyMessages.add(msg); 8558 } 8559 } 8560 8561 void startCleaningPackages() { 8562 // reader 8563 synchronized (mPackages) { 8564 if (!isExternalMediaAvailable()) { 8565 return; 8566 } 8567 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8568 return; 8569 } 8570 } 8571 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8572 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8573 IActivityManager am = ActivityManagerNative.getDefault(); 8574 if (am != null) { 8575 try { 8576 am.startService(null, intent, null, UserHandle.USER_OWNER); 8577 } catch (RemoteException e) { 8578 } 8579 } 8580 } 8581 8582 @Override 8583 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8584 int installFlags, String installerPackageName, VerificationParams verificationParams, 8585 String packageAbiOverride) { 8586 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8587 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8588 } 8589 8590 @Override 8591 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8592 int installFlags, String installerPackageName, VerificationParams verificationParams, 8593 String packageAbiOverride, int userId) { 8594 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8595 8596 final int callingUid = Binder.getCallingUid(); 8597 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8598 8599 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8600 try { 8601 if (observer != null) { 8602 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8603 } 8604 } catch (RemoteException re) { 8605 } 8606 return; 8607 } 8608 8609 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8610 installFlags |= PackageManager.INSTALL_FROM_ADB; 8611 8612 } else { 8613 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8614 // about installerPackageName. 8615 8616 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8617 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8618 } 8619 8620 UserHandle user; 8621 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8622 user = UserHandle.ALL; 8623 } else { 8624 user = new UserHandle(userId); 8625 } 8626 8627 // Only system components can circumvent runtime permissions when installing. 8628 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8629 && mContext.checkCallingOrSelfPermission(Manifest.permission 8630 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8631 throw new SecurityException("You need the " 8632 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8633 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8634 } 8635 8636 verificationParams.setInstallerUid(callingUid); 8637 8638 final File originFile = new File(originPath); 8639 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8640 8641 final Message msg = mHandler.obtainMessage(INIT_COPY); 8642 msg.obj = new InstallParams(origin, observer, installFlags, 8643 installerPackageName, null, verificationParams, user, packageAbiOverride); 8644 mHandler.sendMessage(msg); 8645 } 8646 8647 void installStage(String packageName, File stagedDir, String stagedCid, 8648 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8649 String installerPackageName, int installerUid, UserHandle user) { 8650 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8651 params.referrerUri, installerUid, null); 8652 8653 final OriginInfo origin; 8654 if (stagedDir != null) { 8655 origin = OriginInfo.fromStagedFile(stagedDir); 8656 } else { 8657 origin = OriginInfo.fromStagedContainer(stagedCid); 8658 } 8659 8660 final Message msg = mHandler.obtainMessage(INIT_COPY); 8661 msg.obj = new InstallParams(origin, observer, params.installFlags, 8662 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8663 mHandler.sendMessage(msg); 8664 } 8665 8666 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8667 Bundle extras = new Bundle(1); 8668 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8669 8670 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8671 packageName, extras, null, null, new int[] {userId}); 8672 try { 8673 IActivityManager am = ActivityManagerNative.getDefault(); 8674 final boolean isSystem = 8675 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8676 if (isSystem && am.isUserRunning(userId, false)) { 8677 // The just-installed/enabled app is bundled on the system, so presumed 8678 // to be able to run automatically without needing an explicit launch. 8679 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8680 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8681 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8682 .setPackage(packageName); 8683 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8684 android.app.AppOpsManager.OP_NONE, false, false, userId); 8685 } 8686 } catch (RemoteException e) { 8687 // shouldn't happen 8688 Slog.w(TAG, "Unable to bootstrap installed package", e); 8689 } 8690 } 8691 8692 @Override 8693 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8694 int userId) { 8695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8696 PackageSetting pkgSetting; 8697 final int uid = Binder.getCallingUid(); 8698 enforceCrossUserPermission(uid, userId, true, true, 8699 "setApplicationHiddenSetting for user " + userId); 8700 8701 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8702 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8703 return false; 8704 } 8705 8706 long callingId = Binder.clearCallingIdentity(); 8707 try { 8708 boolean sendAdded = false; 8709 boolean sendRemoved = false; 8710 // writer 8711 synchronized (mPackages) { 8712 pkgSetting = mSettings.mPackages.get(packageName); 8713 if (pkgSetting == null) { 8714 return false; 8715 } 8716 if (pkgSetting.getHidden(userId) != hidden) { 8717 pkgSetting.setHidden(hidden, userId); 8718 mSettings.writePackageRestrictionsLPr(userId); 8719 if (hidden) { 8720 sendRemoved = true; 8721 } else { 8722 sendAdded = true; 8723 } 8724 } 8725 } 8726 if (sendAdded) { 8727 sendPackageAddedForUser(packageName, pkgSetting, userId); 8728 return true; 8729 } 8730 if (sendRemoved) { 8731 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8732 "hiding pkg"); 8733 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8734 } 8735 } finally { 8736 Binder.restoreCallingIdentity(callingId); 8737 } 8738 return false; 8739 } 8740 8741 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8742 int userId) { 8743 final PackageRemovedInfo info = new PackageRemovedInfo(); 8744 info.removedPackage = packageName; 8745 info.removedUsers = new int[] {userId}; 8746 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8747 info.sendBroadcast(false, false, false); 8748 } 8749 8750 /** 8751 * Returns true if application is not found or there was an error. Otherwise it returns 8752 * the hidden state of the package for the given user. 8753 */ 8754 @Override 8755 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8757 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8758 false, "getApplicationHidden for user " + userId); 8759 PackageSetting pkgSetting; 8760 long callingId = Binder.clearCallingIdentity(); 8761 try { 8762 // writer 8763 synchronized (mPackages) { 8764 pkgSetting = mSettings.mPackages.get(packageName); 8765 if (pkgSetting == null) { 8766 return true; 8767 } 8768 return pkgSetting.getHidden(userId); 8769 } 8770 } finally { 8771 Binder.restoreCallingIdentity(callingId); 8772 } 8773 } 8774 8775 /** 8776 * @hide 8777 */ 8778 @Override 8779 public int installExistingPackageAsUser(String packageName, int userId) { 8780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8781 null); 8782 PackageSetting pkgSetting; 8783 final int uid = Binder.getCallingUid(); 8784 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8785 + userId); 8786 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8787 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8788 } 8789 8790 long callingId = Binder.clearCallingIdentity(); 8791 try { 8792 boolean sendAdded = false; 8793 8794 // writer 8795 synchronized (mPackages) { 8796 pkgSetting = mSettings.mPackages.get(packageName); 8797 if (pkgSetting == null) { 8798 return PackageManager.INSTALL_FAILED_INVALID_URI; 8799 } 8800 if (!pkgSetting.getInstalled(userId)) { 8801 pkgSetting.setInstalled(true, userId); 8802 pkgSetting.setHidden(false, userId); 8803 mSettings.writePackageRestrictionsLPr(userId); 8804 sendAdded = true; 8805 } 8806 } 8807 8808 if (sendAdded) { 8809 sendPackageAddedForUser(packageName, pkgSetting, userId); 8810 } 8811 } finally { 8812 Binder.restoreCallingIdentity(callingId); 8813 } 8814 8815 return PackageManager.INSTALL_SUCCEEDED; 8816 } 8817 8818 boolean isUserRestricted(int userId, String restrictionKey) { 8819 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8820 if (restrictions.getBoolean(restrictionKey, false)) { 8821 Log.w(TAG, "User is restricted: " + restrictionKey); 8822 return true; 8823 } 8824 return false; 8825 } 8826 8827 @Override 8828 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8829 mContext.enforceCallingOrSelfPermission( 8830 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8831 "Only package verification agents can verify applications"); 8832 8833 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8834 final PackageVerificationResponse response = new PackageVerificationResponse( 8835 verificationCode, Binder.getCallingUid()); 8836 msg.arg1 = id; 8837 msg.obj = response; 8838 mHandler.sendMessage(msg); 8839 } 8840 8841 @Override 8842 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8843 long millisecondsToDelay) { 8844 mContext.enforceCallingOrSelfPermission( 8845 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8846 "Only package verification agents can extend verification timeouts"); 8847 8848 final PackageVerificationState state = mPendingVerification.get(id); 8849 final PackageVerificationResponse response = new PackageVerificationResponse( 8850 verificationCodeAtTimeout, Binder.getCallingUid()); 8851 8852 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8853 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8854 } 8855 if (millisecondsToDelay < 0) { 8856 millisecondsToDelay = 0; 8857 } 8858 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8859 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8860 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8861 } 8862 8863 if ((state != null) && !state.timeoutExtended()) { 8864 state.extendTimeout(); 8865 8866 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8867 msg.arg1 = id; 8868 msg.obj = response; 8869 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8870 } 8871 } 8872 8873 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8874 int verificationCode, UserHandle user) { 8875 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8876 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8877 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8878 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8879 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8880 8881 mContext.sendBroadcastAsUser(intent, user, 8882 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8883 } 8884 8885 private ComponentName matchComponentForVerifier(String packageName, 8886 List<ResolveInfo> receivers) { 8887 ActivityInfo targetReceiver = null; 8888 8889 final int NR = receivers.size(); 8890 for (int i = 0; i < NR; i++) { 8891 final ResolveInfo info = receivers.get(i); 8892 if (info.activityInfo == null) { 8893 continue; 8894 } 8895 8896 if (packageName.equals(info.activityInfo.packageName)) { 8897 targetReceiver = info.activityInfo; 8898 break; 8899 } 8900 } 8901 8902 if (targetReceiver == null) { 8903 return null; 8904 } 8905 8906 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8907 } 8908 8909 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8910 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8911 if (pkgInfo.verifiers.length == 0) { 8912 return null; 8913 } 8914 8915 final int N = pkgInfo.verifiers.length; 8916 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8917 for (int i = 0; i < N; i++) { 8918 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8919 8920 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8921 receivers); 8922 if (comp == null) { 8923 continue; 8924 } 8925 8926 final int verifierUid = getUidForVerifier(verifierInfo); 8927 if (verifierUid == -1) { 8928 continue; 8929 } 8930 8931 if (DEBUG_VERIFY) { 8932 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8933 + " with the correct signature"); 8934 } 8935 sufficientVerifiers.add(comp); 8936 verificationState.addSufficientVerifier(verifierUid); 8937 } 8938 8939 return sufficientVerifiers; 8940 } 8941 8942 private int getUidForVerifier(VerifierInfo verifierInfo) { 8943 synchronized (mPackages) { 8944 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8945 if (pkg == null) { 8946 return -1; 8947 } else if (pkg.mSignatures.length != 1) { 8948 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8949 + " has more than one signature; ignoring"); 8950 return -1; 8951 } 8952 8953 /* 8954 * If the public key of the package's signature does not match 8955 * our expected public key, then this is a different package and 8956 * we should skip. 8957 */ 8958 8959 final byte[] expectedPublicKey; 8960 try { 8961 final Signature verifierSig = pkg.mSignatures[0]; 8962 final PublicKey publicKey = verifierSig.getPublicKey(); 8963 expectedPublicKey = publicKey.getEncoded(); 8964 } catch (CertificateException e) { 8965 return -1; 8966 } 8967 8968 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8969 8970 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8971 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8972 + " does not have the expected public key; ignoring"); 8973 return -1; 8974 } 8975 8976 return pkg.applicationInfo.uid; 8977 } 8978 } 8979 8980 @Override 8981 public void finishPackageInstall(int token) { 8982 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8983 8984 if (DEBUG_INSTALL) { 8985 Slog.v(TAG, "BM finishing package install for " + token); 8986 } 8987 8988 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8989 mHandler.sendMessage(msg); 8990 } 8991 8992 /** 8993 * Get the verification agent timeout. 8994 * 8995 * @return verification timeout in milliseconds 8996 */ 8997 private long getVerificationTimeout() { 8998 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8999 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9000 DEFAULT_VERIFICATION_TIMEOUT); 9001 } 9002 9003 /** 9004 * Get the default verification agent response code. 9005 * 9006 * @return default verification response code 9007 */ 9008 private int getDefaultVerificationResponse() { 9009 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9010 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9011 DEFAULT_VERIFICATION_RESPONSE); 9012 } 9013 9014 /** 9015 * Check whether or not package verification has been enabled. 9016 * 9017 * @return true if verification should be performed 9018 */ 9019 private boolean isVerificationEnabled(int userId, int installFlags) { 9020 if (!DEFAULT_VERIFY_ENABLE) { 9021 return false; 9022 } 9023 9024 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9025 9026 // Check if installing from ADB 9027 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9028 // Do not run verification in a test harness environment 9029 if (ActivityManager.isRunningInTestHarness()) { 9030 return false; 9031 } 9032 if (ensureVerifyAppsEnabled) { 9033 return true; 9034 } 9035 // Check if the developer does not want package verification for ADB installs 9036 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9037 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9038 return false; 9039 } 9040 } 9041 9042 if (ensureVerifyAppsEnabled) { 9043 return true; 9044 } 9045 9046 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9047 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9048 } 9049 9050 @Override 9051 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9052 throws RemoteException { 9053 mContext.enforceCallingOrSelfPermission( 9054 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9055 "Only intentfilter verification agents can verify applications"); 9056 9057 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9058 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9059 Binder.getCallingUid(), verificationCode, failedDomains); 9060 msg.arg1 = id; 9061 msg.obj = response; 9062 mHandler.sendMessage(msg); 9063 } 9064 9065 @Override 9066 public int getIntentVerificationStatus(String packageName, int userId) { 9067 synchronized (mPackages) { 9068 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9069 } 9070 } 9071 9072 @Override 9073 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9074 boolean result = false; 9075 synchronized (mPackages) { 9076 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9077 } 9078 scheduleWritePackageRestrictionsLocked(userId); 9079 return result; 9080 } 9081 9082 @Override 9083 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9084 synchronized (mPackages) { 9085 return mSettings.getIntentFilterVerificationsLPr(packageName); 9086 } 9087 } 9088 9089 @Override 9090 public List<IntentFilter> getAllIntentFilters(String packageName) { 9091 if (TextUtils.isEmpty(packageName)) { 9092 return Collections.<IntentFilter>emptyList(); 9093 } 9094 synchronized (mPackages) { 9095 PackageParser.Package pkg = mPackages.get(packageName); 9096 if (pkg == null || pkg.activities == null) { 9097 return Collections.<IntentFilter>emptyList(); 9098 } 9099 final int count = pkg.activities.size(); 9100 ArrayList<IntentFilter> result = new ArrayList<>(); 9101 for (int n=0; n<count; n++) { 9102 PackageParser.Activity activity = pkg.activities.get(n); 9103 if (activity.intents != null || activity.intents.size() > 0) { 9104 result.addAll(activity.intents); 9105 } 9106 } 9107 return result; 9108 } 9109 } 9110 9111 @Override 9112 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9113 synchronized (mPackages) { 9114 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9115 } 9116 } 9117 9118 @Override 9119 public String getDefaultBrowserPackageName(int userId) { 9120 synchronized (mPackages) { 9121 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9122 } 9123 } 9124 9125 /** 9126 * Get the "allow unknown sources" setting. 9127 * 9128 * @return the current "allow unknown sources" setting 9129 */ 9130 private int getUnknownSourcesSettings() { 9131 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9132 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9133 -1); 9134 } 9135 9136 @Override 9137 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9138 final int uid = Binder.getCallingUid(); 9139 // writer 9140 synchronized (mPackages) { 9141 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9142 if (targetPackageSetting == null) { 9143 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9144 } 9145 9146 PackageSetting installerPackageSetting; 9147 if (installerPackageName != null) { 9148 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9149 if (installerPackageSetting == null) { 9150 throw new IllegalArgumentException("Unknown installer package: " 9151 + installerPackageName); 9152 } 9153 } else { 9154 installerPackageSetting = null; 9155 } 9156 9157 Signature[] callerSignature; 9158 Object obj = mSettings.getUserIdLPr(uid); 9159 if (obj != null) { 9160 if (obj instanceof SharedUserSetting) { 9161 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9162 } else if (obj instanceof PackageSetting) { 9163 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9164 } else { 9165 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9166 } 9167 } else { 9168 throw new SecurityException("Unknown calling uid " + uid); 9169 } 9170 9171 // Verify: can't set installerPackageName to a package that is 9172 // not signed with the same cert as the caller. 9173 if (installerPackageSetting != null) { 9174 if (compareSignatures(callerSignature, 9175 installerPackageSetting.signatures.mSignatures) 9176 != PackageManager.SIGNATURE_MATCH) { 9177 throw new SecurityException( 9178 "Caller does not have same cert as new installer package " 9179 + installerPackageName); 9180 } 9181 } 9182 9183 // Verify: if target already has an installer package, it must 9184 // be signed with the same cert as the caller. 9185 if (targetPackageSetting.installerPackageName != null) { 9186 PackageSetting setting = mSettings.mPackages.get( 9187 targetPackageSetting.installerPackageName); 9188 // If the currently set package isn't valid, then it's always 9189 // okay to change it. 9190 if (setting != null) { 9191 if (compareSignatures(callerSignature, 9192 setting.signatures.mSignatures) 9193 != PackageManager.SIGNATURE_MATCH) { 9194 throw new SecurityException( 9195 "Caller does not have same cert as old installer package " 9196 + targetPackageSetting.installerPackageName); 9197 } 9198 } 9199 } 9200 9201 // Okay! 9202 targetPackageSetting.installerPackageName = installerPackageName; 9203 scheduleWriteSettingsLocked(); 9204 } 9205 } 9206 9207 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9208 // Queue up an async operation since the package installation may take a little while. 9209 mHandler.post(new Runnable() { 9210 public void run() { 9211 mHandler.removeCallbacks(this); 9212 // Result object to be returned 9213 PackageInstalledInfo res = new PackageInstalledInfo(); 9214 res.returnCode = currentStatus; 9215 res.uid = -1; 9216 res.pkg = null; 9217 res.removedInfo = new PackageRemovedInfo(); 9218 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9219 args.doPreInstall(res.returnCode); 9220 synchronized (mInstallLock) { 9221 installPackageLI(args, res); 9222 } 9223 args.doPostInstall(res.returnCode, res.uid); 9224 } 9225 9226 // A restore should be performed at this point if (a) the install 9227 // succeeded, (b) the operation is not an update, and (c) the new 9228 // package has not opted out of backup participation. 9229 final boolean update = res.removedInfo.removedPackage != null; 9230 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9231 boolean doRestore = !update 9232 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9233 9234 // Set up the post-install work request bookkeeping. This will be used 9235 // and cleaned up by the post-install event handling regardless of whether 9236 // there's a restore pass performed. Token values are >= 1. 9237 int token; 9238 if (mNextInstallToken < 0) mNextInstallToken = 1; 9239 token = mNextInstallToken++; 9240 9241 PostInstallData data = new PostInstallData(args, res); 9242 mRunningInstalls.put(token, data); 9243 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9244 9245 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9246 // Pass responsibility to the Backup Manager. It will perform a 9247 // restore if appropriate, then pass responsibility back to the 9248 // Package Manager to run the post-install observer callbacks 9249 // and broadcasts. 9250 IBackupManager bm = IBackupManager.Stub.asInterface( 9251 ServiceManager.getService(Context.BACKUP_SERVICE)); 9252 if (bm != null) { 9253 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9254 + " to BM for possible restore"); 9255 try { 9256 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9257 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9258 } else { 9259 doRestore = false; 9260 } 9261 } catch (RemoteException e) { 9262 // can't happen; the backup manager is local 9263 } catch (Exception e) { 9264 Slog.e(TAG, "Exception trying to enqueue restore", e); 9265 doRestore = false; 9266 } 9267 } else { 9268 Slog.e(TAG, "Backup Manager not found!"); 9269 doRestore = false; 9270 } 9271 } 9272 9273 if (!doRestore) { 9274 // No restore possible, or the Backup Manager was mysteriously not 9275 // available -- just fire the post-install work request directly. 9276 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9277 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9278 mHandler.sendMessage(msg); 9279 } 9280 } 9281 }); 9282 } 9283 9284 private abstract class HandlerParams { 9285 private static final int MAX_RETRIES = 4; 9286 9287 /** 9288 * Number of times startCopy() has been attempted and had a non-fatal 9289 * error. 9290 */ 9291 private int mRetries = 0; 9292 9293 /** User handle for the user requesting the information or installation. */ 9294 private final UserHandle mUser; 9295 9296 HandlerParams(UserHandle user) { 9297 mUser = user; 9298 } 9299 9300 UserHandle getUser() { 9301 return mUser; 9302 } 9303 9304 final boolean startCopy() { 9305 boolean res; 9306 try { 9307 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9308 9309 if (++mRetries > MAX_RETRIES) { 9310 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9311 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9312 handleServiceError(); 9313 return false; 9314 } else { 9315 handleStartCopy(); 9316 res = true; 9317 } 9318 } catch (RemoteException e) { 9319 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9320 mHandler.sendEmptyMessage(MCS_RECONNECT); 9321 res = false; 9322 } 9323 handleReturnCode(); 9324 return res; 9325 } 9326 9327 final void serviceError() { 9328 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9329 handleServiceError(); 9330 handleReturnCode(); 9331 } 9332 9333 abstract void handleStartCopy() throws RemoteException; 9334 abstract void handleServiceError(); 9335 abstract void handleReturnCode(); 9336 } 9337 9338 class MeasureParams extends HandlerParams { 9339 private final PackageStats mStats; 9340 private boolean mSuccess; 9341 9342 private final IPackageStatsObserver mObserver; 9343 9344 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9345 super(new UserHandle(stats.userHandle)); 9346 mObserver = observer; 9347 mStats = stats; 9348 } 9349 9350 @Override 9351 public String toString() { 9352 return "MeasureParams{" 9353 + Integer.toHexString(System.identityHashCode(this)) 9354 + " " + mStats.packageName + "}"; 9355 } 9356 9357 @Override 9358 void handleStartCopy() throws RemoteException { 9359 synchronized (mInstallLock) { 9360 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9361 } 9362 9363 if (mSuccess) { 9364 final boolean mounted; 9365 if (Environment.isExternalStorageEmulated()) { 9366 mounted = true; 9367 } else { 9368 final String status = Environment.getExternalStorageState(); 9369 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9370 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9371 } 9372 9373 if (mounted) { 9374 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9375 9376 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9377 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9378 9379 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9380 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9381 9382 // Always subtract cache size, since it's a subdirectory 9383 mStats.externalDataSize -= mStats.externalCacheSize; 9384 9385 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9386 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9387 9388 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9389 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9390 } 9391 } 9392 } 9393 9394 @Override 9395 void handleReturnCode() { 9396 if (mObserver != null) { 9397 try { 9398 mObserver.onGetStatsCompleted(mStats, mSuccess); 9399 } catch (RemoteException e) { 9400 Slog.i(TAG, "Observer no longer exists."); 9401 } 9402 } 9403 } 9404 9405 @Override 9406 void handleServiceError() { 9407 Slog.e(TAG, "Could not measure application " + mStats.packageName 9408 + " external storage"); 9409 } 9410 } 9411 9412 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9413 throws RemoteException { 9414 long result = 0; 9415 for (File path : paths) { 9416 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9417 } 9418 return result; 9419 } 9420 9421 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9422 for (File path : paths) { 9423 try { 9424 mcs.clearDirectory(path.getAbsolutePath()); 9425 } catch (RemoteException e) { 9426 } 9427 } 9428 } 9429 9430 static class OriginInfo { 9431 /** 9432 * Location where install is coming from, before it has been 9433 * copied/renamed into place. This could be a single monolithic APK 9434 * file, or a cluster directory. This location may be untrusted. 9435 */ 9436 final File file; 9437 final String cid; 9438 9439 /** 9440 * Flag indicating that {@link #file} or {@link #cid} has already been 9441 * staged, meaning downstream users don't need to defensively copy the 9442 * contents. 9443 */ 9444 final boolean staged; 9445 9446 /** 9447 * Flag indicating that {@link #file} or {@link #cid} is an already 9448 * installed app that is being moved. 9449 */ 9450 final boolean existing; 9451 9452 final String resolvedPath; 9453 final File resolvedFile; 9454 9455 static OriginInfo fromNothing() { 9456 return new OriginInfo(null, null, false, false); 9457 } 9458 9459 static OriginInfo fromUntrustedFile(File file) { 9460 return new OriginInfo(file, null, false, false); 9461 } 9462 9463 static OriginInfo fromExistingFile(File file) { 9464 return new OriginInfo(file, null, false, true); 9465 } 9466 9467 static OriginInfo fromStagedFile(File file) { 9468 return new OriginInfo(file, null, true, false); 9469 } 9470 9471 static OriginInfo fromStagedContainer(String cid) { 9472 return new OriginInfo(null, cid, true, false); 9473 } 9474 9475 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9476 this.file = file; 9477 this.cid = cid; 9478 this.staged = staged; 9479 this.existing = existing; 9480 9481 if (cid != null) { 9482 resolvedPath = PackageHelper.getSdDir(cid); 9483 resolvedFile = new File(resolvedPath); 9484 } else if (file != null) { 9485 resolvedPath = file.getAbsolutePath(); 9486 resolvedFile = file; 9487 } else { 9488 resolvedPath = null; 9489 resolvedFile = null; 9490 } 9491 } 9492 } 9493 9494 class InstallParams extends HandlerParams { 9495 final OriginInfo origin; 9496 final IPackageInstallObserver2 observer; 9497 int installFlags; 9498 final String installerPackageName; 9499 final String volumeUuid; 9500 final VerificationParams verificationParams; 9501 private InstallArgs mArgs; 9502 private int mRet; 9503 final String packageAbiOverride; 9504 9505 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9506 String installerPackageName, String volumeUuid, 9507 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9508 super(user); 9509 this.origin = origin; 9510 this.observer = observer; 9511 this.installFlags = installFlags; 9512 this.installerPackageName = installerPackageName; 9513 this.volumeUuid = volumeUuid; 9514 this.verificationParams = verificationParams; 9515 this.packageAbiOverride = packageAbiOverride; 9516 } 9517 9518 @Override 9519 public String toString() { 9520 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9521 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9522 } 9523 9524 public ManifestDigest getManifestDigest() { 9525 if (verificationParams == null) { 9526 return null; 9527 } 9528 return verificationParams.getManifestDigest(); 9529 } 9530 9531 private int installLocationPolicy(PackageInfoLite pkgLite) { 9532 String packageName = pkgLite.packageName; 9533 int installLocation = pkgLite.installLocation; 9534 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9535 // reader 9536 synchronized (mPackages) { 9537 PackageParser.Package pkg = mPackages.get(packageName); 9538 if (pkg != null) { 9539 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9540 // Check for downgrading. 9541 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9542 try { 9543 checkDowngrade(pkg, pkgLite); 9544 } catch (PackageManagerException e) { 9545 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9546 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9547 } 9548 } 9549 // Check for updated system application. 9550 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9551 if (onSd) { 9552 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9553 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9554 } 9555 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9556 } else { 9557 if (onSd) { 9558 // Install flag overrides everything. 9559 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9560 } 9561 // If current upgrade specifies particular preference 9562 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9563 // Application explicitly specified internal. 9564 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9565 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9566 // App explictly prefers external. Let policy decide 9567 } else { 9568 // Prefer previous location 9569 if (isExternal(pkg)) { 9570 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9571 } 9572 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9573 } 9574 } 9575 } else { 9576 // Invalid install. Return error code 9577 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9578 } 9579 } 9580 } 9581 // All the special cases have been taken care of. 9582 // Return result based on recommended install location. 9583 if (onSd) { 9584 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9585 } 9586 return pkgLite.recommendedInstallLocation; 9587 } 9588 9589 /* 9590 * Invoke remote method to get package information and install 9591 * location values. Override install location based on default 9592 * policy if needed and then create install arguments based 9593 * on the install location. 9594 */ 9595 public void handleStartCopy() throws RemoteException { 9596 int ret = PackageManager.INSTALL_SUCCEEDED; 9597 9598 // If we're already staged, we've firmly committed to an install location 9599 if (origin.staged) { 9600 if (origin.file != null) { 9601 installFlags |= PackageManager.INSTALL_INTERNAL; 9602 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9603 } else if (origin.cid != null) { 9604 installFlags |= PackageManager.INSTALL_EXTERNAL; 9605 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9606 } else { 9607 throw new IllegalStateException("Invalid stage location"); 9608 } 9609 } 9610 9611 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9612 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9613 9614 PackageInfoLite pkgLite = null; 9615 9616 if (onInt && onSd) { 9617 // Check if both bits are set. 9618 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9619 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9620 } else { 9621 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9622 packageAbiOverride); 9623 9624 /* 9625 * If we have too little free space, try to free cache 9626 * before giving up. 9627 */ 9628 if (!origin.staged && pkgLite.recommendedInstallLocation 9629 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9630 // TODO: focus freeing disk space on the target device 9631 final StorageManager storage = StorageManager.from(mContext); 9632 final long lowThreshold = storage.getStorageLowBytes( 9633 Environment.getDataDirectory()); 9634 9635 final long sizeBytes = mContainerService.calculateInstalledSize( 9636 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9637 9638 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9639 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9640 installFlags, packageAbiOverride); 9641 } 9642 9643 /* 9644 * The cache free must have deleted the file we 9645 * downloaded to install. 9646 * 9647 * TODO: fix the "freeCache" call to not delete 9648 * the file we care about. 9649 */ 9650 if (pkgLite.recommendedInstallLocation 9651 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9652 pkgLite.recommendedInstallLocation 9653 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9654 } 9655 } 9656 } 9657 9658 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9659 int loc = pkgLite.recommendedInstallLocation; 9660 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9661 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9662 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9663 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9664 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9665 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9666 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9667 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9668 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9669 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9670 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9671 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9672 } else { 9673 // Override with defaults if needed. 9674 loc = installLocationPolicy(pkgLite); 9675 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9676 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9677 } else if (!onSd && !onInt) { 9678 // Override install location with flags 9679 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9680 // Set the flag to install on external media. 9681 installFlags |= PackageManager.INSTALL_EXTERNAL; 9682 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9683 } else { 9684 // Make sure the flag for installing on external 9685 // media is unset 9686 installFlags |= PackageManager.INSTALL_INTERNAL; 9687 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9688 } 9689 } 9690 } 9691 } 9692 9693 final InstallArgs args = createInstallArgs(this); 9694 mArgs = args; 9695 9696 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9697 /* 9698 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9699 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9700 */ 9701 int userIdentifier = getUser().getIdentifier(); 9702 if (userIdentifier == UserHandle.USER_ALL 9703 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9704 userIdentifier = UserHandle.USER_OWNER; 9705 } 9706 9707 /* 9708 * Determine if we have any installed package verifiers. If we 9709 * do, then we'll defer to them to verify the packages. 9710 */ 9711 final int requiredUid = mRequiredVerifierPackage == null ? -1 9712 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9713 if (!origin.existing && requiredUid != -1 9714 && isVerificationEnabled(userIdentifier, installFlags)) { 9715 final Intent verification = new Intent( 9716 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9717 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9718 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9719 PACKAGE_MIME_TYPE); 9720 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9721 9722 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9723 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9724 0 /* TODO: Which userId? */); 9725 9726 if (DEBUG_VERIFY) { 9727 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9728 + verification.toString() + " with " + pkgLite.verifiers.length 9729 + " optional verifiers"); 9730 } 9731 9732 final int verificationId = mPendingVerificationToken++; 9733 9734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9735 9736 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9737 installerPackageName); 9738 9739 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9740 installFlags); 9741 9742 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9743 pkgLite.packageName); 9744 9745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9746 pkgLite.versionCode); 9747 9748 if (verificationParams != null) { 9749 if (verificationParams.getVerificationURI() != null) { 9750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9751 verificationParams.getVerificationURI()); 9752 } 9753 if (verificationParams.getOriginatingURI() != null) { 9754 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9755 verificationParams.getOriginatingURI()); 9756 } 9757 if (verificationParams.getReferrer() != null) { 9758 verification.putExtra(Intent.EXTRA_REFERRER, 9759 verificationParams.getReferrer()); 9760 } 9761 if (verificationParams.getOriginatingUid() >= 0) { 9762 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9763 verificationParams.getOriginatingUid()); 9764 } 9765 if (verificationParams.getInstallerUid() >= 0) { 9766 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9767 verificationParams.getInstallerUid()); 9768 } 9769 } 9770 9771 final PackageVerificationState verificationState = new PackageVerificationState( 9772 requiredUid, args); 9773 9774 mPendingVerification.append(verificationId, verificationState); 9775 9776 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9777 receivers, verificationState); 9778 9779 /* 9780 * If any sufficient verifiers were listed in the package 9781 * manifest, attempt to ask them. 9782 */ 9783 if (sufficientVerifiers != null) { 9784 final int N = sufficientVerifiers.size(); 9785 if (N == 0) { 9786 Slog.i(TAG, "Additional verifiers required, but none installed."); 9787 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9788 } else { 9789 for (int i = 0; i < N; i++) { 9790 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9791 9792 final Intent sufficientIntent = new Intent(verification); 9793 sufficientIntent.setComponent(verifierComponent); 9794 9795 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9796 } 9797 } 9798 } 9799 9800 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9801 mRequiredVerifierPackage, receivers); 9802 if (ret == PackageManager.INSTALL_SUCCEEDED 9803 && mRequiredVerifierPackage != null) { 9804 /* 9805 * Send the intent to the required verification agent, 9806 * but only start the verification timeout after the 9807 * target BroadcastReceivers have run. 9808 */ 9809 verification.setComponent(requiredVerifierComponent); 9810 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9811 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9812 new BroadcastReceiver() { 9813 @Override 9814 public void onReceive(Context context, Intent intent) { 9815 final Message msg = mHandler 9816 .obtainMessage(CHECK_PENDING_VERIFICATION); 9817 msg.arg1 = verificationId; 9818 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9819 } 9820 }, null, 0, null, null); 9821 9822 /* 9823 * We don't want the copy to proceed until verification 9824 * succeeds, so null out this field. 9825 */ 9826 mArgs = null; 9827 } 9828 } else { 9829 /* 9830 * No package verification is enabled, so immediately start 9831 * the remote call to initiate copy using temporary file. 9832 */ 9833 ret = args.copyApk(mContainerService, true); 9834 } 9835 } 9836 9837 mRet = ret; 9838 } 9839 9840 @Override 9841 void handleReturnCode() { 9842 // If mArgs is null, then MCS couldn't be reached. When it 9843 // reconnects, it will try again to install. At that point, this 9844 // will succeed. 9845 if (mArgs != null) { 9846 processPendingInstall(mArgs, mRet); 9847 } 9848 } 9849 9850 @Override 9851 void handleServiceError() { 9852 mArgs = createInstallArgs(this); 9853 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9854 } 9855 9856 public boolean isForwardLocked() { 9857 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9858 } 9859 } 9860 9861 /** 9862 * Used during creation of InstallArgs 9863 * 9864 * @param installFlags package installation flags 9865 * @return true if should be installed on external storage 9866 */ 9867 private static boolean installOnExternalAsec(int installFlags) { 9868 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9869 return false; 9870 } 9871 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9872 return true; 9873 } 9874 return false; 9875 } 9876 9877 /** 9878 * Used during creation of InstallArgs 9879 * 9880 * @param installFlags package installation flags 9881 * @return true if should be installed as forward locked 9882 */ 9883 private static boolean installForwardLocked(int installFlags) { 9884 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9885 } 9886 9887 private InstallArgs createInstallArgs(InstallParams params) { 9888 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9889 return new AsecInstallArgs(params); 9890 } else { 9891 return new FileInstallArgs(params); 9892 } 9893 } 9894 9895 /** 9896 * Create args that describe an existing installed package. Typically used 9897 * when cleaning up old installs, or used as a move source. 9898 */ 9899 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9900 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9901 final boolean isInAsec; 9902 if (installOnExternalAsec(installFlags)) { 9903 /* Apps on SD card are always in ASEC containers. */ 9904 isInAsec = true; 9905 } else if (installForwardLocked(installFlags) 9906 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9907 /* 9908 * Forward-locked apps are only in ASEC containers if they're the 9909 * new style 9910 */ 9911 isInAsec = true; 9912 } else { 9913 isInAsec = false; 9914 } 9915 9916 if (isInAsec) { 9917 return new AsecInstallArgs(codePath, instructionSets, 9918 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9919 } else { 9920 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9921 instructionSets); 9922 } 9923 } 9924 9925 static abstract class InstallArgs { 9926 /** @see InstallParams#origin */ 9927 final OriginInfo origin; 9928 9929 final IPackageInstallObserver2 observer; 9930 // Always refers to PackageManager flags only 9931 final int installFlags; 9932 final String installerPackageName; 9933 final String volumeUuid; 9934 final ManifestDigest manifestDigest; 9935 final UserHandle user; 9936 final String abiOverride; 9937 9938 // The list of instruction sets supported by this app. This is currently 9939 // only used during the rmdex() phase to clean up resources. We can get rid of this 9940 // if we move dex files under the common app path. 9941 /* nullable */ String[] instructionSets; 9942 9943 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9944 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9945 UserHandle user, String[] instructionSets, String abiOverride) { 9946 this.origin = origin; 9947 this.installFlags = installFlags; 9948 this.observer = observer; 9949 this.installerPackageName = installerPackageName; 9950 this.volumeUuid = volumeUuid; 9951 this.manifestDigest = manifestDigest; 9952 this.user = user; 9953 this.instructionSets = instructionSets; 9954 this.abiOverride = abiOverride; 9955 } 9956 9957 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9958 abstract int doPreInstall(int status); 9959 9960 /** 9961 * Rename package into final resting place. All paths on the given 9962 * scanned package should be updated to reflect the rename. 9963 */ 9964 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9965 abstract int doPostInstall(int status, int uid); 9966 9967 /** @see PackageSettingBase#codePathString */ 9968 abstract String getCodePath(); 9969 /** @see PackageSettingBase#resourcePathString */ 9970 abstract String getResourcePath(); 9971 abstract String getLegacyNativeLibraryPath(); 9972 9973 // Need installer lock especially for dex file removal. 9974 abstract void cleanUpResourcesLI(); 9975 abstract boolean doPostDeleteLI(boolean delete); 9976 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9977 9978 /** 9979 * Called before the source arguments are copied. This is used mostly 9980 * for MoveParams when it needs to read the source file to put it in the 9981 * destination. 9982 */ 9983 int doPreCopy() { 9984 return PackageManager.INSTALL_SUCCEEDED; 9985 } 9986 9987 /** 9988 * Called after the source arguments are copied. This is used mostly for 9989 * MoveParams when it needs to read the source file to put it in the 9990 * destination. 9991 * 9992 * @return 9993 */ 9994 int doPostCopy(int uid) { 9995 return PackageManager.INSTALL_SUCCEEDED; 9996 } 9997 9998 protected boolean isFwdLocked() { 9999 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10000 } 10001 10002 protected boolean isExternalAsec() { 10003 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10004 } 10005 10006 UserHandle getUser() { 10007 return user; 10008 } 10009 } 10010 10011 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10012 if (!allCodePaths.isEmpty()) { 10013 if (instructionSets == null) { 10014 throw new IllegalStateException("instructionSet == null"); 10015 } 10016 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10017 for (String codePath : allCodePaths) { 10018 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10019 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10020 if (retCode < 0) { 10021 Slog.w(TAG, "Couldn't remove dex file for package: " 10022 + " at location " + codePath + ", retcode=" + retCode); 10023 // we don't consider this to be a failure of the core package deletion 10024 } 10025 } 10026 } 10027 } 10028 } 10029 10030 /** 10031 * Logic to handle installation of non-ASEC applications, including copying 10032 * and renaming logic. 10033 */ 10034 class FileInstallArgs extends InstallArgs { 10035 private File codeFile; 10036 private File resourceFile; 10037 private File legacyNativeLibraryPath; 10038 10039 // Example topology: 10040 // /data/app/com.example/base.apk 10041 // /data/app/com.example/split_foo.apk 10042 // /data/app/com.example/lib/arm/libfoo.so 10043 // /data/app/com.example/lib/arm64/libfoo.so 10044 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10045 10046 /** New install */ 10047 FileInstallArgs(InstallParams params) { 10048 super(params.origin, params.observer, params.installFlags, 10049 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10050 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10051 if (isFwdLocked()) { 10052 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10053 } 10054 } 10055 10056 /** Existing install */ 10057 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10058 String[] instructionSets) { 10059 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10060 this.codeFile = (codePath != null) ? new File(codePath) : null; 10061 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10062 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10063 new File(legacyNativeLibraryPath) : null; 10064 } 10065 10066 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10067 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10068 isFwdLocked(), abiOverride); 10069 10070 final StorageManager storage = StorageManager.from(mContext); 10071 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10072 } 10073 10074 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10075 if (origin.staged) { 10076 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10077 codeFile = origin.file; 10078 resourceFile = origin.file; 10079 return PackageManager.INSTALL_SUCCEEDED; 10080 } 10081 10082 try { 10083 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10084 codeFile = tempDir; 10085 resourceFile = tempDir; 10086 } catch (IOException e) { 10087 Slog.w(TAG, "Failed to create copy file: " + e); 10088 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10089 } 10090 10091 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10092 @Override 10093 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10094 if (!FileUtils.isValidExtFilename(name)) { 10095 throw new IllegalArgumentException("Invalid filename: " + name); 10096 } 10097 try { 10098 final File file = new File(codeFile, name); 10099 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10100 O_RDWR | O_CREAT, 0644); 10101 Os.chmod(file.getAbsolutePath(), 0644); 10102 return new ParcelFileDescriptor(fd); 10103 } catch (ErrnoException e) { 10104 throw new RemoteException("Failed to open: " + e.getMessage()); 10105 } 10106 } 10107 }; 10108 10109 int ret = PackageManager.INSTALL_SUCCEEDED; 10110 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10111 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10112 Slog.e(TAG, "Failed to copy package"); 10113 return ret; 10114 } 10115 10116 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10117 NativeLibraryHelper.Handle handle = null; 10118 try { 10119 handle = NativeLibraryHelper.Handle.create(codeFile); 10120 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10121 abiOverride); 10122 } catch (IOException e) { 10123 Slog.e(TAG, "Copying native libraries failed", e); 10124 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10125 } finally { 10126 IoUtils.closeQuietly(handle); 10127 } 10128 10129 return ret; 10130 } 10131 10132 int doPreInstall(int status) { 10133 if (status != PackageManager.INSTALL_SUCCEEDED) { 10134 cleanUp(); 10135 } 10136 return status; 10137 } 10138 10139 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10140 if (status != PackageManager.INSTALL_SUCCEEDED) { 10141 cleanUp(); 10142 return false; 10143 } else { 10144 final File targetDir = codeFile.getParentFile(); 10145 final File beforeCodeFile = codeFile; 10146 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10147 10148 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10149 try { 10150 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10151 } catch (ErrnoException e) { 10152 Slog.d(TAG, "Failed to rename", e); 10153 return false; 10154 } 10155 10156 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10157 Slog.d(TAG, "Failed to restorecon"); 10158 return false; 10159 } 10160 10161 // Reflect the rename internally 10162 codeFile = afterCodeFile; 10163 resourceFile = afterCodeFile; 10164 10165 // Reflect the rename in scanned details 10166 pkg.codePath = afterCodeFile.getAbsolutePath(); 10167 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10168 pkg.baseCodePath); 10169 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10170 pkg.splitCodePaths); 10171 10172 // Reflect the rename in app info 10173 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10174 pkg.applicationInfo.setCodePath(pkg.codePath); 10175 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10176 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10177 pkg.applicationInfo.setResourcePath(pkg.codePath); 10178 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10179 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10180 10181 return true; 10182 } 10183 } 10184 10185 int doPostInstall(int status, int uid) { 10186 if (status != PackageManager.INSTALL_SUCCEEDED) { 10187 cleanUp(); 10188 } 10189 return status; 10190 } 10191 10192 @Override 10193 String getCodePath() { 10194 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10195 } 10196 10197 @Override 10198 String getResourcePath() { 10199 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10200 } 10201 10202 @Override 10203 String getLegacyNativeLibraryPath() { 10204 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10205 } 10206 10207 private boolean cleanUp() { 10208 if (codeFile == null || !codeFile.exists()) { 10209 return false; 10210 } 10211 10212 if (codeFile.isDirectory()) { 10213 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10214 } else { 10215 codeFile.delete(); 10216 } 10217 10218 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10219 resourceFile.delete(); 10220 } 10221 10222 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10223 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10224 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10225 } 10226 legacyNativeLibraryPath.delete(); 10227 } 10228 10229 return true; 10230 } 10231 10232 void cleanUpResourcesLI() { 10233 // Try enumerating all code paths before deleting 10234 List<String> allCodePaths = Collections.EMPTY_LIST; 10235 if (codeFile != null && codeFile.exists()) { 10236 try { 10237 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10238 allCodePaths = pkg.getAllCodePaths(); 10239 } catch (PackageParserException e) { 10240 // Ignored; we tried our best 10241 } 10242 } 10243 10244 cleanUp(); 10245 removeDexFiles(allCodePaths, instructionSets); 10246 } 10247 10248 boolean doPostDeleteLI(boolean delete) { 10249 // XXX err, shouldn't we respect the delete flag? 10250 cleanUpResourcesLI(); 10251 return true; 10252 } 10253 } 10254 10255 private boolean isAsecExternal(String cid) { 10256 final String asecPath = PackageHelper.getSdFilesystem(cid); 10257 return !asecPath.startsWith(mAsecInternalPath); 10258 } 10259 10260 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10261 PackageManagerException { 10262 if (copyRet < 0) { 10263 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10264 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10265 throw new PackageManagerException(copyRet, message); 10266 } 10267 } 10268 } 10269 10270 /** 10271 * Extract the MountService "container ID" from the full code path of an 10272 * .apk. 10273 */ 10274 static String cidFromCodePath(String fullCodePath) { 10275 int eidx = fullCodePath.lastIndexOf("/"); 10276 String subStr1 = fullCodePath.substring(0, eidx); 10277 int sidx = subStr1.lastIndexOf("/"); 10278 return subStr1.substring(sidx+1, eidx); 10279 } 10280 10281 /** 10282 * Logic to handle installation of ASEC applications, including copying and 10283 * renaming logic. 10284 */ 10285 class AsecInstallArgs extends InstallArgs { 10286 static final String RES_FILE_NAME = "pkg.apk"; 10287 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10288 10289 String cid; 10290 String packagePath; 10291 String resourcePath; 10292 String legacyNativeLibraryDir; 10293 10294 /** New install */ 10295 AsecInstallArgs(InstallParams params) { 10296 super(params.origin, params.observer, params.installFlags, 10297 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10298 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10299 } 10300 10301 /** Existing install */ 10302 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10303 boolean isExternal, boolean isForwardLocked) { 10304 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10305 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10306 instructionSets, null); 10307 // Hackily pretend we're still looking at a full code path 10308 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10309 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10310 } 10311 10312 // Extract cid from fullCodePath 10313 int eidx = fullCodePath.lastIndexOf("/"); 10314 String subStr1 = fullCodePath.substring(0, eidx); 10315 int sidx = subStr1.lastIndexOf("/"); 10316 cid = subStr1.substring(sidx+1, eidx); 10317 setMountPath(subStr1); 10318 } 10319 10320 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10321 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10322 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10323 instructionSets, null); 10324 this.cid = cid; 10325 setMountPath(PackageHelper.getSdDir(cid)); 10326 } 10327 10328 void createCopyFile() { 10329 cid = mInstallerService.allocateExternalStageCidLegacy(); 10330 } 10331 10332 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10333 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10334 abiOverride); 10335 10336 final File target; 10337 if (isExternalAsec()) { 10338 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10339 } else { 10340 target = Environment.getDataDirectory(); 10341 } 10342 10343 final StorageManager storage = StorageManager.from(mContext); 10344 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10345 } 10346 10347 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10348 if (origin.staged) { 10349 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10350 cid = origin.cid; 10351 setMountPath(PackageHelper.getSdDir(cid)); 10352 return PackageManager.INSTALL_SUCCEEDED; 10353 } 10354 10355 if (temp) { 10356 createCopyFile(); 10357 } else { 10358 /* 10359 * Pre-emptively destroy the container since it's destroyed if 10360 * copying fails due to it existing anyway. 10361 */ 10362 PackageHelper.destroySdDir(cid); 10363 } 10364 10365 final String newMountPath = imcs.copyPackageToContainer( 10366 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10367 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10368 10369 if (newMountPath != null) { 10370 setMountPath(newMountPath); 10371 return PackageManager.INSTALL_SUCCEEDED; 10372 } else { 10373 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10374 } 10375 } 10376 10377 @Override 10378 String getCodePath() { 10379 return packagePath; 10380 } 10381 10382 @Override 10383 String getResourcePath() { 10384 return resourcePath; 10385 } 10386 10387 @Override 10388 String getLegacyNativeLibraryPath() { 10389 return legacyNativeLibraryDir; 10390 } 10391 10392 int doPreInstall(int status) { 10393 if (status != PackageManager.INSTALL_SUCCEEDED) { 10394 // Destroy container 10395 PackageHelper.destroySdDir(cid); 10396 } else { 10397 boolean mounted = PackageHelper.isContainerMounted(cid); 10398 if (!mounted) { 10399 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10400 Process.SYSTEM_UID); 10401 if (newMountPath != null) { 10402 setMountPath(newMountPath); 10403 } else { 10404 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10405 } 10406 } 10407 } 10408 return status; 10409 } 10410 10411 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10412 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10413 String newMountPath = null; 10414 if (PackageHelper.isContainerMounted(cid)) { 10415 // Unmount the container 10416 if (!PackageHelper.unMountSdDir(cid)) { 10417 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10418 return false; 10419 } 10420 } 10421 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10422 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10423 " which might be stale. Will try to clean up."); 10424 // Clean up the stale container and proceed to recreate. 10425 if (!PackageHelper.destroySdDir(newCacheId)) { 10426 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10427 return false; 10428 } 10429 // Successfully cleaned up stale container. Try to rename again. 10430 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10431 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10432 + " inspite of cleaning it up."); 10433 return false; 10434 } 10435 } 10436 if (!PackageHelper.isContainerMounted(newCacheId)) { 10437 Slog.w(TAG, "Mounting container " + newCacheId); 10438 newMountPath = PackageHelper.mountSdDir(newCacheId, 10439 getEncryptKey(), Process.SYSTEM_UID); 10440 } else { 10441 newMountPath = PackageHelper.getSdDir(newCacheId); 10442 } 10443 if (newMountPath == null) { 10444 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10445 return false; 10446 } 10447 Log.i(TAG, "Succesfully renamed " + cid + 10448 " to " + newCacheId + 10449 " at new path: " + newMountPath); 10450 cid = newCacheId; 10451 10452 final File beforeCodeFile = new File(packagePath); 10453 setMountPath(newMountPath); 10454 final File afterCodeFile = new File(packagePath); 10455 10456 // Reflect the rename in scanned details 10457 pkg.codePath = afterCodeFile.getAbsolutePath(); 10458 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10459 pkg.baseCodePath); 10460 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10461 pkg.splitCodePaths); 10462 10463 // Reflect the rename in app info 10464 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10465 pkg.applicationInfo.setCodePath(pkg.codePath); 10466 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10467 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10468 pkg.applicationInfo.setResourcePath(pkg.codePath); 10469 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10470 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10471 10472 return true; 10473 } 10474 10475 private void setMountPath(String mountPath) { 10476 final File mountFile = new File(mountPath); 10477 10478 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10479 if (monolithicFile.exists()) { 10480 packagePath = monolithicFile.getAbsolutePath(); 10481 if (isFwdLocked()) { 10482 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10483 } else { 10484 resourcePath = packagePath; 10485 } 10486 } else { 10487 packagePath = mountFile.getAbsolutePath(); 10488 resourcePath = packagePath; 10489 } 10490 10491 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10492 } 10493 10494 int doPostInstall(int status, int uid) { 10495 if (status != PackageManager.INSTALL_SUCCEEDED) { 10496 cleanUp(); 10497 } else { 10498 final int groupOwner; 10499 final String protectedFile; 10500 if (isFwdLocked()) { 10501 groupOwner = UserHandle.getSharedAppGid(uid); 10502 protectedFile = RES_FILE_NAME; 10503 } else { 10504 groupOwner = -1; 10505 protectedFile = null; 10506 } 10507 10508 if (uid < Process.FIRST_APPLICATION_UID 10509 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10510 Slog.e(TAG, "Failed to finalize " + cid); 10511 PackageHelper.destroySdDir(cid); 10512 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10513 } 10514 10515 boolean mounted = PackageHelper.isContainerMounted(cid); 10516 if (!mounted) { 10517 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10518 } 10519 } 10520 return status; 10521 } 10522 10523 private void cleanUp() { 10524 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10525 10526 // Destroy secure container 10527 PackageHelper.destroySdDir(cid); 10528 } 10529 10530 private List<String> getAllCodePaths() { 10531 final File codeFile = new File(getCodePath()); 10532 if (codeFile != null && codeFile.exists()) { 10533 try { 10534 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10535 return pkg.getAllCodePaths(); 10536 } catch (PackageParserException e) { 10537 // Ignored; we tried our best 10538 } 10539 } 10540 return Collections.EMPTY_LIST; 10541 } 10542 10543 void cleanUpResourcesLI() { 10544 // Enumerate all code paths before deleting 10545 cleanUpResourcesLI(getAllCodePaths()); 10546 } 10547 10548 private void cleanUpResourcesLI(List<String> allCodePaths) { 10549 cleanUp(); 10550 removeDexFiles(allCodePaths, instructionSets); 10551 } 10552 10553 10554 10555 String getPackageName() { 10556 return getAsecPackageName(cid); 10557 } 10558 10559 boolean doPostDeleteLI(boolean delete) { 10560 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10561 final List<String> allCodePaths = getAllCodePaths(); 10562 boolean mounted = PackageHelper.isContainerMounted(cid); 10563 if (mounted) { 10564 // Unmount first 10565 if (PackageHelper.unMountSdDir(cid)) { 10566 mounted = false; 10567 } 10568 } 10569 if (!mounted && delete) { 10570 cleanUpResourcesLI(allCodePaths); 10571 } 10572 return !mounted; 10573 } 10574 10575 @Override 10576 int doPreCopy() { 10577 if (isFwdLocked()) { 10578 if (!PackageHelper.fixSdPermissions(cid, 10579 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10580 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10581 } 10582 } 10583 10584 return PackageManager.INSTALL_SUCCEEDED; 10585 } 10586 10587 @Override 10588 int doPostCopy(int uid) { 10589 if (isFwdLocked()) { 10590 if (uid < Process.FIRST_APPLICATION_UID 10591 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10592 RES_FILE_NAME)) { 10593 Slog.e(TAG, "Failed to finalize " + cid); 10594 PackageHelper.destroySdDir(cid); 10595 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10596 } 10597 } 10598 10599 return PackageManager.INSTALL_SUCCEEDED; 10600 } 10601 } 10602 10603 static String getAsecPackageName(String packageCid) { 10604 int idx = packageCid.lastIndexOf("-"); 10605 if (idx == -1) { 10606 return packageCid; 10607 } 10608 return packageCid.substring(0, idx); 10609 } 10610 10611 // Utility method used to create code paths based on package name and available index. 10612 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10613 String idxStr = ""; 10614 int idx = 1; 10615 // Fall back to default value of idx=1 if prefix is not 10616 // part of oldCodePath 10617 if (oldCodePath != null) { 10618 String subStr = oldCodePath; 10619 // Drop the suffix right away 10620 if (suffix != null && subStr.endsWith(suffix)) { 10621 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10622 } 10623 // If oldCodePath already contains prefix find out the 10624 // ending index to either increment or decrement. 10625 int sidx = subStr.lastIndexOf(prefix); 10626 if (sidx != -1) { 10627 subStr = subStr.substring(sidx + prefix.length()); 10628 if (subStr != null) { 10629 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10630 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10631 } 10632 try { 10633 idx = Integer.parseInt(subStr); 10634 if (idx <= 1) { 10635 idx++; 10636 } else { 10637 idx--; 10638 } 10639 } catch(NumberFormatException e) { 10640 } 10641 } 10642 } 10643 } 10644 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10645 return prefix + idxStr; 10646 } 10647 10648 private File getNextCodePath(File targetDir, String packageName) { 10649 int suffix = 1; 10650 File result; 10651 do { 10652 result = new File(targetDir, packageName + "-" + suffix); 10653 suffix++; 10654 } while (result.exists()); 10655 return result; 10656 } 10657 10658 // Utility method that returns the relative package path with respect 10659 // to the installation directory. Like say for /data/data/com.test-1.apk 10660 // string com.test-1 is returned. 10661 static String deriveCodePathName(String codePath) { 10662 if (codePath == null) { 10663 return null; 10664 } 10665 final File codeFile = new File(codePath); 10666 final String name = codeFile.getName(); 10667 if (codeFile.isDirectory()) { 10668 return name; 10669 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10670 final int lastDot = name.lastIndexOf('.'); 10671 return name.substring(0, lastDot); 10672 } else { 10673 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10674 return null; 10675 } 10676 } 10677 10678 class PackageInstalledInfo { 10679 String name; 10680 int uid; 10681 // The set of users that originally had this package installed. 10682 int[] origUsers; 10683 // The set of users that now have this package installed. 10684 int[] newUsers; 10685 PackageParser.Package pkg; 10686 int returnCode; 10687 String returnMsg; 10688 PackageRemovedInfo removedInfo; 10689 10690 public void setError(int code, String msg) { 10691 returnCode = code; 10692 returnMsg = msg; 10693 Slog.w(TAG, msg); 10694 } 10695 10696 public void setError(String msg, PackageParserException e) { 10697 returnCode = e.error; 10698 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10699 Slog.w(TAG, msg, e); 10700 } 10701 10702 public void setError(String msg, PackageManagerException e) { 10703 returnCode = e.error; 10704 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10705 Slog.w(TAG, msg, e); 10706 } 10707 10708 // In some error cases we want to convey more info back to the observer 10709 String origPackage; 10710 String origPermission; 10711 } 10712 10713 /* 10714 * Install a non-existing package. 10715 */ 10716 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10717 UserHandle user, String installerPackageName, String volumeUuid, 10718 PackageInstalledInfo res) { 10719 // Remember this for later, in case we need to rollback this install 10720 String pkgName = pkg.packageName; 10721 10722 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10723 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10724 UserHandle.USER_OWNER).exists(); 10725 synchronized(mPackages) { 10726 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10727 // A package with the same name is already installed, though 10728 // it has been renamed to an older name. The package we 10729 // are trying to install should be installed as an update to 10730 // the existing one, but that has not been requested, so bail. 10731 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10732 + " without first uninstalling package running as " 10733 + mSettings.mRenamedPackages.get(pkgName)); 10734 return; 10735 } 10736 if (mPackages.containsKey(pkgName)) { 10737 // Don't allow installation over an existing package with the same name. 10738 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10739 + " without first uninstalling."); 10740 return; 10741 } 10742 } 10743 10744 try { 10745 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10746 System.currentTimeMillis(), user); 10747 10748 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10749 // delete the partially installed application. the data directory will have to be 10750 // restored if it was already existing 10751 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10752 // remove package from internal structures. Note that we want deletePackageX to 10753 // delete the package data and cache directories that it created in 10754 // scanPackageLocked, unless those directories existed before we even tried to 10755 // install. 10756 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10757 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10758 res.removedInfo, true); 10759 } 10760 10761 } catch (PackageManagerException e) { 10762 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10763 } 10764 } 10765 10766 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10767 // Upgrade keysets are being used. Determine if new package has a superset of the 10768 // required keys. 10769 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10771 for (int i = 0; i < upgradeKeySets.length; i++) { 10772 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10773 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10774 return true; 10775 } 10776 } 10777 return false; 10778 } 10779 10780 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10781 UserHandle user, String installerPackageName, String volumeUuid, 10782 PackageInstalledInfo res) { 10783 PackageParser.Package oldPackage; 10784 String pkgName = pkg.packageName; 10785 int[] allUsers; 10786 boolean[] perUserInstalled; 10787 10788 // First find the old package info and check signatures 10789 synchronized(mPackages) { 10790 oldPackage = mPackages.get(pkgName); 10791 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10792 PackageSetting ps = mSettings.mPackages.get(pkgName); 10793 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10794 // default to original signature matching 10795 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10796 != PackageManager.SIGNATURE_MATCH) { 10797 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10798 "New package has a different signature: " + pkgName); 10799 return; 10800 } 10801 } else { 10802 if(!checkUpgradeKeySetLP(ps, pkg)) { 10803 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10804 "New package not signed by keys specified by upgrade-keysets: " 10805 + pkgName); 10806 return; 10807 } 10808 } 10809 10810 // In case of rollback, remember per-user/profile install state 10811 allUsers = sUserManager.getUserIds(); 10812 perUserInstalled = new boolean[allUsers.length]; 10813 for (int i = 0; i < allUsers.length; i++) { 10814 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10815 } 10816 } 10817 10818 boolean sysPkg = (isSystemApp(oldPackage)); 10819 if (sysPkg) { 10820 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10821 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10822 } else { 10823 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10824 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10825 } 10826 } 10827 10828 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10829 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10830 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10831 String volumeUuid, PackageInstalledInfo res) { 10832 String pkgName = deletedPackage.packageName; 10833 boolean deletedPkg = true; 10834 boolean updatedSettings = false; 10835 10836 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10837 + deletedPackage); 10838 long origUpdateTime; 10839 if (pkg.mExtras != null) { 10840 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10841 } else { 10842 origUpdateTime = 0; 10843 } 10844 10845 // First delete the existing package while retaining the data directory 10846 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10847 res.removedInfo, true)) { 10848 // If the existing package wasn't successfully deleted 10849 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10850 deletedPkg = false; 10851 } else { 10852 // Successfully deleted the old package; proceed with replace. 10853 10854 // If deleted package lived in a container, give users a chance to 10855 // relinquish resources before killing. 10856 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10857 if (DEBUG_INSTALL) { 10858 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10859 } 10860 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10861 final ArrayList<String> pkgList = new ArrayList<String>(1); 10862 pkgList.add(deletedPackage.applicationInfo.packageName); 10863 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10864 } 10865 10866 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10867 try { 10868 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10869 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10870 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10871 perUserInstalled, res, user); 10872 updatedSettings = true; 10873 } catch (PackageManagerException e) { 10874 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10875 } 10876 } 10877 10878 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10879 // remove package from internal structures. Note that we want deletePackageX to 10880 // delete the package data and cache directories that it created in 10881 // scanPackageLocked, unless those directories existed before we even tried to 10882 // install. 10883 if(updatedSettings) { 10884 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10885 deletePackageLI( 10886 pkgName, null, true, allUsers, perUserInstalled, 10887 PackageManager.DELETE_KEEP_DATA, 10888 res.removedInfo, true); 10889 } 10890 // Since we failed to install the new package we need to restore the old 10891 // package that we deleted. 10892 if (deletedPkg) { 10893 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10894 File restoreFile = new File(deletedPackage.codePath); 10895 // Parse old package 10896 boolean oldExternal = isExternal(deletedPackage); 10897 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10898 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10899 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10900 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10901 try { 10902 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10903 } catch (PackageManagerException e) { 10904 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10905 + e.getMessage()); 10906 return; 10907 } 10908 // Restore of old package succeeded. Update permissions. 10909 // writer 10910 synchronized (mPackages) { 10911 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10912 UPDATE_PERMISSIONS_ALL); 10913 // can downgrade to reader 10914 mSettings.writeLPr(); 10915 } 10916 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10917 } 10918 } 10919 } 10920 10921 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10922 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10923 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10924 String volumeUuid, PackageInstalledInfo res) { 10925 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10926 + ", old=" + deletedPackage); 10927 boolean disabledSystem = false; 10928 boolean updatedSettings = false; 10929 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10930 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10931 != 0) { 10932 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10933 } 10934 String packageName = deletedPackage.packageName; 10935 if (packageName == null) { 10936 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10937 "Attempt to delete null packageName."); 10938 return; 10939 } 10940 PackageParser.Package oldPkg; 10941 PackageSetting oldPkgSetting; 10942 // reader 10943 synchronized (mPackages) { 10944 oldPkg = mPackages.get(packageName); 10945 oldPkgSetting = mSettings.mPackages.get(packageName); 10946 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10947 (oldPkgSetting == null)) { 10948 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10949 "Couldn't find package:" + packageName + " information"); 10950 return; 10951 } 10952 } 10953 10954 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10955 10956 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10957 res.removedInfo.removedPackage = packageName; 10958 // Remove existing system package 10959 removePackageLI(oldPkgSetting, true); 10960 // writer 10961 synchronized (mPackages) { 10962 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10963 if (!disabledSystem && deletedPackage != null) { 10964 // We didn't need to disable the .apk as a current system package, 10965 // which means we are replacing another update that is already 10966 // installed. We need to make sure to delete the older one's .apk. 10967 res.removedInfo.args = createInstallArgsForExisting(0, 10968 deletedPackage.applicationInfo.getCodePath(), 10969 deletedPackage.applicationInfo.getResourcePath(), 10970 deletedPackage.applicationInfo.nativeLibraryRootDir, 10971 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10972 } else { 10973 res.removedInfo.args = null; 10974 } 10975 } 10976 10977 // Successfully disabled the old package. Now proceed with re-installation 10978 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 10979 10980 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10981 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10982 10983 PackageParser.Package newPackage = null; 10984 try { 10985 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10986 if (newPackage.mExtras != null) { 10987 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10988 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10989 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10990 10991 // is the update attempting to change shared user? that isn't going to work... 10992 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10993 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10994 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10995 + " to " + newPkgSetting.sharedUser); 10996 updatedSettings = true; 10997 } 10998 } 10999 11000 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11001 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11002 perUserInstalled, res, user); 11003 updatedSettings = true; 11004 } 11005 11006 } catch (PackageManagerException e) { 11007 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11008 } 11009 11010 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11011 // Re installation failed. Restore old information 11012 // Remove new pkg information 11013 if (newPackage != null) { 11014 removeInstalledPackageLI(newPackage, true); 11015 } 11016 // Add back the old system package 11017 try { 11018 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11019 } catch (PackageManagerException e) { 11020 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11021 } 11022 // Restore the old system information in Settings 11023 synchronized (mPackages) { 11024 if (disabledSystem) { 11025 mSettings.enableSystemPackageLPw(packageName); 11026 } 11027 if (updatedSettings) { 11028 mSettings.setInstallerPackageName(packageName, 11029 oldPkgSetting.installerPackageName); 11030 } 11031 mSettings.writeLPr(); 11032 } 11033 } 11034 } 11035 11036 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11037 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11038 UserHandle user) { 11039 String pkgName = newPackage.packageName; 11040 synchronized (mPackages) { 11041 //write settings. the installStatus will be incomplete at this stage. 11042 //note that the new package setting would have already been 11043 //added to mPackages. It hasn't been persisted yet. 11044 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11045 mSettings.writeLPr(); 11046 } 11047 11048 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11049 11050 synchronized (mPackages) { 11051 updatePermissionsLPw(newPackage.packageName, newPackage, 11052 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11053 ? UPDATE_PERMISSIONS_ALL : 0)); 11054 // For system-bundled packages, we assume that installing an upgraded version 11055 // of the package implies that the user actually wants to run that new code, 11056 // so we enable the package. 11057 PackageSetting ps = mSettings.mPackages.get(pkgName); 11058 if (ps != null) { 11059 if (isSystemApp(newPackage)) { 11060 // NB: implicit assumption that system package upgrades apply to all users 11061 if (DEBUG_INSTALL) { 11062 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11063 } 11064 if (res.origUsers != null) { 11065 for (int userHandle : res.origUsers) { 11066 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11067 userHandle, installerPackageName); 11068 } 11069 } 11070 // Also convey the prior install/uninstall state 11071 if (allUsers != null && perUserInstalled != null) { 11072 for (int i = 0; i < allUsers.length; i++) { 11073 if (DEBUG_INSTALL) { 11074 Slog.d(TAG, " user " + allUsers[i] 11075 + " => " + perUserInstalled[i]); 11076 } 11077 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11078 } 11079 // these install state changes will be persisted in the 11080 // upcoming call to mSettings.writeLPr(). 11081 } 11082 } 11083 // It's implied that when a user requests installation, they want the app to be 11084 // installed and enabled. 11085 int userId = user.getIdentifier(); 11086 if (userId != UserHandle.USER_ALL) { 11087 ps.setInstalled(true, userId); 11088 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11089 } 11090 } 11091 res.name = pkgName; 11092 res.uid = newPackage.applicationInfo.uid; 11093 res.pkg = newPackage; 11094 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11095 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11096 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11097 //to update install status 11098 mSettings.writeLPr(); 11099 } 11100 } 11101 11102 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11103 final int installFlags = args.installFlags; 11104 final String installerPackageName = args.installerPackageName; 11105 final String volumeUuid = args.volumeUuid; 11106 final File tmpPackageFile = new File(args.getCodePath()); 11107 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11108 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11109 || (args.volumeUuid != null)); 11110 boolean replace = false; 11111 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11112 // Result object to be returned 11113 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11114 11115 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11116 // Retrieve PackageSettings and parse package 11117 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11118 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11119 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11120 PackageParser pp = new PackageParser(); 11121 pp.setSeparateProcesses(mSeparateProcesses); 11122 pp.setDisplayMetrics(mMetrics); 11123 11124 final PackageParser.Package pkg; 11125 try { 11126 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11127 } catch (PackageParserException e) { 11128 res.setError("Failed parse during installPackageLI", e); 11129 return; 11130 } 11131 11132 // Mark that we have an install time CPU ABI override. 11133 pkg.cpuAbiOverride = args.abiOverride; 11134 11135 String pkgName = res.name = pkg.packageName; 11136 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11137 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11138 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11139 return; 11140 } 11141 } 11142 11143 try { 11144 pp.collectCertificates(pkg, parseFlags); 11145 pp.collectManifestDigest(pkg); 11146 } catch (PackageParserException e) { 11147 res.setError("Failed collect during installPackageLI", e); 11148 return; 11149 } 11150 11151 /* If the installer passed in a manifest digest, compare it now. */ 11152 if (args.manifestDigest != null) { 11153 if (DEBUG_INSTALL) { 11154 final String parsedManifest = pkg.manifestDigest == null ? "null" 11155 : pkg.manifestDigest.toString(); 11156 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11157 + parsedManifest); 11158 } 11159 11160 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11161 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11162 return; 11163 } 11164 } else if (DEBUG_INSTALL) { 11165 final String parsedManifest = pkg.manifestDigest == null 11166 ? "null" : pkg.manifestDigest.toString(); 11167 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11168 } 11169 11170 // Get rid of all references to package scan path via parser. 11171 pp = null; 11172 String oldCodePath = null; 11173 boolean systemApp = false; 11174 synchronized (mPackages) { 11175 // Check if installing already existing package 11176 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11177 String oldName = mSettings.mRenamedPackages.get(pkgName); 11178 if (pkg.mOriginalPackages != null 11179 && pkg.mOriginalPackages.contains(oldName) 11180 && mPackages.containsKey(oldName)) { 11181 // This package is derived from an original package, 11182 // and this device has been updating from that original 11183 // name. We must continue using the original name, so 11184 // rename the new package here. 11185 pkg.setPackageName(oldName); 11186 pkgName = pkg.packageName; 11187 replace = true; 11188 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11189 + oldName + " pkgName=" + pkgName); 11190 } else if (mPackages.containsKey(pkgName)) { 11191 // This package, under its official name, already exists 11192 // on the device; we should replace it. 11193 replace = true; 11194 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11195 } 11196 } 11197 11198 PackageSetting ps = mSettings.mPackages.get(pkgName); 11199 if (ps != null) { 11200 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11201 11202 // Quick sanity check that we're signed correctly if updating; 11203 // we'll check this again later when scanning, but we want to 11204 // bail early here before tripping over redefined permissions. 11205 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11206 try { 11207 verifySignaturesLP(ps, pkg); 11208 } catch (PackageManagerException e) { 11209 res.setError(e.error, e.getMessage()); 11210 return; 11211 } 11212 } else { 11213 if (!checkUpgradeKeySetLP(ps, pkg)) { 11214 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11215 + pkg.packageName + " upgrade keys do not match the " 11216 + "previously installed version"); 11217 return; 11218 } 11219 } 11220 11221 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11222 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11223 systemApp = (ps.pkg.applicationInfo.flags & 11224 ApplicationInfo.FLAG_SYSTEM) != 0; 11225 } 11226 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11227 } 11228 11229 // Check whether the newly-scanned package wants to define an already-defined perm 11230 int N = pkg.permissions.size(); 11231 for (int i = N-1; i >= 0; i--) { 11232 PackageParser.Permission perm = pkg.permissions.get(i); 11233 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11234 if (bp != null) { 11235 // If the defining package is signed with our cert, it's okay. This 11236 // also includes the "updating the same package" case, of course. 11237 // "updating same package" could also involve key-rotation. 11238 final boolean sigsOk; 11239 if (!bp.sourcePackage.equals(pkg.packageName) 11240 || !(bp.packageSetting instanceof PackageSetting) 11241 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11242 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11243 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11244 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11245 } else { 11246 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11247 } 11248 if (!sigsOk) { 11249 // If the owning package is the system itself, we log but allow 11250 // install to proceed; we fail the install on all other permission 11251 // redefinitions. 11252 if (!bp.sourcePackage.equals("android")) { 11253 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11254 + pkg.packageName + " attempting to redeclare permission " 11255 + perm.info.name + " already owned by " + bp.sourcePackage); 11256 res.origPermission = perm.info.name; 11257 res.origPackage = bp.sourcePackage; 11258 return; 11259 } else { 11260 Slog.w(TAG, "Package " + pkg.packageName 11261 + " attempting to redeclare system permission " 11262 + perm.info.name + "; ignoring new declaration"); 11263 pkg.permissions.remove(i); 11264 } 11265 } 11266 } 11267 } 11268 11269 } 11270 11271 if (systemApp && onExternal) { 11272 // Disable updates to system apps on sdcard 11273 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11274 "Cannot install updates to system apps on sdcard"); 11275 return; 11276 } 11277 11278 // If app directory is not writable, dexopt will be called after the rename 11279 if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11280 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11281 scanFlags |= SCAN_NO_DEX; 11282 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11283 int result = mPackageDexOptimizer 11284 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11285 false /* defer */, false /* inclDependencies */); 11286 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11287 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11288 return; 11289 } 11290 } 11291 11292 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11293 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11294 return; 11295 } 11296 11297 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11298 11299 if (replace) { 11300 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11301 installerPackageName, volumeUuid, res); 11302 } else { 11303 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11304 args.user, installerPackageName, volumeUuid, res); 11305 } 11306 synchronized (mPackages) { 11307 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11308 if (ps != null) { 11309 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11310 } 11311 } 11312 } 11313 11314 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11315 if (mIntentFilterVerifierComponent == null) { 11316 Slog.d(TAG, "No IntentFilter verification will not be done as " 11317 + "there is no IntentFilterVerifier available!"); 11318 return; 11319 } 11320 11321 final int verifierUid = getPackageUid( 11322 mIntentFilterVerifierComponent.getPackageName(), 11323 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11324 11325 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11326 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11327 msg.obj = pkg; 11328 msg.arg1 = userId; 11329 msg.arg2 = verifierUid; 11330 11331 mHandler.sendMessage(msg); 11332 } 11333 11334 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11335 PackageParser.Package pkg) { 11336 int size = pkg.activities.size(); 11337 if (size == 0) { 11338 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11339 return; 11340 } 11341 11342 final boolean hasDomainURLs = hasDomainURLs(pkg); 11343 if (!hasDomainURLs) { 11344 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11345 return; 11346 } 11347 11348 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11349 + " Activities needs verification ..."); 11350 11351 final int verificationId = mIntentFilterVerificationToken++; 11352 int count = 0; 11353 final String packageName = pkg.packageName; 11354 ArrayList<String> allHosts = new ArrayList<>(); 11355 11356 synchronized (mPackages) { 11357 for (PackageParser.Activity a : pkg.activities) { 11358 for (ActivityIntentInfo filter : a.intents) { 11359 boolean needsFilterVerification = filter.needsVerification(); 11360 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11361 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11362 mIntentFilterVerifier.addOneIntentFilterVerification( 11363 verifierUid, userId, verificationId, filter, packageName); 11364 count++; 11365 } else if (!needsFilterVerification) { 11366 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11367 if (hasValidDomains(filter)) { 11368 ArrayList<String> hosts = filter.getHostsList(); 11369 if (hosts.size() > 0) { 11370 allHosts.addAll(hosts); 11371 } else { 11372 if (allHosts.isEmpty()) { 11373 allHosts.add("*"); 11374 } 11375 } 11376 } 11377 } else { 11378 Slog.d(TAG, "Verification already done for IntentFilter:" 11379 + filter.toString()); 11380 } 11381 } 11382 } 11383 } 11384 11385 if (count > 0) { 11386 mIntentFilterVerifier.startVerifications(userId); 11387 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11388 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11389 } else { 11390 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11391 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11392 packageName, allHosts) != null) { 11393 scheduleWriteSettingsLocked(); 11394 } 11395 } 11396 } 11397 11398 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11399 final ComponentName cn = filter.activity.getComponentName(); 11400 final String packageName = cn.getPackageName(); 11401 11402 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11403 packageName); 11404 if (ivi == null) { 11405 return true; 11406 } 11407 int status = ivi.getStatus(); 11408 switch (status) { 11409 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11410 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11411 return true; 11412 11413 default: 11414 // Nothing to do 11415 return false; 11416 } 11417 } 11418 11419 private static boolean isMultiArch(PackageSetting ps) { 11420 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11421 } 11422 11423 private static boolean isMultiArch(ApplicationInfo info) { 11424 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11425 } 11426 11427 private static boolean isExternal(PackageParser.Package pkg) { 11428 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11429 } 11430 11431 private static boolean isExternal(PackageSetting ps) { 11432 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11433 } 11434 11435 private static boolean isExternal(ApplicationInfo info) { 11436 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11437 } 11438 11439 private static boolean isSystemApp(PackageParser.Package pkg) { 11440 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11441 } 11442 11443 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11444 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11445 } 11446 11447 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11448 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11449 } 11450 11451 private static boolean isSystemApp(PackageSetting ps) { 11452 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11453 } 11454 11455 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11456 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11457 } 11458 11459 private int packageFlagsToInstallFlags(PackageSetting ps) { 11460 int installFlags = 0; 11461 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11462 // This existing package was an external ASEC install when we have 11463 // the external flag without a UUID 11464 installFlags |= PackageManager.INSTALL_EXTERNAL; 11465 } 11466 if (ps.isForwardLocked()) { 11467 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11468 } 11469 return installFlags; 11470 } 11471 11472 private void deleteTempPackageFiles() { 11473 final FilenameFilter filter = new FilenameFilter() { 11474 public boolean accept(File dir, String name) { 11475 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11476 } 11477 }; 11478 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11479 file.delete(); 11480 } 11481 } 11482 11483 @Override 11484 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11485 int flags) { 11486 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11487 flags); 11488 } 11489 11490 @Override 11491 public void deletePackage(final String packageName, 11492 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11493 mContext.enforceCallingOrSelfPermission( 11494 android.Manifest.permission.DELETE_PACKAGES, null); 11495 final int uid = Binder.getCallingUid(); 11496 if (UserHandle.getUserId(uid) != userId) { 11497 mContext.enforceCallingPermission( 11498 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11499 "deletePackage for user " + userId); 11500 } 11501 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11502 try { 11503 observer.onPackageDeleted(packageName, 11504 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11505 } catch (RemoteException re) { 11506 } 11507 return; 11508 } 11509 11510 boolean uninstallBlocked = false; 11511 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11512 int[] users = sUserManager.getUserIds(); 11513 for (int i = 0; i < users.length; ++i) { 11514 if (getBlockUninstallForUser(packageName, users[i])) { 11515 uninstallBlocked = true; 11516 break; 11517 } 11518 } 11519 } else { 11520 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11521 } 11522 if (uninstallBlocked) { 11523 try { 11524 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11525 null); 11526 } catch (RemoteException re) { 11527 } 11528 return; 11529 } 11530 11531 if (DEBUG_REMOVE) { 11532 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11533 } 11534 // Queue up an async operation since the package deletion may take a little while. 11535 mHandler.post(new Runnable() { 11536 public void run() { 11537 mHandler.removeCallbacks(this); 11538 final int returnCode = deletePackageX(packageName, userId, flags); 11539 if (observer != null) { 11540 try { 11541 observer.onPackageDeleted(packageName, returnCode, null); 11542 } catch (RemoteException e) { 11543 Log.i(TAG, "Observer no longer exists."); 11544 } //end catch 11545 } //end if 11546 } //end run 11547 }); 11548 } 11549 11550 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11551 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11552 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11553 try { 11554 if (dpm != null) { 11555 if (dpm.isDeviceOwner(packageName)) { 11556 return true; 11557 } 11558 int[] users; 11559 if (userId == UserHandle.USER_ALL) { 11560 users = sUserManager.getUserIds(); 11561 } else { 11562 users = new int[]{userId}; 11563 } 11564 for (int i = 0; i < users.length; ++i) { 11565 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11566 return true; 11567 } 11568 } 11569 } 11570 } catch (RemoteException e) { 11571 } 11572 return false; 11573 } 11574 11575 /** 11576 * This method is an internal method that could be get invoked either 11577 * to delete an installed package or to clean up a failed installation. 11578 * After deleting an installed package, a broadcast is sent to notify any 11579 * listeners that the package has been installed. For cleaning up a failed 11580 * installation, the broadcast is not necessary since the package's 11581 * installation wouldn't have sent the initial broadcast either 11582 * The key steps in deleting a package are 11583 * deleting the package information in internal structures like mPackages, 11584 * deleting the packages base directories through installd 11585 * updating mSettings to reflect current status 11586 * persisting settings for later use 11587 * sending a broadcast if necessary 11588 */ 11589 private int deletePackageX(String packageName, int userId, int flags) { 11590 final PackageRemovedInfo info = new PackageRemovedInfo(); 11591 final boolean res; 11592 11593 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11594 ? UserHandle.ALL : new UserHandle(userId); 11595 11596 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11597 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11598 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11599 } 11600 11601 boolean removedForAllUsers = false; 11602 boolean systemUpdate = false; 11603 11604 // for the uninstall-updates case and restricted profiles, remember the per- 11605 // userhandle installed state 11606 int[] allUsers; 11607 boolean[] perUserInstalled; 11608 synchronized (mPackages) { 11609 PackageSetting ps = mSettings.mPackages.get(packageName); 11610 allUsers = sUserManager.getUserIds(); 11611 perUserInstalled = new boolean[allUsers.length]; 11612 for (int i = 0; i < allUsers.length; i++) { 11613 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11614 } 11615 } 11616 11617 synchronized (mInstallLock) { 11618 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11619 res = deletePackageLI(packageName, removeForUser, 11620 true, allUsers, perUserInstalled, 11621 flags | REMOVE_CHATTY, info, true); 11622 systemUpdate = info.isRemovedPackageSystemUpdate; 11623 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11624 removedForAllUsers = true; 11625 } 11626 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11627 + " removedForAllUsers=" + removedForAllUsers); 11628 } 11629 11630 if (res) { 11631 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11632 11633 // If the removed package was a system update, the old system package 11634 // was re-enabled; we need to broadcast this information 11635 if (systemUpdate) { 11636 Bundle extras = new Bundle(1); 11637 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11638 ? info.removedAppId : info.uid); 11639 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11640 11641 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11642 extras, null, null, null); 11643 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11644 extras, null, null, null); 11645 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11646 null, packageName, null, null); 11647 } 11648 } 11649 // Force a gc here. 11650 Runtime.getRuntime().gc(); 11651 // Delete the resources here after sending the broadcast to let 11652 // other processes clean up before deleting resources. 11653 if (info.args != null) { 11654 synchronized (mInstallLock) { 11655 info.args.doPostDeleteLI(true); 11656 } 11657 } 11658 11659 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11660 } 11661 11662 static class PackageRemovedInfo { 11663 String removedPackage; 11664 int uid = -1; 11665 int removedAppId = -1; 11666 int[] removedUsers = null; 11667 boolean isRemovedPackageSystemUpdate = false; 11668 // Clean up resources deleted packages. 11669 InstallArgs args = null; 11670 11671 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11672 Bundle extras = new Bundle(1); 11673 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11674 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11675 if (replacing) { 11676 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11677 } 11678 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11679 if (removedPackage != null) { 11680 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11681 extras, null, null, removedUsers); 11682 if (fullRemove && !replacing) { 11683 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11684 extras, null, null, removedUsers); 11685 } 11686 } 11687 if (removedAppId >= 0) { 11688 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11689 removedUsers); 11690 } 11691 } 11692 } 11693 11694 /* 11695 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11696 * flag is not set, the data directory is removed as well. 11697 * make sure this flag is set for partially installed apps. If not its meaningless to 11698 * delete a partially installed application. 11699 */ 11700 private void removePackageDataLI(PackageSetting ps, 11701 int[] allUserHandles, boolean[] perUserInstalled, 11702 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11703 String packageName = ps.name; 11704 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11705 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11706 // Retrieve object to delete permissions for shared user later on 11707 final PackageSetting deletedPs; 11708 // reader 11709 synchronized (mPackages) { 11710 deletedPs = mSettings.mPackages.get(packageName); 11711 if (outInfo != null) { 11712 outInfo.removedPackage = packageName; 11713 outInfo.removedUsers = deletedPs != null 11714 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11715 : null; 11716 } 11717 } 11718 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11719 removeDataDirsLI(ps.volumeUuid, packageName); 11720 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11721 } 11722 // writer 11723 synchronized (mPackages) { 11724 if (deletedPs != null) { 11725 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11726 if (outInfo != null) { 11727 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11728 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11729 } 11730 updatePermissionsLPw(deletedPs.name, null, 0); 11731 if (deletedPs.sharedUser != null) { 11732 // Remove permissions associated with package. Since runtime 11733 // permissions are per user we have to kill the removed package 11734 // or packages running under the shared user of the removed 11735 // package if revoking the permissions requested only by the removed 11736 // package is successful and this causes a change in gids. 11737 for (int userId : UserManagerService.getInstance().getUserIds()) { 11738 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11739 userId); 11740 if (userIdToKill == UserHandle.USER_ALL 11741 || userIdToKill >= UserHandle.USER_OWNER) { 11742 // If gids changed for this user, kill all affected packages. 11743 mHandler.post(new Runnable() { 11744 @Override 11745 public void run() { 11746 // This has to happen with no lock held. 11747 killSettingPackagesForUser(deletedPs, userIdToKill, 11748 KILL_APP_REASON_GIDS_CHANGED); 11749 } 11750 }); 11751 break; 11752 } 11753 } 11754 } 11755 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11756 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11757 } 11758 // make sure to preserve per-user disabled state if this removal was just 11759 // a downgrade of a system app to the factory package 11760 if (allUserHandles != null && perUserInstalled != null) { 11761 if (DEBUG_REMOVE) { 11762 Slog.d(TAG, "Propagating install state across downgrade"); 11763 } 11764 for (int i = 0; i < allUserHandles.length; i++) { 11765 if (DEBUG_REMOVE) { 11766 Slog.d(TAG, " user " + allUserHandles[i] 11767 + " => " + perUserInstalled[i]); 11768 } 11769 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11770 } 11771 } 11772 } 11773 // can downgrade to reader 11774 if (writeSettings) { 11775 // Save settings now 11776 mSettings.writeLPr(); 11777 } 11778 } 11779 if (outInfo != null) { 11780 // A user ID was deleted here. Go through all users and remove it 11781 // from KeyStore. 11782 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11783 } 11784 } 11785 11786 static boolean locationIsPrivileged(File path) { 11787 try { 11788 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11789 .getCanonicalPath(); 11790 return path.getCanonicalPath().startsWith(privilegedAppDir); 11791 } catch (IOException e) { 11792 Slog.e(TAG, "Unable to access code path " + path); 11793 } 11794 return false; 11795 } 11796 11797 /* 11798 * Tries to delete system package. 11799 */ 11800 private boolean deleteSystemPackageLI(PackageSetting newPs, 11801 int[] allUserHandles, boolean[] perUserInstalled, 11802 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11803 final boolean applyUserRestrictions 11804 = (allUserHandles != null) && (perUserInstalled != null); 11805 PackageSetting disabledPs = null; 11806 // Confirm if the system package has been updated 11807 // An updated system app can be deleted. This will also have to restore 11808 // the system pkg from system partition 11809 // reader 11810 synchronized (mPackages) { 11811 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11812 } 11813 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11814 + " disabledPs=" + disabledPs); 11815 if (disabledPs == null) { 11816 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11817 return false; 11818 } else if (DEBUG_REMOVE) { 11819 Slog.d(TAG, "Deleting system pkg from data partition"); 11820 } 11821 if (DEBUG_REMOVE) { 11822 if (applyUserRestrictions) { 11823 Slog.d(TAG, "Remembering install states:"); 11824 for (int i = 0; i < allUserHandles.length; i++) { 11825 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11826 } 11827 } 11828 } 11829 // Delete the updated package 11830 outInfo.isRemovedPackageSystemUpdate = true; 11831 if (disabledPs.versionCode < newPs.versionCode) { 11832 // Delete data for downgrades 11833 flags &= ~PackageManager.DELETE_KEEP_DATA; 11834 } else { 11835 // Preserve data by setting flag 11836 flags |= PackageManager.DELETE_KEEP_DATA; 11837 } 11838 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11839 allUserHandles, perUserInstalled, outInfo, writeSettings); 11840 if (!ret) { 11841 return false; 11842 } 11843 // writer 11844 synchronized (mPackages) { 11845 // Reinstate the old system package 11846 mSettings.enableSystemPackageLPw(newPs.name); 11847 // Remove any native libraries from the upgraded package. 11848 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11849 } 11850 // Install the system package 11851 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11852 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11853 if (locationIsPrivileged(disabledPs.codePath)) { 11854 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11855 } 11856 11857 final PackageParser.Package newPkg; 11858 try { 11859 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11860 } catch (PackageManagerException e) { 11861 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11862 return false; 11863 } 11864 11865 // writer 11866 synchronized (mPackages) { 11867 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11868 updatePermissionsLPw(newPkg.packageName, newPkg, 11869 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11870 if (applyUserRestrictions) { 11871 if (DEBUG_REMOVE) { 11872 Slog.d(TAG, "Propagating install state across reinstall"); 11873 } 11874 for (int i = 0; i < allUserHandles.length; i++) { 11875 if (DEBUG_REMOVE) { 11876 Slog.d(TAG, " user " + allUserHandles[i] 11877 + " => " + perUserInstalled[i]); 11878 } 11879 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11880 } 11881 // Regardless of writeSettings we need to ensure that this restriction 11882 // state propagation is persisted 11883 mSettings.writeAllUsersPackageRestrictionsLPr(); 11884 } 11885 // can downgrade to reader here 11886 if (writeSettings) { 11887 mSettings.writeLPr(); 11888 } 11889 } 11890 return true; 11891 } 11892 11893 private boolean deleteInstalledPackageLI(PackageSetting ps, 11894 boolean deleteCodeAndResources, int flags, 11895 int[] allUserHandles, boolean[] perUserInstalled, 11896 PackageRemovedInfo outInfo, boolean writeSettings) { 11897 if (outInfo != null) { 11898 outInfo.uid = ps.appId; 11899 } 11900 11901 // Delete package data from internal structures and also remove data if flag is set 11902 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11903 11904 // Delete application code and resources 11905 if (deleteCodeAndResources && (outInfo != null)) { 11906 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11907 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11908 getAppDexInstructionSets(ps)); 11909 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11910 } 11911 return true; 11912 } 11913 11914 @Override 11915 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11916 int userId) { 11917 mContext.enforceCallingOrSelfPermission( 11918 android.Manifest.permission.DELETE_PACKAGES, null); 11919 synchronized (mPackages) { 11920 PackageSetting ps = mSettings.mPackages.get(packageName); 11921 if (ps == null) { 11922 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11923 return false; 11924 } 11925 if (!ps.getInstalled(userId)) { 11926 // Can't block uninstall for an app that is not installed or enabled. 11927 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11928 return false; 11929 } 11930 ps.setBlockUninstall(blockUninstall, userId); 11931 mSettings.writePackageRestrictionsLPr(userId); 11932 } 11933 return true; 11934 } 11935 11936 @Override 11937 public boolean getBlockUninstallForUser(String packageName, int userId) { 11938 synchronized (mPackages) { 11939 PackageSetting ps = mSettings.mPackages.get(packageName); 11940 if (ps == null) { 11941 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11942 return false; 11943 } 11944 return ps.getBlockUninstall(userId); 11945 } 11946 } 11947 11948 /* 11949 * This method handles package deletion in general 11950 */ 11951 private boolean deletePackageLI(String packageName, UserHandle user, 11952 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11953 int flags, PackageRemovedInfo outInfo, 11954 boolean writeSettings) { 11955 if (packageName == null) { 11956 Slog.w(TAG, "Attempt to delete null packageName."); 11957 return false; 11958 } 11959 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11960 PackageSetting ps; 11961 boolean dataOnly = false; 11962 int removeUser = -1; 11963 int appId = -1; 11964 synchronized (mPackages) { 11965 ps = mSettings.mPackages.get(packageName); 11966 if (ps == null) { 11967 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11968 return false; 11969 } 11970 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11971 && user.getIdentifier() != UserHandle.USER_ALL) { 11972 // The caller is asking that the package only be deleted for a single 11973 // user. To do this, we just mark its uninstalled state and delete 11974 // its data. If this is a system app, we only allow this to happen if 11975 // they have set the special DELETE_SYSTEM_APP which requests different 11976 // semantics than normal for uninstalling system apps. 11977 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11978 ps.setUserState(user.getIdentifier(), 11979 COMPONENT_ENABLED_STATE_DEFAULT, 11980 false, //installed 11981 true, //stopped 11982 true, //notLaunched 11983 false, //hidden 11984 null, null, null, 11985 false, // blockUninstall 11986 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11987 if (!isSystemApp(ps)) { 11988 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11989 // Other user still have this package installed, so all 11990 // we need to do is clear this user's data and save that 11991 // it is uninstalled. 11992 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11993 removeUser = user.getIdentifier(); 11994 appId = ps.appId; 11995 scheduleWritePackageRestrictionsLocked(removeUser); 11996 } else { 11997 // We need to set it back to 'installed' so the uninstall 11998 // broadcasts will be sent correctly. 11999 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12000 ps.setInstalled(true, user.getIdentifier()); 12001 } 12002 } else { 12003 // This is a system app, so we assume that the 12004 // other users still have this package installed, so all 12005 // we need to do is clear this user's data and save that 12006 // it is uninstalled. 12007 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12008 removeUser = user.getIdentifier(); 12009 appId = ps.appId; 12010 scheduleWritePackageRestrictionsLocked(removeUser); 12011 } 12012 } 12013 } 12014 12015 if (removeUser >= 0) { 12016 // From above, we determined that we are deleting this only 12017 // for a single user. Continue the work here. 12018 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12019 if (outInfo != null) { 12020 outInfo.removedPackage = packageName; 12021 outInfo.removedAppId = appId; 12022 outInfo.removedUsers = new int[] {removeUser}; 12023 } 12024 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12025 removeKeystoreDataIfNeeded(removeUser, appId); 12026 schedulePackageCleaning(packageName, removeUser, false); 12027 synchronized (mPackages) { 12028 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12029 scheduleWritePackageRestrictionsLocked(removeUser); 12030 } 12031 } 12032 return true; 12033 } 12034 12035 if (dataOnly) { 12036 // Delete application data first 12037 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12038 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12039 return true; 12040 } 12041 12042 boolean ret = false; 12043 if (isSystemApp(ps)) { 12044 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12045 // When an updated system application is deleted we delete the existing resources as well and 12046 // fall back to existing code in system partition 12047 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12048 flags, outInfo, writeSettings); 12049 } else { 12050 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12051 // Kill application pre-emptively especially for apps on sd. 12052 killApplication(packageName, ps.appId, "uninstall pkg"); 12053 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12054 allUserHandles, perUserInstalled, 12055 outInfo, writeSettings); 12056 } 12057 12058 return ret; 12059 } 12060 12061 private final class ClearStorageConnection implements ServiceConnection { 12062 IMediaContainerService mContainerService; 12063 12064 @Override 12065 public void onServiceConnected(ComponentName name, IBinder service) { 12066 synchronized (this) { 12067 mContainerService = IMediaContainerService.Stub.asInterface(service); 12068 notifyAll(); 12069 } 12070 } 12071 12072 @Override 12073 public void onServiceDisconnected(ComponentName name) { 12074 } 12075 } 12076 12077 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12078 final boolean mounted; 12079 if (Environment.isExternalStorageEmulated()) { 12080 mounted = true; 12081 } else { 12082 final String status = Environment.getExternalStorageState(); 12083 12084 mounted = status.equals(Environment.MEDIA_MOUNTED) 12085 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12086 } 12087 12088 if (!mounted) { 12089 return; 12090 } 12091 12092 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12093 int[] users; 12094 if (userId == UserHandle.USER_ALL) { 12095 users = sUserManager.getUserIds(); 12096 } else { 12097 users = new int[] { userId }; 12098 } 12099 final ClearStorageConnection conn = new ClearStorageConnection(); 12100 if (mContext.bindServiceAsUser( 12101 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12102 try { 12103 for (int curUser : users) { 12104 long timeout = SystemClock.uptimeMillis() + 5000; 12105 synchronized (conn) { 12106 long now = SystemClock.uptimeMillis(); 12107 while (conn.mContainerService == null && now < timeout) { 12108 try { 12109 conn.wait(timeout - now); 12110 } catch (InterruptedException e) { 12111 } 12112 } 12113 } 12114 if (conn.mContainerService == null) { 12115 return; 12116 } 12117 12118 final UserEnvironment userEnv = new UserEnvironment(curUser); 12119 clearDirectory(conn.mContainerService, 12120 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12121 if (allData) { 12122 clearDirectory(conn.mContainerService, 12123 userEnv.buildExternalStorageAppDataDirs(packageName)); 12124 clearDirectory(conn.mContainerService, 12125 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12126 } 12127 } 12128 } finally { 12129 mContext.unbindService(conn); 12130 } 12131 } 12132 } 12133 12134 @Override 12135 public void clearApplicationUserData(final String packageName, 12136 final IPackageDataObserver observer, final int userId) { 12137 mContext.enforceCallingOrSelfPermission( 12138 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12139 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12140 // Queue up an async operation since the package deletion may take a little while. 12141 mHandler.post(new Runnable() { 12142 public void run() { 12143 mHandler.removeCallbacks(this); 12144 final boolean succeeded; 12145 synchronized (mInstallLock) { 12146 succeeded = clearApplicationUserDataLI(packageName, userId); 12147 } 12148 clearExternalStorageDataSync(packageName, userId, true); 12149 if (succeeded) { 12150 // invoke DeviceStorageMonitor's update method to clear any notifications 12151 DeviceStorageMonitorInternal 12152 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12153 if (dsm != null) { 12154 dsm.checkMemory(); 12155 } 12156 } 12157 if(observer != null) { 12158 try { 12159 observer.onRemoveCompleted(packageName, succeeded); 12160 } catch (RemoteException e) { 12161 Log.i(TAG, "Observer no longer exists."); 12162 } 12163 } //end if observer 12164 } //end run 12165 }); 12166 } 12167 12168 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12169 if (packageName == null) { 12170 Slog.w(TAG, "Attempt to delete null packageName."); 12171 return false; 12172 } 12173 12174 // Try finding details about the requested package 12175 PackageParser.Package pkg; 12176 synchronized (mPackages) { 12177 pkg = mPackages.get(packageName); 12178 if (pkg == null) { 12179 final PackageSetting ps = mSettings.mPackages.get(packageName); 12180 if (ps != null) { 12181 pkg = ps.pkg; 12182 } 12183 } 12184 } 12185 12186 if (pkg == null) { 12187 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12188 } 12189 12190 // Always delete data directories for package, even if we found no other 12191 // record of app. This helps users recover from UID mismatches without 12192 // resorting to a full data wipe. 12193 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12194 if (retCode < 0) { 12195 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12196 return false; 12197 } 12198 12199 if (pkg == null) { 12200 return false; 12201 } 12202 12203 if (pkg != null && pkg.applicationInfo != null) { 12204 final int appId = pkg.applicationInfo.uid; 12205 removeKeystoreDataIfNeeded(userId, appId); 12206 } 12207 12208 // Create a native library symlink only if we have native libraries 12209 // and if the native libraries are 32 bit libraries. We do not provide 12210 // this symlink for 64 bit libraries. 12211 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12212 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12213 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12214 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12215 nativeLibPath, userId) < 0) { 12216 Slog.w(TAG, "Failed linking native library dir"); 12217 return false; 12218 } 12219 } 12220 12221 return true; 12222 } 12223 12224 /** 12225 * Remove entries from the keystore daemon. Will only remove it if the 12226 * {@code appId} is valid. 12227 */ 12228 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12229 if (appId < 0) { 12230 return; 12231 } 12232 12233 final KeyStore keyStore = KeyStore.getInstance(); 12234 if (keyStore != null) { 12235 if (userId == UserHandle.USER_ALL) { 12236 for (final int individual : sUserManager.getUserIds()) { 12237 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12238 } 12239 } else { 12240 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12241 } 12242 } else { 12243 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12244 } 12245 } 12246 12247 @Override 12248 public void deleteApplicationCacheFiles(final String packageName, 12249 final IPackageDataObserver observer) { 12250 mContext.enforceCallingOrSelfPermission( 12251 android.Manifest.permission.DELETE_CACHE_FILES, null); 12252 // Queue up an async operation since the package deletion may take a little while. 12253 final int userId = UserHandle.getCallingUserId(); 12254 mHandler.post(new Runnable() { 12255 public void run() { 12256 mHandler.removeCallbacks(this); 12257 final boolean succeded; 12258 synchronized (mInstallLock) { 12259 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12260 } 12261 clearExternalStorageDataSync(packageName, userId, false); 12262 if(observer != null) { 12263 try { 12264 observer.onRemoveCompleted(packageName, succeded); 12265 } catch (RemoteException e) { 12266 Log.i(TAG, "Observer no longer exists."); 12267 } 12268 } //end if observer 12269 } //end run 12270 }); 12271 } 12272 12273 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12274 if (packageName == null) { 12275 Slog.w(TAG, "Attempt to delete null packageName."); 12276 return false; 12277 } 12278 PackageParser.Package p; 12279 synchronized (mPackages) { 12280 p = mPackages.get(packageName); 12281 } 12282 if (p == null) { 12283 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12284 return false; 12285 } 12286 final ApplicationInfo applicationInfo = p.applicationInfo; 12287 if (applicationInfo == null) { 12288 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12289 return false; 12290 } 12291 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12292 if (retCode < 0) { 12293 Slog.w(TAG, "Couldn't remove cache files for package: " 12294 + packageName + " u" + userId); 12295 return false; 12296 } 12297 return true; 12298 } 12299 12300 @Override 12301 public void getPackageSizeInfo(final String packageName, int userHandle, 12302 final IPackageStatsObserver observer) { 12303 mContext.enforceCallingOrSelfPermission( 12304 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12305 if (packageName == null) { 12306 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12307 } 12308 12309 PackageStats stats = new PackageStats(packageName, userHandle); 12310 12311 /* 12312 * Queue up an async operation since the package measurement may take a 12313 * little while. 12314 */ 12315 Message msg = mHandler.obtainMessage(INIT_COPY); 12316 msg.obj = new MeasureParams(stats, observer); 12317 mHandler.sendMessage(msg); 12318 } 12319 12320 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12321 PackageStats pStats) { 12322 if (packageName == null) { 12323 Slog.w(TAG, "Attempt to get size of null packageName."); 12324 return false; 12325 } 12326 PackageParser.Package p; 12327 boolean dataOnly = false; 12328 String libDirRoot = null; 12329 String asecPath = null; 12330 PackageSetting ps = null; 12331 synchronized (mPackages) { 12332 p = mPackages.get(packageName); 12333 ps = mSettings.mPackages.get(packageName); 12334 if(p == null) { 12335 dataOnly = true; 12336 if((ps == null) || (ps.pkg == null)) { 12337 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12338 return false; 12339 } 12340 p = ps.pkg; 12341 } 12342 if (ps != null) { 12343 libDirRoot = ps.legacyNativeLibraryPathString; 12344 } 12345 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12346 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12347 if (secureContainerId != null) { 12348 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12349 } 12350 } 12351 } 12352 String publicSrcDir = null; 12353 if(!dataOnly) { 12354 final ApplicationInfo applicationInfo = p.applicationInfo; 12355 if (applicationInfo == null) { 12356 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12357 return false; 12358 } 12359 if (p.isForwardLocked()) { 12360 publicSrcDir = applicationInfo.getBaseResourcePath(); 12361 } 12362 } 12363 // TODO: extend to measure size of split APKs 12364 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12365 // not just the first level. 12366 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12367 // just the primary. 12368 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12369 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12370 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12371 if (res < 0) { 12372 return false; 12373 } 12374 12375 // Fix-up for forward-locked applications in ASEC containers. 12376 if (!isExternal(p)) { 12377 pStats.codeSize += pStats.externalCodeSize; 12378 pStats.externalCodeSize = 0L; 12379 } 12380 12381 return true; 12382 } 12383 12384 12385 @Override 12386 public void addPackageToPreferred(String packageName) { 12387 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12388 } 12389 12390 @Override 12391 public void removePackageFromPreferred(String packageName) { 12392 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12393 } 12394 12395 @Override 12396 public List<PackageInfo> getPreferredPackages(int flags) { 12397 return new ArrayList<PackageInfo>(); 12398 } 12399 12400 private int getUidTargetSdkVersionLockedLPr(int uid) { 12401 Object obj = mSettings.getUserIdLPr(uid); 12402 if (obj instanceof SharedUserSetting) { 12403 final SharedUserSetting sus = (SharedUserSetting) obj; 12404 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12405 final Iterator<PackageSetting> it = sus.packages.iterator(); 12406 while (it.hasNext()) { 12407 final PackageSetting ps = it.next(); 12408 if (ps.pkg != null) { 12409 int v = ps.pkg.applicationInfo.targetSdkVersion; 12410 if (v < vers) vers = v; 12411 } 12412 } 12413 return vers; 12414 } else if (obj instanceof PackageSetting) { 12415 final PackageSetting ps = (PackageSetting) obj; 12416 if (ps.pkg != null) { 12417 return ps.pkg.applicationInfo.targetSdkVersion; 12418 } 12419 } 12420 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12421 } 12422 12423 @Override 12424 public void addPreferredActivity(IntentFilter filter, int match, 12425 ComponentName[] set, ComponentName activity, int userId) { 12426 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12427 "Adding preferred"); 12428 } 12429 12430 private void addPreferredActivityInternal(IntentFilter filter, int match, 12431 ComponentName[] set, ComponentName activity, boolean always, int userId, 12432 String opname) { 12433 // writer 12434 int callingUid = Binder.getCallingUid(); 12435 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12436 if (filter.countActions() == 0) { 12437 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12438 return; 12439 } 12440 synchronized (mPackages) { 12441 if (mContext.checkCallingOrSelfPermission( 12442 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12443 != PackageManager.PERMISSION_GRANTED) { 12444 if (getUidTargetSdkVersionLockedLPr(callingUid) 12445 < Build.VERSION_CODES.FROYO) { 12446 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12447 + callingUid); 12448 return; 12449 } 12450 mContext.enforceCallingOrSelfPermission( 12451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12452 } 12453 12454 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12455 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12456 + userId + ":"); 12457 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12458 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12459 scheduleWritePackageRestrictionsLocked(userId); 12460 } 12461 } 12462 12463 @Override 12464 public void replacePreferredActivity(IntentFilter filter, int match, 12465 ComponentName[] set, ComponentName activity, int userId) { 12466 if (filter.countActions() != 1) { 12467 throw new IllegalArgumentException( 12468 "replacePreferredActivity expects filter to have only 1 action."); 12469 } 12470 if (filter.countDataAuthorities() != 0 12471 || filter.countDataPaths() != 0 12472 || filter.countDataSchemes() > 1 12473 || filter.countDataTypes() != 0) { 12474 throw new IllegalArgumentException( 12475 "replacePreferredActivity expects filter to have no data authorities, " + 12476 "paths, or types; and at most one scheme."); 12477 } 12478 12479 final int callingUid = Binder.getCallingUid(); 12480 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12481 synchronized (mPackages) { 12482 if (mContext.checkCallingOrSelfPermission( 12483 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12484 != PackageManager.PERMISSION_GRANTED) { 12485 if (getUidTargetSdkVersionLockedLPr(callingUid) 12486 < Build.VERSION_CODES.FROYO) { 12487 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12488 + Binder.getCallingUid()); 12489 return; 12490 } 12491 mContext.enforceCallingOrSelfPermission( 12492 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12493 } 12494 12495 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12496 if (pir != null) { 12497 // Get all of the existing entries that exactly match this filter. 12498 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12499 if (existing != null && existing.size() == 1) { 12500 PreferredActivity cur = existing.get(0); 12501 if (DEBUG_PREFERRED) { 12502 Slog.i(TAG, "Checking replace of preferred:"); 12503 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12504 if (!cur.mPref.mAlways) { 12505 Slog.i(TAG, " -- CUR; not mAlways!"); 12506 } else { 12507 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12508 Slog.i(TAG, " -- CUR: mSet=" 12509 + Arrays.toString(cur.mPref.mSetComponents)); 12510 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12511 Slog.i(TAG, " -- NEW: mMatch=" 12512 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12513 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12514 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12515 } 12516 } 12517 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12518 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12519 && cur.mPref.sameSet(set)) { 12520 // Setting the preferred activity to what it happens to be already 12521 if (DEBUG_PREFERRED) { 12522 Slog.i(TAG, "Replacing with same preferred activity " 12523 + cur.mPref.mShortComponent + " for user " 12524 + userId + ":"); 12525 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12526 } 12527 return; 12528 } 12529 } 12530 12531 if (existing != null) { 12532 if (DEBUG_PREFERRED) { 12533 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12534 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12535 } 12536 for (int i = 0; i < existing.size(); i++) { 12537 PreferredActivity pa = existing.get(i); 12538 if (DEBUG_PREFERRED) { 12539 Slog.i(TAG, "Removing existing preferred activity " 12540 + pa.mPref.mComponent + ":"); 12541 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12542 } 12543 pir.removeFilter(pa); 12544 } 12545 } 12546 } 12547 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12548 "Replacing preferred"); 12549 } 12550 } 12551 12552 @Override 12553 public void clearPackagePreferredActivities(String packageName) { 12554 final int uid = Binder.getCallingUid(); 12555 // writer 12556 synchronized (mPackages) { 12557 PackageParser.Package pkg = mPackages.get(packageName); 12558 if (pkg == null || pkg.applicationInfo.uid != uid) { 12559 if (mContext.checkCallingOrSelfPermission( 12560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12561 != PackageManager.PERMISSION_GRANTED) { 12562 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12563 < Build.VERSION_CODES.FROYO) { 12564 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12565 + Binder.getCallingUid()); 12566 return; 12567 } 12568 mContext.enforceCallingOrSelfPermission( 12569 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12570 } 12571 } 12572 12573 int user = UserHandle.getCallingUserId(); 12574 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12575 scheduleWritePackageRestrictionsLocked(user); 12576 } 12577 } 12578 } 12579 12580 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12581 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12582 ArrayList<PreferredActivity> removed = null; 12583 boolean changed = false; 12584 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12585 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12586 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12587 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12588 continue; 12589 } 12590 Iterator<PreferredActivity> it = pir.filterIterator(); 12591 while (it.hasNext()) { 12592 PreferredActivity pa = it.next(); 12593 // Mark entry for removal only if it matches the package name 12594 // and the entry is of type "always". 12595 if (packageName == null || 12596 (pa.mPref.mComponent.getPackageName().equals(packageName) 12597 && pa.mPref.mAlways)) { 12598 if (removed == null) { 12599 removed = new ArrayList<PreferredActivity>(); 12600 } 12601 removed.add(pa); 12602 } 12603 } 12604 if (removed != null) { 12605 for (int j=0; j<removed.size(); j++) { 12606 PreferredActivity pa = removed.get(j); 12607 pir.removeFilter(pa); 12608 } 12609 changed = true; 12610 } 12611 } 12612 return changed; 12613 } 12614 12615 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12616 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12617 if (userId == UserHandle.USER_ALL) { 12618 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12619 for (int oneUserId : sUserManager.getUserIds()) { 12620 scheduleWritePackageRestrictionsLocked(oneUserId); 12621 } 12622 } else { 12623 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12624 scheduleWritePackageRestrictionsLocked(userId); 12625 } 12626 } 12627 12628 @Override 12629 public void resetPreferredActivities(int userId) { 12630 /* TODO: Actually use userId. Why is it being passed in? */ 12631 mContext.enforceCallingOrSelfPermission( 12632 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12633 // writer 12634 synchronized (mPackages) { 12635 int user = UserHandle.getCallingUserId(); 12636 clearPackagePreferredActivitiesLPw(null, user); 12637 mSettings.readDefaultPreferredAppsLPw(this, user); 12638 scheduleWritePackageRestrictionsLocked(user); 12639 } 12640 } 12641 12642 @Override 12643 public int getPreferredActivities(List<IntentFilter> outFilters, 12644 List<ComponentName> outActivities, String packageName) { 12645 12646 int num = 0; 12647 final int userId = UserHandle.getCallingUserId(); 12648 // reader 12649 synchronized (mPackages) { 12650 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12651 if (pir != null) { 12652 final Iterator<PreferredActivity> it = pir.filterIterator(); 12653 while (it.hasNext()) { 12654 final PreferredActivity pa = it.next(); 12655 if (packageName == null 12656 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12657 && pa.mPref.mAlways)) { 12658 if (outFilters != null) { 12659 outFilters.add(new IntentFilter(pa)); 12660 } 12661 if (outActivities != null) { 12662 outActivities.add(pa.mPref.mComponent); 12663 } 12664 } 12665 } 12666 } 12667 } 12668 12669 return num; 12670 } 12671 12672 @Override 12673 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12674 int userId) { 12675 int callingUid = Binder.getCallingUid(); 12676 if (callingUid != Process.SYSTEM_UID) { 12677 throw new SecurityException( 12678 "addPersistentPreferredActivity can only be run by the system"); 12679 } 12680 if (filter.countActions() == 0) { 12681 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12682 return; 12683 } 12684 synchronized (mPackages) { 12685 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12686 " :"); 12687 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12688 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12689 new PersistentPreferredActivity(filter, activity)); 12690 scheduleWritePackageRestrictionsLocked(userId); 12691 } 12692 } 12693 12694 @Override 12695 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12696 int callingUid = Binder.getCallingUid(); 12697 if (callingUid != Process.SYSTEM_UID) { 12698 throw new SecurityException( 12699 "clearPackagePersistentPreferredActivities can only be run by the system"); 12700 } 12701 ArrayList<PersistentPreferredActivity> removed = null; 12702 boolean changed = false; 12703 synchronized (mPackages) { 12704 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12705 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12706 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12707 .valueAt(i); 12708 if (userId != thisUserId) { 12709 continue; 12710 } 12711 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12712 while (it.hasNext()) { 12713 PersistentPreferredActivity ppa = it.next(); 12714 // Mark entry for removal only if it matches the package name. 12715 if (ppa.mComponent.getPackageName().equals(packageName)) { 12716 if (removed == null) { 12717 removed = new ArrayList<PersistentPreferredActivity>(); 12718 } 12719 removed.add(ppa); 12720 } 12721 } 12722 if (removed != null) { 12723 for (int j=0; j<removed.size(); j++) { 12724 PersistentPreferredActivity ppa = removed.get(j); 12725 ppir.removeFilter(ppa); 12726 } 12727 changed = true; 12728 } 12729 } 12730 12731 if (changed) { 12732 scheduleWritePackageRestrictionsLocked(userId); 12733 } 12734 } 12735 } 12736 12737 /** 12738 * Non-Binder method, support for the backup/restore mechanism: write the 12739 * full set of preferred activities in its canonical XML format. Returns true 12740 * on success; false otherwise. 12741 */ 12742 @Override 12743 public byte[] getPreferredActivityBackup(int userId) { 12744 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12745 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12746 } 12747 12748 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12749 try { 12750 final XmlSerializer serializer = new FastXmlSerializer(); 12751 serializer.setOutput(dataStream, "utf-8"); 12752 serializer.startDocument(null, true); 12753 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12754 12755 synchronized (mPackages) { 12756 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12757 } 12758 12759 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12760 serializer.endDocument(); 12761 serializer.flush(); 12762 } catch (Exception e) { 12763 if (DEBUG_BACKUP) { 12764 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12765 } 12766 return null; 12767 } 12768 12769 return dataStream.toByteArray(); 12770 } 12771 12772 @Override 12773 public void restorePreferredActivities(byte[] backup, int userId) { 12774 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12775 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12776 } 12777 12778 try { 12779 final XmlPullParser parser = Xml.newPullParser(); 12780 parser.setInput(new ByteArrayInputStream(backup), null); 12781 12782 int type; 12783 while ((type = parser.next()) != XmlPullParser.START_TAG 12784 && type != XmlPullParser.END_DOCUMENT) { 12785 } 12786 if (type != XmlPullParser.START_TAG) { 12787 // oops didn't find a start tag?! 12788 if (DEBUG_BACKUP) { 12789 Slog.e(TAG, "Didn't find start tag during restore"); 12790 } 12791 return; 12792 } 12793 12794 // this is supposed to be TAG_PREFERRED_BACKUP 12795 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12796 if (DEBUG_BACKUP) { 12797 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12798 } 12799 return; 12800 } 12801 12802 // skip interfering stuff, then we're aligned with the backing implementation 12803 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12804 synchronized (mPackages) { 12805 mSettings.readPreferredActivitiesLPw(parser, userId); 12806 } 12807 } catch (Exception e) { 12808 if (DEBUG_BACKUP) { 12809 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12810 } 12811 } 12812 } 12813 12814 @Override 12815 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12816 int sourceUserId, int targetUserId, int flags) { 12817 mContext.enforceCallingOrSelfPermission( 12818 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12819 int callingUid = Binder.getCallingUid(); 12820 enforceOwnerRights(ownerPackage, callingUid); 12821 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12822 if (intentFilter.countActions() == 0) { 12823 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12824 return; 12825 } 12826 synchronized (mPackages) { 12827 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12828 ownerPackage, targetUserId, flags); 12829 CrossProfileIntentResolver resolver = 12830 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12831 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12832 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12833 if (existing != null) { 12834 int size = existing.size(); 12835 for (int i = 0; i < size; i++) { 12836 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12837 return; 12838 } 12839 } 12840 } 12841 resolver.addFilter(newFilter); 12842 scheduleWritePackageRestrictionsLocked(sourceUserId); 12843 } 12844 } 12845 12846 @Override 12847 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12848 mContext.enforceCallingOrSelfPermission( 12849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12850 int callingUid = Binder.getCallingUid(); 12851 enforceOwnerRights(ownerPackage, callingUid); 12852 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12853 synchronized (mPackages) { 12854 CrossProfileIntentResolver resolver = 12855 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12856 ArraySet<CrossProfileIntentFilter> set = 12857 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12858 for (CrossProfileIntentFilter filter : set) { 12859 if (filter.getOwnerPackage().equals(ownerPackage)) { 12860 resolver.removeFilter(filter); 12861 } 12862 } 12863 scheduleWritePackageRestrictionsLocked(sourceUserId); 12864 } 12865 } 12866 12867 // Enforcing that callingUid is owning pkg on userId 12868 private void enforceOwnerRights(String pkg, int callingUid) { 12869 // The system owns everything. 12870 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12871 return; 12872 } 12873 int callingUserId = UserHandle.getUserId(callingUid); 12874 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12875 if (pi == null) { 12876 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12877 + callingUserId); 12878 } 12879 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12880 throw new SecurityException("Calling uid " + callingUid 12881 + " does not own package " + pkg); 12882 } 12883 } 12884 12885 @Override 12886 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12887 Intent intent = new Intent(Intent.ACTION_MAIN); 12888 intent.addCategory(Intent.CATEGORY_HOME); 12889 12890 final int callingUserId = UserHandle.getCallingUserId(); 12891 List<ResolveInfo> list = queryIntentActivities(intent, null, 12892 PackageManager.GET_META_DATA, callingUserId); 12893 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12894 true, false, false, callingUserId); 12895 12896 allHomeCandidates.clear(); 12897 if (list != null) { 12898 for (ResolveInfo ri : list) { 12899 allHomeCandidates.add(ri); 12900 } 12901 } 12902 return (preferred == null || preferred.activityInfo == null) 12903 ? null 12904 : new ComponentName(preferred.activityInfo.packageName, 12905 preferred.activityInfo.name); 12906 } 12907 12908 @Override 12909 public void setApplicationEnabledSetting(String appPackageName, 12910 int newState, int flags, int userId, String callingPackage) { 12911 if (!sUserManager.exists(userId)) return; 12912 if (callingPackage == null) { 12913 callingPackage = Integer.toString(Binder.getCallingUid()); 12914 } 12915 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12916 } 12917 12918 @Override 12919 public void setComponentEnabledSetting(ComponentName componentName, 12920 int newState, int flags, int userId) { 12921 if (!sUserManager.exists(userId)) return; 12922 setEnabledSetting(componentName.getPackageName(), 12923 componentName.getClassName(), newState, flags, userId, null); 12924 } 12925 12926 private void setEnabledSetting(final String packageName, String className, int newState, 12927 final int flags, int userId, String callingPackage) { 12928 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12929 || newState == COMPONENT_ENABLED_STATE_ENABLED 12930 || newState == COMPONENT_ENABLED_STATE_DISABLED 12931 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12932 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12933 throw new IllegalArgumentException("Invalid new component state: " 12934 + newState); 12935 } 12936 PackageSetting pkgSetting; 12937 final int uid = Binder.getCallingUid(); 12938 final int permission = mContext.checkCallingOrSelfPermission( 12939 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12940 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12941 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12942 boolean sendNow = false; 12943 boolean isApp = (className == null); 12944 String componentName = isApp ? packageName : className; 12945 int packageUid = -1; 12946 ArrayList<String> components; 12947 12948 // writer 12949 synchronized (mPackages) { 12950 pkgSetting = mSettings.mPackages.get(packageName); 12951 if (pkgSetting == null) { 12952 if (className == null) { 12953 throw new IllegalArgumentException( 12954 "Unknown package: " + packageName); 12955 } 12956 throw new IllegalArgumentException( 12957 "Unknown component: " + packageName 12958 + "/" + className); 12959 } 12960 // Allow root and verify that userId is not being specified by a different user 12961 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12962 throw new SecurityException( 12963 "Permission Denial: attempt to change component state from pid=" 12964 + Binder.getCallingPid() 12965 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12966 } 12967 if (className == null) { 12968 // We're dealing with an application/package level state change 12969 if (pkgSetting.getEnabled(userId) == newState) { 12970 // Nothing to do 12971 return; 12972 } 12973 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12974 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12975 // Don't care about who enables an app. 12976 callingPackage = null; 12977 } 12978 pkgSetting.setEnabled(newState, userId, callingPackage); 12979 // pkgSetting.pkg.mSetEnabled = newState; 12980 } else { 12981 // We're dealing with a component level state change 12982 // First, verify that this is a valid class name. 12983 PackageParser.Package pkg = pkgSetting.pkg; 12984 if (pkg == null || !pkg.hasComponentClassName(className)) { 12985 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12986 throw new IllegalArgumentException("Component class " + className 12987 + " does not exist in " + packageName); 12988 } else { 12989 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12990 + className + " does not exist in " + packageName); 12991 } 12992 } 12993 switch (newState) { 12994 case COMPONENT_ENABLED_STATE_ENABLED: 12995 if (!pkgSetting.enableComponentLPw(className, userId)) { 12996 return; 12997 } 12998 break; 12999 case COMPONENT_ENABLED_STATE_DISABLED: 13000 if (!pkgSetting.disableComponentLPw(className, userId)) { 13001 return; 13002 } 13003 break; 13004 case COMPONENT_ENABLED_STATE_DEFAULT: 13005 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13006 return; 13007 } 13008 break; 13009 default: 13010 Slog.e(TAG, "Invalid new component state: " + newState); 13011 return; 13012 } 13013 } 13014 scheduleWritePackageRestrictionsLocked(userId); 13015 components = mPendingBroadcasts.get(userId, packageName); 13016 final boolean newPackage = components == null; 13017 if (newPackage) { 13018 components = new ArrayList<String>(); 13019 } 13020 if (!components.contains(componentName)) { 13021 components.add(componentName); 13022 } 13023 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13024 sendNow = true; 13025 // Purge entry from pending broadcast list if another one exists already 13026 // since we are sending one right away. 13027 mPendingBroadcasts.remove(userId, packageName); 13028 } else { 13029 if (newPackage) { 13030 mPendingBroadcasts.put(userId, packageName, components); 13031 } 13032 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13033 // Schedule a message 13034 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13035 } 13036 } 13037 } 13038 13039 long callingId = Binder.clearCallingIdentity(); 13040 try { 13041 if (sendNow) { 13042 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13043 sendPackageChangedBroadcast(packageName, 13044 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13045 } 13046 } finally { 13047 Binder.restoreCallingIdentity(callingId); 13048 } 13049 } 13050 13051 private void sendPackageChangedBroadcast(String packageName, 13052 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13053 if (DEBUG_INSTALL) 13054 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13055 + componentNames); 13056 Bundle extras = new Bundle(4); 13057 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13058 String nameList[] = new String[componentNames.size()]; 13059 componentNames.toArray(nameList); 13060 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13061 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13062 extras.putInt(Intent.EXTRA_UID, packageUid); 13063 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13064 new int[] {UserHandle.getUserId(packageUid)}); 13065 } 13066 13067 @Override 13068 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13069 if (!sUserManager.exists(userId)) return; 13070 final int uid = Binder.getCallingUid(); 13071 final int permission = mContext.checkCallingOrSelfPermission( 13072 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13073 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13074 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13075 // writer 13076 synchronized (mPackages) { 13077 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13078 uid, userId)) { 13079 scheduleWritePackageRestrictionsLocked(userId); 13080 } 13081 } 13082 } 13083 13084 @Override 13085 public String getInstallerPackageName(String packageName) { 13086 // reader 13087 synchronized (mPackages) { 13088 return mSettings.getInstallerPackageNameLPr(packageName); 13089 } 13090 } 13091 13092 @Override 13093 public int getApplicationEnabledSetting(String packageName, int userId) { 13094 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13095 int uid = Binder.getCallingUid(); 13096 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13097 // reader 13098 synchronized (mPackages) { 13099 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13100 } 13101 } 13102 13103 @Override 13104 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13105 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13106 int uid = Binder.getCallingUid(); 13107 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13108 // reader 13109 synchronized (mPackages) { 13110 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13111 } 13112 } 13113 13114 @Override 13115 public void enterSafeMode() { 13116 enforceSystemOrRoot("Only the system can request entering safe mode"); 13117 13118 if (!mSystemReady) { 13119 mSafeMode = true; 13120 } 13121 } 13122 13123 @Override 13124 public void systemReady() { 13125 mSystemReady = true; 13126 13127 // Read the compatibilty setting when the system is ready. 13128 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13129 mContext.getContentResolver(), 13130 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13131 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13132 if (DEBUG_SETTINGS) { 13133 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13134 } 13135 13136 synchronized (mPackages) { 13137 // Verify that all of the preferred activity components actually 13138 // exist. It is possible for applications to be updated and at 13139 // that point remove a previously declared activity component that 13140 // had been set as a preferred activity. We try to clean this up 13141 // the next time we encounter that preferred activity, but it is 13142 // possible for the user flow to never be able to return to that 13143 // situation so here we do a sanity check to make sure we haven't 13144 // left any junk around. 13145 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13146 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13147 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13148 removed.clear(); 13149 for (PreferredActivity pa : pir.filterSet()) { 13150 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13151 removed.add(pa); 13152 } 13153 } 13154 if (removed.size() > 0) { 13155 for (int r=0; r<removed.size(); r++) { 13156 PreferredActivity pa = removed.get(r); 13157 Slog.w(TAG, "Removing dangling preferred activity: " 13158 + pa.mPref.mComponent); 13159 pir.removeFilter(pa); 13160 } 13161 mSettings.writePackageRestrictionsLPr( 13162 mSettings.mPreferredActivities.keyAt(i)); 13163 } 13164 } 13165 } 13166 sUserManager.systemReady(); 13167 13168 // Kick off any messages waiting for system ready 13169 if (mPostSystemReadyMessages != null) { 13170 for (Message msg : mPostSystemReadyMessages) { 13171 msg.sendToTarget(); 13172 } 13173 mPostSystemReadyMessages = null; 13174 } 13175 13176 // Watch for external volumes that come and go over time 13177 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13178 storage.registerListener(mStorageListener); 13179 13180 mInstallerService.systemReady(); 13181 } 13182 13183 @Override 13184 public boolean isSafeMode() { 13185 return mSafeMode; 13186 } 13187 13188 @Override 13189 public boolean hasSystemUidErrors() { 13190 return mHasSystemUidErrors; 13191 } 13192 13193 static String arrayToString(int[] array) { 13194 StringBuffer buf = new StringBuffer(128); 13195 buf.append('['); 13196 if (array != null) { 13197 for (int i=0; i<array.length; i++) { 13198 if (i > 0) buf.append(", "); 13199 buf.append(array[i]); 13200 } 13201 } 13202 buf.append(']'); 13203 return buf.toString(); 13204 } 13205 13206 static class DumpState { 13207 public static final int DUMP_LIBS = 1 << 0; 13208 public static final int DUMP_FEATURES = 1 << 1; 13209 public static final int DUMP_RESOLVERS = 1 << 2; 13210 public static final int DUMP_PERMISSIONS = 1 << 3; 13211 public static final int DUMP_PACKAGES = 1 << 4; 13212 public static final int DUMP_SHARED_USERS = 1 << 5; 13213 public static final int DUMP_MESSAGES = 1 << 6; 13214 public static final int DUMP_PROVIDERS = 1 << 7; 13215 public static final int DUMP_VERIFIERS = 1 << 8; 13216 public static final int DUMP_PREFERRED = 1 << 9; 13217 public static final int DUMP_PREFERRED_XML = 1 << 10; 13218 public static final int DUMP_KEYSETS = 1 << 11; 13219 public static final int DUMP_VERSION = 1 << 12; 13220 public static final int DUMP_INSTALLS = 1 << 13; 13221 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13222 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13223 13224 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13225 13226 private int mTypes; 13227 13228 private int mOptions; 13229 13230 private boolean mTitlePrinted; 13231 13232 private SharedUserSetting mSharedUser; 13233 13234 public boolean isDumping(int type) { 13235 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13236 return true; 13237 } 13238 13239 return (mTypes & type) != 0; 13240 } 13241 13242 public void setDump(int type) { 13243 mTypes |= type; 13244 } 13245 13246 public boolean isOptionEnabled(int option) { 13247 return (mOptions & option) != 0; 13248 } 13249 13250 public void setOptionEnabled(int option) { 13251 mOptions |= option; 13252 } 13253 13254 public boolean onTitlePrinted() { 13255 final boolean printed = mTitlePrinted; 13256 mTitlePrinted = true; 13257 return printed; 13258 } 13259 13260 public boolean getTitlePrinted() { 13261 return mTitlePrinted; 13262 } 13263 13264 public void setTitlePrinted(boolean enabled) { 13265 mTitlePrinted = enabled; 13266 } 13267 13268 public SharedUserSetting getSharedUser() { 13269 return mSharedUser; 13270 } 13271 13272 public void setSharedUser(SharedUserSetting user) { 13273 mSharedUser = user; 13274 } 13275 } 13276 13277 @Override 13278 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13279 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13280 != PackageManager.PERMISSION_GRANTED) { 13281 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13282 + Binder.getCallingPid() 13283 + ", uid=" + Binder.getCallingUid() 13284 + " without permission " 13285 + android.Manifest.permission.DUMP); 13286 return; 13287 } 13288 13289 DumpState dumpState = new DumpState(); 13290 boolean fullPreferred = false; 13291 boolean checkin = false; 13292 13293 String packageName = null; 13294 13295 int opti = 0; 13296 while (opti < args.length) { 13297 String opt = args[opti]; 13298 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13299 break; 13300 } 13301 opti++; 13302 13303 if ("-a".equals(opt)) { 13304 // Right now we only know how to print all. 13305 } else if ("-h".equals(opt)) { 13306 pw.println("Package manager dump options:"); 13307 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13308 pw.println(" --checkin: dump for a checkin"); 13309 pw.println(" -f: print details of intent filters"); 13310 pw.println(" -h: print this help"); 13311 pw.println(" cmd may be one of:"); 13312 pw.println(" l[ibraries]: list known shared libraries"); 13313 pw.println(" f[ibraries]: list device features"); 13314 pw.println(" k[eysets]: print known keysets"); 13315 pw.println(" r[esolvers]: dump intent resolvers"); 13316 pw.println(" perm[issions]: dump permissions"); 13317 pw.println(" pref[erred]: print preferred package settings"); 13318 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13319 pw.println(" prov[iders]: dump content providers"); 13320 pw.println(" p[ackages]: dump installed packages"); 13321 pw.println(" s[hared-users]: dump shared user IDs"); 13322 pw.println(" m[essages]: print collected runtime messages"); 13323 pw.println(" v[erifiers]: print package verifier info"); 13324 pw.println(" version: print database version info"); 13325 pw.println(" write: write current settings now"); 13326 pw.println(" <package.name>: info about given package"); 13327 pw.println(" installs: details about install sessions"); 13328 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13329 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13330 return; 13331 } else if ("--checkin".equals(opt)) { 13332 checkin = true; 13333 } else if ("-f".equals(opt)) { 13334 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13335 } else { 13336 pw.println("Unknown argument: " + opt + "; use -h for help"); 13337 } 13338 } 13339 13340 // Is the caller requesting to dump a particular piece of data? 13341 if (opti < args.length) { 13342 String cmd = args[opti]; 13343 opti++; 13344 // Is this a package name? 13345 if ("android".equals(cmd) || cmd.contains(".")) { 13346 packageName = cmd; 13347 // When dumping a single package, we always dump all of its 13348 // filter information since the amount of data will be reasonable. 13349 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13350 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13351 dumpState.setDump(DumpState.DUMP_LIBS); 13352 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13353 dumpState.setDump(DumpState.DUMP_FEATURES); 13354 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13355 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13356 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13357 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13358 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13359 dumpState.setDump(DumpState.DUMP_PREFERRED); 13360 } else if ("preferred-xml".equals(cmd)) { 13361 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13362 if (opti < args.length && "--full".equals(args[opti])) { 13363 fullPreferred = true; 13364 opti++; 13365 } 13366 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13367 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13368 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13369 dumpState.setDump(DumpState.DUMP_PACKAGES); 13370 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13371 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13372 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13373 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13374 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13375 dumpState.setDump(DumpState.DUMP_MESSAGES); 13376 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13377 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13378 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13379 || "intent-filter-verifiers".equals(cmd)) { 13380 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13381 } else if ("version".equals(cmd)) { 13382 dumpState.setDump(DumpState.DUMP_VERSION); 13383 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13384 dumpState.setDump(DumpState.DUMP_KEYSETS); 13385 } else if ("installs".equals(cmd)) { 13386 dumpState.setDump(DumpState.DUMP_INSTALLS); 13387 } else if ("write".equals(cmd)) { 13388 synchronized (mPackages) { 13389 mSettings.writeLPr(); 13390 pw.println("Settings written."); 13391 return; 13392 } 13393 } 13394 } 13395 13396 if (checkin) { 13397 pw.println("vers,1"); 13398 } 13399 13400 // reader 13401 synchronized (mPackages) { 13402 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13403 if (!checkin) { 13404 if (dumpState.onTitlePrinted()) 13405 pw.println(); 13406 pw.println("Database versions:"); 13407 pw.print(" SDK Version:"); 13408 pw.print(" internal="); 13409 pw.print(mSettings.mInternalSdkPlatform); 13410 pw.print(" external="); 13411 pw.println(mSettings.mExternalSdkPlatform); 13412 pw.print(" DB Version:"); 13413 pw.print(" internal="); 13414 pw.print(mSettings.mInternalDatabaseVersion); 13415 pw.print(" external="); 13416 pw.println(mSettings.mExternalDatabaseVersion); 13417 } 13418 } 13419 13420 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13421 if (!checkin) { 13422 if (dumpState.onTitlePrinted()) 13423 pw.println(); 13424 pw.println("Verifiers:"); 13425 pw.print(" Required: "); 13426 pw.print(mRequiredVerifierPackage); 13427 pw.print(" (uid="); 13428 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13429 pw.println(")"); 13430 } else if (mRequiredVerifierPackage != null) { 13431 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13432 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13433 } 13434 } 13435 13436 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13437 packageName == null) { 13438 if (mIntentFilterVerifierComponent != null) { 13439 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13440 if (!checkin) { 13441 if (dumpState.onTitlePrinted()) 13442 pw.println(); 13443 pw.println("Intent Filter Verifier:"); 13444 pw.print(" Using: "); 13445 pw.print(verifierPackageName); 13446 pw.print(" (uid="); 13447 pw.print(getPackageUid(verifierPackageName, 0)); 13448 pw.println(")"); 13449 } else if (verifierPackageName != null) { 13450 pw.print("ifv,"); pw.print(verifierPackageName); 13451 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13452 } 13453 } else { 13454 pw.println(); 13455 pw.println("No Intent Filter Verifier available!"); 13456 } 13457 } 13458 13459 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13460 boolean printedHeader = false; 13461 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13462 while (it.hasNext()) { 13463 String name = it.next(); 13464 SharedLibraryEntry ent = mSharedLibraries.get(name); 13465 if (!checkin) { 13466 if (!printedHeader) { 13467 if (dumpState.onTitlePrinted()) 13468 pw.println(); 13469 pw.println("Libraries:"); 13470 printedHeader = true; 13471 } 13472 pw.print(" "); 13473 } else { 13474 pw.print("lib,"); 13475 } 13476 pw.print(name); 13477 if (!checkin) { 13478 pw.print(" -> "); 13479 } 13480 if (ent.path != null) { 13481 if (!checkin) { 13482 pw.print("(jar) "); 13483 pw.print(ent.path); 13484 } else { 13485 pw.print(",jar,"); 13486 pw.print(ent.path); 13487 } 13488 } else { 13489 if (!checkin) { 13490 pw.print("(apk) "); 13491 pw.print(ent.apk); 13492 } else { 13493 pw.print(",apk,"); 13494 pw.print(ent.apk); 13495 } 13496 } 13497 pw.println(); 13498 } 13499 } 13500 13501 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13502 if (dumpState.onTitlePrinted()) 13503 pw.println(); 13504 if (!checkin) { 13505 pw.println("Features:"); 13506 } 13507 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13508 while (it.hasNext()) { 13509 String name = it.next(); 13510 if (!checkin) { 13511 pw.print(" "); 13512 } else { 13513 pw.print("feat,"); 13514 } 13515 pw.println(name); 13516 } 13517 } 13518 13519 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13520 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13521 : "Activity Resolver Table:", " ", packageName, 13522 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13523 dumpState.setTitlePrinted(true); 13524 } 13525 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13526 : "Receiver Resolver Table:", " ", packageName, 13527 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13528 dumpState.setTitlePrinted(true); 13529 } 13530 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13531 : "Service Resolver Table:", " ", packageName, 13532 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13533 dumpState.setTitlePrinted(true); 13534 } 13535 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13536 : "Provider Resolver Table:", " ", packageName, 13537 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13538 dumpState.setTitlePrinted(true); 13539 } 13540 } 13541 13542 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13543 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13544 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13545 int user = mSettings.mPreferredActivities.keyAt(i); 13546 if (pir.dump(pw, 13547 dumpState.getTitlePrinted() 13548 ? "\nPreferred Activities User " + user + ":" 13549 : "Preferred Activities User " + user + ":", " ", 13550 packageName, true, false)) { 13551 dumpState.setTitlePrinted(true); 13552 } 13553 } 13554 } 13555 13556 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13557 pw.flush(); 13558 FileOutputStream fout = new FileOutputStream(fd); 13559 BufferedOutputStream str = new BufferedOutputStream(fout); 13560 XmlSerializer serializer = new FastXmlSerializer(); 13561 try { 13562 serializer.setOutput(str, "utf-8"); 13563 serializer.startDocument(null, true); 13564 serializer.setFeature( 13565 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13566 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13567 serializer.endDocument(); 13568 serializer.flush(); 13569 } catch (IllegalArgumentException e) { 13570 pw.println("Failed writing: " + e); 13571 } catch (IllegalStateException e) { 13572 pw.println("Failed writing: " + e); 13573 } catch (IOException e) { 13574 pw.println("Failed writing: " + e); 13575 } 13576 } 13577 13578 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13579 pw.println(); 13580 int count = mSettings.mPackages.size(); 13581 if (count == 0) { 13582 pw.println("No domain preferred apps!"); 13583 pw.println(); 13584 } else { 13585 final String prefix = " "; 13586 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13587 if (allPackageSettings.size() == 0) { 13588 pw.println("No domain preferred apps!"); 13589 pw.println(); 13590 } else { 13591 pw.println("Domain preferred apps status:"); 13592 pw.println(); 13593 count = 0; 13594 for (PackageSetting ps : allPackageSettings) { 13595 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13596 if (ivi == null || ivi.getPackageName() == null) continue; 13597 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13598 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13599 pw.println(prefix + "Status: " + ivi.getStatusString()); 13600 pw.println(); 13601 count++; 13602 } 13603 if (count == 0) { 13604 pw.println(prefix + "No domain preferred app status!"); 13605 pw.println(); 13606 } 13607 for (int userId : sUserManager.getUserIds()) { 13608 pw.println("Domain preferred apps for User " + userId + ":"); 13609 pw.println(); 13610 count = 0; 13611 for (PackageSetting ps : allPackageSettings) { 13612 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13613 if (ivi == null || ivi.getPackageName() == null) { 13614 continue; 13615 } 13616 final int status = ps.getDomainVerificationStatusForUser(userId); 13617 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13618 continue; 13619 } 13620 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13621 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13622 String statusStr = IntentFilterVerificationInfo. 13623 getStatusStringFromValue(status); 13624 pw.println(prefix + "Status: " + statusStr); 13625 pw.println(); 13626 count++; 13627 } 13628 if (count == 0) { 13629 pw.println(prefix + "No domain preferred apps!"); 13630 pw.println(); 13631 } 13632 } 13633 } 13634 } 13635 } 13636 13637 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13638 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13639 if (packageName == null) { 13640 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13641 if (iperm == 0) { 13642 if (dumpState.onTitlePrinted()) 13643 pw.println(); 13644 pw.println("AppOp Permissions:"); 13645 } 13646 pw.print(" AppOp Permission "); 13647 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13648 pw.println(":"); 13649 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13650 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13651 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13652 } 13653 } 13654 } 13655 } 13656 13657 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13658 boolean printedSomething = false; 13659 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13660 if (packageName != null && !packageName.equals(p.info.packageName)) { 13661 continue; 13662 } 13663 if (!printedSomething) { 13664 if (dumpState.onTitlePrinted()) 13665 pw.println(); 13666 pw.println("Registered ContentProviders:"); 13667 printedSomething = true; 13668 } 13669 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13670 pw.print(" "); pw.println(p.toString()); 13671 } 13672 printedSomething = false; 13673 for (Map.Entry<String, PackageParser.Provider> entry : 13674 mProvidersByAuthority.entrySet()) { 13675 PackageParser.Provider p = entry.getValue(); 13676 if (packageName != null && !packageName.equals(p.info.packageName)) { 13677 continue; 13678 } 13679 if (!printedSomething) { 13680 if (dumpState.onTitlePrinted()) 13681 pw.println(); 13682 pw.println("ContentProvider Authorities:"); 13683 printedSomething = true; 13684 } 13685 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13686 pw.print(" "); pw.println(p.toString()); 13687 if (p.info != null && p.info.applicationInfo != null) { 13688 final String appInfo = p.info.applicationInfo.toString(); 13689 pw.print(" applicationInfo="); pw.println(appInfo); 13690 } 13691 } 13692 } 13693 13694 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13695 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13696 } 13697 13698 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13699 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13700 } 13701 13702 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13703 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13704 } 13705 13706 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13707 // XXX should handle packageName != null by dumping only install data that 13708 // the given package is involved with. 13709 if (dumpState.onTitlePrinted()) pw.println(); 13710 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13711 } 13712 13713 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13714 if (dumpState.onTitlePrinted()) pw.println(); 13715 mSettings.dumpReadMessagesLPr(pw, dumpState); 13716 13717 pw.println(); 13718 pw.println("Package warning messages:"); 13719 BufferedReader in = null; 13720 String line = null; 13721 try { 13722 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13723 while ((line = in.readLine()) != null) { 13724 if (line.contains("ignored: updated version")) continue; 13725 pw.println(line); 13726 } 13727 } catch (IOException ignored) { 13728 } finally { 13729 IoUtils.closeQuietly(in); 13730 } 13731 } 13732 13733 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13734 BufferedReader in = null; 13735 String line = null; 13736 try { 13737 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13738 while ((line = in.readLine()) != null) { 13739 if (line.contains("ignored: updated version")) continue; 13740 pw.print("msg,"); 13741 pw.println(line); 13742 } 13743 } catch (IOException ignored) { 13744 } finally { 13745 IoUtils.closeQuietly(in); 13746 } 13747 } 13748 } 13749 } 13750 13751 // ------- apps on sdcard specific code ------- 13752 static final boolean DEBUG_SD_INSTALL = false; 13753 13754 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13755 13756 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13757 13758 private boolean mMediaMounted = false; 13759 13760 static String getEncryptKey() { 13761 try { 13762 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13763 SD_ENCRYPTION_KEYSTORE_NAME); 13764 if (sdEncKey == null) { 13765 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13766 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13767 if (sdEncKey == null) { 13768 Slog.e(TAG, "Failed to create encryption keys"); 13769 return null; 13770 } 13771 } 13772 return sdEncKey; 13773 } catch (NoSuchAlgorithmException nsae) { 13774 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13775 return null; 13776 } catch (IOException ioe) { 13777 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13778 return null; 13779 } 13780 } 13781 13782 /* 13783 * Update media status on PackageManager. 13784 */ 13785 @Override 13786 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13787 int callingUid = Binder.getCallingUid(); 13788 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13789 throw new SecurityException("Media status can only be updated by the system"); 13790 } 13791 // reader; this apparently protects mMediaMounted, but should probably 13792 // be a different lock in that case. 13793 synchronized (mPackages) { 13794 Log.i(TAG, "Updating external media status from " 13795 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13796 + (mediaStatus ? "mounted" : "unmounted")); 13797 if (DEBUG_SD_INSTALL) 13798 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13799 + ", mMediaMounted=" + mMediaMounted); 13800 if (mediaStatus == mMediaMounted) { 13801 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13802 : 0, -1); 13803 mHandler.sendMessage(msg); 13804 return; 13805 } 13806 mMediaMounted = mediaStatus; 13807 } 13808 // Queue up an async operation since the package installation may take a 13809 // little while. 13810 mHandler.post(new Runnable() { 13811 public void run() { 13812 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13813 } 13814 }); 13815 } 13816 13817 /** 13818 * Called by MountService when the initial ASECs to scan are available. 13819 * Should block until all the ASEC containers are finished being scanned. 13820 */ 13821 public void scanAvailableAsecs() { 13822 updateExternalMediaStatusInner(true, false, false); 13823 if (mShouldRestoreconData) { 13824 SELinuxMMAC.setRestoreconDone(); 13825 mShouldRestoreconData = false; 13826 } 13827 } 13828 13829 /* 13830 * Collect information of applications on external media, map them against 13831 * existing containers and update information based on current mount status. 13832 * Please note that we always have to report status if reportStatus has been 13833 * set to true especially when unloading packages. 13834 */ 13835 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13836 boolean externalStorage) { 13837 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13838 int[] uidArr = EmptyArray.INT; 13839 13840 final String[] list = PackageHelper.getSecureContainerList(); 13841 if (ArrayUtils.isEmpty(list)) { 13842 Log.i(TAG, "No secure containers found"); 13843 } else { 13844 // Process list of secure containers and categorize them 13845 // as active or stale based on their package internal state. 13846 13847 // reader 13848 synchronized (mPackages) { 13849 for (String cid : list) { 13850 // Leave stages untouched for now; installer service owns them 13851 if (PackageInstallerService.isStageName(cid)) continue; 13852 13853 if (DEBUG_SD_INSTALL) 13854 Log.i(TAG, "Processing container " + cid); 13855 String pkgName = getAsecPackageName(cid); 13856 if (pkgName == null) { 13857 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13858 continue; 13859 } 13860 if (DEBUG_SD_INSTALL) 13861 Log.i(TAG, "Looking for pkg : " + pkgName); 13862 13863 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13864 if (ps == null) { 13865 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13866 continue; 13867 } 13868 13869 /* 13870 * Skip packages that are not external if we're unmounting 13871 * external storage. 13872 */ 13873 if (externalStorage && !isMounted && !isExternal(ps)) { 13874 continue; 13875 } 13876 13877 final AsecInstallArgs args = new AsecInstallArgs(cid, 13878 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13879 // The package status is changed only if the code path 13880 // matches between settings and the container id. 13881 if (ps.codePathString != null 13882 && ps.codePathString.startsWith(args.getCodePath())) { 13883 if (DEBUG_SD_INSTALL) { 13884 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13885 + " at code path: " + ps.codePathString); 13886 } 13887 13888 // We do have a valid package installed on sdcard 13889 processCids.put(args, ps.codePathString); 13890 final int uid = ps.appId; 13891 if (uid != -1) { 13892 uidArr = ArrayUtils.appendInt(uidArr, uid); 13893 } 13894 } else { 13895 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13896 + ps.codePathString); 13897 } 13898 } 13899 } 13900 13901 Arrays.sort(uidArr); 13902 } 13903 13904 // Process packages with valid entries. 13905 if (isMounted) { 13906 if (DEBUG_SD_INSTALL) 13907 Log.i(TAG, "Loading packages"); 13908 loadMediaPackages(processCids, uidArr); 13909 startCleaningPackages(); 13910 mInstallerService.onSecureContainersAvailable(); 13911 } else { 13912 if (DEBUG_SD_INSTALL) 13913 Log.i(TAG, "Unloading packages"); 13914 unloadMediaPackages(processCids, uidArr, reportStatus); 13915 } 13916 } 13917 13918 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13919 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13920 final int size = infos.size(); 13921 final String[] packageNames = new String[size]; 13922 final int[] packageUids = new int[size]; 13923 for (int i = 0; i < size; i++) { 13924 final ApplicationInfo info = infos.get(i); 13925 packageNames[i] = info.packageName; 13926 packageUids[i] = info.uid; 13927 } 13928 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13929 finishedReceiver); 13930 } 13931 13932 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13933 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13934 sendResourcesChangedBroadcast(mediaStatus, replacing, 13935 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13936 } 13937 13938 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13939 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13940 int size = pkgList.length; 13941 if (size > 0) { 13942 // Send broadcasts here 13943 Bundle extras = new Bundle(); 13944 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13945 if (uidArr != null) { 13946 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13947 } 13948 if (replacing) { 13949 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13950 } 13951 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13952 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13953 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13954 } 13955 } 13956 13957 /* 13958 * Look at potentially valid container ids from processCids If package 13959 * information doesn't match the one on record or package scanning fails, 13960 * the cid is added to list of removeCids. We currently don't delete stale 13961 * containers. 13962 */ 13963 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13964 ArrayList<String> pkgList = new ArrayList<String>(); 13965 Set<AsecInstallArgs> keys = processCids.keySet(); 13966 13967 for (AsecInstallArgs args : keys) { 13968 String codePath = processCids.get(args); 13969 if (DEBUG_SD_INSTALL) 13970 Log.i(TAG, "Loading container : " + args.cid); 13971 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13972 try { 13973 // Make sure there are no container errors first. 13974 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13975 Slog.e(TAG, "Failed to mount cid : " + args.cid 13976 + " when installing from sdcard"); 13977 continue; 13978 } 13979 // Check code path here. 13980 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13981 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13982 + " does not match one in settings " + codePath); 13983 continue; 13984 } 13985 // Parse package 13986 int parseFlags = mDefParseFlags; 13987 if (args.isExternalAsec()) { 13988 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13989 } 13990 if (args.isFwdLocked()) { 13991 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13992 } 13993 13994 synchronized (mInstallLock) { 13995 PackageParser.Package pkg = null; 13996 try { 13997 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13998 } catch (PackageManagerException e) { 13999 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14000 } 14001 // Scan the package 14002 if (pkg != null) { 14003 /* 14004 * TODO why is the lock being held? doPostInstall is 14005 * called in other places without the lock. This needs 14006 * to be straightened out. 14007 */ 14008 // writer 14009 synchronized (mPackages) { 14010 retCode = PackageManager.INSTALL_SUCCEEDED; 14011 pkgList.add(pkg.packageName); 14012 // Post process args 14013 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14014 pkg.applicationInfo.uid); 14015 } 14016 } else { 14017 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14018 } 14019 } 14020 14021 } finally { 14022 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14023 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14024 } 14025 } 14026 } 14027 // writer 14028 synchronized (mPackages) { 14029 // If the platform SDK has changed since the last time we booted, 14030 // we need to re-grant app permission to catch any new ones that 14031 // appear. This is really a hack, and means that apps can in some 14032 // cases get permissions that the user didn't initially explicitly 14033 // allow... it would be nice to have some better way to handle 14034 // this situation. 14035 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14036 if (regrantPermissions) 14037 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14038 + mSdkVersion + "; regranting permissions for external storage"); 14039 mSettings.mExternalSdkPlatform = mSdkVersion; 14040 14041 // Make sure group IDs have been assigned, and any permission 14042 // changes in other apps are accounted for 14043 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14044 | (regrantPermissions 14045 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14046 : 0)); 14047 14048 mSettings.updateExternalDatabaseVersion(); 14049 14050 // can downgrade to reader 14051 // Persist settings 14052 mSettings.writeLPr(); 14053 } 14054 // Send a broadcast to let everyone know we are done processing 14055 if (pkgList.size() > 0) { 14056 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14057 } 14058 } 14059 14060 /* 14061 * Utility method to unload a list of specified containers 14062 */ 14063 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14064 // Just unmount all valid containers. 14065 for (AsecInstallArgs arg : cidArgs) { 14066 synchronized (mInstallLock) { 14067 arg.doPostDeleteLI(false); 14068 } 14069 } 14070 } 14071 14072 /* 14073 * Unload packages mounted on external media. This involves deleting package 14074 * data from internal structures, sending broadcasts about diabled packages, 14075 * gc'ing to free up references, unmounting all secure containers 14076 * corresponding to packages on external media, and posting a 14077 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14078 * that we always have to post this message if status has been requested no 14079 * matter what. 14080 */ 14081 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14082 final boolean reportStatus) { 14083 if (DEBUG_SD_INSTALL) 14084 Log.i(TAG, "unloading media packages"); 14085 ArrayList<String> pkgList = new ArrayList<String>(); 14086 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14087 final Set<AsecInstallArgs> keys = processCids.keySet(); 14088 for (AsecInstallArgs args : keys) { 14089 String pkgName = args.getPackageName(); 14090 if (DEBUG_SD_INSTALL) 14091 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14092 // Delete package internally 14093 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14094 synchronized (mInstallLock) { 14095 boolean res = deletePackageLI(pkgName, null, false, null, null, 14096 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14097 if (res) { 14098 pkgList.add(pkgName); 14099 } else { 14100 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14101 failedList.add(args); 14102 } 14103 } 14104 } 14105 14106 // reader 14107 synchronized (mPackages) { 14108 // We didn't update the settings after removing each package; 14109 // write them now for all packages. 14110 mSettings.writeLPr(); 14111 } 14112 14113 // We have to absolutely send UPDATED_MEDIA_STATUS only 14114 // after confirming that all the receivers processed the ordered 14115 // broadcast when packages get disabled, force a gc to clean things up. 14116 // and unload all the containers. 14117 if (pkgList.size() > 0) { 14118 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14119 new IIntentReceiver.Stub() { 14120 public void performReceive(Intent intent, int resultCode, String data, 14121 Bundle extras, boolean ordered, boolean sticky, 14122 int sendingUser) throws RemoteException { 14123 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14124 reportStatus ? 1 : 0, 1, keys); 14125 mHandler.sendMessage(msg); 14126 } 14127 }); 14128 } else { 14129 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14130 keys); 14131 mHandler.sendMessage(msg); 14132 } 14133 } 14134 14135 private void loadPrivatePackages(VolumeInfo vol) { 14136 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14137 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14138 synchronized (mPackages) { 14139 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14140 for (PackageSetting ps : packages) { 14141 synchronized (mInstallLock) { 14142 final PackageParser.Package pkg; 14143 try { 14144 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14145 loaded.add(pkg.applicationInfo); 14146 } catch (PackageManagerException e) { 14147 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14148 } 14149 } 14150 } 14151 14152 // TODO: regrant any permissions that changed based since original install 14153 14154 mSettings.writeLPr(); 14155 } 14156 14157 Slog.d(TAG, "Loaded packages " + loaded); 14158 sendResourcesChangedBroadcast(true, false, loaded, null); 14159 } 14160 14161 private void unloadPrivatePackages(VolumeInfo vol) { 14162 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14163 synchronized (mPackages) { 14164 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14165 for (PackageSetting ps : packages) { 14166 if (ps.pkg == null) continue; 14167 synchronized (mInstallLock) { 14168 final ApplicationInfo info = ps.pkg.applicationInfo; 14169 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14170 if (deletePackageLI(ps.name, null, false, null, null, 14171 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14172 unloaded.add(info); 14173 } else { 14174 Slog.w(TAG, "Failed to unload " + ps.codePath); 14175 } 14176 } 14177 } 14178 14179 mSettings.writeLPr(); 14180 } 14181 14182 Slog.d(TAG, "Unloaded packages " + unloaded); 14183 sendResourcesChangedBroadcast(false, false, unloaded, null); 14184 } 14185 14186 @Override 14187 public int movePackage(final String packageName, final String volumeUuid) { 14188 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14189 14190 final int moveId = mNextMoveId.getAndIncrement(); 14191 try { 14192 movePackageInternal(packageName, volumeUuid, moveId); 14193 } catch (PackageManagerException e) { 14194 Slog.d(TAG, "Failed to move " + packageName, e); 14195 mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14196 } 14197 return moveId; 14198 } 14199 14200 private void movePackageInternal(final String packageName, final String volumeUuid, 14201 final int moveId) throws PackageManagerException { 14202 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14203 final PackageManager pm = mContext.getPackageManager(); 14204 14205 final boolean currentAsec; 14206 final String currentVolumeUuid; 14207 final File codeFile; 14208 final String installerPackageName; 14209 final String packageAbiOverride; 14210 final int appId; 14211 final String seinfo; 14212 14213 // reader 14214 synchronized (mPackages) { 14215 final PackageParser.Package pkg = mPackages.get(packageName); 14216 final PackageSetting ps = mSettings.mPackages.get(packageName); 14217 if (pkg == null || ps == null) { 14218 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14219 } 14220 14221 if (pkg.applicationInfo.isSystemApp()) { 14222 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14223 "Cannot move system application"); 14224 } else if (pkg.mOperationPending) { 14225 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14226 "Attempt to move package which has pending operations"); 14227 } 14228 14229 // TODO: yell if already in desired location 14230 14231 mMoveCallbacks.notifyStarted(moveId, 14232 String.valueOf(pm.getApplicationLabel(pkg.applicationInfo))); 14233 14234 pkg.mOperationPending = true; 14235 14236 currentAsec = pkg.applicationInfo.isForwardLocked() 14237 || pkg.applicationInfo.isExternalAsec(); 14238 currentVolumeUuid = ps.volumeUuid; 14239 codeFile = new File(pkg.codePath); 14240 installerPackageName = ps.installerPackageName; 14241 packageAbiOverride = ps.cpuAbiOverrideString; 14242 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14243 seinfo = pkg.applicationInfo.seinfo; 14244 } 14245 14246 int installFlags; 14247 final boolean moveData; 14248 14249 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14250 installFlags = INSTALL_INTERNAL; 14251 moveData = !currentAsec; 14252 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14253 installFlags = INSTALL_EXTERNAL; 14254 moveData = false; 14255 } else { 14256 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14257 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14258 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14259 || !volume.isMountedWritable()) { 14260 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14261 "Move location not mounted private volume"); 14262 } 14263 14264 Preconditions.checkState(!currentAsec); 14265 14266 installFlags = INSTALL_INTERNAL; 14267 moveData = true; 14268 } 14269 14270 Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid); 14271 mMoveCallbacks.notifyStatusChanged(moveId, 10, -1); 14272 14273 if (moveData) { 14274 synchronized (mInstallLock) { 14275 // TODO: split this into separate copy and delete operations 14276 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14277 seinfo) != 0) { 14278 synchronized (mPackages) { 14279 final PackageParser.Package pkg = mPackages.get(packageName); 14280 if (pkg != null) { 14281 pkg.mOperationPending = false; 14282 } 14283 } 14284 14285 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14286 "Failed to move private data"); 14287 } 14288 } 14289 } 14290 14291 mMoveCallbacks.notifyStatusChanged(moveId, 50); 14292 14293 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14294 @Override 14295 public void onUserActionRequired(Intent intent) throws RemoteException { 14296 throw new IllegalStateException(); 14297 } 14298 14299 @Override 14300 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14301 Bundle extras) throws RemoteException { 14302 Slog.d(TAG, "Install result for move: " 14303 + PackageManager.installStatusToString(returnCode, msg)); 14304 14305 // We usually have a new package now after the install, but if 14306 // we failed we need to clear the pending flag on the original 14307 // package object. 14308 synchronized (mPackages) { 14309 final PackageParser.Package pkg = mPackages.get(packageName); 14310 if (pkg != null) { 14311 pkg.mOperationPending = false; 14312 } 14313 } 14314 14315 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14316 switch (status) { 14317 case PackageInstaller.STATUS_SUCCESS: 14318 mMoveCallbacks.notifyStatusChanged(moveId, 14319 PackageManager.MOVE_SUCCEEDED); 14320 break; 14321 case PackageInstaller.STATUS_FAILURE_STORAGE: 14322 mMoveCallbacks.notifyStatusChanged(moveId, 14323 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14324 break; 14325 default: 14326 mMoveCallbacks.notifyStatusChanged(moveId, 14327 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14328 break; 14329 } 14330 } 14331 }; 14332 14333 // Treat a move like reinstalling an existing app, which ensures that we 14334 // process everythign uniformly, like unpacking native libraries. 14335 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14336 14337 final Message msg = mHandler.obtainMessage(INIT_COPY); 14338 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14339 msg.obj = new InstallParams(origin, installObserver, installFlags, 14340 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14341 mHandler.sendMessage(msg); 14342 } 14343 14344 @Override 14345 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14347 14348 final int realMoveId = mNextMoveId.getAndIncrement(); 14349 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14350 @Override 14351 public void onStarted(int moveId, String title) { 14352 // Ignored 14353 } 14354 14355 @Override 14356 public void onStatusChanged(int moveId, int status, long estMillis) { 14357 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14358 } 14359 }; 14360 14361 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14362 storage.setPrimaryStorageUuid(volumeUuid, callback); 14363 return realMoveId; 14364 } 14365 14366 @Override 14367 public int getMoveStatus(int moveId) { 14368 mContext.enforceCallingOrSelfPermission( 14369 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14370 return mMoveCallbacks.mLastStatus.get(moveId); 14371 } 14372 14373 @Override 14374 public void registerMoveCallback(IPackageMoveObserver callback) { 14375 mContext.enforceCallingOrSelfPermission( 14376 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14377 mMoveCallbacks.register(callback); 14378 } 14379 14380 @Override 14381 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14382 mContext.enforceCallingOrSelfPermission( 14383 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14384 mMoveCallbacks.unregister(callback); 14385 } 14386 14387 @Override 14388 public boolean setInstallLocation(int loc) { 14389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14390 null); 14391 if (getInstallLocation() == loc) { 14392 return true; 14393 } 14394 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14395 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14396 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14397 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14398 return true; 14399 } 14400 return false; 14401 } 14402 14403 @Override 14404 public int getInstallLocation() { 14405 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14406 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14407 PackageHelper.APP_INSTALL_AUTO); 14408 } 14409 14410 /** Called by UserManagerService */ 14411 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14412 mDirtyUsers.remove(userHandle); 14413 mSettings.removeUserLPw(userHandle); 14414 mPendingBroadcasts.remove(userHandle); 14415 if (mInstaller != null) { 14416 // Technically, we shouldn't be doing this with the package lock 14417 // held. However, this is very rare, and there is already so much 14418 // other disk I/O going on, that we'll let it slide for now. 14419 final StorageManager storage = StorageManager.from(mContext); 14420 final List<VolumeInfo> vols = storage.getVolumes(); 14421 for (VolumeInfo vol : vols) { 14422 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14423 final String volumeUuid = vol.getFsUuid(); 14424 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14425 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14426 } 14427 } 14428 } 14429 mUserNeedsBadging.delete(userHandle); 14430 removeUnusedPackagesLILPw(userManager, userHandle); 14431 } 14432 14433 /** 14434 * We're removing userHandle and would like to remove any downloaded packages 14435 * that are no longer in use by any other user. 14436 * @param userHandle the user being removed 14437 */ 14438 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14439 final boolean DEBUG_CLEAN_APKS = false; 14440 int [] users = userManager.getUserIdsLPr(); 14441 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14442 while (psit.hasNext()) { 14443 PackageSetting ps = psit.next(); 14444 if (ps.pkg == null) { 14445 continue; 14446 } 14447 final String packageName = ps.pkg.packageName; 14448 // Skip over if system app 14449 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14450 continue; 14451 } 14452 if (DEBUG_CLEAN_APKS) { 14453 Slog.i(TAG, "Checking package " + packageName); 14454 } 14455 boolean keep = false; 14456 for (int i = 0; i < users.length; i++) { 14457 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14458 keep = true; 14459 if (DEBUG_CLEAN_APKS) { 14460 Slog.i(TAG, " Keeping package " + packageName + " for user " 14461 + users[i]); 14462 } 14463 break; 14464 } 14465 } 14466 if (!keep) { 14467 if (DEBUG_CLEAN_APKS) { 14468 Slog.i(TAG, " Removing package " + packageName); 14469 } 14470 mHandler.post(new Runnable() { 14471 public void run() { 14472 deletePackageX(packageName, userHandle, 0); 14473 } //end run 14474 }); 14475 } 14476 } 14477 } 14478 14479 /** Called by UserManagerService */ 14480 void createNewUserLILPw(int userHandle, File path) { 14481 if (mInstaller != null) { 14482 mInstaller.createUserConfig(userHandle); 14483 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14484 } 14485 } 14486 14487 void newUserCreatedLILPw(int userHandle) { 14488 // Adding a user requires updating runtime permissions for system apps. 14489 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14490 } 14491 14492 @Override 14493 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14494 mContext.enforceCallingOrSelfPermission( 14495 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14496 "Only package verification agents can read the verifier device identity"); 14497 14498 synchronized (mPackages) { 14499 return mSettings.getVerifierDeviceIdentityLPw(); 14500 } 14501 } 14502 14503 @Override 14504 public void setPermissionEnforced(String permission, boolean enforced) { 14505 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14506 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14507 synchronized (mPackages) { 14508 if (mSettings.mReadExternalStorageEnforced == null 14509 || mSettings.mReadExternalStorageEnforced != enforced) { 14510 mSettings.mReadExternalStorageEnforced = enforced; 14511 mSettings.writeLPr(); 14512 } 14513 } 14514 // kill any non-foreground processes so we restart them and 14515 // grant/revoke the GID. 14516 final IActivityManager am = ActivityManagerNative.getDefault(); 14517 if (am != null) { 14518 final long token = Binder.clearCallingIdentity(); 14519 try { 14520 am.killProcessesBelowForeground("setPermissionEnforcement"); 14521 } catch (RemoteException e) { 14522 } finally { 14523 Binder.restoreCallingIdentity(token); 14524 } 14525 } 14526 } else { 14527 throw new IllegalArgumentException("No selective enforcement for " + permission); 14528 } 14529 } 14530 14531 @Override 14532 @Deprecated 14533 public boolean isPermissionEnforced(String permission) { 14534 return true; 14535 } 14536 14537 @Override 14538 public boolean isStorageLow() { 14539 final long token = Binder.clearCallingIdentity(); 14540 try { 14541 final DeviceStorageMonitorInternal 14542 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14543 if (dsm != null) { 14544 return dsm.isMemoryLow(); 14545 } else { 14546 return false; 14547 } 14548 } finally { 14549 Binder.restoreCallingIdentity(token); 14550 } 14551 } 14552 14553 @Override 14554 public IPackageInstaller getPackageInstaller() { 14555 return mInstallerService; 14556 } 14557 14558 private boolean userNeedsBadging(int userId) { 14559 int index = mUserNeedsBadging.indexOfKey(userId); 14560 if (index < 0) { 14561 final UserInfo userInfo; 14562 final long token = Binder.clearCallingIdentity(); 14563 try { 14564 userInfo = sUserManager.getUserInfo(userId); 14565 } finally { 14566 Binder.restoreCallingIdentity(token); 14567 } 14568 final boolean b; 14569 if (userInfo != null && userInfo.isManagedProfile()) { 14570 b = true; 14571 } else { 14572 b = false; 14573 } 14574 mUserNeedsBadging.put(userId, b); 14575 return b; 14576 } 14577 return mUserNeedsBadging.valueAt(index); 14578 } 14579 14580 @Override 14581 public KeySet getKeySetByAlias(String packageName, String alias) { 14582 if (packageName == null || alias == null) { 14583 return null; 14584 } 14585 synchronized(mPackages) { 14586 final PackageParser.Package pkg = mPackages.get(packageName); 14587 if (pkg == null) { 14588 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14589 throw new IllegalArgumentException("Unknown package: " + packageName); 14590 } 14591 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14592 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14593 } 14594 } 14595 14596 @Override 14597 public KeySet getSigningKeySet(String packageName) { 14598 if (packageName == null) { 14599 return null; 14600 } 14601 synchronized(mPackages) { 14602 final PackageParser.Package pkg = mPackages.get(packageName); 14603 if (pkg == null) { 14604 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14605 throw new IllegalArgumentException("Unknown package: " + packageName); 14606 } 14607 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14608 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14609 throw new SecurityException("May not access signing KeySet of other apps."); 14610 } 14611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14612 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14613 } 14614 } 14615 14616 @Override 14617 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14618 if (packageName == null || ks == null) { 14619 return false; 14620 } 14621 synchronized(mPackages) { 14622 final PackageParser.Package pkg = mPackages.get(packageName); 14623 if (pkg == null) { 14624 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14625 throw new IllegalArgumentException("Unknown package: " + packageName); 14626 } 14627 IBinder ksh = ks.getToken(); 14628 if (ksh instanceof KeySetHandle) { 14629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14630 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14631 } 14632 return false; 14633 } 14634 } 14635 14636 @Override 14637 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14638 if (packageName == null || ks == null) { 14639 return false; 14640 } 14641 synchronized(mPackages) { 14642 final PackageParser.Package pkg = mPackages.get(packageName); 14643 if (pkg == null) { 14644 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14645 throw new IllegalArgumentException("Unknown package: " + packageName); 14646 } 14647 IBinder ksh = ks.getToken(); 14648 if (ksh instanceof KeySetHandle) { 14649 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14650 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14651 } 14652 return false; 14653 } 14654 } 14655 14656 public void getUsageStatsIfNoPackageUsageInfo() { 14657 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14658 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14659 if (usm == null) { 14660 throw new IllegalStateException("UsageStatsManager must be initialized"); 14661 } 14662 long now = System.currentTimeMillis(); 14663 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14664 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14665 String packageName = entry.getKey(); 14666 PackageParser.Package pkg = mPackages.get(packageName); 14667 if (pkg == null) { 14668 continue; 14669 } 14670 UsageStats usage = entry.getValue(); 14671 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14672 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14673 } 14674 } 14675 } 14676 14677 /** 14678 * Check and throw if the given before/after packages would be considered a 14679 * downgrade. 14680 */ 14681 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14682 throws PackageManagerException { 14683 if (after.versionCode < before.mVersionCode) { 14684 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14685 "Update version code " + after.versionCode + " is older than current " 14686 + before.mVersionCode); 14687 } else if (after.versionCode == before.mVersionCode) { 14688 if (after.baseRevisionCode < before.baseRevisionCode) { 14689 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14690 "Update base revision code " + after.baseRevisionCode 14691 + " is older than current " + before.baseRevisionCode); 14692 } 14693 14694 if (!ArrayUtils.isEmpty(after.splitNames)) { 14695 for (int i = 0; i < after.splitNames.length; i++) { 14696 final String splitName = after.splitNames[i]; 14697 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14698 if (j != -1) { 14699 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14700 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14701 "Update split " + splitName + " revision code " 14702 + after.splitRevisionCodes[i] + " is older than current " 14703 + before.splitRevisionCodes[j]); 14704 } 14705 } 14706 } 14707 } 14708 } 14709 } 14710 14711 private static class MoveCallbacks extends Handler { 14712 private static final int MSG_STARTED = 1; 14713 private static final int MSG_STATUS_CHANGED = 2; 14714 14715 private final RemoteCallbackList<IPackageMoveObserver> 14716 mCallbacks = new RemoteCallbackList<>(); 14717 14718 private final SparseIntArray mLastStatus = new SparseIntArray(); 14719 14720 public MoveCallbacks(Looper looper) { 14721 super(looper); 14722 } 14723 14724 public void register(IPackageMoveObserver callback) { 14725 mCallbacks.register(callback); 14726 } 14727 14728 public void unregister(IPackageMoveObserver callback) { 14729 mCallbacks.unregister(callback); 14730 } 14731 14732 @Override 14733 public void handleMessage(Message msg) { 14734 final SomeArgs args = (SomeArgs) msg.obj; 14735 final int n = mCallbacks.beginBroadcast(); 14736 for (int i = 0; i < n; i++) { 14737 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14738 try { 14739 invokeCallback(callback, msg.what, args); 14740 } catch (RemoteException ignored) { 14741 } 14742 } 14743 mCallbacks.finishBroadcast(); 14744 args.recycle(); 14745 } 14746 14747 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14748 throws RemoteException { 14749 switch (what) { 14750 case MSG_STARTED: { 14751 callback.onStarted(args.argi1, (String) args.arg2); 14752 break; 14753 } 14754 case MSG_STATUS_CHANGED: { 14755 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14756 break; 14757 } 14758 } 14759 } 14760 14761 private void notifyStarted(int moveId, String title) { 14762 Slog.v(TAG, "Move " + moveId + " started with title " + title); 14763 14764 final SomeArgs args = SomeArgs.obtain(); 14765 args.argi1 = moveId; 14766 args.arg2 = title; 14767 obtainMessage(MSG_STARTED, args).sendToTarget(); 14768 } 14769 14770 private void notifyStatusChanged(int moveId, int status) { 14771 notifyStatusChanged(moveId, status, -1); 14772 } 14773 14774 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14775 Slog.v(TAG, "Move " + moveId + " status " + status); 14776 14777 final SomeArgs args = SomeArgs.obtain(); 14778 args.argi1 = moveId; 14779 args.argi2 = status; 14780 args.arg3 = estMillis; 14781 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14782 14783 synchronized (mLastStatus) { 14784 mLastStatus.put(moveId, status); 14785 } 14786 } 14787 } 14788} 14789