PackageManagerService.java revision 5c361fc3c219b6999f1208fbc9e6414b87ed7a18
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.IOnPermissionsChangeListener; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageManagerInternal; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260runtest -c android.content.pm.PackageManagerTests frameworks-core 261 * 262 * {@hide} 263 */ 264public class PackageManagerService extends IPackageManager.Stub { 265 static final String TAG = "PackageManager"; 266 static final boolean DEBUG_SETTINGS = false; 267 static final boolean DEBUG_PREFERRED = false; 268 static final boolean DEBUG_UPGRADE = false; 269 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 270 private static final boolean DEBUG_BACKUP = true; 271 private static final boolean DEBUG_INSTALL = false; 272 private static final boolean DEBUG_REMOVE = false; 273 private static final boolean DEBUG_BROADCASTS = false; 274 private static final boolean DEBUG_SHOW_INFO = false; 275 private static final boolean DEBUG_PACKAGE_INFO = false; 276 private static final boolean DEBUG_INTENT_MATCHING = false; 277 private static final boolean DEBUG_PACKAGE_SCANNING = false; 278 private static final boolean DEBUG_VERIFY = false; 279 private static final boolean DEBUG_DEXOPT = false; 280 private static final boolean DEBUG_ABI_SELECTION = false; 281 282 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 283 284 private static final int RADIO_UID = Process.PHONE_UID; 285 private static final int LOG_UID = Process.LOG_UID; 286 private static final int NFC_UID = Process.NFC_UID; 287 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 288 private static final int SHELL_UID = Process.SHELL_UID; 289 290 // Cap the size of permission trees that 3rd party apps can define 291 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 292 293 // Suffix used during package installation when copying/moving 294 // package apks to install directory. 295 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 296 297 static final int SCAN_NO_DEX = 1<<1; 298 static final int SCAN_FORCE_DEX = 1<<2; 299 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 300 static final int SCAN_NEW_INSTALL = 1<<4; 301 static final int SCAN_NO_PATHS = 1<<5; 302 static final int SCAN_UPDATE_TIME = 1<<6; 303 static final int SCAN_DEFER_DEX = 1<<7; 304 static final int SCAN_BOOTING = 1<<8; 305 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 306 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 307 static final int SCAN_REQUIRE_KNOWN = 1<<12; 308 static final int SCAN_MOVE = 1<<13; 309 310 static final int REMOVE_CHATTY = 1<<16; 311 312 private static final int[] EMPTY_INT_ARRAY = new int[0]; 313 314 /** 315 * Timeout (in milliseconds) after which the watchdog should declare that 316 * our handler thread is wedged. The usual default for such things is one 317 * minute but we sometimes do very lengthy I/O operations on this thread, 318 * such as installing multi-gigabyte applications, so ours needs to be longer. 319 */ 320 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 321 322 /** 323 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 324 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 325 * settings entry if available, otherwise we use the hardcoded default. If it's been 326 * more than this long since the last fstrim, we force one during the boot sequence. 327 * 328 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 329 * one gets run at the next available charging+idle time. This final mandatory 330 * no-fstrim check kicks in only of the other scheduling criteria is never met. 331 */ 332 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 333 334 /** 335 * Whether verification is enabled by default. 336 */ 337 private static final boolean DEFAULT_VERIFY_ENABLE = true; 338 339 /** 340 * The default maximum time to wait for the verification agent to return in 341 * milliseconds. 342 */ 343 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 344 345 /** 346 * The default response for package verification timeout. 347 * 348 * This can be either PackageManager.VERIFICATION_ALLOW or 349 * PackageManager.VERIFICATION_REJECT. 350 */ 351 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 352 353 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 354 355 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 356 DEFAULT_CONTAINER_PACKAGE, 357 "com.android.defcontainer.DefaultContainerService"); 358 359 private static final String KILL_APP_REASON_GIDS_CHANGED = 360 "permission grant or revoke changed gids"; 361 362 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 363 "permissions revoked"; 364 365 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 366 367 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 368 369 /** Permission grant: not grant the permission. */ 370 private static final int GRANT_DENIED = 1; 371 372 /** Permission grant: grant the permission as an install permission. */ 373 private static final int GRANT_INSTALL = 2; 374 375 /** Permission grant: grant the permission as an install permission for a legacy app. */ 376 private static final int GRANT_INSTALL_LEGACY = 3; 377 378 /** Permission grant: grant the permission as a runtime one. */ 379 private static final int GRANT_RUNTIME = 4; 380 381 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 382 private static final int GRANT_UPGRADE = 5; 383 384 final ServiceThread mHandlerThread; 385 386 final PackageHandler mHandler; 387 388 /** 389 * Messages for {@link #mHandler} that need to wait for system ready before 390 * being dispatched. 391 */ 392 private ArrayList<Message> mPostSystemReadyMessages; 393 394 final int mSdkVersion = Build.VERSION.SDK_INT; 395 396 final Context mContext; 397 final boolean mFactoryTest; 398 final boolean mOnlyCore; 399 final boolean mLazyDexOpt; 400 final long mDexOptLRUThresholdInMills; 401 final DisplayMetrics mMetrics; 402 final int mDefParseFlags; 403 final String[] mSeparateProcesses; 404 final boolean mIsUpgrade; 405 406 // This is where all application persistent data goes. 407 final File mAppDataDir; 408 409 // This is where all application persistent data goes for secondary users. 410 final File mUserAppDataDir; 411 412 /** The location for ASEC container files on internal storage. */ 413 final String mAsecInternalPath; 414 415 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 416 // LOCK HELD. Can be called with mInstallLock held. 417 final Installer mInstaller; 418 419 /** Directory where installed third-party apps stored */ 420 final File mAppInstallDir; 421 422 /** 423 * Directory to which applications installed internally have their 424 * 32 bit native libraries copied. 425 */ 426 private File mAppLib32InstallDir; 427 428 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 429 // apps. 430 final File mDrmAppPrivateInstallDir; 431 432 // ---------------------------------------------------------------- 433 434 // Lock for state used when installing and doing other long running 435 // operations. Methods that must be called with this lock held have 436 // the suffix "LI". 437 final Object mInstallLock = new Object(); 438 439 // ---------------------------------------------------------------- 440 441 // Keys are String (package name), values are Package. This also serves 442 // as the lock for the global state. Methods that must be called with 443 // this lock held have the prefix "LP". 444 final ArrayMap<String, PackageParser.Package> mPackages = 445 new ArrayMap<String, PackageParser.Package>(); 446 447 // Tracks available target package names -> overlay package paths. 448 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 449 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 450 451 final Settings mSettings; 452 boolean mRestoredSettings; 453 454 // System configuration read by SystemConfig. 455 final int[] mGlobalGids; 456 final SparseArray<ArraySet<String>> mSystemPermissions; 457 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 458 459 // If mac_permissions.xml was found for seinfo labeling. 460 boolean mFoundPolicyFile; 461 462 // If a recursive restorecon of /data/data/<pkg> is needed. 463 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 464 465 public static final class SharedLibraryEntry { 466 public final String path; 467 public final String apk; 468 469 SharedLibraryEntry(String _path, String _apk) { 470 path = _path; 471 apk = _apk; 472 } 473 } 474 475 // Currently known shared libraries. 476 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 477 new ArrayMap<String, SharedLibraryEntry>(); 478 479 // All available activities, for your resolving pleasure. 480 final ActivityIntentResolver mActivities = 481 new ActivityIntentResolver(); 482 483 // All available receivers, for your resolving pleasure. 484 final ActivityIntentResolver mReceivers = 485 new ActivityIntentResolver(); 486 487 // All available services, for your resolving pleasure. 488 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 489 490 // All available providers, for your resolving pleasure. 491 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 492 493 // Mapping from provider base names (first directory in content URI codePath) 494 // to the provider information. 495 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 496 new ArrayMap<String, PackageParser.Provider>(); 497 498 // Mapping from instrumentation class names to info about them. 499 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 500 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 501 502 // Mapping from permission names to info about them. 503 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 504 new ArrayMap<String, PackageParser.PermissionGroup>(); 505 506 // Packages whose data we have transfered into another package, thus 507 // should no longer exist. 508 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 509 510 // Broadcast actions that are only available to the system. 511 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 512 513 /** List of packages waiting for verification. */ 514 final SparseArray<PackageVerificationState> mPendingVerification 515 = new SparseArray<PackageVerificationState>(); 516 517 /** Set of packages associated with each app op permission. */ 518 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 519 520 final PackageInstallerService mInstallerService; 521 522 private final PackageDexOptimizer mPackageDexOptimizer; 523 524 private AtomicInteger mNextMoveId = new AtomicInteger(); 525 private final MoveCallbacks mMoveCallbacks; 526 527 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 528 529 // Cache of users who need badging. 530 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 531 532 /** Token for keys in mPendingVerification. */ 533 private int mPendingVerificationToken = 0; 534 535 volatile boolean mSystemReady; 536 volatile boolean mSafeMode; 537 volatile boolean mHasSystemUidErrors; 538 539 ApplicationInfo mAndroidApplication; 540 final ActivityInfo mResolveActivity = new ActivityInfo(); 541 final ResolveInfo mResolveInfo = new ResolveInfo(); 542 ComponentName mResolveComponentName; 543 PackageParser.Package mPlatformPackage; 544 ComponentName mCustomResolverComponentName; 545 546 boolean mResolverReplaced = false; 547 548 private final ComponentName mIntentFilterVerifierComponent; 549 private int mIntentFilterVerificationToken = 0; 550 551 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 552 = new SparseArray<IntentFilterVerificationState>(); 553 554 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 555 new DefaultPermissionGrantPolicy(this); 556 557 private interface IntentFilterVerifier<T extends IntentFilter> { 558 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 559 T filter, String packageName); 560 void startVerifications(int userId); 561 void receiveVerificationResponse(int verificationId); 562 } 563 564 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 565 private Context mContext; 566 private ComponentName mIntentFilterVerifierComponent; 567 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 568 569 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 570 mContext = context; 571 mIntentFilterVerifierComponent = verifierComponent; 572 } 573 574 private String getDefaultScheme() { 575 return IntentFilter.SCHEME_HTTPS; 576 } 577 578 @Override 579 public void startVerifications(int userId) { 580 // Launch verifications requests 581 int count = mCurrentIntentFilterVerifications.size(); 582 for (int n=0; n<count; n++) { 583 int verificationId = mCurrentIntentFilterVerifications.get(n); 584 final IntentFilterVerificationState ivs = 585 mIntentFilterVerificationStates.get(verificationId); 586 587 String packageName = ivs.getPackageName(); 588 589 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 590 final int filterCount = filters.size(); 591 ArraySet<String> domainsSet = new ArraySet<>(); 592 for (int m=0; m<filterCount; m++) { 593 PackageParser.ActivityIntentInfo filter = filters.get(m); 594 domainsSet.addAll(filter.getHostsList()); 595 } 596 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 597 synchronized (mPackages) { 598 if (mSettings.createIntentFilterVerificationIfNeededLPw( 599 packageName, domainsList) != null) { 600 scheduleWriteSettingsLocked(); 601 } 602 } 603 sendVerificationRequest(userId, verificationId, ivs); 604 } 605 mCurrentIntentFilterVerifications.clear(); 606 } 607 608 private void sendVerificationRequest(int userId, int verificationId, 609 IntentFilterVerificationState ivs) { 610 611 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 612 verificationIntent.putExtra( 613 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 614 verificationId); 615 verificationIntent.putExtra( 616 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 617 getDefaultScheme()); 618 verificationIntent.putExtra( 619 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 620 ivs.getHostsString()); 621 verificationIntent.putExtra( 622 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 623 ivs.getPackageName()); 624 verificationIntent.setComponent(mIntentFilterVerifierComponent); 625 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 626 627 UserHandle user = new UserHandle(userId); 628 mContext.sendBroadcastAsUser(verificationIntent, user); 629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 630 "Sending IntenFilter verification broadcast"); 631 } 632 633 public void receiveVerificationResponse(int verificationId) { 634 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 635 636 final boolean verified = ivs.isVerified(); 637 638 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 639 final int count = filters.size(); 640 for (int n=0; n<count; n++) { 641 PackageParser.ActivityIntentInfo filter = filters.get(n); 642 filter.setVerified(verified); 643 644 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 645 + " verified with result:" + verified + " and hosts:" 646 + ivs.getHostsString()); 647 } 648 649 mIntentFilterVerificationStates.remove(verificationId); 650 651 final String packageName = ivs.getPackageName(); 652 IntentFilterVerificationInfo ivi = null; 653 654 synchronized (mPackages) { 655 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 656 } 657 if (ivi == null) { 658 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 659 + verificationId + " packageName:" + packageName); 660 return; 661 } 662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 663 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 664 665 synchronized (mPackages) { 666 if (verified) { 667 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 668 } else { 669 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 670 } 671 scheduleWriteSettingsLocked(); 672 673 final int userId = ivs.getUserId(); 674 if (userId != UserHandle.USER_ALL) { 675 final int userStatus = 676 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 677 678 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 679 boolean needUpdate = false; 680 681 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 682 // already been set by the User thru the Disambiguation dialog 683 switch (userStatus) { 684 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 685 if (verified) { 686 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 687 } else { 688 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 689 } 690 needUpdate = true; 691 break; 692 693 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 694 if (verified) { 695 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 696 needUpdate = true; 697 } 698 break; 699 700 default: 701 // Nothing to do 702 } 703 704 if (needUpdate) { 705 mSettings.updateIntentFilterVerificationStatusLPw( 706 packageName, updatedStatus, userId); 707 scheduleWritePackageRestrictionsLocked(userId); 708 } 709 } 710 } 711 } 712 713 @Override 714 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 715 ActivityIntentInfo filter, String packageName) { 716 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 717 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 720 return false; 721 } 722 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 723 if (ivs == null) { 724 ivs = createDomainVerificationState(verifierId, userId, verificationId, 725 packageName); 726 } 727 if (!hasValidDomains(filter)) { 728 return false; 729 } 730 ivs.addFilter(filter); 731 return true; 732 } 733 734 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 735 int userId, int verificationId, String packageName) { 736 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 737 verifierId, userId, packageName); 738 ivs.setPendingState(); 739 synchronized (mPackages) { 740 mIntentFilterVerificationStates.append(verificationId, ivs); 741 mCurrentIntentFilterVerifications.add(verificationId); 742 } 743 return ivs; 744 } 745 } 746 747 private static boolean hasValidDomains(ActivityIntentInfo filter) { 748 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 749 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 750 if (!hasHTTPorHTTPS) { 751 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 752 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 753 return false; 754 } 755 return true; 756 } 757 758 private IntentFilterVerifier mIntentFilterVerifier; 759 760 // Set of pending broadcasts for aggregating enable/disable of components. 761 static class PendingPackageBroadcasts { 762 // for each user id, a map of <package name -> components within that package> 763 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 764 765 public PendingPackageBroadcasts() { 766 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 767 } 768 769 public ArrayList<String> get(int userId, String packageName) { 770 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 771 return packages.get(packageName); 772 } 773 774 public void put(int userId, String packageName, ArrayList<String> components) { 775 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 776 packages.put(packageName, components); 777 } 778 779 public void remove(int userId, String packageName) { 780 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 781 if (packages != null) { 782 packages.remove(packageName); 783 } 784 } 785 786 public void remove(int userId) { 787 mUidMap.remove(userId); 788 } 789 790 public int userIdCount() { 791 return mUidMap.size(); 792 } 793 794 public int userIdAt(int n) { 795 return mUidMap.keyAt(n); 796 } 797 798 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 799 return mUidMap.get(userId); 800 } 801 802 public int size() { 803 // total number of pending broadcast entries across all userIds 804 int num = 0; 805 for (int i = 0; i< mUidMap.size(); i++) { 806 num += mUidMap.valueAt(i).size(); 807 } 808 return num; 809 } 810 811 public void clear() { 812 mUidMap.clear(); 813 } 814 815 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 816 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 817 if (map == null) { 818 map = new ArrayMap<String, ArrayList<String>>(); 819 mUidMap.put(userId, map); 820 } 821 return map; 822 } 823 } 824 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 825 826 // Service Connection to remote media container service to copy 827 // package uri's from external media onto secure containers 828 // or internal storage. 829 private IMediaContainerService mContainerService = null; 830 831 static final int SEND_PENDING_BROADCAST = 1; 832 static final int MCS_BOUND = 3; 833 static final int END_COPY = 4; 834 static final int INIT_COPY = 5; 835 static final int MCS_UNBIND = 6; 836 static final int START_CLEANING_PACKAGE = 7; 837 static final int FIND_INSTALL_LOC = 8; 838 static final int POST_INSTALL = 9; 839 static final int MCS_RECONNECT = 10; 840 static final int MCS_GIVE_UP = 11; 841 static final int UPDATED_MEDIA_STATUS = 12; 842 static final int WRITE_SETTINGS = 13; 843 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 844 static final int PACKAGE_VERIFIED = 15; 845 static final int CHECK_PENDING_VERIFICATION = 16; 846 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 847 static final int INTENT_FILTER_VERIFIED = 18; 848 849 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 850 851 // Delay time in millisecs 852 static final int BROADCAST_DELAY = 10 * 1000; 853 854 static UserManagerService sUserManager; 855 856 // Stores a list of users whose package restrictions file needs to be updated 857 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 858 859 final private DefaultContainerConnection mDefContainerConn = 860 new DefaultContainerConnection(); 861 class DefaultContainerConnection implements ServiceConnection { 862 public void onServiceConnected(ComponentName name, IBinder service) { 863 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 864 IMediaContainerService imcs = 865 IMediaContainerService.Stub.asInterface(service); 866 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 867 } 868 869 public void onServiceDisconnected(ComponentName name) { 870 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 871 } 872 }; 873 874 // Recordkeeping of restore-after-install operations that are currently in flight 875 // between the Package Manager and the Backup Manager 876 class PostInstallData { 877 public InstallArgs args; 878 public PackageInstalledInfo res; 879 880 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 881 args = _a; 882 res = _r; 883 } 884 }; 885 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 886 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 887 888 // backup/restore of preferred activity state 889 private static final String TAG_PREFERRED_BACKUP = "pa"; 890 891 private final String mRequiredVerifierPackage; 892 893 private final PackageUsage mPackageUsage = new PackageUsage(); 894 895 private class PackageUsage { 896 private static final int WRITE_INTERVAL 897 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 898 899 private final Object mFileLock = new Object(); 900 private final AtomicLong mLastWritten = new AtomicLong(0); 901 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 902 903 private boolean mIsHistoricalPackageUsageAvailable = true; 904 905 boolean isHistoricalPackageUsageAvailable() { 906 return mIsHistoricalPackageUsageAvailable; 907 } 908 909 void write(boolean force) { 910 if (force) { 911 writeInternal(); 912 return; 913 } 914 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 915 && !DEBUG_DEXOPT) { 916 return; 917 } 918 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 919 new Thread("PackageUsage_DiskWriter") { 920 @Override 921 public void run() { 922 try { 923 writeInternal(); 924 } finally { 925 mBackgroundWriteRunning.set(false); 926 } 927 } 928 }.start(); 929 } 930 } 931 932 private void writeInternal() { 933 synchronized (mPackages) { 934 synchronized (mFileLock) { 935 AtomicFile file = getFile(); 936 FileOutputStream f = null; 937 try { 938 f = file.startWrite(); 939 BufferedOutputStream out = new BufferedOutputStream(f); 940 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 941 StringBuilder sb = new StringBuilder(); 942 for (PackageParser.Package pkg : mPackages.values()) { 943 if (pkg.mLastPackageUsageTimeInMills == 0) { 944 continue; 945 } 946 sb.setLength(0); 947 sb.append(pkg.packageName); 948 sb.append(' '); 949 sb.append((long)pkg.mLastPackageUsageTimeInMills); 950 sb.append('\n'); 951 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 952 } 953 out.flush(); 954 file.finishWrite(f); 955 } catch (IOException e) { 956 if (f != null) { 957 file.failWrite(f); 958 } 959 Log.e(TAG, "Failed to write package usage times", e); 960 } 961 } 962 } 963 mLastWritten.set(SystemClock.elapsedRealtime()); 964 } 965 966 void readLP() { 967 synchronized (mFileLock) { 968 AtomicFile file = getFile(); 969 BufferedInputStream in = null; 970 try { 971 in = new BufferedInputStream(file.openRead()); 972 StringBuffer sb = new StringBuffer(); 973 while (true) { 974 String packageName = readToken(in, sb, ' '); 975 if (packageName == null) { 976 break; 977 } 978 String timeInMillisString = readToken(in, sb, '\n'); 979 if (timeInMillisString == null) { 980 throw new IOException("Failed to find last usage time for package " 981 + packageName); 982 } 983 PackageParser.Package pkg = mPackages.get(packageName); 984 if (pkg == null) { 985 continue; 986 } 987 long timeInMillis; 988 try { 989 timeInMillis = Long.parseLong(timeInMillisString.toString()); 990 } catch (NumberFormatException e) { 991 throw new IOException("Failed to parse " + timeInMillisString 992 + " as a long.", e); 993 } 994 pkg.mLastPackageUsageTimeInMills = timeInMillis; 995 } 996 } catch (FileNotFoundException expected) { 997 mIsHistoricalPackageUsageAvailable = false; 998 } catch (IOException e) { 999 Log.w(TAG, "Failed to read package usage times", e); 1000 } finally { 1001 IoUtils.closeQuietly(in); 1002 } 1003 } 1004 mLastWritten.set(SystemClock.elapsedRealtime()); 1005 } 1006 1007 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1008 throws IOException { 1009 sb.setLength(0); 1010 while (true) { 1011 int ch = in.read(); 1012 if (ch == -1) { 1013 if (sb.length() == 0) { 1014 return null; 1015 } 1016 throw new IOException("Unexpected EOF"); 1017 } 1018 if (ch == endOfToken) { 1019 return sb.toString(); 1020 } 1021 sb.append((char)ch); 1022 } 1023 } 1024 1025 private AtomicFile getFile() { 1026 File dataDir = Environment.getDataDirectory(); 1027 File systemDir = new File(dataDir, "system"); 1028 File fname = new File(systemDir, "package-usage.list"); 1029 return new AtomicFile(fname); 1030 } 1031 } 1032 1033 class PackageHandler extends Handler { 1034 private boolean mBound = false; 1035 final ArrayList<HandlerParams> mPendingInstalls = 1036 new ArrayList<HandlerParams>(); 1037 1038 private boolean connectToService() { 1039 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1040 " DefaultContainerService"); 1041 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1042 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1043 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1044 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 mBound = true; 1047 return true; 1048 } 1049 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1050 return false; 1051 } 1052 1053 private void disconnectService() { 1054 mContainerService = null; 1055 mBound = false; 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1057 mContext.unbindService(mDefContainerConn); 1058 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1059 } 1060 1061 PackageHandler(Looper looper) { 1062 super(looper); 1063 } 1064 1065 public void handleMessage(Message msg) { 1066 try { 1067 doHandleMessage(msg); 1068 } finally { 1069 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1070 } 1071 } 1072 1073 void doHandleMessage(Message msg) { 1074 switch (msg.what) { 1075 case INIT_COPY: { 1076 HandlerParams params = (HandlerParams) msg.obj; 1077 int idx = mPendingInstalls.size(); 1078 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1079 // If a bind was already initiated we dont really 1080 // need to do anything. The pending install 1081 // will be processed later on. 1082 if (!mBound) { 1083 // If this is the only one pending we might 1084 // have to bind to the service again. 1085 if (!connectToService()) { 1086 Slog.e(TAG, "Failed to bind to media container service"); 1087 params.serviceError(); 1088 return; 1089 } else { 1090 // Once we bind to the service, the first 1091 // pending request will be processed. 1092 mPendingInstalls.add(idx, params); 1093 } 1094 } else { 1095 mPendingInstalls.add(idx, params); 1096 // Already bound to the service. Just make 1097 // sure we trigger off processing the first request. 1098 if (idx == 0) { 1099 mHandler.sendEmptyMessage(MCS_BOUND); 1100 } 1101 } 1102 break; 1103 } 1104 case MCS_BOUND: { 1105 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1106 if (msg.obj != null) { 1107 mContainerService = (IMediaContainerService) msg.obj; 1108 } 1109 if (mContainerService == null) { 1110 // Something seriously wrong. Bail out 1111 Slog.e(TAG, "Cannot bind to media container service"); 1112 for (HandlerParams params : mPendingInstalls) { 1113 // Indicate service bind error 1114 params.serviceError(); 1115 } 1116 mPendingInstalls.clear(); 1117 } else if (mPendingInstalls.size() > 0) { 1118 HandlerParams params = mPendingInstalls.get(0); 1119 if (params != null) { 1120 if (params.startCopy()) { 1121 // We are done... look for more work or to 1122 // go idle. 1123 if (DEBUG_SD_INSTALL) Log.i(TAG, 1124 "Checking for more work or unbind..."); 1125 // Delete pending install 1126 if (mPendingInstalls.size() > 0) { 1127 mPendingInstalls.remove(0); 1128 } 1129 if (mPendingInstalls.size() == 0) { 1130 if (mBound) { 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Posting delayed MCS_UNBIND"); 1133 removeMessages(MCS_UNBIND); 1134 Message ubmsg = obtainMessage(MCS_UNBIND); 1135 // Unbind after a little delay, to avoid 1136 // continual thrashing. 1137 sendMessageDelayed(ubmsg, 10000); 1138 } 1139 } else { 1140 // There are more pending requests in queue. 1141 // Just post MCS_BOUND message to trigger processing 1142 // of next pending install. 1143 if (DEBUG_SD_INSTALL) Log.i(TAG, 1144 "Posting MCS_BOUND for next work"); 1145 mHandler.sendEmptyMessage(MCS_BOUND); 1146 } 1147 } 1148 } 1149 } else { 1150 // Should never happen ideally. 1151 Slog.w(TAG, "Empty queue"); 1152 } 1153 break; 1154 } 1155 case MCS_RECONNECT: { 1156 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1157 if (mPendingInstalls.size() > 0) { 1158 if (mBound) { 1159 disconnectService(); 1160 } 1161 if (!connectToService()) { 1162 Slog.e(TAG, "Failed to bind to media container service"); 1163 for (HandlerParams params : mPendingInstalls) { 1164 // Indicate service bind error 1165 params.serviceError(); 1166 } 1167 mPendingInstalls.clear(); 1168 } 1169 } 1170 break; 1171 } 1172 case MCS_UNBIND: { 1173 // If there is no actual work left, then time to unbind. 1174 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1175 1176 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1177 if (mBound) { 1178 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1179 1180 disconnectService(); 1181 } 1182 } else if (mPendingInstalls.size() > 0) { 1183 // There are more pending requests in queue. 1184 // Just post MCS_BOUND message to trigger processing 1185 // of next pending install. 1186 mHandler.sendEmptyMessage(MCS_BOUND); 1187 } 1188 1189 break; 1190 } 1191 case MCS_GIVE_UP: { 1192 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1193 mPendingInstalls.remove(0); 1194 break; 1195 } 1196 case SEND_PENDING_BROADCAST: { 1197 String packages[]; 1198 ArrayList<String> components[]; 1199 int size = 0; 1200 int uids[]; 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1202 synchronized (mPackages) { 1203 if (mPendingBroadcasts == null) { 1204 return; 1205 } 1206 size = mPendingBroadcasts.size(); 1207 if (size <= 0) { 1208 // Nothing to be done. Just return 1209 return; 1210 } 1211 packages = new String[size]; 1212 components = new ArrayList[size]; 1213 uids = new int[size]; 1214 int i = 0; // filling out the above arrays 1215 1216 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1217 int packageUserId = mPendingBroadcasts.userIdAt(n); 1218 Iterator<Map.Entry<String, ArrayList<String>>> it 1219 = mPendingBroadcasts.packagesForUserId(packageUserId) 1220 .entrySet().iterator(); 1221 while (it.hasNext() && i < size) { 1222 Map.Entry<String, ArrayList<String>> ent = it.next(); 1223 packages[i] = ent.getKey(); 1224 components[i] = ent.getValue(); 1225 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1226 uids[i] = (ps != null) 1227 ? UserHandle.getUid(packageUserId, ps.appId) 1228 : -1; 1229 i++; 1230 } 1231 } 1232 size = i; 1233 mPendingBroadcasts.clear(); 1234 } 1235 // Send broadcasts 1236 for (int i = 0; i < size; i++) { 1237 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1238 } 1239 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1240 break; 1241 } 1242 case START_CLEANING_PACKAGE: { 1243 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1244 final String packageName = (String)msg.obj; 1245 final int userId = msg.arg1; 1246 final boolean andCode = msg.arg2 != 0; 1247 synchronized (mPackages) { 1248 if (userId == UserHandle.USER_ALL) { 1249 int[] users = sUserManager.getUserIds(); 1250 for (int user : users) { 1251 mSettings.addPackageToCleanLPw( 1252 new PackageCleanItem(user, packageName, andCode)); 1253 } 1254 } else { 1255 mSettings.addPackageToCleanLPw( 1256 new PackageCleanItem(userId, packageName, andCode)); 1257 } 1258 } 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 startCleaningPackages(); 1261 } break; 1262 case POST_INSTALL: { 1263 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1264 PostInstallData data = mRunningInstalls.get(msg.arg1); 1265 mRunningInstalls.delete(msg.arg1); 1266 boolean deleteOld = false; 1267 1268 if (data != null) { 1269 InstallArgs args = data.args; 1270 PackageInstalledInfo res = data.res; 1271 1272 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1273 res.removedInfo.sendBroadcast(false, true, false); 1274 Bundle extras = new Bundle(1); 1275 extras.putInt(Intent.EXTRA_UID, res.uid); 1276 1277 // Now that we successfully installed the package, grant runtime 1278 // permissions if requested before broadcasting the install. 1279 if ((args.installFlags 1280 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1281 grantRequestedRuntimePermissions(res.pkg, 1282 args.user.getIdentifier()); 1283 } 1284 1285 // Determine the set of users who are adding this 1286 // package for the first time vs. those who are seeing 1287 // an update. 1288 int[] firstUsers; 1289 int[] updateUsers = new int[0]; 1290 if (res.origUsers == null || res.origUsers.length == 0) { 1291 firstUsers = res.newUsers; 1292 } else { 1293 firstUsers = new int[0]; 1294 for (int i=0; i<res.newUsers.length; i++) { 1295 int user = res.newUsers[i]; 1296 boolean isNew = true; 1297 for (int j=0; j<res.origUsers.length; j++) { 1298 if (res.origUsers[j] == user) { 1299 isNew = false; 1300 break; 1301 } 1302 } 1303 if (isNew) { 1304 int[] newFirst = new int[firstUsers.length+1]; 1305 System.arraycopy(firstUsers, 0, newFirst, 0, 1306 firstUsers.length); 1307 newFirst[firstUsers.length] = user; 1308 firstUsers = newFirst; 1309 } else { 1310 int[] newUpdate = new int[updateUsers.length+1]; 1311 System.arraycopy(updateUsers, 0, newUpdate, 0, 1312 updateUsers.length); 1313 newUpdate[updateUsers.length] = user; 1314 updateUsers = newUpdate; 1315 } 1316 } 1317 } 1318 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1319 res.pkg.applicationInfo.packageName, 1320 extras, null, null, firstUsers); 1321 final boolean update = res.removedInfo.removedPackage != null; 1322 if (update) { 1323 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1324 } 1325 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1326 res.pkg.applicationInfo.packageName, 1327 extras, null, null, updateUsers); 1328 if (update) { 1329 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1330 res.pkg.applicationInfo.packageName, 1331 extras, null, null, updateUsers); 1332 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1333 null, null, 1334 res.pkg.applicationInfo.packageName, null, updateUsers); 1335 1336 // treat asec-hosted packages like removable media on upgrade 1337 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1338 if (DEBUG_INSTALL) { 1339 Slog.i(TAG, "upgrading pkg " + res.pkg 1340 + " is ASEC-hosted -> AVAILABLE"); 1341 } 1342 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1343 ArrayList<String> pkgList = new ArrayList<String>(1); 1344 pkgList.add(res.pkg.applicationInfo.packageName); 1345 sendResourcesChangedBroadcast(true, true, 1346 pkgList,uidArray, null); 1347 } 1348 } 1349 if (res.removedInfo.args != null) { 1350 // Remove the replaced package's older resources safely now 1351 deleteOld = true; 1352 } 1353 1354 // Log current value of "unknown sources" setting 1355 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1356 getUnknownSourcesSettings()); 1357 } 1358 // Force a gc to clear up things 1359 Runtime.getRuntime().gc(); 1360 // We delete after a gc for applications on sdcard. 1361 if (deleteOld) { 1362 synchronized (mInstallLock) { 1363 res.removedInfo.args.doPostDeleteLI(true); 1364 } 1365 } 1366 if (args.observer != null) { 1367 try { 1368 Bundle extras = extrasForInstallResult(res); 1369 args.observer.onPackageInstalled(res.name, res.returnCode, 1370 res.returnMsg, extras); 1371 } catch (RemoteException e) { 1372 Slog.i(TAG, "Observer no longer exists."); 1373 } 1374 } 1375 } else { 1376 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1377 } 1378 } break; 1379 case UPDATED_MEDIA_STATUS: { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1381 boolean reportStatus = msg.arg1 == 1; 1382 boolean doGc = msg.arg2 == 1; 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1384 if (doGc) { 1385 // Force a gc to clear up stale containers. 1386 Runtime.getRuntime().gc(); 1387 } 1388 if (msg.obj != null) { 1389 @SuppressWarnings("unchecked") 1390 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1391 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1392 // Unload containers 1393 unloadAllContainers(args); 1394 } 1395 if (reportStatus) { 1396 try { 1397 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1398 PackageHelper.getMountService().finishMediaUpdate(); 1399 } catch (RemoteException e) { 1400 Log.e(TAG, "MountService not running?"); 1401 } 1402 } 1403 } break; 1404 case WRITE_SETTINGS: { 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 synchronized (mPackages) { 1407 removeMessages(WRITE_SETTINGS); 1408 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1409 mSettings.writeLPr(); 1410 mDirtyUsers.clear(); 1411 } 1412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1413 } break; 1414 case WRITE_PACKAGE_RESTRICTIONS: { 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1416 synchronized (mPackages) { 1417 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1418 for (int userId : mDirtyUsers) { 1419 mSettings.writePackageRestrictionsLPr(userId); 1420 } 1421 mDirtyUsers.clear(); 1422 } 1423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1424 } break; 1425 case CHECK_PENDING_VERIFICATION: { 1426 final int verificationId = msg.arg1; 1427 final PackageVerificationState state = mPendingVerification.get(verificationId); 1428 1429 if ((state != null) && !state.timeoutExtended()) { 1430 final InstallArgs args = state.getInstallArgs(); 1431 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1432 1433 Slog.i(TAG, "Verification timed out for " + originUri); 1434 mPendingVerification.remove(verificationId); 1435 1436 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1437 1438 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1439 Slog.i(TAG, "Continuing with installation of " + originUri); 1440 state.setVerifierResponse(Binder.getCallingUid(), 1441 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1442 broadcastPackageVerified(verificationId, originUri, 1443 PackageManager.VERIFICATION_ALLOW, 1444 state.getInstallArgs().getUser()); 1445 try { 1446 ret = args.copyApk(mContainerService, true); 1447 } catch (RemoteException e) { 1448 Slog.e(TAG, "Could not contact the ContainerService"); 1449 } 1450 } else { 1451 broadcastPackageVerified(verificationId, originUri, 1452 PackageManager.VERIFICATION_REJECT, 1453 state.getInstallArgs().getUser()); 1454 } 1455 1456 processPendingInstall(args, ret); 1457 mHandler.sendEmptyMessage(MCS_UNBIND); 1458 } 1459 break; 1460 } 1461 case PACKAGE_VERIFIED: { 1462 final int verificationId = msg.arg1; 1463 1464 final PackageVerificationState state = mPendingVerification.get(verificationId); 1465 if (state == null) { 1466 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1467 break; 1468 } 1469 1470 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1471 1472 state.setVerifierResponse(response.callerUid, response.code); 1473 1474 if (state.isVerificationComplete()) { 1475 mPendingVerification.remove(verificationId); 1476 1477 final InstallArgs args = state.getInstallArgs(); 1478 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1479 1480 int ret; 1481 if (state.isInstallAllowed()) { 1482 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1483 broadcastPackageVerified(verificationId, originUri, 1484 response.code, state.getInstallArgs().getUser()); 1485 try { 1486 ret = args.copyApk(mContainerService, true); 1487 } catch (RemoteException e) { 1488 Slog.e(TAG, "Could not contact the ContainerService"); 1489 } 1490 } else { 1491 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1492 } 1493 1494 processPendingInstall(args, ret); 1495 1496 mHandler.sendEmptyMessage(MCS_UNBIND); 1497 } 1498 1499 break; 1500 } 1501 case START_INTENT_FILTER_VERIFICATIONS: { 1502 int userId = msg.arg1; 1503 int verifierUid = msg.arg2; 1504 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1505 1506 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1507 break; 1508 } 1509 case INTENT_FILTER_VERIFIED: { 1510 final int verificationId = msg.arg1; 1511 1512 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1513 verificationId); 1514 if (state == null) { 1515 Slog.w(TAG, "Invalid IntentFilter verification token " 1516 + verificationId + " received"); 1517 break; 1518 } 1519 1520 final int userId = state.getUserId(); 1521 1522 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1523 "Processing IntentFilter verification with token:" 1524 + verificationId + " and userId:" + userId); 1525 1526 final IntentFilterVerificationResponse response = 1527 (IntentFilterVerificationResponse) msg.obj; 1528 1529 state.setVerifierResponse(response.callerUid, response.code); 1530 1531 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1532 "IntentFilter verification with token:" + verificationId 1533 + " and userId:" + userId 1534 + " is settings verifier response with response code:" 1535 + response.code); 1536 1537 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1538 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1539 + response.getFailedDomainsString()); 1540 } 1541 1542 if (state.isVerificationComplete()) { 1543 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1544 } else { 1545 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1546 "IntentFilter verification with token:" + verificationId 1547 + " was not said to be complete"); 1548 } 1549 1550 break; 1551 } 1552 } 1553 } 1554 } 1555 1556 private StorageEventListener mStorageListener = new StorageEventListener() { 1557 @Override 1558 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1559 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1560 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1561 // TODO: ensure that private directories exist for all active users 1562 // TODO: remove user data whose serial number doesn't match 1563 loadPrivatePackages(vol); 1564 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1565 unloadPrivatePackages(vol); 1566 } 1567 } 1568 1569 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1570 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1571 updateExternalMediaStatus(true, false); 1572 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1573 updateExternalMediaStatus(false, false); 1574 } 1575 } 1576 } 1577 1578 @Override 1579 public void onVolumeForgotten(String fsUuid) { 1580 // TODO: remove all packages hosted on this uuid 1581 } 1582 }; 1583 1584 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1585 if (userId >= UserHandle.USER_OWNER) { 1586 grantRequestedRuntimePermissionsForUser(pkg, userId); 1587 } else if (userId == UserHandle.USER_ALL) { 1588 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1589 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1590 } 1591 } 1592 1593 // We could have touched GID membership, so flush out packages.list 1594 synchronized (mPackages) { 1595 mSettings.writePackageListLPr(); 1596 } 1597 } 1598 1599 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1600 SettingBase sb = (SettingBase) pkg.mExtras; 1601 if (sb == null) { 1602 return; 1603 } 1604 1605 PermissionsState permissionsState = sb.getPermissionsState(); 1606 1607 for (String permission : pkg.requestedPermissions) { 1608 BasePermission bp = mSettings.mPermissions.get(permission); 1609 if (bp != null && bp.isRuntime()) { 1610 permissionsState.grantRuntimePermission(bp, userId); 1611 } 1612 } 1613 } 1614 1615 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1616 Bundle extras = null; 1617 switch (res.returnCode) { 1618 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1619 extras = new Bundle(); 1620 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1621 res.origPermission); 1622 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1623 res.origPackage); 1624 break; 1625 } 1626 case PackageManager.INSTALL_SUCCEEDED: { 1627 extras = new Bundle(); 1628 extras.putBoolean(Intent.EXTRA_REPLACING, 1629 res.removedInfo != null && res.removedInfo.removedPackage != null); 1630 break; 1631 } 1632 } 1633 return extras; 1634 } 1635 1636 void scheduleWriteSettingsLocked() { 1637 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1638 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1639 } 1640 } 1641 1642 void scheduleWritePackageRestrictionsLocked(int userId) { 1643 if (!sUserManager.exists(userId)) return; 1644 mDirtyUsers.add(userId); 1645 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1646 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1647 } 1648 } 1649 1650 public static PackageManagerService main(Context context, Installer installer, 1651 boolean factoryTest, boolean onlyCore) { 1652 PackageManagerService m = new PackageManagerService(context, installer, 1653 factoryTest, onlyCore); 1654 ServiceManager.addService("package", m); 1655 return m; 1656 } 1657 1658 static String[] splitString(String str, char sep) { 1659 int count = 1; 1660 int i = 0; 1661 while ((i=str.indexOf(sep, i)) >= 0) { 1662 count++; 1663 i++; 1664 } 1665 1666 String[] res = new String[count]; 1667 i=0; 1668 count = 0; 1669 int lastI=0; 1670 while ((i=str.indexOf(sep, i)) >= 0) { 1671 res[count] = str.substring(lastI, i); 1672 count++; 1673 i++; 1674 lastI = i; 1675 } 1676 res[count] = str.substring(lastI, str.length()); 1677 return res; 1678 } 1679 1680 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1681 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1682 Context.DISPLAY_SERVICE); 1683 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1684 } 1685 1686 public PackageManagerService(Context context, Installer installer, 1687 boolean factoryTest, boolean onlyCore) { 1688 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1689 SystemClock.uptimeMillis()); 1690 1691 if (mSdkVersion <= 0) { 1692 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1693 } 1694 1695 mContext = context; 1696 mFactoryTest = factoryTest; 1697 mOnlyCore = onlyCore; 1698 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1699 mMetrics = new DisplayMetrics(); 1700 mSettings = new Settings(mPackages); 1701 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1702 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1703 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1704 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1705 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1706 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1707 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1708 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1709 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1710 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1711 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1712 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1713 1714 // TODO: add a property to control this? 1715 long dexOptLRUThresholdInMinutes; 1716 if (mLazyDexOpt) { 1717 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1718 } else { 1719 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1720 } 1721 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1722 1723 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1724 if (separateProcesses != null && separateProcesses.length() > 0) { 1725 if ("*".equals(separateProcesses)) { 1726 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1727 mSeparateProcesses = null; 1728 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1729 } else { 1730 mDefParseFlags = 0; 1731 mSeparateProcesses = separateProcesses.split(","); 1732 Slog.w(TAG, "Running with debug.separate_processes: " 1733 + separateProcesses); 1734 } 1735 } else { 1736 mDefParseFlags = 0; 1737 mSeparateProcesses = null; 1738 } 1739 1740 mInstaller = installer; 1741 mPackageDexOptimizer = new PackageDexOptimizer(this); 1742 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1743 1744 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1745 FgThread.get().getLooper()); 1746 1747 getDefaultDisplayMetrics(context, mMetrics); 1748 1749 SystemConfig systemConfig = SystemConfig.getInstance(); 1750 mGlobalGids = systemConfig.getGlobalGids(); 1751 mSystemPermissions = systemConfig.getSystemPermissions(); 1752 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1753 1754 synchronized (mInstallLock) { 1755 // writer 1756 synchronized (mPackages) { 1757 mHandlerThread = new ServiceThread(TAG, 1758 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1759 mHandlerThread.start(); 1760 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1761 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1762 1763 File dataDir = Environment.getDataDirectory(); 1764 mAppDataDir = new File(dataDir, "data"); 1765 mAppInstallDir = new File(dataDir, "app"); 1766 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1767 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1768 mUserAppDataDir = new File(dataDir, "user"); 1769 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1770 1771 sUserManager = new UserManagerService(context, this, 1772 mInstallLock, mPackages); 1773 1774 // Propagate permission configuration in to package manager. 1775 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1776 = systemConfig.getPermissions(); 1777 for (int i=0; i<permConfig.size(); i++) { 1778 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1779 BasePermission bp = mSettings.mPermissions.get(perm.name); 1780 if (bp == null) { 1781 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1782 mSettings.mPermissions.put(perm.name, bp); 1783 } 1784 if (perm.gids != null) { 1785 bp.setGids(perm.gids, perm.perUser); 1786 } 1787 } 1788 1789 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1790 for (int i=0; i<libConfig.size(); i++) { 1791 mSharedLibraries.put(libConfig.keyAt(i), 1792 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1793 } 1794 1795 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1796 1797 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1798 mSdkVersion, mOnlyCore); 1799 1800 String customResolverActivity = Resources.getSystem().getString( 1801 R.string.config_customResolverActivity); 1802 if (TextUtils.isEmpty(customResolverActivity)) { 1803 customResolverActivity = null; 1804 } else { 1805 mCustomResolverComponentName = ComponentName.unflattenFromString( 1806 customResolverActivity); 1807 } 1808 1809 long startTime = SystemClock.uptimeMillis(); 1810 1811 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1812 startTime); 1813 1814 // Set flag to monitor and not change apk file paths when 1815 // scanning install directories. 1816 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1817 1818 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1819 1820 /** 1821 * Add everything in the in the boot class path to the 1822 * list of process files because dexopt will have been run 1823 * if necessary during zygote startup. 1824 */ 1825 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1826 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1827 1828 if (bootClassPath != null) { 1829 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1830 for (String element : bootClassPathElements) { 1831 alreadyDexOpted.add(element); 1832 } 1833 } else { 1834 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1835 } 1836 1837 if (systemServerClassPath != null) { 1838 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1839 for (String element : systemServerClassPathElements) { 1840 alreadyDexOpted.add(element); 1841 } 1842 } else { 1843 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1844 } 1845 1846 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1847 final String[] dexCodeInstructionSets = 1848 getDexCodeInstructionSets( 1849 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1850 1851 /** 1852 * Ensure all external libraries have had dexopt run on them. 1853 */ 1854 if (mSharedLibraries.size() > 0) { 1855 // NOTE: For now, we're compiling these system "shared libraries" 1856 // (and framework jars) into all available architectures. It's possible 1857 // to compile them only when we come across an app that uses them (there's 1858 // already logic for that in scanPackageLI) but that adds some complexity. 1859 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1860 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1861 final String lib = libEntry.path; 1862 if (lib == null) { 1863 continue; 1864 } 1865 1866 try { 1867 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1868 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1869 alreadyDexOpted.add(lib); 1870 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1871 } 1872 } catch (FileNotFoundException e) { 1873 Slog.w(TAG, "Library not found: " + lib); 1874 } catch (IOException e) { 1875 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1876 + e.getMessage()); 1877 } 1878 } 1879 } 1880 } 1881 1882 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1883 1884 // Gross hack for now: we know this file doesn't contain any 1885 // code, so don't dexopt it to avoid the resulting log spew. 1886 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1887 1888 // Gross hack for now: we know this file is only part of 1889 // the boot class path for art, so don't dexopt it to 1890 // avoid the resulting log spew. 1891 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1892 1893 /** 1894 * There are a number of commands implemented in Java, which 1895 * we currently need to do the dexopt on so that they can be 1896 * run from a non-root shell. 1897 */ 1898 String[] frameworkFiles = frameworkDir.list(); 1899 if (frameworkFiles != null) { 1900 // TODO: We could compile these only for the most preferred ABI. We should 1901 // first double check that the dex files for these commands are not referenced 1902 // by other system apps. 1903 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1904 for (int i=0; i<frameworkFiles.length; i++) { 1905 File libPath = new File(frameworkDir, frameworkFiles[i]); 1906 String path = libPath.getPath(); 1907 // Skip the file if we already did it. 1908 if (alreadyDexOpted.contains(path)) { 1909 continue; 1910 } 1911 // Skip the file if it is not a type we want to dexopt. 1912 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1913 continue; 1914 } 1915 try { 1916 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1917 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1918 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1919 } 1920 } catch (FileNotFoundException e) { 1921 Slog.w(TAG, "Jar not found: " + path); 1922 } catch (IOException e) { 1923 Slog.w(TAG, "Exception reading jar: " + path, e); 1924 } 1925 } 1926 } 1927 } 1928 1929 // Collect vendor overlay packages. 1930 // (Do this before scanning any apps.) 1931 // For security and version matching reason, only consider 1932 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1933 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1934 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1935 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1936 1937 // Find base frameworks (resource packages without code). 1938 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR 1940 | PackageParser.PARSE_IS_PRIVILEGED, 1941 scanFlags | SCAN_NO_DEX, 0); 1942 1943 // Collected privileged system packages. 1944 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1945 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1946 | PackageParser.PARSE_IS_SYSTEM_DIR 1947 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1948 1949 // Collect ordinary system packages. 1950 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1951 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1952 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1953 1954 // Collect all vendor packages. 1955 File vendorAppDir = new File("/vendor/app"); 1956 try { 1957 vendorAppDir = vendorAppDir.getCanonicalFile(); 1958 } catch (IOException e) { 1959 // failed to look up canonical path, continue with original one 1960 } 1961 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1962 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1963 1964 // Collect all OEM packages. 1965 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1966 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1967 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1968 1969 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1970 mInstaller.moveFiles(); 1971 1972 // Prune any system packages that no longer exist. 1973 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1974 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1975 if (!mOnlyCore) { 1976 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1977 while (psit.hasNext()) { 1978 PackageSetting ps = psit.next(); 1979 1980 /* 1981 * If this is not a system app, it can't be a 1982 * disable system app. 1983 */ 1984 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1985 continue; 1986 } 1987 1988 /* 1989 * If the package is scanned, it's not erased. 1990 */ 1991 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1992 if (scannedPkg != null) { 1993 /* 1994 * If the system app is both scanned and in the 1995 * disabled packages list, then it must have been 1996 * added via OTA. Remove it from the currently 1997 * scanned package so the previously user-installed 1998 * application can be scanned. 1999 */ 2000 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2001 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2002 + ps.name + "; removing system app. Last known codePath=" 2003 + ps.codePathString + ", installStatus=" + ps.installStatus 2004 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2005 + scannedPkg.mVersionCode); 2006 removePackageLI(ps, true); 2007 expectingBetter.put(ps.name, ps.codePath); 2008 } 2009 2010 continue; 2011 } 2012 2013 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2014 psit.remove(); 2015 logCriticalInfo(Log.WARN, "System package " + ps.name 2016 + " no longer exists; wiping its data"); 2017 removeDataDirsLI(null, ps.name); 2018 } else { 2019 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2020 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2021 possiblyDeletedUpdatedSystemApps.add(ps.name); 2022 } 2023 } 2024 } 2025 } 2026 2027 //look for any incomplete package installations 2028 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2029 //clean up list 2030 for(int i = 0; i < deletePkgsList.size(); i++) { 2031 //clean up here 2032 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2033 } 2034 //delete tmp files 2035 deleteTempPackageFiles(); 2036 2037 // Remove any shared userIDs that have no associated packages 2038 mSettings.pruneSharedUsersLPw(); 2039 2040 if (!mOnlyCore) { 2041 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2042 SystemClock.uptimeMillis()); 2043 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2044 2045 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2046 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2047 2048 /** 2049 * Remove disable package settings for any updated system 2050 * apps that were removed via an OTA. If they're not a 2051 * previously-updated app, remove them completely. 2052 * Otherwise, just revoke their system-level permissions. 2053 */ 2054 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2055 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2056 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2057 2058 String msg; 2059 if (deletedPkg == null) { 2060 msg = "Updated system package " + deletedAppName 2061 + " no longer exists; wiping its data"; 2062 removeDataDirsLI(null, deletedAppName); 2063 } else { 2064 msg = "Updated system app + " + deletedAppName 2065 + " no longer present; removing system privileges for " 2066 + deletedAppName; 2067 2068 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2069 2070 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2071 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2072 } 2073 logCriticalInfo(Log.WARN, msg); 2074 } 2075 2076 /** 2077 * Make sure all system apps that we expected to appear on 2078 * the userdata partition actually showed up. If they never 2079 * appeared, crawl back and revive the system version. 2080 */ 2081 for (int i = 0; i < expectingBetter.size(); i++) { 2082 final String packageName = expectingBetter.keyAt(i); 2083 if (!mPackages.containsKey(packageName)) { 2084 final File scanFile = expectingBetter.valueAt(i); 2085 2086 logCriticalInfo(Log.WARN, "Expected better " + packageName 2087 + " but never showed up; reverting to system"); 2088 2089 final int reparseFlags; 2090 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2091 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR 2093 | PackageParser.PARSE_IS_PRIVILEGED; 2094 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2095 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR; 2097 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2098 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2099 | PackageParser.PARSE_IS_SYSTEM_DIR; 2100 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2101 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2102 | PackageParser.PARSE_IS_SYSTEM_DIR; 2103 } else { 2104 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2105 continue; 2106 } 2107 2108 mSettings.enableSystemPackageLPw(packageName); 2109 2110 try { 2111 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2112 } catch (PackageManagerException e) { 2113 Slog.e(TAG, "Failed to parse original system package: " 2114 + e.getMessage()); 2115 } 2116 } 2117 } 2118 } 2119 2120 // Now that we know all of the shared libraries, update all clients to have 2121 // the correct library paths. 2122 updateAllSharedLibrariesLPw(); 2123 2124 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2125 // NOTE: We ignore potential failures here during a system scan (like 2126 // the rest of the commands above) because there's precious little we 2127 // can do about it. A settings error is reported, though. 2128 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2129 false /* force dexopt */, false /* defer dexopt */); 2130 } 2131 2132 // Now that we know all the packages we are keeping, 2133 // read and update their last usage times. 2134 mPackageUsage.readLP(); 2135 2136 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2137 SystemClock.uptimeMillis()); 2138 Slog.i(TAG, "Time to scan packages: " 2139 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2140 + " seconds"); 2141 2142 // If the platform SDK has changed since the last time we booted, 2143 // we need to re-grant app permission to catch any new ones that 2144 // appear. This is really a hack, and means that apps can in some 2145 // cases get permissions that the user didn't initially explicitly 2146 // allow... it would be nice to have some better way to handle 2147 // this situation. 2148 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2149 != mSdkVersion; 2150 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2151 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2152 + "; regranting permissions for internal storage"); 2153 mSettings.mInternalSdkPlatform = mSdkVersion; 2154 2155 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2156 | (regrantPermissions 2157 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2158 : 0)); 2159 2160 // If this is the first boot, and it is a normal boot, then 2161 // we need to initialize the default preferred apps. 2162 if (!mRestoredSettings && !onlyCore) { 2163 mSettings.readDefaultPreferredAppsLPw(this, 0); 2164 } 2165 2166 // If this is first boot after an OTA, and a normal boot, then 2167 // we need to clear code cache directories. 2168 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2169 if (mIsUpgrade && !onlyCore) { 2170 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2171 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2172 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2173 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2174 } 2175 mSettings.mFingerprint = Build.FINGERPRINT; 2176 } 2177 2178 primeDomainVerificationsLPw(); 2179 checkDefaultBrowser(); 2180 2181 // All the changes are done during package scanning. 2182 mSettings.updateInternalDatabaseVersion(); 2183 2184 // can downgrade to reader 2185 mSettings.writeLPr(); 2186 2187 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2188 SystemClock.uptimeMillis()); 2189 2190 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2191 2192 mInstallerService = new PackageInstallerService(context, this); 2193 2194 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2195 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2196 mIntentFilterVerifierComponent); 2197 2198 } // synchronized (mPackages) 2199 } // synchronized (mInstallLock) 2200 2201 // Now after opening every single application zip, make sure they 2202 // are all flushed. Not really needed, but keeps things nice and 2203 // tidy. 2204 Runtime.getRuntime().gc(); 2205 2206 // Expose private service for system components to use. 2207 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2208 } 2209 2210 @Override 2211 public boolean isFirstBoot() { 2212 return !mRestoredSettings; 2213 } 2214 2215 @Override 2216 public boolean isOnlyCoreApps() { 2217 return mOnlyCore; 2218 } 2219 2220 @Override 2221 public boolean isUpgrade() { 2222 return mIsUpgrade; 2223 } 2224 2225 private String getRequiredVerifierLPr() { 2226 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2227 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2228 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2229 2230 String requiredVerifier = null; 2231 2232 final int N = receivers.size(); 2233 for (int i = 0; i < N; i++) { 2234 final ResolveInfo info = receivers.get(i); 2235 2236 if (info.activityInfo == null) { 2237 continue; 2238 } 2239 2240 final String packageName = info.activityInfo.packageName; 2241 2242 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2243 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2244 continue; 2245 } 2246 2247 if (requiredVerifier != null) { 2248 throw new RuntimeException("There can be only one required verifier"); 2249 } 2250 2251 requiredVerifier = packageName; 2252 } 2253 2254 return requiredVerifier; 2255 } 2256 2257 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2258 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2259 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2260 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2261 2262 ComponentName verifierComponentName = null; 2263 2264 int priority = -1000; 2265 final int N = receivers.size(); 2266 for (int i = 0; i < N; i++) { 2267 final ResolveInfo info = receivers.get(i); 2268 2269 if (info.activityInfo == null) { 2270 continue; 2271 } 2272 2273 final String packageName = info.activityInfo.packageName; 2274 2275 final PackageSetting ps = mSettings.mPackages.get(packageName); 2276 if (ps == null) { 2277 continue; 2278 } 2279 2280 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2281 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2282 continue; 2283 } 2284 2285 // Select the IntentFilterVerifier with the highest priority 2286 if (priority < info.priority) { 2287 priority = info.priority; 2288 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2289 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2290 + verifierComponentName + " with priority: " + info.priority); 2291 } 2292 } 2293 2294 return verifierComponentName; 2295 } 2296 2297 private void primeDomainVerificationsLPw() { 2298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2299 boolean updated = false; 2300 ArraySet<String> allHostsSet = new ArraySet<>(); 2301 for (PackageParser.Package pkg : mPackages.values()) { 2302 final String packageName = pkg.packageName; 2303 if (!hasDomainURLs(pkg)) { 2304 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2305 "package with no domain URLs: " + packageName); 2306 continue; 2307 } 2308 if (!pkg.isSystemApp()) { 2309 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2310 "No priming domain verifications for a non system package : " + 2311 packageName); 2312 continue; 2313 } 2314 for (PackageParser.Activity a : pkg.activities) { 2315 for (ActivityIntentInfo filter : a.intents) { 2316 if (hasValidDomains(filter)) { 2317 allHostsSet.addAll(filter.getHostsList()); 2318 } 2319 } 2320 } 2321 if (allHostsSet.size() == 0) { 2322 allHostsSet.add("*"); 2323 } 2324 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2325 IntentFilterVerificationInfo ivi = 2326 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2327 if (ivi != null) { 2328 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2329 "Priming domain verifications for package: " + packageName + 2330 " with hosts:" + ivi.getDomainsString()); 2331 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2332 updated = true; 2333 } 2334 else { 2335 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2336 "No priming domain verifications for package: " + packageName); 2337 } 2338 allHostsSet.clear(); 2339 } 2340 if (updated) { 2341 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2342 "Will need to write primed domain verifications"); 2343 } 2344 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2345 } 2346 2347 private void checkDefaultBrowser() { 2348 final int myUserId = UserHandle.myUserId(); 2349 final String packageName = getDefaultBrowserPackageName(myUserId); 2350 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2351 if (info == null) { 2352 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2353 packageName); 2354 setDefaultBrowserPackageName(null, myUserId); 2355 } 2356 } 2357 2358 @Override 2359 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2360 throws RemoteException { 2361 try { 2362 return super.onTransact(code, data, reply, flags); 2363 } catch (RuntimeException e) { 2364 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2365 Slog.wtf(TAG, "Package Manager Crash", e); 2366 } 2367 throw e; 2368 } 2369 } 2370 2371 void cleanupInstallFailedPackage(PackageSetting ps) { 2372 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2373 2374 removeDataDirsLI(ps.volumeUuid, ps.name); 2375 if (ps.codePath != null) { 2376 if (ps.codePath.isDirectory()) { 2377 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2378 } else { 2379 ps.codePath.delete(); 2380 } 2381 } 2382 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2383 if (ps.resourcePath.isDirectory()) { 2384 FileUtils.deleteContents(ps.resourcePath); 2385 } 2386 ps.resourcePath.delete(); 2387 } 2388 mSettings.removePackageLPw(ps.name); 2389 } 2390 2391 static int[] appendInts(int[] cur, int[] add) { 2392 if (add == null) return cur; 2393 if (cur == null) return add; 2394 final int N = add.length; 2395 for (int i=0; i<N; i++) { 2396 cur = appendInt(cur, add[i]); 2397 } 2398 return cur; 2399 } 2400 2401 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2402 if (!sUserManager.exists(userId)) return null; 2403 final PackageSetting ps = (PackageSetting) p.mExtras; 2404 if (ps == null) { 2405 return null; 2406 } 2407 2408 final PermissionsState permissionsState = ps.getPermissionsState(); 2409 2410 final int[] gids = permissionsState.computeGids(userId); 2411 final Set<String> permissions = permissionsState.getPermissions(userId); 2412 final PackageUserState state = ps.readUserState(userId); 2413 2414 return PackageParser.generatePackageInfo(p, gids, flags, 2415 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2416 } 2417 2418 @Override 2419 public boolean isPackageFrozen(String packageName) { 2420 synchronized (mPackages) { 2421 final PackageSetting ps = mSettings.mPackages.get(packageName); 2422 if (ps != null) { 2423 return ps.frozen; 2424 } 2425 } 2426 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2427 return true; 2428 } 2429 2430 @Override 2431 public boolean isPackageAvailable(String packageName, int userId) { 2432 if (!sUserManager.exists(userId)) return false; 2433 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2434 synchronized (mPackages) { 2435 PackageParser.Package p = mPackages.get(packageName); 2436 if (p != null) { 2437 final PackageSetting ps = (PackageSetting) p.mExtras; 2438 if (ps != null) { 2439 final PackageUserState state = ps.readUserState(userId); 2440 if (state != null) { 2441 return PackageParser.isAvailable(state); 2442 } 2443 } 2444 } 2445 } 2446 return false; 2447 } 2448 2449 @Override 2450 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2451 if (!sUserManager.exists(userId)) return null; 2452 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2453 // reader 2454 synchronized (mPackages) { 2455 PackageParser.Package p = mPackages.get(packageName); 2456 if (DEBUG_PACKAGE_INFO) 2457 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2458 if (p != null) { 2459 return generatePackageInfo(p, flags, userId); 2460 } 2461 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2462 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2463 } 2464 } 2465 return null; 2466 } 2467 2468 @Override 2469 public String[] currentToCanonicalPackageNames(String[] names) { 2470 String[] out = new String[names.length]; 2471 // reader 2472 synchronized (mPackages) { 2473 for (int i=names.length-1; i>=0; i--) { 2474 PackageSetting ps = mSettings.mPackages.get(names[i]); 2475 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2476 } 2477 } 2478 return out; 2479 } 2480 2481 @Override 2482 public String[] canonicalToCurrentPackageNames(String[] names) { 2483 String[] out = new String[names.length]; 2484 // reader 2485 synchronized (mPackages) { 2486 for (int i=names.length-1; i>=0; i--) { 2487 String cur = mSettings.mRenamedPackages.get(names[i]); 2488 out[i] = cur != null ? cur : names[i]; 2489 } 2490 } 2491 return out; 2492 } 2493 2494 @Override 2495 public int getPackageUid(String packageName, int userId) { 2496 if (!sUserManager.exists(userId)) return -1; 2497 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2498 2499 // reader 2500 synchronized (mPackages) { 2501 PackageParser.Package p = mPackages.get(packageName); 2502 if(p != null) { 2503 return UserHandle.getUid(userId, p.applicationInfo.uid); 2504 } 2505 PackageSetting ps = mSettings.mPackages.get(packageName); 2506 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2507 return -1; 2508 } 2509 p = ps.pkg; 2510 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2511 } 2512 } 2513 2514 @Override 2515 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2516 if (!sUserManager.exists(userId)) { 2517 return null; 2518 } 2519 2520 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2521 "getPackageGids"); 2522 2523 // reader 2524 synchronized (mPackages) { 2525 PackageParser.Package p = mPackages.get(packageName); 2526 if (DEBUG_PACKAGE_INFO) { 2527 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2528 } 2529 if (p != null) { 2530 PackageSetting ps = (PackageSetting) p.mExtras; 2531 return ps.getPermissionsState().computeGids(userId); 2532 } 2533 } 2534 2535 return null; 2536 } 2537 2538 static PermissionInfo generatePermissionInfo( 2539 BasePermission bp, int flags) { 2540 if (bp.perm != null) { 2541 return PackageParser.generatePermissionInfo(bp.perm, flags); 2542 } 2543 PermissionInfo pi = new PermissionInfo(); 2544 pi.name = bp.name; 2545 pi.packageName = bp.sourcePackage; 2546 pi.nonLocalizedLabel = bp.name; 2547 pi.protectionLevel = bp.protectionLevel; 2548 return pi; 2549 } 2550 2551 @Override 2552 public PermissionInfo getPermissionInfo(String name, int flags) { 2553 // reader 2554 synchronized (mPackages) { 2555 final BasePermission p = mSettings.mPermissions.get(name); 2556 if (p != null) { 2557 return generatePermissionInfo(p, flags); 2558 } 2559 return null; 2560 } 2561 } 2562 2563 @Override 2564 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2565 // reader 2566 synchronized (mPackages) { 2567 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2568 for (BasePermission p : mSettings.mPermissions.values()) { 2569 if (group == null) { 2570 if (p.perm == null || p.perm.info.group == null) { 2571 out.add(generatePermissionInfo(p, flags)); 2572 } 2573 } else { 2574 if (p.perm != null && group.equals(p.perm.info.group)) { 2575 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2576 } 2577 } 2578 } 2579 2580 if (out.size() > 0) { 2581 return out; 2582 } 2583 return mPermissionGroups.containsKey(group) ? out : null; 2584 } 2585 } 2586 2587 @Override 2588 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2589 // reader 2590 synchronized (mPackages) { 2591 return PackageParser.generatePermissionGroupInfo( 2592 mPermissionGroups.get(name), flags); 2593 } 2594 } 2595 2596 @Override 2597 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2598 // reader 2599 synchronized (mPackages) { 2600 final int N = mPermissionGroups.size(); 2601 ArrayList<PermissionGroupInfo> out 2602 = new ArrayList<PermissionGroupInfo>(N); 2603 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2604 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2605 } 2606 return out; 2607 } 2608 } 2609 2610 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2611 int userId) { 2612 if (!sUserManager.exists(userId)) return null; 2613 PackageSetting ps = mSettings.mPackages.get(packageName); 2614 if (ps != null) { 2615 if (ps.pkg == null) { 2616 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2617 flags, userId); 2618 if (pInfo != null) { 2619 return pInfo.applicationInfo; 2620 } 2621 return null; 2622 } 2623 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2624 ps.readUserState(userId), userId); 2625 } 2626 return null; 2627 } 2628 2629 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2630 int userId) { 2631 if (!sUserManager.exists(userId)) return null; 2632 PackageSetting ps = mSettings.mPackages.get(packageName); 2633 if (ps != null) { 2634 PackageParser.Package pkg = ps.pkg; 2635 if (pkg == null) { 2636 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2637 return null; 2638 } 2639 // Only data remains, so we aren't worried about code paths 2640 pkg = new PackageParser.Package(packageName); 2641 pkg.applicationInfo.packageName = packageName; 2642 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2643 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2644 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2645 packageName, userId).getAbsolutePath(); 2646 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2647 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2648 } 2649 return generatePackageInfo(pkg, flags, userId); 2650 } 2651 return null; 2652 } 2653 2654 @Override 2655 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2656 if (!sUserManager.exists(userId)) return null; 2657 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2658 // writer 2659 synchronized (mPackages) { 2660 PackageParser.Package p = mPackages.get(packageName); 2661 if (DEBUG_PACKAGE_INFO) Log.v( 2662 TAG, "getApplicationInfo " + packageName 2663 + ": " + p); 2664 if (p != null) { 2665 PackageSetting ps = mSettings.mPackages.get(packageName); 2666 if (ps == null) return null; 2667 // Note: isEnabledLP() does not apply here - always return info 2668 return PackageParser.generateApplicationInfo( 2669 p, flags, ps.readUserState(userId), userId); 2670 } 2671 if ("android".equals(packageName)||"system".equals(packageName)) { 2672 return mAndroidApplication; 2673 } 2674 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2675 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2676 } 2677 } 2678 return null; 2679 } 2680 2681 @Override 2682 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2683 final IPackageDataObserver observer) { 2684 mContext.enforceCallingOrSelfPermission( 2685 android.Manifest.permission.CLEAR_APP_CACHE, null); 2686 // Queue up an async operation since clearing cache may take a little while. 2687 mHandler.post(new Runnable() { 2688 public void run() { 2689 mHandler.removeCallbacks(this); 2690 int retCode = -1; 2691 synchronized (mInstallLock) { 2692 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2693 if (retCode < 0) { 2694 Slog.w(TAG, "Couldn't clear application caches"); 2695 } 2696 } 2697 if (observer != null) { 2698 try { 2699 observer.onRemoveCompleted(null, (retCode >= 0)); 2700 } catch (RemoteException e) { 2701 Slog.w(TAG, "RemoveException when invoking call back"); 2702 } 2703 } 2704 } 2705 }); 2706 } 2707 2708 @Override 2709 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2710 final IntentSender pi) { 2711 mContext.enforceCallingOrSelfPermission( 2712 android.Manifest.permission.CLEAR_APP_CACHE, null); 2713 // Queue up an async operation since clearing cache may take a little while. 2714 mHandler.post(new Runnable() { 2715 public void run() { 2716 mHandler.removeCallbacks(this); 2717 int retCode = -1; 2718 synchronized (mInstallLock) { 2719 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2720 if (retCode < 0) { 2721 Slog.w(TAG, "Couldn't clear application caches"); 2722 } 2723 } 2724 if(pi != null) { 2725 try { 2726 // Callback via pending intent 2727 int code = (retCode >= 0) ? 1 : 0; 2728 pi.sendIntent(null, code, null, 2729 null, null); 2730 } catch (SendIntentException e1) { 2731 Slog.i(TAG, "Failed to send pending intent"); 2732 } 2733 } 2734 } 2735 }); 2736 } 2737 2738 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2739 synchronized (mInstallLock) { 2740 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2741 throw new IOException("Failed to free enough space"); 2742 } 2743 } 2744 } 2745 2746 @Override 2747 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2748 if (!sUserManager.exists(userId)) return null; 2749 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2750 synchronized (mPackages) { 2751 PackageParser.Activity a = mActivities.mActivities.get(component); 2752 2753 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2754 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2755 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2756 if (ps == null) return null; 2757 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2758 userId); 2759 } 2760 if (mResolveComponentName.equals(component)) { 2761 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2762 new PackageUserState(), userId); 2763 } 2764 } 2765 return null; 2766 } 2767 2768 @Override 2769 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2770 String resolvedType) { 2771 synchronized (mPackages) { 2772 PackageParser.Activity a = mActivities.mActivities.get(component); 2773 if (a == null) { 2774 return false; 2775 } 2776 for (int i=0; i<a.intents.size(); i++) { 2777 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2778 intent.getData(), intent.getCategories(), TAG) >= 0) { 2779 return true; 2780 } 2781 } 2782 return false; 2783 } 2784 } 2785 2786 @Override 2787 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2788 if (!sUserManager.exists(userId)) return null; 2789 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2790 synchronized (mPackages) { 2791 PackageParser.Activity a = mReceivers.mActivities.get(component); 2792 if (DEBUG_PACKAGE_INFO) Log.v( 2793 TAG, "getReceiverInfo " + component + ": " + a); 2794 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2795 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2796 if (ps == null) return null; 2797 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2798 userId); 2799 } 2800 } 2801 return null; 2802 } 2803 2804 @Override 2805 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2806 if (!sUserManager.exists(userId)) return null; 2807 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2808 synchronized (mPackages) { 2809 PackageParser.Service s = mServices.mServices.get(component); 2810 if (DEBUG_PACKAGE_INFO) Log.v( 2811 TAG, "getServiceInfo " + component + ": " + s); 2812 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2813 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2814 if (ps == null) return null; 2815 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2816 userId); 2817 } 2818 } 2819 return null; 2820 } 2821 2822 @Override 2823 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2824 if (!sUserManager.exists(userId)) return null; 2825 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2826 synchronized (mPackages) { 2827 PackageParser.Provider p = mProviders.mProviders.get(component); 2828 if (DEBUG_PACKAGE_INFO) Log.v( 2829 TAG, "getProviderInfo " + component + ": " + p); 2830 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2831 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2832 if (ps == null) return null; 2833 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2834 userId); 2835 } 2836 } 2837 return null; 2838 } 2839 2840 @Override 2841 public String[] getSystemSharedLibraryNames() { 2842 Set<String> libSet; 2843 synchronized (mPackages) { 2844 libSet = mSharedLibraries.keySet(); 2845 int size = libSet.size(); 2846 if (size > 0) { 2847 String[] libs = new String[size]; 2848 libSet.toArray(libs); 2849 return libs; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 /** 2856 * @hide 2857 */ 2858 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2859 synchronized (mPackages) { 2860 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2861 if (lib != null && lib.apk != null) { 2862 return mPackages.get(lib.apk); 2863 } 2864 } 2865 return null; 2866 } 2867 2868 @Override 2869 public FeatureInfo[] getSystemAvailableFeatures() { 2870 Collection<FeatureInfo> featSet; 2871 synchronized (mPackages) { 2872 featSet = mAvailableFeatures.values(); 2873 int size = featSet.size(); 2874 if (size > 0) { 2875 FeatureInfo[] features = new FeatureInfo[size+1]; 2876 featSet.toArray(features); 2877 FeatureInfo fi = new FeatureInfo(); 2878 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2879 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2880 features[size] = fi; 2881 return features; 2882 } 2883 } 2884 return null; 2885 } 2886 2887 @Override 2888 public boolean hasSystemFeature(String name) { 2889 synchronized (mPackages) { 2890 return mAvailableFeatures.containsKey(name); 2891 } 2892 } 2893 2894 private void checkValidCaller(int uid, int userId) { 2895 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2896 return; 2897 2898 throw new SecurityException("Caller uid=" + uid 2899 + " is not privileged to communicate with user=" + userId); 2900 } 2901 2902 @Override 2903 public int checkPermission(String permName, String pkgName, int userId) { 2904 if (!sUserManager.exists(userId)) { 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 synchronized (mPackages) { 2909 final PackageParser.Package p = mPackages.get(pkgName); 2910 if (p != null && p.mExtras != null) { 2911 final PackageSetting ps = (PackageSetting) p.mExtras; 2912 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2913 return PackageManager.PERMISSION_GRANTED; 2914 } 2915 } 2916 } 2917 2918 return PackageManager.PERMISSION_DENIED; 2919 } 2920 2921 @Override 2922 public int checkUidPermission(String permName, int uid) { 2923 final int userId = UserHandle.getUserId(uid); 2924 2925 if (!sUserManager.exists(userId)) { 2926 return PackageManager.PERMISSION_DENIED; 2927 } 2928 2929 synchronized (mPackages) { 2930 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2931 if (obj != null) { 2932 final SettingBase ps = (SettingBase) obj; 2933 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2934 return PackageManager.PERMISSION_GRANTED; 2935 } 2936 } else { 2937 ArraySet<String> perms = mSystemPermissions.get(uid); 2938 if (perms != null && perms.contains(permName)) { 2939 return PackageManager.PERMISSION_GRANTED; 2940 } 2941 } 2942 } 2943 2944 return PackageManager.PERMISSION_DENIED; 2945 } 2946 2947 /** 2948 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2949 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2950 * @param checkShell TODO(yamasani): 2951 * @param message the message to log on security exception 2952 */ 2953 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2954 boolean checkShell, String message) { 2955 if (userId < 0) { 2956 throw new IllegalArgumentException("Invalid userId " + userId); 2957 } 2958 if (checkShell) { 2959 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2960 } 2961 if (userId == UserHandle.getUserId(callingUid)) return; 2962 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2963 if (requireFullPermission) { 2964 mContext.enforceCallingOrSelfPermission( 2965 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2966 } else { 2967 try { 2968 mContext.enforceCallingOrSelfPermission( 2969 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2970 } catch (SecurityException se) { 2971 mContext.enforceCallingOrSelfPermission( 2972 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2973 } 2974 } 2975 } 2976 } 2977 2978 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2979 if (callingUid == Process.SHELL_UID) { 2980 if (userHandle >= 0 2981 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2982 throw new SecurityException("Shell does not have permission to access user " 2983 + userHandle); 2984 } else if (userHandle < 0) { 2985 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2986 + Debug.getCallers(3)); 2987 } 2988 } 2989 } 2990 2991 private BasePermission findPermissionTreeLP(String permName) { 2992 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2993 if (permName.startsWith(bp.name) && 2994 permName.length() > bp.name.length() && 2995 permName.charAt(bp.name.length()) == '.') { 2996 return bp; 2997 } 2998 } 2999 return null; 3000 } 3001 3002 private BasePermission checkPermissionTreeLP(String permName) { 3003 if (permName != null) { 3004 BasePermission bp = findPermissionTreeLP(permName); 3005 if (bp != null) { 3006 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3007 return bp; 3008 } 3009 throw new SecurityException("Calling uid " 3010 + Binder.getCallingUid() 3011 + " is not allowed to add to permission tree " 3012 + bp.name + " owned by uid " + bp.uid); 3013 } 3014 } 3015 throw new SecurityException("No permission tree found for " + permName); 3016 } 3017 3018 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3019 if (s1 == null) { 3020 return s2 == null; 3021 } 3022 if (s2 == null) { 3023 return false; 3024 } 3025 if (s1.getClass() != s2.getClass()) { 3026 return false; 3027 } 3028 return s1.equals(s2); 3029 } 3030 3031 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3032 if (pi1.icon != pi2.icon) return false; 3033 if (pi1.logo != pi2.logo) return false; 3034 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3035 if (!compareStrings(pi1.name, pi2.name)) return false; 3036 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3037 // We'll take care of setting this one. 3038 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3039 // These are not currently stored in settings. 3040 //if (!compareStrings(pi1.group, pi2.group)) return false; 3041 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3042 //if (pi1.labelRes != pi2.labelRes) return false; 3043 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3044 return true; 3045 } 3046 3047 int permissionInfoFootprint(PermissionInfo info) { 3048 int size = info.name.length(); 3049 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3050 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3051 return size; 3052 } 3053 3054 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3055 int size = 0; 3056 for (BasePermission perm : mSettings.mPermissions.values()) { 3057 if (perm.uid == tree.uid) { 3058 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3059 } 3060 } 3061 return size; 3062 } 3063 3064 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3065 // We calculate the max size of permissions defined by this uid and throw 3066 // if that plus the size of 'info' would exceed our stated maximum. 3067 if (tree.uid != Process.SYSTEM_UID) { 3068 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3069 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3070 throw new SecurityException("Permission tree size cap exceeded"); 3071 } 3072 } 3073 } 3074 3075 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3076 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3077 throw new SecurityException("Label must be specified in permission"); 3078 } 3079 BasePermission tree = checkPermissionTreeLP(info.name); 3080 BasePermission bp = mSettings.mPermissions.get(info.name); 3081 boolean added = bp == null; 3082 boolean changed = true; 3083 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3084 if (added) { 3085 enforcePermissionCapLocked(info, tree); 3086 bp = new BasePermission(info.name, tree.sourcePackage, 3087 BasePermission.TYPE_DYNAMIC); 3088 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3089 throw new SecurityException( 3090 "Not allowed to modify non-dynamic permission " 3091 + info.name); 3092 } else { 3093 if (bp.protectionLevel == fixedLevel 3094 && bp.perm.owner.equals(tree.perm.owner) 3095 && bp.uid == tree.uid 3096 && comparePermissionInfos(bp.perm.info, info)) { 3097 changed = false; 3098 } 3099 } 3100 bp.protectionLevel = fixedLevel; 3101 info = new PermissionInfo(info); 3102 info.protectionLevel = fixedLevel; 3103 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3104 bp.perm.info.packageName = tree.perm.info.packageName; 3105 bp.uid = tree.uid; 3106 if (added) { 3107 mSettings.mPermissions.put(info.name, bp); 3108 } 3109 if (changed) { 3110 if (!async) { 3111 mSettings.writeLPr(); 3112 } else { 3113 scheduleWriteSettingsLocked(); 3114 } 3115 } 3116 return added; 3117 } 3118 3119 @Override 3120 public boolean addPermission(PermissionInfo info) { 3121 synchronized (mPackages) { 3122 return addPermissionLocked(info, false); 3123 } 3124 } 3125 3126 @Override 3127 public boolean addPermissionAsync(PermissionInfo info) { 3128 synchronized (mPackages) { 3129 return addPermissionLocked(info, true); 3130 } 3131 } 3132 3133 @Override 3134 public void removePermission(String name) { 3135 synchronized (mPackages) { 3136 checkPermissionTreeLP(name); 3137 BasePermission bp = mSettings.mPermissions.get(name); 3138 if (bp != null) { 3139 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3140 throw new SecurityException( 3141 "Not allowed to modify non-dynamic permission " 3142 + name); 3143 } 3144 mSettings.mPermissions.remove(name); 3145 mSettings.writeLPr(); 3146 } 3147 } 3148 } 3149 3150 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3151 BasePermission bp) { 3152 int index = pkg.requestedPermissions.indexOf(bp.name); 3153 if (index == -1) { 3154 throw new SecurityException("Package " + pkg.packageName 3155 + " has not requested permission " + bp.name); 3156 } 3157 if (!bp.isRuntime()) { 3158 throw new SecurityException("Permission " + bp.name 3159 + " is not a changeable permission type"); 3160 } 3161 } 3162 3163 @Override 3164 public void grantRuntimePermission(String packageName, String name, final int userId) { 3165 if (!sUserManager.exists(userId)) { 3166 Log.e(TAG, "No such user:" + userId); 3167 return; 3168 } 3169 3170 mContext.enforceCallingOrSelfPermission( 3171 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3172 "grantRuntimePermission"); 3173 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3175 "grantRuntimePermission"); 3176 3177 final SettingBase sb; 3178 3179 synchronized (mPackages) { 3180 final PackageParser.Package pkg = mPackages.get(packageName); 3181 if (pkg == null) { 3182 throw new IllegalArgumentException("Unknown package: " + packageName); 3183 } 3184 3185 final BasePermission bp = mSettings.mPermissions.get(name); 3186 if (bp == null) { 3187 throw new IllegalArgumentException("Unknown permission: " + name); 3188 } 3189 3190 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3191 3192 sb = (SettingBase) pkg.mExtras; 3193 if (sb == null) { 3194 throw new IllegalArgumentException("Unknown package: " + packageName); 3195 } 3196 3197 final PermissionsState permissionsState = sb.getPermissionsState(); 3198 3199 final int flags = permissionsState.getPermissionFlags(name, userId); 3200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3201 throw new SecurityException("Cannot grant system fixed permission: " 3202 + name + " for package: " + packageName); 3203 } 3204 3205 final int result = permissionsState.grantRuntimePermission(bp, userId); 3206 switch (result) { 3207 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3208 return; 3209 } 3210 3211 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3212 mHandler.post(new Runnable() { 3213 @Override 3214 public void run() { 3215 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3216 } 3217 }); 3218 } break; 3219 } 3220 3221 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3222 3223 // Not critical if that is lost - app has to request again. 3224 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3225 } 3226 } 3227 3228 @Override 3229 public void revokeRuntimePermission(String packageName, String name, int userId) { 3230 if (!sUserManager.exists(userId)) { 3231 Log.e(TAG, "No such user:" + userId); 3232 return; 3233 } 3234 3235 mContext.enforceCallingOrSelfPermission( 3236 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3237 "revokeRuntimePermission"); 3238 3239 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3240 "revokeRuntimePermission"); 3241 3242 final SettingBase sb; 3243 3244 synchronized (mPackages) { 3245 final PackageParser.Package pkg = mPackages.get(packageName); 3246 if (pkg == null) { 3247 throw new IllegalArgumentException("Unknown package: " + packageName); 3248 } 3249 3250 final BasePermission bp = mSettings.mPermissions.get(name); 3251 if (bp == null) { 3252 throw new IllegalArgumentException("Unknown permission: " + name); 3253 } 3254 3255 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3256 3257 sb = (SettingBase) pkg.mExtras; 3258 if (sb == null) { 3259 throw new IllegalArgumentException("Unknown package: " + packageName); 3260 } 3261 3262 final PermissionsState permissionsState = sb.getPermissionsState(); 3263 3264 final int flags = permissionsState.getPermissionFlags(name, userId); 3265 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3266 throw new SecurityException("Cannot revoke system fixed permission: " 3267 + name + " for package: " + packageName); 3268 } 3269 3270 if (permissionsState.revokeRuntimePermission(bp, userId) == 3271 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3272 return; 3273 } 3274 3275 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3276 3277 // Critical, after this call app should never have the permission. 3278 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3279 } 3280 3281 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3282 } 3283 3284 @Override 3285 public int getPermissionFlags(String name, String packageName, int userId) { 3286 if (!sUserManager.exists(userId)) { 3287 return 0; 3288 } 3289 3290 mContext.enforceCallingOrSelfPermission( 3291 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3292 "getPermissionFlags"); 3293 3294 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3295 "getPermissionFlags"); 3296 3297 synchronized (mPackages) { 3298 final PackageParser.Package pkg = mPackages.get(packageName); 3299 if (pkg == null) { 3300 throw new IllegalArgumentException("Unknown package: " + packageName); 3301 } 3302 3303 final BasePermission bp = mSettings.mPermissions.get(name); 3304 if (bp == null) { 3305 throw new IllegalArgumentException("Unknown permission: " + name); 3306 } 3307 3308 SettingBase sb = (SettingBase) pkg.mExtras; 3309 if (sb == null) { 3310 throw new IllegalArgumentException("Unknown package: " + packageName); 3311 } 3312 3313 PermissionsState permissionsState = sb.getPermissionsState(); 3314 return permissionsState.getPermissionFlags(name, userId); 3315 } 3316 } 3317 3318 @Override 3319 public void updatePermissionFlags(String name, String packageName, int flagMask, 3320 int flagValues, int userId) { 3321 if (!sUserManager.exists(userId)) { 3322 return; 3323 } 3324 3325 mContext.enforceCallingOrSelfPermission( 3326 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3327 "updatePermissionFlags"); 3328 3329 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3330 "updatePermissionFlags"); 3331 3332 // Only the system can change policy and system fixed flags. 3333 if (getCallingUid() != Process.SYSTEM_UID) { 3334 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3335 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3336 3337 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3338 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3339 } 3340 3341 synchronized (mPackages) { 3342 final PackageParser.Package pkg = mPackages.get(packageName); 3343 if (pkg == null) { 3344 throw new IllegalArgumentException("Unknown package: " + packageName); 3345 } 3346 3347 final BasePermission bp = mSettings.mPermissions.get(name); 3348 if (bp == null) { 3349 throw new IllegalArgumentException("Unknown permission: " + name); 3350 } 3351 3352 SettingBase sb = (SettingBase) pkg.mExtras; 3353 if (sb == null) { 3354 throw new IllegalArgumentException("Unknown package: " + packageName); 3355 } 3356 3357 PermissionsState permissionsState = sb.getPermissionsState(); 3358 3359 // Only the package manager can change flags for system component permissions. 3360 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3361 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3362 return; 3363 } 3364 3365 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3366 // Install and runtime permissions are stored in different places, 3367 // so figure out what permission changed and persist the change. 3368 if (permissionsState.getInstallPermissionState(name) != null) { 3369 scheduleWriteSettingsLocked(); 3370 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3371 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3372 } 3373 } 3374 } 3375 } 3376 3377 @Override 3378 public boolean shouldShowRequestPermissionRationale(String permissionName, 3379 String packageName, int userId) { 3380 if (UserHandle.getCallingUserId() != userId) { 3381 mContext.enforceCallingPermission( 3382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3383 "canShowRequestPermissionRationale for user " + userId); 3384 } 3385 3386 final int uid = getPackageUid(packageName, userId); 3387 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3388 return false; 3389 } 3390 3391 if (checkPermission(permissionName, packageName, userId) 3392 == PackageManager.PERMISSION_GRANTED) { 3393 return false; 3394 } 3395 3396 final int flags; 3397 3398 final long identity = Binder.clearCallingIdentity(); 3399 try { 3400 flags = getPermissionFlags(permissionName, 3401 packageName, userId); 3402 } finally { 3403 Binder.restoreCallingIdentity(identity); 3404 } 3405 3406 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3407 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3408 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3409 3410 if ((flags & fixedFlags) != 0) { 3411 return false; 3412 } 3413 3414 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3415 } 3416 3417 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3418 BasePermission bp = mSettings.mPermissions.get(permission); 3419 if (bp == null) { 3420 throw new SecurityException("Missing " + permission + " permission"); 3421 } 3422 3423 SettingBase sb = (SettingBase) pkg.mExtras; 3424 PermissionsState permissionsState = sb.getPermissionsState(); 3425 3426 if (permissionsState.grantInstallPermission(bp) != 3427 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3428 scheduleWriteSettingsLocked(); 3429 } 3430 } 3431 3432 @Override 3433 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3434 mContext.enforceCallingOrSelfPermission( 3435 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3436 "addOnPermissionsChangeListener"); 3437 3438 synchronized (mPackages) { 3439 mOnPermissionChangeListeners.addListenerLocked(listener); 3440 } 3441 } 3442 3443 @Override 3444 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3445 synchronized (mPackages) { 3446 mOnPermissionChangeListeners.removeListenerLocked(listener); 3447 } 3448 } 3449 3450 @Override 3451 public boolean isProtectedBroadcast(String actionName) { 3452 synchronized (mPackages) { 3453 return mProtectedBroadcasts.contains(actionName); 3454 } 3455 } 3456 3457 @Override 3458 public int checkSignatures(String pkg1, String pkg2) { 3459 synchronized (mPackages) { 3460 final PackageParser.Package p1 = mPackages.get(pkg1); 3461 final PackageParser.Package p2 = mPackages.get(pkg2); 3462 if (p1 == null || p1.mExtras == null 3463 || p2 == null || p2.mExtras == null) { 3464 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3465 } 3466 return compareSignatures(p1.mSignatures, p2.mSignatures); 3467 } 3468 } 3469 3470 @Override 3471 public int checkUidSignatures(int uid1, int uid2) { 3472 // Map to base uids. 3473 uid1 = UserHandle.getAppId(uid1); 3474 uid2 = UserHandle.getAppId(uid2); 3475 // reader 3476 synchronized (mPackages) { 3477 Signature[] s1; 3478 Signature[] s2; 3479 Object obj = mSettings.getUserIdLPr(uid1); 3480 if (obj != null) { 3481 if (obj instanceof SharedUserSetting) { 3482 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3483 } else if (obj instanceof PackageSetting) { 3484 s1 = ((PackageSetting)obj).signatures.mSignatures; 3485 } else { 3486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3487 } 3488 } else { 3489 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3490 } 3491 obj = mSettings.getUserIdLPr(uid2); 3492 if (obj != null) { 3493 if (obj instanceof SharedUserSetting) { 3494 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3495 } else if (obj instanceof PackageSetting) { 3496 s2 = ((PackageSetting)obj).signatures.mSignatures; 3497 } else { 3498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3499 } 3500 } else { 3501 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3502 } 3503 return compareSignatures(s1, s2); 3504 } 3505 } 3506 3507 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3508 final long identity = Binder.clearCallingIdentity(); 3509 try { 3510 if (sb instanceof SharedUserSetting) { 3511 SharedUserSetting sus = (SharedUserSetting) sb; 3512 final int packageCount = sus.packages.size(); 3513 for (int i = 0; i < packageCount; i++) { 3514 PackageSetting susPs = sus.packages.valueAt(i); 3515 if (userId == UserHandle.USER_ALL) { 3516 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3517 } else { 3518 final int uid = UserHandle.getUid(userId, susPs.appId); 3519 killUid(uid, reason); 3520 } 3521 } 3522 } else if (sb instanceof PackageSetting) { 3523 PackageSetting ps = (PackageSetting) sb; 3524 if (userId == UserHandle.USER_ALL) { 3525 killApplication(ps.pkg.packageName, ps.appId, reason); 3526 } else { 3527 final int uid = UserHandle.getUid(userId, ps.appId); 3528 killUid(uid, reason); 3529 } 3530 } 3531 } finally { 3532 Binder.restoreCallingIdentity(identity); 3533 } 3534 } 3535 3536 private static void killUid(int uid, String reason) { 3537 IActivityManager am = ActivityManagerNative.getDefault(); 3538 if (am != null) { 3539 try { 3540 am.killUid(uid, reason); 3541 } catch (RemoteException e) { 3542 /* ignore - same process */ 3543 } 3544 } 3545 } 3546 3547 /** 3548 * Compares two sets of signatures. Returns: 3549 * <br /> 3550 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3551 * <br /> 3552 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3553 * <br /> 3554 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3555 * <br /> 3556 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3557 * <br /> 3558 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3559 */ 3560 static int compareSignatures(Signature[] s1, Signature[] s2) { 3561 if (s1 == null) { 3562 return s2 == null 3563 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3564 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3565 } 3566 3567 if (s2 == null) { 3568 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3569 } 3570 3571 if (s1.length != s2.length) { 3572 return PackageManager.SIGNATURE_NO_MATCH; 3573 } 3574 3575 // Since both signature sets are of size 1, we can compare without HashSets. 3576 if (s1.length == 1) { 3577 return s1[0].equals(s2[0]) ? 3578 PackageManager.SIGNATURE_MATCH : 3579 PackageManager.SIGNATURE_NO_MATCH; 3580 } 3581 3582 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3583 for (Signature sig : s1) { 3584 set1.add(sig); 3585 } 3586 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3587 for (Signature sig : s2) { 3588 set2.add(sig); 3589 } 3590 // Make sure s2 contains all signatures in s1. 3591 if (set1.equals(set2)) { 3592 return PackageManager.SIGNATURE_MATCH; 3593 } 3594 return PackageManager.SIGNATURE_NO_MATCH; 3595 } 3596 3597 /** 3598 * If the database version for this type of package (internal storage or 3599 * external storage) is less than the version where package signatures 3600 * were updated, return true. 3601 */ 3602 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3603 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3604 DatabaseVersion.SIGNATURE_END_ENTITY)) 3605 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3606 DatabaseVersion.SIGNATURE_END_ENTITY)); 3607 } 3608 3609 /** 3610 * Used for backward compatibility to make sure any packages with 3611 * certificate chains get upgraded to the new style. {@code existingSigs} 3612 * will be in the old format (since they were stored on disk from before the 3613 * system upgrade) and {@code scannedSigs} will be in the newer format. 3614 */ 3615 private int compareSignaturesCompat(PackageSignatures existingSigs, 3616 PackageParser.Package scannedPkg) { 3617 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3618 return PackageManager.SIGNATURE_NO_MATCH; 3619 } 3620 3621 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3622 for (Signature sig : existingSigs.mSignatures) { 3623 existingSet.add(sig); 3624 } 3625 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3626 for (Signature sig : scannedPkg.mSignatures) { 3627 try { 3628 Signature[] chainSignatures = sig.getChainSignatures(); 3629 for (Signature chainSig : chainSignatures) { 3630 scannedCompatSet.add(chainSig); 3631 } 3632 } catch (CertificateEncodingException e) { 3633 scannedCompatSet.add(sig); 3634 } 3635 } 3636 /* 3637 * Make sure the expanded scanned set contains all signatures in the 3638 * existing one. 3639 */ 3640 if (scannedCompatSet.equals(existingSet)) { 3641 // Migrate the old signatures to the new scheme. 3642 existingSigs.assignSignatures(scannedPkg.mSignatures); 3643 // The new KeySets will be re-added later in the scanning process. 3644 synchronized (mPackages) { 3645 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3646 } 3647 return PackageManager.SIGNATURE_MATCH; 3648 } 3649 return PackageManager.SIGNATURE_NO_MATCH; 3650 } 3651 3652 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3653 if (isExternal(scannedPkg)) { 3654 return mSettings.isExternalDatabaseVersionOlderThan( 3655 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3656 } else { 3657 return mSettings.isInternalDatabaseVersionOlderThan( 3658 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3659 } 3660 } 3661 3662 private int compareSignaturesRecover(PackageSignatures existingSigs, 3663 PackageParser.Package scannedPkg) { 3664 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3665 return PackageManager.SIGNATURE_NO_MATCH; 3666 } 3667 3668 String msg = null; 3669 try { 3670 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3671 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3672 + scannedPkg.packageName); 3673 return PackageManager.SIGNATURE_MATCH; 3674 } 3675 } catch (CertificateException e) { 3676 msg = e.getMessage(); 3677 } 3678 3679 logCriticalInfo(Log.INFO, 3680 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3681 return PackageManager.SIGNATURE_NO_MATCH; 3682 } 3683 3684 @Override 3685 public String[] getPackagesForUid(int uid) { 3686 uid = UserHandle.getAppId(uid); 3687 // reader 3688 synchronized (mPackages) { 3689 Object obj = mSettings.getUserIdLPr(uid); 3690 if (obj instanceof SharedUserSetting) { 3691 final SharedUserSetting sus = (SharedUserSetting) obj; 3692 final int N = sus.packages.size(); 3693 final String[] res = new String[N]; 3694 final Iterator<PackageSetting> it = sus.packages.iterator(); 3695 int i = 0; 3696 while (it.hasNext()) { 3697 res[i++] = it.next().name; 3698 } 3699 return res; 3700 } else if (obj instanceof PackageSetting) { 3701 final PackageSetting ps = (PackageSetting) obj; 3702 return new String[] { ps.name }; 3703 } 3704 } 3705 return null; 3706 } 3707 3708 @Override 3709 public String getNameForUid(int uid) { 3710 // reader 3711 synchronized (mPackages) { 3712 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3713 if (obj instanceof SharedUserSetting) { 3714 final SharedUserSetting sus = (SharedUserSetting) obj; 3715 return sus.name + ":" + sus.userId; 3716 } else if (obj instanceof PackageSetting) { 3717 final PackageSetting ps = (PackageSetting) obj; 3718 return ps.name; 3719 } 3720 } 3721 return null; 3722 } 3723 3724 @Override 3725 public int getUidForSharedUser(String sharedUserName) { 3726 if(sharedUserName == null) { 3727 return -1; 3728 } 3729 // reader 3730 synchronized (mPackages) { 3731 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3732 if (suid == null) { 3733 return -1; 3734 } 3735 return suid.userId; 3736 } 3737 } 3738 3739 @Override 3740 public int getFlagsForUid(int uid) { 3741 synchronized (mPackages) { 3742 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3743 if (obj instanceof SharedUserSetting) { 3744 final SharedUserSetting sus = (SharedUserSetting) obj; 3745 return sus.pkgFlags; 3746 } else if (obj instanceof PackageSetting) { 3747 final PackageSetting ps = (PackageSetting) obj; 3748 return ps.pkgFlags; 3749 } 3750 } 3751 return 0; 3752 } 3753 3754 @Override 3755 public int getPrivateFlagsForUid(int uid) { 3756 synchronized (mPackages) { 3757 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3758 if (obj instanceof SharedUserSetting) { 3759 final SharedUserSetting sus = (SharedUserSetting) obj; 3760 return sus.pkgPrivateFlags; 3761 } else if (obj instanceof PackageSetting) { 3762 final PackageSetting ps = (PackageSetting) obj; 3763 return ps.pkgPrivateFlags; 3764 } 3765 } 3766 return 0; 3767 } 3768 3769 @Override 3770 public boolean isUidPrivileged(int uid) { 3771 uid = UserHandle.getAppId(uid); 3772 // reader 3773 synchronized (mPackages) { 3774 Object obj = mSettings.getUserIdLPr(uid); 3775 if (obj instanceof SharedUserSetting) { 3776 final SharedUserSetting sus = (SharedUserSetting) obj; 3777 final Iterator<PackageSetting> it = sus.packages.iterator(); 3778 while (it.hasNext()) { 3779 if (it.next().isPrivileged()) { 3780 return true; 3781 } 3782 } 3783 } else if (obj instanceof PackageSetting) { 3784 final PackageSetting ps = (PackageSetting) obj; 3785 return ps.isPrivileged(); 3786 } 3787 } 3788 return false; 3789 } 3790 3791 @Override 3792 public String[] getAppOpPermissionPackages(String permissionName) { 3793 synchronized (mPackages) { 3794 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3795 if (pkgs == null) { 3796 return null; 3797 } 3798 return pkgs.toArray(new String[pkgs.size()]); 3799 } 3800 } 3801 3802 @Override 3803 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3804 int flags, int userId) { 3805 if (!sUserManager.exists(userId)) return null; 3806 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3807 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3808 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3809 } 3810 3811 @Override 3812 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3813 IntentFilter filter, int match, ComponentName activity) { 3814 final int userId = UserHandle.getCallingUserId(); 3815 if (DEBUG_PREFERRED) { 3816 Log.v(TAG, "setLastChosenActivity intent=" + intent 3817 + " resolvedType=" + resolvedType 3818 + " flags=" + flags 3819 + " filter=" + filter 3820 + " match=" + match 3821 + " activity=" + activity); 3822 filter.dump(new PrintStreamPrinter(System.out), " "); 3823 } 3824 intent.setComponent(null); 3825 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3826 // Find any earlier preferred or last chosen entries and nuke them 3827 findPreferredActivity(intent, resolvedType, 3828 flags, query, 0, false, true, false, userId); 3829 // Add the new activity as the last chosen for this filter 3830 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3831 "Setting last chosen"); 3832 } 3833 3834 @Override 3835 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3836 final int userId = UserHandle.getCallingUserId(); 3837 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3838 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3839 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3840 false, false, false, userId); 3841 } 3842 3843 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3844 int flags, List<ResolveInfo> query, int userId) { 3845 if (query != null) { 3846 final int N = query.size(); 3847 if (N == 1) { 3848 return query.get(0); 3849 } else if (N > 1) { 3850 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3851 // If there is more than one activity with the same priority, 3852 // then let the user decide between them. 3853 ResolveInfo r0 = query.get(0); 3854 ResolveInfo r1 = query.get(1); 3855 if (DEBUG_INTENT_MATCHING || debug) { 3856 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3857 + r1.activityInfo.name + "=" + r1.priority); 3858 } 3859 // If the first activity has a higher priority, or a different 3860 // default, then it is always desireable to pick it. 3861 if (r0.priority != r1.priority 3862 || r0.preferredOrder != r1.preferredOrder 3863 || r0.isDefault != r1.isDefault) { 3864 return query.get(0); 3865 } 3866 // If we have saved a preference for a preferred activity for 3867 // this Intent, use that. 3868 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3869 flags, query, r0.priority, true, false, debug, userId); 3870 if (ri != null) { 3871 return ri; 3872 } 3873 if (userId != 0) { 3874 ri = new ResolveInfo(mResolveInfo); 3875 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3876 ri.activityInfo.applicationInfo = new ApplicationInfo( 3877 ri.activityInfo.applicationInfo); 3878 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3879 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3880 return ri; 3881 } 3882 return mResolveInfo; 3883 } 3884 } 3885 return null; 3886 } 3887 3888 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3889 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3890 final int N = query.size(); 3891 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3892 .get(userId); 3893 // Get the list of persistent preferred activities that handle the intent 3894 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3895 List<PersistentPreferredActivity> pprefs = ppir != null 3896 ? ppir.queryIntent(intent, resolvedType, 3897 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3898 : null; 3899 if (pprefs != null && pprefs.size() > 0) { 3900 final int M = pprefs.size(); 3901 for (int i=0; i<M; i++) { 3902 final PersistentPreferredActivity ppa = pprefs.get(i); 3903 if (DEBUG_PREFERRED || debug) { 3904 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3905 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3906 + "\n component=" + ppa.mComponent); 3907 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3908 } 3909 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3910 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3911 if (DEBUG_PREFERRED || debug) { 3912 Slog.v(TAG, "Found persistent preferred activity:"); 3913 if (ai != null) { 3914 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3915 } else { 3916 Slog.v(TAG, " null"); 3917 } 3918 } 3919 if (ai == null) { 3920 // This previously registered persistent preferred activity 3921 // component is no longer known. Ignore it and do NOT remove it. 3922 continue; 3923 } 3924 for (int j=0; j<N; j++) { 3925 final ResolveInfo ri = query.get(j); 3926 if (!ri.activityInfo.applicationInfo.packageName 3927 .equals(ai.applicationInfo.packageName)) { 3928 continue; 3929 } 3930 if (!ri.activityInfo.name.equals(ai.name)) { 3931 continue; 3932 } 3933 // Found a persistent preference that can handle the intent. 3934 if (DEBUG_PREFERRED || debug) { 3935 Slog.v(TAG, "Returning persistent preferred activity: " + 3936 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3937 } 3938 return ri; 3939 } 3940 } 3941 } 3942 return null; 3943 } 3944 3945 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3946 List<ResolveInfo> query, int priority, boolean always, 3947 boolean removeMatches, boolean debug, int userId) { 3948 if (!sUserManager.exists(userId)) return null; 3949 // writer 3950 synchronized (mPackages) { 3951 if (intent.getSelector() != null) { 3952 intent = intent.getSelector(); 3953 } 3954 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3955 3956 // Try to find a matching persistent preferred activity. 3957 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3958 debug, userId); 3959 3960 // If a persistent preferred activity matched, use it. 3961 if (pri != null) { 3962 return pri; 3963 } 3964 3965 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3966 // Get the list of preferred activities that handle the intent 3967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3968 List<PreferredActivity> prefs = pir != null 3969 ? pir.queryIntent(intent, resolvedType, 3970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3971 : null; 3972 if (prefs != null && prefs.size() > 0) { 3973 boolean changed = false; 3974 try { 3975 // First figure out how good the original match set is. 3976 // We will only allow preferred activities that came 3977 // from the same match quality. 3978 int match = 0; 3979 3980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3981 3982 final int N = query.size(); 3983 for (int j=0; j<N; j++) { 3984 final ResolveInfo ri = query.get(j); 3985 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3986 + ": 0x" + Integer.toHexString(match)); 3987 if (ri.match > match) { 3988 match = ri.match; 3989 } 3990 } 3991 3992 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3993 + Integer.toHexString(match)); 3994 3995 match &= IntentFilter.MATCH_CATEGORY_MASK; 3996 final int M = prefs.size(); 3997 for (int i=0; i<M; i++) { 3998 final PreferredActivity pa = prefs.get(i); 3999 if (DEBUG_PREFERRED || debug) { 4000 Slog.v(TAG, "Checking PreferredActivity ds=" 4001 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4002 + "\n component=" + pa.mPref.mComponent); 4003 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4004 } 4005 if (pa.mPref.mMatch != match) { 4006 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4007 + Integer.toHexString(pa.mPref.mMatch)); 4008 continue; 4009 } 4010 // If it's not an "always" type preferred activity and that's what we're 4011 // looking for, skip it. 4012 if (always && !pa.mPref.mAlways) { 4013 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4014 continue; 4015 } 4016 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4017 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4018 if (DEBUG_PREFERRED || debug) { 4019 Slog.v(TAG, "Found preferred activity:"); 4020 if (ai != null) { 4021 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4022 } else { 4023 Slog.v(TAG, " null"); 4024 } 4025 } 4026 if (ai == null) { 4027 // This previously registered preferred activity 4028 // component is no longer known. Most likely an update 4029 // to the app was installed and in the new version this 4030 // component no longer exists. Clean it up by removing 4031 // it from the preferred activities list, and skip it. 4032 Slog.w(TAG, "Removing dangling preferred activity: " 4033 + pa.mPref.mComponent); 4034 pir.removeFilter(pa); 4035 changed = true; 4036 continue; 4037 } 4038 for (int j=0; j<N; j++) { 4039 final ResolveInfo ri = query.get(j); 4040 if (!ri.activityInfo.applicationInfo.packageName 4041 .equals(ai.applicationInfo.packageName)) { 4042 continue; 4043 } 4044 if (!ri.activityInfo.name.equals(ai.name)) { 4045 continue; 4046 } 4047 4048 if (removeMatches) { 4049 pir.removeFilter(pa); 4050 changed = true; 4051 if (DEBUG_PREFERRED) { 4052 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4053 } 4054 break; 4055 } 4056 4057 // Okay we found a previously set preferred or last chosen app. 4058 // If the result set is different from when this 4059 // was created, we need to clear it and re-ask the 4060 // user their preference, if we're looking for an "always" type entry. 4061 if (always && !pa.mPref.sameSet(query)) { 4062 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4063 + intent + " type " + resolvedType); 4064 if (DEBUG_PREFERRED) { 4065 Slog.v(TAG, "Removing preferred activity since set changed " 4066 + pa.mPref.mComponent); 4067 } 4068 pir.removeFilter(pa); 4069 // Re-add the filter as a "last chosen" entry (!always) 4070 PreferredActivity lastChosen = new PreferredActivity( 4071 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4072 pir.addFilter(lastChosen); 4073 changed = true; 4074 return null; 4075 } 4076 4077 // Yay! Either the set matched or we're looking for the last chosen 4078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4079 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4080 return ri; 4081 } 4082 } 4083 } finally { 4084 if (changed) { 4085 if (DEBUG_PREFERRED) { 4086 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4087 } 4088 scheduleWritePackageRestrictionsLocked(userId); 4089 } 4090 } 4091 } 4092 } 4093 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4094 return null; 4095 } 4096 4097 /* 4098 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4099 */ 4100 @Override 4101 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4102 int targetUserId) { 4103 mContext.enforceCallingOrSelfPermission( 4104 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4105 List<CrossProfileIntentFilter> matches = 4106 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4107 if (matches != null) { 4108 int size = matches.size(); 4109 for (int i = 0; i < size; i++) { 4110 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4111 } 4112 } 4113 return false; 4114 } 4115 4116 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4117 String resolvedType, int userId) { 4118 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4119 if (resolver != null) { 4120 return resolver.queryIntent(intent, resolvedType, false, userId); 4121 } 4122 return null; 4123 } 4124 4125 @Override 4126 public List<ResolveInfo> queryIntentActivities(Intent intent, 4127 String resolvedType, int flags, int userId) { 4128 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4129 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4130 ComponentName comp = intent.getComponent(); 4131 if (comp == null) { 4132 if (intent.getSelector() != null) { 4133 intent = intent.getSelector(); 4134 comp = intent.getComponent(); 4135 } 4136 } 4137 4138 if (comp != null) { 4139 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4140 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4141 if (ai != null) { 4142 final ResolveInfo ri = new ResolveInfo(); 4143 ri.activityInfo = ai; 4144 list.add(ri); 4145 } 4146 return list; 4147 } 4148 4149 // reader 4150 synchronized (mPackages) { 4151 final String pkgName = intent.getPackage(); 4152 if (pkgName == null) { 4153 List<CrossProfileIntentFilter> matchingFilters = 4154 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4155 // Check for results that need to skip the current profile. 4156 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4157 resolvedType, flags, userId); 4158 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4159 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4160 result.add(resolveInfo); 4161 return filterIfNotPrimaryUser(result, userId); 4162 } 4163 4164 // Check for results in the current profile. 4165 List<ResolveInfo> result = mActivities.queryIntent( 4166 intent, resolvedType, flags, userId); 4167 4168 // Check for cross profile results. 4169 resolveInfo = queryCrossProfileIntents( 4170 matchingFilters, intent, resolvedType, flags, userId); 4171 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4172 result.add(resolveInfo); 4173 Collections.sort(result, mResolvePrioritySorter); 4174 } 4175 result = filterIfNotPrimaryUser(result, userId); 4176 if (result.size() > 1 && hasWebURI(intent)) { 4177 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4178 } 4179 return result; 4180 } 4181 final PackageParser.Package pkg = mPackages.get(pkgName); 4182 if (pkg != null) { 4183 return filterIfNotPrimaryUser( 4184 mActivities.queryIntentForPackage( 4185 intent, resolvedType, flags, pkg.activities, userId), 4186 userId); 4187 } 4188 return new ArrayList<ResolveInfo>(); 4189 } 4190 } 4191 4192 private boolean isUserEnabled(int userId) { 4193 long callingId = Binder.clearCallingIdentity(); 4194 try { 4195 UserInfo userInfo = sUserManager.getUserInfo(userId); 4196 return userInfo != null && userInfo.isEnabled(); 4197 } finally { 4198 Binder.restoreCallingIdentity(callingId); 4199 } 4200 } 4201 4202 /** 4203 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4204 * 4205 * @return filtered list 4206 */ 4207 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4208 if (userId == UserHandle.USER_OWNER) { 4209 return resolveInfos; 4210 } 4211 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4212 ResolveInfo info = resolveInfos.get(i); 4213 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4214 resolveInfos.remove(i); 4215 } 4216 } 4217 return resolveInfos; 4218 } 4219 4220 private static boolean hasWebURI(Intent intent) { 4221 if (intent.getData() == null) { 4222 return false; 4223 } 4224 final String scheme = intent.getScheme(); 4225 if (TextUtils.isEmpty(scheme)) { 4226 return false; 4227 } 4228 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4229 } 4230 4231 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4232 int flags, List<ResolveInfo> candidates) { 4233 if (DEBUG_PREFERRED) { 4234 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4235 candidates.size()); 4236 } 4237 4238 final int userId = UserHandle.getCallingUserId(); 4239 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4240 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4241 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4242 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4243 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4244 4245 synchronized (mPackages) { 4246 final int count = candidates.size(); 4247 // First, try to use the domain prefered App. Partition the candidates into four lists: 4248 // one for the final results, one for the "do not use ever", one for "undefined status" 4249 // and finally one for "Browser App type". 4250 for (int n=0; n<count; n++) { 4251 ResolveInfo info = candidates.get(n); 4252 String packageName = info.activityInfo.packageName; 4253 PackageSetting ps = mSettings.mPackages.get(packageName); 4254 if (ps != null) { 4255 // Add to the special match all list (Browser use case) 4256 if (info.handleAllWebDataURI) { 4257 matchAllList.add(info); 4258 continue; 4259 } 4260 // Try to get the status from User settings first 4261 int status = getDomainVerificationStatusLPr(ps, userId); 4262 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4263 alwaysList.add(info); 4264 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4265 neverList.add(info); 4266 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4267 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4268 undefinedList.add(info); 4269 } 4270 } 4271 } 4272 // First try to add the "always" if there is any 4273 if (alwaysList.size() > 0) { 4274 result.addAll(alwaysList); 4275 } else { 4276 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4277 result.addAll(undefinedList); 4278 // Also add Browsers (all of them or only the default one) 4279 if ((flags & MATCH_ALL) != 0) { 4280 result.addAll(matchAllList); 4281 } else { 4282 // Try to add the Default Browser if we can 4283 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4284 UserHandle.myUserId()); 4285 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4286 boolean defaultBrowserFound = false; 4287 final int browserCount = matchAllList.size(); 4288 for (int n=0; n<browserCount; n++) { 4289 ResolveInfo browser = matchAllList.get(n); 4290 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4291 result.add(browser); 4292 defaultBrowserFound = true; 4293 break; 4294 } 4295 } 4296 if (!defaultBrowserFound) { 4297 result.addAll(matchAllList); 4298 } 4299 } else { 4300 result.addAll(matchAllList); 4301 } 4302 } 4303 4304 // If there is nothing selected, add all candidates and remove the ones that the User 4305 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4306 if (result.size() == 0) { 4307 result.addAll(candidates); 4308 result.removeAll(neverList); 4309 } 4310 } 4311 } 4312 if (DEBUG_PREFERRED) { 4313 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4314 result.size()); 4315 } 4316 return result; 4317 } 4318 4319 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4320 int status = ps.getDomainVerificationStatusForUser(userId); 4321 // if none available, get the master status 4322 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4323 if (ps.getIntentFilterVerificationInfo() != null) { 4324 status = ps.getIntentFilterVerificationInfo().getStatus(); 4325 } 4326 } 4327 return status; 4328 } 4329 4330 private ResolveInfo querySkipCurrentProfileIntents( 4331 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4332 int flags, int sourceUserId) { 4333 if (matchingFilters != null) { 4334 int size = matchingFilters.size(); 4335 for (int i = 0; i < size; i ++) { 4336 CrossProfileIntentFilter filter = matchingFilters.get(i); 4337 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4338 // Checking if there are activities in the target user that can handle the 4339 // intent. 4340 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4341 flags, sourceUserId); 4342 if (resolveInfo != null) { 4343 return resolveInfo; 4344 } 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 // Return matching ResolveInfo if any for skip current profile intent filters. 4352 private ResolveInfo queryCrossProfileIntents( 4353 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4354 int flags, int sourceUserId) { 4355 if (matchingFilters != null) { 4356 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4357 // match the same intent. For performance reasons, it is better not to 4358 // run queryIntent twice for the same userId 4359 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4360 int size = matchingFilters.size(); 4361 for (int i = 0; i < size; i++) { 4362 CrossProfileIntentFilter filter = matchingFilters.get(i); 4363 int targetUserId = filter.getTargetUserId(); 4364 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4365 && !alreadyTriedUserIds.get(targetUserId)) { 4366 // Checking if there are activities in the target user that can handle the 4367 // intent. 4368 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4369 flags, sourceUserId); 4370 if (resolveInfo != null) return resolveInfo; 4371 alreadyTriedUserIds.put(targetUserId, true); 4372 } 4373 } 4374 } 4375 return null; 4376 } 4377 4378 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4379 String resolvedType, int flags, int sourceUserId) { 4380 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4381 resolvedType, flags, filter.getTargetUserId()); 4382 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4383 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4384 } 4385 return null; 4386 } 4387 4388 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4389 int sourceUserId, int targetUserId) { 4390 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4391 String className; 4392 if (targetUserId == UserHandle.USER_OWNER) { 4393 className = FORWARD_INTENT_TO_USER_OWNER; 4394 } else { 4395 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4396 } 4397 ComponentName forwardingActivityComponentName = new ComponentName( 4398 mAndroidApplication.packageName, className); 4399 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4400 sourceUserId); 4401 if (targetUserId == UserHandle.USER_OWNER) { 4402 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4403 forwardingResolveInfo.noResourceId = true; 4404 } 4405 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4406 forwardingResolveInfo.priority = 0; 4407 forwardingResolveInfo.preferredOrder = 0; 4408 forwardingResolveInfo.match = 0; 4409 forwardingResolveInfo.isDefault = true; 4410 forwardingResolveInfo.filter = filter; 4411 forwardingResolveInfo.targetUserId = targetUserId; 4412 return forwardingResolveInfo; 4413 } 4414 4415 @Override 4416 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4417 Intent[] specifics, String[] specificTypes, Intent intent, 4418 String resolvedType, int flags, int userId) { 4419 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4421 false, "query intent activity options"); 4422 final String resultsAction = intent.getAction(); 4423 4424 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4425 | PackageManager.GET_RESOLVED_FILTER, userId); 4426 4427 if (DEBUG_INTENT_MATCHING) { 4428 Log.v(TAG, "Query " + intent + ": " + results); 4429 } 4430 4431 int specificsPos = 0; 4432 int N; 4433 4434 // todo: note that the algorithm used here is O(N^2). This 4435 // isn't a problem in our current environment, but if we start running 4436 // into situations where we have more than 5 or 10 matches then this 4437 // should probably be changed to something smarter... 4438 4439 // First we go through and resolve each of the specific items 4440 // that were supplied, taking care of removing any corresponding 4441 // duplicate items in the generic resolve list. 4442 if (specifics != null) { 4443 for (int i=0; i<specifics.length; i++) { 4444 final Intent sintent = specifics[i]; 4445 if (sintent == null) { 4446 continue; 4447 } 4448 4449 if (DEBUG_INTENT_MATCHING) { 4450 Log.v(TAG, "Specific #" + i + ": " + sintent); 4451 } 4452 4453 String action = sintent.getAction(); 4454 if (resultsAction != null && resultsAction.equals(action)) { 4455 // If this action was explicitly requested, then don't 4456 // remove things that have it. 4457 action = null; 4458 } 4459 4460 ResolveInfo ri = null; 4461 ActivityInfo ai = null; 4462 4463 ComponentName comp = sintent.getComponent(); 4464 if (comp == null) { 4465 ri = resolveIntent( 4466 sintent, 4467 specificTypes != null ? specificTypes[i] : null, 4468 flags, userId); 4469 if (ri == null) { 4470 continue; 4471 } 4472 if (ri == mResolveInfo) { 4473 // ACK! Must do something better with this. 4474 } 4475 ai = ri.activityInfo; 4476 comp = new ComponentName(ai.applicationInfo.packageName, 4477 ai.name); 4478 } else { 4479 ai = getActivityInfo(comp, flags, userId); 4480 if (ai == null) { 4481 continue; 4482 } 4483 } 4484 4485 // Look for any generic query activities that are duplicates 4486 // of this specific one, and remove them from the results. 4487 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4488 N = results.size(); 4489 int j; 4490 for (j=specificsPos; j<N; j++) { 4491 ResolveInfo sri = results.get(j); 4492 if ((sri.activityInfo.name.equals(comp.getClassName()) 4493 && sri.activityInfo.applicationInfo.packageName.equals( 4494 comp.getPackageName())) 4495 || (action != null && sri.filter.matchAction(action))) { 4496 results.remove(j); 4497 if (DEBUG_INTENT_MATCHING) Log.v( 4498 TAG, "Removing duplicate item from " + j 4499 + " due to specific " + specificsPos); 4500 if (ri == null) { 4501 ri = sri; 4502 } 4503 j--; 4504 N--; 4505 } 4506 } 4507 4508 // Add this specific item to its proper place. 4509 if (ri == null) { 4510 ri = new ResolveInfo(); 4511 ri.activityInfo = ai; 4512 } 4513 results.add(specificsPos, ri); 4514 ri.specificIndex = i; 4515 specificsPos++; 4516 } 4517 } 4518 4519 // Now we go through the remaining generic results and remove any 4520 // duplicate actions that are found here. 4521 N = results.size(); 4522 for (int i=specificsPos; i<N-1; i++) { 4523 final ResolveInfo rii = results.get(i); 4524 if (rii.filter == null) { 4525 continue; 4526 } 4527 4528 // Iterate over all of the actions of this result's intent 4529 // filter... typically this should be just one. 4530 final Iterator<String> it = rii.filter.actionsIterator(); 4531 if (it == null) { 4532 continue; 4533 } 4534 while (it.hasNext()) { 4535 final String action = it.next(); 4536 if (resultsAction != null && resultsAction.equals(action)) { 4537 // If this action was explicitly requested, then don't 4538 // remove things that have it. 4539 continue; 4540 } 4541 for (int j=i+1; j<N; j++) { 4542 final ResolveInfo rij = results.get(j); 4543 if (rij.filter != null && rij.filter.hasAction(action)) { 4544 results.remove(j); 4545 if (DEBUG_INTENT_MATCHING) Log.v( 4546 TAG, "Removing duplicate item from " + j 4547 + " due to action " + action + " at " + i); 4548 j--; 4549 N--; 4550 } 4551 } 4552 } 4553 4554 // If the caller didn't request filter information, drop it now 4555 // so we don't have to marshall/unmarshall it. 4556 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4557 rii.filter = null; 4558 } 4559 } 4560 4561 // Filter out the caller activity if so requested. 4562 if (caller != null) { 4563 N = results.size(); 4564 for (int i=0; i<N; i++) { 4565 ActivityInfo ainfo = results.get(i).activityInfo; 4566 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4567 && caller.getClassName().equals(ainfo.name)) { 4568 results.remove(i); 4569 break; 4570 } 4571 } 4572 } 4573 4574 // If the caller didn't request filter information, 4575 // drop them now so we don't have to 4576 // marshall/unmarshall it. 4577 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4578 N = results.size(); 4579 for (int i=0; i<N; i++) { 4580 results.get(i).filter = null; 4581 } 4582 } 4583 4584 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4585 return results; 4586 } 4587 4588 @Override 4589 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4590 int userId) { 4591 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4592 ComponentName comp = intent.getComponent(); 4593 if (comp == null) { 4594 if (intent.getSelector() != null) { 4595 intent = intent.getSelector(); 4596 comp = intent.getComponent(); 4597 } 4598 } 4599 if (comp != null) { 4600 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4601 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4602 if (ai != null) { 4603 ResolveInfo ri = new ResolveInfo(); 4604 ri.activityInfo = ai; 4605 list.add(ri); 4606 } 4607 return list; 4608 } 4609 4610 // reader 4611 synchronized (mPackages) { 4612 String pkgName = intent.getPackage(); 4613 if (pkgName == null) { 4614 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4615 } 4616 final PackageParser.Package pkg = mPackages.get(pkgName); 4617 if (pkg != null) { 4618 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4619 userId); 4620 } 4621 return null; 4622 } 4623 } 4624 4625 @Override 4626 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4627 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4628 if (!sUserManager.exists(userId)) return null; 4629 if (query != null) { 4630 if (query.size() >= 1) { 4631 // If there is more than one service with the same priority, 4632 // just arbitrarily pick the first one. 4633 return query.get(0); 4634 } 4635 } 4636 return null; 4637 } 4638 4639 @Override 4640 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4641 int userId) { 4642 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4643 ComponentName comp = intent.getComponent(); 4644 if (comp == null) { 4645 if (intent.getSelector() != null) { 4646 intent = intent.getSelector(); 4647 comp = intent.getComponent(); 4648 } 4649 } 4650 if (comp != null) { 4651 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4652 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4653 if (si != null) { 4654 final ResolveInfo ri = new ResolveInfo(); 4655 ri.serviceInfo = si; 4656 list.add(ri); 4657 } 4658 return list; 4659 } 4660 4661 // reader 4662 synchronized (mPackages) { 4663 String pkgName = intent.getPackage(); 4664 if (pkgName == null) { 4665 return mServices.queryIntent(intent, resolvedType, flags, userId); 4666 } 4667 final PackageParser.Package pkg = mPackages.get(pkgName); 4668 if (pkg != null) { 4669 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4670 userId); 4671 } 4672 return null; 4673 } 4674 } 4675 4676 @Override 4677 public List<ResolveInfo> queryIntentContentProviders( 4678 Intent intent, String resolvedType, int flags, int userId) { 4679 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4680 ComponentName comp = intent.getComponent(); 4681 if (comp == null) { 4682 if (intent.getSelector() != null) { 4683 intent = intent.getSelector(); 4684 comp = intent.getComponent(); 4685 } 4686 } 4687 if (comp != null) { 4688 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4689 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4690 if (pi != null) { 4691 final ResolveInfo ri = new ResolveInfo(); 4692 ri.providerInfo = pi; 4693 list.add(ri); 4694 } 4695 return list; 4696 } 4697 4698 // reader 4699 synchronized (mPackages) { 4700 String pkgName = intent.getPackage(); 4701 if (pkgName == null) { 4702 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4703 } 4704 final PackageParser.Package pkg = mPackages.get(pkgName); 4705 if (pkg != null) { 4706 return mProviders.queryIntentForPackage( 4707 intent, resolvedType, flags, pkg.providers, userId); 4708 } 4709 return null; 4710 } 4711 } 4712 4713 @Override 4714 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4715 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4716 4717 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4718 4719 // writer 4720 synchronized (mPackages) { 4721 ArrayList<PackageInfo> list; 4722 if (listUninstalled) { 4723 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4724 for (PackageSetting ps : mSettings.mPackages.values()) { 4725 PackageInfo pi; 4726 if (ps.pkg != null) { 4727 pi = generatePackageInfo(ps.pkg, flags, userId); 4728 } else { 4729 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4730 } 4731 if (pi != null) { 4732 list.add(pi); 4733 } 4734 } 4735 } else { 4736 list = new ArrayList<PackageInfo>(mPackages.size()); 4737 for (PackageParser.Package p : mPackages.values()) { 4738 PackageInfo pi = generatePackageInfo(p, flags, userId); 4739 if (pi != null) { 4740 list.add(pi); 4741 } 4742 } 4743 } 4744 4745 return new ParceledListSlice<PackageInfo>(list); 4746 } 4747 } 4748 4749 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4750 String[] permissions, boolean[] tmp, int flags, int userId) { 4751 int numMatch = 0; 4752 final PermissionsState permissionsState = ps.getPermissionsState(); 4753 for (int i=0; i<permissions.length; i++) { 4754 final String permission = permissions[i]; 4755 if (permissionsState.hasPermission(permission, userId)) { 4756 tmp[i] = true; 4757 numMatch++; 4758 } else { 4759 tmp[i] = false; 4760 } 4761 } 4762 if (numMatch == 0) { 4763 return; 4764 } 4765 PackageInfo pi; 4766 if (ps.pkg != null) { 4767 pi = generatePackageInfo(ps.pkg, flags, userId); 4768 } else { 4769 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4770 } 4771 // The above might return null in cases of uninstalled apps or install-state 4772 // skew across users/profiles. 4773 if (pi != null) { 4774 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4775 if (numMatch == permissions.length) { 4776 pi.requestedPermissions = permissions; 4777 } else { 4778 pi.requestedPermissions = new String[numMatch]; 4779 numMatch = 0; 4780 for (int i=0; i<permissions.length; i++) { 4781 if (tmp[i]) { 4782 pi.requestedPermissions[numMatch] = permissions[i]; 4783 numMatch++; 4784 } 4785 } 4786 } 4787 } 4788 list.add(pi); 4789 } 4790 } 4791 4792 @Override 4793 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4794 String[] permissions, int flags, int userId) { 4795 if (!sUserManager.exists(userId)) return null; 4796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4797 4798 // writer 4799 synchronized (mPackages) { 4800 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4801 boolean[] tmpBools = new boolean[permissions.length]; 4802 if (listUninstalled) { 4803 for (PackageSetting ps : mSettings.mPackages.values()) { 4804 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4805 } 4806 } else { 4807 for (PackageParser.Package pkg : mPackages.values()) { 4808 PackageSetting ps = (PackageSetting)pkg.mExtras; 4809 if (ps != null) { 4810 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4811 userId); 4812 } 4813 } 4814 } 4815 4816 return new ParceledListSlice<PackageInfo>(list); 4817 } 4818 } 4819 4820 @Override 4821 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4822 if (!sUserManager.exists(userId)) return null; 4823 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4824 4825 // writer 4826 synchronized (mPackages) { 4827 ArrayList<ApplicationInfo> list; 4828 if (listUninstalled) { 4829 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4830 for (PackageSetting ps : mSettings.mPackages.values()) { 4831 ApplicationInfo ai; 4832 if (ps.pkg != null) { 4833 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4834 ps.readUserState(userId), userId); 4835 } else { 4836 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4837 } 4838 if (ai != null) { 4839 list.add(ai); 4840 } 4841 } 4842 } else { 4843 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4844 for (PackageParser.Package p : mPackages.values()) { 4845 if (p.mExtras != null) { 4846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4847 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4848 if (ai != null) { 4849 list.add(ai); 4850 } 4851 } 4852 } 4853 } 4854 4855 return new ParceledListSlice<ApplicationInfo>(list); 4856 } 4857 } 4858 4859 public List<ApplicationInfo> getPersistentApplications(int flags) { 4860 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4861 4862 // reader 4863 synchronized (mPackages) { 4864 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4865 final int userId = UserHandle.getCallingUserId(); 4866 while (i.hasNext()) { 4867 final PackageParser.Package p = i.next(); 4868 if (p.applicationInfo != null 4869 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4870 && (!mSafeMode || isSystemApp(p))) { 4871 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4872 if (ps != null) { 4873 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4874 ps.readUserState(userId), userId); 4875 if (ai != null) { 4876 finalList.add(ai); 4877 } 4878 } 4879 } 4880 } 4881 } 4882 4883 return finalList; 4884 } 4885 4886 @Override 4887 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4888 if (!sUserManager.exists(userId)) return null; 4889 // reader 4890 synchronized (mPackages) { 4891 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4892 PackageSetting ps = provider != null 4893 ? mSettings.mPackages.get(provider.owner.packageName) 4894 : null; 4895 return ps != null 4896 && mSettings.isEnabledLPr(provider.info, flags, userId) 4897 && (!mSafeMode || (provider.info.applicationInfo.flags 4898 &ApplicationInfo.FLAG_SYSTEM) != 0) 4899 ? PackageParser.generateProviderInfo(provider, flags, 4900 ps.readUserState(userId), userId) 4901 : null; 4902 } 4903 } 4904 4905 /** 4906 * @deprecated 4907 */ 4908 @Deprecated 4909 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4910 // reader 4911 synchronized (mPackages) { 4912 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4913 .entrySet().iterator(); 4914 final int userId = UserHandle.getCallingUserId(); 4915 while (i.hasNext()) { 4916 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4917 PackageParser.Provider p = entry.getValue(); 4918 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4919 4920 if (ps != null && p.syncable 4921 && (!mSafeMode || (p.info.applicationInfo.flags 4922 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4923 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4924 ps.readUserState(userId), userId); 4925 if (info != null) { 4926 outNames.add(entry.getKey()); 4927 outInfo.add(info); 4928 } 4929 } 4930 } 4931 } 4932 } 4933 4934 @Override 4935 public List<ProviderInfo> queryContentProviders(String processName, 4936 int uid, int flags) { 4937 ArrayList<ProviderInfo> finalList = null; 4938 // reader 4939 synchronized (mPackages) { 4940 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4941 final int userId = processName != null ? 4942 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4943 while (i.hasNext()) { 4944 final PackageParser.Provider p = i.next(); 4945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4946 if (ps != null && p.info.authority != null 4947 && (processName == null 4948 || (p.info.processName.equals(processName) 4949 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4950 && mSettings.isEnabledLPr(p.info, flags, userId) 4951 && (!mSafeMode 4952 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4953 if (finalList == null) { 4954 finalList = new ArrayList<ProviderInfo>(3); 4955 } 4956 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4957 ps.readUserState(userId), userId); 4958 if (info != null) { 4959 finalList.add(info); 4960 } 4961 } 4962 } 4963 } 4964 4965 if (finalList != null) { 4966 Collections.sort(finalList, mProviderInitOrderSorter); 4967 } 4968 4969 return finalList; 4970 } 4971 4972 @Override 4973 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4974 int flags) { 4975 // reader 4976 synchronized (mPackages) { 4977 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4978 return PackageParser.generateInstrumentationInfo(i, flags); 4979 } 4980 } 4981 4982 @Override 4983 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4984 int flags) { 4985 ArrayList<InstrumentationInfo> finalList = 4986 new ArrayList<InstrumentationInfo>(); 4987 4988 // reader 4989 synchronized (mPackages) { 4990 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4991 while (i.hasNext()) { 4992 final PackageParser.Instrumentation p = i.next(); 4993 if (targetPackage == null 4994 || targetPackage.equals(p.info.targetPackage)) { 4995 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4996 flags); 4997 if (ii != null) { 4998 finalList.add(ii); 4999 } 5000 } 5001 } 5002 } 5003 5004 return finalList; 5005 } 5006 5007 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5008 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5009 if (overlays == null) { 5010 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5011 return; 5012 } 5013 for (PackageParser.Package opkg : overlays.values()) { 5014 // Not much to do if idmap fails: we already logged the error 5015 // and we certainly don't want to abort installation of pkg simply 5016 // because an overlay didn't fit properly. For these reasons, 5017 // ignore the return value of createIdmapForPackagePairLI. 5018 createIdmapForPackagePairLI(pkg, opkg); 5019 } 5020 } 5021 5022 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5023 PackageParser.Package opkg) { 5024 if (!opkg.mTrustedOverlay) { 5025 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5026 opkg.baseCodePath + ": overlay not trusted"); 5027 return false; 5028 } 5029 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5030 if (overlaySet == null) { 5031 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5032 opkg.baseCodePath + " but target package has no known overlays"); 5033 return false; 5034 } 5035 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5036 // TODO: generate idmap for split APKs 5037 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5038 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5039 + opkg.baseCodePath); 5040 return false; 5041 } 5042 PackageParser.Package[] overlayArray = 5043 overlaySet.values().toArray(new PackageParser.Package[0]); 5044 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5045 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5046 return p1.mOverlayPriority - p2.mOverlayPriority; 5047 } 5048 }; 5049 Arrays.sort(overlayArray, cmp); 5050 5051 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5052 int i = 0; 5053 for (PackageParser.Package p : overlayArray) { 5054 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5055 } 5056 return true; 5057 } 5058 5059 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5060 final File[] files = dir.listFiles(); 5061 if (ArrayUtils.isEmpty(files)) { 5062 Log.d(TAG, "No files in app dir " + dir); 5063 return; 5064 } 5065 5066 if (DEBUG_PACKAGE_SCANNING) { 5067 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5068 + " flags=0x" + Integer.toHexString(parseFlags)); 5069 } 5070 5071 for (File file : files) { 5072 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5073 && !PackageInstallerService.isStageName(file.getName()); 5074 if (!isPackage) { 5075 // Ignore entries which are not packages 5076 continue; 5077 } 5078 try { 5079 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5080 scanFlags, currentTime, null); 5081 } catch (PackageManagerException e) { 5082 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5083 5084 // Delete invalid userdata apps 5085 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5086 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5087 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5088 if (file.isDirectory()) { 5089 mInstaller.rmPackageDir(file.getAbsolutePath()); 5090 } else { 5091 file.delete(); 5092 } 5093 } 5094 } 5095 } 5096 } 5097 5098 private static File getSettingsProblemFile() { 5099 File dataDir = Environment.getDataDirectory(); 5100 File systemDir = new File(dataDir, "system"); 5101 File fname = new File(systemDir, "uiderrors.txt"); 5102 return fname; 5103 } 5104 5105 static void reportSettingsProblem(int priority, String msg) { 5106 logCriticalInfo(priority, msg); 5107 } 5108 5109 static void logCriticalInfo(int priority, String msg) { 5110 Slog.println(priority, TAG, msg); 5111 EventLogTags.writePmCriticalInfo(msg); 5112 try { 5113 File fname = getSettingsProblemFile(); 5114 FileOutputStream out = new FileOutputStream(fname, true); 5115 PrintWriter pw = new FastPrintWriter(out); 5116 SimpleDateFormat formatter = new SimpleDateFormat(); 5117 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5118 pw.println(dateString + ": " + msg); 5119 pw.close(); 5120 FileUtils.setPermissions( 5121 fname.toString(), 5122 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5123 -1, -1); 5124 } catch (java.io.IOException e) { 5125 } 5126 } 5127 5128 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5129 PackageParser.Package pkg, File srcFile, int parseFlags) 5130 throws PackageManagerException { 5131 if (ps != null 5132 && ps.codePath.equals(srcFile) 5133 && ps.timeStamp == srcFile.lastModified() 5134 && !isCompatSignatureUpdateNeeded(pkg) 5135 && !isRecoverSignatureUpdateNeeded(pkg)) { 5136 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5137 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5138 ArraySet<PublicKey> signingKs; 5139 synchronized (mPackages) { 5140 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5141 } 5142 if (ps.signatures.mSignatures != null 5143 && ps.signatures.mSignatures.length != 0 5144 && signingKs != null) { 5145 // Optimization: reuse the existing cached certificates 5146 // if the package appears to be unchanged. 5147 pkg.mSignatures = ps.signatures.mSignatures; 5148 pkg.mSigningKeys = signingKs; 5149 return; 5150 } 5151 5152 Slog.w(TAG, "PackageSetting for " + ps.name 5153 + " is missing signatures. Collecting certs again to recover them."); 5154 } else { 5155 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5156 } 5157 5158 try { 5159 pp.collectCertificates(pkg, parseFlags); 5160 pp.collectManifestDigest(pkg); 5161 } catch (PackageParserException e) { 5162 throw PackageManagerException.from(e); 5163 } 5164 } 5165 5166 /* 5167 * Scan a package and return the newly parsed package. 5168 * Returns null in case of errors and the error code is stored in mLastScanError 5169 */ 5170 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5171 long currentTime, UserHandle user) throws PackageManagerException { 5172 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5173 parseFlags |= mDefParseFlags; 5174 PackageParser pp = new PackageParser(); 5175 pp.setSeparateProcesses(mSeparateProcesses); 5176 pp.setOnlyCoreApps(mOnlyCore); 5177 pp.setDisplayMetrics(mMetrics); 5178 5179 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5180 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5181 } 5182 5183 final PackageParser.Package pkg; 5184 try { 5185 pkg = pp.parsePackage(scanFile, parseFlags); 5186 } catch (PackageParserException e) { 5187 throw PackageManagerException.from(e); 5188 } 5189 5190 PackageSetting ps = null; 5191 PackageSetting updatedPkg; 5192 // reader 5193 synchronized (mPackages) { 5194 // Look to see if we already know about this package. 5195 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5196 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5197 // This package has been renamed to its original name. Let's 5198 // use that. 5199 ps = mSettings.peekPackageLPr(oldName); 5200 } 5201 // If there was no original package, see one for the real package name. 5202 if (ps == null) { 5203 ps = mSettings.peekPackageLPr(pkg.packageName); 5204 } 5205 // Check to see if this package could be hiding/updating a system 5206 // package. Must look for it either under the original or real 5207 // package name depending on our state. 5208 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5209 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5210 } 5211 boolean updatedPkgBetter = false; 5212 // First check if this is a system package that may involve an update 5213 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5214 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5215 // it needs to drop FLAG_PRIVILEGED. 5216 if (locationIsPrivileged(scanFile)) { 5217 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5218 } else { 5219 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5220 } 5221 5222 if (ps != null && !ps.codePath.equals(scanFile)) { 5223 // The path has changed from what was last scanned... check the 5224 // version of the new path against what we have stored to determine 5225 // what to do. 5226 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5227 if (pkg.mVersionCode <= ps.versionCode) { 5228 // The system package has been updated and the code path does not match 5229 // Ignore entry. Skip it. 5230 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5231 + " ignored: updated version " + ps.versionCode 5232 + " better than this " + pkg.mVersionCode); 5233 if (!updatedPkg.codePath.equals(scanFile)) { 5234 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5235 + ps.name + " changing from " + updatedPkg.codePathString 5236 + " to " + scanFile); 5237 updatedPkg.codePath = scanFile; 5238 updatedPkg.codePathString = scanFile.toString(); 5239 updatedPkg.resourcePath = scanFile; 5240 updatedPkg.resourcePathString = scanFile.toString(); 5241 } 5242 updatedPkg.pkg = pkg; 5243 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5244 } else { 5245 // The current app on the system partition is better than 5246 // what we have updated to on the data partition; switch 5247 // back to the system partition version. 5248 // At this point, its safely assumed that package installation for 5249 // apps in system partition will go through. If not there won't be a working 5250 // version of the app 5251 // writer 5252 synchronized (mPackages) { 5253 // Just remove the loaded entries from package lists. 5254 mPackages.remove(ps.name); 5255 } 5256 5257 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5258 + " reverting from " + ps.codePathString 5259 + ": new version " + pkg.mVersionCode 5260 + " better than installed " + ps.versionCode); 5261 5262 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5263 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5264 synchronized (mInstallLock) { 5265 args.cleanUpResourcesLI(); 5266 } 5267 synchronized (mPackages) { 5268 mSettings.enableSystemPackageLPw(ps.name); 5269 } 5270 updatedPkgBetter = true; 5271 } 5272 } 5273 } 5274 5275 if (updatedPkg != null) { 5276 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5277 // initially 5278 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5279 5280 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5281 // flag set initially 5282 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5283 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5284 } 5285 } 5286 5287 // Verify certificates against what was last scanned 5288 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5289 5290 /* 5291 * A new system app appeared, but we already had a non-system one of the 5292 * same name installed earlier. 5293 */ 5294 boolean shouldHideSystemApp = false; 5295 if (updatedPkg == null && ps != null 5296 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5297 /* 5298 * Check to make sure the signatures match first. If they don't, 5299 * wipe the installed application and its data. 5300 */ 5301 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5302 != PackageManager.SIGNATURE_MATCH) { 5303 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5304 + " signatures don't match existing userdata copy; removing"); 5305 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5306 ps = null; 5307 } else { 5308 /* 5309 * If the newly-added system app is an older version than the 5310 * already installed version, hide it. It will be scanned later 5311 * and re-added like an update. 5312 */ 5313 if (pkg.mVersionCode <= ps.versionCode) { 5314 shouldHideSystemApp = true; 5315 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5316 + " but new version " + pkg.mVersionCode + " better than installed " 5317 + ps.versionCode + "; hiding system"); 5318 } else { 5319 /* 5320 * The newly found system app is a newer version that the 5321 * one previously installed. Simply remove the 5322 * already-installed application and replace it with our own 5323 * while keeping the application data. 5324 */ 5325 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5326 + " reverting from " + ps.codePathString + ": new version " 5327 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5329 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5330 synchronized (mInstallLock) { 5331 args.cleanUpResourcesLI(); 5332 } 5333 } 5334 } 5335 } 5336 5337 // The apk is forward locked (not public) if its code and resources 5338 // are kept in different files. (except for app in either system or 5339 // vendor path). 5340 // TODO grab this value from PackageSettings 5341 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5342 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5343 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5344 } 5345 } 5346 5347 // TODO: extend to support forward-locked splits 5348 String resourcePath = null; 5349 String baseResourcePath = null; 5350 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5351 if (ps != null && ps.resourcePathString != null) { 5352 resourcePath = ps.resourcePathString; 5353 baseResourcePath = ps.resourcePathString; 5354 } else { 5355 // Should not happen at all. Just log an error. 5356 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5357 } 5358 } else { 5359 resourcePath = pkg.codePath; 5360 baseResourcePath = pkg.baseCodePath; 5361 } 5362 5363 // Set application objects path explicitly. 5364 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5365 pkg.applicationInfo.setCodePath(pkg.codePath); 5366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5368 pkg.applicationInfo.setResourcePath(resourcePath); 5369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5371 5372 // Note that we invoke the following method only if we are about to unpack an application 5373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5374 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5375 5376 /* 5377 * If the system app should be overridden by a previously installed 5378 * data, hide the system app now and let the /data/app scan pick it up 5379 * again. 5380 */ 5381 if (shouldHideSystemApp) { 5382 synchronized (mPackages) { 5383 /* 5384 * We have to grant systems permissions before we hide, because 5385 * grantPermissions will assume the package update is trying to 5386 * expand its permissions. 5387 */ 5388 grantPermissionsLPw(pkg, true, pkg.packageName); 5389 mSettings.disableSystemPackageLPw(pkg.packageName); 5390 } 5391 } 5392 5393 return scannedPkg; 5394 } 5395 5396 private static String fixProcessName(String defProcessName, 5397 String processName, int uid) { 5398 if (processName == null) { 5399 return defProcessName; 5400 } 5401 return processName; 5402 } 5403 5404 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5405 throws PackageManagerException { 5406 if (pkgSetting.signatures.mSignatures != null) { 5407 // Already existing package. Make sure signatures match 5408 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5409 == PackageManager.SIGNATURE_MATCH; 5410 if (!match) { 5411 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5412 == PackageManager.SIGNATURE_MATCH; 5413 } 5414 if (!match) { 5415 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5416 == PackageManager.SIGNATURE_MATCH; 5417 } 5418 if (!match) { 5419 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5420 + pkg.packageName + " signatures do not match the " 5421 + "previously installed version; ignoring!"); 5422 } 5423 } 5424 5425 // Check for shared user signatures 5426 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5427 // Already existing package. Make sure signatures match 5428 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5429 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5430 if (!match) { 5431 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5432 == PackageManager.SIGNATURE_MATCH; 5433 } 5434 if (!match) { 5435 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5436 == PackageManager.SIGNATURE_MATCH; 5437 } 5438 if (!match) { 5439 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5440 "Package " + pkg.packageName 5441 + " has no signatures that match those in shared user " 5442 + pkgSetting.sharedUser.name + "; ignoring!"); 5443 } 5444 } 5445 } 5446 5447 /** 5448 * Enforces that only the system UID or root's UID can call a method exposed 5449 * via Binder. 5450 * 5451 * @param message used as message if SecurityException is thrown 5452 * @throws SecurityException if the caller is not system or root 5453 */ 5454 private static final void enforceSystemOrRoot(String message) { 5455 final int uid = Binder.getCallingUid(); 5456 if (uid != Process.SYSTEM_UID && uid != 0) { 5457 throw new SecurityException(message); 5458 } 5459 } 5460 5461 @Override 5462 public void performBootDexOpt() { 5463 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5464 5465 // Before everything else, see whether we need to fstrim. 5466 try { 5467 IMountService ms = PackageHelper.getMountService(); 5468 if (ms != null) { 5469 final boolean isUpgrade = isUpgrade(); 5470 boolean doTrim = isUpgrade; 5471 if (doTrim) { 5472 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5473 } else { 5474 final long interval = android.provider.Settings.Global.getLong( 5475 mContext.getContentResolver(), 5476 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5477 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5478 if (interval > 0) { 5479 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5480 if (timeSinceLast > interval) { 5481 doTrim = true; 5482 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5483 + "; running immediately"); 5484 } 5485 } 5486 } 5487 if (doTrim) { 5488 if (!isFirstBoot()) { 5489 try { 5490 ActivityManagerNative.getDefault().showBootMessage( 5491 mContext.getResources().getString( 5492 R.string.android_upgrading_fstrim), true); 5493 } catch (RemoteException e) { 5494 } 5495 } 5496 ms.runMaintenance(); 5497 } 5498 } else { 5499 Slog.e(TAG, "Mount service unavailable!"); 5500 } 5501 } catch (RemoteException e) { 5502 // Can't happen; MountService is local 5503 } 5504 5505 final ArraySet<PackageParser.Package> pkgs; 5506 synchronized (mPackages) { 5507 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5508 } 5509 5510 if (pkgs != null) { 5511 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5512 // in case the device runs out of space. 5513 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5514 // Give priority to core apps. 5515 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5516 PackageParser.Package pkg = it.next(); 5517 if (pkg.coreApp) { 5518 if (DEBUG_DEXOPT) { 5519 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5520 } 5521 sortedPkgs.add(pkg); 5522 it.remove(); 5523 } 5524 } 5525 // Give priority to system apps that listen for pre boot complete. 5526 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5527 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5528 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5529 PackageParser.Package pkg = it.next(); 5530 if (pkgNames.contains(pkg.packageName)) { 5531 if (DEBUG_DEXOPT) { 5532 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5533 } 5534 sortedPkgs.add(pkg); 5535 it.remove(); 5536 } 5537 } 5538 // Give priority to system apps. 5539 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5540 PackageParser.Package pkg = it.next(); 5541 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5542 if (DEBUG_DEXOPT) { 5543 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5544 } 5545 sortedPkgs.add(pkg); 5546 it.remove(); 5547 } 5548 } 5549 // Give priority to updated system apps. 5550 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5551 PackageParser.Package pkg = it.next(); 5552 if (pkg.isUpdatedSystemApp()) { 5553 if (DEBUG_DEXOPT) { 5554 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5555 } 5556 sortedPkgs.add(pkg); 5557 it.remove(); 5558 } 5559 } 5560 // Give priority to apps that listen for boot complete. 5561 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5562 pkgNames = getPackageNamesForIntent(intent); 5563 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5564 PackageParser.Package pkg = it.next(); 5565 if (pkgNames.contains(pkg.packageName)) { 5566 if (DEBUG_DEXOPT) { 5567 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5568 } 5569 sortedPkgs.add(pkg); 5570 it.remove(); 5571 } 5572 } 5573 // Filter out packages that aren't recently used. 5574 filterRecentlyUsedApps(pkgs); 5575 // Add all remaining apps. 5576 for (PackageParser.Package pkg : pkgs) { 5577 if (DEBUG_DEXOPT) { 5578 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5579 } 5580 sortedPkgs.add(pkg); 5581 } 5582 5583 // If we want to be lazy, filter everything that wasn't recently used. 5584 if (mLazyDexOpt) { 5585 filterRecentlyUsedApps(sortedPkgs); 5586 } 5587 5588 int i = 0; 5589 int total = sortedPkgs.size(); 5590 File dataDir = Environment.getDataDirectory(); 5591 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5592 if (lowThreshold == 0) { 5593 throw new IllegalStateException("Invalid low memory threshold"); 5594 } 5595 for (PackageParser.Package pkg : sortedPkgs) { 5596 long usableSpace = dataDir.getUsableSpace(); 5597 if (usableSpace < lowThreshold) { 5598 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5599 break; 5600 } 5601 performBootDexOpt(pkg, ++i, total); 5602 } 5603 } 5604 } 5605 5606 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5607 // Filter out packages that aren't recently used. 5608 // 5609 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5610 // should do a full dexopt. 5611 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5612 int total = pkgs.size(); 5613 int skipped = 0; 5614 long now = System.currentTimeMillis(); 5615 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5616 PackageParser.Package pkg = i.next(); 5617 long then = pkg.mLastPackageUsageTimeInMills; 5618 if (then + mDexOptLRUThresholdInMills < now) { 5619 if (DEBUG_DEXOPT) { 5620 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5621 ((then == 0) ? "never" : new Date(then))); 5622 } 5623 i.remove(); 5624 skipped++; 5625 } 5626 } 5627 if (DEBUG_DEXOPT) { 5628 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5629 } 5630 } 5631 } 5632 5633 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5634 List<ResolveInfo> ris = null; 5635 try { 5636 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5637 intent, null, 0, UserHandle.USER_OWNER); 5638 } catch (RemoteException e) { 5639 } 5640 ArraySet<String> pkgNames = new ArraySet<String>(); 5641 if (ris != null) { 5642 for (ResolveInfo ri : ris) { 5643 pkgNames.add(ri.activityInfo.packageName); 5644 } 5645 } 5646 return pkgNames; 5647 } 5648 5649 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5650 if (DEBUG_DEXOPT) { 5651 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5652 } 5653 if (!isFirstBoot()) { 5654 try { 5655 ActivityManagerNative.getDefault().showBootMessage( 5656 mContext.getResources().getString(R.string.android_upgrading_apk, 5657 curr, total), true); 5658 } catch (RemoteException e) { 5659 } 5660 } 5661 PackageParser.Package p = pkg; 5662 synchronized (mInstallLock) { 5663 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5664 false /* force dex */, false /* defer */, true /* include dependencies */); 5665 } 5666 } 5667 5668 @Override 5669 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5670 return performDexOpt(packageName, instructionSet, false); 5671 } 5672 5673 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5674 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5675 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5676 if (!dexopt && !updateUsage) { 5677 // We aren't going to dexopt or update usage, so bail early. 5678 return false; 5679 } 5680 PackageParser.Package p; 5681 final String targetInstructionSet; 5682 synchronized (mPackages) { 5683 p = mPackages.get(packageName); 5684 if (p == null) { 5685 return false; 5686 } 5687 if (updateUsage) { 5688 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5689 } 5690 mPackageUsage.write(false); 5691 if (!dexopt) { 5692 // We aren't going to dexopt, so bail early. 5693 return false; 5694 } 5695 5696 targetInstructionSet = instructionSet != null ? instructionSet : 5697 getPrimaryInstructionSet(p.applicationInfo); 5698 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5699 return false; 5700 } 5701 } 5702 5703 synchronized (mInstallLock) { 5704 final String[] instructionSets = new String[] { targetInstructionSet }; 5705 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5706 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5707 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5708 } 5709 } 5710 5711 public ArraySet<String> getPackagesThatNeedDexOpt() { 5712 ArraySet<String> pkgs = null; 5713 synchronized (mPackages) { 5714 for (PackageParser.Package p : mPackages.values()) { 5715 if (DEBUG_DEXOPT) { 5716 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5717 } 5718 if (!p.mDexOptPerformed.isEmpty()) { 5719 continue; 5720 } 5721 if (pkgs == null) { 5722 pkgs = new ArraySet<String>(); 5723 } 5724 pkgs.add(p.packageName); 5725 } 5726 } 5727 return pkgs; 5728 } 5729 5730 public void shutdown() { 5731 mPackageUsage.write(true); 5732 } 5733 5734 @Override 5735 public void forceDexOpt(String packageName) { 5736 enforceSystemOrRoot("forceDexOpt"); 5737 5738 PackageParser.Package pkg; 5739 synchronized (mPackages) { 5740 pkg = mPackages.get(packageName); 5741 if (pkg == null) { 5742 throw new IllegalArgumentException("Missing package: " + packageName); 5743 } 5744 } 5745 5746 synchronized (mInstallLock) { 5747 final String[] instructionSets = new String[] { 5748 getPrimaryInstructionSet(pkg.applicationInfo) }; 5749 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5750 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5751 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5752 throw new IllegalStateException("Failed to dexopt: " + res); 5753 } 5754 } 5755 } 5756 5757 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5758 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5759 Slog.w(TAG, "Unable to update from " + oldPkg.name 5760 + " to " + newPkg.packageName 5761 + ": old package not in system partition"); 5762 return false; 5763 } else if (mPackages.get(oldPkg.name) != null) { 5764 Slog.w(TAG, "Unable to update from " + oldPkg.name 5765 + " to " + newPkg.packageName 5766 + ": old package still exists"); 5767 return false; 5768 } 5769 return true; 5770 } 5771 5772 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5773 int[] users = sUserManager.getUserIds(); 5774 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5775 if (res < 0) { 5776 return res; 5777 } 5778 for (int user : users) { 5779 if (user != 0) { 5780 res = mInstaller.createUserData(volumeUuid, packageName, 5781 UserHandle.getUid(user, uid), user, seinfo); 5782 if (res < 0) { 5783 return res; 5784 } 5785 } 5786 } 5787 return res; 5788 } 5789 5790 private int removeDataDirsLI(String volumeUuid, String packageName) { 5791 int[] users = sUserManager.getUserIds(); 5792 int res = 0; 5793 for (int user : users) { 5794 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5795 if (resInner < 0) { 5796 res = resInner; 5797 } 5798 } 5799 5800 return res; 5801 } 5802 5803 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5804 int[] users = sUserManager.getUserIds(); 5805 int res = 0; 5806 for (int user : users) { 5807 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5808 if (resInner < 0) { 5809 res = resInner; 5810 } 5811 } 5812 return res; 5813 } 5814 5815 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5816 PackageParser.Package changingLib) { 5817 if (file.path != null) { 5818 usesLibraryFiles.add(file.path); 5819 return; 5820 } 5821 PackageParser.Package p = mPackages.get(file.apk); 5822 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5823 // If we are doing this while in the middle of updating a library apk, 5824 // then we need to make sure to use that new apk for determining the 5825 // dependencies here. (We haven't yet finished committing the new apk 5826 // to the package manager state.) 5827 if (p == null || p.packageName.equals(changingLib.packageName)) { 5828 p = changingLib; 5829 } 5830 } 5831 if (p != null) { 5832 usesLibraryFiles.addAll(p.getAllCodePaths()); 5833 } 5834 } 5835 5836 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5837 PackageParser.Package changingLib) throws PackageManagerException { 5838 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5839 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5840 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5841 for (int i=0; i<N; i++) { 5842 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5843 if (file == null) { 5844 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5845 "Package " + pkg.packageName + " requires unavailable shared library " 5846 + pkg.usesLibraries.get(i) + "; failing!"); 5847 } 5848 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5849 } 5850 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5851 for (int i=0; i<N; i++) { 5852 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5853 if (file == null) { 5854 Slog.w(TAG, "Package " + pkg.packageName 5855 + " desires unavailable shared library " 5856 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5857 } else { 5858 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5859 } 5860 } 5861 N = usesLibraryFiles.size(); 5862 if (N > 0) { 5863 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5864 } else { 5865 pkg.usesLibraryFiles = null; 5866 } 5867 } 5868 } 5869 5870 private static boolean hasString(List<String> list, List<String> which) { 5871 if (list == null) { 5872 return false; 5873 } 5874 for (int i=list.size()-1; i>=0; i--) { 5875 for (int j=which.size()-1; j>=0; j--) { 5876 if (which.get(j).equals(list.get(i))) { 5877 return true; 5878 } 5879 } 5880 } 5881 return false; 5882 } 5883 5884 private void updateAllSharedLibrariesLPw() { 5885 for (PackageParser.Package pkg : mPackages.values()) { 5886 try { 5887 updateSharedLibrariesLPw(pkg, null); 5888 } catch (PackageManagerException e) { 5889 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5890 } 5891 } 5892 } 5893 5894 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5895 PackageParser.Package changingPkg) { 5896 ArrayList<PackageParser.Package> res = null; 5897 for (PackageParser.Package pkg : mPackages.values()) { 5898 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5899 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5900 if (res == null) { 5901 res = new ArrayList<PackageParser.Package>(); 5902 } 5903 res.add(pkg); 5904 try { 5905 updateSharedLibrariesLPw(pkg, changingPkg); 5906 } catch (PackageManagerException e) { 5907 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5908 } 5909 } 5910 } 5911 return res; 5912 } 5913 5914 /** 5915 * Derive the value of the {@code cpuAbiOverride} based on the provided 5916 * value and an optional stored value from the package settings. 5917 */ 5918 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5919 String cpuAbiOverride = null; 5920 5921 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5922 cpuAbiOverride = null; 5923 } else if (abiOverride != null) { 5924 cpuAbiOverride = abiOverride; 5925 } else if (settings != null) { 5926 cpuAbiOverride = settings.cpuAbiOverrideString; 5927 } 5928 5929 return cpuAbiOverride; 5930 } 5931 5932 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5933 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5934 boolean success = false; 5935 try { 5936 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5937 currentTime, user); 5938 success = true; 5939 return res; 5940 } finally { 5941 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5942 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5943 } 5944 } 5945 } 5946 5947 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5948 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5949 final File scanFile = new File(pkg.codePath); 5950 if (pkg.applicationInfo.getCodePath() == null || 5951 pkg.applicationInfo.getResourcePath() == null) { 5952 // Bail out. The resource and code paths haven't been set. 5953 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5954 "Code and resource paths haven't been set correctly"); 5955 } 5956 5957 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5958 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5959 } else { 5960 // Only allow system apps to be flagged as core apps. 5961 pkg.coreApp = false; 5962 } 5963 5964 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5965 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5966 } 5967 5968 if (mCustomResolverComponentName != null && 5969 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5970 setUpCustomResolverActivity(pkg); 5971 } 5972 5973 if (pkg.packageName.equals("android")) { 5974 synchronized (mPackages) { 5975 if (mAndroidApplication != null) { 5976 Slog.w(TAG, "*************************************************"); 5977 Slog.w(TAG, "Core android package being redefined. Skipping."); 5978 Slog.w(TAG, " file=" + scanFile); 5979 Slog.w(TAG, "*************************************************"); 5980 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5981 "Core android package being redefined. Skipping."); 5982 } 5983 5984 // Set up information for our fall-back user intent resolution activity. 5985 mPlatformPackage = pkg; 5986 pkg.mVersionCode = mSdkVersion; 5987 mAndroidApplication = pkg.applicationInfo; 5988 5989 if (!mResolverReplaced) { 5990 mResolveActivity.applicationInfo = mAndroidApplication; 5991 mResolveActivity.name = ResolverActivity.class.getName(); 5992 mResolveActivity.packageName = mAndroidApplication.packageName; 5993 mResolveActivity.processName = "system:ui"; 5994 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5995 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5996 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5997 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5998 mResolveActivity.exported = true; 5999 mResolveActivity.enabled = true; 6000 mResolveInfo.activityInfo = mResolveActivity; 6001 mResolveInfo.priority = 0; 6002 mResolveInfo.preferredOrder = 0; 6003 mResolveInfo.match = 0; 6004 mResolveComponentName = new ComponentName( 6005 mAndroidApplication.packageName, mResolveActivity.name); 6006 } 6007 } 6008 } 6009 6010 if (DEBUG_PACKAGE_SCANNING) { 6011 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6012 Log.d(TAG, "Scanning package " + pkg.packageName); 6013 } 6014 6015 if (mPackages.containsKey(pkg.packageName) 6016 || mSharedLibraries.containsKey(pkg.packageName)) { 6017 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6018 "Application package " + pkg.packageName 6019 + " already installed. Skipping duplicate."); 6020 } 6021 6022 // If we're only installing presumed-existing packages, require that the 6023 // scanned APK is both already known and at the path previously established 6024 // for it. Previously unknown packages we pick up normally, but if we have an 6025 // a priori expectation about this package's install presence, enforce it. 6026 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6027 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6028 if (known != null) { 6029 if (DEBUG_PACKAGE_SCANNING) { 6030 Log.d(TAG, "Examining " + pkg.codePath 6031 + " and requiring known paths " + known.codePathString 6032 + " & " + known.resourcePathString); 6033 } 6034 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6035 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6036 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6037 "Application package " + pkg.packageName 6038 + " found at " + pkg.applicationInfo.getCodePath() 6039 + " but expected at " + known.codePathString + "; ignoring."); 6040 } 6041 } 6042 } 6043 6044 // Initialize package source and resource directories 6045 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6046 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6047 6048 SharedUserSetting suid = null; 6049 PackageSetting pkgSetting = null; 6050 6051 if (!isSystemApp(pkg)) { 6052 // Only system apps can use these features. 6053 pkg.mOriginalPackages = null; 6054 pkg.mRealPackage = null; 6055 pkg.mAdoptPermissions = null; 6056 } 6057 6058 // writer 6059 synchronized (mPackages) { 6060 if (pkg.mSharedUserId != null) { 6061 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6062 if (suid == null) { 6063 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6064 "Creating application package " + pkg.packageName 6065 + " for shared user failed"); 6066 } 6067 if (DEBUG_PACKAGE_SCANNING) { 6068 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6069 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6070 + "): packages=" + suid.packages); 6071 } 6072 } 6073 6074 // Check if we are renaming from an original package name. 6075 PackageSetting origPackage = null; 6076 String realName = null; 6077 if (pkg.mOriginalPackages != null) { 6078 // This package may need to be renamed to a previously 6079 // installed name. Let's check on that... 6080 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6081 if (pkg.mOriginalPackages.contains(renamed)) { 6082 // This package had originally been installed as the 6083 // original name, and we have already taken care of 6084 // transitioning to the new one. Just update the new 6085 // one to continue using the old name. 6086 realName = pkg.mRealPackage; 6087 if (!pkg.packageName.equals(renamed)) { 6088 // Callers into this function may have already taken 6089 // care of renaming the package; only do it here if 6090 // it is not already done. 6091 pkg.setPackageName(renamed); 6092 } 6093 6094 } else { 6095 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6096 if ((origPackage = mSettings.peekPackageLPr( 6097 pkg.mOriginalPackages.get(i))) != null) { 6098 // We do have the package already installed under its 6099 // original name... should we use it? 6100 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6101 // New package is not compatible with original. 6102 origPackage = null; 6103 continue; 6104 } else if (origPackage.sharedUser != null) { 6105 // Make sure uid is compatible between packages. 6106 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6107 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6108 + " to " + pkg.packageName + ": old uid " 6109 + origPackage.sharedUser.name 6110 + " differs from " + pkg.mSharedUserId); 6111 origPackage = null; 6112 continue; 6113 } 6114 } else { 6115 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6116 + pkg.packageName + " to old name " + origPackage.name); 6117 } 6118 break; 6119 } 6120 } 6121 } 6122 } 6123 6124 if (mTransferedPackages.contains(pkg.packageName)) { 6125 Slog.w(TAG, "Package " + pkg.packageName 6126 + " was transferred to another, but its .apk remains"); 6127 } 6128 6129 // Just create the setting, don't add it yet. For already existing packages 6130 // the PkgSetting exists already and doesn't have to be created. 6131 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6132 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6133 pkg.applicationInfo.primaryCpuAbi, 6134 pkg.applicationInfo.secondaryCpuAbi, 6135 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6136 user, false); 6137 if (pkgSetting == null) { 6138 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6139 "Creating application package " + pkg.packageName + " failed"); 6140 } 6141 6142 if (pkgSetting.origPackage != null) { 6143 // If we are first transitioning from an original package, 6144 // fix up the new package's name now. We need to do this after 6145 // looking up the package under its new name, so getPackageLP 6146 // can take care of fiddling things correctly. 6147 pkg.setPackageName(origPackage.name); 6148 6149 // File a report about this. 6150 String msg = "New package " + pkgSetting.realName 6151 + " renamed to replace old package " + pkgSetting.name; 6152 reportSettingsProblem(Log.WARN, msg); 6153 6154 // Make a note of it. 6155 mTransferedPackages.add(origPackage.name); 6156 6157 // No longer need to retain this. 6158 pkgSetting.origPackage = null; 6159 } 6160 6161 if (realName != null) { 6162 // Make a note of it. 6163 mTransferedPackages.add(pkg.packageName); 6164 } 6165 6166 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6167 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6168 } 6169 6170 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6171 // Check all shared libraries and map to their actual file path. 6172 // We only do this here for apps not on a system dir, because those 6173 // are the only ones that can fail an install due to this. We 6174 // will take care of the system apps by updating all of their 6175 // library paths after the scan is done. 6176 updateSharedLibrariesLPw(pkg, null); 6177 } 6178 6179 if (mFoundPolicyFile) { 6180 SELinuxMMAC.assignSeinfoValue(pkg); 6181 } 6182 6183 pkg.applicationInfo.uid = pkgSetting.appId; 6184 pkg.mExtras = pkgSetting; 6185 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6186 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6187 // We just determined the app is signed correctly, so bring 6188 // over the latest parsed certs. 6189 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6190 } else { 6191 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6192 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6193 "Package " + pkg.packageName + " upgrade keys do not match the " 6194 + "previously installed version"); 6195 } else { 6196 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6197 String msg = "System package " + pkg.packageName 6198 + " signature changed; retaining data."; 6199 reportSettingsProblem(Log.WARN, msg); 6200 } 6201 } 6202 } else { 6203 try { 6204 verifySignaturesLP(pkgSetting, pkg); 6205 // We just determined the app is signed correctly, so bring 6206 // over the latest parsed certs. 6207 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6208 } catch (PackageManagerException e) { 6209 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6210 throw e; 6211 } 6212 // The signature has changed, but this package is in the system 6213 // image... let's recover! 6214 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6215 // However... if this package is part of a shared user, but it 6216 // doesn't match the signature of the shared user, let's fail. 6217 // What this means is that you can't change the signatures 6218 // associated with an overall shared user, which doesn't seem all 6219 // that unreasonable. 6220 if (pkgSetting.sharedUser != null) { 6221 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6222 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6223 throw new PackageManagerException( 6224 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6225 "Signature mismatch for shared user : " 6226 + pkgSetting.sharedUser); 6227 } 6228 } 6229 // File a report about this. 6230 String msg = "System package " + pkg.packageName 6231 + " signature changed; retaining data."; 6232 reportSettingsProblem(Log.WARN, msg); 6233 } 6234 } 6235 // Verify that this new package doesn't have any content providers 6236 // that conflict with existing packages. Only do this if the 6237 // package isn't already installed, since we don't want to break 6238 // things that are installed. 6239 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6240 final int N = pkg.providers.size(); 6241 int i; 6242 for (i=0; i<N; i++) { 6243 PackageParser.Provider p = pkg.providers.get(i); 6244 if (p.info.authority != null) { 6245 String names[] = p.info.authority.split(";"); 6246 for (int j = 0; j < names.length; j++) { 6247 if (mProvidersByAuthority.containsKey(names[j])) { 6248 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6249 final String otherPackageName = 6250 ((other != null && other.getComponentName() != null) ? 6251 other.getComponentName().getPackageName() : "?"); 6252 throw new PackageManagerException( 6253 INSTALL_FAILED_CONFLICTING_PROVIDER, 6254 "Can't install because provider name " + names[j] 6255 + " (in package " + pkg.applicationInfo.packageName 6256 + ") is already used by " + otherPackageName); 6257 } 6258 } 6259 } 6260 } 6261 } 6262 6263 if (pkg.mAdoptPermissions != null) { 6264 // This package wants to adopt ownership of permissions from 6265 // another package. 6266 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6267 final String origName = pkg.mAdoptPermissions.get(i); 6268 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6269 if (orig != null) { 6270 if (verifyPackageUpdateLPr(orig, pkg)) { 6271 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6272 + pkg.packageName); 6273 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6274 } 6275 } 6276 } 6277 } 6278 } 6279 6280 final String pkgName = pkg.packageName; 6281 6282 final long scanFileTime = scanFile.lastModified(); 6283 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6284 pkg.applicationInfo.processName = fixProcessName( 6285 pkg.applicationInfo.packageName, 6286 pkg.applicationInfo.processName, 6287 pkg.applicationInfo.uid); 6288 6289 File dataPath; 6290 if (mPlatformPackage == pkg) { 6291 // The system package is special. 6292 dataPath = new File(Environment.getDataDirectory(), "system"); 6293 6294 pkg.applicationInfo.dataDir = dataPath.getPath(); 6295 6296 } else { 6297 // This is a normal package, need to make its data directory. 6298 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6299 UserHandle.USER_OWNER); 6300 6301 boolean uidError = false; 6302 if (dataPath.exists()) { 6303 int currentUid = 0; 6304 try { 6305 StructStat stat = Os.stat(dataPath.getPath()); 6306 currentUid = stat.st_uid; 6307 } catch (ErrnoException e) { 6308 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6309 } 6310 6311 // If we have mismatched owners for the data path, we have a problem. 6312 if (currentUid != pkg.applicationInfo.uid) { 6313 boolean recovered = false; 6314 if (currentUid == 0) { 6315 // The directory somehow became owned by root. Wow. 6316 // This is probably because the system was stopped while 6317 // installd was in the middle of messing with its libs 6318 // directory. Ask installd to fix that. 6319 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6320 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6321 if (ret >= 0) { 6322 recovered = true; 6323 String msg = "Package " + pkg.packageName 6324 + " unexpectedly changed to uid 0; recovered to " + 6325 + pkg.applicationInfo.uid; 6326 reportSettingsProblem(Log.WARN, msg); 6327 } 6328 } 6329 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6330 || (scanFlags&SCAN_BOOTING) != 0)) { 6331 // If this is a system app, we can at least delete its 6332 // current data so the application will still work. 6333 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6334 if (ret >= 0) { 6335 // TODO: Kill the processes first 6336 // Old data gone! 6337 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6338 ? "System package " : "Third party package "; 6339 String msg = prefix + pkg.packageName 6340 + " has changed from uid: " 6341 + currentUid + " to " 6342 + pkg.applicationInfo.uid + "; old data erased"; 6343 reportSettingsProblem(Log.WARN, msg); 6344 recovered = true; 6345 6346 // And now re-install the app. 6347 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6348 pkg.applicationInfo.seinfo); 6349 if (ret == -1) { 6350 // Ack should not happen! 6351 msg = prefix + pkg.packageName 6352 + " could not have data directory re-created after delete."; 6353 reportSettingsProblem(Log.WARN, msg); 6354 throw new PackageManagerException( 6355 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6356 } 6357 } 6358 if (!recovered) { 6359 mHasSystemUidErrors = true; 6360 } 6361 } else if (!recovered) { 6362 // If we allow this install to proceed, we will be broken. 6363 // Abort, abort! 6364 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6365 "scanPackageLI"); 6366 } 6367 if (!recovered) { 6368 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6369 + pkg.applicationInfo.uid + "/fs_" 6370 + currentUid; 6371 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6372 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6373 String msg = "Package " + pkg.packageName 6374 + " has mismatched uid: " 6375 + currentUid + " on disk, " 6376 + pkg.applicationInfo.uid + " in settings"; 6377 // writer 6378 synchronized (mPackages) { 6379 mSettings.mReadMessages.append(msg); 6380 mSettings.mReadMessages.append('\n'); 6381 uidError = true; 6382 if (!pkgSetting.uidError) { 6383 reportSettingsProblem(Log.ERROR, msg); 6384 } 6385 } 6386 } 6387 } 6388 pkg.applicationInfo.dataDir = dataPath.getPath(); 6389 if (mShouldRestoreconData) { 6390 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6391 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6392 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6393 } 6394 } else { 6395 if (DEBUG_PACKAGE_SCANNING) { 6396 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6397 Log.v(TAG, "Want this data dir: " + dataPath); 6398 } 6399 //invoke installer to do the actual installation 6400 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6401 pkg.applicationInfo.seinfo); 6402 if (ret < 0) { 6403 // Error from installer 6404 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6405 "Unable to create data dirs [errorCode=" + ret + "]"); 6406 } 6407 6408 if (dataPath.exists()) { 6409 pkg.applicationInfo.dataDir = dataPath.getPath(); 6410 } else { 6411 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6412 pkg.applicationInfo.dataDir = null; 6413 } 6414 } 6415 6416 pkgSetting.uidError = uidError; 6417 } 6418 6419 final String path = scanFile.getPath(); 6420 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6421 6422 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6423 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6424 6425 // Some system apps still use directory structure for native libraries 6426 // in which case we might end up not detecting abi solely based on apk 6427 // structure. Try to detect abi based on directory structure. 6428 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6429 pkg.applicationInfo.primaryCpuAbi == null) { 6430 setBundledAppAbisAndRoots(pkg, pkgSetting); 6431 setNativeLibraryPaths(pkg); 6432 } 6433 6434 } else { 6435 if ((scanFlags & SCAN_MOVE) != 0) { 6436 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6437 // but we already have this packages package info in the PackageSetting. We just 6438 // use that and derive the native library path based on the new codepath. 6439 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6440 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6441 } 6442 6443 // Set native library paths again. For moves, the path will be updated based on the 6444 // ABIs we've determined above. For non-moves, the path will be updated based on the 6445 // ABIs we determined during compilation, but the path will depend on the final 6446 // package path (after the rename away from the stage path). 6447 setNativeLibraryPaths(pkg); 6448 } 6449 6450 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6451 final int[] userIds = sUserManager.getUserIds(); 6452 synchronized (mInstallLock) { 6453 // Create a native library symlink only if we have native libraries 6454 // and if the native libraries are 32 bit libraries. We do not provide 6455 // this symlink for 64 bit libraries. 6456 if (pkg.applicationInfo.primaryCpuAbi != null && 6457 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6458 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6459 for (int userId : userIds) { 6460 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6461 nativeLibPath, userId) < 0) { 6462 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6463 "Failed linking native library dir (user=" + userId + ")"); 6464 } 6465 } 6466 } 6467 } 6468 6469 // This is a special case for the "system" package, where the ABI is 6470 // dictated by the zygote configuration (and init.rc). We should keep track 6471 // of this ABI so that we can deal with "normal" applications that run under 6472 // the same UID correctly. 6473 if (mPlatformPackage == pkg) { 6474 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6475 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6476 } 6477 6478 // If there's a mismatch between the abi-override in the package setting 6479 // and the abiOverride specified for the install. Warn about this because we 6480 // would've already compiled the app without taking the package setting into 6481 // account. 6482 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6483 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6484 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6485 " for package: " + pkg.packageName); 6486 } 6487 } 6488 6489 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6490 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6491 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6492 6493 // Copy the derived override back to the parsed package, so that we can 6494 // update the package settings accordingly. 6495 pkg.cpuAbiOverride = cpuAbiOverride; 6496 6497 if (DEBUG_ABI_SELECTION) { 6498 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6499 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6500 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6501 } 6502 6503 // Push the derived path down into PackageSettings so we know what to 6504 // clean up at uninstall time. 6505 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6506 6507 if (DEBUG_ABI_SELECTION) { 6508 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6509 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6510 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6511 } 6512 6513 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6514 // We don't do this here during boot because we can do it all 6515 // at once after scanning all existing packages. 6516 // 6517 // We also do this *before* we perform dexopt on this package, so that 6518 // we can avoid redundant dexopts, and also to make sure we've got the 6519 // code and package path correct. 6520 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6521 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6522 } 6523 6524 if ((scanFlags & SCAN_NO_DEX) == 0) { 6525 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6526 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6527 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6528 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6529 } 6530 } 6531 if (mFactoryTest && pkg.requestedPermissions.contains( 6532 android.Manifest.permission.FACTORY_TEST)) { 6533 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6534 } 6535 6536 ArrayList<PackageParser.Package> clientLibPkgs = null; 6537 6538 // writer 6539 synchronized (mPackages) { 6540 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6541 // Only system apps can add new shared libraries. 6542 if (pkg.libraryNames != null) { 6543 for (int i=0; i<pkg.libraryNames.size(); i++) { 6544 String name = pkg.libraryNames.get(i); 6545 boolean allowed = false; 6546 if (pkg.isUpdatedSystemApp()) { 6547 // New library entries can only be added through the 6548 // system image. This is important to get rid of a lot 6549 // of nasty edge cases: for example if we allowed a non- 6550 // system update of the app to add a library, then uninstalling 6551 // the update would make the library go away, and assumptions 6552 // we made such as through app install filtering would now 6553 // have allowed apps on the device which aren't compatible 6554 // with it. Better to just have the restriction here, be 6555 // conservative, and create many fewer cases that can negatively 6556 // impact the user experience. 6557 final PackageSetting sysPs = mSettings 6558 .getDisabledSystemPkgLPr(pkg.packageName); 6559 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6560 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6561 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6562 allowed = true; 6563 allowed = true; 6564 break; 6565 } 6566 } 6567 } 6568 } else { 6569 allowed = true; 6570 } 6571 if (allowed) { 6572 if (!mSharedLibraries.containsKey(name)) { 6573 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6574 } else if (!name.equals(pkg.packageName)) { 6575 Slog.w(TAG, "Package " + pkg.packageName + " library " 6576 + name + " already exists; skipping"); 6577 } 6578 } else { 6579 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6580 + name + " that is not declared on system image; skipping"); 6581 } 6582 } 6583 if ((scanFlags&SCAN_BOOTING) == 0) { 6584 // If we are not booting, we need to update any applications 6585 // that are clients of our shared library. If we are booting, 6586 // this will all be done once the scan is complete. 6587 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6588 } 6589 } 6590 } 6591 } 6592 6593 // We also need to dexopt any apps that are dependent on this library. Note that 6594 // if these fail, we should abort the install since installing the library will 6595 // result in some apps being broken. 6596 if (clientLibPkgs != null) { 6597 if ((scanFlags & SCAN_NO_DEX) == 0) { 6598 for (int i = 0; i < clientLibPkgs.size(); i++) { 6599 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6600 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6601 null /* instruction sets */, forceDex, 6602 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6603 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6604 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6605 "scanPackageLI failed to dexopt clientLibPkgs"); 6606 } 6607 } 6608 } 6609 } 6610 6611 // Also need to kill any apps that are dependent on the library. 6612 if (clientLibPkgs != null) { 6613 for (int i=0; i<clientLibPkgs.size(); i++) { 6614 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6615 killApplication(clientPkg.applicationInfo.packageName, 6616 clientPkg.applicationInfo.uid, "update lib"); 6617 } 6618 } 6619 6620 // Make sure we're not adding any bogus keyset info 6621 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6622 ksms.assertScannedPackageValid(pkg); 6623 6624 // writer 6625 synchronized (mPackages) { 6626 // We don't expect installation to fail beyond this point 6627 6628 // Add the new setting to mSettings 6629 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6630 // Add the new setting to mPackages 6631 mPackages.put(pkg.applicationInfo.packageName, pkg); 6632 // Make sure we don't accidentally delete its data. 6633 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6634 while (iter.hasNext()) { 6635 PackageCleanItem item = iter.next(); 6636 if (pkgName.equals(item.packageName)) { 6637 iter.remove(); 6638 } 6639 } 6640 6641 // Take care of first install / last update times. 6642 if (currentTime != 0) { 6643 if (pkgSetting.firstInstallTime == 0) { 6644 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6645 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6646 pkgSetting.lastUpdateTime = currentTime; 6647 } 6648 } else if (pkgSetting.firstInstallTime == 0) { 6649 // We need *something*. Take time time stamp of the file. 6650 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6651 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6652 if (scanFileTime != pkgSetting.timeStamp) { 6653 // A package on the system image has changed; consider this 6654 // to be an update. 6655 pkgSetting.lastUpdateTime = scanFileTime; 6656 } 6657 } 6658 6659 // Add the package's KeySets to the global KeySetManagerService 6660 ksms.addScannedPackageLPw(pkg); 6661 6662 int N = pkg.providers.size(); 6663 StringBuilder r = null; 6664 int i; 6665 for (i=0; i<N; i++) { 6666 PackageParser.Provider p = pkg.providers.get(i); 6667 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6668 p.info.processName, pkg.applicationInfo.uid); 6669 mProviders.addProvider(p); 6670 p.syncable = p.info.isSyncable; 6671 if (p.info.authority != null) { 6672 String names[] = p.info.authority.split(";"); 6673 p.info.authority = null; 6674 for (int j = 0; j < names.length; j++) { 6675 if (j == 1 && p.syncable) { 6676 // We only want the first authority for a provider to possibly be 6677 // syncable, so if we already added this provider using a different 6678 // authority clear the syncable flag. We copy the provider before 6679 // changing it because the mProviders object contains a reference 6680 // to a provider that we don't want to change. 6681 // Only do this for the second authority since the resulting provider 6682 // object can be the same for all future authorities for this provider. 6683 p = new PackageParser.Provider(p); 6684 p.syncable = false; 6685 } 6686 if (!mProvidersByAuthority.containsKey(names[j])) { 6687 mProvidersByAuthority.put(names[j], p); 6688 if (p.info.authority == null) { 6689 p.info.authority = names[j]; 6690 } else { 6691 p.info.authority = p.info.authority + ";" + names[j]; 6692 } 6693 if (DEBUG_PACKAGE_SCANNING) { 6694 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6695 Log.d(TAG, "Registered content provider: " + names[j] 6696 + ", className = " + p.info.name + ", isSyncable = " 6697 + p.info.isSyncable); 6698 } 6699 } else { 6700 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6701 Slog.w(TAG, "Skipping provider name " + names[j] + 6702 " (in package " + pkg.applicationInfo.packageName + 6703 "): name already used by " 6704 + ((other != null && other.getComponentName() != null) 6705 ? other.getComponentName().getPackageName() : "?")); 6706 } 6707 } 6708 } 6709 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6710 if (r == null) { 6711 r = new StringBuilder(256); 6712 } else { 6713 r.append(' '); 6714 } 6715 r.append(p.info.name); 6716 } 6717 } 6718 if (r != null) { 6719 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6720 } 6721 6722 N = pkg.services.size(); 6723 r = null; 6724 for (i=0; i<N; i++) { 6725 PackageParser.Service s = pkg.services.get(i); 6726 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6727 s.info.processName, pkg.applicationInfo.uid); 6728 mServices.addService(s); 6729 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6730 if (r == null) { 6731 r = new StringBuilder(256); 6732 } else { 6733 r.append(' '); 6734 } 6735 r.append(s.info.name); 6736 } 6737 } 6738 if (r != null) { 6739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6740 } 6741 6742 N = pkg.receivers.size(); 6743 r = null; 6744 for (i=0; i<N; i++) { 6745 PackageParser.Activity a = pkg.receivers.get(i); 6746 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6747 a.info.processName, pkg.applicationInfo.uid); 6748 mReceivers.addActivity(a, "receiver"); 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(a.info.name); 6756 } 6757 } 6758 if (r != null) { 6759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6760 } 6761 6762 N = pkg.activities.size(); 6763 r = null; 6764 for (i=0; i<N; i++) { 6765 PackageParser.Activity a = pkg.activities.get(i); 6766 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6767 a.info.processName, pkg.applicationInfo.uid); 6768 mActivities.addActivity(a, "activity"); 6769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6770 if (r == null) { 6771 r = new StringBuilder(256); 6772 } else { 6773 r.append(' '); 6774 } 6775 r.append(a.info.name); 6776 } 6777 } 6778 if (r != null) { 6779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6780 } 6781 6782 N = pkg.permissionGroups.size(); 6783 r = null; 6784 for (i=0; i<N; i++) { 6785 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6786 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6787 if (cur == null) { 6788 mPermissionGroups.put(pg.info.name, pg); 6789 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6790 if (r == null) { 6791 r = new StringBuilder(256); 6792 } else { 6793 r.append(' '); 6794 } 6795 r.append(pg.info.name); 6796 } 6797 } else { 6798 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6799 + pg.info.packageName + " ignored: original from " 6800 + cur.info.packageName); 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("DUP:"); 6808 r.append(pg.info.name); 6809 } 6810 } 6811 } 6812 if (r != null) { 6813 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6814 } 6815 6816 N = pkg.permissions.size(); 6817 r = null; 6818 for (i=0; i<N; i++) { 6819 PackageParser.Permission p = pkg.permissions.get(i); 6820 6821 // Now that permission groups have a special meaning, we ignore permission 6822 // groups for legacy apps to prevent unexpected behavior. In particular, 6823 // permissions for one app being granted to someone just becuase they happen 6824 // to be in a group defined by another app (before this had no implications). 6825 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6826 p.group = mPermissionGroups.get(p.info.group); 6827 // Warn for a permission in an unknown group. 6828 if (p.info.group != null && p.group == null) { 6829 Slog.w(TAG, "Permission " + p.info.name + " from package " 6830 + p.info.packageName + " in an unknown group " + p.info.group); 6831 } 6832 } 6833 6834 ArrayMap<String, BasePermission> permissionMap = 6835 p.tree ? mSettings.mPermissionTrees 6836 : mSettings.mPermissions; 6837 BasePermission bp = permissionMap.get(p.info.name); 6838 6839 // Allow system apps to redefine non-system permissions 6840 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6841 final boolean currentOwnerIsSystem = (bp.perm != null 6842 && isSystemApp(bp.perm.owner)); 6843 if (isSystemApp(p.owner)) { 6844 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6845 // It's a built-in permission and no owner, take ownership now 6846 bp.packageSetting = pkgSetting; 6847 bp.perm = p; 6848 bp.uid = pkg.applicationInfo.uid; 6849 bp.sourcePackage = p.info.packageName; 6850 } else if (!currentOwnerIsSystem) { 6851 String msg = "New decl " + p.owner + " of permission " 6852 + p.info.name + " is system; overriding " + bp.sourcePackage; 6853 reportSettingsProblem(Log.WARN, msg); 6854 bp = null; 6855 } 6856 } 6857 } 6858 6859 if (bp == null) { 6860 bp = new BasePermission(p.info.name, p.info.packageName, 6861 BasePermission.TYPE_NORMAL); 6862 permissionMap.put(p.info.name, bp); 6863 } 6864 6865 if (bp.perm == null) { 6866 if (bp.sourcePackage == null 6867 || bp.sourcePackage.equals(p.info.packageName)) { 6868 BasePermission tree = findPermissionTreeLP(p.info.name); 6869 if (tree == null 6870 || tree.sourcePackage.equals(p.info.packageName)) { 6871 bp.packageSetting = pkgSetting; 6872 bp.perm = p; 6873 bp.uid = pkg.applicationInfo.uid; 6874 bp.sourcePackage = p.info.packageName; 6875 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6876 if (r == null) { 6877 r = new StringBuilder(256); 6878 } else { 6879 r.append(' '); 6880 } 6881 r.append(p.info.name); 6882 } 6883 } else { 6884 Slog.w(TAG, "Permission " + p.info.name + " from package " 6885 + p.info.packageName + " ignored: base tree " 6886 + tree.name + " is from package " 6887 + tree.sourcePackage); 6888 } 6889 } else { 6890 Slog.w(TAG, "Permission " + p.info.name + " from package " 6891 + p.info.packageName + " ignored: original from " 6892 + bp.sourcePackage); 6893 } 6894 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6895 if (r == null) { 6896 r = new StringBuilder(256); 6897 } else { 6898 r.append(' '); 6899 } 6900 r.append("DUP:"); 6901 r.append(p.info.name); 6902 } 6903 if (bp.perm == p) { 6904 bp.protectionLevel = p.info.protectionLevel; 6905 } 6906 } 6907 6908 if (r != null) { 6909 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6910 } 6911 6912 N = pkg.instrumentation.size(); 6913 r = null; 6914 for (i=0; i<N; i++) { 6915 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6916 a.info.packageName = pkg.applicationInfo.packageName; 6917 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6918 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6919 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6920 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6921 a.info.dataDir = pkg.applicationInfo.dataDir; 6922 6923 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6924 // need other information about the application, like the ABI and what not ? 6925 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6926 mInstrumentation.put(a.getComponentName(), a); 6927 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6928 if (r == null) { 6929 r = new StringBuilder(256); 6930 } else { 6931 r.append(' '); 6932 } 6933 r.append(a.info.name); 6934 } 6935 } 6936 if (r != null) { 6937 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6938 } 6939 6940 if (pkg.protectedBroadcasts != null) { 6941 N = pkg.protectedBroadcasts.size(); 6942 for (i=0; i<N; i++) { 6943 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6944 } 6945 } 6946 6947 pkgSetting.setTimeStamp(scanFileTime); 6948 6949 // Create idmap files for pairs of (packages, overlay packages). 6950 // Note: "android", ie framework-res.apk, is handled by native layers. 6951 if (pkg.mOverlayTarget != null) { 6952 // This is an overlay package. 6953 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6954 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6955 mOverlays.put(pkg.mOverlayTarget, 6956 new ArrayMap<String, PackageParser.Package>()); 6957 } 6958 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6959 map.put(pkg.packageName, pkg); 6960 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6961 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6962 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6963 "scanPackageLI failed to createIdmap"); 6964 } 6965 } 6966 } else if (mOverlays.containsKey(pkg.packageName) && 6967 !pkg.packageName.equals("android")) { 6968 // This is a regular package, with one or more known overlay packages. 6969 createIdmapsForPackageLI(pkg); 6970 } 6971 } 6972 6973 return pkg; 6974 } 6975 6976 /** 6977 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6978 * is derived purely on the basis of the contents of {@code scanFile} and 6979 * {@code cpuAbiOverride}. 6980 * 6981 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6982 */ 6983 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6984 String cpuAbiOverride, boolean extractLibs) 6985 throws PackageManagerException { 6986 // TODO: We can probably be smarter about this stuff. For installed apps, 6987 // we can calculate this information at install time once and for all. For 6988 // system apps, we can probably assume that this information doesn't change 6989 // after the first boot scan. As things stand, we do lots of unnecessary work. 6990 6991 // Give ourselves some initial paths; we'll come back for another 6992 // pass once we've determined ABI below. 6993 setNativeLibraryPaths(pkg); 6994 6995 // We would never need to extract libs for forward-locked and external packages, 6996 // since the container service will do it for us. We shouldn't attempt to 6997 // extract libs from system app when it was not updated. 6998 if (pkg.isForwardLocked() || isExternal(pkg) || 6999 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7000 extractLibs = false; 7001 } 7002 7003 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7004 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7005 7006 NativeLibraryHelper.Handle handle = null; 7007 try { 7008 handle = NativeLibraryHelper.Handle.create(scanFile); 7009 // TODO(multiArch): This can be null for apps that didn't go through the 7010 // usual installation process. We can calculate it again, like we 7011 // do during install time. 7012 // 7013 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7014 // unnecessary. 7015 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7016 7017 // Null out the abis so that they can be recalculated. 7018 pkg.applicationInfo.primaryCpuAbi = null; 7019 pkg.applicationInfo.secondaryCpuAbi = null; 7020 if (isMultiArch(pkg.applicationInfo)) { 7021 // Warn if we've set an abiOverride for multi-lib packages.. 7022 // By definition, we need to copy both 32 and 64 bit libraries for 7023 // such packages. 7024 if (pkg.cpuAbiOverride != null 7025 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7026 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7027 } 7028 7029 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7030 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7031 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7032 if (extractLibs) { 7033 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7034 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7035 useIsaSpecificSubdirs); 7036 } else { 7037 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7038 } 7039 } 7040 7041 maybeThrowExceptionForMultiArchCopy( 7042 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7043 7044 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7045 if (extractLibs) { 7046 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7047 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7048 useIsaSpecificSubdirs); 7049 } else { 7050 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7051 } 7052 } 7053 7054 maybeThrowExceptionForMultiArchCopy( 7055 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7056 7057 if (abi64 >= 0) { 7058 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7059 } 7060 7061 if (abi32 >= 0) { 7062 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7063 if (abi64 >= 0) { 7064 pkg.applicationInfo.secondaryCpuAbi = abi; 7065 } else { 7066 pkg.applicationInfo.primaryCpuAbi = abi; 7067 } 7068 } 7069 } else { 7070 String[] abiList = (cpuAbiOverride != null) ? 7071 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7072 7073 // Enable gross and lame hacks for apps that are built with old 7074 // SDK tools. We must scan their APKs for renderscript bitcode and 7075 // not launch them if it's present. Don't bother checking on devices 7076 // that don't have 64 bit support. 7077 boolean needsRenderScriptOverride = false; 7078 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7079 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7080 abiList = Build.SUPPORTED_32_BIT_ABIS; 7081 needsRenderScriptOverride = true; 7082 } 7083 7084 final int copyRet; 7085 if (extractLibs) { 7086 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7087 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7088 } else { 7089 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7090 } 7091 7092 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7093 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7094 "Error unpackaging native libs for app, errorCode=" + copyRet); 7095 } 7096 7097 if (copyRet >= 0) { 7098 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7099 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7100 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7101 } else if (needsRenderScriptOverride) { 7102 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7103 } 7104 } 7105 } catch (IOException ioe) { 7106 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7107 } finally { 7108 IoUtils.closeQuietly(handle); 7109 } 7110 7111 // Now that we've calculated the ABIs and determined if it's an internal app, 7112 // we will go ahead and populate the nativeLibraryPath. 7113 setNativeLibraryPaths(pkg); 7114 } 7115 7116 /** 7117 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7118 * i.e, so that all packages can be run inside a single process if required. 7119 * 7120 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7121 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7122 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7123 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7124 * updating a package that belongs to a shared user. 7125 * 7126 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7127 * adds unnecessary complexity. 7128 */ 7129 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7130 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7131 String requiredInstructionSet = null; 7132 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7133 requiredInstructionSet = VMRuntime.getInstructionSet( 7134 scannedPackage.applicationInfo.primaryCpuAbi); 7135 } 7136 7137 PackageSetting requirer = null; 7138 for (PackageSetting ps : packagesForUser) { 7139 // If packagesForUser contains scannedPackage, we skip it. This will happen 7140 // when scannedPackage is an update of an existing package. Without this check, 7141 // we will never be able to change the ABI of any package belonging to a shared 7142 // user, even if it's compatible with other packages. 7143 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7144 if (ps.primaryCpuAbiString == null) { 7145 continue; 7146 } 7147 7148 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7149 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7150 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7151 // this but there's not much we can do. 7152 String errorMessage = "Instruction set mismatch, " 7153 + ((requirer == null) ? "[caller]" : requirer) 7154 + " requires " + requiredInstructionSet + " whereas " + ps 7155 + " requires " + instructionSet; 7156 Slog.w(TAG, errorMessage); 7157 } 7158 7159 if (requiredInstructionSet == null) { 7160 requiredInstructionSet = instructionSet; 7161 requirer = ps; 7162 } 7163 } 7164 } 7165 7166 if (requiredInstructionSet != null) { 7167 String adjustedAbi; 7168 if (requirer != null) { 7169 // requirer != null implies that either scannedPackage was null or that scannedPackage 7170 // did not require an ABI, in which case we have to adjust scannedPackage to match 7171 // the ABI of the set (which is the same as requirer's ABI) 7172 adjustedAbi = requirer.primaryCpuAbiString; 7173 if (scannedPackage != null) { 7174 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7175 } 7176 } else { 7177 // requirer == null implies that we're updating all ABIs in the set to 7178 // match scannedPackage. 7179 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7180 } 7181 7182 for (PackageSetting ps : packagesForUser) { 7183 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7184 if (ps.primaryCpuAbiString != null) { 7185 continue; 7186 } 7187 7188 ps.primaryCpuAbiString = adjustedAbi; 7189 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7190 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7191 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7192 7193 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7194 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7195 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7196 ps.primaryCpuAbiString = null; 7197 ps.pkg.applicationInfo.primaryCpuAbi = null; 7198 return; 7199 } else { 7200 mInstaller.rmdex(ps.codePathString, 7201 getDexCodeInstructionSet(getPreferredInstructionSet())); 7202 } 7203 } 7204 } 7205 } 7206 } 7207 } 7208 7209 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7210 synchronized (mPackages) { 7211 mResolverReplaced = true; 7212 // Set up information for custom user intent resolution activity. 7213 mResolveActivity.applicationInfo = pkg.applicationInfo; 7214 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7215 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7216 mResolveActivity.processName = pkg.applicationInfo.packageName; 7217 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7218 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7219 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7220 mResolveActivity.theme = 0; 7221 mResolveActivity.exported = true; 7222 mResolveActivity.enabled = true; 7223 mResolveInfo.activityInfo = mResolveActivity; 7224 mResolveInfo.priority = 0; 7225 mResolveInfo.preferredOrder = 0; 7226 mResolveInfo.match = 0; 7227 mResolveComponentName = mCustomResolverComponentName; 7228 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7229 mResolveComponentName); 7230 } 7231 } 7232 7233 private static String calculateBundledApkRoot(final String codePathString) { 7234 final File codePath = new File(codePathString); 7235 final File codeRoot; 7236 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7237 codeRoot = Environment.getRootDirectory(); 7238 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7239 codeRoot = Environment.getOemDirectory(); 7240 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7241 codeRoot = Environment.getVendorDirectory(); 7242 } else { 7243 // Unrecognized code path; take its top real segment as the apk root: 7244 // e.g. /something/app/blah.apk => /something 7245 try { 7246 File f = codePath.getCanonicalFile(); 7247 File parent = f.getParentFile(); // non-null because codePath is a file 7248 File tmp; 7249 while ((tmp = parent.getParentFile()) != null) { 7250 f = parent; 7251 parent = tmp; 7252 } 7253 codeRoot = f; 7254 Slog.w(TAG, "Unrecognized code path " 7255 + codePath + " - using " + codeRoot); 7256 } catch (IOException e) { 7257 // Can't canonicalize the code path -- shenanigans? 7258 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7259 return Environment.getRootDirectory().getPath(); 7260 } 7261 } 7262 return codeRoot.getPath(); 7263 } 7264 7265 /** 7266 * Derive and set the location of native libraries for the given package, 7267 * which varies depending on where and how the package was installed. 7268 */ 7269 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7270 final ApplicationInfo info = pkg.applicationInfo; 7271 final String codePath = pkg.codePath; 7272 final File codeFile = new File(codePath); 7273 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7274 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7275 7276 info.nativeLibraryRootDir = null; 7277 info.nativeLibraryRootRequiresIsa = false; 7278 info.nativeLibraryDir = null; 7279 info.secondaryNativeLibraryDir = null; 7280 7281 if (isApkFile(codeFile)) { 7282 // Monolithic install 7283 if (bundledApp) { 7284 // If "/system/lib64/apkname" exists, assume that is the per-package 7285 // native library directory to use; otherwise use "/system/lib/apkname". 7286 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7287 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7288 getPrimaryInstructionSet(info)); 7289 7290 // This is a bundled system app so choose the path based on the ABI. 7291 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7292 // is just the default path. 7293 final String apkName = deriveCodePathName(codePath); 7294 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7295 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7296 apkName).getAbsolutePath(); 7297 7298 if (info.secondaryCpuAbi != null) { 7299 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7300 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7301 secondaryLibDir, apkName).getAbsolutePath(); 7302 } 7303 } else if (asecApp) { 7304 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7305 .getAbsolutePath(); 7306 } else { 7307 final String apkName = deriveCodePathName(codePath); 7308 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7309 .getAbsolutePath(); 7310 } 7311 7312 info.nativeLibraryRootRequiresIsa = false; 7313 info.nativeLibraryDir = info.nativeLibraryRootDir; 7314 } else { 7315 // Cluster install 7316 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7317 info.nativeLibraryRootRequiresIsa = true; 7318 7319 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7320 getPrimaryInstructionSet(info)).getAbsolutePath(); 7321 7322 if (info.secondaryCpuAbi != null) { 7323 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7324 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7325 } 7326 } 7327 } 7328 7329 /** 7330 * Calculate the abis and roots for a bundled app. These can uniquely 7331 * be determined from the contents of the system partition, i.e whether 7332 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7333 * of this information, and instead assume that the system was built 7334 * sensibly. 7335 */ 7336 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7337 PackageSetting pkgSetting) { 7338 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7339 7340 // If "/system/lib64/apkname" exists, assume that is the per-package 7341 // native library directory to use; otherwise use "/system/lib/apkname". 7342 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7343 setBundledAppAbi(pkg, apkRoot, apkName); 7344 // pkgSetting might be null during rescan following uninstall of updates 7345 // to a bundled app, so accommodate that possibility. The settings in 7346 // that case will be established later from the parsed package. 7347 // 7348 // If the settings aren't null, sync them up with what we've just derived. 7349 // note that apkRoot isn't stored in the package settings. 7350 if (pkgSetting != null) { 7351 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7352 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7353 } 7354 } 7355 7356 /** 7357 * Deduces the ABI of a bundled app and sets the relevant fields on the 7358 * parsed pkg object. 7359 * 7360 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7361 * under which system libraries are installed. 7362 * @param apkName the name of the installed package. 7363 */ 7364 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7365 final File codeFile = new File(pkg.codePath); 7366 7367 final boolean has64BitLibs; 7368 final boolean has32BitLibs; 7369 if (isApkFile(codeFile)) { 7370 // Monolithic install 7371 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7372 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7373 } else { 7374 // Cluster install 7375 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7376 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7377 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7378 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7379 has64BitLibs = (new File(rootDir, isa)).exists(); 7380 } else { 7381 has64BitLibs = false; 7382 } 7383 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7384 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7385 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7386 has32BitLibs = (new File(rootDir, isa)).exists(); 7387 } else { 7388 has32BitLibs = false; 7389 } 7390 } 7391 7392 if (has64BitLibs && !has32BitLibs) { 7393 // The package has 64 bit libs, but not 32 bit libs. Its primary 7394 // ABI should be 64 bit. We can safely assume here that the bundled 7395 // native libraries correspond to the most preferred ABI in the list. 7396 7397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7398 pkg.applicationInfo.secondaryCpuAbi = null; 7399 } else if (has32BitLibs && !has64BitLibs) { 7400 // The package has 32 bit libs but not 64 bit libs. Its primary 7401 // ABI should be 32 bit. 7402 7403 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7404 pkg.applicationInfo.secondaryCpuAbi = null; 7405 } else if (has32BitLibs && has64BitLibs) { 7406 // The application has both 64 and 32 bit bundled libraries. We check 7407 // here that the app declares multiArch support, and warn if it doesn't. 7408 // 7409 // We will be lenient here and record both ABIs. The primary will be the 7410 // ABI that's higher on the list, i.e, a device that's configured to prefer 7411 // 64 bit apps will see a 64 bit primary ABI, 7412 7413 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7414 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7415 } 7416 7417 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7418 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7419 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7420 } else { 7421 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7422 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7423 } 7424 } else { 7425 pkg.applicationInfo.primaryCpuAbi = null; 7426 pkg.applicationInfo.secondaryCpuAbi = null; 7427 } 7428 } 7429 7430 private void killApplication(String pkgName, int appId, String reason) { 7431 // Request the ActivityManager to kill the process(only for existing packages) 7432 // so that we do not end up in a confused state while the user is still using the older 7433 // version of the application while the new one gets installed. 7434 IActivityManager am = ActivityManagerNative.getDefault(); 7435 if (am != null) { 7436 try { 7437 am.killApplicationWithAppId(pkgName, appId, reason); 7438 } catch (RemoteException e) { 7439 } 7440 } 7441 } 7442 7443 void removePackageLI(PackageSetting ps, boolean chatty) { 7444 if (DEBUG_INSTALL) { 7445 if (chatty) 7446 Log.d(TAG, "Removing package " + ps.name); 7447 } 7448 7449 // writer 7450 synchronized (mPackages) { 7451 mPackages.remove(ps.name); 7452 final PackageParser.Package pkg = ps.pkg; 7453 if (pkg != null) { 7454 cleanPackageDataStructuresLILPw(pkg, chatty); 7455 } 7456 } 7457 } 7458 7459 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7460 if (DEBUG_INSTALL) { 7461 if (chatty) 7462 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7463 } 7464 7465 // writer 7466 synchronized (mPackages) { 7467 mPackages.remove(pkg.applicationInfo.packageName); 7468 cleanPackageDataStructuresLILPw(pkg, chatty); 7469 } 7470 } 7471 7472 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7473 int N = pkg.providers.size(); 7474 StringBuilder r = null; 7475 int i; 7476 for (i=0; i<N; i++) { 7477 PackageParser.Provider p = pkg.providers.get(i); 7478 mProviders.removeProvider(p); 7479 if (p.info.authority == null) { 7480 7481 /* There was another ContentProvider with this authority when 7482 * this app was installed so this authority is null, 7483 * Ignore it as we don't have to unregister the provider. 7484 */ 7485 continue; 7486 } 7487 String names[] = p.info.authority.split(";"); 7488 for (int j = 0; j < names.length; j++) { 7489 if (mProvidersByAuthority.get(names[j]) == p) { 7490 mProvidersByAuthority.remove(names[j]); 7491 if (DEBUG_REMOVE) { 7492 if (chatty) 7493 Log.d(TAG, "Unregistered content provider: " + names[j] 7494 + ", className = " + p.info.name + ", isSyncable = " 7495 + p.info.isSyncable); 7496 } 7497 } 7498 } 7499 if (DEBUG_REMOVE && chatty) { 7500 if (r == null) { 7501 r = new StringBuilder(256); 7502 } else { 7503 r.append(' '); 7504 } 7505 r.append(p.info.name); 7506 } 7507 } 7508 if (r != null) { 7509 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7510 } 7511 7512 N = pkg.services.size(); 7513 r = null; 7514 for (i=0; i<N; i++) { 7515 PackageParser.Service s = pkg.services.get(i); 7516 mServices.removeService(s); 7517 if (chatty) { 7518 if (r == null) { 7519 r = new StringBuilder(256); 7520 } else { 7521 r.append(' '); 7522 } 7523 r.append(s.info.name); 7524 } 7525 } 7526 if (r != null) { 7527 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7528 } 7529 7530 N = pkg.receivers.size(); 7531 r = null; 7532 for (i=0; i<N; i++) { 7533 PackageParser.Activity a = pkg.receivers.get(i); 7534 mReceivers.removeActivity(a, "receiver"); 7535 if (DEBUG_REMOVE && chatty) { 7536 if (r == null) { 7537 r = new StringBuilder(256); 7538 } else { 7539 r.append(' '); 7540 } 7541 r.append(a.info.name); 7542 } 7543 } 7544 if (r != null) { 7545 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7546 } 7547 7548 N = pkg.activities.size(); 7549 r = null; 7550 for (i=0; i<N; i++) { 7551 PackageParser.Activity a = pkg.activities.get(i); 7552 mActivities.removeActivity(a, "activity"); 7553 if (DEBUG_REMOVE && chatty) { 7554 if (r == null) { 7555 r = new StringBuilder(256); 7556 } else { 7557 r.append(' '); 7558 } 7559 r.append(a.info.name); 7560 } 7561 } 7562 if (r != null) { 7563 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7564 } 7565 7566 N = pkg.permissions.size(); 7567 r = null; 7568 for (i=0; i<N; i++) { 7569 PackageParser.Permission p = pkg.permissions.get(i); 7570 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7571 if (bp == null) { 7572 bp = mSettings.mPermissionTrees.get(p.info.name); 7573 } 7574 if (bp != null && bp.perm == p) { 7575 bp.perm = null; 7576 if (DEBUG_REMOVE && chatty) { 7577 if (r == null) { 7578 r = new StringBuilder(256); 7579 } else { 7580 r.append(' '); 7581 } 7582 r.append(p.info.name); 7583 } 7584 } 7585 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7586 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7587 if (appOpPerms != null) { 7588 appOpPerms.remove(pkg.packageName); 7589 } 7590 } 7591 } 7592 if (r != null) { 7593 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7594 } 7595 7596 N = pkg.requestedPermissions.size(); 7597 r = null; 7598 for (i=0; i<N; i++) { 7599 String perm = pkg.requestedPermissions.get(i); 7600 BasePermission bp = mSettings.mPermissions.get(perm); 7601 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7602 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7603 if (appOpPerms != null) { 7604 appOpPerms.remove(pkg.packageName); 7605 if (appOpPerms.isEmpty()) { 7606 mAppOpPermissionPackages.remove(perm); 7607 } 7608 } 7609 } 7610 } 7611 if (r != null) { 7612 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7613 } 7614 7615 N = pkg.instrumentation.size(); 7616 r = null; 7617 for (i=0; i<N; i++) { 7618 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7619 mInstrumentation.remove(a.getComponentName()); 7620 if (DEBUG_REMOVE && chatty) { 7621 if (r == null) { 7622 r = new StringBuilder(256); 7623 } else { 7624 r.append(' '); 7625 } 7626 r.append(a.info.name); 7627 } 7628 } 7629 if (r != null) { 7630 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7631 } 7632 7633 r = null; 7634 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7635 // Only system apps can hold shared libraries. 7636 if (pkg.libraryNames != null) { 7637 for (i=0; i<pkg.libraryNames.size(); i++) { 7638 String name = pkg.libraryNames.get(i); 7639 SharedLibraryEntry cur = mSharedLibraries.get(name); 7640 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7641 mSharedLibraries.remove(name); 7642 if (DEBUG_REMOVE && chatty) { 7643 if (r == null) { 7644 r = new StringBuilder(256); 7645 } else { 7646 r.append(' '); 7647 } 7648 r.append(name); 7649 } 7650 } 7651 } 7652 } 7653 } 7654 if (r != null) { 7655 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7656 } 7657 } 7658 7659 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7660 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7661 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7662 return true; 7663 } 7664 } 7665 return false; 7666 } 7667 7668 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7669 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7670 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7671 7672 private void updatePermissionsLPw(String changingPkg, 7673 PackageParser.Package pkgInfo, int flags) { 7674 // Make sure there are no dangling permission trees. 7675 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7676 while (it.hasNext()) { 7677 final BasePermission bp = it.next(); 7678 if (bp.packageSetting == null) { 7679 // We may not yet have parsed the package, so just see if 7680 // we still know about its settings. 7681 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7682 } 7683 if (bp.packageSetting == null) { 7684 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7685 + " from package " + bp.sourcePackage); 7686 it.remove(); 7687 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7688 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7689 Slog.i(TAG, "Removing old permission tree: " + bp.name 7690 + " from package " + bp.sourcePackage); 7691 flags |= UPDATE_PERMISSIONS_ALL; 7692 it.remove(); 7693 } 7694 } 7695 } 7696 7697 // Make sure all dynamic permissions have been assigned to a package, 7698 // and make sure there are no dangling permissions. 7699 it = mSettings.mPermissions.values().iterator(); 7700 while (it.hasNext()) { 7701 final BasePermission bp = it.next(); 7702 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7703 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7704 + bp.name + " pkg=" + bp.sourcePackage 7705 + " info=" + bp.pendingInfo); 7706 if (bp.packageSetting == null && bp.pendingInfo != null) { 7707 final BasePermission tree = findPermissionTreeLP(bp.name); 7708 if (tree != null && tree.perm != null) { 7709 bp.packageSetting = tree.packageSetting; 7710 bp.perm = new PackageParser.Permission(tree.perm.owner, 7711 new PermissionInfo(bp.pendingInfo)); 7712 bp.perm.info.packageName = tree.perm.info.packageName; 7713 bp.perm.info.name = bp.name; 7714 bp.uid = tree.uid; 7715 } 7716 } 7717 } 7718 if (bp.packageSetting == null) { 7719 // We may not yet have parsed the package, so just see if 7720 // we still know about its settings. 7721 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7722 } 7723 if (bp.packageSetting == null) { 7724 Slog.w(TAG, "Removing dangling permission: " + bp.name 7725 + " from package " + bp.sourcePackage); 7726 it.remove(); 7727 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7728 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7729 Slog.i(TAG, "Removing old permission: " + bp.name 7730 + " from package " + bp.sourcePackage); 7731 flags |= UPDATE_PERMISSIONS_ALL; 7732 it.remove(); 7733 } 7734 } 7735 } 7736 7737 // Now update the permissions for all packages, in particular 7738 // replace the granted permissions of the system packages. 7739 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7740 for (PackageParser.Package pkg : mPackages.values()) { 7741 if (pkg != pkgInfo) { 7742 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7743 changingPkg); 7744 } 7745 } 7746 } 7747 7748 if (pkgInfo != null) { 7749 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7750 } 7751 } 7752 7753 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7754 String packageOfInterest) { 7755 // IMPORTANT: There are two types of permissions: install and runtime. 7756 // Install time permissions are granted when the app is installed to 7757 // all device users and users added in the future. Runtime permissions 7758 // are granted at runtime explicitly to specific users. Normal and signature 7759 // protected permissions are install time permissions. Dangerous permissions 7760 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7761 // otherwise they are runtime permissions. This function does not manage 7762 // runtime permissions except for the case an app targeting Lollipop MR1 7763 // being upgraded to target a newer SDK, in which case dangerous permissions 7764 // are transformed from install time to runtime ones. 7765 7766 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7767 if (ps == null) { 7768 return; 7769 } 7770 7771 PermissionsState permissionsState = ps.getPermissionsState(); 7772 PermissionsState origPermissions = permissionsState; 7773 7774 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7775 7776 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7777 7778 boolean changedInstallPermission = false; 7779 7780 if (replace) { 7781 ps.installPermissionsFixed = false; 7782 if (!ps.isSharedUser()) { 7783 origPermissions = new PermissionsState(permissionsState); 7784 permissionsState.reset(); 7785 } 7786 } 7787 7788 permissionsState.setGlobalGids(mGlobalGids); 7789 7790 final int N = pkg.requestedPermissions.size(); 7791 for (int i=0; i<N; i++) { 7792 final String name = pkg.requestedPermissions.get(i); 7793 final BasePermission bp = mSettings.mPermissions.get(name); 7794 7795 if (DEBUG_INSTALL) { 7796 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7797 } 7798 7799 if (bp == null || bp.packageSetting == null) { 7800 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7801 Slog.w(TAG, "Unknown permission " + name 7802 + " in package " + pkg.packageName); 7803 } 7804 continue; 7805 } 7806 7807 final String perm = bp.name; 7808 boolean allowedSig = false; 7809 int grant = GRANT_DENIED; 7810 7811 // Keep track of app op permissions. 7812 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7813 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7814 if (pkgs == null) { 7815 pkgs = new ArraySet<>(); 7816 mAppOpPermissionPackages.put(bp.name, pkgs); 7817 } 7818 pkgs.add(pkg.packageName); 7819 } 7820 7821 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7822 switch (level) { 7823 case PermissionInfo.PROTECTION_NORMAL: { 7824 // For all apps normal permissions are install time ones. 7825 grant = GRANT_INSTALL; 7826 } break; 7827 7828 case PermissionInfo.PROTECTION_DANGEROUS: { 7829 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7830 // For legacy apps dangerous permissions are install time ones. 7831 grant = GRANT_INSTALL_LEGACY; 7832 } else if (origPermissions.hasInstallPermission(bp.name)) { 7833 // For legacy apps that became modern, install becomes runtime. 7834 grant = GRANT_UPGRADE; 7835 } else { 7836 // For modern apps keep runtime permissions unchanged. 7837 grant = GRANT_RUNTIME; 7838 } 7839 } break; 7840 7841 case PermissionInfo.PROTECTION_SIGNATURE: { 7842 // For all apps signature permissions are install time ones. 7843 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7844 if (allowedSig) { 7845 grant = GRANT_INSTALL; 7846 } 7847 } break; 7848 } 7849 7850 if (DEBUG_INSTALL) { 7851 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7852 } 7853 7854 if (grant != GRANT_DENIED) { 7855 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7856 // If this is an existing, non-system package, then 7857 // we can't add any new permissions to it. 7858 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7859 // Except... if this is a permission that was added 7860 // to the platform (note: need to only do this when 7861 // updating the platform). 7862 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7863 grant = GRANT_DENIED; 7864 } 7865 } 7866 } 7867 7868 switch (grant) { 7869 case GRANT_INSTALL: { 7870 // Revoke this as runtime permission to handle the case of 7871 // a runtime permission being downgraded to an install one. 7872 for (int userId : UserManagerService.getInstance().getUserIds()) { 7873 if (origPermissions.getRuntimePermissionState( 7874 bp.name, userId) != null) { 7875 // Revoke the runtime permission and clear the flags. 7876 origPermissions.revokeRuntimePermission(bp, userId); 7877 origPermissions.updatePermissionFlags(bp, userId, 7878 PackageManager.MASK_PERMISSION_FLAGS, 0); 7879 // If we revoked a permission permission, we have to write. 7880 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7881 changedRuntimePermissionUserIds, userId); 7882 } 7883 } 7884 // Grant an install permission. 7885 if (permissionsState.grantInstallPermission(bp) != 7886 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7887 changedInstallPermission = true; 7888 } 7889 } break; 7890 7891 case GRANT_INSTALL_LEGACY: { 7892 // Grant an install permission. 7893 if (permissionsState.grantInstallPermission(bp) != 7894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7895 changedInstallPermission = true; 7896 } 7897 } break; 7898 7899 case GRANT_RUNTIME: { 7900 // Grant previously granted runtime permissions. 7901 for (int userId : UserManagerService.getInstance().getUserIds()) { 7902 PermissionState permissionState = origPermissions 7903 .getRuntimePermissionState(bp.name, userId); 7904 final int flags = permissionState != null 7905 ? permissionState.getFlags() : 0; 7906 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7907 if (permissionsState.grantRuntimePermission(bp, userId) == 7908 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7909 // If we cannot put the permission as it was, we have to write. 7910 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7911 changedRuntimePermissionUserIds, userId); 7912 } 7913 } 7914 // Propagate the permission flags. 7915 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 7916 } 7917 } break; 7918 7919 case GRANT_UPGRADE: { 7920 // Grant runtime permissions for a previously held install permission. 7921 PermissionState permissionState = origPermissions 7922 .getInstallPermissionState(bp.name); 7923 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7924 7925 if (origPermissions.revokeInstallPermission(bp) 7926 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 7927 // We will be transferring the permission flags, so clear them. 7928 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7929 PackageManager.MASK_PERMISSION_FLAGS, 0); 7930 changedInstallPermission = true; 7931 } 7932 7933 // If the permission is not to be promoted to runtime we ignore it and 7934 // also its other flags as they are not applicable to install permissions. 7935 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7936 for (int userId : currentUserIds) { 7937 if (permissionsState.grantRuntimePermission(bp, userId) != 7938 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7939 // Transfer the permission flags. 7940 permissionsState.updatePermissionFlags(bp, userId, 7941 flags, flags); 7942 // If we granted the permission, we have to write. 7943 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7944 changedRuntimePermissionUserIds, userId); 7945 } 7946 } 7947 } 7948 } break; 7949 7950 default: { 7951 if (packageOfInterest == null 7952 || packageOfInterest.equals(pkg.packageName)) { 7953 Slog.w(TAG, "Not granting permission " + perm 7954 + " to package " + pkg.packageName 7955 + " because it was previously installed without"); 7956 } 7957 } break; 7958 } 7959 } else { 7960 if (permissionsState.revokeInstallPermission(bp) != 7961 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7962 // Also drop the permission flags. 7963 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7964 PackageManager.MASK_PERMISSION_FLAGS, 0); 7965 changedInstallPermission = true; 7966 Slog.i(TAG, "Un-granting permission " + perm 7967 + " from package " + pkg.packageName 7968 + " (protectionLevel=" + bp.protectionLevel 7969 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7970 + ")"); 7971 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7972 // Don't print warning for app op permissions, since it is fine for them 7973 // not to be granted, there is a UI for the user to decide. 7974 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7975 Slog.w(TAG, "Not granting permission " + perm 7976 + " to package " + pkg.packageName 7977 + " (protectionLevel=" + bp.protectionLevel 7978 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7979 + ")"); 7980 } 7981 } 7982 } 7983 } 7984 7985 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7986 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7987 // This is the first that we have heard about this package, so the 7988 // permissions we have now selected are fixed until explicitly 7989 // changed. 7990 ps.installPermissionsFixed = true; 7991 } 7992 7993 // Persist the runtime permissions state for users with changes. 7994 for (int userId : changedRuntimePermissionUserIds) { 7995 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 7996 } 7997 } 7998 7999 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8000 boolean allowed = false; 8001 final int NP = PackageParser.NEW_PERMISSIONS.length; 8002 for (int ip=0; ip<NP; ip++) { 8003 final PackageParser.NewPermissionInfo npi 8004 = PackageParser.NEW_PERMISSIONS[ip]; 8005 if (npi.name.equals(perm) 8006 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8007 allowed = true; 8008 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8009 + pkg.packageName); 8010 break; 8011 } 8012 } 8013 return allowed; 8014 } 8015 8016 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8017 BasePermission bp, PermissionsState origPermissions) { 8018 boolean allowed; 8019 allowed = (compareSignatures( 8020 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8021 == PackageManager.SIGNATURE_MATCH) 8022 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8023 == PackageManager.SIGNATURE_MATCH); 8024 if (!allowed && (bp.protectionLevel 8025 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8026 if (isSystemApp(pkg)) { 8027 // For updated system applications, a system permission 8028 // is granted only if it had been defined by the original application. 8029 if (pkg.isUpdatedSystemApp()) { 8030 final PackageSetting sysPs = mSettings 8031 .getDisabledSystemPkgLPr(pkg.packageName); 8032 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8033 // If the original was granted this permission, we take 8034 // that grant decision as read and propagate it to the 8035 // update. 8036 if (sysPs.isPrivileged()) { 8037 allowed = true; 8038 } 8039 } else { 8040 // The system apk may have been updated with an older 8041 // version of the one on the data partition, but which 8042 // granted a new system permission that it didn't have 8043 // before. In this case we do want to allow the app to 8044 // now get the new permission if the ancestral apk is 8045 // privileged to get it. 8046 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8047 for (int j=0; 8048 j<sysPs.pkg.requestedPermissions.size(); j++) { 8049 if (perm.equals( 8050 sysPs.pkg.requestedPermissions.get(j))) { 8051 allowed = true; 8052 break; 8053 } 8054 } 8055 } 8056 } 8057 } else { 8058 allowed = isPrivilegedApp(pkg); 8059 } 8060 } 8061 } 8062 if (!allowed && (bp.protectionLevel 8063 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8064 // For development permissions, a development permission 8065 // is granted only if it was already granted. 8066 allowed = origPermissions.hasInstallPermission(perm); 8067 } 8068 return allowed; 8069 } 8070 8071 final class ActivityIntentResolver 8072 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8073 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8074 boolean defaultOnly, int userId) { 8075 if (!sUserManager.exists(userId)) return null; 8076 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8077 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8078 } 8079 8080 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8081 int userId) { 8082 if (!sUserManager.exists(userId)) return null; 8083 mFlags = flags; 8084 return super.queryIntent(intent, resolvedType, 8085 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8086 } 8087 8088 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8089 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8090 if (!sUserManager.exists(userId)) return null; 8091 if (packageActivities == null) { 8092 return null; 8093 } 8094 mFlags = flags; 8095 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8096 final int N = packageActivities.size(); 8097 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8098 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8099 8100 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8101 for (int i = 0; i < N; ++i) { 8102 intentFilters = packageActivities.get(i).intents; 8103 if (intentFilters != null && intentFilters.size() > 0) { 8104 PackageParser.ActivityIntentInfo[] array = 8105 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8106 intentFilters.toArray(array); 8107 listCut.add(array); 8108 } 8109 } 8110 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8111 } 8112 8113 public final void addActivity(PackageParser.Activity a, String type) { 8114 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8115 mActivities.put(a.getComponentName(), a); 8116 if (DEBUG_SHOW_INFO) 8117 Log.v( 8118 TAG, " " + type + " " + 8119 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8120 if (DEBUG_SHOW_INFO) 8121 Log.v(TAG, " Class=" + a.info.name); 8122 final int NI = a.intents.size(); 8123 for (int j=0; j<NI; j++) { 8124 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8125 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8126 intent.setPriority(0); 8127 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8128 + a.className + " with priority > 0, forcing to 0"); 8129 } 8130 if (DEBUG_SHOW_INFO) { 8131 Log.v(TAG, " IntentFilter:"); 8132 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8133 } 8134 if (!intent.debugCheck()) { 8135 Log.w(TAG, "==> For Activity " + a.info.name); 8136 } 8137 addFilter(intent); 8138 } 8139 } 8140 8141 public final void removeActivity(PackageParser.Activity a, String type) { 8142 mActivities.remove(a.getComponentName()); 8143 if (DEBUG_SHOW_INFO) { 8144 Log.v(TAG, " " + type + " " 8145 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8146 : a.info.name) + ":"); 8147 Log.v(TAG, " Class=" + a.info.name); 8148 } 8149 final int NI = a.intents.size(); 8150 for (int j=0; j<NI; j++) { 8151 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8152 if (DEBUG_SHOW_INFO) { 8153 Log.v(TAG, " IntentFilter:"); 8154 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8155 } 8156 removeFilter(intent); 8157 } 8158 } 8159 8160 @Override 8161 protected boolean allowFilterResult( 8162 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8163 ActivityInfo filterAi = filter.activity.info; 8164 for (int i=dest.size()-1; i>=0; i--) { 8165 ActivityInfo destAi = dest.get(i).activityInfo; 8166 if (destAi.name == filterAi.name 8167 && destAi.packageName == filterAi.packageName) { 8168 return false; 8169 } 8170 } 8171 return true; 8172 } 8173 8174 @Override 8175 protected ActivityIntentInfo[] newArray(int size) { 8176 return new ActivityIntentInfo[size]; 8177 } 8178 8179 @Override 8180 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8181 if (!sUserManager.exists(userId)) return true; 8182 PackageParser.Package p = filter.activity.owner; 8183 if (p != null) { 8184 PackageSetting ps = (PackageSetting)p.mExtras; 8185 if (ps != null) { 8186 // System apps are never considered stopped for purposes of 8187 // filtering, because there may be no way for the user to 8188 // actually re-launch them. 8189 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8190 && ps.getStopped(userId); 8191 } 8192 } 8193 return false; 8194 } 8195 8196 @Override 8197 protected boolean isPackageForFilter(String packageName, 8198 PackageParser.ActivityIntentInfo info) { 8199 return packageName.equals(info.activity.owner.packageName); 8200 } 8201 8202 @Override 8203 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8204 int match, int userId) { 8205 if (!sUserManager.exists(userId)) return null; 8206 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8207 return null; 8208 } 8209 final PackageParser.Activity activity = info.activity; 8210 if (mSafeMode && (activity.info.applicationInfo.flags 8211 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8212 return null; 8213 } 8214 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8215 if (ps == null) { 8216 return null; 8217 } 8218 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8219 ps.readUserState(userId), userId); 8220 if (ai == null) { 8221 return null; 8222 } 8223 final ResolveInfo res = new ResolveInfo(); 8224 res.activityInfo = ai; 8225 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8226 res.filter = info; 8227 } 8228 if (info != null) { 8229 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8230 } 8231 res.priority = info.getPriority(); 8232 res.preferredOrder = activity.owner.mPreferredOrder; 8233 //System.out.println("Result: " + res.activityInfo.className + 8234 // " = " + res.priority); 8235 res.match = match; 8236 res.isDefault = info.hasDefault; 8237 res.labelRes = info.labelRes; 8238 res.nonLocalizedLabel = info.nonLocalizedLabel; 8239 if (userNeedsBadging(userId)) { 8240 res.noResourceId = true; 8241 } else { 8242 res.icon = info.icon; 8243 } 8244 res.iconResourceId = info.icon; 8245 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8246 return res; 8247 } 8248 8249 @Override 8250 protected void sortResults(List<ResolveInfo> results) { 8251 Collections.sort(results, mResolvePrioritySorter); 8252 } 8253 8254 @Override 8255 protected void dumpFilter(PrintWriter out, String prefix, 8256 PackageParser.ActivityIntentInfo filter) { 8257 out.print(prefix); out.print( 8258 Integer.toHexString(System.identityHashCode(filter.activity))); 8259 out.print(' '); 8260 filter.activity.printComponentShortName(out); 8261 out.print(" filter "); 8262 out.println(Integer.toHexString(System.identityHashCode(filter))); 8263 } 8264 8265 @Override 8266 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8267 return filter.activity; 8268 } 8269 8270 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8271 PackageParser.Activity activity = (PackageParser.Activity)label; 8272 out.print(prefix); out.print( 8273 Integer.toHexString(System.identityHashCode(activity))); 8274 out.print(' '); 8275 activity.printComponentShortName(out); 8276 if (count > 1) { 8277 out.print(" ("); out.print(count); out.print(" filters)"); 8278 } 8279 out.println(); 8280 } 8281 8282// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8283// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8284// final List<ResolveInfo> retList = Lists.newArrayList(); 8285// while (i.hasNext()) { 8286// final ResolveInfo resolveInfo = i.next(); 8287// if (isEnabledLP(resolveInfo.activityInfo)) { 8288// retList.add(resolveInfo); 8289// } 8290// } 8291// return retList; 8292// } 8293 8294 // Keys are String (activity class name), values are Activity. 8295 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8296 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8297 private int mFlags; 8298 } 8299 8300 private final class ServiceIntentResolver 8301 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8302 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8303 boolean defaultOnly, int userId) { 8304 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8305 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8306 } 8307 8308 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8309 int userId) { 8310 if (!sUserManager.exists(userId)) return null; 8311 mFlags = flags; 8312 return super.queryIntent(intent, resolvedType, 8313 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8314 } 8315 8316 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8317 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8318 if (!sUserManager.exists(userId)) return null; 8319 if (packageServices == null) { 8320 return null; 8321 } 8322 mFlags = flags; 8323 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8324 final int N = packageServices.size(); 8325 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8326 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8327 8328 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8329 for (int i = 0; i < N; ++i) { 8330 intentFilters = packageServices.get(i).intents; 8331 if (intentFilters != null && intentFilters.size() > 0) { 8332 PackageParser.ServiceIntentInfo[] array = 8333 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8334 intentFilters.toArray(array); 8335 listCut.add(array); 8336 } 8337 } 8338 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8339 } 8340 8341 public final void addService(PackageParser.Service s) { 8342 mServices.put(s.getComponentName(), s); 8343 if (DEBUG_SHOW_INFO) { 8344 Log.v(TAG, " " 8345 + (s.info.nonLocalizedLabel != null 8346 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8347 Log.v(TAG, " Class=" + s.info.name); 8348 } 8349 final int NI = s.intents.size(); 8350 int j; 8351 for (j=0; j<NI; j++) { 8352 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8353 if (DEBUG_SHOW_INFO) { 8354 Log.v(TAG, " IntentFilter:"); 8355 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8356 } 8357 if (!intent.debugCheck()) { 8358 Log.w(TAG, "==> For Service " + s.info.name); 8359 } 8360 addFilter(intent); 8361 } 8362 } 8363 8364 public final void removeService(PackageParser.Service s) { 8365 mServices.remove(s.getComponentName()); 8366 if (DEBUG_SHOW_INFO) { 8367 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8368 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8369 Log.v(TAG, " Class=" + s.info.name); 8370 } 8371 final int NI = s.intents.size(); 8372 int j; 8373 for (j=0; j<NI; j++) { 8374 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8375 if (DEBUG_SHOW_INFO) { 8376 Log.v(TAG, " IntentFilter:"); 8377 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8378 } 8379 removeFilter(intent); 8380 } 8381 } 8382 8383 @Override 8384 protected boolean allowFilterResult( 8385 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8386 ServiceInfo filterSi = filter.service.info; 8387 for (int i=dest.size()-1; i>=0; i--) { 8388 ServiceInfo destAi = dest.get(i).serviceInfo; 8389 if (destAi.name == filterSi.name 8390 && destAi.packageName == filterSi.packageName) { 8391 return false; 8392 } 8393 } 8394 return true; 8395 } 8396 8397 @Override 8398 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8399 return new PackageParser.ServiceIntentInfo[size]; 8400 } 8401 8402 @Override 8403 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8404 if (!sUserManager.exists(userId)) return true; 8405 PackageParser.Package p = filter.service.owner; 8406 if (p != null) { 8407 PackageSetting ps = (PackageSetting)p.mExtras; 8408 if (ps != null) { 8409 // System apps are never considered stopped for purposes of 8410 // filtering, because there may be no way for the user to 8411 // actually re-launch them. 8412 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8413 && ps.getStopped(userId); 8414 } 8415 } 8416 return false; 8417 } 8418 8419 @Override 8420 protected boolean isPackageForFilter(String packageName, 8421 PackageParser.ServiceIntentInfo info) { 8422 return packageName.equals(info.service.owner.packageName); 8423 } 8424 8425 @Override 8426 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8427 int match, int userId) { 8428 if (!sUserManager.exists(userId)) return null; 8429 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8430 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8431 return null; 8432 } 8433 final PackageParser.Service service = info.service; 8434 if (mSafeMode && (service.info.applicationInfo.flags 8435 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8436 return null; 8437 } 8438 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8439 if (ps == null) { 8440 return null; 8441 } 8442 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8443 ps.readUserState(userId), userId); 8444 if (si == null) { 8445 return null; 8446 } 8447 final ResolveInfo res = new ResolveInfo(); 8448 res.serviceInfo = si; 8449 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8450 res.filter = filter; 8451 } 8452 res.priority = info.getPriority(); 8453 res.preferredOrder = service.owner.mPreferredOrder; 8454 res.match = match; 8455 res.isDefault = info.hasDefault; 8456 res.labelRes = info.labelRes; 8457 res.nonLocalizedLabel = info.nonLocalizedLabel; 8458 res.icon = info.icon; 8459 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8460 return res; 8461 } 8462 8463 @Override 8464 protected void sortResults(List<ResolveInfo> results) { 8465 Collections.sort(results, mResolvePrioritySorter); 8466 } 8467 8468 @Override 8469 protected void dumpFilter(PrintWriter out, String prefix, 8470 PackageParser.ServiceIntentInfo filter) { 8471 out.print(prefix); out.print( 8472 Integer.toHexString(System.identityHashCode(filter.service))); 8473 out.print(' '); 8474 filter.service.printComponentShortName(out); 8475 out.print(" filter "); 8476 out.println(Integer.toHexString(System.identityHashCode(filter))); 8477 } 8478 8479 @Override 8480 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8481 return filter.service; 8482 } 8483 8484 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8485 PackageParser.Service service = (PackageParser.Service)label; 8486 out.print(prefix); out.print( 8487 Integer.toHexString(System.identityHashCode(service))); 8488 out.print(' '); 8489 service.printComponentShortName(out); 8490 if (count > 1) { 8491 out.print(" ("); out.print(count); out.print(" filters)"); 8492 } 8493 out.println(); 8494 } 8495 8496// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8497// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8498// final List<ResolveInfo> retList = Lists.newArrayList(); 8499// while (i.hasNext()) { 8500// final ResolveInfo resolveInfo = (ResolveInfo) i; 8501// if (isEnabledLP(resolveInfo.serviceInfo)) { 8502// retList.add(resolveInfo); 8503// } 8504// } 8505// return retList; 8506// } 8507 8508 // Keys are String (activity class name), values are Activity. 8509 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8510 = new ArrayMap<ComponentName, PackageParser.Service>(); 8511 private int mFlags; 8512 }; 8513 8514 private final class ProviderIntentResolver 8515 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8517 boolean defaultOnly, int userId) { 8518 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8519 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8520 } 8521 8522 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8523 int userId) { 8524 if (!sUserManager.exists(userId)) 8525 return null; 8526 mFlags = flags; 8527 return super.queryIntent(intent, resolvedType, 8528 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8529 } 8530 8531 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8532 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8533 if (!sUserManager.exists(userId)) 8534 return null; 8535 if (packageProviders == null) { 8536 return null; 8537 } 8538 mFlags = flags; 8539 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8540 final int N = packageProviders.size(); 8541 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8542 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8543 8544 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8545 for (int i = 0; i < N; ++i) { 8546 intentFilters = packageProviders.get(i).intents; 8547 if (intentFilters != null && intentFilters.size() > 0) { 8548 PackageParser.ProviderIntentInfo[] array = 8549 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8550 intentFilters.toArray(array); 8551 listCut.add(array); 8552 } 8553 } 8554 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8555 } 8556 8557 public final void addProvider(PackageParser.Provider p) { 8558 if (mProviders.containsKey(p.getComponentName())) { 8559 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8560 return; 8561 } 8562 8563 mProviders.put(p.getComponentName(), p); 8564 if (DEBUG_SHOW_INFO) { 8565 Log.v(TAG, " " 8566 + (p.info.nonLocalizedLabel != null 8567 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8568 Log.v(TAG, " Class=" + p.info.name); 8569 } 8570 final int NI = p.intents.size(); 8571 int j; 8572 for (j = 0; j < NI; j++) { 8573 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8574 if (DEBUG_SHOW_INFO) { 8575 Log.v(TAG, " IntentFilter:"); 8576 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8577 } 8578 if (!intent.debugCheck()) { 8579 Log.w(TAG, "==> For Provider " + p.info.name); 8580 } 8581 addFilter(intent); 8582 } 8583 } 8584 8585 public final void removeProvider(PackageParser.Provider p) { 8586 mProviders.remove(p.getComponentName()); 8587 if (DEBUG_SHOW_INFO) { 8588 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8589 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8590 Log.v(TAG, " Class=" + p.info.name); 8591 } 8592 final int NI = p.intents.size(); 8593 int j; 8594 for (j = 0; j < NI; j++) { 8595 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8596 if (DEBUG_SHOW_INFO) { 8597 Log.v(TAG, " IntentFilter:"); 8598 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8599 } 8600 removeFilter(intent); 8601 } 8602 } 8603 8604 @Override 8605 protected boolean allowFilterResult( 8606 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8607 ProviderInfo filterPi = filter.provider.info; 8608 for (int i = dest.size() - 1; i >= 0; i--) { 8609 ProviderInfo destPi = dest.get(i).providerInfo; 8610 if (destPi.name == filterPi.name 8611 && destPi.packageName == filterPi.packageName) { 8612 return false; 8613 } 8614 } 8615 return true; 8616 } 8617 8618 @Override 8619 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8620 return new PackageParser.ProviderIntentInfo[size]; 8621 } 8622 8623 @Override 8624 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8625 if (!sUserManager.exists(userId)) 8626 return true; 8627 PackageParser.Package p = filter.provider.owner; 8628 if (p != null) { 8629 PackageSetting ps = (PackageSetting) p.mExtras; 8630 if (ps != null) { 8631 // System apps are never considered stopped for purposes of 8632 // filtering, because there may be no way for the user to 8633 // actually re-launch them. 8634 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8635 && ps.getStopped(userId); 8636 } 8637 } 8638 return false; 8639 } 8640 8641 @Override 8642 protected boolean isPackageForFilter(String packageName, 8643 PackageParser.ProviderIntentInfo info) { 8644 return packageName.equals(info.provider.owner.packageName); 8645 } 8646 8647 @Override 8648 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8649 int match, int userId) { 8650 if (!sUserManager.exists(userId)) 8651 return null; 8652 final PackageParser.ProviderIntentInfo info = filter; 8653 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8654 return null; 8655 } 8656 final PackageParser.Provider provider = info.provider; 8657 if (mSafeMode && (provider.info.applicationInfo.flags 8658 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8659 return null; 8660 } 8661 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8662 if (ps == null) { 8663 return null; 8664 } 8665 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8666 ps.readUserState(userId), userId); 8667 if (pi == null) { 8668 return null; 8669 } 8670 final ResolveInfo res = new ResolveInfo(); 8671 res.providerInfo = pi; 8672 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8673 res.filter = filter; 8674 } 8675 res.priority = info.getPriority(); 8676 res.preferredOrder = provider.owner.mPreferredOrder; 8677 res.match = match; 8678 res.isDefault = info.hasDefault; 8679 res.labelRes = info.labelRes; 8680 res.nonLocalizedLabel = info.nonLocalizedLabel; 8681 res.icon = info.icon; 8682 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8683 return res; 8684 } 8685 8686 @Override 8687 protected void sortResults(List<ResolveInfo> results) { 8688 Collections.sort(results, mResolvePrioritySorter); 8689 } 8690 8691 @Override 8692 protected void dumpFilter(PrintWriter out, String prefix, 8693 PackageParser.ProviderIntentInfo filter) { 8694 out.print(prefix); 8695 out.print( 8696 Integer.toHexString(System.identityHashCode(filter.provider))); 8697 out.print(' '); 8698 filter.provider.printComponentShortName(out); 8699 out.print(" filter "); 8700 out.println(Integer.toHexString(System.identityHashCode(filter))); 8701 } 8702 8703 @Override 8704 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8705 return filter.provider; 8706 } 8707 8708 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8709 PackageParser.Provider provider = (PackageParser.Provider)label; 8710 out.print(prefix); out.print( 8711 Integer.toHexString(System.identityHashCode(provider))); 8712 out.print(' '); 8713 provider.printComponentShortName(out); 8714 if (count > 1) { 8715 out.print(" ("); out.print(count); out.print(" filters)"); 8716 } 8717 out.println(); 8718 } 8719 8720 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8721 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8722 private int mFlags; 8723 }; 8724 8725 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8726 new Comparator<ResolveInfo>() { 8727 public int compare(ResolveInfo r1, ResolveInfo r2) { 8728 int v1 = r1.priority; 8729 int v2 = r2.priority; 8730 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8731 if (v1 != v2) { 8732 return (v1 > v2) ? -1 : 1; 8733 } 8734 v1 = r1.preferredOrder; 8735 v2 = r2.preferredOrder; 8736 if (v1 != v2) { 8737 return (v1 > v2) ? -1 : 1; 8738 } 8739 if (r1.isDefault != r2.isDefault) { 8740 return r1.isDefault ? -1 : 1; 8741 } 8742 v1 = r1.match; 8743 v2 = r2.match; 8744 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8745 if (v1 != v2) { 8746 return (v1 > v2) ? -1 : 1; 8747 } 8748 if (r1.system != r2.system) { 8749 return r1.system ? -1 : 1; 8750 } 8751 return 0; 8752 } 8753 }; 8754 8755 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8756 new Comparator<ProviderInfo>() { 8757 public int compare(ProviderInfo p1, ProviderInfo p2) { 8758 final int v1 = p1.initOrder; 8759 final int v2 = p2.initOrder; 8760 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8761 } 8762 }; 8763 8764 final void sendPackageBroadcast(final String action, final String pkg, 8765 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8766 final int[] userIds) { 8767 mHandler.post(new Runnable() { 8768 @Override 8769 public void run() { 8770 try { 8771 final IActivityManager am = ActivityManagerNative.getDefault(); 8772 if (am == null) return; 8773 final int[] resolvedUserIds; 8774 if (userIds == null) { 8775 resolvedUserIds = am.getRunningUserIds(); 8776 } else { 8777 resolvedUserIds = userIds; 8778 } 8779 for (int id : resolvedUserIds) { 8780 final Intent intent = new Intent(action, 8781 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8782 if (extras != null) { 8783 intent.putExtras(extras); 8784 } 8785 if (targetPkg != null) { 8786 intent.setPackage(targetPkg); 8787 } 8788 // Modify the UID when posting to other users 8789 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8790 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8791 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8792 intent.putExtra(Intent.EXTRA_UID, uid); 8793 } 8794 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8795 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8796 if (DEBUG_BROADCASTS) { 8797 RuntimeException here = new RuntimeException("here"); 8798 here.fillInStackTrace(); 8799 Slog.d(TAG, "Sending to user " + id + ": " 8800 + intent.toShortString(false, true, false, false) 8801 + " " + intent.getExtras(), here); 8802 } 8803 am.broadcastIntent(null, intent, null, finishedReceiver, 8804 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8805 null, finishedReceiver != null, false, id); 8806 } 8807 } catch (RemoteException ex) { 8808 } 8809 } 8810 }); 8811 } 8812 8813 /** 8814 * Check if the external storage media is available. This is true if there 8815 * is a mounted external storage medium or if the external storage is 8816 * emulated. 8817 */ 8818 private boolean isExternalMediaAvailable() { 8819 return mMediaMounted || Environment.isExternalStorageEmulated(); 8820 } 8821 8822 @Override 8823 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8824 // writer 8825 synchronized (mPackages) { 8826 if (!isExternalMediaAvailable()) { 8827 // If the external storage is no longer mounted at this point, 8828 // the caller may not have been able to delete all of this 8829 // packages files and can not delete any more. Bail. 8830 return null; 8831 } 8832 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8833 if (lastPackage != null) { 8834 pkgs.remove(lastPackage); 8835 } 8836 if (pkgs.size() > 0) { 8837 return pkgs.get(0); 8838 } 8839 } 8840 return null; 8841 } 8842 8843 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8844 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8845 userId, andCode ? 1 : 0, packageName); 8846 if (mSystemReady) { 8847 msg.sendToTarget(); 8848 } else { 8849 if (mPostSystemReadyMessages == null) { 8850 mPostSystemReadyMessages = new ArrayList<>(); 8851 } 8852 mPostSystemReadyMessages.add(msg); 8853 } 8854 } 8855 8856 void startCleaningPackages() { 8857 // reader 8858 synchronized (mPackages) { 8859 if (!isExternalMediaAvailable()) { 8860 return; 8861 } 8862 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8863 return; 8864 } 8865 } 8866 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8867 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8868 IActivityManager am = ActivityManagerNative.getDefault(); 8869 if (am != null) { 8870 try { 8871 am.startService(null, intent, null, UserHandle.USER_OWNER); 8872 } catch (RemoteException e) { 8873 } 8874 } 8875 } 8876 8877 @Override 8878 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8879 int installFlags, String installerPackageName, VerificationParams verificationParams, 8880 String packageAbiOverride) { 8881 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8882 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8883 } 8884 8885 @Override 8886 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8887 int installFlags, String installerPackageName, VerificationParams verificationParams, 8888 String packageAbiOverride, int userId) { 8889 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8890 8891 final int callingUid = Binder.getCallingUid(); 8892 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8893 8894 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8895 try { 8896 if (observer != null) { 8897 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8898 } 8899 } catch (RemoteException re) { 8900 } 8901 return; 8902 } 8903 8904 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8905 installFlags |= PackageManager.INSTALL_FROM_ADB; 8906 8907 } else { 8908 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8909 // about installerPackageName. 8910 8911 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8912 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8913 } 8914 8915 UserHandle user; 8916 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8917 user = UserHandle.ALL; 8918 } else { 8919 user = new UserHandle(userId); 8920 } 8921 8922 // Only system components can circumvent runtime permissions when installing. 8923 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8924 && mContext.checkCallingOrSelfPermission(Manifest.permission 8925 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8926 throw new SecurityException("You need the " 8927 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8928 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8929 } 8930 8931 verificationParams.setInstallerUid(callingUid); 8932 8933 final File originFile = new File(originPath); 8934 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8935 8936 final Message msg = mHandler.obtainMessage(INIT_COPY); 8937 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8938 null, verificationParams, user, packageAbiOverride); 8939 mHandler.sendMessage(msg); 8940 } 8941 8942 void installStage(String packageName, File stagedDir, String stagedCid, 8943 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8944 String installerPackageName, int installerUid, UserHandle user) { 8945 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8946 params.referrerUri, installerUid, null); 8947 8948 final OriginInfo origin; 8949 if (stagedDir != null) { 8950 origin = OriginInfo.fromStagedFile(stagedDir); 8951 } else { 8952 origin = OriginInfo.fromStagedContainer(stagedCid); 8953 } 8954 8955 final Message msg = mHandler.obtainMessage(INIT_COPY); 8956 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8957 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8958 mHandler.sendMessage(msg); 8959 } 8960 8961 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8962 Bundle extras = new Bundle(1); 8963 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8964 8965 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8966 packageName, extras, null, null, new int[] {userId}); 8967 try { 8968 IActivityManager am = ActivityManagerNative.getDefault(); 8969 final boolean isSystem = 8970 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8971 if (isSystem && am.isUserRunning(userId, false)) { 8972 // The just-installed/enabled app is bundled on the system, so presumed 8973 // to be able to run automatically without needing an explicit launch. 8974 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8975 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8976 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8977 .setPackage(packageName); 8978 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8979 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8980 } 8981 } catch (RemoteException e) { 8982 // shouldn't happen 8983 Slog.w(TAG, "Unable to bootstrap installed package", e); 8984 } 8985 } 8986 8987 @Override 8988 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8989 int userId) { 8990 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8991 PackageSetting pkgSetting; 8992 final int uid = Binder.getCallingUid(); 8993 enforceCrossUserPermission(uid, userId, true, true, 8994 "setApplicationHiddenSetting for user " + userId); 8995 8996 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8997 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8998 return false; 8999 } 9000 9001 long callingId = Binder.clearCallingIdentity(); 9002 try { 9003 boolean sendAdded = false; 9004 boolean sendRemoved = false; 9005 // writer 9006 synchronized (mPackages) { 9007 pkgSetting = mSettings.mPackages.get(packageName); 9008 if (pkgSetting == null) { 9009 return false; 9010 } 9011 if (pkgSetting.getHidden(userId) != hidden) { 9012 pkgSetting.setHidden(hidden, userId); 9013 mSettings.writePackageRestrictionsLPr(userId); 9014 if (hidden) { 9015 sendRemoved = true; 9016 } else { 9017 sendAdded = true; 9018 } 9019 } 9020 } 9021 if (sendAdded) { 9022 sendPackageAddedForUser(packageName, pkgSetting, userId); 9023 return true; 9024 } 9025 if (sendRemoved) { 9026 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9027 "hiding pkg"); 9028 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9029 } 9030 } finally { 9031 Binder.restoreCallingIdentity(callingId); 9032 } 9033 return false; 9034 } 9035 9036 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9037 int userId) { 9038 final PackageRemovedInfo info = new PackageRemovedInfo(); 9039 info.removedPackage = packageName; 9040 info.removedUsers = new int[] {userId}; 9041 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9042 info.sendBroadcast(false, false, false); 9043 } 9044 9045 /** 9046 * Returns true if application is not found or there was an error. Otherwise it returns 9047 * the hidden state of the package for the given user. 9048 */ 9049 @Override 9050 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9052 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9053 false, "getApplicationHidden for user " + userId); 9054 PackageSetting pkgSetting; 9055 long callingId = Binder.clearCallingIdentity(); 9056 try { 9057 // writer 9058 synchronized (mPackages) { 9059 pkgSetting = mSettings.mPackages.get(packageName); 9060 if (pkgSetting == null) { 9061 return true; 9062 } 9063 return pkgSetting.getHidden(userId); 9064 } 9065 } finally { 9066 Binder.restoreCallingIdentity(callingId); 9067 } 9068 } 9069 9070 /** 9071 * @hide 9072 */ 9073 @Override 9074 public int installExistingPackageAsUser(String packageName, int userId) { 9075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9076 null); 9077 PackageSetting pkgSetting; 9078 final int uid = Binder.getCallingUid(); 9079 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9080 + userId); 9081 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9082 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9083 } 9084 9085 long callingId = Binder.clearCallingIdentity(); 9086 try { 9087 boolean sendAdded = false; 9088 9089 // writer 9090 synchronized (mPackages) { 9091 pkgSetting = mSettings.mPackages.get(packageName); 9092 if (pkgSetting == null) { 9093 return PackageManager.INSTALL_FAILED_INVALID_URI; 9094 } 9095 if (!pkgSetting.getInstalled(userId)) { 9096 pkgSetting.setInstalled(true, userId); 9097 pkgSetting.setHidden(false, userId); 9098 mSettings.writePackageRestrictionsLPr(userId); 9099 sendAdded = true; 9100 } 9101 } 9102 9103 if (sendAdded) { 9104 sendPackageAddedForUser(packageName, pkgSetting, userId); 9105 } 9106 } finally { 9107 Binder.restoreCallingIdentity(callingId); 9108 } 9109 9110 return PackageManager.INSTALL_SUCCEEDED; 9111 } 9112 9113 boolean isUserRestricted(int userId, String restrictionKey) { 9114 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9115 if (restrictions.getBoolean(restrictionKey, false)) { 9116 Log.w(TAG, "User is restricted: " + restrictionKey); 9117 return true; 9118 } 9119 return false; 9120 } 9121 9122 @Override 9123 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9124 mContext.enforceCallingOrSelfPermission( 9125 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9126 "Only package verification agents can verify applications"); 9127 9128 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9129 final PackageVerificationResponse response = new PackageVerificationResponse( 9130 verificationCode, Binder.getCallingUid()); 9131 msg.arg1 = id; 9132 msg.obj = response; 9133 mHandler.sendMessage(msg); 9134 } 9135 9136 @Override 9137 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9138 long millisecondsToDelay) { 9139 mContext.enforceCallingOrSelfPermission( 9140 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9141 "Only package verification agents can extend verification timeouts"); 9142 9143 final PackageVerificationState state = mPendingVerification.get(id); 9144 final PackageVerificationResponse response = new PackageVerificationResponse( 9145 verificationCodeAtTimeout, Binder.getCallingUid()); 9146 9147 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9148 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9149 } 9150 if (millisecondsToDelay < 0) { 9151 millisecondsToDelay = 0; 9152 } 9153 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9154 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9155 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9156 } 9157 9158 if ((state != null) && !state.timeoutExtended()) { 9159 state.extendTimeout(); 9160 9161 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9162 msg.arg1 = id; 9163 msg.obj = response; 9164 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9165 } 9166 } 9167 9168 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9169 int verificationCode, UserHandle user) { 9170 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9171 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9172 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9173 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9174 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9175 9176 mContext.sendBroadcastAsUser(intent, user, 9177 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9178 } 9179 9180 private ComponentName matchComponentForVerifier(String packageName, 9181 List<ResolveInfo> receivers) { 9182 ActivityInfo targetReceiver = null; 9183 9184 final int NR = receivers.size(); 9185 for (int i = 0; i < NR; i++) { 9186 final ResolveInfo info = receivers.get(i); 9187 if (info.activityInfo == null) { 9188 continue; 9189 } 9190 9191 if (packageName.equals(info.activityInfo.packageName)) { 9192 targetReceiver = info.activityInfo; 9193 break; 9194 } 9195 } 9196 9197 if (targetReceiver == null) { 9198 return null; 9199 } 9200 9201 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9202 } 9203 9204 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9205 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9206 if (pkgInfo.verifiers.length == 0) { 9207 return null; 9208 } 9209 9210 final int N = pkgInfo.verifiers.length; 9211 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9212 for (int i = 0; i < N; i++) { 9213 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9214 9215 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9216 receivers); 9217 if (comp == null) { 9218 continue; 9219 } 9220 9221 final int verifierUid = getUidForVerifier(verifierInfo); 9222 if (verifierUid == -1) { 9223 continue; 9224 } 9225 9226 if (DEBUG_VERIFY) { 9227 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9228 + " with the correct signature"); 9229 } 9230 sufficientVerifiers.add(comp); 9231 verificationState.addSufficientVerifier(verifierUid); 9232 } 9233 9234 return sufficientVerifiers; 9235 } 9236 9237 private int getUidForVerifier(VerifierInfo verifierInfo) { 9238 synchronized (mPackages) { 9239 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9240 if (pkg == null) { 9241 return -1; 9242 } else if (pkg.mSignatures.length != 1) { 9243 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9244 + " has more than one signature; ignoring"); 9245 return -1; 9246 } 9247 9248 /* 9249 * If the public key of the package's signature does not match 9250 * our expected public key, then this is a different package and 9251 * we should skip. 9252 */ 9253 9254 final byte[] expectedPublicKey; 9255 try { 9256 final Signature verifierSig = pkg.mSignatures[0]; 9257 final PublicKey publicKey = verifierSig.getPublicKey(); 9258 expectedPublicKey = publicKey.getEncoded(); 9259 } catch (CertificateException e) { 9260 return -1; 9261 } 9262 9263 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9264 9265 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9266 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9267 + " does not have the expected public key; ignoring"); 9268 return -1; 9269 } 9270 9271 return pkg.applicationInfo.uid; 9272 } 9273 } 9274 9275 @Override 9276 public void finishPackageInstall(int token) { 9277 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9278 9279 if (DEBUG_INSTALL) { 9280 Slog.v(TAG, "BM finishing package install for " + token); 9281 } 9282 9283 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9284 mHandler.sendMessage(msg); 9285 } 9286 9287 /** 9288 * Get the verification agent timeout. 9289 * 9290 * @return verification timeout in milliseconds 9291 */ 9292 private long getVerificationTimeout() { 9293 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9294 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9295 DEFAULT_VERIFICATION_TIMEOUT); 9296 } 9297 9298 /** 9299 * Get the default verification agent response code. 9300 * 9301 * @return default verification response code 9302 */ 9303 private int getDefaultVerificationResponse() { 9304 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9305 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9306 DEFAULT_VERIFICATION_RESPONSE); 9307 } 9308 9309 /** 9310 * Check whether or not package verification has been enabled. 9311 * 9312 * @return true if verification should be performed 9313 */ 9314 private boolean isVerificationEnabled(int userId, int installFlags) { 9315 if (!DEFAULT_VERIFY_ENABLE) { 9316 return false; 9317 } 9318 9319 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9320 9321 // Check if installing from ADB 9322 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9323 // Do not run verification in a test harness environment 9324 if (ActivityManager.isRunningInTestHarness()) { 9325 return false; 9326 } 9327 if (ensureVerifyAppsEnabled) { 9328 return true; 9329 } 9330 // Check if the developer does not want package verification for ADB installs 9331 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9332 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9333 return false; 9334 } 9335 } 9336 9337 if (ensureVerifyAppsEnabled) { 9338 return true; 9339 } 9340 9341 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9342 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9343 } 9344 9345 @Override 9346 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9347 throws RemoteException { 9348 mContext.enforceCallingOrSelfPermission( 9349 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9350 "Only intentfilter verification agents can verify applications"); 9351 9352 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9353 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9354 Binder.getCallingUid(), verificationCode, failedDomains); 9355 msg.arg1 = id; 9356 msg.obj = response; 9357 mHandler.sendMessage(msg); 9358 } 9359 9360 @Override 9361 public int getIntentVerificationStatus(String packageName, int userId) { 9362 synchronized (mPackages) { 9363 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9364 } 9365 } 9366 9367 @Override 9368 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9369 boolean result = false; 9370 synchronized (mPackages) { 9371 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9372 } 9373 if (result) { 9374 scheduleWritePackageRestrictionsLocked(userId); 9375 } 9376 return result; 9377 } 9378 9379 @Override 9380 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9381 synchronized (mPackages) { 9382 return mSettings.getIntentFilterVerificationsLPr(packageName); 9383 } 9384 } 9385 9386 @Override 9387 public List<IntentFilter> getAllIntentFilters(String packageName) { 9388 if (TextUtils.isEmpty(packageName)) { 9389 return Collections.<IntentFilter>emptyList(); 9390 } 9391 synchronized (mPackages) { 9392 PackageParser.Package pkg = mPackages.get(packageName); 9393 if (pkg == null || pkg.activities == null) { 9394 return Collections.<IntentFilter>emptyList(); 9395 } 9396 final int count = pkg.activities.size(); 9397 ArrayList<IntentFilter> result = new ArrayList<>(); 9398 for (int n=0; n<count; n++) { 9399 PackageParser.Activity activity = pkg.activities.get(n); 9400 if (activity.intents != null || activity.intents.size() > 0) { 9401 result.addAll(activity.intents); 9402 } 9403 } 9404 return result; 9405 } 9406 } 9407 9408 @Override 9409 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9410 synchronized (mPackages) { 9411 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9412 if (packageName != null) { 9413 result |= updateIntentVerificationStatus(packageName, 9414 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9415 UserHandle.myUserId()); 9416 } 9417 return result; 9418 } 9419 } 9420 9421 @Override 9422 public String getDefaultBrowserPackageName(int userId) { 9423 synchronized (mPackages) { 9424 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9425 } 9426 } 9427 9428 /** 9429 * Get the "allow unknown sources" setting. 9430 * 9431 * @return the current "allow unknown sources" setting 9432 */ 9433 private int getUnknownSourcesSettings() { 9434 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9435 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9436 -1); 9437 } 9438 9439 @Override 9440 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9441 final int uid = Binder.getCallingUid(); 9442 // writer 9443 synchronized (mPackages) { 9444 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9445 if (targetPackageSetting == null) { 9446 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9447 } 9448 9449 PackageSetting installerPackageSetting; 9450 if (installerPackageName != null) { 9451 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9452 if (installerPackageSetting == null) { 9453 throw new IllegalArgumentException("Unknown installer package: " 9454 + installerPackageName); 9455 } 9456 } else { 9457 installerPackageSetting = null; 9458 } 9459 9460 Signature[] callerSignature; 9461 Object obj = mSettings.getUserIdLPr(uid); 9462 if (obj != null) { 9463 if (obj instanceof SharedUserSetting) { 9464 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9465 } else if (obj instanceof PackageSetting) { 9466 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9467 } else { 9468 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9469 } 9470 } else { 9471 throw new SecurityException("Unknown calling uid " + uid); 9472 } 9473 9474 // Verify: can't set installerPackageName to a package that is 9475 // not signed with the same cert as the caller. 9476 if (installerPackageSetting != null) { 9477 if (compareSignatures(callerSignature, 9478 installerPackageSetting.signatures.mSignatures) 9479 != PackageManager.SIGNATURE_MATCH) { 9480 throw new SecurityException( 9481 "Caller does not have same cert as new installer package " 9482 + installerPackageName); 9483 } 9484 } 9485 9486 // Verify: if target already has an installer package, it must 9487 // be signed with the same cert as the caller. 9488 if (targetPackageSetting.installerPackageName != null) { 9489 PackageSetting setting = mSettings.mPackages.get( 9490 targetPackageSetting.installerPackageName); 9491 // If the currently set package isn't valid, then it's always 9492 // okay to change it. 9493 if (setting != null) { 9494 if (compareSignatures(callerSignature, 9495 setting.signatures.mSignatures) 9496 != PackageManager.SIGNATURE_MATCH) { 9497 throw new SecurityException( 9498 "Caller does not have same cert as old installer package " 9499 + targetPackageSetting.installerPackageName); 9500 } 9501 } 9502 } 9503 9504 // Okay! 9505 targetPackageSetting.installerPackageName = installerPackageName; 9506 scheduleWriteSettingsLocked(); 9507 } 9508 } 9509 9510 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9511 // Queue up an async operation since the package installation may take a little while. 9512 mHandler.post(new Runnable() { 9513 public void run() { 9514 mHandler.removeCallbacks(this); 9515 // Result object to be returned 9516 PackageInstalledInfo res = new PackageInstalledInfo(); 9517 res.returnCode = currentStatus; 9518 res.uid = -1; 9519 res.pkg = null; 9520 res.removedInfo = new PackageRemovedInfo(); 9521 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9522 args.doPreInstall(res.returnCode); 9523 synchronized (mInstallLock) { 9524 installPackageLI(args, res); 9525 } 9526 args.doPostInstall(res.returnCode, res.uid); 9527 } 9528 9529 // A restore should be performed at this point if (a) the install 9530 // succeeded, (b) the operation is not an update, and (c) the new 9531 // package has not opted out of backup participation. 9532 final boolean update = res.removedInfo.removedPackage != null; 9533 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9534 boolean doRestore = !update 9535 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9536 9537 // Set up the post-install work request bookkeeping. This will be used 9538 // and cleaned up by the post-install event handling regardless of whether 9539 // there's a restore pass performed. Token values are >= 1. 9540 int token; 9541 if (mNextInstallToken < 0) mNextInstallToken = 1; 9542 token = mNextInstallToken++; 9543 9544 PostInstallData data = new PostInstallData(args, res); 9545 mRunningInstalls.put(token, data); 9546 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9547 9548 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9549 // Pass responsibility to the Backup Manager. It will perform a 9550 // restore if appropriate, then pass responsibility back to the 9551 // Package Manager to run the post-install observer callbacks 9552 // and broadcasts. 9553 IBackupManager bm = IBackupManager.Stub.asInterface( 9554 ServiceManager.getService(Context.BACKUP_SERVICE)); 9555 if (bm != null) { 9556 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9557 + " to BM for possible restore"); 9558 try { 9559 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9560 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9561 } else { 9562 doRestore = false; 9563 } 9564 } catch (RemoteException e) { 9565 // can't happen; the backup manager is local 9566 } catch (Exception e) { 9567 Slog.e(TAG, "Exception trying to enqueue restore", e); 9568 doRestore = false; 9569 } 9570 } else { 9571 Slog.e(TAG, "Backup Manager not found!"); 9572 doRestore = false; 9573 } 9574 } 9575 9576 if (!doRestore) { 9577 // No restore possible, or the Backup Manager was mysteriously not 9578 // available -- just fire the post-install work request directly. 9579 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9580 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9581 mHandler.sendMessage(msg); 9582 } 9583 } 9584 }); 9585 } 9586 9587 private abstract class HandlerParams { 9588 private static final int MAX_RETRIES = 4; 9589 9590 /** 9591 * Number of times startCopy() has been attempted and had a non-fatal 9592 * error. 9593 */ 9594 private int mRetries = 0; 9595 9596 /** User handle for the user requesting the information or installation. */ 9597 private final UserHandle mUser; 9598 9599 HandlerParams(UserHandle user) { 9600 mUser = user; 9601 } 9602 9603 UserHandle getUser() { 9604 return mUser; 9605 } 9606 9607 final boolean startCopy() { 9608 boolean res; 9609 try { 9610 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9611 9612 if (++mRetries > MAX_RETRIES) { 9613 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9614 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9615 handleServiceError(); 9616 return false; 9617 } else { 9618 handleStartCopy(); 9619 res = true; 9620 } 9621 } catch (RemoteException e) { 9622 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9623 mHandler.sendEmptyMessage(MCS_RECONNECT); 9624 res = false; 9625 } 9626 handleReturnCode(); 9627 return res; 9628 } 9629 9630 final void serviceError() { 9631 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9632 handleServiceError(); 9633 handleReturnCode(); 9634 } 9635 9636 abstract void handleStartCopy() throws RemoteException; 9637 abstract void handleServiceError(); 9638 abstract void handleReturnCode(); 9639 } 9640 9641 class MeasureParams extends HandlerParams { 9642 private final PackageStats mStats; 9643 private boolean mSuccess; 9644 9645 private final IPackageStatsObserver mObserver; 9646 9647 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9648 super(new UserHandle(stats.userHandle)); 9649 mObserver = observer; 9650 mStats = stats; 9651 } 9652 9653 @Override 9654 public String toString() { 9655 return "MeasureParams{" 9656 + Integer.toHexString(System.identityHashCode(this)) 9657 + " " + mStats.packageName + "}"; 9658 } 9659 9660 @Override 9661 void handleStartCopy() throws RemoteException { 9662 synchronized (mInstallLock) { 9663 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9664 } 9665 9666 if (mSuccess) { 9667 final boolean mounted; 9668 if (Environment.isExternalStorageEmulated()) { 9669 mounted = true; 9670 } else { 9671 final String status = Environment.getExternalStorageState(); 9672 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9673 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9674 } 9675 9676 if (mounted) { 9677 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9678 9679 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9680 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9681 9682 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9683 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9684 9685 // Always subtract cache size, since it's a subdirectory 9686 mStats.externalDataSize -= mStats.externalCacheSize; 9687 9688 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9689 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9690 9691 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9692 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9693 } 9694 } 9695 } 9696 9697 @Override 9698 void handleReturnCode() { 9699 if (mObserver != null) { 9700 try { 9701 mObserver.onGetStatsCompleted(mStats, mSuccess); 9702 } catch (RemoteException e) { 9703 Slog.i(TAG, "Observer no longer exists."); 9704 } 9705 } 9706 } 9707 9708 @Override 9709 void handleServiceError() { 9710 Slog.e(TAG, "Could not measure application " + mStats.packageName 9711 + " external storage"); 9712 } 9713 } 9714 9715 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9716 throws RemoteException { 9717 long result = 0; 9718 for (File path : paths) { 9719 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9720 } 9721 return result; 9722 } 9723 9724 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9725 for (File path : paths) { 9726 try { 9727 mcs.clearDirectory(path.getAbsolutePath()); 9728 } catch (RemoteException e) { 9729 } 9730 } 9731 } 9732 9733 static class OriginInfo { 9734 /** 9735 * Location where install is coming from, before it has been 9736 * copied/renamed into place. This could be a single monolithic APK 9737 * file, or a cluster directory. This location may be untrusted. 9738 */ 9739 final File file; 9740 final String cid; 9741 9742 /** 9743 * Flag indicating that {@link #file} or {@link #cid} has already been 9744 * staged, meaning downstream users don't need to defensively copy the 9745 * contents. 9746 */ 9747 final boolean staged; 9748 9749 /** 9750 * Flag indicating that {@link #file} or {@link #cid} is an already 9751 * installed app that is being moved. 9752 */ 9753 final boolean existing; 9754 9755 final String resolvedPath; 9756 final File resolvedFile; 9757 9758 static OriginInfo fromNothing() { 9759 return new OriginInfo(null, null, false, false); 9760 } 9761 9762 static OriginInfo fromUntrustedFile(File file) { 9763 return new OriginInfo(file, null, false, false); 9764 } 9765 9766 static OriginInfo fromExistingFile(File file) { 9767 return new OriginInfo(file, null, false, true); 9768 } 9769 9770 static OriginInfo fromStagedFile(File file) { 9771 return new OriginInfo(file, null, true, false); 9772 } 9773 9774 static OriginInfo fromStagedContainer(String cid) { 9775 return new OriginInfo(null, cid, true, false); 9776 } 9777 9778 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9779 this.file = file; 9780 this.cid = cid; 9781 this.staged = staged; 9782 this.existing = existing; 9783 9784 if (cid != null) { 9785 resolvedPath = PackageHelper.getSdDir(cid); 9786 resolvedFile = new File(resolvedPath); 9787 } else if (file != null) { 9788 resolvedPath = file.getAbsolutePath(); 9789 resolvedFile = file; 9790 } else { 9791 resolvedPath = null; 9792 resolvedFile = null; 9793 } 9794 } 9795 } 9796 9797 class MoveInfo { 9798 final int moveId; 9799 final String fromUuid; 9800 final String toUuid; 9801 final String packageName; 9802 final String dataAppName; 9803 final int appId; 9804 final String seinfo; 9805 9806 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9807 String dataAppName, int appId, String seinfo) { 9808 this.moveId = moveId; 9809 this.fromUuid = fromUuid; 9810 this.toUuid = toUuid; 9811 this.packageName = packageName; 9812 this.dataAppName = dataAppName; 9813 this.appId = appId; 9814 this.seinfo = seinfo; 9815 } 9816 } 9817 9818 class InstallParams extends HandlerParams { 9819 final OriginInfo origin; 9820 final MoveInfo move; 9821 final IPackageInstallObserver2 observer; 9822 int installFlags; 9823 final String installerPackageName; 9824 final String volumeUuid; 9825 final VerificationParams verificationParams; 9826 private InstallArgs mArgs; 9827 private int mRet; 9828 final String packageAbiOverride; 9829 9830 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9831 int installFlags, String installerPackageName, String volumeUuid, 9832 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9833 super(user); 9834 this.origin = origin; 9835 this.move = move; 9836 this.observer = observer; 9837 this.installFlags = installFlags; 9838 this.installerPackageName = installerPackageName; 9839 this.volumeUuid = volumeUuid; 9840 this.verificationParams = verificationParams; 9841 this.packageAbiOverride = packageAbiOverride; 9842 } 9843 9844 @Override 9845 public String toString() { 9846 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9847 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9848 } 9849 9850 public ManifestDigest getManifestDigest() { 9851 if (verificationParams == null) { 9852 return null; 9853 } 9854 return verificationParams.getManifestDigest(); 9855 } 9856 9857 private int installLocationPolicy(PackageInfoLite pkgLite) { 9858 String packageName = pkgLite.packageName; 9859 int installLocation = pkgLite.installLocation; 9860 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9861 // reader 9862 synchronized (mPackages) { 9863 PackageParser.Package pkg = mPackages.get(packageName); 9864 if (pkg != null) { 9865 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9866 // Check for downgrading. 9867 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9868 try { 9869 checkDowngrade(pkg, pkgLite); 9870 } catch (PackageManagerException e) { 9871 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9872 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9873 } 9874 } 9875 // Check for updated system application. 9876 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9877 if (onSd) { 9878 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9879 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9880 } 9881 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9882 } else { 9883 if (onSd) { 9884 // Install flag overrides everything. 9885 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9886 } 9887 // If current upgrade specifies particular preference 9888 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9889 // Application explicitly specified internal. 9890 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9891 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9892 // App explictly prefers external. Let policy decide 9893 } else { 9894 // Prefer previous location 9895 if (isExternal(pkg)) { 9896 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9897 } 9898 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9899 } 9900 } 9901 } else { 9902 // Invalid install. Return error code 9903 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9904 } 9905 } 9906 } 9907 // All the special cases have been taken care of. 9908 // Return result based on recommended install location. 9909 if (onSd) { 9910 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9911 } 9912 return pkgLite.recommendedInstallLocation; 9913 } 9914 9915 /* 9916 * Invoke remote method to get package information and install 9917 * location values. Override install location based on default 9918 * policy if needed and then create install arguments based 9919 * on the install location. 9920 */ 9921 public void handleStartCopy() throws RemoteException { 9922 int ret = PackageManager.INSTALL_SUCCEEDED; 9923 9924 // If we're already staged, we've firmly committed to an install location 9925 if (origin.staged) { 9926 if (origin.file != null) { 9927 installFlags |= PackageManager.INSTALL_INTERNAL; 9928 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9929 } else if (origin.cid != null) { 9930 installFlags |= PackageManager.INSTALL_EXTERNAL; 9931 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9932 } else { 9933 throw new IllegalStateException("Invalid stage location"); 9934 } 9935 } 9936 9937 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9938 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9939 9940 PackageInfoLite pkgLite = null; 9941 9942 if (onInt && onSd) { 9943 // Check if both bits are set. 9944 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9945 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9946 } else { 9947 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9948 packageAbiOverride); 9949 9950 /* 9951 * If we have too little free space, try to free cache 9952 * before giving up. 9953 */ 9954 if (!origin.staged && pkgLite.recommendedInstallLocation 9955 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9956 // TODO: focus freeing disk space on the target device 9957 final StorageManager storage = StorageManager.from(mContext); 9958 final long lowThreshold = storage.getStorageLowBytes( 9959 Environment.getDataDirectory()); 9960 9961 final long sizeBytes = mContainerService.calculateInstalledSize( 9962 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9963 9964 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9965 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9966 installFlags, packageAbiOverride); 9967 } 9968 9969 /* 9970 * The cache free must have deleted the file we 9971 * downloaded to install. 9972 * 9973 * TODO: fix the "freeCache" call to not delete 9974 * the file we care about. 9975 */ 9976 if (pkgLite.recommendedInstallLocation 9977 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9978 pkgLite.recommendedInstallLocation 9979 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9980 } 9981 } 9982 } 9983 9984 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9985 int loc = pkgLite.recommendedInstallLocation; 9986 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9987 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9988 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9989 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9990 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9991 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9992 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9993 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9994 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9995 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9996 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9997 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9998 } else { 9999 // Override with defaults if needed. 10000 loc = installLocationPolicy(pkgLite); 10001 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10002 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10003 } else if (!onSd && !onInt) { 10004 // Override install location with flags 10005 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10006 // Set the flag to install on external media. 10007 installFlags |= PackageManager.INSTALL_EXTERNAL; 10008 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10009 } else { 10010 // Make sure the flag for installing on external 10011 // media is unset 10012 installFlags |= PackageManager.INSTALL_INTERNAL; 10013 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10014 } 10015 } 10016 } 10017 } 10018 10019 final InstallArgs args = createInstallArgs(this); 10020 mArgs = args; 10021 10022 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10023 /* 10024 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10025 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10026 */ 10027 int userIdentifier = getUser().getIdentifier(); 10028 if (userIdentifier == UserHandle.USER_ALL 10029 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10030 userIdentifier = UserHandle.USER_OWNER; 10031 } 10032 10033 /* 10034 * Determine if we have any installed package verifiers. If we 10035 * do, then we'll defer to them to verify the packages. 10036 */ 10037 final int requiredUid = mRequiredVerifierPackage == null ? -1 10038 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10039 if (!origin.existing && requiredUid != -1 10040 && isVerificationEnabled(userIdentifier, installFlags)) { 10041 final Intent verification = new Intent( 10042 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10043 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10044 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10045 PACKAGE_MIME_TYPE); 10046 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10047 10048 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10049 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10050 0 /* TODO: Which userId? */); 10051 10052 if (DEBUG_VERIFY) { 10053 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10054 + verification.toString() + " with " + pkgLite.verifiers.length 10055 + " optional verifiers"); 10056 } 10057 10058 final int verificationId = mPendingVerificationToken++; 10059 10060 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10061 10062 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10063 installerPackageName); 10064 10065 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10066 installFlags); 10067 10068 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10069 pkgLite.packageName); 10070 10071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10072 pkgLite.versionCode); 10073 10074 if (verificationParams != null) { 10075 if (verificationParams.getVerificationURI() != null) { 10076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10077 verificationParams.getVerificationURI()); 10078 } 10079 if (verificationParams.getOriginatingURI() != null) { 10080 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10081 verificationParams.getOriginatingURI()); 10082 } 10083 if (verificationParams.getReferrer() != null) { 10084 verification.putExtra(Intent.EXTRA_REFERRER, 10085 verificationParams.getReferrer()); 10086 } 10087 if (verificationParams.getOriginatingUid() >= 0) { 10088 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10089 verificationParams.getOriginatingUid()); 10090 } 10091 if (verificationParams.getInstallerUid() >= 0) { 10092 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10093 verificationParams.getInstallerUid()); 10094 } 10095 } 10096 10097 final PackageVerificationState verificationState = new PackageVerificationState( 10098 requiredUid, args); 10099 10100 mPendingVerification.append(verificationId, verificationState); 10101 10102 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10103 receivers, verificationState); 10104 10105 /* 10106 * If any sufficient verifiers were listed in the package 10107 * manifest, attempt to ask them. 10108 */ 10109 if (sufficientVerifiers != null) { 10110 final int N = sufficientVerifiers.size(); 10111 if (N == 0) { 10112 Slog.i(TAG, "Additional verifiers required, but none installed."); 10113 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10114 } else { 10115 for (int i = 0; i < N; i++) { 10116 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10117 10118 final Intent sufficientIntent = new Intent(verification); 10119 sufficientIntent.setComponent(verifierComponent); 10120 10121 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10122 } 10123 } 10124 } 10125 10126 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10127 mRequiredVerifierPackage, receivers); 10128 if (ret == PackageManager.INSTALL_SUCCEEDED 10129 && mRequiredVerifierPackage != null) { 10130 /* 10131 * Send the intent to the required verification agent, 10132 * but only start the verification timeout after the 10133 * target BroadcastReceivers have run. 10134 */ 10135 verification.setComponent(requiredVerifierComponent); 10136 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10137 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10138 new BroadcastReceiver() { 10139 @Override 10140 public void onReceive(Context context, Intent intent) { 10141 final Message msg = mHandler 10142 .obtainMessage(CHECK_PENDING_VERIFICATION); 10143 msg.arg1 = verificationId; 10144 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10145 } 10146 }, null, 0, null, null); 10147 10148 /* 10149 * We don't want the copy to proceed until verification 10150 * succeeds, so null out this field. 10151 */ 10152 mArgs = null; 10153 } 10154 } else { 10155 /* 10156 * No package verification is enabled, so immediately start 10157 * the remote call to initiate copy using temporary file. 10158 */ 10159 ret = args.copyApk(mContainerService, true); 10160 } 10161 } 10162 10163 mRet = ret; 10164 } 10165 10166 @Override 10167 void handleReturnCode() { 10168 // If mArgs is null, then MCS couldn't be reached. When it 10169 // reconnects, it will try again to install. At that point, this 10170 // will succeed. 10171 if (mArgs != null) { 10172 processPendingInstall(mArgs, mRet); 10173 } 10174 } 10175 10176 @Override 10177 void handleServiceError() { 10178 mArgs = createInstallArgs(this); 10179 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10180 } 10181 10182 public boolean isForwardLocked() { 10183 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10184 } 10185 } 10186 10187 /** 10188 * Used during creation of InstallArgs 10189 * 10190 * @param installFlags package installation flags 10191 * @return true if should be installed on external storage 10192 */ 10193 private static boolean installOnExternalAsec(int installFlags) { 10194 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10195 return false; 10196 } 10197 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10198 return true; 10199 } 10200 return false; 10201 } 10202 10203 /** 10204 * Used during creation of InstallArgs 10205 * 10206 * @param installFlags package installation flags 10207 * @return true if should be installed as forward locked 10208 */ 10209 private static boolean installForwardLocked(int installFlags) { 10210 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10211 } 10212 10213 private InstallArgs createInstallArgs(InstallParams params) { 10214 if (params.move != null) { 10215 return new MoveInstallArgs(params); 10216 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10217 return new AsecInstallArgs(params); 10218 } else { 10219 return new FileInstallArgs(params); 10220 } 10221 } 10222 10223 /** 10224 * Create args that describe an existing installed package. Typically used 10225 * when cleaning up old installs, or used as a move source. 10226 */ 10227 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10228 String resourcePath, String[] instructionSets) { 10229 final boolean isInAsec; 10230 if (installOnExternalAsec(installFlags)) { 10231 /* Apps on SD card are always in ASEC containers. */ 10232 isInAsec = true; 10233 } else if (installForwardLocked(installFlags) 10234 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10235 /* 10236 * Forward-locked apps are only in ASEC containers if they're the 10237 * new style 10238 */ 10239 isInAsec = true; 10240 } else { 10241 isInAsec = false; 10242 } 10243 10244 if (isInAsec) { 10245 return new AsecInstallArgs(codePath, instructionSets, 10246 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10247 } else { 10248 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10249 } 10250 } 10251 10252 static abstract class InstallArgs { 10253 /** @see InstallParams#origin */ 10254 final OriginInfo origin; 10255 /** @see InstallParams#move */ 10256 final MoveInfo move; 10257 10258 final IPackageInstallObserver2 observer; 10259 // Always refers to PackageManager flags only 10260 final int installFlags; 10261 final String installerPackageName; 10262 final String volumeUuid; 10263 final ManifestDigest manifestDigest; 10264 final UserHandle user; 10265 final String abiOverride; 10266 10267 // The list of instruction sets supported by this app. This is currently 10268 // only used during the rmdex() phase to clean up resources. We can get rid of this 10269 // if we move dex files under the common app path. 10270 /* nullable */ String[] instructionSets; 10271 10272 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10273 int installFlags, String installerPackageName, String volumeUuid, 10274 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10275 String abiOverride) { 10276 this.origin = origin; 10277 this.move = move; 10278 this.installFlags = installFlags; 10279 this.observer = observer; 10280 this.installerPackageName = installerPackageName; 10281 this.volumeUuid = volumeUuid; 10282 this.manifestDigest = manifestDigest; 10283 this.user = user; 10284 this.instructionSets = instructionSets; 10285 this.abiOverride = abiOverride; 10286 } 10287 10288 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10289 abstract int doPreInstall(int status); 10290 10291 /** 10292 * Rename package into final resting place. All paths on the given 10293 * scanned package should be updated to reflect the rename. 10294 */ 10295 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10296 abstract int doPostInstall(int status, int uid); 10297 10298 /** @see PackageSettingBase#codePathString */ 10299 abstract String getCodePath(); 10300 /** @see PackageSettingBase#resourcePathString */ 10301 abstract String getResourcePath(); 10302 10303 // Need installer lock especially for dex file removal. 10304 abstract void cleanUpResourcesLI(); 10305 abstract boolean doPostDeleteLI(boolean delete); 10306 10307 /** 10308 * Called before the source arguments are copied. This is used mostly 10309 * for MoveParams when it needs to read the source file to put it in the 10310 * destination. 10311 */ 10312 int doPreCopy() { 10313 return PackageManager.INSTALL_SUCCEEDED; 10314 } 10315 10316 /** 10317 * Called after the source arguments are copied. This is used mostly for 10318 * MoveParams when it needs to read the source file to put it in the 10319 * destination. 10320 * 10321 * @return 10322 */ 10323 int doPostCopy(int uid) { 10324 return PackageManager.INSTALL_SUCCEEDED; 10325 } 10326 10327 protected boolean isFwdLocked() { 10328 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10329 } 10330 10331 protected boolean isExternalAsec() { 10332 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10333 } 10334 10335 UserHandle getUser() { 10336 return user; 10337 } 10338 } 10339 10340 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10341 if (!allCodePaths.isEmpty()) { 10342 if (instructionSets == null) { 10343 throw new IllegalStateException("instructionSet == null"); 10344 } 10345 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10346 for (String codePath : allCodePaths) { 10347 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10348 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10349 if (retCode < 0) { 10350 Slog.w(TAG, "Couldn't remove dex file for package: " 10351 + " at location " + codePath + ", retcode=" + retCode); 10352 // we don't consider this to be a failure of the core package deletion 10353 } 10354 } 10355 } 10356 } 10357 } 10358 10359 /** 10360 * Logic to handle installation of non-ASEC applications, including copying 10361 * and renaming logic. 10362 */ 10363 class FileInstallArgs extends InstallArgs { 10364 private File codeFile; 10365 private File resourceFile; 10366 10367 // Example topology: 10368 // /data/app/com.example/base.apk 10369 // /data/app/com.example/split_foo.apk 10370 // /data/app/com.example/lib/arm/libfoo.so 10371 // /data/app/com.example/lib/arm64/libfoo.so 10372 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10373 10374 /** New install */ 10375 FileInstallArgs(InstallParams params) { 10376 super(params.origin, params.move, params.observer, params.installFlags, 10377 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10378 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10379 if (isFwdLocked()) { 10380 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10381 } 10382 } 10383 10384 /** Existing install */ 10385 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10386 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10387 null); 10388 this.codeFile = (codePath != null) ? new File(codePath) : null; 10389 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10390 } 10391 10392 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10393 if (origin.staged) { 10394 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10395 codeFile = origin.file; 10396 resourceFile = origin.file; 10397 return PackageManager.INSTALL_SUCCEEDED; 10398 } 10399 10400 try { 10401 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10402 codeFile = tempDir; 10403 resourceFile = tempDir; 10404 } catch (IOException e) { 10405 Slog.w(TAG, "Failed to create copy file: " + e); 10406 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10407 } 10408 10409 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10410 @Override 10411 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10412 if (!FileUtils.isValidExtFilename(name)) { 10413 throw new IllegalArgumentException("Invalid filename: " + name); 10414 } 10415 try { 10416 final File file = new File(codeFile, name); 10417 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10418 O_RDWR | O_CREAT, 0644); 10419 Os.chmod(file.getAbsolutePath(), 0644); 10420 return new ParcelFileDescriptor(fd); 10421 } catch (ErrnoException e) { 10422 throw new RemoteException("Failed to open: " + e.getMessage()); 10423 } 10424 } 10425 }; 10426 10427 int ret = PackageManager.INSTALL_SUCCEEDED; 10428 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10429 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10430 Slog.e(TAG, "Failed to copy package"); 10431 return ret; 10432 } 10433 10434 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10435 NativeLibraryHelper.Handle handle = null; 10436 try { 10437 handle = NativeLibraryHelper.Handle.create(codeFile); 10438 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10439 abiOverride); 10440 } catch (IOException e) { 10441 Slog.e(TAG, "Copying native libraries failed", e); 10442 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10443 } finally { 10444 IoUtils.closeQuietly(handle); 10445 } 10446 10447 return ret; 10448 } 10449 10450 int doPreInstall(int status) { 10451 if (status != PackageManager.INSTALL_SUCCEEDED) { 10452 cleanUp(); 10453 } 10454 return status; 10455 } 10456 10457 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10458 if (status != PackageManager.INSTALL_SUCCEEDED) { 10459 cleanUp(); 10460 return false; 10461 } 10462 10463 final File targetDir = codeFile.getParentFile(); 10464 final File beforeCodeFile = codeFile; 10465 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10466 10467 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10468 try { 10469 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10470 } catch (ErrnoException e) { 10471 Slog.w(TAG, "Failed to rename", e); 10472 return false; 10473 } 10474 10475 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10476 Slog.w(TAG, "Failed to restorecon"); 10477 return false; 10478 } 10479 10480 // Reflect the rename internally 10481 codeFile = afterCodeFile; 10482 resourceFile = afterCodeFile; 10483 10484 // Reflect the rename in scanned details 10485 pkg.codePath = afterCodeFile.getAbsolutePath(); 10486 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10487 pkg.baseCodePath); 10488 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10489 pkg.splitCodePaths); 10490 10491 // Reflect the rename in app info 10492 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10493 pkg.applicationInfo.setCodePath(pkg.codePath); 10494 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10495 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10496 pkg.applicationInfo.setResourcePath(pkg.codePath); 10497 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10498 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10499 10500 return true; 10501 } 10502 10503 int doPostInstall(int status, int uid) { 10504 if (status != PackageManager.INSTALL_SUCCEEDED) { 10505 cleanUp(); 10506 } 10507 return status; 10508 } 10509 10510 @Override 10511 String getCodePath() { 10512 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10513 } 10514 10515 @Override 10516 String getResourcePath() { 10517 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10518 } 10519 10520 private boolean cleanUp() { 10521 if (codeFile == null || !codeFile.exists()) { 10522 return false; 10523 } 10524 10525 if (codeFile.isDirectory()) { 10526 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10527 } else { 10528 codeFile.delete(); 10529 } 10530 10531 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10532 resourceFile.delete(); 10533 } 10534 10535 return true; 10536 } 10537 10538 void cleanUpResourcesLI() { 10539 // Try enumerating all code paths before deleting 10540 List<String> allCodePaths = Collections.EMPTY_LIST; 10541 if (codeFile != null && codeFile.exists()) { 10542 try { 10543 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10544 allCodePaths = pkg.getAllCodePaths(); 10545 } catch (PackageParserException e) { 10546 // Ignored; we tried our best 10547 } 10548 } 10549 10550 cleanUp(); 10551 removeDexFiles(allCodePaths, instructionSets); 10552 } 10553 10554 boolean doPostDeleteLI(boolean delete) { 10555 // XXX err, shouldn't we respect the delete flag? 10556 cleanUpResourcesLI(); 10557 return true; 10558 } 10559 } 10560 10561 private boolean isAsecExternal(String cid) { 10562 final String asecPath = PackageHelper.getSdFilesystem(cid); 10563 return !asecPath.startsWith(mAsecInternalPath); 10564 } 10565 10566 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10567 PackageManagerException { 10568 if (copyRet < 0) { 10569 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10570 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10571 throw new PackageManagerException(copyRet, message); 10572 } 10573 } 10574 } 10575 10576 /** 10577 * Extract the MountService "container ID" from the full code path of an 10578 * .apk. 10579 */ 10580 static String cidFromCodePath(String fullCodePath) { 10581 int eidx = fullCodePath.lastIndexOf("/"); 10582 String subStr1 = fullCodePath.substring(0, eidx); 10583 int sidx = subStr1.lastIndexOf("/"); 10584 return subStr1.substring(sidx+1, eidx); 10585 } 10586 10587 /** 10588 * Logic to handle installation of ASEC applications, including copying and 10589 * renaming logic. 10590 */ 10591 class AsecInstallArgs extends InstallArgs { 10592 static final String RES_FILE_NAME = "pkg.apk"; 10593 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10594 10595 String cid; 10596 String packagePath; 10597 String resourcePath; 10598 10599 /** New install */ 10600 AsecInstallArgs(InstallParams params) { 10601 super(params.origin, params.move, params.observer, params.installFlags, 10602 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10603 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10604 } 10605 10606 /** Existing install */ 10607 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10608 boolean isExternal, boolean isForwardLocked) { 10609 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10610 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10611 instructionSets, null); 10612 // Hackily pretend we're still looking at a full code path 10613 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10614 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10615 } 10616 10617 // Extract cid from fullCodePath 10618 int eidx = fullCodePath.lastIndexOf("/"); 10619 String subStr1 = fullCodePath.substring(0, eidx); 10620 int sidx = subStr1.lastIndexOf("/"); 10621 cid = subStr1.substring(sidx+1, eidx); 10622 setMountPath(subStr1); 10623 } 10624 10625 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10626 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10627 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10628 instructionSets, null); 10629 this.cid = cid; 10630 setMountPath(PackageHelper.getSdDir(cid)); 10631 } 10632 10633 void createCopyFile() { 10634 cid = mInstallerService.allocateExternalStageCidLegacy(); 10635 } 10636 10637 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10638 if (origin.staged) { 10639 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10640 cid = origin.cid; 10641 setMountPath(PackageHelper.getSdDir(cid)); 10642 return PackageManager.INSTALL_SUCCEEDED; 10643 } 10644 10645 if (temp) { 10646 createCopyFile(); 10647 } else { 10648 /* 10649 * Pre-emptively destroy the container since it's destroyed if 10650 * copying fails due to it existing anyway. 10651 */ 10652 PackageHelper.destroySdDir(cid); 10653 } 10654 10655 final String newMountPath = imcs.copyPackageToContainer( 10656 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10657 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10658 10659 if (newMountPath != null) { 10660 setMountPath(newMountPath); 10661 return PackageManager.INSTALL_SUCCEEDED; 10662 } else { 10663 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10664 } 10665 } 10666 10667 @Override 10668 String getCodePath() { 10669 return packagePath; 10670 } 10671 10672 @Override 10673 String getResourcePath() { 10674 return resourcePath; 10675 } 10676 10677 int doPreInstall(int status) { 10678 if (status != PackageManager.INSTALL_SUCCEEDED) { 10679 // Destroy container 10680 PackageHelper.destroySdDir(cid); 10681 } else { 10682 boolean mounted = PackageHelper.isContainerMounted(cid); 10683 if (!mounted) { 10684 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10685 Process.SYSTEM_UID); 10686 if (newMountPath != null) { 10687 setMountPath(newMountPath); 10688 } else { 10689 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10690 } 10691 } 10692 } 10693 return status; 10694 } 10695 10696 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10697 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10698 String newMountPath = null; 10699 if (PackageHelper.isContainerMounted(cid)) { 10700 // Unmount the container 10701 if (!PackageHelper.unMountSdDir(cid)) { 10702 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10703 return false; 10704 } 10705 } 10706 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10707 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10708 " which might be stale. Will try to clean up."); 10709 // Clean up the stale container and proceed to recreate. 10710 if (!PackageHelper.destroySdDir(newCacheId)) { 10711 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10712 return false; 10713 } 10714 // Successfully cleaned up stale container. Try to rename again. 10715 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10716 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10717 + " inspite of cleaning it up."); 10718 return false; 10719 } 10720 } 10721 if (!PackageHelper.isContainerMounted(newCacheId)) { 10722 Slog.w(TAG, "Mounting container " + newCacheId); 10723 newMountPath = PackageHelper.mountSdDir(newCacheId, 10724 getEncryptKey(), Process.SYSTEM_UID); 10725 } else { 10726 newMountPath = PackageHelper.getSdDir(newCacheId); 10727 } 10728 if (newMountPath == null) { 10729 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10730 return false; 10731 } 10732 Log.i(TAG, "Succesfully renamed " + cid + 10733 " to " + newCacheId + 10734 " at new path: " + newMountPath); 10735 cid = newCacheId; 10736 10737 final File beforeCodeFile = new File(packagePath); 10738 setMountPath(newMountPath); 10739 final File afterCodeFile = new File(packagePath); 10740 10741 // Reflect the rename in scanned details 10742 pkg.codePath = afterCodeFile.getAbsolutePath(); 10743 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10744 pkg.baseCodePath); 10745 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10746 pkg.splitCodePaths); 10747 10748 // Reflect the rename in app info 10749 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10750 pkg.applicationInfo.setCodePath(pkg.codePath); 10751 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10752 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10753 pkg.applicationInfo.setResourcePath(pkg.codePath); 10754 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10755 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10756 10757 return true; 10758 } 10759 10760 private void setMountPath(String mountPath) { 10761 final File mountFile = new File(mountPath); 10762 10763 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10764 if (monolithicFile.exists()) { 10765 packagePath = monolithicFile.getAbsolutePath(); 10766 if (isFwdLocked()) { 10767 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10768 } else { 10769 resourcePath = packagePath; 10770 } 10771 } else { 10772 packagePath = mountFile.getAbsolutePath(); 10773 resourcePath = packagePath; 10774 } 10775 } 10776 10777 int doPostInstall(int status, int uid) { 10778 if (status != PackageManager.INSTALL_SUCCEEDED) { 10779 cleanUp(); 10780 } else { 10781 final int groupOwner; 10782 final String protectedFile; 10783 if (isFwdLocked()) { 10784 groupOwner = UserHandle.getSharedAppGid(uid); 10785 protectedFile = RES_FILE_NAME; 10786 } else { 10787 groupOwner = -1; 10788 protectedFile = null; 10789 } 10790 10791 if (uid < Process.FIRST_APPLICATION_UID 10792 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10793 Slog.e(TAG, "Failed to finalize " + cid); 10794 PackageHelper.destroySdDir(cid); 10795 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10796 } 10797 10798 boolean mounted = PackageHelper.isContainerMounted(cid); 10799 if (!mounted) { 10800 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10801 } 10802 } 10803 return status; 10804 } 10805 10806 private void cleanUp() { 10807 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10808 10809 // Destroy secure container 10810 PackageHelper.destroySdDir(cid); 10811 } 10812 10813 private List<String> getAllCodePaths() { 10814 final File codeFile = new File(getCodePath()); 10815 if (codeFile != null && codeFile.exists()) { 10816 try { 10817 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10818 return pkg.getAllCodePaths(); 10819 } catch (PackageParserException e) { 10820 // Ignored; we tried our best 10821 } 10822 } 10823 return Collections.EMPTY_LIST; 10824 } 10825 10826 void cleanUpResourcesLI() { 10827 // Enumerate all code paths before deleting 10828 cleanUpResourcesLI(getAllCodePaths()); 10829 } 10830 10831 private void cleanUpResourcesLI(List<String> allCodePaths) { 10832 cleanUp(); 10833 removeDexFiles(allCodePaths, instructionSets); 10834 } 10835 10836 String getPackageName() { 10837 return getAsecPackageName(cid); 10838 } 10839 10840 boolean doPostDeleteLI(boolean delete) { 10841 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10842 final List<String> allCodePaths = getAllCodePaths(); 10843 boolean mounted = PackageHelper.isContainerMounted(cid); 10844 if (mounted) { 10845 // Unmount first 10846 if (PackageHelper.unMountSdDir(cid)) { 10847 mounted = false; 10848 } 10849 } 10850 if (!mounted && delete) { 10851 cleanUpResourcesLI(allCodePaths); 10852 } 10853 return !mounted; 10854 } 10855 10856 @Override 10857 int doPreCopy() { 10858 if (isFwdLocked()) { 10859 if (!PackageHelper.fixSdPermissions(cid, 10860 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10861 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10862 } 10863 } 10864 10865 return PackageManager.INSTALL_SUCCEEDED; 10866 } 10867 10868 @Override 10869 int doPostCopy(int uid) { 10870 if (isFwdLocked()) { 10871 if (uid < Process.FIRST_APPLICATION_UID 10872 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10873 RES_FILE_NAME)) { 10874 Slog.e(TAG, "Failed to finalize " + cid); 10875 PackageHelper.destroySdDir(cid); 10876 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10877 } 10878 } 10879 10880 return PackageManager.INSTALL_SUCCEEDED; 10881 } 10882 } 10883 10884 /** 10885 * Logic to handle movement of existing installed applications. 10886 */ 10887 class MoveInstallArgs extends InstallArgs { 10888 private File codeFile; 10889 private File resourceFile; 10890 10891 /** New install */ 10892 MoveInstallArgs(InstallParams params) { 10893 super(params.origin, params.move, params.observer, params.installFlags, 10894 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10895 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10896 } 10897 10898 int copyApk(IMediaContainerService imcs, boolean temp) { 10899 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10900 + move.fromUuid + " to " + move.toUuid); 10901 synchronized (mInstaller) { 10902 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10903 move.dataAppName, move.appId, move.seinfo) != 0) { 10904 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10905 } 10906 } 10907 10908 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10909 resourceFile = codeFile; 10910 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10911 10912 return PackageManager.INSTALL_SUCCEEDED; 10913 } 10914 10915 int doPreInstall(int status) { 10916 if (status != PackageManager.INSTALL_SUCCEEDED) { 10917 cleanUp(); 10918 } 10919 return status; 10920 } 10921 10922 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10923 if (status != PackageManager.INSTALL_SUCCEEDED) { 10924 cleanUp(); 10925 return false; 10926 } 10927 10928 // Reflect the move in app info 10929 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10930 pkg.applicationInfo.setCodePath(pkg.codePath); 10931 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10932 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10933 pkg.applicationInfo.setResourcePath(pkg.codePath); 10934 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10935 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10936 10937 return true; 10938 } 10939 10940 int doPostInstall(int status, int uid) { 10941 if (status != PackageManager.INSTALL_SUCCEEDED) { 10942 cleanUp(); 10943 } 10944 return status; 10945 } 10946 10947 @Override 10948 String getCodePath() { 10949 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10950 } 10951 10952 @Override 10953 String getResourcePath() { 10954 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10955 } 10956 10957 private boolean cleanUp() { 10958 if (codeFile == null || !codeFile.exists()) { 10959 return false; 10960 } 10961 10962 if (codeFile.isDirectory()) { 10963 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10964 } else { 10965 codeFile.delete(); 10966 } 10967 10968 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10969 resourceFile.delete(); 10970 } 10971 10972 return true; 10973 } 10974 10975 void cleanUpResourcesLI() { 10976 cleanUp(); 10977 } 10978 10979 boolean doPostDeleteLI(boolean delete) { 10980 // XXX err, shouldn't we respect the delete flag? 10981 cleanUpResourcesLI(); 10982 return true; 10983 } 10984 } 10985 10986 static String getAsecPackageName(String packageCid) { 10987 int idx = packageCid.lastIndexOf("-"); 10988 if (idx == -1) { 10989 return packageCid; 10990 } 10991 return packageCid.substring(0, idx); 10992 } 10993 10994 // Utility method used to create code paths based on package name and available index. 10995 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10996 String idxStr = ""; 10997 int idx = 1; 10998 // Fall back to default value of idx=1 if prefix is not 10999 // part of oldCodePath 11000 if (oldCodePath != null) { 11001 String subStr = oldCodePath; 11002 // Drop the suffix right away 11003 if (suffix != null && subStr.endsWith(suffix)) { 11004 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11005 } 11006 // If oldCodePath already contains prefix find out the 11007 // ending index to either increment or decrement. 11008 int sidx = subStr.lastIndexOf(prefix); 11009 if (sidx != -1) { 11010 subStr = subStr.substring(sidx + prefix.length()); 11011 if (subStr != null) { 11012 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11013 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11014 } 11015 try { 11016 idx = Integer.parseInt(subStr); 11017 if (idx <= 1) { 11018 idx++; 11019 } else { 11020 idx--; 11021 } 11022 } catch(NumberFormatException e) { 11023 } 11024 } 11025 } 11026 } 11027 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11028 return prefix + idxStr; 11029 } 11030 11031 private File getNextCodePath(File targetDir, String packageName) { 11032 int suffix = 1; 11033 File result; 11034 do { 11035 result = new File(targetDir, packageName + "-" + suffix); 11036 suffix++; 11037 } while (result.exists()); 11038 return result; 11039 } 11040 11041 // Utility method that returns the relative package path with respect 11042 // to the installation directory. Like say for /data/data/com.test-1.apk 11043 // string com.test-1 is returned. 11044 static String deriveCodePathName(String codePath) { 11045 if (codePath == null) { 11046 return null; 11047 } 11048 final File codeFile = new File(codePath); 11049 final String name = codeFile.getName(); 11050 if (codeFile.isDirectory()) { 11051 return name; 11052 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11053 final int lastDot = name.lastIndexOf('.'); 11054 return name.substring(0, lastDot); 11055 } else { 11056 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11057 return null; 11058 } 11059 } 11060 11061 class PackageInstalledInfo { 11062 String name; 11063 int uid; 11064 // The set of users that originally had this package installed. 11065 int[] origUsers; 11066 // The set of users that now have this package installed. 11067 int[] newUsers; 11068 PackageParser.Package pkg; 11069 int returnCode; 11070 String returnMsg; 11071 PackageRemovedInfo removedInfo; 11072 11073 public void setError(int code, String msg) { 11074 returnCode = code; 11075 returnMsg = msg; 11076 Slog.w(TAG, msg); 11077 } 11078 11079 public void setError(String msg, PackageParserException e) { 11080 returnCode = e.error; 11081 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11082 Slog.w(TAG, msg, e); 11083 } 11084 11085 public void setError(String msg, PackageManagerException e) { 11086 returnCode = e.error; 11087 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11088 Slog.w(TAG, msg, e); 11089 } 11090 11091 // In some error cases we want to convey more info back to the observer 11092 String origPackage; 11093 String origPermission; 11094 } 11095 11096 /* 11097 * Install a non-existing package. 11098 */ 11099 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11100 UserHandle user, String installerPackageName, String volumeUuid, 11101 PackageInstalledInfo res) { 11102 // Remember this for later, in case we need to rollback this install 11103 String pkgName = pkg.packageName; 11104 11105 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11106 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11107 UserHandle.USER_OWNER).exists(); 11108 synchronized(mPackages) { 11109 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11110 // A package with the same name is already installed, though 11111 // it has been renamed to an older name. The package we 11112 // are trying to install should be installed as an update to 11113 // the existing one, but that has not been requested, so bail. 11114 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11115 + " without first uninstalling package running as " 11116 + mSettings.mRenamedPackages.get(pkgName)); 11117 return; 11118 } 11119 if (mPackages.containsKey(pkgName)) { 11120 // Don't allow installation over an existing package with the same name. 11121 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11122 + " without first uninstalling."); 11123 return; 11124 } 11125 } 11126 11127 try { 11128 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11129 System.currentTimeMillis(), user); 11130 11131 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11132 // delete the partially installed application. the data directory will have to be 11133 // restored if it was already existing 11134 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11135 // remove package from internal structures. Note that we want deletePackageX to 11136 // delete the package data and cache directories that it created in 11137 // scanPackageLocked, unless those directories existed before we even tried to 11138 // install. 11139 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11140 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11141 res.removedInfo, true); 11142 } 11143 11144 } catch (PackageManagerException e) { 11145 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11146 } 11147 } 11148 11149 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11150 // Can't rotate keys during boot or if sharedUser. 11151 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11152 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11153 return false; 11154 } 11155 // app is using upgradeKeySets; make sure all are valid 11156 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11157 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11158 for (int i = 0; i < upgradeKeySets.length; i++) { 11159 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11160 Slog.wtf(TAG, "Package " 11161 + (oldPs.name != null ? oldPs.name : "<null>") 11162 + " contains upgrade-key-set reference to unknown key-set: " 11163 + upgradeKeySets[i] 11164 + " reverting to signatures check."); 11165 return false; 11166 } 11167 } 11168 return true; 11169 } 11170 11171 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11172 // Upgrade keysets are being used. Determine if new package has a superset of the 11173 // required keys. 11174 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11176 for (int i = 0; i < upgradeKeySets.length; i++) { 11177 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11178 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11179 return true; 11180 } 11181 } 11182 return false; 11183 } 11184 11185 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11186 UserHandle user, String installerPackageName, String volumeUuid, 11187 PackageInstalledInfo res) { 11188 final PackageParser.Package oldPackage; 11189 final String pkgName = pkg.packageName; 11190 final int[] allUsers; 11191 final boolean[] perUserInstalled; 11192 final boolean weFroze; 11193 11194 // First find the old package info and check signatures 11195 synchronized(mPackages) { 11196 oldPackage = mPackages.get(pkgName); 11197 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11198 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11199 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11200 if(!checkUpgradeKeySetLP(ps, pkg)) { 11201 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11202 "New package not signed by keys specified by upgrade-keysets: " 11203 + pkgName); 11204 return; 11205 } 11206 } else { 11207 // default to original signature matching 11208 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11209 != PackageManager.SIGNATURE_MATCH) { 11210 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11211 "New package has a different signature: " + pkgName); 11212 return; 11213 } 11214 } 11215 11216 // In case of rollback, remember per-user/profile install state 11217 allUsers = sUserManager.getUserIds(); 11218 perUserInstalled = new boolean[allUsers.length]; 11219 for (int i = 0; i < allUsers.length; i++) { 11220 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11221 } 11222 11223 // Mark the app as frozen to prevent launching during the upgrade 11224 // process, and then kill all running instances 11225 if (!ps.frozen) { 11226 ps.frozen = true; 11227 weFroze = true; 11228 } else { 11229 weFroze = false; 11230 } 11231 } 11232 11233 // Now that we're guarded by frozen state, kill app during upgrade 11234 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11235 11236 try { 11237 boolean sysPkg = (isSystemApp(oldPackage)); 11238 if (sysPkg) { 11239 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11240 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11241 } else { 11242 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11243 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11244 } 11245 } finally { 11246 // Regardless of success or failure of upgrade steps above, always 11247 // unfreeze the package if we froze it 11248 if (weFroze) { 11249 unfreezePackage(pkgName); 11250 } 11251 } 11252 } 11253 11254 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11255 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11256 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11257 String volumeUuid, PackageInstalledInfo res) { 11258 String pkgName = deletedPackage.packageName; 11259 boolean deletedPkg = true; 11260 boolean updatedSettings = false; 11261 11262 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11263 + deletedPackage); 11264 long origUpdateTime; 11265 if (pkg.mExtras != null) { 11266 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11267 } else { 11268 origUpdateTime = 0; 11269 } 11270 11271 // First delete the existing package while retaining the data directory 11272 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11273 res.removedInfo, true)) { 11274 // If the existing package wasn't successfully deleted 11275 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11276 deletedPkg = false; 11277 } else { 11278 // Successfully deleted the old package; proceed with replace. 11279 11280 // If deleted package lived in a container, give users a chance to 11281 // relinquish resources before killing. 11282 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11283 if (DEBUG_INSTALL) { 11284 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11285 } 11286 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11287 final ArrayList<String> pkgList = new ArrayList<String>(1); 11288 pkgList.add(deletedPackage.applicationInfo.packageName); 11289 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11290 } 11291 11292 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11293 try { 11294 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11295 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11296 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11297 perUserInstalled, res, user); 11298 updatedSettings = true; 11299 } catch (PackageManagerException e) { 11300 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11301 } 11302 } 11303 11304 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11305 // remove package from internal structures. Note that we want deletePackageX to 11306 // delete the package data and cache directories that it created in 11307 // scanPackageLocked, unless those directories existed before we even tried to 11308 // install. 11309 if(updatedSettings) { 11310 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11311 deletePackageLI( 11312 pkgName, null, true, allUsers, perUserInstalled, 11313 PackageManager.DELETE_KEEP_DATA, 11314 res.removedInfo, true); 11315 } 11316 // Since we failed to install the new package we need to restore the old 11317 // package that we deleted. 11318 if (deletedPkg) { 11319 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11320 File restoreFile = new File(deletedPackage.codePath); 11321 // Parse old package 11322 boolean oldExternal = isExternal(deletedPackage); 11323 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11324 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11325 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11326 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11327 try { 11328 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11329 } catch (PackageManagerException e) { 11330 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11331 + e.getMessage()); 11332 return; 11333 } 11334 // Restore of old package succeeded. Update permissions. 11335 // writer 11336 synchronized (mPackages) { 11337 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11338 UPDATE_PERMISSIONS_ALL); 11339 // can downgrade to reader 11340 mSettings.writeLPr(); 11341 } 11342 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11343 } 11344 } 11345 } 11346 11347 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11348 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11349 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11350 String volumeUuid, PackageInstalledInfo res) { 11351 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11352 + ", old=" + deletedPackage); 11353 boolean disabledSystem = false; 11354 boolean updatedSettings = false; 11355 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11356 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11357 != 0) { 11358 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11359 } 11360 String packageName = deletedPackage.packageName; 11361 if (packageName == null) { 11362 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11363 "Attempt to delete null packageName."); 11364 return; 11365 } 11366 PackageParser.Package oldPkg; 11367 PackageSetting oldPkgSetting; 11368 // reader 11369 synchronized (mPackages) { 11370 oldPkg = mPackages.get(packageName); 11371 oldPkgSetting = mSettings.mPackages.get(packageName); 11372 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11373 (oldPkgSetting == null)) { 11374 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11375 "Couldn't find package:" + packageName + " information"); 11376 return; 11377 } 11378 } 11379 11380 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11381 res.removedInfo.removedPackage = packageName; 11382 // Remove existing system package 11383 removePackageLI(oldPkgSetting, true); 11384 // writer 11385 synchronized (mPackages) { 11386 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11387 if (!disabledSystem && deletedPackage != null) { 11388 // We didn't need to disable the .apk as a current system package, 11389 // which means we are replacing another update that is already 11390 // installed. We need to make sure to delete the older one's .apk. 11391 res.removedInfo.args = createInstallArgsForExisting(0, 11392 deletedPackage.applicationInfo.getCodePath(), 11393 deletedPackage.applicationInfo.getResourcePath(), 11394 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11395 } else { 11396 res.removedInfo.args = null; 11397 } 11398 } 11399 11400 // Successfully disabled the old package. Now proceed with re-installation 11401 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11402 11403 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11404 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11405 11406 PackageParser.Package newPackage = null; 11407 try { 11408 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11409 if (newPackage.mExtras != null) { 11410 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11411 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11412 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11413 11414 // is the update attempting to change shared user? that isn't going to work... 11415 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11416 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11417 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11418 + " to " + newPkgSetting.sharedUser); 11419 updatedSettings = true; 11420 } 11421 } 11422 11423 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11424 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11425 perUserInstalled, res, user); 11426 updatedSettings = true; 11427 } 11428 11429 } catch (PackageManagerException e) { 11430 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11431 } 11432 11433 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11434 // Re installation failed. Restore old information 11435 // Remove new pkg information 11436 if (newPackage != null) { 11437 removeInstalledPackageLI(newPackage, true); 11438 } 11439 // Add back the old system package 11440 try { 11441 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11442 } catch (PackageManagerException e) { 11443 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11444 } 11445 // Restore the old system information in Settings 11446 synchronized (mPackages) { 11447 if (disabledSystem) { 11448 mSettings.enableSystemPackageLPw(packageName); 11449 } 11450 if (updatedSettings) { 11451 mSettings.setInstallerPackageName(packageName, 11452 oldPkgSetting.installerPackageName); 11453 } 11454 mSettings.writeLPr(); 11455 } 11456 } 11457 } 11458 11459 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11460 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11461 UserHandle user) { 11462 String pkgName = newPackage.packageName; 11463 synchronized (mPackages) { 11464 //write settings. the installStatus will be incomplete at this stage. 11465 //note that the new package setting would have already been 11466 //added to mPackages. It hasn't been persisted yet. 11467 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11468 mSettings.writeLPr(); 11469 } 11470 11471 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11472 11473 synchronized (mPackages) { 11474 updatePermissionsLPw(newPackage.packageName, newPackage, 11475 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11476 ? UPDATE_PERMISSIONS_ALL : 0)); 11477 // For system-bundled packages, we assume that installing an upgraded version 11478 // of the package implies that the user actually wants to run that new code, 11479 // so we enable the package. 11480 PackageSetting ps = mSettings.mPackages.get(pkgName); 11481 if (ps != null) { 11482 if (isSystemApp(newPackage)) { 11483 // NB: implicit assumption that system package upgrades apply to all users 11484 if (DEBUG_INSTALL) { 11485 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11486 } 11487 if (res.origUsers != null) { 11488 for (int userHandle : res.origUsers) { 11489 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11490 userHandle, installerPackageName); 11491 } 11492 } 11493 // Also convey the prior install/uninstall state 11494 if (allUsers != null && perUserInstalled != null) { 11495 for (int i = 0; i < allUsers.length; i++) { 11496 if (DEBUG_INSTALL) { 11497 Slog.d(TAG, " user " + allUsers[i] 11498 + " => " + perUserInstalled[i]); 11499 } 11500 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11501 } 11502 // these install state changes will be persisted in the 11503 // upcoming call to mSettings.writeLPr(). 11504 } 11505 } 11506 // It's implied that when a user requests installation, they want the app to be 11507 // installed and enabled. 11508 int userId = user.getIdentifier(); 11509 if (userId != UserHandle.USER_ALL) { 11510 ps.setInstalled(true, userId); 11511 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11512 } 11513 } 11514 res.name = pkgName; 11515 res.uid = newPackage.applicationInfo.uid; 11516 res.pkg = newPackage; 11517 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11518 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11519 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11520 //to update install status 11521 mSettings.writeLPr(); 11522 } 11523 } 11524 11525 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11526 final int installFlags = args.installFlags; 11527 final String installerPackageName = args.installerPackageName; 11528 final String volumeUuid = args.volumeUuid; 11529 final File tmpPackageFile = new File(args.getCodePath()); 11530 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11531 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11532 || (args.volumeUuid != null)); 11533 boolean replace = false; 11534 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11535 // Result object to be returned 11536 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11537 11538 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11539 // Retrieve PackageSettings and parse package 11540 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11541 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11542 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11543 PackageParser pp = new PackageParser(); 11544 pp.setSeparateProcesses(mSeparateProcesses); 11545 pp.setDisplayMetrics(mMetrics); 11546 11547 final PackageParser.Package pkg; 11548 try { 11549 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11550 } catch (PackageParserException e) { 11551 res.setError("Failed parse during installPackageLI", e); 11552 return; 11553 } 11554 11555 // Mark that we have an install time CPU ABI override. 11556 pkg.cpuAbiOverride = args.abiOverride; 11557 11558 String pkgName = res.name = pkg.packageName; 11559 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11560 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11561 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11562 return; 11563 } 11564 } 11565 11566 try { 11567 pp.collectCertificates(pkg, parseFlags); 11568 pp.collectManifestDigest(pkg); 11569 } catch (PackageParserException e) { 11570 res.setError("Failed collect during installPackageLI", e); 11571 return; 11572 } 11573 11574 /* If the installer passed in a manifest digest, compare it now. */ 11575 if (args.manifestDigest != null) { 11576 if (DEBUG_INSTALL) { 11577 final String parsedManifest = pkg.manifestDigest == null ? "null" 11578 : pkg.manifestDigest.toString(); 11579 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11580 + parsedManifest); 11581 } 11582 11583 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11584 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11585 return; 11586 } 11587 } else if (DEBUG_INSTALL) { 11588 final String parsedManifest = pkg.manifestDigest == null 11589 ? "null" : pkg.manifestDigest.toString(); 11590 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11591 } 11592 11593 // Get rid of all references to package scan path via parser. 11594 pp = null; 11595 String oldCodePath = null; 11596 boolean systemApp = false; 11597 synchronized (mPackages) { 11598 // Check if installing already existing package 11599 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11600 String oldName = mSettings.mRenamedPackages.get(pkgName); 11601 if (pkg.mOriginalPackages != null 11602 && pkg.mOriginalPackages.contains(oldName) 11603 && mPackages.containsKey(oldName)) { 11604 // This package is derived from an original package, 11605 // and this device has been updating from that original 11606 // name. We must continue using the original name, so 11607 // rename the new package here. 11608 pkg.setPackageName(oldName); 11609 pkgName = pkg.packageName; 11610 replace = true; 11611 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11612 + oldName + " pkgName=" + pkgName); 11613 } else if (mPackages.containsKey(pkgName)) { 11614 // This package, under its official name, already exists 11615 // on the device; we should replace it. 11616 replace = true; 11617 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11618 } 11619 11620 // Prevent apps opting out from runtime permissions 11621 if (replace) { 11622 PackageParser.Package oldPackage = mPackages.get(pkgName); 11623 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11624 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11625 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11626 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11627 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11628 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11629 + " doesn't support runtime permissions but the old" 11630 + " target SDK " + oldTargetSdk + " does."); 11631 return; 11632 } 11633 } 11634 } 11635 11636 PackageSetting ps = mSettings.mPackages.get(pkgName); 11637 if (ps != null) { 11638 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11639 11640 // Quick sanity check that we're signed correctly if updating; 11641 // we'll check this again later when scanning, but we want to 11642 // bail early here before tripping over redefined permissions. 11643 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11644 if (!checkUpgradeKeySetLP(ps, pkg)) { 11645 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11646 + pkg.packageName + " upgrade keys do not match the " 11647 + "previously installed version"); 11648 return; 11649 } 11650 } else { 11651 try { 11652 verifySignaturesLP(ps, pkg); 11653 } catch (PackageManagerException e) { 11654 res.setError(e.error, e.getMessage()); 11655 return; 11656 } 11657 } 11658 11659 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11660 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11661 systemApp = (ps.pkg.applicationInfo.flags & 11662 ApplicationInfo.FLAG_SYSTEM) != 0; 11663 } 11664 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11665 } 11666 11667 // Check whether the newly-scanned package wants to define an already-defined perm 11668 int N = pkg.permissions.size(); 11669 for (int i = N-1; i >= 0; i--) { 11670 PackageParser.Permission perm = pkg.permissions.get(i); 11671 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11672 if (bp != null) { 11673 // If the defining package is signed with our cert, it's okay. This 11674 // also includes the "updating the same package" case, of course. 11675 // "updating same package" could also involve key-rotation. 11676 final boolean sigsOk; 11677 if (bp.sourcePackage.equals(pkg.packageName) 11678 && (bp.packageSetting instanceof PackageSetting) 11679 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11680 scanFlags))) { 11681 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11682 } else { 11683 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11684 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11685 } 11686 if (!sigsOk) { 11687 // If the owning package is the system itself, we log but allow 11688 // install to proceed; we fail the install on all other permission 11689 // redefinitions. 11690 if (!bp.sourcePackage.equals("android")) { 11691 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11692 + pkg.packageName + " attempting to redeclare permission " 11693 + perm.info.name + " already owned by " + bp.sourcePackage); 11694 res.origPermission = perm.info.name; 11695 res.origPackage = bp.sourcePackage; 11696 return; 11697 } else { 11698 Slog.w(TAG, "Package " + pkg.packageName 11699 + " attempting to redeclare system permission " 11700 + perm.info.name + "; ignoring new declaration"); 11701 pkg.permissions.remove(i); 11702 } 11703 } 11704 } 11705 } 11706 11707 } 11708 11709 if (systemApp && onExternal) { 11710 // Disable updates to system apps on sdcard 11711 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11712 "Cannot install updates to system apps on sdcard"); 11713 return; 11714 } 11715 11716 if (args.move != null) { 11717 // We did an in-place move, so dex is ready to roll 11718 scanFlags |= SCAN_NO_DEX; 11719 scanFlags |= SCAN_MOVE; 11720 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11721 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11722 scanFlags |= SCAN_NO_DEX; 11723 11724 try { 11725 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11726 true /* extract libs */); 11727 } catch (PackageManagerException pme) { 11728 Slog.e(TAG, "Error deriving application ABI", pme); 11729 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11730 return; 11731 } 11732 11733 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11734 int result = mPackageDexOptimizer 11735 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11736 false /* defer */, false /* inclDependencies */); 11737 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11738 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11739 return; 11740 } 11741 } 11742 11743 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11744 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11745 return; 11746 } 11747 11748 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11749 11750 if (replace) { 11751 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11752 installerPackageName, volumeUuid, res); 11753 } else { 11754 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11755 args.user, installerPackageName, volumeUuid, res); 11756 } 11757 synchronized (mPackages) { 11758 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11759 if (ps != null) { 11760 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11761 } 11762 } 11763 } 11764 11765 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11766 if (mIntentFilterVerifierComponent == null) { 11767 Slog.w(TAG, "No IntentFilter verification will not be done as " 11768 + "there is no IntentFilterVerifier available!"); 11769 return; 11770 } 11771 11772 final int verifierUid = getPackageUid( 11773 mIntentFilterVerifierComponent.getPackageName(), 11774 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11775 11776 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11777 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11778 msg.obj = pkg; 11779 msg.arg1 = userId; 11780 msg.arg2 = verifierUid; 11781 11782 mHandler.sendMessage(msg); 11783 } 11784 11785 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11786 PackageParser.Package pkg) { 11787 int size = pkg.activities.size(); 11788 if (size == 0) { 11789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11790 "No activity, so no need to verify any IntentFilter!"); 11791 return; 11792 } 11793 11794 final boolean hasDomainURLs = hasDomainURLs(pkg); 11795 if (!hasDomainURLs) { 11796 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11797 "No domain URLs, so no need to verify any IntentFilter!"); 11798 return; 11799 } 11800 11801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11802 + " if any IntentFilter from the " + size 11803 + " Activities needs verification ..."); 11804 11805 final int verificationId = mIntentFilterVerificationToken++; 11806 int count = 0; 11807 final String packageName = pkg.packageName; 11808 boolean needToVerify = false; 11809 11810 synchronized (mPackages) { 11811 // If any filters need to be verified, then all need to be. 11812 for (PackageParser.Activity a : pkg.activities) { 11813 for (ActivityIntentInfo filter : a.intents) { 11814 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11815 if (DEBUG_DOMAIN_VERIFICATION) { 11816 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11817 } 11818 needToVerify = true; 11819 break; 11820 } 11821 } 11822 } 11823 if (needToVerify) { 11824 for (PackageParser.Activity a : pkg.activities) { 11825 for (ActivityIntentInfo filter : a.intents) { 11826 boolean needsFilterVerification = filter.hasWebDataURI(); 11827 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11828 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11829 "Verification needed for IntentFilter:" + filter.toString()); 11830 mIntentFilterVerifier.addOneIntentFilterVerification( 11831 verifierUid, userId, verificationId, filter, packageName); 11832 count++; 11833 } 11834 } 11835 } 11836 } 11837 } 11838 11839 if (count > 0) { 11840 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11841 + " IntentFilter verification" + (count > 1 ? "s" : "") 11842 + " for userId:" + userId); 11843 mIntentFilterVerifier.startVerifications(userId); 11844 } else { 11845 if (DEBUG_DOMAIN_VERIFICATION) { 11846 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11847 } 11848 } 11849 } 11850 11851 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11852 final ComponentName cn = filter.activity.getComponentName(); 11853 final String packageName = cn.getPackageName(); 11854 11855 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11856 packageName); 11857 if (ivi == null) { 11858 return true; 11859 } 11860 int status = ivi.getStatus(); 11861 switch (status) { 11862 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11863 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11864 return true; 11865 11866 default: 11867 // Nothing to do 11868 return false; 11869 } 11870 } 11871 11872 private static boolean isMultiArch(PackageSetting ps) { 11873 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11874 } 11875 11876 private static boolean isMultiArch(ApplicationInfo info) { 11877 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11878 } 11879 11880 private static boolean isExternal(PackageParser.Package pkg) { 11881 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11882 } 11883 11884 private static boolean isExternal(PackageSetting ps) { 11885 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11886 } 11887 11888 private static boolean isExternal(ApplicationInfo info) { 11889 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11890 } 11891 11892 private static boolean isSystemApp(PackageParser.Package pkg) { 11893 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11894 } 11895 11896 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11897 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11898 } 11899 11900 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11901 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11902 } 11903 11904 private static boolean isSystemApp(PackageSetting ps) { 11905 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11906 } 11907 11908 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11909 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11910 } 11911 11912 private int packageFlagsToInstallFlags(PackageSetting ps) { 11913 int installFlags = 0; 11914 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11915 // This existing package was an external ASEC install when we have 11916 // the external flag without a UUID 11917 installFlags |= PackageManager.INSTALL_EXTERNAL; 11918 } 11919 if (ps.isForwardLocked()) { 11920 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11921 } 11922 return installFlags; 11923 } 11924 11925 private void deleteTempPackageFiles() { 11926 final FilenameFilter filter = new FilenameFilter() { 11927 public boolean accept(File dir, String name) { 11928 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11929 } 11930 }; 11931 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11932 file.delete(); 11933 } 11934 } 11935 11936 @Override 11937 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11938 int flags) { 11939 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11940 flags); 11941 } 11942 11943 @Override 11944 public void deletePackage(final String packageName, 11945 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11946 mContext.enforceCallingOrSelfPermission( 11947 android.Manifest.permission.DELETE_PACKAGES, null); 11948 final int uid = Binder.getCallingUid(); 11949 if (UserHandle.getUserId(uid) != userId) { 11950 mContext.enforceCallingPermission( 11951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11952 "deletePackage for user " + userId); 11953 } 11954 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11955 try { 11956 observer.onPackageDeleted(packageName, 11957 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11958 } catch (RemoteException re) { 11959 } 11960 return; 11961 } 11962 11963 boolean uninstallBlocked = false; 11964 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11965 int[] users = sUserManager.getUserIds(); 11966 for (int i = 0; i < users.length; ++i) { 11967 if (getBlockUninstallForUser(packageName, users[i])) { 11968 uninstallBlocked = true; 11969 break; 11970 } 11971 } 11972 } else { 11973 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11974 } 11975 if (uninstallBlocked) { 11976 try { 11977 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11978 null); 11979 } catch (RemoteException re) { 11980 } 11981 return; 11982 } 11983 11984 if (DEBUG_REMOVE) { 11985 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11986 } 11987 // Queue up an async operation since the package deletion may take a little while. 11988 mHandler.post(new Runnable() { 11989 public void run() { 11990 mHandler.removeCallbacks(this); 11991 final int returnCode = deletePackageX(packageName, userId, flags); 11992 if (observer != null) { 11993 try { 11994 observer.onPackageDeleted(packageName, returnCode, null); 11995 } catch (RemoteException e) { 11996 Log.i(TAG, "Observer no longer exists."); 11997 } //end catch 11998 } //end if 11999 } //end run 12000 }); 12001 } 12002 12003 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12004 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12005 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12006 try { 12007 if (dpm != null) { 12008 if (dpm.isDeviceOwner(packageName)) { 12009 return true; 12010 } 12011 int[] users; 12012 if (userId == UserHandle.USER_ALL) { 12013 users = sUserManager.getUserIds(); 12014 } else { 12015 users = new int[]{userId}; 12016 } 12017 for (int i = 0; i < users.length; ++i) { 12018 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12019 return true; 12020 } 12021 } 12022 } 12023 } catch (RemoteException e) { 12024 } 12025 return false; 12026 } 12027 12028 /** 12029 * This method is an internal method that could be get invoked either 12030 * to delete an installed package or to clean up a failed installation. 12031 * After deleting an installed package, a broadcast is sent to notify any 12032 * listeners that the package has been installed. For cleaning up a failed 12033 * installation, the broadcast is not necessary since the package's 12034 * installation wouldn't have sent the initial broadcast either 12035 * The key steps in deleting a package are 12036 * deleting the package information in internal structures like mPackages, 12037 * deleting the packages base directories through installd 12038 * updating mSettings to reflect current status 12039 * persisting settings for later use 12040 * sending a broadcast if necessary 12041 */ 12042 private int deletePackageX(String packageName, int userId, int flags) { 12043 final PackageRemovedInfo info = new PackageRemovedInfo(); 12044 final boolean res; 12045 12046 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12047 ? UserHandle.ALL : new UserHandle(userId); 12048 12049 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12050 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12051 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12052 } 12053 12054 boolean removedForAllUsers = false; 12055 boolean systemUpdate = false; 12056 12057 // for the uninstall-updates case and restricted profiles, remember the per- 12058 // userhandle installed state 12059 int[] allUsers; 12060 boolean[] perUserInstalled; 12061 synchronized (mPackages) { 12062 PackageSetting ps = mSettings.mPackages.get(packageName); 12063 allUsers = sUserManager.getUserIds(); 12064 perUserInstalled = new boolean[allUsers.length]; 12065 for (int i = 0; i < allUsers.length; i++) { 12066 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12067 } 12068 } 12069 12070 synchronized (mInstallLock) { 12071 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12072 res = deletePackageLI(packageName, removeForUser, 12073 true, allUsers, perUserInstalled, 12074 flags | REMOVE_CHATTY, info, true); 12075 systemUpdate = info.isRemovedPackageSystemUpdate; 12076 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12077 removedForAllUsers = true; 12078 } 12079 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12080 + " removedForAllUsers=" + removedForAllUsers); 12081 } 12082 12083 if (res) { 12084 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12085 12086 // If the removed package was a system update, the old system package 12087 // was re-enabled; we need to broadcast this information 12088 if (systemUpdate) { 12089 Bundle extras = new Bundle(1); 12090 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12091 ? info.removedAppId : info.uid); 12092 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12093 12094 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12095 extras, null, null, null); 12096 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12097 extras, null, null, null); 12098 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12099 null, packageName, null, null); 12100 } 12101 } 12102 // Force a gc here. 12103 Runtime.getRuntime().gc(); 12104 // Delete the resources here after sending the broadcast to let 12105 // other processes clean up before deleting resources. 12106 if (info.args != null) { 12107 synchronized (mInstallLock) { 12108 info.args.doPostDeleteLI(true); 12109 } 12110 } 12111 12112 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12113 } 12114 12115 class PackageRemovedInfo { 12116 String removedPackage; 12117 int uid = -1; 12118 int removedAppId = -1; 12119 int[] removedUsers = null; 12120 boolean isRemovedPackageSystemUpdate = false; 12121 // Clean up resources deleted packages. 12122 InstallArgs args = null; 12123 12124 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12125 Bundle extras = new Bundle(1); 12126 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12127 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12128 if (replacing) { 12129 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12130 } 12131 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12132 if (removedPackage != null) { 12133 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12134 extras, null, null, removedUsers); 12135 if (fullRemove && !replacing) { 12136 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12137 extras, null, null, removedUsers); 12138 } 12139 } 12140 if (removedAppId >= 0) { 12141 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12142 removedUsers); 12143 } 12144 } 12145 } 12146 12147 /* 12148 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12149 * flag is not set, the data directory is removed as well. 12150 * make sure this flag is set for partially installed apps. If not its meaningless to 12151 * delete a partially installed application. 12152 */ 12153 private void removePackageDataLI(PackageSetting ps, 12154 int[] allUserHandles, boolean[] perUserInstalled, 12155 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12156 String packageName = ps.name; 12157 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12158 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12159 // Retrieve object to delete permissions for shared user later on 12160 final PackageSetting deletedPs; 12161 // reader 12162 synchronized (mPackages) { 12163 deletedPs = mSettings.mPackages.get(packageName); 12164 if (outInfo != null) { 12165 outInfo.removedPackage = packageName; 12166 outInfo.removedUsers = deletedPs != null 12167 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12168 : null; 12169 } 12170 } 12171 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12172 removeDataDirsLI(ps.volumeUuid, packageName); 12173 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12174 } 12175 // writer 12176 synchronized (mPackages) { 12177 if (deletedPs != null) { 12178 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12179 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12180 clearDefaultBrowserIfNeeded(packageName); 12181 if (outInfo != null) { 12182 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12183 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12184 } 12185 updatePermissionsLPw(deletedPs.name, null, 0); 12186 if (deletedPs.sharedUser != null) { 12187 // Remove permissions associated with package. Since runtime 12188 // permissions are per user we have to kill the removed package 12189 // or packages running under the shared user of the removed 12190 // package if revoking the permissions requested only by the removed 12191 // package is successful and this causes a change in gids. 12192 for (int userId : UserManagerService.getInstance().getUserIds()) { 12193 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12194 userId); 12195 if (userIdToKill == UserHandle.USER_ALL 12196 || userIdToKill >= UserHandle.USER_OWNER) { 12197 // If gids changed for this user, kill all affected packages. 12198 mHandler.post(new Runnable() { 12199 @Override 12200 public void run() { 12201 // This has to happen with no lock held. 12202 killSettingPackagesForUser(deletedPs, userIdToKill, 12203 KILL_APP_REASON_GIDS_CHANGED); 12204 } 12205 }); 12206 break; 12207 } 12208 } 12209 } 12210 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12211 } 12212 // make sure to preserve per-user disabled state if this removal was just 12213 // a downgrade of a system app to the factory package 12214 if (allUserHandles != null && perUserInstalled != null) { 12215 if (DEBUG_REMOVE) { 12216 Slog.d(TAG, "Propagating install state across downgrade"); 12217 } 12218 for (int i = 0; i < allUserHandles.length; i++) { 12219 if (DEBUG_REMOVE) { 12220 Slog.d(TAG, " user " + allUserHandles[i] 12221 + " => " + perUserInstalled[i]); 12222 } 12223 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12224 } 12225 } 12226 } 12227 // can downgrade to reader 12228 if (writeSettings) { 12229 // Save settings now 12230 mSettings.writeLPr(); 12231 } 12232 } 12233 if (outInfo != null) { 12234 // A user ID was deleted here. Go through all users and remove it 12235 // from KeyStore. 12236 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12237 } 12238 } 12239 12240 static boolean locationIsPrivileged(File path) { 12241 try { 12242 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12243 .getCanonicalPath(); 12244 return path.getCanonicalPath().startsWith(privilegedAppDir); 12245 } catch (IOException e) { 12246 Slog.e(TAG, "Unable to access code path " + path); 12247 } 12248 return false; 12249 } 12250 12251 /* 12252 * Tries to delete system package. 12253 */ 12254 private boolean deleteSystemPackageLI(PackageSetting newPs, 12255 int[] allUserHandles, boolean[] perUserInstalled, 12256 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12257 final boolean applyUserRestrictions 12258 = (allUserHandles != null) && (perUserInstalled != null); 12259 PackageSetting disabledPs = null; 12260 // Confirm if the system package has been updated 12261 // An updated system app can be deleted. This will also have to restore 12262 // the system pkg from system partition 12263 // reader 12264 synchronized (mPackages) { 12265 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12266 } 12267 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12268 + " disabledPs=" + disabledPs); 12269 if (disabledPs == null) { 12270 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12271 return false; 12272 } else if (DEBUG_REMOVE) { 12273 Slog.d(TAG, "Deleting system pkg from data partition"); 12274 } 12275 if (DEBUG_REMOVE) { 12276 if (applyUserRestrictions) { 12277 Slog.d(TAG, "Remembering install states:"); 12278 for (int i = 0; i < allUserHandles.length; i++) { 12279 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12280 } 12281 } 12282 } 12283 // Delete the updated package 12284 outInfo.isRemovedPackageSystemUpdate = true; 12285 if (disabledPs.versionCode < newPs.versionCode) { 12286 // Delete data for downgrades 12287 flags &= ~PackageManager.DELETE_KEEP_DATA; 12288 } else { 12289 // Preserve data by setting flag 12290 flags |= PackageManager.DELETE_KEEP_DATA; 12291 } 12292 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12293 allUserHandles, perUserInstalled, outInfo, writeSettings); 12294 if (!ret) { 12295 return false; 12296 } 12297 // writer 12298 synchronized (mPackages) { 12299 // Reinstate the old system package 12300 mSettings.enableSystemPackageLPw(newPs.name); 12301 // Remove any native libraries from the upgraded package. 12302 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12303 } 12304 // Install the system package 12305 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12306 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12307 if (locationIsPrivileged(disabledPs.codePath)) { 12308 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12309 } 12310 12311 final PackageParser.Package newPkg; 12312 try { 12313 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12314 } catch (PackageManagerException e) { 12315 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12316 return false; 12317 } 12318 12319 // writer 12320 synchronized (mPackages) { 12321 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12322 updatePermissionsLPw(newPkg.packageName, newPkg, 12323 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12324 if (applyUserRestrictions) { 12325 if (DEBUG_REMOVE) { 12326 Slog.d(TAG, "Propagating install state across reinstall"); 12327 } 12328 for (int i = 0; i < allUserHandles.length; i++) { 12329 if (DEBUG_REMOVE) { 12330 Slog.d(TAG, " user " + allUserHandles[i] 12331 + " => " + perUserInstalled[i]); 12332 } 12333 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12334 } 12335 // Regardless of writeSettings we need to ensure that this restriction 12336 // state propagation is persisted 12337 mSettings.writeAllUsersPackageRestrictionsLPr(); 12338 } 12339 // can downgrade to reader here 12340 if (writeSettings) { 12341 mSettings.writeLPr(); 12342 } 12343 } 12344 return true; 12345 } 12346 12347 private boolean deleteInstalledPackageLI(PackageSetting ps, 12348 boolean deleteCodeAndResources, int flags, 12349 int[] allUserHandles, boolean[] perUserInstalled, 12350 PackageRemovedInfo outInfo, boolean writeSettings) { 12351 if (outInfo != null) { 12352 outInfo.uid = ps.appId; 12353 } 12354 12355 // Delete package data from internal structures and also remove data if flag is set 12356 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12357 12358 // Delete application code and resources 12359 if (deleteCodeAndResources && (outInfo != null)) { 12360 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12361 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12362 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12363 } 12364 return true; 12365 } 12366 12367 @Override 12368 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12369 int userId) { 12370 mContext.enforceCallingOrSelfPermission( 12371 android.Manifest.permission.DELETE_PACKAGES, null); 12372 synchronized (mPackages) { 12373 PackageSetting ps = mSettings.mPackages.get(packageName); 12374 if (ps == null) { 12375 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12376 return false; 12377 } 12378 if (!ps.getInstalled(userId)) { 12379 // Can't block uninstall for an app that is not installed or enabled. 12380 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12381 return false; 12382 } 12383 ps.setBlockUninstall(blockUninstall, userId); 12384 mSettings.writePackageRestrictionsLPr(userId); 12385 } 12386 return true; 12387 } 12388 12389 @Override 12390 public boolean getBlockUninstallForUser(String packageName, int userId) { 12391 synchronized (mPackages) { 12392 PackageSetting ps = mSettings.mPackages.get(packageName); 12393 if (ps == null) { 12394 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12395 return false; 12396 } 12397 return ps.getBlockUninstall(userId); 12398 } 12399 } 12400 12401 /* 12402 * This method handles package deletion in general 12403 */ 12404 private boolean deletePackageLI(String packageName, UserHandle user, 12405 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12406 int flags, PackageRemovedInfo outInfo, 12407 boolean writeSettings) { 12408 if (packageName == null) { 12409 Slog.w(TAG, "Attempt to delete null packageName."); 12410 return false; 12411 } 12412 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12413 PackageSetting ps; 12414 boolean dataOnly = false; 12415 int removeUser = -1; 12416 int appId = -1; 12417 synchronized (mPackages) { 12418 ps = mSettings.mPackages.get(packageName); 12419 if (ps == null) { 12420 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12421 return false; 12422 } 12423 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12424 && user.getIdentifier() != UserHandle.USER_ALL) { 12425 // The caller is asking that the package only be deleted for a single 12426 // user. To do this, we just mark its uninstalled state and delete 12427 // its data. If this is a system app, we only allow this to happen if 12428 // they have set the special DELETE_SYSTEM_APP which requests different 12429 // semantics than normal for uninstalling system apps. 12430 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12431 ps.setUserState(user.getIdentifier(), 12432 COMPONENT_ENABLED_STATE_DEFAULT, 12433 false, //installed 12434 true, //stopped 12435 true, //notLaunched 12436 false, //hidden 12437 null, null, null, 12438 false, // blockUninstall 12439 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12440 if (!isSystemApp(ps)) { 12441 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12442 // Other user still have this package installed, so all 12443 // we need to do is clear this user's data and save that 12444 // it is uninstalled. 12445 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12446 removeUser = user.getIdentifier(); 12447 appId = ps.appId; 12448 scheduleWritePackageRestrictionsLocked(removeUser); 12449 } else { 12450 // We need to set it back to 'installed' so the uninstall 12451 // broadcasts will be sent correctly. 12452 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12453 ps.setInstalled(true, user.getIdentifier()); 12454 } 12455 } else { 12456 // This is a system app, so we assume that the 12457 // other users still have this package installed, so all 12458 // we need to do is clear this user's data and save that 12459 // it is uninstalled. 12460 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12461 removeUser = user.getIdentifier(); 12462 appId = ps.appId; 12463 scheduleWritePackageRestrictionsLocked(removeUser); 12464 } 12465 } 12466 } 12467 12468 if (removeUser >= 0) { 12469 // From above, we determined that we are deleting this only 12470 // for a single user. Continue the work here. 12471 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12472 if (outInfo != null) { 12473 outInfo.removedPackage = packageName; 12474 outInfo.removedAppId = appId; 12475 outInfo.removedUsers = new int[] {removeUser}; 12476 } 12477 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12478 removeKeystoreDataIfNeeded(removeUser, appId); 12479 schedulePackageCleaning(packageName, removeUser, false); 12480 synchronized (mPackages) { 12481 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12482 scheduleWritePackageRestrictionsLocked(removeUser); 12483 } 12484 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12485 removeUser); 12486 } 12487 return true; 12488 } 12489 12490 if (dataOnly) { 12491 // Delete application data first 12492 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12493 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12494 return true; 12495 } 12496 12497 boolean ret = false; 12498 if (isSystemApp(ps)) { 12499 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12500 // When an updated system application is deleted we delete the existing resources as well and 12501 // fall back to existing code in system partition 12502 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12503 flags, outInfo, writeSettings); 12504 } else { 12505 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12506 // Kill application pre-emptively especially for apps on sd. 12507 killApplication(packageName, ps.appId, "uninstall pkg"); 12508 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12509 allUserHandles, perUserInstalled, 12510 outInfo, writeSettings); 12511 } 12512 12513 return ret; 12514 } 12515 12516 private final class ClearStorageConnection implements ServiceConnection { 12517 IMediaContainerService mContainerService; 12518 12519 @Override 12520 public void onServiceConnected(ComponentName name, IBinder service) { 12521 synchronized (this) { 12522 mContainerService = IMediaContainerService.Stub.asInterface(service); 12523 notifyAll(); 12524 } 12525 } 12526 12527 @Override 12528 public void onServiceDisconnected(ComponentName name) { 12529 } 12530 } 12531 12532 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12533 final boolean mounted; 12534 if (Environment.isExternalStorageEmulated()) { 12535 mounted = true; 12536 } else { 12537 final String status = Environment.getExternalStorageState(); 12538 12539 mounted = status.equals(Environment.MEDIA_MOUNTED) 12540 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12541 } 12542 12543 if (!mounted) { 12544 return; 12545 } 12546 12547 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12548 int[] users; 12549 if (userId == UserHandle.USER_ALL) { 12550 users = sUserManager.getUserIds(); 12551 } else { 12552 users = new int[] { userId }; 12553 } 12554 final ClearStorageConnection conn = new ClearStorageConnection(); 12555 if (mContext.bindServiceAsUser( 12556 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12557 try { 12558 for (int curUser : users) { 12559 long timeout = SystemClock.uptimeMillis() + 5000; 12560 synchronized (conn) { 12561 long now = SystemClock.uptimeMillis(); 12562 while (conn.mContainerService == null && now < timeout) { 12563 try { 12564 conn.wait(timeout - now); 12565 } catch (InterruptedException e) { 12566 } 12567 } 12568 } 12569 if (conn.mContainerService == null) { 12570 return; 12571 } 12572 12573 final UserEnvironment userEnv = new UserEnvironment(curUser); 12574 clearDirectory(conn.mContainerService, 12575 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12576 if (allData) { 12577 clearDirectory(conn.mContainerService, 12578 userEnv.buildExternalStorageAppDataDirs(packageName)); 12579 clearDirectory(conn.mContainerService, 12580 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12581 } 12582 } 12583 } finally { 12584 mContext.unbindService(conn); 12585 } 12586 } 12587 } 12588 12589 @Override 12590 public void clearApplicationUserData(final String packageName, 12591 final IPackageDataObserver observer, final int userId) { 12592 mContext.enforceCallingOrSelfPermission( 12593 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12594 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12595 // Queue up an async operation since the package deletion may take a little while. 12596 mHandler.post(new Runnable() { 12597 public void run() { 12598 mHandler.removeCallbacks(this); 12599 final boolean succeeded; 12600 synchronized (mInstallLock) { 12601 succeeded = clearApplicationUserDataLI(packageName, userId); 12602 } 12603 clearExternalStorageDataSync(packageName, userId, true); 12604 if (succeeded) { 12605 // invoke DeviceStorageMonitor's update method to clear any notifications 12606 DeviceStorageMonitorInternal 12607 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12608 if (dsm != null) { 12609 dsm.checkMemory(); 12610 } 12611 } 12612 if(observer != null) { 12613 try { 12614 observer.onRemoveCompleted(packageName, succeeded); 12615 } catch (RemoteException e) { 12616 Log.i(TAG, "Observer no longer exists."); 12617 } 12618 } //end if observer 12619 } //end run 12620 }); 12621 } 12622 12623 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12624 if (packageName == null) { 12625 Slog.w(TAG, "Attempt to delete null packageName."); 12626 return false; 12627 } 12628 12629 // Try finding details about the requested package 12630 PackageParser.Package pkg; 12631 synchronized (mPackages) { 12632 pkg = mPackages.get(packageName); 12633 if (pkg == null) { 12634 final PackageSetting ps = mSettings.mPackages.get(packageName); 12635 if (ps != null) { 12636 pkg = ps.pkg; 12637 } 12638 } 12639 12640 if (pkg == null) { 12641 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12642 return false; 12643 } 12644 12645 PackageSetting ps = (PackageSetting) pkg.mExtras; 12646 PermissionsState permissionsState = ps.getPermissionsState(); 12647 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12648 } 12649 12650 // Always delete data directories for package, even if we found no other 12651 // record of app. This helps users recover from UID mismatches without 12652 // resorting to a full data wipe. 12653 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12654 if (retCode < 0) { 12655 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12656 return false; 12657 } 12658 12659 final int appId = pkg.applicationInfo.uid; 12660 removeKeystoreDataIfNeeded(userId, appId); 12661 12662 // Create a native library symlink only if we have native libraries 12663 // and if the native libraries are 32 bit libraries. We do not provide 12664 // this symlink for 64 bit libraries. 12665 if (pkg.applicationInfo.primaryCpuAbi != null && 12666 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12667 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12668 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12669 nativeLibPath, userId) < 0) { 12670 Slog.w(TAG, "Failed linking native library dir"); 12671 return false; 12672 } 12673 } 12674 12675 return true; 12676 } 12677 12678 12679 /** 12680 * Revokes granted runtime permissions and clears resettable flags 12681 * which are flags that can be set by a user interaction. 12682 * 12683 * @param permissionsState The permission state to reset. 12684 * @param userId The device user for which to do a reset. 12685 */ 12686 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12687 PermissionsState permissionsState, int userId) { 12688 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12689 | PackageManager.FLAG_PERMISSION_USER_FIXED 12690 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12691 12692 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12693 } 12694 12695 /** 12696 * Revokes granted runtime permissions and clears all flags. 12697 * 12698 * @param permissionsState The permission state to reset. 12699 * @param userId The device user for which to do a reset. 12700 */ 12701 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12702 PermissionsState permissionsState, int userId) { 12703 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12704 PackageManager.MASK_PERMISSION_FLAGS); 12705 } 12706 12707 /** 12708 * Revokes granted runtime permissions and clears certain flags. 12709 * 12710 * @param permissionsState The permission state to reset. 12711 * @param userId The device user for which to do a reset. 12712 * @param flags The flags that is going to be reset. 12713 */ 12714 private void revokeRuntimePermissionsAndClearFlagsLocked( 12715 PermissionsState permissionsState, int userId, int flags) { 12716 boolean needsWrite = false; 12717 12718 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12719 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12720 if (bp != null) { 12721 permissionsState.revokeRuntimePermission(bp, userId); 12722 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12723 needsWrite = true; 12724 } 12725 } 12726 12727 // Ensure default permissions are never cleared. 12728 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12729 12730 if (needsWrite) { 12731 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12732 } 12733 } 12734 12735 /** 12736 * Remove entries from the keystore daemon. Will only remove it if the 12737 * {@code appId} is valid. 12738 */ 12739 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12740 if (appId < 0) { 12741 return; 12742 } 12743 12744 final KeyStore keyStore = KeyStore.getInstance(); 12745 if (keyStore != null) { 12746 if (userId == UserHandle.USER_ALL) { 12747 for (final int individual : sUserManager.getUserIds()) { 12748 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12749 } 12750 } else { 12751 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12752 } 12753 } else { 12754 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12755 } 12756 } 12757 12758 @Override 12759 public void deleteApplicationCacheFiles(final String packageName, 12760 final IPackageDataObserver observer) { 12761 mContext.enforceCallingOrSelfPermission( 12762 android.Manifest.permission.DELETE_CACHE_FILES, null); 12763 // Queue up an async operation since the package deletion may take a little while. 12764 final int userId = UserHandle.getCallingUserId(); 12765 mHandler.post(new Runnable() { 12766 public void run() { 12767 mHandler.removeCallbacks(this); 12768 final boolean succeded; 12769 synchronized (mInstallLock) { 12770 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12771 } 12772 clearExternalStorageDataSync(packageName, userId, false); 12773 if (observer != null) { 12774 try { 12775 observer.onRemoveCompleted(packageName, succeded); 12776 } catch (RemoteException e) { 12777 Log.i(TAG, "Observer no longer exists."); 12778 } 12779 } //end if observer 12780 } //end run 12781 }); 12782 } 12783 12784 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12785 if (packageName == null) { 12786 Slog.w(TAG, "Attempt to delete null packageName."); 12787 return false; 12788 } 12789 PackageParser.Package p; 12790 synchronized (mPackages) { 12791 p = mPackages.get(packageName); 12792 } 12793 if (p == null) { 12794 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12795 return false; 12796 } 12797 final ApplicationInfo applicationInfo = p.applicationInfo; 12798 if (applicationInfo == null) { 12799 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12800 return false; 12801 } 12802 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12803 if (retCode < 0) { 12804 Slog.w(TAG, "Couldn't remove cache files for package: " 12805 + packageName + " u" + userId); 12806 return false; 12807 } 12808 return true; 12809 } 12810 12811 @Override 12812 public void getPackageSizeInfo(final String packageName, int userHandle, 12813 final IPackageStatsObserver observer) { 12814 mContext.enforceCallingOrSelfPermission( 12815 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12816 if (packageName == null) { 12817 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12818 } 12819 12820 PackageStats stats = new PackageStats(packageName, userHandle); 12821 12822 /* 12823 * Queue up an async operation since the package measurement may take a 12824 * little while. 12825 */ 12826 Message msg = mHandler.obtainMessage(INIT_COPY); 12827 msg.obj = new MeasureParams(stats, observer); 12828 mHandler.sendMessage(msg); 12829 } 12830 12831 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12832 PackageStats pStats) { 12833 if (packageName == null) { 12834 Slog.w(TAG, "Attempt to get size of null packageName."); 12835 return false; 12836 } 12837 PackageParser.Package p; 12838 boolean dataOnly = false; 12839 String libDirRoot = null; 12840 String asecPath = null; 12841 PackageSetting ps = null; 12842 synchronized (mPackages) { 12843 p = mPackages.get(packageName); 12844 ps = mSettings.mPackages.get(packageName); 12845 if(p == null) { 12846 dataOnly = true; 12847 if((ps == null) || (ps.pkg == null)) { 12848 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12849 return false; 12850 } 12851 p = ps.pkg; 12852 } 12853 if (ps != null) { 12854 libDirRoot = ps.legacyNativeLibraryPathString; 12855 } 12856 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12857 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12858 if (secureContainerId != null) { 12859 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12860 } 12861 } 12862 } 12863 String publicSrcDir = null; 12864 if(!dataOnly) { 12865 final ApplicationInfo applicationInfo = p.applicationInfo; 12866 if (applicationInfo == null) { 12867 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12868 return false; 12869 } 12870 if (p.isForwardLocked()) { 12871 publicSrcDir = applicationInfo.getBaseResourcePath(); 12872 } 12873 } 12874 // TODO: extend to measure size of split APKs 12875 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12876 // not just the first level. 12877 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12878 // just the primary. 12879 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12880 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12881 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12882 if (res < 0) { 12883 return false; 12884 } 12885 12886 // Fix-up for forward-locked applications in ASEC containers. 12887 if (!isExternal(p)) { 12888 pStats.codeSize += pStats.externalCodeSize; 12889 pStats.externalCodeSize = 0L; 12890 } 12891 12892 return true; 12893 } 12894 12895 12896 @Override 12897 public void addPackageToPreferred(String packageName) { 12898 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12899 } 12900 12901 @Override 12902 public void removePackageFromPreferred(String packageName) { 12903 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12904 } 12905 12906 @Override 12907 public List<PackageInfo> getPreferredPackages(int flags) { 12908 return new ArrayList<PackageInfo>(); 12909 } 12910 12911 private int getUidTargetSdkVersionLockedLPr(int uid) { 12912 Object obj = mSettings.getUserIdLPr(uid); 12913 if (obj instanceof SharedUserSetting) { 12914 final SharedUserSetting sus = (SharedUserSetting) obj; 12915 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12916 final Iterator<PackageSetting> it = sus.packages.iterator(); 12917 while (it.hasNext()) { 12918 final PackageSetting ps = it.next(); 12919 if (ps.pkg != null) { 12920 int v = ps.pkg.applicationInfo.targetSdkVersion; 12921 if (v < vers) vers = v; 12922 } 12923 } 12924 return vers; 12925 } else if (obj instanceof PackageSetting) { 12926 final PackageSetting ps = (PackageSetting) obj; 12927 if (ps.pkg != null) { 12928 return ps.pkg.applicationInfo.targetSdkVersion; 12929 } 12930 } 12931 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12932 } 12933 12934 @Override 12935 public void addPreferredActivity(IntentFilter filter, int match, 12936 ComponentName[] set, ComponentName activity, int userId) { 12937 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12938 "Adding preferred"); 12939 } 12940 12941 private void addPreferredActivityInternal(IntentFilter filter, int match, 12942 ComponentName[] set, ComponentName activity, boolean always, int userId, 12943 String opname) { 12944 // writer 12945 int callingUid = Binder.getCallingUid(); 12946 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12947 if (filter.countActions() == 0) { 12948 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12949 return; 12950 } 12951 synchronized (mPackages) { 12952 if (mContext.checkCallingOrSelfPermission( 12953 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12954 != PackageManager.PERMISSION_GRANTED) { 12955 if (getUidTargetSdkVersionLockedLPr(callingUid) 12956 < Build.VERSION_CODES.FROYO) { 12957 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12958 + callingUid); 12959 return; 12960 } 12961 mContext.enforceCallingOrSelfPermission( 12962 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12963 } 12964 12965 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12966 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12967 + userId + ":"); 12968 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12969 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12970 scheduleWritePackageRestrictionsLocked(userId); 12971 } 12972 } 12973 12974 @Override 12975 public void replacePreferredActivity(IntentFilter filter, int match, 12976 ComponentName[] set, ComponentName activity, int userId) { 12977 if (filter.countActions() != 1) { 12978 throw new IllegalArgumentException( 12979 "replacePreferredActivity expects filter to have only 1 action."); 12980 } 12981 if (filter.countDataAuthorities() != 0 12982 || filter.countDataPaths() != 0 12983 || filter.countDataSchemes() > 1 12984 || filter.countDataTypes() != 0) { 12985 throw new IllegalArgumentException( 12986 "replacePreferredActivity expects filter to have no data authorities, " + 12987 "paths, or types; and at most one scheme."); 12988 } 12989 12990 final int callingUid = Binder.getCallingUid(); 12991 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12992 synchronized (mPackages) { 12993 if (mContext.checkCallingOrSelfPermission( 12994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12995 != PackageManager.PERMISSION_GRANTED) { 12996 if (getUidTargetSdkVersionLockedLPr(callingUid) 12997 < Build.VERSION_CODES.FROYO) { 12998 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12999 + Binder.getCallingUid()); 13000 return; 13001 } 13002 mContext.enforceCallingOrSelfPermission( 13003 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13004 } 13005 13006 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13007 if (pir != null) { 13008 // Get all of the existing entries that exactly match this filter. 13009 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13010 if (existing != null && existing.size() == 1) { 13011 PreferredActivity cur = existing.get(0); 13012 if (DEBUG_PREFERRED) { 13013 Slog.i(TAG, "Checking replace of preferred:"); 13014 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13015 if (!cur.mPref.mAlways) { 13016 Slog.i(TAG, " -- CUR; not mAlways!"); 13017 } else { 13018 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13019 Slog.i(TAG, " -- CUR: mSet=" 13020 + Arrays.toString(cur.mPref.mSetComponents)); 13021 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13022 Slog.i(TAG, " -- NEW: mMatch=" 13023 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13024 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13025 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13026 } 13027 } 13028 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13029 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13030 && cur.mPref.sameSet(set)) { 13031 // Setting the preferred activity to what it happens to be already 13032 if (DEBUG_PREFERRED) { 13033 Slog.i(TAG, "Replacing with same preferred activity " 13034 + cur.mPref.mShortComponent + " for user " 13035 + userId + ":"); 13036 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13037 } 13038 return; 13039 } 13040 } 13041 13042 if (existing != null) { 13043 if (DEBUG_PREFERRED) { 13044 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13045 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13046 } 13047 for (int i = 0; i < existing.size(); i++) { 13048 PreferredActivity pa = existing.get(i); 13049 if (DEBUG_PREFERRED) { 13050 Slog.i(TAG, "Removing existing preferred activity " 13051 + pa.mPref.mComponent + ":"); 13052 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13053 } 13054 pir.removeFilter(pa); 13055 } 13056 } 13057 } 13058 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13059 "Replacing preferred"); 13060 } 13061 } 13062 13063 @Override 13064 public void clearPackagePreferredActivities(String packageName) { 13065 final int uid = Binder.getCallingUid(); 13066 // writer 13067 synchronized (mPackages) { 13068 PackageParser.Package pkg = mPackages.get(packageName); 13069 if (pkg == null || pkg.applicationInfo.uid != uid) { 13070 if (mContext.checkCallingOrSelfPermission( 13071 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13072 != PackageManager.PERMISSION_GRANTED) { 13073 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13074 < Build.VERSION_CODES.FROYO) { 13075 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13076 + Binder.getCallingUid()); 13077 return; 13078 } 13079 mContext.enforceCallingOrSelfPermission( 13080 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13081 } 13082 } 13083 13084 int user = UserHandle.getCallingUserId(); 13085 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13086 scheduleWritePackageRestrictionsLocked(user); 13087 } 13088 } 13089 } 13090 13091 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13092 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13093 ArrayList<PreferredActivity> removed = null; 13094 boolean changed = false; 13095 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13096 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13097 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13098 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13099 continue; 13100 } 13101 Iterator<PreferredActivity> it = pir.filterIterator(); 13102 while (it.hasNext()) { 13103 PreferredActivity pa = it.next(); 13104 // Mark entry for removal only if it matches the package name 13105 // and the entry is of type "always". 13106 if (packageName == null || 13107 (pa.mPref.mComponent.getPackageName().equals(packageName) 13108 && pa.mPref.mAlways)) { 13109 if (removed == null) { 13110 removed = new ArrayList<PreferredActivity>(); 13111 } 13112 removed.add(pa); 13113 } 13114 } 13115 if (removed != null) { 13116 for (int j=0; j<removed.size(); j++) { 13117 PreferredActivity pa = removed.get(j); 13118 pir.removeFilter(pa); 13119 } 13120 changed = true; 13121 } 13122 } 13123 return changed; 13124 } 13125 13126 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13127 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13128 if (userId == UserHandle.USER_ALL) { 13129 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13130 sUserManager.getUserIds())) { 13131 for (int oneUserId : sUserManager.getUserIds()) { 13132 scheduleWritePackageRestrictionsLocked(oneUserId); 13133 } 13134 } 13135 } else { 13136 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13137 scheduleWritePackageRestrictionsLocked(userId); 13138 } 13139 } 13140 } 13141 13142 13143 void clearDefaultBrowserIfNeeded(String packageName) { 13144 for (int oneUserId : sUserManager.getUserIds()) { 13145 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13146 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13147 if (packageName.equals(defaultBrowserPackageName)) { 13148 setDefaultBrowserPackageName(null, oneUserId); 13149 } 13150 } 13151 } 13152 13153 @Override 13154 public void resetPreferredActivities(int userId) { 13155 /* TODO: Actually use userId. Why is it being passed in? */ 13156 mContext.enforceCallingOrSelfPermission( 13157 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13158 // writer 13159 synchronized (mPackages) { 13160 int user = UserHandle.getCallingUserId(); 13161 clearPackagePreferredActivitiesLPw(null, user); 13162 mSettings.readDefaultPreferredAppsLPw(this, user); 13163 scheduleWritePackageRestrictionsLocked(user); 13164 } 13165 } 13166 13167 @Override 13168 public int getPreferredActivities(List<IntentFilter> outFilters, 13169 List<ComponentName> outActivities, String packageName) { 13170 13171 int num = 0; 13172 final int userId = UserHandle.getCallingUserId(); 13173 // reader 13174 synchronized (mPackages) { 13175 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13176 if (pir != null) { 13177 final Iterator<PreferredActivity> it = pir.filterIterator(); 13178 while (it.hasNext()) { 13179 final PreferredActivity pa = it.next(); 13180 if (packageName == null 13181 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13182 && pa.mPref.mAlways)) { 13183 if (outFilters != null) { 13184 outFilters.add(new IntentFilter(pa)); 13185 } 13186 if (outActivities != null) { 13187 outActivities.add(pa.mPref.mComponent); 13188 } 13189 } 13190 } 13191 } 13192 } 13193 13194 return num; 13195 } 13196 13197 @Override 13198 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13199 int userId) { 13200 int callingUid = Binder.getCallingUid(); 13201 if (callingUid != Process.SYSTEM_UID) { 13202 throw new SecurityException( 13203 "addPersistentPreferredActivity can only be run by the system"); 13204 } 13205 if (filter.countActions() == 0) { 13206 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13207 return; 13208 } 13209 synchronized (mPackages) { 13210 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13211 " :"); 13212 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13213 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13214 new PersistentPreferredActivity(filter, activity)); 13215 scheduleWritePackageRestrictionsLocked(userId); 13216 } 13217 } 13218 13219 @Override 13220 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13221 int callingUid = Binder.getCallingUid(); 13222 if (callingUid != Process.SYSTEM_UID) { 13223 throw new SecurityException( 13224 "clearPackagePersistentPreferredActivities can only be run by the system"); 13225 } 13226 ArrayList<PersistentPreferredActivity> removed = null; 13227 boolean changed = false; 13228 synchronized (mPackages) { 13229 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13230 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13231 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13232 .valueAt(i); 13233 if (userId != thisUserId) { 13234 continue; 13235 } 13236 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13237 while (it.hasNext()) { 13238 PersistentPreferredActivity ppa = it.next(); 13239 // Mark entry for removal only if it matches the package name. 13240 if (ppa.mComponent.getPackageName().equals(packageName)) { 13241 if (removed == null) { 13242 removed = new ArrayList<PersistentPreferredActivity>(); 13243 } 13244 removed.add(ppa); 13245 } 13246 } 13247 if (removed != null) { 13248 for (int j=0; j<removed.size(); j++) { 13249 PersistentPreferredActivity ppa = removed.get(j); 13250 ppir.removeFilter(ppa); 13251 } 13252 changed = true; 13253 } 13254 } 13255 13256 if (changed) { 13257 scheduleWritePackageRestrictionsLocked(userId); 13258 } 13259 } 13260 } 13261 13262 /** 13263 * Non-Binder method, support for the backup/restore mechanism: write the 13264 * full set of preferred activities in its canonical XML format. Returns true 13265 * on success; false otherwise. 13266 */ 13267 @Override 13268 public byte[] getPreferredActivityBackup(int userId) { 13269 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13270 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13271 } 13272 13273 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13274 try { 13275 final XmlSerializer serializer = new FastXmlSerializer(); 13276 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13277 serializer.startDocument(null, true); 13278 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13279 13280 synchronized (mPackages) { 13281 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13282 } 13283 13284 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13285 serializer.endDocument(); 13286 serializer.flush(); 13287 } catch (Exception e) { 13288 if (DEBUG_BACKUP) { 13289 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13290 } 13291 return null; 13292 } 13293 13294 return dataStream.toByteArray(); 13295 } 13296 13297 @Override 13298 public void restorePreferredActivities(byte[] backup, int userId) { 13299 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13300 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13301 } 13302 13303 try { 13304 final XmlPullParser parser = Xml.newPullParser(); 13305 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13306 13307 int type; 13308 while ((type = parser.next()) != XmlPullParser.START_TAG 13309 && type != XmlPullParser.END_DOCUMENT) { 13310 } 13311 if (type != XmlPullParser.START_TAG) { 13312 // oops didn't find a start tag?! 13313 if (DEBUG_BACKUP) { 13314 Slog.e(TAG, "Didn't find start tag during restore"); 13315 } 13316 return; 13317 } 13318 13319 // this is supposed to be TAG_PREFERRED_BACKUP 13320 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13321 if (DEBUG_BACKUP) { 13322 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13323 } 13324 return; 13325 } 13326 13327 // skip interfering stuff, then we're aligned with the backing implementation 13328 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13329 synchronized (mPackages) { 13330 mSettings.readPreferredActivitiesLPw(parser, userId); 13331 } 13332 } catch (Exception e) { 13333 if (DEBUG_BACKUP) { 13334 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13335 } 13336 } 13337 } 13338 13339 @Override 13340 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13341 int sourceUserId, int targetUserId, int flags) { 13342 mContext.enforceCallingOrSelfPermission( 13343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13344 int callingUid = Binder.getCallingUid(); 13345 enforceOwnerRights(ownerPackage, callingUid); 13346 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13347 if (intentFilter.countActions() == 0) { 13348 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13349 return; 13350 } 13351 synchronized (mPackages) { 13352 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13353 ownerPackage, targetUserId, flags); 13354 CrossProfileIntentResolver resolver = 13355 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13356 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13357 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13358 if (existing != null) { 13359 int size = existing.size(); 13360 for (int i = 0; i < size; i++) { 13361 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13362 return; 13363 } 13364 } 13365 } 13366 resolver.addFilter(newFilter); 13367 scheduleWritePackageRestrictionsLocked(sourceUserId); 13368 } 13369 } 13370 13371 @Override 13372 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13373 mContext.enforceCallingOrSelfPermission( 13374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13375 int callingUid = Binder.getCallingUid(); 13376 enforceOwnerRights(ownerPackage, callingUid); 13377 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13378 synchronized (mPackages) { 13379 CrossProfileIntentResolver resolver = 13380 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13381 ArraySet<CrossProfileIntentFilter> set = 13382 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13383 for (CrossProfileIntentFilter filter : set) { 13384 if (filter.getOwnerPackage().equals(ownerPackage)) { 13385 resolver.removeFilter(filter); 13386 } 13387 } 13388 scheduleWritePackageRestrictionsLocked(sourceUserId); 13389 } 13390 } 13391 13392 // Enforcing that callingUid is owning pkg on userId 13393 private void enforceOwnerRights(String pkg, int callingUid) { 13394 // The system owns everything. 13395 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13396 return; 13397 } 13398 int callingUserId = UserHandle.getUserId(callingUid); 13399 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13400 if (pi == null) { 13401 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13402 + callingUserId); 13403 } 13404 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13405 throw new SecurityException("Calling uid " + callingUid 13406 + " does not own package " + pkg); 13407 } 13408 } 13409 13410 @Override 13411 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13412 Intent intent = new Intent(Intent.ACTION_MAIN); 13413 intent.addCategory(Intent.CATEGORY_HOME); 13414 13415 final int callingUserId = UserHandle.getCallingUserId(); 13416 List<ResolveInfo> list = queryIntentActivities(intent, null, 13417 PackageManager.GET_META_DATA, callingUserId); 13418 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13419 true, false, false, callingUserId); 13420 13421 allHomeCandidates.clear(); 13422 if (list != null) { 13423 for (ResolveInfo ri : list) { 13424 allHomeCandidates.add(ri); 13425 } 13426 } 13427 return (preferred == null || preferred.activityInfo == null) 13428 ? null 13429 : new ComponentName(preferred.activityInfo.packageName, 13430 preferred.activityInfo.name); 13431 } 13432 13433 @Override 13434 public void setApplicationEnabledSetting(String appPackageName, 13435 int newState, int flags, int userId, String callingPackage) { 13436 if (!sUserManager.exists(userId)) return; 13437 if (callingPackage == null) { 13438 callingPackage = Integer.toString(Binder.getCallingUid()); 13439 } 13440 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13441 } 13442 13443 @Override 13444 public void setComponentEnabledSetting(ComponentName componentName, 13445 int newState, int flags, int userId) { 13446 if (!sUserManager.exists(userId)) return; 13447 setEnabledSetting(componentName.getPackageName(), 13448 componentName.getClassName(), newState, flags, userId, null); 13449 } 13450 13451 private void setEnabledSetting(final String packageName, String className, int newState, 13452 final int flags, int userId, String callingPackage) { 13453 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13454 || newState == COMPONENT_ENABLED_STATE_ENABLED 13455 || newState == COMPONENT_ENABLED_STATE_DISABLED 13456 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13457 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13458 throw new IllegalArgumentException("Invalid new component state: " 13459 + newState); 13460 } 13461 PackageSetting pkgSetting; 13462 final int uid = Binder.getCallingUid(); 13463 final int permission = mContext.checkCallingOrSelfPermission( 13464 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13465 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13466 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13467 boolean sendNow = false; 13468 boolean isApp = (className == null); 13469 String componentName = isApp ? packageName : className; 13470 int packageUid = -1; 13471 ArrayList<String> components; 13472 13473 // writer 13474 synchronized (mPackages) { 13475 pkgSetting = mSettings.mPackages.get(packageName); 13476 if (pkgSetting == null) { 13477 if (className == null) { 13478 throw new IllegalArgumentException( 13479 "Unknown package: " + packageName); 13480 } 13481 throw new IllegalArgumentException( 13482 "Unknown component: " + packageName 13483 + "/" + className); 13484 } 13485 // Allow root and verify that userId is not being specified by a different user 13486 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13487 throw new SecurityException( 13488 "Permission Denial: attempt to change component state from pid=" 13489 + Binder.getCallingPid() 13490 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13491 } 13492 if (className == null) { 13493 // We're dealing with an application/package level state change 13494 if (pkgSetting.getEnabled(userId) == newState) { 13495 // Nothing to do 13496 return; 13497 } 13498 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13499 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13500 // Don't care about who enables an app. 13501 callingPackage = null; 13502 } 13503 pkgSetting.setEnabled(newState, userId, callingPackage); 13504 // pkgSetting.pkg.mSetEnabled = newState; 13505 } else { 13506 // We're dealing with a component level state change 13507 // First, verify that this is a valid class name. 13508 PackageParser.Package pkg = pkgSetting.pkg; 13509 if (pkg == null || !pkg.hasComponentClassName(className)) { 13510 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13511 throw new IllegalArgumentException("Component class " + className 13512 + " does not exist in " + packageName); 13513 } else { 13514 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13515 + className + " does not exist in " + packageName); 13516 } 13517 } 13518 switch (newState) { 13519 case COMPONENT_ENABLED_STATE_ENABLED: 13520 if (!pkgSetting.enableComponentLPw(className, userId)) { 13521 return; 13522 } 13523 break; 13524 case COMPONENT_ENABLED_STATE_DISABLED: 13525 if (!pkgSetting.disableComponentLPw(className, userId)) { 13526 return; 13527 } 13528 break; 13529 case COMPONENT_ENABLED_STATE_DEFAULT: 13530 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13531 return; 13532 } 13533 break; 13534 default: 13535 Slog.e(TAG, "Invalid new component state: " + newState); 13536 return; 13537 } 13538 } 13539 scheduleWritePackageRestrictionsLocked(userId); 13540 components = mPendingBroadcasts.get(userId, packageName); 13541 final boolean newPackage = components == null; 13542 if (newPackage) { 13543 components = new ArrayList<String>(); 13544 } 13545 if (!components.contains(componentName)) { 13546 components.add(componentName); 13547 } 13548 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13549 sendNow = true; 13550 // Purge entry from pending broadcast list if another one exists already 13551 // since we are sending one right away. 13552 mPendingBroadcasts.remove(userId, packageName); 13553 } else { 13554 if (newPackage) { 13555 mPendingBroadcasts.put(userId, packageName, components); 13556 } 13557 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13558 // Schedule a message 13559 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13560 } 13561 } 13562 } 13563 13564 long callingId = Binder.clearCallingIdentity(); 13565 try { 13566 if (sendNow) { 13567 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13568 sendPackageChangedBroadcast(packageName, 13569 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13570 } 13571 } finally { 13572 Binder.restoreCallingIdentity(callingId); 13573 } 13574 } 13575 13576 private void sendPackageChangedBroadcast(String packageName, 13577 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13578 if (DEBUG_INSTALL) 13579 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13580 + componentNames); 13581 Bundle extras = new Bundle(4); 13582 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13583 String nameList[] = new String[componentNames.size()]; 13584 componentNames.toArray(nameList); 13585 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13586 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13587 extras.putInt(Intent.EXTRA_UID, packageUid); 13588 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13589 new int[] {UserHandle.getUserId(packageUid)}); 13590 } 13591 13592 @Override 13593 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13594 if (!sUserManager.exists(userId)) return; 13595 final int uid = Binder.getCallingUid(); 13596 final int permission = mContext.checkCallingOrSelfPermission( 13597 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13598 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13599 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13600 // writer 13601 synchronized (mPackages) { 13602 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13603 allowedByPermission, uid, userId)) { 13604 scheduleWritePackageRestrictionsLocked(userId); 13605 } 13606 } 13607 } 13608 13609 @Override 13610 public String getInstallerPackageName(String packageName) { 13611 // reader 13612 synchronized (mPackages) { 13613 return mSettings.getInstallerPackageNameLPr(packageName); 13614 } 13615 } 13616 13617 @Override 13618 public int getApplicationEnabledSetting(String packageName, int userId) { 13619 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13620 int uid = Binder.getCallingUid(); 13621 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13622 // reader 13623 synchronized (mPackages) { 13624 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13625 } 13626 } 13627 13628 @Override 13629 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13630 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13631 int uid = Binder.getCallingUid(); 13632 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13633 // reader 13634 synchronized (mPackages) { 13635 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13636 } 13637 } 13638 13639 @Override 13640 public void enterSafeMode() { 13641 enforceSystemOrRoot("Only the system can request entering safe mode"); 13642 13643 if (!mSystemReady) { 13644 mSafeMode = true; 13645 } 13646 } 13647 13648 @Override 13649 public void systemReady() { 13650 mSystemReady = true; 13651 13652 // Read the compatibilty setting when the system is ready. 13653 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13654 mContext.getContentResolver(), 13655 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13656 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13657 if (DEBUG_SETTINGS) { 13658 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13659 } 13660 13661 synchronized (mPackages) { 13662 // Verify that all of the preferred activity components actually 13663 // exist. It is possible for applications to be updated and at 13664 // that point remove a previously declared activity component that 13665 // had been set as a preferred activity. We try to clean this up 13666 // the next time we encounter that preferred activity, but it is 13667 // possible for the user flow to never be able to return to that 13668 // situation so here we do a sanity check to make sure we haven't 13669 // left any junk around. 13670 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13671 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13672 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13673 removed.clear(); 13674 for (PreferredActivity pa : pir.filterSet()) { 13675 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13676 removed.add(pa); 13677 } 13678 } 13679 if (removed.size() > 0) { 13680 for (int r=0; r<removed.size(); r++) { 13681 PreferredActivity pa = removed.get(r); 13682 Slog.w(TAG, "Removing dangling preferred activity: " 13683 + pa.mPref.mComponent); 13684 pir.removeFilter(pa); 13685 } 13686 mSettings.writePackageRestrictionsLPr( 13687 mSettings.mPreferredActivities.keyAt(i)); 13688 } 13689 } 13690 } 13691 sUserManager.systemReady(); 13692 13693 // If we upgraded grant all default permissions before kicking off. 13694 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 13695 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13696 for (int userId : UserManagerService.getInstance().getUserIds()) { 13697 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13698 } 13699 } 13700 13701 // Kick off any messages waiting for system ready 13702 if (mPostSystemReadyMessages != null) { 13703 for (Message msg : mPostSystemReadyMessages) { 13704 msg.sendToTarget(); 13705 } 13706 mPostSystemReadyMessages = null; 13707 } 13708 13709 // Watch for external volumes that come and go over time 13710 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13711 storage.registerListener(mStorageListener); 13712 13713 mInstallerService.systemReady(); 13714 mPackageDexOptimizer.systemReady(); 13715 } 13716 13717 @Override 13718 public boolean isSafeMode() { 13719 return mSafeMode; 13720 } 13721 13722 @Override 13723 public boolean hasSystemUidErrors() { 13724 return mHasSystemUidErrors; 13725 } 13726 13727 static String arrayToString(int[] array) { 13728 StringBuffer buf = new StringBuffer(128); 13729 buf.append('['); 13730 if (array != null) { 13731 for (int i=0; i<array.length; i++) { 13732 if (i > 0) buf.append(", "); 13733 buf.append(array[i]); 13734 } 13735 } 13736 buf.append(']'); 13737 return buf.toString(); 13738 } 13739 13740 static class DumpState { 13741 public static final int DUMP_LIBS = 1 << 0; 13742 public static final int DUMP_FEATURES = 1 << 1; 13743 public static final int DUMP_RESOLVERS = 1 << 2; 13744 public static final int DUMP_PERMISSIONS = 1 << 3; 13745 public static final int DUMP_PACKAGES = 1 << 4; 13746 public static final int DUMP_SHARED_USERS = 1 << 5; 13747 public static final int DUMP_MESSAGES = 1 << 6; 13748 public static final int DUMP_PROVIDERS = 1 << 7; 13749 public static final int DUMP_VERIFIERS = 1 << 8; 13750 public static final int DUMP_PREFERRED = 1 << 9; 13751 public static final int DUMP_PREFERRED_XML = 1 << 10; 13752 public static final int DUMP_KEYSETS = 1 << 11; 13753 public static final int DUMP_VERSION = 1 << 12; 13754 public static final int DUMP_INSTALLS = 1 << 13; 13755 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13756 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13757 13758 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13759 13760 private int mTypes; 13761 13762 private int mOptions; 13763 13764 private boolean mTitlePrinted; 13765 13766 private SharedUserSetting mSharedUser; 13767 13768 public boolean isDumping(int type) { 13769 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13770 return true; 13771 } 13772 13773 return (mTypes & type) != 0; 13774 } 13775 13776 public void setDump(int type) { 13777 mTypes |= type; 13778 } 13779 13780 public boolean isOptionEnabled(int option) { 13781 return (mOptions & option) != 0; 13782 } 13783 13784 public void setOptionEnabled(int option) { 13785 mOptions |= option; 13786 } 13787 13788 public boolean onTitlePrinted() { 13789 final boolean printed = mTitlePrinted; 13790 mTitlePrinted = true; 13791 return printed; 13792 } 13793 13794 public boolean getTitlePrinted() { 13795 return mTitlePrinted; 13796 } 13797 13798 public void setTitlePrinted(boolean enabled) { 13799 mTitlePrinted = enabled; 13800 } 13801 13802 public SharedUserSetting getSharedUser() { 13803 return mSharedUser; 13804 } 13805 13806 public void setSharedUser(SharedUserSetting user) { 13807 mSharedUser = user; 13808 } 13809 } 13810 13811 @Override 13812 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13813 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13814 != PackageManager.PERMISSION_GRANTED) { 13815 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13816 + Binder.getCallingPid() 13817 + ", uid=" + Binder.getCallingUid() 13818 + " without permission " 13819 + android.Manifest.permission.DUMP); 13820 return; 13821 } 13822 13823 DumpState dumpState = new DumpState(); 13824 boolean fullPreferred = false; 13825 boolean checkin = false; 13826 13827 String packageName = null; 13828 13829 int opti = 0; 13830 while (opti < args.length) { 13831 String opt = args[opti]; 13832 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13833 break; 13834 } 13835 opti++; 13836 13837 if ("-a".equals(opt)) { 13838 // Right now we only know how to print all. 13839 } else if ("-h".equals(opt)) { 13840 pw.println("Package manager dump options:"); 13841 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13842 pw.println(" --checkin: dump for a checkin"); 13843 pw.println(" -f: print details of intent filters"); 13844 pw.println(" -h: print this help"); 13845 pw.println(" cmd may be one of:"); 13846 pw.println(" l[ibraries]: list known shared libraries"); 13847 pw.println(" f[ibraries]: list device features"); 13848 pw.println(" k[eysets]: print known keysets"); 13849 pw.println(" r[esolvers]: dump intent resolvers"); 13850 pw.println(" perm[issions]: dump permissions"); 13851 pw.println(" pref[erred]: print preferred package settings"); 13852 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13853 pw.println(" prov[iders]: dump content providers"); 13854 pw.println(" p[ackages]: dump installed packages"); 13855 pw.println(" s[hared-users]: dump shared user IDs"); 13856 pw.println(" m[essages]: print collected runtime messages"); 13857 pw.println(" v[erifiers]: print package verifier info"); 13858 pw.println(" version: print database version info"); 13859 pw.println(" write: write current settings now"); 13860 pw.println(" <package.name>: info about given package"); 13861 pw.println(" installs: details about install sessions"); 13862 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13863 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13864 return; 13865 } else if ("--checkin".equals(opt)) { 13866 checkin = true; 13867 } else if ("-f".equals(opt)) { 13868 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13869 } else { 13870 pw.println("Unknown argument: " + opt + "; use -h for help"); 13871 } 13872 } 13873 13874 // Is the caller requesting to dump a particular piece of data? 13875 if (opti < args.length) { 13876 String cmd = args[opti]; 13877 opti++; 13878 // Is this a package name? 13879 if ("android".equals(cmd) || cmd.contains(".")) { 13880 packageName = cmd; 13881 // When dumping a single package, we always dump all of its 13882 // filter information since the amount of data will be reasonable. 13883 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13884 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13885 dumpState.setDump(DumpState.DUMP_LIBS); 13886 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13887 dumpState.setDump(DumpState.DUMP_FEATURES); 13888 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13889 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13890 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13891 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13892 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13893 dumpState.setDump(DumpState.DUMP_PREFERRED); 13894 } else if ("preferred-xml".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13896 if (opti < args.length && "--full".equals(args[opti])) { 13897 fullPreferred = true; 13898 opti++; 13899 } 13900 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13901 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13902 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13903 dumpState.setDump(DumpState.DUMP_PACKAGES); 13904 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13905 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13906 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13907 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13908 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13909 dumpState.setDump(DumpState.DUMP_MESSAGES); 13910 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13911 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13912 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13913 || "intent-filter-verifiers".equals(cmd)) { 13914 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13915 } else if ("version".equals(cmd)) { 13916 dumpState.setDump(DumpState.DUMP_VERSION); 13917 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13918 dumpState.setDump(DumpState.DUMP_KEYSETS); 13919 } else if ("installs".equals(cmd)) { 13920 dumpState.setDump(DumpState.DUMP_INSTALLS); 13921 } else if ("write".equals(cmd)) { 13922 synchronized (mPackages) { 13923 mSettings.writeLPr(); 13924 pw.println("Settings written."); 13925 return; 13926 } 13927 } 13928 } 13929 13930 if (checkin) { 13931 pw.println("vers,1"); 13932 } 13933 13934 // reader 13935 synchronized (mPackages) { 13936 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13937 if (!checkin) { 13938 if (dumpState.onTitlePrinted()) 13939 pw.println(); 13940 pw.println("Database versions:"); 13941 pw.print(" SDK Version:"); 13942 pw.print(" internal="); 13943 pw.print(mSettings.mInternalSdkPlatform); 13944 pw.print(" external="); 13945 pw.println(mSettings.mExternalSdkPlatform); 13946 pw.print(" DB Version:"); 13947 pw.print(" internal="); 13948 pw.print(mSettings.mInternalDatabaseVersion); 13949 pw.print(" external="); 13950 pw.println(mSettings.mExternalDatabaseVersion); 13951 } 13952 } 13953 13954 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13955 if (!checkin) { 13956 if (dumpState.onTitlePrinted()) 13957 pw.println(); 13958 pw.println("Verifiers:"); 13959 pw.print(" Required: "); 13960 pw.print(mRequiredVerifierPackage); 13961 pw.print(" (uid="); 13962 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13963 pw.println(")"); 13964 } else if (mRequiredVerifierPackage != null) { 13965 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13966 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13967 } 13968 } 13969 13970 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13971 packageName == null) { 13972 if (mIntentFilterVerifierComponent != null) { 13973 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13974 if (!checkin) { 13975 if (dumpState.onTitlePrinted()) 13976 pw.println(); 13977 pw.println("Intent Filter Verifier:"); 13978 pw.print(" Using: "); 13979 pw.print(verifierPackageName); 13980 pw.print(" (uid="); 13981 pw.print(getPackageUid(verifierPackageName, 0)); 13982 pw.println(")"); 13983 } else if (verifierPackageName != null) { 13984 pw.print("ifv,"); pw.print(verifierPackageName); 13985 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13986 } 13987 } else { 13988 pw.println(); 13989 pw.println("No Intent Filter Verifier available!"); 13990 } 13991 } 13992 13993 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13994 boolean printedHeader = false; 13995 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13996 while (it.hasNext()) { 13997 String name = it.next(); 13998 SharedLibraryEntry ent = mSharedLibraries.get(name); 13999 if (!checkin) { 14000 if (!printedHeader) { 14001 if (dumpState.onTitlePrinted()) 14002 pw.println(); 14003 pw.println("Libraries:"); 14004 printedHeader = true; 14005 } 14006 pw.print(" "); 14007 } else { 14008 pw.print("lib,"); 14009 } 14010 pw.print(name); 14011 if (!checkin) { 14012 pw.print(" -> "); 14013 } 14014 if (ent.path != null) { 14015 if (!checkin) { 14016 pw.print("(jar) "); 14017 pw.print(ent.path); 14018 } else { 14019 pw.print(",jar,"); 14020 pw.print(ent.path); 14021 } 14022 } else { 14023 if (!checkin) { 14024 pw.print("(apk) "); 14025 pw.print(ent.apk); 14026 } else { 14027 pw.print(",apk,"); 14028 pw.print(ent.apk); 14029 } 14030 } 14031 pw.println(); 14032 } 14033 } 14034 14035 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14036 if (dumpState.onTitlePrinted()) 14037 pw.println(); 14038 if (!checkin) { 14039 pw.println("Features:"); 14040 } 14041 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14042 while (it.hasNext()) { 14043 String name = it.next(); 14044 if (!checkin) { 14045 pw.print(" "); 14046 } else { 14047 pw.print("feat,"); 14048 } 14049 pw.println(name); 14050 } 14051 } 14052 14053 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14054 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14055 : "Activity Resolver Table:", " ", packageName, 14056 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14057 dumpState.setTitlePrinted(true); 14058 } 14059 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14060 : "Receiver Resolver Table:", " ", packageName, 14061 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14062 dumpState.setTitlePrinted(true); 14063 } 14064 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14065 : "Service Resolver Table:", " ", packageName, 14066 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14067 dumpState.setTitlePrinted(true); 14068 } 14069 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14070 : "Provider Resolver Table:", " ", packageName, 14071 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14072 dumpState.setTitlePrinted(true); 14073 } 14074 } 14075 14076 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14077 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14078 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14079 int user = mSettings.mPreferredActivities.keyAt(i); 14080 if (pir.dump(pw, 14081 dumpState.getTitlePrinted() 14082 ? "\nPreferred Activities User " + user + ":" 14083 : "Preferred Activities User " + user + ":", " ", 14084 packageName, true, false)) { 14085 dumpState.setTitlePrinted(true); 14086 } 14087 } 14088 } 14089 14090 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14091 pw.flush(); 14092 FileOutputStream fout = new FileOutputStream(fd); 14093 BufferedOutputStream str = new BufferedOutputStream(fout); 14094 XmlSerializer serializer = new FastXmlSerializer(); 14095 try { 14096 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14097 serializer.startDocument(null, true); 14098 serializer.setFeature( 14099 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14100 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14101 serializer.endDocument(); 14102 serializer.flush(); 14103 } catch (IllegalArgumentException e) { 14104 pw.println("Failed writing: " + e); 14105 } catch (IllegalStateException e) { 14106 pw.println("Failed writing: " + e); 14107 } catch (IOException e) { 14108 pw.println("Failed writing: " + e); 14109 } 14110 } 14111 14112 if (!checkin 14113 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14114 && packageName == null) { 14115 pw.println(); 14116 int count = mSettings.mPackages.size(); 14117 if (count == 0) { 14118 pw.println("No domain preferred apps!"); 14119 pw.println(); 14120 } else { 14121 final String prefix = " "; 14122 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14123 if (allPackageSettings.size() == 0) { 14124 pw.println("No domain preferred apps!"); 14125 pw.println(); 14126 } else { 14127 pw.println("Domain preferred apps status:"); 14128 pw.println(); 14129 count = 0; 14130 for (PackageSetting ps : allPackageSettings) { 14131 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14132 if (ivi == null || ivi.getPackageName() == null) continue; 14133 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14134 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14135 pw.println(prefix + "Status: " + ivi.getStatusString()); 14136 pw.println(); 14137 count++; 14138 } 14139 if (count == 0) { 14140 pw.println(prefix + "No domain preferred app status!"); 14141 pw.println(); 14142 } 14143 for (int userId : sUserManager.getUserIds()) { 14144 pw.println("Domain preferred apps for User " + userId + ":"); 14145 pw.println(); 14146 count = 0; 14147 for (PackageSetting ps : allPackageSettings) { 14148 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14149 if (ivi == null || ivi.getPackageName() == null) { 14150 continue; 14151 } 14152 final int status = ps.getDomainVerificationStatusForUser(userId); 14153 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14154 continue; 14155 } 14156 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14157 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14158 String statusStr = IntentFilterVerificationInfo. 14159 getStatusStringFromValue(status); 14160 pw.println(prefix + "Status: " + statusStr); 14161 pw.println(); 14162 count++; 14163 } 14164 if (count == 0) { 14165 pw.println(prefix + "No domain preferred apps!"); 14166 pw.println(); 14167 } 14168 } 14169 } 14170 } 14171 } 14172 14173 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14174 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14175 if (packageName == null) { 14176 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14177 if (iperm == 0) { 14178 if (dumpState.onTitlePrinted()) 14179 pw.println(); 14180 pw.println("AppOp Permissions:"); 14181 } 14182 pw.print(" AppOp Permission "); 14183 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14184 pw.println(":"); 14185 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14186 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14187 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14188 } 14189 } 14190 } 14191 } 14192 14193 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14194 boolean printedSomething = false; 14195 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14196 if (packageName != null && !packageName.equals(p.info.packageName)) { 14197 continue; 14198 } 14199 if (!printedSomething) { 14200 if (dumpState.onTitlePrinted()) 14201 pw.println(); 14202 pw.println("Registered ContentProviders:"); 14203 printedSomething = true; 14204 } 14205 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14206 pw.print(" "); pw.println(p.toString()); 14207 } 14208 printedSomething = false; 14209 for (Map.Entry<String, PackageParser.Provider> entry : 14210 mProvidersByAuthority.entrySet()) { 14211 PackageParser.Provider p = entry.getValue(); 14212 if (packageName != null && !packageName.equals(p.info.packageName)) { 14213 continue; 14214 } 14215 if (!printedSomething) { 14216 if (dumpState.onTitlePrinted()) 14217 pw.println(); 14218 pw.println("ContentProvider Authorities:"); 14219 printedSomething = true; 14220 } 14221 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14222 pw.print(" "); pw.println(p.toString()); 14223 if (p.info != null && p.info.applicationInfo != null) { 14224 final String appInfo = p.info.applicationInfo.toString(); 14225 pw.print(" applicationInfo="); pw.println(appInfo); 14226 } 14227 } 14228 } 14229 14230 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14231 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14232 } 14233 14234 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14235 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14236 } 14237 14238 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14239 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14240 } 14241 14242 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14243 // XXX should handle packageName != null by dumping only install data that 14244 // the given package is involved with. 14245 if (dumpState.onTitlePrinted()) pw.println(); 14246 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14247 } 14248 14249 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14250 if (dumpState.onTitlePrinted()) pw.println(); 14251 mSettings.dumpReadMessagesLPr(pw, dumpState); 14252 14253 pw.println(); 14254 pw.println("Package warning messages:"); 14255 BufferedReader in = null; 14256 String line = null; 14257 try { 14258 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14259 while ((line = in.readLine()) != null) { 14260 if (line.contains("ignored: updated version")) continue; 14261 pw.println(line); 14262 } 14263 } catch (IOException ignored) { 14264 } finally { 14265 IoUtils.closeQuietly(in); 14266 } 14267 } 14268 14269 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14270 BufferedReader in = null; 14271 String line = null; 14272 try { 14273 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14274 while ((line = in.readLine()) != null) { 14275 if (line.contains("ignored: updated version")) continue; 14276 pw.print("msg,"); 14277 pw.println(line); 14278 } 14279 } catch (IOException ignored) { 14280 } finally { 14281 IoUtils.closeQuietly(in); 14282 } 14283 } 14284 } 14285 } 14286 14287 // ------- apps on sdcard specific code ------- 14288 static final boolean DEBUG_SD_INSTALL = false; 14289 14290 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14291 14292 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14293 14294 private boolean mMediaMounted = false; 14295 14296 static String getEncryptKey() { 14297 try { 14298 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14299 SD_ENCRYPTION_KEYSTORE_NAME); 14300 if (sdEncKey == null) { 14301 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14302 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14303 if (sdEncKey == null) { 14304 Slog.e(TAG, "Failed to create encryption keys"); 14305 return null; 14306 } 14307 } 14308 return sdEncKey; 14309 } catch (NoSuchAlgorithmException nsae) { 14310 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14311 return null; 14312 } catch (IOException ioe) { 14313 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14314 return null; 14315 } 14316 } 14317 14318 /* 14319 * Update media status on PackageManager. 14320 */ 14321 @Override 14322 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14323 int callingUid = Binder.getCallingUid(); 14324 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14325 throw new SecurityException("Media status can only be updated by the system"); 14326 } 14327 // reader; this apparently protects mMediaMounted, but should probably 14328 // be a different lock in that case. 14329 synchronized (mPackages) { 14330 Log.i(TAG, "Updating external media status from " 14331 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14332 + (mediaStatus ? "mounted" : "unmounted")); 14333 if (DEBUG_SD_INSTALL) 14334 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14335 + ", mMediaMounted=" + mMediaMounted); 14336 if (mediaStatus == mMediaMounted) { 14337 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14338 : 0, -1); 14339 mHandler.sendMessage(msg); 14340 return; 14341 } 14342 mMediaMounted = mediaStatus; 14343 } 14344 // Queue up an async operation since the package installation may take a 14345 // little while. 14346 mHandler.post(new Runnable() { 14347 public void run() { 14348 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14349 } 14350 }); 14351 } 14352 14353 /** 14354 * Called by MountService when the initial ASECs to scan are available. 14355 * Should block until all the ASEC containers are finished being scanned. 14356 */ 14357 public void scanAvailableAsecs() { 14358 updateExternalMediaStatusInner(true, false, false); 14359 if (mShouldRestoreconData) { 14360 SELinuxMMAC.setRestoreconDone(); 14361 mShouldRestoreconData = false; 14362 } 14363 } 14364 14365 /* 14366 * Collect information of applications on external media, map them against 14367 * existing containers and update information based on current mount status. 14368 * Please note that we always have to report status if reportStatus has been 14369 * set to true especially when unloading packages. 14370 */ 14371 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14372 boolean externalStorage) { 14373 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14374 int[] uidArr = EmptyArray.INT; 14375 14376 final String[] list = PackageHelper.getSecureContainerList(); 14377 if (ArrayUtils.isEmpty(list)) { 14378 Log.i(TAG, "No secure containers found"); 14379 } else { 14380 // Process list of secure containers and categorize them 14381 // as active or stale based on their package internal state. 14382 14383 // reader 14384 synchronized (mPackages) { 14385 for (String cid : list) { 14386 // Leave stages untouched for now; installer service owns them 14387 if (PackageInstallerService.isStageName(cid)) continue; 14388 14389 if (DEBUG_SD_INSTALL) 14390 Log.i(TAG, "Processing container " + cid); 14391 String pkgName = getAsecPackageName(cid); 14392 if (pkgName == null) { 14393 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14394 continue; 14395 } 14396 if (DEBUG_SD_INSTALL) 14397 Log.i(TAG, "Looking for pkg : " + pkgName); 14398 14399 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14400 if (ps == null) { 14401 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14402 continue; 14403 } 14404 14405 /* 14406 * Skip packages that are not external if we're unmounting 14407 * external storage. 14408 */ 14409 if (externalStorage && !isMounted && !isExternal(ps)) { 14410 continue; 14411 } 14412 14413 final AsecInstallArgs args = new AsecInstallArgs(cid, 14414 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14415 // The package status is changed only if the code path 14416 // matches between settings and the container id. 14417 if (ps.codePathString != null 14418 && ps.codePathString.startsWith(args.getCodePath())) { 14419 if (DEBUG_SD_INSTALL) { 14420 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14421 + " at code path: " + ps.codePathString); 14422 } 14423 14424 // We do have a valid package installed on sdcard 14425 processCids.put(args, ps.codePathString); 14426 final int uid = ps.appId; 14427 if (uid != -1) { 14428 uidArr = ArrayUtils.appendInt(uidArr, uid); 14429 } 14430 } else { 14431 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14432 + ps.codePathString); 14433 } 14434 } 14435 } 14436 14437 Arrays.sort(uidArr); 14438 } 14439 14440 // Process packages with valid entries. 14441 if (isMounted) { 14442 if (DEBUG_SD_INSTALL) 14443 Log.i(TAG, "Loading packages"); 14444 loadMediaPackages(processCids, uidArr); 14445 startCleaningPackages(); 14446 mInstallerService.onSecureContainersAvailable(); 14447 } else { 14448 if (DEBUG_SD_INSTALL) 14449 Log.i(TAG, "Unloading packages"); 14450 unloadMediaPackages(processCids, uidArr, reportStatus); 14451 } 14452 } 14453 14454 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14455 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14456 final int size = infos.size(); 14457 final String[] packageNames = new String[size]; 14458 final int[] packageUids = new int[size]; 14459 for (int i = 0; i < size; i++) { 14460 final ApplicationInfo info = infos.get(i); 14461 packageNames[i] = info.packageName; 14462 packageUids[i] = info.uid; 14463 } 14464 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14465 finishedReceiver); 14466 } 14467 14468 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14469 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14470 sendResourcesChangedBroadcast(mediaStatus, replacing, 14471 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14472 } 14473 14474 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14475 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14476 int size = pkgList.length; 14477 if (size > 0) { 14478 // Send broadcasts here 14479 Bundle extras = new Bundle(); 14480 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14481 if (uidArr != null) { 14482 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14483 } 14484 if (replacing) { 14485 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14486 } 14487 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14488 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14489 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14490 } 14491 } 14492 14493 /* 14494 * Look at potentially valid container ids from processCids If package 14495 * information doesn't match the one on record or package scanning fails, 14496 * the cid is added to list of removeCids. We currently don't delete stale 14497 * containers. 14498 */ 14499 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14500 ArrayList<String> pkgList = new ArrayList<String>(); 14501 Set<AsecInstallArgs> keys = processCids.keySet(); 14502 14503 for (AsecInstallArgs args : keys) { 14504 String codePath = processCids.get(args); 14505 if (DEBUG_SD_INSTALL) 14506 Log.i(TAG, "Loading container : " + args.cid); 14507 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14508 try { 14509 // Make sure there are no container errors first. 14510 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14511 Slog.e(TAG, "Failed to mount cid : " + args.cid 14512 + " when installing from sdcard"); 14513 continue; 14514 } 14515 // Check code path here. 14516 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14517 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14518 + " does not match one in settings " + codePath); 14519 continue; 14520 } 14521 // Parse package 14522 int parseFlags = mDefParseFlags; 14523 if (args.isExternalAsec()) { 14524 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14525 } 14526 if (args.isFwdLocked()) { 14527 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14528 } 14529 14530 synchronized (mInstallLock) { 14531 PackageParser.Package pkg = null; 14532 try { 14533 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14534 } catch (PackageManagerException e) { 14535 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14536 } 14537 // Scan the package 14538 if (pkg != null) { 14539 /* 14540 * TODO why is the lock being held? doPostInstall is 14541 * called in other places without the lock. This needs 14542 * to be straightened out. 14543 */ 14544 // writer 14545 synchronized (mPackages) { 14546 retCode = PackageManager.INSTALL_SUCCEEDED; 14547 pkgList.add(pkg.packageName); 14548 // Post process args 14549 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14550 pkg.applicationInfo.uid); 14551 } 14552 } else { 14553 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14554 } 14555 } 14556 14557 } finally { 14558 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14559 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14560 } 14561 } 14562 } 14563 // writer 14564 synchronized (mPackages) { 14565 // If the platform SDK has changed since the last time we booted, 14566 // we need to re-grant app permission to catch any new ones that 14567 // appear. This is really a hack, and means that apps can in some 14568 // cases get permissions that the user didn't initially explicitly 14569 // allow... it would be nice to have some better way to handle 14570 // this situation. 14571 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14572 if (regrantPermissions) 14573 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14574 + mSdkVersion + "; regranting permissions for external storage"); 14575 mSettings.mExternalSdkPlatform = mSdkVersion; 14576 14577 // Make sure group IDs have been assigned, and any permission 14578 // changes in other apps are accounted for 14579 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14580 | (regrantPermissions 14581 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14582 : 0)); 14583 14584 mSettings.updateExternalDatabaseVersion(); 14585 14586 // can downgrade to reader 14587 // Persist settings 14588 mSettings.writeLPr(); 14589 } 14590 // Send a broadcast to let everyone know we are done processing 14591 if (pkgList.size() > 0) { 14592 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14593 } 14594 } 14595 14596 /* 14597 * Utility method to unload a list of specified containers 14598 */ 14599 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14600 // Just unmount all valid containers. 14601 for (AsecInstallArgs arg : cidArgs) { 14602 synchronized (mInstallLock) { 14603 arg.doPostDeleteLI(false); 14604 } 14605 } 14606 } 14607 14608 /* 14609 * Unload packages mounted on external media. This involves deleting package 14610 * data from internal structures, sending broadcasts about diabled packages, 14611 * gc'ing to free up references, unmounting all secure containers 14612 * corresponding to packages on external media, and posting a 14613 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14614 * that we always have to post this message if status has been requested no 14615 * matter what. 14616 */ 14617 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14618 final boolean reportStatus) { 14619 if (DEBUG_SD_INSTALL) 14620 Log.i(TAG, "unloading media packages"); 14621 ArrayList<String> pkgList = new ArrayList<String>(); 14622 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14623 final Set<AsecInstallArgs> keys = processCids.keySet(); 14624 for (AsecInstallArgs args : keys) { 14625 String pkgName = args.getPackageName(); 14626 if (DEBUG_SD_INSTALL) 14627 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14628 // Delete package internally 14629 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14630 synchronized (mInstallLock) { 14631 boolean res = deletePackageLI(pkgName, null, false, null, null, 14632 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14633 if (res) { 14634 pkgList.add(pkgName); 14635 } else { 14636 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14637 failedList.add(args); 14638 } 14639 } 14640 } 14641 14642 // reader 14643 synchronized (mPackages) { 14644 // We didn't update the settings after removing each package; 14645 // write them now for all packages. 14646 mSettings.writeLPr(); 14647 } 14648 14649 // We have to absolutely send UPDATED_MEDIA_STATUS only 14650 // after confirming that all the receivers processed the ordered 14651 // broadcast when packages get disabled, force a gc to clean things up. 14652 // and unload all the containers. 14653 if (pkgList.size() > 0) { 14654 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14655 new IIntentReceiver.Stub() { 14656 public void performReceive(Intent intent, int resultCode, String data, 14657 Bundle extras, boolean ordered, boolean sticky, 14658 int sendingUser) throws RemoteException { 14659 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14660 reportStatus ? 1 : 0, 1, keys); 14661 mHandler.sendMessage(msg); 14662 } 14663 }); 14664 } else { 14665 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14666 keys); 14667 mHandler.sendMessage(msg); 14668 } 14669 } 14670 14671 private void loadPrivatePackages(VolumeInfo vol) { 14672 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14673 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14674 synchronized (mInstallLock) { 14675 synchronized (mPackages) { 14676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14677 for (PackageSetting ps : packages) { 14678 final PackageParser.Package pkg; 14679 try { 14680 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14681 loaded.add(pkg.applicationInfo); 14682 } catch (PackageManagerException e) { 14683 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14684 } 14685 } 14686 14687 // TODO: regrant any permissions that changed based since original install 14688 14689 mSettings.writeLPr(); 14690 } 14691 } 14692 14693 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14694 sendResourcesChangedBroadcast(true, false, loaded, null); 14695 } 14696 14697 private void unloadPrivatePackages(VolumeInfo vol) { 14698 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14699 synchronized (mInstallLock) { 14700 synchronized (mPackages) { 14701 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14702 for (PackageSetting ps : packages) { 14703 if (ps.pkg == null) continue; 14704 14705 final ApplicationInfo info = ps.pkg.applicationInfo; 14706 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14707 if (deletePackageLI(ps.name, null, false, null, null, 14708 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14709 unloaded.add(info); 14710 } else { 14711 Slog.w(TAG, "Failed to unload " + ps.codePath); 14712 } 14713 } 14714 14715 mSettings.writeLPr(); 14716 } 14717 } 14718 14719 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14720 sendResourcesChangedBroadcast(false, false, unloaded, null); 14721 } 14722 14723 private void unfreezePackage(String packageName) { 14724 synchronized (mPackages) { 14725 final PackageSetting ps = mSettings.mPackages.get(packageName); 14726 if (ps != null) { 14727 ps.frozen = false; 14728 } 14729 } 14730 } 14731 14732 @Override 14733 public int movePackage(final String packageName, final String volumeUuid) { 14734 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14735 14736 final int moveId = mNextMoveId.getAndIncrement(); 14737 try { 14738 movePackageInternal(packageName, volumeUuid, moveId); 14739 } catch (PackageManagerException e) { 14740 Slog.w(TAG, "Failed to move " + packageName, e); 14741 mMoveCallbacks.notifyStatusChanged(moveId, 14742 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14743 } 14744 return moveId; 14745 } 14746 14747 private void movePackageInternal(final String packageName, final String volumeUuid, 14748 final int moveId) throws PackageManagerException { 14749 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14750 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14751 final PackageManager pm = mContext.getPackageManager(); 14752 14753 final boolean currentAsec; 14754 final String currentVolumeUuid; 14755 final File codeFile; 14756 final String installerPackageName; 14757 final String packageAbiOverride; 14758 final int appId; 14759 final String seinfo; 14760 final String label; 14761 14762 // reader 14763 synchronized (mPackages) { 14764 final PackageParser.Package pkg = mPackages.get(packageName); 14765 final PackageSetting ps = mSettings.mPackages.get(packageName); 14766 if (pkg == null || ps == null) { 14767 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14768 } 14769 14770 if (pkg.applicationInfo.isSystemApp()) { 14771 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14772 "Cannot move system application"); 14773 } 14774 14775 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14776 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14777 "Package already moved to " + volumeUuid); 14778 } 14779 14780 final File probe = new File(pkg.codePath); 14781 final File probeOat = new File(probe, "oat"); 14782 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14783 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14784 "Move only supported for modern cluster style installs"); 14785 } 14786 14787 if (ps.frozen) { 14788 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14789 "Failed to move already frozen package"); 14790 } 14791 ps.frozen = true; 14792 14793 currentAsec = pkg.applicationInfo.isForwardLocked() 14794 || pkg.applicationInfo.isExternalAsec(); 14795 currentVolumeUuid = ps.volumeUuid; 14796 codeFile = new File(pkg.codePath); 14797 installerPackageName = ps.installerPackageName; 14798 packageAbiOverride = ps.cpuAbiOverrideString; 14799 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14800 seinfo = pkg.applicationInfo.seinfo; 14801 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14802 } 14803 14804 // Now that we're guarded by frozen state, kill app during move 14805 killApplication(packageName, appId, "move pkg"); 14806 14807 final Bundle extras = new Bundle(); 14808 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14809 extras.putString(Intent.EXTRA_TITLE, label); 14810 mMoveCallbacks.notifyCreated(moveId, extras); 14811 14812 int installFlags; 14813 final boolean moveCompleteApp; 14814 final File measurePath; 14815 14816 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14817 installFlags = INSTALL_INTERNAL; 14818 moveCompleteApp = !currentAsec; 14819 measurePath = Environment.getDataAppDirectory(volumeUuid); 14820 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14821 installFlags = INSTALL_EXTERNAL; 14822 moveCompleteApp = false; 14823 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14824 } else { 14825 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14826 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14827 || !volume.isMountedWritable()) { 14828 unfreezePackage(packageName); 14829 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14830 "Move location not mounted private volume"); 14831 } 14832 14833 Preconditions.checkState(!currentAsec); 14834 14835 installFlags = INSTALL_INTERNAL; 14836 moveCompleteApp = true; 14837 measurePath = Environment.getDataAppDirectory(volumeUuid); 14838 } 14839 14840 final PackageStats stats = new PackageStats(null, -1); 14841 synchronized (mInstaller) { 14842 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14843 unfreezePackage(packageName); 14844 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14845 "Failed to measure package size"); 14846 } 14847 } 14848 14849 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14850 + stats.dataSize); 14851 14852 final long startFreeBytes = measurePath.getFreeSpace(); 14853 final long sizeBytes; 14854 if (moveCompleteApp) { 14855 sizeBytes = stats.codeSize + stats.dataSize; 14856 } else { 14857 sizeBytes = stats.codeSize; 14858 } 14859 14860 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14861 unfreezePackage(packageName); 14862 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14863 "Not enough free space to move"); 14864 } 14865 14866 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14867 14868 final CountDownLatch installedLatch = new CountDownLatch(1); 14869 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14870 @Override 14871 public void onUserActionRequired(Intent intent) throws RemoteException { 14872 throw new IllegalStateException(); 14873 } 14874 14875 @Override 14876 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14877 Bundle extras) throws RemoteException { 14878 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14879 + PackageManager.installStatusToString(returnCode, msg)); 14880 14881 installedLatch.countDown(); 14882 14883 // Regardless of success or failure of the move operation, 14884 // always unfreeze the package 14885 unfreezePackage(packageName); 14886 14887 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14888 switch (status) { 14889 case PackageInstaller.STATUS_SUCCESS: 14890 mMoveCallbacks.notifyStatusChanged(moveId, 14891 PackageManager.MOVE_SUCCEEDED); 14892 break; 14893 case PackageInstaller.STATUS_FAILURE_STORAGE: 14894 mMoveCallbacks.notifyStatusChanged(moveId, 14895 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14896 break; 14897 default: 14898 mMoveCallbacks.notifyStatusChanged(moveId, 14899 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14900 break; 14901 } 14902 } 14903 }; 14904 14905 final MoveInfo move; 14906 if (moveCompleteApp) { 14907 // Kick off a thread to report progress estimates 14908 new Thread() { 14909 @Override 14910 public void run() { 14911 while (true) { 14912 try { 14913 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14914 break; 14915 } 14916 } catch (InterruptedException ignored) { 14917 } 14918 14919 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14920 final int progress = 10 + (int) MathUtils.constrain( 14921 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14922 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14923 } 14924 } 14925 }.start(); 14926 14927 final String dataAppName = codeFile.getName(); 14928 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14929 dataAppName, appId, seinfo); 14930 } else { 14931 move = null; 14932 } 14933 14934 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14935 14936 final Message msg = mHandler.obtainMessage(INIT_COPY); 14937 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14938 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14939 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14940 mHandler.sendMessage(msg); 14941 } 14942 14943 @Override 14944 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14946 14947 final int realMoveId = mNextMoveId.getAndIncrement(); 14948 final Bundle extras = new Bundle(); 14949 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14950 mMoveCallbacks.notifyCreated(realMoveId, extras); 14951 14952 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14953 @Override 14954 public void onCreated(int moveId, Bundle extras) { 14955 // Ignored 14956 } 14957 14958 @Override 14959 public void onStatusChanged(int moveId, int status, long estMillis) { 14960 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14961 } 14962 }; 14963 14964 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14965 storage.setPrimaryStorageUuid(volumeUuid, callback); 14966 return realMoveId; 14967 } 14968 14969 @Override 14970 public int getMoveStatus(int moveId) { 14971 mContext.enforceCallingOrSelfPermission( 14972 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14973 return mMoveCallbacks.mLastStatus.get(moveId); 14974 } 14975 14976 @Override 14977 public void registerMoveCallback(IPackageMoveObserver callback) { 14978 mContext.enforceCallingOrSelfPermission( 14979 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14980 mMoveCallbacks.register(callback); 14981 } 14982 14983 @Override 14984 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14985 mContext.enforceCallingOrSelfPermission( 14986 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14987 mMoveCallbacks.unregister(callback); 14988 } 14989 14990 @Override 14991 public boolean setInstallLocation(int loc) { 14992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14993 null); 14994 if (getInstallLocation() == loc) { 14995 return true; 14996 } 14997 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14998 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14999 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15000 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15001 return true; 15002 } 15003 return false; 15004 } 15005 15006 @Override 15007 public int getInstallLocation() { 15008 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15009 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15010 PackageHelper.APP_INSTALL_AUTO); 15011 } 15012 15013 /** Called by UserManagerService */ 15014 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15015 mDirtyUsers.remove(userHandle); 15016 mSettings.removeUserLPw(userHandle); 15017 mPendingBroadcasts.remove(userHandle); 15018 if (mInstaller != null) { 15019 // Technically, we shouldn't be doing this with the package lock 15020 // held. However, this is very rare, and there is already so much 15021 // other disk I/O going on, that we'll let it slide for now. 15022 final StorageManager storage = StorageManager.from(mContext); 15023 final List<VolumeInfo> vols = storage.getVolumes(); 15024 for (VolumeInfo vol : vols) { 15025 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15026 final String volumeUuid = vol.getFsUuid(); 15027 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15028 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15029 } 15030 } 15031 } 15032 mUserNeedsBadging.delete(userHandle); 15033 removeUnusedPackagesLILPw(userManager, userHandle); 15034 } 15035 15036 /** 15037 * We're removing userHandle and would like to remove any downloaded packages 15038 * that are no longer in use by any other user. 15039 * @param userHandle the user being removed 15040 */ 15041 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15042 final boolean DEBUG_CLEAN_APKS = false; 15043 int [] users = userManager.getUserIdsLPr(); 15044 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15045 while (psit.hasNext()) { 15046 PackageSetting ps = psit.next(); 15047 if (ps.pkg == null) { 15048 continue; 15049 } 15050 final String packageName = ps.pkg.packageName; 15051 // Skip over if system app 15052 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15053 continue; 15054 } 15055 if (DEBUG_CLEAN_APKS) { 15056 Slog.i(TAG, "Checking package " + packageName); 15057 } 15058 boolean keep = false; 15059 for (int i = 0; i < users.length; i++) { 15060 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15061 keep = true; 15062 if (DEBUG_CLEAN_APKS) { 15063 Slog.i(TAG, " Keeping package " + packageName + " for user " 15064 + users[i]); 15065 } 15066 break; 15067 } 15068 } 15069 if (!keep) { 15070 if (DEBUG_CLEAN_APKS) { 15071 Slog.i(TAG, " Removing package " + packageName); 15072 } 15073 mHandler.post(new Runnable() { 15074 public void run() { 15075 deletePackageX(packageName, userHandle, 0); 15076 } //end run 15077 }); 15078 } 15079 } 15080 } 15081 15082 /** Called by UserManagerService */ 15083 void createNewUserLILPw(int userHandle, File path) { 15084 if (mInstaller != null) { 15085 mInstaller.createUserConfig(userHandle); 15086 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15087 } 15088 } 15089 15090 void newUserCreatedLILPw(final int userHandle) { 15091 // We cannot grant the default permissions with a lock held as 15092 // we query providers from other components for default handlers 15093 // such as enabled IMEs, etc. 15094 mHandler.post(new Runnable() { 15095 @Override 15096 public void run() { 15097 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15098 } 15099 }); 15100 } 15101 15102 @Override 15103 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15104 mContext.enforceCallingOrSelfPermission( 15105 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15106 "Only package verification agents can read the verifier device identity"); 15107 15108 synchronized (mPackages) { 15109 return mSettings.getVerifierDeviceIdentityLPw(); 15110 } 15111 } 15112 15113 @Override 15114 public void setPermissionEnforced(String permission, boolean enforced) { 15115 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15116 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15117 synchronized (mPackages) { 15118 if (mSettings.mReadExternalStorageEnforced == null 15119 || mSettings.mReadExternalStorageEnforced != enforced) { 15120 mSettings.mReadExternalStorageEnforced = enforced; 15121 mSettings.writeLPr(); 15122 } 15123 } 15124 // kill any non-foreground processes so we restart them and 15125 // grant/revoke the GID. 15126 final IActivityManager am = ActivityManagerNative.getDefault(); 15127 if (am != null) { 15128 final long token = Binder.clearCallingIdentity(); 15129 try { 15130 am.killProcessesBelowForeground("setPermissionEnforcement"); 15131 } catch (RemoteException e) { 15132 } finally { 15133 Binder.restoreCallingIdentity(token); 15134 } 15135 } 15136 } else { 15137 throw new IllegalArgumentException("No selective enforcement for " + permission); 15138 } 15139 } 15140 15141 @Override 15142 @Deprecated 15143 public boolean isPermissionEnforced(String permission) { 15144 return true; 15145 } 15146 15147 @Override 15148 public boolean isStorageLow() { 15149 final long token = Binder.clearCallingIdentity(); 15150 try { 15151 final DeviceStorageMonitorInternal 15152 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15153 if (dsm != null) { 15154 return dsm.isMemoryLow(); 15155 } else { 15156 return false; 15157 } 15158 } finally { 15159 Binder.restoreCallingIdentity(token); 15160 } 15161 } 15162 15163 @Override 15164 public IPackageInstaller getPackageInstaller() { 15165 return mInstallerService; 15166 } 15167 15168 private boolean userNeedsBadging(int userId) { 15169 int index = mUserNeedsBadging.indexOfKey(userId); 15170 if (index < 0) { 15171 final UserInfo userInfo; 15172 final long token = Binder.clearCallingIdentity(); 15173 try { 15174 userInfo = sUserManager.getUserInfo(userId); 15175 } finally { 15176 Binder.restoreCallingIdentity(token); 15177 } 15178 final boolean b; 15179 if (userInfo != null && userInfo.isManagedProfile()) { 15180 b = true; 15181 } else { 15182 b = false; 15183 } 15184 mUserNeedsBadging.put(userId, b); 15185 return b; 15186 } 15187 return mUserNeedsBadging.valueAt(index); 15188 } 15189 15190 @Override 15191 public KeySet getKeySetByAlias(String packageName, String alias) { 15192 if (packageName == null || alias == null) { 15193 return null; 15194 } 15195 synchronized(mPackages) { 15196 final PackageParser.Package pkg = mPackages.get(packageName); 15197 if (pkg == null) { 15198 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15199 throw new IllegalArgumentException("Unknown package: " + packageName); 15200 } 15201 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15202 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15203 } 15204 } 15205 15206 @Override 15207 public KeySet getSigningKeySet(String packageName) { 15208 if (packageName == null) { 15209 return null; 15210 } 15211 synchronized(mPackages) { 15212 final PackageParser.Package pkg = mPackages.get(packageName); 15213 if (pkg == null) { 15214 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15215 throw new IllegalArgumentException("Unknown package: " + packageName); 15216 } 15217 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15218 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15219 throw new SecurityException("May not access signing KeySet of other apps."); 15220 } 15221 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15222 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15223 } 15224 } 15225 15226 @Override 15227 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15228 if (packageName == null || ks == null) { 15229 return false; 15230 } 15231 synchronized(mPackages) { 15232 final PackageParser.Package pkg = mPackages.get(packageName); 15233 if (pkg == null) { 15234 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15235 throw new IllegalArgumentException("Unknown package: " + packageName); 15236 } 15237 IBinder ksh = ks.getToken(); 15238 if (ksh instanceof KeySetHandle) { 15239 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15240 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15241 } 15242 return false; 15243 } 15244 } 15245 15246 @Override 15247 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15248 if (packageName == null || ks == null) { 15249 return false; 15250 } 15251 synchronized(mPackages) { 15252 final PackageParser.Package pkg = mPackages.get(packageName); 15253 if (pkg == null) { 15254 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15255 throw new IllegalArgumentException("Unknown package: " + packageName); 15256 } 15257 IBinder ksh = ks.getToken(); 15258 if (ksh instanceof KeySetHandle) { 15259 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15260 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15261 } 15262 return false; 15263 } 15264 } 15265 15266 public void getUsageStatsIfNoPackageUsageInfo() { 15267 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15268 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15269 if (usm == null) { 15270 throw new IllegalStateException("UsageStatsManager must be initialized"); 15271 } 15272 long now = System.currentTimeMillis(); 15273 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15274 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15275 String packageName = entry.getKey(); 15276 PackageParser.Package pkg = mPackages.get(packageName); 15277 if (pkg == null) { 15278 continue; 15279 } 15280 UsageStats usage = entry.getValue(); 15281 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15282 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15283 } 15284 } 15285 } 15286 15287 /** 15288 * Check and throw if the given before/after packages would be considered a 15289 * downgrade. 15290 */ 15291 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15292 throws PackageManagerException { 15293 if (after.versionCode < before.mVersionCode) { 15294 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15295 "Update version code " + after.versionCode + " is older than current " 15296 + before.mVersionCode); 15297 } else if (after.versionCode == before.mVersionCode) { 15298 if (after.baseRevisionCode < before.baseRevisionCode) { 15299 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15300 "Update base revision code " + after.baseRevisionCode 15301 + " is older than current " + before.baseRevisionCode); 15302 } 15303 15304 if (!ArrayUtils.isEmpty(after.splitNames)) { 15305 for (int i = 0; i < after.splitNames.length; i++) { 15306 final String splitName = after.splitNames[i]; 15307 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15308 if (j != -1) { 15309 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15310 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15311 "Update split " + splitName + " revision code " 15312 + after.splitRevisionCodes[i] + " is older than current " 15313 + before.splitRevisionCodes[j]); 15314 } 15315 } 15316 } 15317 } 15318 } 15319 } 15320 15321 private static class MoveCallbacks extends Handler { 15322 private static final int MSG_CREATED = 1; 15323 private static final int MSG_STATUS_CHANGED = 2; 15324 15325 private final RemoteCallbackList<IPackageMoveObserver> 15326 mCallbacks = new RemoteCallbackList<>(); 15327 15328 private final SparseIntArray mLastStatus = new SparseIntArray(); 15329 15330 public MoveCallbacks(Looper looper) { 15331 super(looper); 15332 } 15333 15334 public void register(IPackageMoveObserver callback) { 15335 mCallbacks.register(callback); 15336 } 15337 15338 public void unregister(IPackageMoveObserver callback) { 15339 mCallbacks.unregister(callback); 15340 } 15341 15342 @Override 15343 public void handleMessage(Message msg) { 15344 final SomeArgs args = (SomeArgs) msg.obj; 15345 final int n = mCallbacks.beginBroadcast(); 15346 for (int i = 0; i < n; i++) { 15347 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15348 try { 15349 invokeCallback(callback, msg.what, args); 15350 } catch (RemoteException ignored) { 15351 } 15352 } 15353 mCallbacks.finishBroadcast(); 15354 args.recycle(); 15355 } 15356 15357 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15358 throws RemoteException { 15359 switch (what) { 15360 case MSG_CREATED: { 15361 callback.onCreated(args.argi1, (Bundle) args.arg2); 15362 break; 15363 } 15364 case MSG_STATUS_CHANGED: { 15365 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15366 break; 15367 } 15368 } 15369 } 15370 15371 private void notifyCreated(int moveId, Bundle extras) { 15372 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15373 15374 final SomeArgs args = SomeArgs.obtain(); 15375 args.argi1 = moveId; 15376 args.arg2 = extras; 15377 obtainMessage(MSG_CREATED, args).sendToTarget(); 15378 } 15379 15380 private void notifyStatusChanged(int moveId, int status) { 15381 notifyStatusChanged(moveId, status, -1); 15382 } 15383 15384 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15385 Slog.v(TAG, "Move " + moveId + " status " + status); 15386 15387 final SomeArgs args = SomeArgs.obtain(); 15388 args.argi1 = moveId; 15389 args.argi2 = status; 15390 args.arg3 = estMillis; 15391 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15392 15393 synchronized (mLastStatus) { 15394 mLastStatus.put(moveId, status); 15395 } 15396 } 15397 } 15398 15399 private final class OnPermissionChangeListeners extends Handler { 15400 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15401 15402 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15403 new RemoteCallbackList<>(); 15404 15405 public OnPermissionChangeListeners(Looper looper) { 15406 super(looper); 15407 } 15408 15409 @Override 15410 public void handleMessage(Message msg) { 15411 switch (msg.what) { 15412 case MSG_ON_PERMISSIONS_CHANGED: { 15413 final int uid = msg.arg1; 15414 handleOnPermissionsChanged(uid); 15415 } break; 15416 } 15417 } 15418 15419 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15420 mPermissionListeners.register(listener); 15421 15422 } 15423 15424 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15425 mPermissionListeners.unregister(listener); 15426 } 15427 15428 public void onPermissionsChanged(int uid) { 15429 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15430 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15431 } 15432 } 15433 15434 private void handleOnPermissionsChanged(int uid) { 15435 final int count = mPermissionListeners.beginBroadcast(); 15436 try { 15437 for (int i = 0; i < count; i++) { 15438 IOnPermissionsChangeListener callback = mPermissionListeners 15439 .getBroadcastItem(i); 15440 try { 15441 callback.onPermissionsChanged(uid); 15442 } catch (RemoteException e) { 15443 Log.e(TAG, "Permission listener is dead", e); 15444 } 15445 } 15446 } finally { 15447 mPermissionListeners.finishBroadcast(); 15448 } 15449 } 15450 } 15451 15452 private class PackageManagerInternalImpl extends PackageManagerInternal { 15453 @Override 15454 public void setLocationPackagesProvider(PackagesProvider provider) { 15455 synchronized (mPackages) { 15456 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15457 } 15458 } 15459 15460 @Override 15461 public void setImePackagesProvider(PackagesProvider provider) { 15462 synchronized (mPackages) { 15463 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15464 } 15465 } 15466 15467 @Override 15468 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15469 synchronized (mPackages) { 15470 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15471 } 15472 } 15473 } 15474} 15475