PackageManagerService.java revision 9b3890b8dcf18fed6705e0c84fd8cc5fbfe1882d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IOnPermissionsChangeListener; 96import android.content.pm.IPackageDataObserver; 97import android.content.pm.IPackageDeleteObserver; 98import android.content.pm.IPackageDeleteObserver2; 99import android.content.pm.IPackageInstallObserver2; 100import android.content.pm.IPackageInstaller; 101import android.content.pm.IPackageManager; 102import android.content.pm.IPackageMoveObserver; 103import android.content.pm.IPackageStatsObserver; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.IntentFilterVerificationInfo; 106import android.content.pm.KeySet; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 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 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 static final int SCAN_MOVE = 1<<13; 307 308 static final int REMOVE_CHATTY = 1<<16; 309 310 private static final int[] EMPTY_INT_ARRAY = new int[0]; 311 312 /** 313 * Timeout (in milliseconds) after which the watchdog should declare that 314 * our handler thread is wedged. The usual default for such things is one 315 * minute but we sometimes do very lengthy I/O operations on this thread, 316 * such as installing multi-gigabyte applications, so ours needs to be longer. 317 */ 318 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 319 320 /** 321 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 322 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 323 * settings entry if available, otherwise we use the hardcoded default. If it's been 324 * more than this long since the last fstrim, we force one during the boot sequence. 325 * 326 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 327 * one gets run at the next available charging+idle time. This final mandatory 328 * no-fstrim check kicks in only of the other scheduling criteria is never met. 329 */ 330 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 331 332 /** 333 * Whether verification is enabled by default. 334 */ 335 private static final boolean DEFAULT_VERIFY_ENABLE = true; 336 337 /** 338 * The default maximum time to wait for the verification agent to return in 339 * milliseconds. 340 */ 341 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 342 343 /** 344 * The default response for package verification timeout. 345 * 346 * This can be either PackageManager.VERIFICATION_ALLOW or 347 * PackageManager.VERIFICATION_REJECT. 348 */ 349 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 350 351 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 352 353 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 354 DEFAULT_CONTAINER_PACKAGE, 355 "com.android.defcontainer.DefaultContainerService"); 356 357 private static final String KILL_APP_REASON_GIDS_CHANGED = 358 "permission grant or revoke changed gids"; 359 360 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 361 "permissions revoked"; 362 363 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 364 365 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 366 367 /** Permission grant: not grant the permission. */ 368 private static final int GRANT_DENIED = 1; 369 370 /** Permission grant: grant the permission as an install permission. */ 371 private static final int GRANT_INSTALL = 2; 372 373 /** Permission grant: grant the permission as an install permission for a legacy app. */ 374 private static final int GRANT_INSTALL_LEGACY = 3; 375 376 /** Permission grant: grant the permission as a runtime one. */ 377 private static final int GRANT_RUNTIME = 4; 378 379 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 380 private static final int GRANT_UPGRADE = 5; 381 382 final ServiceThread mHandlerThread; 383 384 final PackageHandler mHandler; 385 386 /** 387 * Messages for {@link #mHandler} that need to wait for system ready before 388 * being dispatched. 389 */ 390 private ArrayList<Message> mPostSystemReadyMessages; 391 392 final int mSdkVersion = Build.VERSION.SDK_INT; 393 394 final Context mContext; 395 final boolean mFactoryTest; 396 final boolean mOnlyCore; 397 final boolean mLazyDexOpt; 398 final long mDexOptLRUThresholdInMills; 399 final DisplayMetrics mMetrics; 400 final int mDefParseFlags; 401 final String[] mSeparateProcesses; 402 final boolean mIsUpgrade; 403 404 // This is where all application persistent data goes. 405 final File mAppDataDir; 406 407 // This is where all application persistent data goes for secondary users. 408 final File mUserAppDataDir; 409 410 /** The location for ASEC container files on internal storage. */ 411 final String mAsecInternalPath; 412 413 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 414 // LOCK HELD. Can be called with mInstallLock held. 415 final Installer mInstaller; 416 417 /** Directory where installed third-party apps stored */ 418 final File mAppInstallDir; 419 420 /** 421 * Directory to which applications installed internally have their 422 * 32 bit native libraries copied. 423 */ 424 private File mAppLib32InstallDir; 425 426 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 427 // apps. 428 final File mDrmAppPrivateInstallDir; 429 430 // ---------------------------------------------------------------- 431 432 // Lock for state used when installing and doing other long running 433 // operations. Methods that must be called with this lock held have 434 // the suffix "LI". 435 final Object mInstallLock = new Object(); 436 437 // ---------------------------------------------------------------- 438 439 // Keys are String (package name), values are Package. This also serves 440 // as the lock for the global state. Methods that must be called with 441 // this lock held have the prefix "LP". 442 final ArrayMap<String, PackageParser.Package> mPackages = 443 new ArrayMap<String, PackageParser.Package>(); 444 445 // Tracks available target package names -> overlay package paths. 446 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 447 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 448 449 final Settings mSettings; 450 boolean mRestoredSettings; 451 452 // System configuration read by SystemConfig. 453 final int[] mGlobalGids; 454 final SparseArray<ArraySet<String>> mSystemPermissions; 455 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 456 457 // If mac_permissions.xml was found for seinfo labeling. 458 boolean mFoundPolicyFile; 459 460 // If a recursive restorecon of /data/data/<pkg> is needed. 461 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 462 463 public static final class SharedLibraryEntry { 464 public final String path; 465 public final String apk; 466 467 SharedLibraryEntry(String _path, String _apk) { 468 path = _path; 469 apk = _apk; 470 } 471 } 472 473 // Currently known shared libraries. 474 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 475 new ArrayMap<String, SharedLibraryEntry>(); 476 477 // All available activities, for your resolving pleasure. 478 final ActivityIntentResolver mActivities = 479 new ActivityIntentResolver(); 480 481 // All available receivers, for your resolving pleasure. 482 final ActivityIntentResolver mReceivers = 483 new ActivityIntentResolver(); 484 485 // All available services, for your resolving pleasure. 486 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 487 488 // All available providers, for your resolving pleasure. 489 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 490 491 // Mapping from provider base names (first directory in content URI codePath) 492 // to the provider information. 493 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 494 new ArrayMap<String, PackageParser.Provider>(); 495 496 // Mapping from instrumentation class names to info about them. 497 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 498 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 499 500 // Mapping from permission names to info about them. 501 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 502 new ArrayMap<String, PackageParser.PermissionGroup>(); 503 504 // Packages whose data we have transfered into another package, thus 505 // should no longer exist. 506 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 507 508 // Broadcast actions that are only available to the system. 509 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 510 511 /** List of packages waiting for verification. */ 512 final SparseArray<PackageVerificationState> mPendingVerification 513 = new SparseArray<PackageVerificationState>(); 514 515 /** Set of packages associated with each app op permission. */ 516 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 517 518 final PackageInstallerService mInstallerService; 519 520 private final PackageDexOptimizer mPackageDexOptimizer; 521 522 private AtomicInteger mNextMoveId = new AtomicInteger(); 523 private final MoveCallbacks mMoveCallbacks; 524 525 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 526 527 // Cache of users who need badging. 528 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 529 530 /** Token for keys in mPendingVerification. */ 531 private int mPendingVerificationToken = 0; 532 533 volatile boolean mSystemReady; 534 volatile boolean mSafeMode; 535 volatile boolean mHasSystemUidErrors; 536 537 ApplicationInfo mAndroidApplication; 538 final ActivityInfo mResolveActivity = new ActivityInfo(); 539 final ResolveInfo mResolveInfo = new ResolveInfo(); 540 ComponentName mResolveComponentName; 541 PackageParser.Package mPlatformPackage; 542 ComponentName mCustomResolverComponentName; 543 544 boolean mResolverReplaced = false; 545 546 private final ComponentName mIntentFilterVerifierComponent; 547 private int mIntentFilterVerificationToken = 0; 548 549 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 550 = new SparseArray<IntentFilterVerificationState>(); 551 552 private interface IntentFilterVerifier<T extends IntentFilter> { 553 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 554 T filter, String packageName); 555 void startVerifications(int userId); 556 void receiveVerificationResponse(int verificationId); 557 } 558 559 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 560 private Context mContext; 561 private ComponentName mIntentFilterVerifierComponent; 562 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 563 564 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 565 mContext = context; 566 mIntentFilterVerifierComponent = verifierComponent; 567 } 568 569 private String getDefaultScheme() { 570 return IntentFilter.SCHEME_HTTPS; 571 } 572 573 @Override 574 public void startVerifications(int userId) { 575 // Launch verifications requests 576 int count = mCurrentIntentFilterVerifications.size(); 577 for (int n=0; n<count; n++) { 578 int verificationId = mCurrentIntentFilterVerifications.get(n); 579 final IntentFilterVerificationState ivs = 580 mIntentFilterVerificationStates.get(verificationId); 581 582 String packageName = ivs.getPackageName(); 583 584 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 585 final int filterCount = filters.size(); 586 ArraySet<String> domainsSet = new ArraySet<>(); 587 for (int m=0; m<filterCount; m++) { 588 PackageParser.ActivityIntentInfo filter = filters.get(m); 589 domainsSet.addAll(filter.getHostsList()); 590 } 591 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 592 synchronized (mPackages) { 593 if (mSettings.createIntentFilterVerificationIfNeededLPw( 594 packageName, domainsList) != null) { 595 scheduleWriteSettingsLocked(); 596 } 597 } 598 sendVerificationRequest(userId, verificationId, ivs); 599 } 600 mCurrentIntentFilterVerifications.clear(); 601 } 602 603 private void sendVerificationRequest(int userId, int verificationId, 604 IntentFilterVerificationState ivs) { 605 606 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 609 verificationId); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 612 getDefaultScheme()); 613 verificationIntent.putExtra( 614 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 615 ivs.getHostsString()); 616 verificationIntent.putExtra( 617 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 618 ivs.getPackageName()); 619 verificationIntent.setComponent(mIntentFilterVerifierComponent); 620 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 621 622 UserHandle user = new UserHandle(userId); 623 mContext.sendBroadcastAsUser(verificationIntent, user); 624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 625 "Sending IntenFilter verification broadcast"); 626 } 627 628 public void receiveVerificationResponse(int verificationId) { 629 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 630 631 final boolean verified = ivs.isVerified(); 632 633 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 634 final int count = filters.size(); 635 for (int n=0; n<count; n++) { 636 PackageParser.ActivityIntentInfo filter = filters.get(n); 637 filter.setVerified(verified); 638 639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 640 + " verified with result:" + verified + " and hosts:" 641 + ivs.getHostsString()); 642 } 643 644 mIntentFilterVerificationStates.remove(verificationId); 645 646 final String packageName = ivs.getPackageName(); 647 IntentFilterVerificationInfo ivi = null; 648 649 synchronized (mPackages) { 650 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 651 } 652 if (ivi == null) { 653 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 654 + verificationId + " packageName:" + packageName); 655 return; 656 } 657 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 658 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 659 660 synchronized (mPackages) { 661 if (verified) { 662 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 663 } else { 664 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 665 } 666 scheduleWriteSettingsLocked(); 667 668 final int userId = ivs.getUserId(); 669 if (userId != UserHandle.USER_ALL) { 670 final int userStatus = 671 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 672 673 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 674 boolean needUpdate = false; 675 676 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 677 // already been set by the User thru the Disambiguation dialog 678 switch (userStatus) { 679 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 680 if (verified) { 681 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 682 } else { 683 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 684 } 685 needUpdate = true; 686 break; 687 688 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 689 if (verified) { 690 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 691 needUpdate = true; 692 } 693 break; 694 695 default: 696 // Nothing to do 697 } 698 699 if (needUpdate) { 700 mSettings.updateIntentFilterVerificationStatusLPw( 701 packageName, updatedStatus, userId); 702 scheduleWritePackageRestrictionsLocked(userId); 703 } 704 } 705 } 706 } 707 708 @Override 709 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 710 ActivityIntentInfo filter, String packageName) { 711 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 712 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 714 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 715 return false; 716 } 717 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 718 if (ivs == null) { 719 ivs = createDomainVerificationState(verifierId, userId, verificationId, 720 packageName); 721 } 722 if (!hasValidDomains(filter)) { 723 return false; 724 } 725 ivs.addFilter(filter); 726 return true; 727 } 728 729 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 730 int userId, int verificationId, String packageName) { 731 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 732 verifierId, userId, packageName); 733 ivs.setPendingState(); 734 synchronized (mPackages) { 735 mIntentFilterVerificationStates.append(verificationId, ivs); 736 mCurrentIntentFilterVerifications.add(verificationId); 737 } 738 return ivs; 739 } 740 } 741 742 private static boolean hasValidDomains(ActivityIntentInfo filter) { 743 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 744 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 745 if (!hasHTTPorHTTPS) { 746 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 747 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 748 return false; 749 } 750 return true; 751 } 752 753 private IntentFilterVerifier mIntentFilterVerifier; 754 755 // Set of pending broadcasts for aggregating enable/disable of components. 756 static class PendingPackageBroadcasts { 757 // for each user id, a map of <package name -> components within that package> 758 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 759 760 public PendingPackageBroadcasts() { 761 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 762 } 763 764 public ArrayList<String> get(int userId, String packageName) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 return packages.get(packageName); 767 } 768 769 public void put(int userId, String packageName, ArrayList<String> components) { 770 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 771 packages.put(packageName, components); 772 } 773 774 public void remove(int userId, String packageName) { 775 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 776 if (packages != null) { 777 packages.remove(packageName); 778 } 779 } 780 781 public void remove(int userId) { 782 mUidMap.remove(userId); 783 } 784 785 public int userIdCount() { 786 return mUidMap.size(); 787 } 788 789 public int userIdAt(int n) { 790 return mUidMap.keyAt(n); 791 } 792 793 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 794 return mUidMap.get(userId); 795 } 796 797 public int size() { 798 // total number of pending broadcast entries across all userIds 799 int num = 0; 800 for (int i = 0; i< mUidMap.size(); i++) { 801 num += mUidMap.valueAt(i).size(); 802 } 803 return num; 804 } 805 806 public void clear() { 807 mUidMap.clear(); 808 } 809 810 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 811 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 812 if (map == null) { 813 map = new ArrayMap<String, ArrayList<String>>(); 814 mUidMap.put(userId, map); 815 } 816 return map; 817 } 818 } 819 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 820 821 // Service Connection to remote media container service to copy 822 // package uri's from external media onto secure containers 823 // or internal storage. 824 private IMediaContainerService mContainerService = null; 825 826 static final int SEND_PENDING_BROADCAST = 1; 827 static final int MCS_BOUND = 3; 828 static final int END_COPY = 4; 829 static final int INIT_COPY = 5; 830 static final int MCS_UNBIND = 6; 831 static final int START_CLEANING_PACKAGE = 7; 832 static final int FIND_INSTALL_LOC = 8; 833 static final int POST_INSTALL = 9; 834 static final int MCS_RECONNECT = 10; 835 static final int MCS_GIVE_UP = 11; 836 static final int UPDATED_MEDIA_STATUS = 12; 837 static final int WRITE_SETTINGS = 13; 838 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 839 static final int PACKAGE_VERIFIED = 15; 840 static final int CHECK_PENDING_VERIFICATION = 16; 841 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 842 static final int INTENT_FILTER_VERIFIED = 18; 843 844 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 845 846 // Delay time in millisecs 847 static final int BROADCAST_DELAY = 10 * 1000; 848 849 static UserManagerService sUserManager; 850 851 // Stores a list of users whose package restrictions file needs to be updated 852 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 853 854 final private DefaultContainerConnection mDefContainerConn = 855 new DefaultContainerConnection(); 856 class DefaultContainerConnection implements ServiceConnection { 857 public void onServiceConnected(ComponentName name, IBinder service) { 858 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 859 IMediaContainerService imcs = 860 IMediaContainerService.Stub.asInterface(service); 861 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 862 } 863 864 public void onServiceDisconnected(ComponentName name) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 866 } 867 }; 868 869 // Recordkeeping of restore-after-install operations that are currently in flight 870 // between the Package Manager and the Backup Manager 871 class PostInstallData { 872 public InstallArgs args; 873 public PackageInstalledInfo res; 874 875 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 876 args = _a; 877 res = _r; 878 } 879 }; 880 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 881 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 882 883 // backup/restore of preferred activity state 884 private static final String TAG_PREFERRED_BACKUP = "pa"; 885 886 private final String mRequiredVerifierPackage; 887 888 private final PackageUsage mPackageUsage = new PackageUsage(); 889 890 private class PackageUsage { 891 private static final int WRITE_INTERVAL 892 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 893 894 private final Object mFileLock = new Object(); 895 private final AtomicLong mLastWritten = new AtomicLong(0); 896 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 897 898 private boolean mIsHistoricalPackageUsageAvailable = true; 899 900 boolean isHistoricalPackageUsageAvailable() { 901 return mIsHistoricalPackageUsageAvailable; 902 } 903 904 void write(boolean force) { 905 if (force) { 906 writeInternal(); 907 return; 908 } 909 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 910 && !DEBUG_DEXOPT) { 911 return; 912 } 913 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 914 new Thread("PackageUsage_DiskWriter") { 915 @Override 916 public void run() { 917 try { 918 writeInternal(); 919 } finally { 920 mBackgroundWriteRunning.set(false); 921 } 922 } 923 }.start(); 924 } 925 } 926 927 private void writeInternal() { 928 synchronized (mPackages) { 929 synchronized (mFileLock) { 930 AtomicFile file = getFile(); 931 FileOutputStream f = null; 932 try { 933 f = file.startWrite(); 934 BufferedOutputStream out = new BufferedOutputStream(f); 935 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 936 StringBuilder sb = new StringBuilder(); 937 for (PackageParser.Package pkg : mPackages.values()) { 938 if (pkg.mLastPackageUsageTimeInMills == 0) { 939 continue; 940 } 941 sb.setLength(0); 942 sb.append(pkg.packageName); 943 sb.append(' '); 944 sb.append((long)pkg.mLastPackageUsageTimeInMills); 945 sb.append('\n'); 946 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 947 } 948 out.flush(); 949 file.finishWrite(f); 950 } catch (IOException e) { 951 if (f != null) { 952 file.failWrite(f); 953 } 954 Log.e(TAG, "Failed to write package usage times", e); 955 } 956 } 957 } 958 mLastWritten.set(SystemClock.elapsedRealtime()); 959 } 960 961 void readLP() { 962 synchronized (mFileLock) { 963 AtomicFile file = getFile(); 964 BufferedInputStream in = null; 965 try { 966 in = new BufferedInputStream(file.openRead()); 967 StringBuffer sb = new StringBuffer(); 968 while (true) { 969 String packageName = readToken(in, sb, ' '); 970 if (packageName == null) { 971 break; 972 } 973 String timeInMillisString = readToken(in, sb, '\n'); 974 if (timeInMillisString == null) { 975 throw new IOException("Failed to find last usage time for package " 976 + packageName); 977 } 978 PackageParser.Package pkg = mPackages.get(packageName); 979 if (pkg == null) { 980 continue; 981 } 982 long timeInMillis; 983 try { 984 timeInMillis = Long.parseLong(timeInMillisString.toString()); 985 } catch (NumberFormatException e) { 986 throw new IOException("Failed to parse " + timeInMillisString 987 + " as a long.", e); 988 } 989 pkg.mLastPackageUsageTimeInMills = timeInMillis; 990 } 991 } catch (FileNotFoundException expected) { 992 mIsHistoricalPackageUsageAvailable = false; 993 } catch (IOException e) { 994 Log.w(TAG, "Failed to read package usage times", e); 995 } finally { 996 IoUtils.closeQuietly(in); 997 } 998 } 999 mLastWritten.set(SystemClock.elapsedRealtime()); 1000 } 1001 1002 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1003 throws IOException { 1004 sb.setLength(0); 1005 while (true) { 1006 int ch = in.read(); 1007 if (ch == -1) { 1008 if (sb.length() == 0) { 1009 return null; 1010 } 1011 throw new IOException("Unexpected EOF"); 1012 } 1013 if (ch == endOfToken) { 1014 return sb.toString(); 1015 } 1016 sb.append((char)ch); 1017 } 1018 } 1019 1020 private AtomicFile getFile() { 1021 File dataDir = Environment.getDataDirectory(); 1022 File systemDir = new File(dataDir, "system"); 1023 File fname = new File(systemDir, "package-usage.list"); 1024 return new AtomicFile(fname); 1025 } 1026 } 1027 1028 class PackageHandler extends Handler { 1029 private boolean mBound = false; 1030 final ArrayList<HandlerParams> mPendingInstalls = 1031 new ArrayList<HandlerParams>(); 1032 1033 private boolean connectToService() { 1034 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1035 " DefaultContainerService"); 1036 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1038 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1039 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 mBound = true; 1042 return true; 1043 } 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 return false; 1046 } 1047 1048 private void disconnectService() { 1049 mContainerService = null; 1050 mBound = false; 1051 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1052 mContext.unbindService(mDefContainerConn); 1053 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1054 } 1055 1056 PackageHandler(Looper looper) { 1057 super(looper); 1058 } 1059 1060 public void handleMessage(Message msg) { 1061 try { 1062 doHandleMessage(msg); 1063 } finally { 1064 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1065 } 1066 } 1067 1068 void doHandleMessage(Message msg) { 1069 switch (msg.what) { 1070 case INIT_COPY: { 1071 HandlerParams params = (HandlerParams) msg.obj; 1072 int idx = mPendingInstalls.size(); 1073 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1074 // If a bind was already initiated we dont really 1075 // need to do anything. The pending install 1076 // will be processed later on. 1077 if (!mBound) { 1078 // If this is the only one pending we might 1079 // have to bind to the service again. 1080 if (!connectToService()) { 1081 Slog.e(TAG, "Failed to bind to media container service"); 1082 params.serviceError(); 1083 return; 1084 } else { 1085 // Once we bind to the service, the first 1086 // pending request will be processed. 1087 mPendingInstalls.add(idx, params); 1088 } 1089 } else { 1090 mPendingInstalls.add(idx, params); 1091 // Already bound to the service. Just make 1092 // sure we trigger off processing the first request. 1093 if (idx == 0) { 1094 mHandler.sendEmptyMessage(MCS_BOUND); 1095 } 1096 } 1097 break; 1098 } 1099 case MCS_BOUND: { 1100 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1101 if (msg.obj != null) { 1102 mContainerService = (IMediaContainerService) msg.obj; 1103 } 1104 if (mContainerService == null) { 1105 // Something seriously wrong. Bail out 1106 Slog.e(TAG, "Cannot bind to media container service"); 1107 for (HandlerParams params : mPendingInstalls) { 1108 // Indicate service bind error 1109 params.serviceError(); 1110 } 1111 mPendingInstalls.clear(); 1112 } else if (mPendingInstalls.size() > 0) { 1113 HandlerParams params = mPendingInstalls.get(0); 1114 if (params != null) { 1115 if (params.startCopy()) { 1116 // We are done... look for more work or to 1117 // go idle. 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Checking for more work or unbind..."); 1120 // Delete pending install 1121 if (mPendingInstalls.size() > 0) { 1122 mPendingInstalls.remove(0); 1123 } 1124 if (mPendingInstalls.size() == 0) { 1125 if (mBound) { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, 1127 "Posting delayed MCS_UNBIND"); 1128 removeMessages(MCS_UNBIND); 1129 Message ubmsg = obtainMessage(MCS_UNBIND); 1130 // Unbind after a little delay, to avoid 1131 // continual thrashing. 1132 sendMessageDelayed(ubmsg, 10000); 1133 } 1134 } else { 1135 // There are more pending requests in queue. 1136 // Just post MCS_BOUND message to trigger processing 1137 // of next pending install. 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, 1139 "Posting MCS_BOUND for next work"); 1140 mHandler.sendEmptyMessage(MCS_BOUND); 1141 } 1142 } 1143 } 1144 } else { 1145 // Should never happen ideally. 1146 Slog.w(TAG, "Empty queue"); 1147 } 1148 break; 1149 } 1150 case MCS_RECONNECT: { 1151 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1152 if (mPendingInstalls.size() > 0) { 1153 if (mBound) { 1154 disconnectService(); 1155 } 1156 if (!connectToService()) { 1157 Slog.e(TAG, "Failed to bind to media container service"); 1158 for (HandlerParams params : mPendingInstalls) { 1159 // Indicate service bind error 1160 params.serviceError(); 1161 } 1162 mPendingInstalls.clear(); 1163 } 1164 } 1165 break; 1166 } 1167 case MCS_UNBIND: { 1168 // If there is no actual work left, then time to unbind. 1169 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1170 1171 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1172 if (mBound) { 1173 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1174 1175 disconnectService(); 1176 } 1177 } else if (mPendingInstalls.size() > 0) { 1178 // There are more pending requests in queue. 1179 // Just post MCS_BOUND message to trigger processing 1180 // of next pending install. 1181 mHandler.sendEmptyMessage(MCS_BOUND); 1182 } 1183 1184 break; 1185 } 1186 case MCS_GIVE_UP: { 1187 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1188 mPendingInstalls.remove(0); 1189 break; 1190 } 1191 case SEND_PENDING_BROADCAST: { 1192 String packages[]; 1193 ArrayList<String> components[]; 1194 int size = 0; 1195 int uids[]; 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1197 synchronized (mPackages) { 1198 if (mPendingBroadcasts == null) { 1199 return; 1200 } 1201 size = mPendingBroadcasts.size(); 1202 if (size <= 0) { 1203 // Nothing to be done. Just return 1204 return; 1205 } 1206 packages = new String[size]; 1207 components = new ArrayList[size]; 1208 uids = new int[size]; 1209 int i = 0; // filling out the above arrays 1210 1211 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1212 int packageUserId = mPendingBroadcasts.userIdAt(n); 1213 Iterator<Map.Entry<String, ArrayList<String>>> it 1214 = mPendingBroadcasts.packagesForUserId(packageUserId) 1215 .entrySet().iterator(); 1216 while (it.hasNext() && i < size) { 1217 Map.Entry<String, ArrayList<String>> ent = it.next(); 1218 packages[i] = ent.getKey(); 1219 components[i] = ent.getValue(); 1220 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1221 uids[i] = (ps != null) 1222 ? UserHandle.getUid(packageUserId, ps.appId) 1223 : -1; 1224 i++; 1225 } 1226 } 1227 size = i; 1228 mPendingBroadcasts.clear(); 1229 } 1230 // Send broadcasts 1231 for (int i = 0; i < size; i++) { 1232 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1233 } 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1235 break; 1236 } 1237 case START_CLEANING_PACKAGE: { 1238 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1239 final String packageName = (String)msg.obj; 1240 final int userId = msg.arg1; 1241 final boolean andCode = msg.arg2 != 0; 1242 synchronized (mPackages) { 1243 if (userId == UserHandle.USER_ALL) { 1244 int[] users = sUserManager.getUserIds(); 1245 for (int user : users) { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(user, packageName, andCode)); 1248 } 1249 } else { 1250 mSettings.addPackageToCleanLPw( 1251 new PackageCleanItem(userId, packageName, andCode)); 1252 } 1253 } 1254 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1255 startCleaningPackages(); 1256 } break; 1257 case POST_INSTALL: { 1258 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1259 PostInstallData data = mRunningInstalls.get(msg.arg1); 1260 mRunningInstalls.delete(msg.arg1); 1261 boolean deleteOld = false; 1262 1263 if (data != null) { 1264 InstallArgs args = data.args; 1265 PackageInstalledInfo res = data.res; 1266 1267 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1268 res.removedInfo.sendBroadcast(false, true, false); 1269 Bundle extras = new Bundle(1); 1270 extras.putInt(Intent.EXTRA_UID, res.uid); 1271 1272 // Now that we successfully installed the package, grant runtime 1273 // permissions if requested before broadcasting the install. 1274 if ((args.installFlags 1275 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1276 grantRequestedRuntimePermissions(res.pkg, 1277 args.user.getIdentifier()); 1278 } 1279 1280 // Determine the set of users who are adding this 1281 // package for the first time vs. those who are seeing 1282 // an update. 1283 int[] firstUsers; 1284 int[] updateUsers = new int[0]; 1285 if (res.origUsers == null || res.origUsers.length == 0) { 1286 firstUsers = res.newUsers; 1287 } else { 1288 firstUsers = new int[0]; 1289 for (int i=0; i<res.newUsers.length; i++) { 1290 int user = res.newUsers[i]; 1291 boolean isNew = true; 1292 for (int j=0; j<res.origUsers.length; j++) { 1293 if (res.origUsers[j] == user) { 1294 isNew = false; 1295 break; 1296 } 1297 } 1298 if (isNew) { 1299 int[] newFirst = new int[firstUsers.length+1]; 1300 System.arraycopy(firstUsers, 0, newFirst, 0, 1301 firstUsers.length); 1302 newFirst[firstUsers.length] = user; 1303 firstUsers = newFirst; 1304 } else { 1305 int[] newUpdate = new int[updateUsers.length+1]; 1306 System.arraycopy(updateUsers, 0, newUpdate, 0, 1307 updateUsers.length); 1308 newUpdate[updateUsers.length] = user; 1309 updateUsers = newUpdate; 1310 } 1311 } 1312 } 1313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1314 res.pkg.applicationInfo.packageName, 1315 extras, null, null, firstUsers); 1316 final boolean update = res.removedInfo.removedPackage != null; 1317 if (update) { 1318 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1319 } 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 if (update) { 1324 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1325 res.pkg.applicationInfo.packageName, 1326 extras, null, null, updateUsers); 1327 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1328 null, null, 1329 res.pkg.applicationInfo.packageName, null, updateUsers); 1330 1331 // treat asec-hosted packages like removable media on upgrade 1332 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1333 if (DEBUG_INSTALL) { 1334 Slog.i(TAG, "upgrading pkg " + res.pkg 1335 + " is ASEC-hosted -> AVAILABLE"); 1336 } 1337 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1338 ArrayList<String> pkgList = new ArrayList<String>(1); 1339 pkgList.add(res.pkg.applicationInfo.packageName); 1340 sendResourcesChangedBroadcast(true, true, 1341 pkgList,uidArray, null); 1342 } 1343 } 1344 if (res.removedInfo.args != null) { 1345 // Remove the replaced package's older resources safely now 1346 deleteOld = true; 1347 } 1348 1349 // Log current value of "unknown sources" setting 1350 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1351 getUnknownSourcesSettings()); 1352 } 1353 // Force a gc to clear up things 1354 Runtime.getRuntime().gc(); 1355 // We delete after a gc for applications on sdcard. 1356 if (deleteOld) { 1357 synchronized (mInstallLock) { 1358 res.removedInfo.args.doPostDeleteLI(true); 1359 } 1360 } 1361 if (args.observer != null) { 1362 try { 1363 Bundle extras = extrasForInstallResult(res); 1364 args.observer.onPackageInstalled(res.name, res.returnCode, 1365 res.returnMsg, extras); 1366 } catch (RemoteException e) { 1367 Slog.i(TAG, "Observer no longer exists."); 1368 } 1369 } 1370 } else { 1371 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1372 } 1373 } break; 1374 case UPDATED_MEDIA_STATUS: { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1376 boolean reportStatus = msg.arg1 == 1; 1377 boolean doGc = msg.arg2 == 1; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1379 if (doGc) { 1380 // Force a gc to clear up stale containers. 1381 Runtime.getRuntime().gc(); 1382 } 1383 if (msg.obj != null) { 1384 @SuppressWarnings("unchecked") 1385 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1387 // Unload containers 1388 unloadAllContainers(args); 1389 } 1390 if (reportStatus) { 1391 try { 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1393 PackageHelper.getMountService().finishMediaUpdate(); 1394 } catch (RemoteException e) { 1395 Log.e(TAG, "MountService not running?"); 1396 } 1397 } 1398 } break; 1399 case WRITE_SETTINGS: { 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1401 synchronized (mPackages) { 1402 removeMessages(WRITE_SETTINGS); 1403 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1404 mSettings.writeLPr(); 1405 mDirtyUsers.clear(); 1406 } 1407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1408 } break; 1409 case WRITE_PACKAGE_RESTRICTIONS: { 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1411 synchronized (mPackages) { 1412 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1413 for (int userId : mDirtyUsers) { 1414 mSettings.writePackageRestrictionsLPr(userId); 1415 } 1416 mDirtyUsers.clear(); 1417 } 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1419 } break; 1420 case CHECK_PENDING_VERIFICATION: { 1421 final int verificationId = msg.arg1; 1422 final PackageVerificationState state = mPendingVerification.get(verificationId); 1423 1424 if ((state != null) && !state.timeoutExtended()) { 1425 final InstallArgs args = state.getInstallArgs(); 1426 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1427 1428 Slog.i(TAG, "Verification timed out for " + originUri); 1429 mPendingVerification.remove(verificationId); 1430 1431 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1432 1433 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1434 Slog.i(TAG, "Continuing with installation of " + originUri); 1435 state.setVerifierResponse(Binder.getCallingUid(), 1436 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1437 broadcastPackageVerified(verificationId, originUri, 1438 PackageManager.VERIFICATION_ALLOW, 1439 state.getInstallArgs().getUser()); 1440 try { 1441 ret = args.copyApk(mContainerService, true); 1442 } catch (RemoteException e) { 1443 Slog.e(TAG, "Could not contact the ContainerService"); 1444 } 1445 } else { 1446 broadcastPackageVerified(verificationId, originUri, 1447 PackageManager.VERIFICATION_REJECT, 1448 state.getInstallArgs().getUser()); 1449 } 1450 1451 processPendingInstall(args, ret); 1452 mHandler.sendEmptyMessage(MCS_UNBIND); 1453 } 1454 break; 1455 } 1456 case PACKAGE_VERIFIED: { 1457 final int verificationId = msg.arg1; 1458 1459 final PackageVerificationState state = mPendingVerification.get(verificationId); 1460 if (state == null) { 1461 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1462 break; 1463 } 1464 1465 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1466 1467 state.setVerifierResponse(response.callerUid, response.code); 1468 1469 if (state.isVerificationComplete()) { 1470 mPendingVerification.remove(verificationId); 1471 1472 final InstallArgs args = state.getInstallArgs(); 1473 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1474 1475 int ret; 1476 if (state.isInstallAllowed()) { 1477 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1478 broadcastPackageVerified(verificationId, originUri, 1479 response.code, state.getInstallArgs().getUser()); 1480 try { 1481 ret = args.copyApk(mContainerService, true); 1482 } catch (RemoteException e) { 1483 Slog.e(TAG, "Could not contact the ContainerService"); 1484 } 1485 } else { 1486 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1487 } 1488 1489 processPendingInstall(args, ret); 1490 1491 mHandler.sendEmptyMessage(MCS_UNBIND); 1492 } 1493 1494 break; 1495 } 1496 case START_INTENT_FILTER_VERIFICATIONS: { 1497 int userId = msg.arg1; 1498 int verifierUid = msg.arg2; 1499 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1500 1501 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1502 break; 1503 } 1504 case INTENT_FILTER_VERIFIED: { 1505 final int verificationId = msg.arg1; 1506 1507 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1508 verificationId); 1509 if (state == null) { 1510 Slog.w(TAG, "Invalid IntentFilter verification token " 1511 + verificationId + " received"); 1512 break; 1513 } 1514 1515 final int userId = state.getUserId(); 1516 1517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1518 "Processing IntentFilter verification with token:" 1519 + verificationId + " and userId:" + userId); 1520 1521 final IntentFilterVerificationResponse response = 1522 (IntentFilterVerificationResponse) msg.obj; 1523 1524 state.setVerifierResponse(response.callerUid, response.code); 1525 1526 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1527 "IntentFilter verification with token:" + verificationId 1528 + " and userId:" + userId 1529 + " is settings verifier response with response code:" 1530 + response.code); 1531 1532 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1533 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1534 + response.getFailedDomainsString()); 1535 } 1536 1537 if (state.isVerificationComplete()) { 1538 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1539 } else { 1540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1541 "IntentFilter verification with token:" + verificationId 1542 + " was not said to be complete"); 1543 } 1544 1545 break; 1546 } 1547 } 1548 } 1549 } 1550 1551 private StorageEventListener mStorageListener = new StorageEventListener() { 1552 @Override 1553 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1554 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1555 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1556 // TODO: ensure that private directories exist for all active users 1557 // TODO: remove user data whose serial number doesn't match 1558 loadPrivatePackages(vol); 1559 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1560 unloadPrivatePackages(vol); 1561 } 1562 } 1563 1564 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1565 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1566 updateExternalMediaStatus(true, false); 1567 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1568 updateExternalMediaStatus(false, false); 1569 } 1570 } 1571 } 1572 1573 @Override 1574 public void onVolumeForgotten(String fsUuid) { 1575 // TODO: remove all packages hosted on this uuid 1576 } 1577 }; 1578 1579 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1580 if (userId >= UserHandle.USER_OWNER) { 1581 grantRequestedRuntimePermissionsForUser(pkg, userId); 1582 } else if (userId == UserHandle.USER_ALL) { 1583 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1584 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1585 } 1586 } 1587 1588 // We could have touched GID membership, so flush out packages.list 1589 synchronized (mPackages) { 1590 mSettings.writePackageListLPr(); 1591 } 1592 } 1593 1594 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1595 SettingBase sb = (SettingBase) pkg.mExtras; 1596 if (sb == null) { 1597 return; 1598 } 1599 1600 PermissionsState permissionsState = sb.getPermissionsState(); 1601 1602 for (String permission : pkg.requestedPermissions) { 1603 BasePermission bp = mSettings.mPermissions.get(permission); 1604 if (bp != null && bp.isRuntime()) { 1605 permissionsState.grantRuntimePermission(bp, userId); 1606 } 1607 } 1608 } 1609 1610 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1611 Bundle extras = null; 1612 switch (res.returnCode) { 1613 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1614 extras = new Bundle(); 1615 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1616 res.origPermission); 1617 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1618 res.origPackage); 1619 break; 1620 } 1621 case PackageManager.INSTALL_SUCCEEDED: { 1622 extras = new Bundle(); 1623 extras.putBoolean(Intent.EXTRA_REPLACING, 1624 res.removedInfo != null && res.removedInfo.removedPackage != null); 1625 break; 1626 } 1627 } 1628 return extras; 1629 } 1630 1631 void scheduleWriteSettingsLocked() { 1632 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1633 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1634 } 1635 } 1636 1637 void scheduleWritePackageRestrictionsLocked(int userId) { 1638 if (!sUserManager.exists(userId)) return; 1639 mDirtyUsers.add(userId); 1640 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1641 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1642 } 1643 } 1644 1645 public static PackageManagerService main(Context context, Installer installer, 1646 boolean factoryTest, boolean onlyCore) { 1647 PackageManagerService m = new PackageManagerService(context, installer, 1648 factoryTest, onlyCore); 1649 ServiceManager.addService("package", m); 1650 return m; 1651 } 1652 1653 static String[] splitString(String str, char sep) { 1654 int count = 1; 1655 int i = 0; 1656 while ((i=str.indexOf(sep, i)) >= 0) { 1657 count++; 1658 i++; 1659 } 1660 1661 String[] res = new String[count]; 1662 i=0; 1663 count = 0; 1664 int lastI=0; 1665 while ((i=str.indexOf(sep, i)) >= 0) { 1666 res[count] = str.substring(lastI, i); 1667 count++; 1668 i++; 1669 lastI = i; 1670 } 1671 res[count] = str.substring(lastI, str.length()); 1672 return res; 1673 } 1674 1675 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1676 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1677 Context.DISPLAY_SERVICE); 1678 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1679 } 1680 1681 public PackageManagerService(Context context, Installer installer, 1682 boolean factoryTest, boolean onlyCore) { 1683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1684 SystemClock.uptimeMillis()); 1685 1686 if (mSdkVersion <= 0) { 1687 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1688 } 1689 1690 mContext = context; 1691 mFactoryTest = factoryTest; 1692 mOnlyCore = onlyCore; 1693 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1694 mMetrics = new DisplayMetrics(); 1695 mSettings = new Settings(mPackages); 1696 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1703 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1704 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1705 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1706 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1707 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1708 1709 // TODO: add a property to control this? 1710 long dexOptLRUThresholdInMinutes; 1711 if (mLazyDexOpt) { 1712 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1713 } else { 1714 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1715 } 1716 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1717 1718 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1719 if (separateProcesses != null && separateProcesses.length() > 0) { 1720 if ("*".equals(separateProcesses)) { 1721 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1722 mSeparateProcesses = null; 1723 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1724 } else { 1725 mDefParseFlags = 0; 1726 mSeparateProcesses = separateProcesses.split(","); 1727 Slog.w(TAG, "Running with debug.separate_processes: " 1728 + separateProcesses); 1729 } 1730 } else { 1731 mDefParseFlags = 0; 1732 mSeparateProcesses = null; 1733 } 1734 1735 mInstaller = installer; 1736 mPackageDexOptimizer = new PackageDexOptimizer(this); 1737 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1738 1739 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1740 FgThread.get().getLooper()); 1741 1742 getDefaultDisplayMetrics(context, mMetrics); 1743 1744 SystemConfig systemConfig = SystemConfig.getInstance(); 1745 mGlobalGids = systemConfig.getGlobalGids(); 1746 mSystemPermissions = systemConfig.getSystemPermissions(); 1747 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1748 1749 synchronized (mInstallLock) { 1750 // writer 1751 synchronized (mPackages) { 1752 mHandlerThread = new ServiceThread(TAG, 1753 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1754 mHandlerThread.start(); 1755 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1756 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1757 1758 File dataDir = Environment.getDataDirectory(); 1759 mAppDataDir = new File(dataDir, "data"); 1760 mAppInstallDir = new File(dataDir, "app"); 1761 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1762 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1763 mUserAppDataDir = new File(dataDir, "user"); 1764 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1765 1766 sUserManager = new UserManagerService(context, this, 1767 mInstallLock, mPackages); 1768 1769 // Propagate permission configuration in to package manager. 1770 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1771 = systemConfig.getPermissions(); 1772 for (int i=0; i<permConfig.size(); i++) { 1773 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1774 BasePermission bp = mSettings.mPermissions.get(perm.name); 1775 if (bp == null) { 1776 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1777 mSettings.mPermissions.put(perm.name, bp); 1778 } 1779 if (perm.gids != null) { 1780 bp.setGids(perm.gids, perm.perUser); 1781 } 1782 } 1783 1784 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1785 for (int i=0; i<libConfig.size(); i++) { 1786 mSharedLibraries.put(libConfig.keyAt(i), 1787 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1788 } 1789 1790 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1791 1792 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1793 mSdkVersion, mOnlyCore); 1794 1795 String customResolverActivity = Resources.getSystem().getString( 1796 R.string.config_customResolverActivity); 1797 if (TextUtils.isEmpty(customResolverActivity)) { 1798 customResolverActivity = null; 1799 } else { 1800 mCustomResolverComponentName = ComponentName.unflattenFromString( 1801 customResolverActivity); 1802 } 1803 1804 long startTime = SystemClock.uptimeMillis(); 1805 1806 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1807 startTime); 1808 1809 // Set flag to monitor and not change apk file paths when 1810 // scanning install directories. 1811 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1812 1813 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1814 1815 /** 1816 * Add everything in the in the boot class path to the 1817 * list of process files because dexopt will have been run 1818 * if necessary during zygote startup. 1819 */ 1820 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1821 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1822 1823 if (bootClassPath != null) { 1824 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1825 for (String element : bootClassPathElements) { 1826 alreadyDexOpted.add(element); 1827 } 1828 } else { 1829 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1830 } 1831 1832 if (systemServerClassPath != null) { 1833 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1834 for (String element : systemServerClassPathElements) { 1835 alreadyDexOpted.add(element); 1836 } 1837 } else { 1838 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1839 } 1840 1841 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1842 final String[] dexCodeInstructionSets = 1843 getDexCodeInstructionSets( 1844 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1845 1846 /** 1847 * Ensure all external libraries have had dexopt run on them. 1848 */ 1849 if (mSharedLibraries.size() > 0) { 1850 // NOTE: For now, we're compiling these system "shared libraries" 1851 // (and framework jars) into all available architectures. It's possible 1852 // to compile them only when we come across an app that uses them (there's 1853 // already logic for that in scanPackageLI) but that adds some complexity. 1854 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1855 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1856 final String lib = libEntry.path; 1857 if (lib == null) { 1858 continue; 1859 } 1860 1861 try { 1862 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1863 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1864 alreadyDexOpted.add(lib); 1865 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1866 } 1867 } catch (FileNotFoundException e) { 1868 Slog.w(TAG, "Library not found: " + lib); 1869 } catch (IOException e) { 1870 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1871 + e.getMessage()); 1872 } 1873 } 1874 } 1875 } 1876 1877 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1878 1879 // Gross hack for now: we know this file doesn't contain any 1880 // code, so don't dexopt it to avoid the resulting log spew. 1881 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1882 1883 // Gross hack for now: we know this file is only part of 1884 // the boot class path for art, so don't dexopt it to 1885 // avoid the resulting log spew. 1886 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1887 1888 /** 1889 * There are a number of commands implemented in Java, which 1890 * we currently need to do the dexopt on so that they can be 1891 * run from a non-root shell. 1892 */ 1893 String[] frameworkFiles = frameworkDir.list(); 1894 if (frameworkFiles != null) { 1895 // TODO: We could compile these only for the most preferred ABI. We should 1896 // first double check that the dex files for these commands are not referenced 1897 // by other system apps. 1898 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1899 for (int i=0; i<frameworkFiles.length; i++) { 1900 File libPath = new File(frameworkDir, frameworkFiles[i]); 1901 String path = libPath.getPath(); 1902 // Skip the file if we already did it. 1903 if (alreadyDexOpted.contains(path)) { 1904 continue; 1905 } 1906 // Skip the file if it is not a type we want to dexopt. 1907 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1908 continue; 1909 } 1910 try { 1911 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1912 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1913 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1914 } 1915 } catch (FileNotFoundException e) { 1916 Slog.w(TAG, "Jar not found: " + path); 1917 } catch (IOException e) { 1918 Slog.w(TAG, "Exception reading jar: " + path, e); 1919 } 1920 } 1921 } 1922 } 1923 1924 // Collect vendor overlay packages. 1925 // (Do this before scanning any apps.) 1926 // For security and version matching reason, only consider 1927 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1928 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1929 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1931 1932 // Find base frameworks (resource packages without code). 1933 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1934 | PackageParser.PARSE_IS_SYSTEM_DIR 1935 | PackageParser.PARSE_IS_PRIVILEGED, 1936 scanFlags | SCAN_NO_DEX, 0); 1937 1938 // Collected privileged system packages. 1939 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1940 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1941 | PackageParser.PARSE_IS_SYSTEM_DIR 1942 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1943 1944 // Collect ordinary system packages. 1945 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1946 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 // Collect all vendor packages. 1950 File vendorAppDir = new File("/vendor/app"); 1951 try { 1952 vendorAppDir = vendorAppDir.getCanonicalFile(); 1953 } catch (IOException e) { 1954 // failed to look up canonical path, continue with original one 1955 } 1956 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1957 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1958 1959 // Collect all OEM packages. 1960 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1961 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1962 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1963 1964 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1965 mInstaller.moveFiles(); 1966 1967 // Prune any system packages that no longer exist. 1968 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1969 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1970 if (!mOnlyCore) { 1971 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1972 while (psit.hasNext()) { 1973 PackageSetting ps = psit.next(); 1974 1975 /* 1976 * If this is not a system app, it can't be a 1977 * disable system app. 1978 */ 1979 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1980 continue; 1981 } 1982 1983 /* 1984 * If the package is scanned, it's not erased. 1985 */ 1986 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1987 if (scannedPkg != null) { 1988 /* 1989 * If the system app is both scanned and in the 1990 * disabled packages list, then it must have been 1991 * added via OTA. Remove it from the currently 1992 * scanned package so the previously user-installed 1993 * application can be scanned. 1994 */ 1995 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1996 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1997 + ps.name + "; removing system app. Last known codePath=" 1998 + ps.codePathString + ", installStatus=" + ps.installStatus 1999 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2000 + scannedPkg.mVersionCode); 2001 removePackageLI(ps, true); 2002 expectingBetter.put(ps.name, ps.codePath); 2003 } 2004 2005 continue; 2006 } 2007 2008 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2009 psit.remove(); 2010 logCriticalInfo(Log.WARN, "System package " + ps.name 2011 + " no longer exists; wiping its data"); 2012 removeDataDirsLI(null, ps.name); 2013 } else { 2014 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2015 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2016 possiblyDeletedUpdatedSystemApps.add(ps.name); 2017 } 2018 } 2019 } 2020 } 2021 2022 //look for any incomplete package installations 2023 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2024 //clean up list 2025 for(int i = 0; i < deletePkgsList.size(); i++) { 2026 //clean up here 2027 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2028 } 2029 //delete tmp files 2030 deleteTempPackageFiles(); 2031 2032 // Remove any shared userIDs that have no associated packages 2033 mSettings.pruneSharedUsersLPw(); 2034 2035 if (!mOnlyCore) { 2036 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2037 SystemClock.uptimeMillis()); 2038 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2039 2040 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2041 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2042 2043 /** 2044 * Remove disable package settings for any updated system 2045 * apps that were removed via an OTA. If they're not a 2046 * previously-updated app, remove them completely. 2047 * Otherwise, just revoke their system-level permissions. 2048 */ 2049 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2050 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2051 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2052 2053 String msg; 2054 if (deletedPkg == null) { 2055 msg = "Updated system package " + deletedAppName 2056 + " no longer exists; wiping its data"; 2057 removeDataDirsLI(null, deletedAppName); 2058 } else { 2059 msg = "Updated system app + " + deletedAppName 2060 + " no longer present; removing system privileges for " 2061 + deletedAppName; 2062 2063 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2064 2065 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2066 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2067 } 2068 logCriticalInfo(Log.WARN, msg); 2069 } 2070 2071 /** 2072 * Make sure all system apps that we expected to appear on 2073 * the userdata partition actually showed up. If they never 2074 * appeared, crawl back and revive the system version. 2075 */ 2076 for (int i = 0; i < expectingBetter.size(); i++) { 2077 final String packageName = expectingBetter.keyAt(i); 2078 if (!mPackages.containsKey(packageName)) { 2079 final File scanFile = expectingBetter.valueAt(i); 2080 2081 logCriticalInfo(Log.WARN, "Expected better " + packageName 2082 + " but never showed up; reverting to system"); 2083 2084 final int reparseFlags; 2085 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2086 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR 2088 | PackageParser.PARSE_IS_PRIVILEGED; 2089 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2090 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2091 | PackageParser.PARSE_IS_SYSTEM_DIR; 2092 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2093 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR; 2095 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2096 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2097 | PackageParser.PARSE_IS_SYSTEM_DIR; 2098 } else { 2099 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2100 continue; 2101 } 2102 2103 mSettings.enableSystemPackageLPw(packageName); 2104 2105 try { 2106 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2107 } catch (PackageManagerException e) { 2108 Slog.e(TAG, "Failed to parse original system package: " 2109 + e.getMessage()); 2110 } 2111 } 2112 } 2113 } 2114 2115 // Now that we know all of the shared libraries, update all clients to have 2116 // the correct library paths. 2117 updateAllSharedLibrariesLPw(); 2118 2119 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2120 // NOTE: We ignore potential failures here during a system scan (like 2121 // the rest of the commands above) because there's precious little we 2122 // can do about it. A settings error is reported, though. 2123 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2124 false /* force dexopt */, false /* defer dexopt */); 2125 } 2126 2127 // Now that we know all the packages we are keeping, 2128 // read and update their last usage times. 2129 mPackageUsage.readLP(); 2130 2131 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2132 SystemClock.uptimeMillis()); 2133 Slog.i(TAG, "Time to scan packages: " 2134 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2135 + " seconds"); 2136 2137 // If the platform SDK has changed since the last time we booted, 2138 // we need to re-grant app permission to catch any new ones that 2139 // appear. This is really a hack, and means that apps can in some 2140 // cases get permissions that the user didn't initially explicitly 2141 // allow... it would be nice to have some better way to handle 2142 // this situation. 2143 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2144 != mSdkVersion; 2145 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2146 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2147 + "; regranting permissions for internal storage"); 2148 mSettings.mInternalSdkPlatform = mSdkVersion; 2149 2150 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2151 | (regrantPermissions 2152 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2153 : 0)); 2154 2155 // If this is the first boot, and it is a normal boot, then 2156 // we need to initialize the default preferred apps. 2157 if (!mRestoredSettings && !onlyCore) { 2158 mSettings.readDefaultPreferredAppsLPw(this, 0); 2159 } 2160 2161 // If this is first boot after an OTA, and a normal boot, then 2162 // we need to clear code cache directories. 2163 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2164 if (mIsUpgrade && !onlyCore) { 2165 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2166 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2167 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2168 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2169 } 2170 mSettings.mFingerprint = Build.FINGERPRINT; 2171 } 2172 2173 primeDomainVerificationsLPw(); 2174 checkDefaultBrowser(); 2175 2176 // All the changes are done during package scanning. 2177 mSettings.updateInternalDatabaseVersion(); 2178 2179 // can downgrade to reader 2180 mSettings.writeLPr(); 2181 2182 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2183 SystemClock.uptimeMillis()); 2184 2185 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2186 2187 mInstallerService = new PackageInstallerService(context, this); 2188 2189 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2190 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2191 mIntentFilterVerifierComponent); 2192 2193 } // synchronized (mPackages) 2194 } // synchronized (mInstallLock) 2195 2196 // Now after opening every single application zip, make sure they 2197 // are all flushed. Not really needed, but keeps things nice and 2198 // tidy. 2199 Runtime.getRuntime().gc(); 2200 } 2201 2202 @Override 2203 public boolean isFirstBoot() { 2204 return !mRestoredSettings; 2205 } 2206 2207 @Override 2208 public boolean isOnlyCoreApps() { 2209 return mOnlyCore; 2210 } 2211 2212 @Override 2213 public boolean isUpgrade() { 2214 return mIsUpgrade; 2215 } 2216 2217 private String getRequiredVerifierLPr() { 2218 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2219 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2220 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2221 2222 String requiredVerifier = null; 2223 2224 final int N = receivers.size(); 2225 for (int i = 0; i < N; i++) { 2226 final ResolveInfo info = receivers.get(i); 2227 2228 if (info.activityInfo == null) { 2229 continue; 2230 } 2231 2232 final String packageName = info.activityInfo.packageName; 2233 2234 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2235 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2236 continue; 2237 } 2238 2239 if (requiredVerifier != null) { 2240 throw new RuntimeException("There can be only one required verifier"); 2241 } 2242 2243 requiredVerifier = packageName; 2244 } 2245 2246 return requiredVerifier; 2247 } 2248 2249 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2250 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2251 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2252 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2253 2254 ComponentName verifierComponentName = null; 2255 2256 int priority = -1000; 2257 final int N = receivers.size(); 2258 for (int i = 0; i < N; i++) { 2259 final ResolveInfo info = receivers.get(i); 2260 2261 if (info.activityInfo == null) { 2262 continue; 2263 } 2264 2265 final String packageName = info.activityInfo.packageName; 2266 2267 final PackageSetting ps = mSettings.mPackages.get(packageName); 2268 if (ps == null) { 2269 continue; 2270 } 2271 2272 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2273 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2274 continue; 2275 } 2276 2277 // Select the IntentFilterVerifier with the highest priority 2278 if (priority < info.priority) { 2279 priority = info.priority; 2280 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2281 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2282 + verifierComponentName + " with priority: " + info.priority); 2283 } 2284 } 2285 2286 return verifierComponentName; 2287 } 2288 2289 private void primeDomainVerificationsLPw() { 2290 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2291 boolean updated = false; 2292 ArraySet<String> allHostsSet = new ArraySet<>(); 2293 for (PackageParser.Package pkg : mPackages.values()) { 2294 final String packageName = pkg.packageName; 2295 if (!hasDomainURLs(pkg)) { 2296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2297 "package with no domain URLs: " + packageName); 2298 continue; 2299 } 2300 if (!pkg.isSystemApp()) { 2301 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2302 "No priming domain verifications for a non system package : " + 2303 packageName); 2304 continue; 2305 } 2306 for (PackageParser.Activity a : pkg.activities) { 2307 for (ActivityIntentInfo filter : a.intents) { 2308 if (hasValidDomains(filter)) { 2309 allHostsSet.addAll(filter.getHostsList()); 2310 } 2311 } 2312 } 2313 if (allHostsSet.size() == 0) { 2314 allHostsSet.add("*"); 2315 } 2316 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2317 IntentFilterVerificationInfo ivi = 2318 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2319 if (ivi != null) { 2320 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2321 "Priming domain verifications for package: " + packageName + 2322 " with hosts:" + ivi.getDomainsString()); 2323 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2324 updated = true; 2325 } 2326 else { 2327 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2328 "No priming domain verifications for package: " + packageName); 2329 } 2330 allHostsSet.clear(); 2331 } 2332 if (updated) { 2333 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2334 "Will need to write primed domain verifications"); 2335 } 2336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2337 } 2338 2339 private void checkDefaultBrowser() { 2340 final int myUserId = UserHandle.myUserId(); 2341 final String packageName = getDefaultBrowserPackageName(myUserId); 2342 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2343 if (info == null) { 2344 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2345 packageName); 2346 setDefaultBrowserPackageName(null, myUserId); 2347 } 2348 } 2349 2350 @Override 2351 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2352 throws RemoteException { 2353 try { 2354 return super.onTransact(code, data, reply, flags); 2355 } catch (RuntimeException e) { 2356 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2357 Slog.wtf(TAG, "Package Manager Crash", e); 2358 } 2359 throw e; 2360 } 2361 } 2362 2363 void cleanupInstallFailedPackage(PackageSetting ps) { 2364 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2365 2366 removeDataDirsLI(ps.volumeUuid, ps.name); 2367 if (ps.codePath != null) { 2368 if (ps.codePath.isDirectory()) { 2369 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2370 } else { 2371 ps.codePath.delete(); 2372 } 2373 } 2374 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2375 if (ps.resourcePath.isDirectory()) { 2376 FileUtils.deleteContents(ps.resourcePath); 2377 } 2378 ps.resourcePath.delete(); 2379 } 2380 mSettings.removePackageLPw(ps.name); 2381 } 2382 2383 static int[] appendInts(int[] cur, int[] add) { 2384 if (add == null) return cur; 2385 if (cur == null) return add; 2386 final int N = add.length; 2387 for (int i=0; i<N; i++) { 2388 cur = appendInt(cur, add[i]); 2389 } 2390 return cur; 2391 } 2392 2393 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2394 if (!sUserManager.exists(userId)) return null; 2395 final PackageSetting ps = (PackageSetting) p.mExtras; 2396 if (ps == null) { 2397 return null; 2398 } 2399 2400 final PermissionsState permissionsState = ps.getPermissionsState(); 2401 2402 final int[] gids = permissionsState.computeGids(userId); 2403 final Set<String> permissions = permissionsState.getPermissions(userId); 2404 final PackageUserState state = ps.readUserState(userId); 2405 2406 return PackageParser.generatePackageInfo(p, gids, flags, 2407 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2408 } 2409 2410 @Override 2411 public boolean isPackageFrozen(String packageName) { 2412 synchronized (mPackages) { 2413 final PackageSetting ps = mSettings.mPackages.get(packageName); 2414 if (ps != null) { 2415 return ps.frozen; 2416 } 2417 } 2418 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2419 return true; 2420 } 2421 2422 @Override 2423 public boolean isPackageAvailable(String packageName, int userId) { 2424 if (!sUserManager.exists(userId)) return false; 2425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2426 synchronized (mPackages) { 2427 PackageParser.Package p = mPackages.get(packageName); 2428 if (p != null) { 2429 final PackageSetting ps = (PackageSetting) p.mExtras; 2430 if (ps != null) { 2431 final PackageUserState state = ps.readUserState(userId); 2432 if (state != null) { 2433 return PackageParser.isAvailable(state); 2434 } 2435 } 2436 } 2437 } 2438 return false; 2439 } 2440 2441 @Override 2442 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2443 if (!sUserManager.exists(userId)) return null; 2444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2445 // reader 2446 synchronized (mPackages) { 2447 PackageParser.Package p = mPackages.get(packageName); 2448 if (DEBUG_PACKAGE_INFO) 2449 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2450 if (p != null) { 2451 return generatePackageInfo(p, flags, userId); 2452 } 2453 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2454 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2455 } 2456 } 2457 return null; 2458 } 2459 2460 @Override 2461 public String[] currentToCanonicalPackageNames(String[] names) { 2462 String[] out = new String[names.length]; 2463 // reader 2464 synchronized (mPackages) { 2465 for (int i=names.length-1; i>=0; i--) { 2466 PackageSetting ps = mSettings.mPackages.get(names[i]); 2467 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2468 } 2469 } 2470 return out; 2471 } 2472 2473 @Override 2474 public String[] canonicalToCurrentPackageNames(String[] names) { 2475 String[] out = new String[names.length]; 2476 // reader 2477 synchronized (mPackages) { 2478 for (int i=names.length-1; i>=0; i--) { 2479 String cur = mSettings.mRenamedPackages.get(names[i]); 2480 out[i] = cur != null ? cur : names[i]; 2481 } 2482 } 2483 return out; 2484 } 2485 2486 @Override 2487 public int getPackageUid(String packageName, int userId) { 2488 if (!sUserManager.exists(userId)) return -1; 2489 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2490 2491 // reader 2492 synchronized (mPackages) { 2493 PackageParser.Package p = mPackages.get(packageName); 2494 if(p != null) { 2495 return UserHandle.getUid(userId, p.applicationInfo.uid); 2496 } 2497 PackageSetting ps = mSettings.mPackages.get(packageName); 2498 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2499 return -1; 2500 } 2501 p = ps.pkg; 2502 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2503 } 2504 } 2505 2506 @Override 2507 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2508 if (!sUserManager.exists(userId)) { 2509 return null; 2510 } 2511 2512 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2513 "getPackageGids"); 2514 2515 // reader 2516 synchronized (mPackages) { 2517 PackageParser.Package p = mPackages.get(packageName); 2518 if (DEBUG_PACKAGE_INFO) { 2519 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2520 } 2521 if (p != null) { 2522 PackageSetting ps = (PackageSetting) p.mExtras; 2523 return ps.getPermissionsState().computeGids(userId); 2524 } 2525 } 2526 2527 return null; 2528 } 2529 2530 static PermissionInfo generatePermissionInfo( 2531 BasePermission bp, int flags) { 2532 if (bp.perm != null) { 2533 return PackageParser.generatePermissionInfo(bp.perm, flags); 2534 } 2535 PermissionInfo pi = new PermissionInfo(); 2536 pi.name = bp.name; 2537 pi.packageName = bp.sourcePackage; 2538 pi.nonLocalizedLabel = bp.name; 2539 pi.protectionLevel = bp.protectionLevel; 2540 return pi; 2541 } 2542 2543 @Override 2544 public PermissionInfo getPermissionInfo(String name, int flags) { 2545 // reader 2546 synchronized (mPackages) { 2547 final BasePermission p = mSettings.mPermissions.get(name); 2548 if (p != null) { 2549 return generatePermissionInfo(p, flags); 2550 } 2551 return null; 2552 } 2553 } 2554 2555 @Override 2556 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2557 // reader 2558 synchronized (mPackages) { 2559 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2560 for (BasePermission p : mSettings.mPermissions.values()) { 2561 if (group == null) { 2562 if (p.perm == null || p.perm.info.group == null) { 2563 out.add(generatePermissionInfo(p, flags)); 2564 } 2565 } else { 2566 if (p.perm != null && group.equals(p.perm.info.group)) { 2567 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2568 } 2569 } 2570 } 2571 2572 if (out.size() > 0) { 2573 return out; 2574 } 2575 return mPermissionGroups.containsKey(group) ? out : null; 2576 } 2577 } 2578 2579 @Override 2580 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2581 // reader 2582 synchronized (mPackages) { 2583 return PackageParser.generatePermissionGroupInfo( 2584 mPermissionGroups.get(name), flags); 2585 } 2586 } 2587 2588 @Override 2589 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2590 // reader 2591 synchronized (mPackages) { 2592 final int N = mPermissionGroups.size(); 2593 ArrayList<PermissionGroupInfo> out 2594 = new ArrayList<PermissionGroupInfo>(N); 2595 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2596 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2597 } 2598 return out; 2599 } 2600 } 2601 2602 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2603 int userId) { 2604 if (!sUserManager.exists(userId)) return null; 2605 PackageSetting ps = mSettings.mPackages.get(packageName); 2606 if (ps != null) { 2607 if (ps.pkg == null) { 2608 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2609 flags, userId); 2610 if (pInfo != null) { 2611 return pInfo.applicationInfo; 2612 } 2613 return null; 2614 } 2615 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2616 ps.readUserState(userId), userId); 2617 } 2618 return null; 2619 } 2620 2621 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2622 int userId) { 2623 if (!sUserManager.exists(userId)) return null; 2624 PackageSetting ps = mSettings.mPackages.get(packageName); 2625 if (ps != null) { 2626 PackageParser.Package pkg = ps.pkg; 2627 if (pkg == null) { 2628 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2629 return null; 2630 } 2631 // Only data remains, so we aren't worried about code paths 2632 pkg = new PackageParser.Package(packageName); 2633 pkg.applicationInfo.packageName = packageName; 2634 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2635 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2636 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2637 packageName, userId).getAbsolutePath(); 2638 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2639 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2640 } 2641 return generatePackageInfo(pkg, flags, userId); 2642 } 2643 return null; 2644 } 2645 2646 @Override 2647 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2648 if (!sUserManager.exists(userId)) return null; 2649 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2650 // writer 2651 synchronized (mPackages) { 2652 PackageParser.Package p = mPackages.get(packageName); 2653 if (DEBUG_PACKAGE_INFO) Log.v( 2654 TAG, "getApplicationInfo " + packageName 2655 + ": " + p); 2656 if (p != null) { 2657 PackageSetting ps = mSettings.mPackages.get(packageName); 2658 if (ps == null) return null; 2659 // Note: isEnabledLP() does not apply here - always return info 2660 return PackageParser.generateApplicationInfo( 2661 p, flags, ps.readUserState(userId), userId); 2662 } 2663 if ("android".equals(packageName)||"system".equals(packageName)) { 2664 return mAndroidApplication; 2665 } 2666 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2667 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2668 } 2669 } 2670 return null; 2671 } 2672 2673 @Override 2674 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2675 final IPackageDataObserver observer) { 2676 mContext.enforceCallingOrSelfPermission( 2677 android.Manifest.permission.CLEAR_APP_CACHE, null); 2678 // Queue up an async operation since clearing cache may take a little while. 2679 mHandler.post(new Runnable() { 2680 public void run() { 2681 mHandler.removeCallbacks(this); 2682 int retCode = -1; 2683 synchronized (mInstallLock) { 2684 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2685 if (retCode < 0) { 2686 Slog.w(TAG, "Couldn't clear application caches"); 2687 } 2688 } 2689 if (observer != null) { 2690 try { 2691 observer.onRemoveCompleted(null, (retCode >= 0)); 2692 } catch (RemoteException e) { 2693 Slog.w(TAG, "RemoveException when invoking call back"); 2694 } 2695 } 2696 } 2697 }); 2698 } 2699 2700 @Override 2701 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2702 final IntentSender pi) { 2703 mContext.enforceCallingOrSelfPermission( 2704 android.Manifest.permission.CLEAR_APP_CACHE, null); 2705 // Queue up an async operation since clearing cache may take a little while. 2706 mHandler.post(new Runnable() { 2707 public void run() { 2708 mHandler.removeCallbacks(this); 2709 int retCode = -1; 2710 synchronized (mInstallLock) { 2711 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2712 if (retCode < 0) { 2713 Slog.w(TAG, "Couldn't clear application caches"); 2714 } 2715 } 2716 if(pi != null) { 2717 try { 2718 // Callback via pending intent 2719 int code = (retCode >= 0) ? 1 : 0; 2720 pi.sendIntent(null, code, null, 2721 null, null); 2722 } catch (SendIntentException e1) { 2723 Slog.i(TAG, "Failed to send pending intent"); 2724 } 2725 } 2726 } 2727 }); 2728 } 2729 2730 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2731 synchronized (mInstallLock) { 2732 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2733 throw new IOException("Failed to free enough space"); 2734 } 2735 } 2736 } 2737 2738 @Override 2739 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2740 if (!sUserManager.exists(userId)) return null; 2741 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2742 synchronized (mPackages) { 2743 PackageParser.Activity a = mActivities.mActivities.get(component); 2744 2745 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2746 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2747 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2748 if (ps == null) return null; 2749 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2750 userId); 2751 } 2752 if (mResolveComponentName.equals(component)) { 2753 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2754 new PackageUserState(), userId); 2755 } 2756 } 2757 return null; 2758 } 2759 2760 @Override 2761 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2762 String resolvedType) { 2763 synchronized (mPackages) { 2764 PackageParser.Activity a = mActivities.mActivities.get(component); 2765 if (a == null) { 2766 return false; 2767 } 2768 for (int i=0; i<a.intents.size(); i++) { 2769 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2770 intent.getData(), intent.getCategories(), TAG) >= 0) { 2771 return true; 2772 } 2773 } 2774 return false; 2775 } 2776 } 2777 2778 @Override 2779 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2780 if (!sUserManager.exists(userId)) return null; 2781 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2782 synchronized (mPackages) { 2783 PackageParser.Activity a = mReceivers.mActivities.get(component); 2784 if (DEBUG_PACKAGE_INFO) Log.v( 2785 TAG, "getReceiverInfo " + component + ": " + a); 2786 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2787 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2788 if (ps == null) return null; 2789 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2790 userId); 2791 } 2792 } 2793 return null; 2794 } 2795 2796 @Override 2797 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2798 if (!sUserManager.exists(userId)) return null; 2799 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2800 synchronized (mPackages) { 2801 PackageParser.Service s = mServices.mServices.get(component); 2802 if (DEBUG_PACKAGE_INFO) Log.v( 2803 TAG, "getServiceInfo " + component + ": " + s); 2804 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2805 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2806 if (ps == null) return null; 2807 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2808 userId); 2809 } 2810 } 2811 return null; 2812 } 2813 2814 @Override 2815 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2816 if (!sUserManager.exists(userId)) return null; 2817 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2818 synchronized (mPackages) { 2819 PackageParser.Provider p = mProviders.mProviders.get(component); 2820 if (DEBUG_PACKAGE_INFO) Log.v( 2821 TAG, "getProviderInfo " + component + ": " + p); 2822 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2823 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2824 if (ps == null) return null; 2825 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2826 userId); 2827 } 2828 } 2829 return null; 2830 } 2831 2832 @Override 2833 public String[] getSystemSharedLibraryNames() { 2834 Set<String> libSet; 2835 synchronized (mPackages) { 2836 libSet = mSharedLibraries.keySet(); 2837 int size = libSet.size(); 2838 if (size > 0) { 2839 String[] libs = new String[size]; 2840 libSet.toArray(libs); 2841 return libs; 2842 } 2843 } 2844 return null; 2845 } 2846 2847 /** 2848 * @hide 2849 */ 2850 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2851 synchronized (mPackages) { 2852 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2853 if (lib != null && lib.apk != null) { 2854 return mPackages.get(lib.apk); 2855 } 2856 } 2857 return null; 2858 } 2859 2860 @Override 2861 public FeatureInfo[] getSystemAvailableFeatures() { 2862 Collection<FeatureInfo> featSet; 2863 synchronized (mPackages) { 2864 featSet = mAvailableFeatures.values(); 2865 int size = featSet.size(); 2866 if (size > 0) { 2867 FeatureInfo[] features = new FeatureInfo[size+1]; 2868 featSet.toArray(features); 2869 FeatureInfo fi = new FeatureInfo(); 2870 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2871 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2872 features[size] = fi; 2873 return features; 2874 } 2875 } 2876 return null; 2877 } 2878 2879 @Override 2880 public boolean hasSystemFeature(String name) { 2881 synchronized (mPackages) { 2882 return mAvailableFeatures.containsKey(name); 2883 } 2884 } 2885 2886 private void checkValidCaller(int uid, int userId) { 2887 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2888 return; 2889 2890 throw new SecurityException("Caller uid=" + uid 2891 + " is not privileged to communicate with user=" + userId); 2892 } 2893 2894 @Override 2895 public int checkPermission(String permName, String pkgName, int userId) { 2896 if (!sUserManager.exists(userId)) { 2897 return PackageManager.PERMISSION_DENIED; 2898 } 2899 2900 synchronized (mPackages) { 2901 final PackageParser.Package p = mPackages.get(pkgName); 2902 if (p != null && p.mExtras != null) { 2903 final PackageSetting ps = (PackageSetting) p.mExtras; 2904 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2905 return PackageManager.PERMISSION_GRANTED; 2906 } 2907 } 2908 } 2909 2910 return PackageManager.PERMISSION_DENIED; 2911 } 2912 2913 @Override 2914 public int checkUidPermission(String permName, int uid) { 2915 final int userId = UserHandle.getUserId(uid); 2916 2917 if (!sUserManager.exists(userId)) { 2918 return PackageManager.PERMISSION_DENIED; 2919 } 2920 2921 synchronized (mPackages) { 2922 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2923 if (obj != null) { 2924 final SettingBase ps = (SettingBase) obj; 2925 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } else { 2929 ArraySet<String> perms = mSystemPermissions.get(uid); 2930 if (perms != null && perms.contains(permName)) { 2931 return PackageManager.PERMISSION_GRANTED; 2932 } 2933 } 2934 } 2935 2936 return PackageManager.PERMISSION_DENIED; 2937 } 2938 2939 /** 2940 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2941 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2942 * @param checkShell TODO(yamasani): 2943 * @param message the message to log on security exception 2944 */ 2945 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2946 boolean checkShell, String message) { 2947 if (userId < 0) { 2948 throw new IllegalArgumentException("Invalid userId " + userId); 2949 } 2950 if (checkShell) { 2951 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2952 } 2953 if (userId == UserHandle.getUserId(callingUid)) return; 2954 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2955 if (requireFullPermission) { 2956 mContext.enforceCallingOrSelfPermission( 2957 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2958 } else { 2959 try { 2960 mContext.enforceCallingOrSelfPermission( 2961 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2962 } catch (SecurityException se) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2965 } 2966 } 2967 } 2968 } 2969 2970 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2971 if (callingUid == Process.SHELL_UID) { 2972 if (userHandle >= 0 2973 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2974 throw new SecurityException("Shell does not have permission to access user " 2975 + userHandle); 2976 } else if (userHandle < 0) { 2977 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2978 + Debug.getCallers(3)); 2979 } 2980 } 2981 } 2982 2983 private BasePermission findPermissionTreeLP(String permName) { 2984 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2985 if (permName.startsWith(bp.name) && 2986 permName.length() > bp.name.length() && 2987 permName.charAt(bp.name.length()) == '.') { 2988 return bp; 2989 } 2990 } 2991 return null; 2992 } 2993 2994 private BasePermission checkPermissionTreeLP(String permName) { 2995 if (permName != null) { 2996 BasePermission bp = findPermissionTreeLP(permName); 2997 if (bp != null) { 2998 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2999 return bp; 3000 } 3001 throw new SecurityException("Calling uid " 3002 + Binder.getCallingUid() 3003 + " is not allowed to add to permission tree " 3004 + bp.name + " owned by uid " + bp.uid); 3005 } 3006 } 3007 throw new SecurityException("No permission tree found for " + permName); 3008 } 3009 3010 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3011 if (s1 == null) { 3012 return s2 == null; 3013 } 3014 if (s2 == null) { 3015 return false; 3016 } 3017 if (s1.getClass() != s2.getClass()) { 3018 return false; 3019 } 3020 return s1.equals(s2); 3021 } 3022 3023 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3024 if (pi1.icon != pi2.icon) return false; 3025 if (pi1.logo != pi2.logo) return false; 3026 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3027 if (!compareStrings(pi1.name, pi2.name)) return false; 3028 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3029 // We'll take care of setting this one. 3030 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3031 // These are not currently stored in settings. 3032 //if (!compareStrings(pi1.group, pi2.group)) return false; 3033 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3034 //if (pi1.labelRes != pi2.labelRes) return false; 3035 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3036 return true; 3037 } 3038 3039 int permissionInfoFootprint(PermissionInfo info) { 3040 int size = info.name.length(); 3041 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3042 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3043 return size; 3044 } 3045 3046 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3047 int size = 0; 3048 for (BasePermission perm : mSettings.mPermissions.values()) { 3049 if (perm.uid == tree.uid) { 3050 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3051 } 3052 } 3053 return size; 3054 } 3055 3056 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3057 // We calculate the max size of permissions defined by this uid and throw 3058 // if that plus the size of 'info' would exceed our stated maximum. 3059 if (tree.uid != Process.SYSTEM_UID) { 3060 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3061 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3062 throw new SecurityException("Permission tree size cap exceeded"); 3063 } 3064 } 3065 } 3066 3067 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3068 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3069 throw new SecurityException("Label must be specified in permission"); 3070 } 3071 BasePermission tree = checkPermissionTreeLP(info.name); 3072 BasePermission bp = mSettings.mPermissions.get(info.name); 3073 boolean added = bp == null; 3074 boolean changed = true; 3075 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3076 if (added) { 3077 enforcePermissionCapLocked(info, tree); 3078 bp = new BasePermission(info.name, tree.sourcePackage, 3079 BasePermission.TYPE_DYNAMIC); 3080 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3081 throw new SecurityException( 3082 "Not allowed to modify non-dynamic permission " 3083 + info.name); 3084 } else { 3085 if (bp.protectionLevel == fixedLevel 3086 && bp.perm.owner.equals(tree.perm.owner) 3087 && bp.uid == tree.uid 3088 && comparePermissionInfos(bp.perm.info, info)) { 3089 changed = false; 3090 } 3091 } 3092 bp.protectionLevel = fixedLevel; 3093 info = new PermissionInfo(info); 3094 info.protectionLevel = fixedLevel; 3095 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3096 bp.perm.info.packageName = tree.perm.info.packageName; 3097 bp.uid = tree.uid; 3098 if (added) { 3099 mSettings.mPermissions.put(info.name, bp); 3100 } 3101 if (changed) { 3102 if (!async) { 3103 mSettings.writeLPr(); 3104 } else { 3105 scheduleWriteSettingsLocked(); 3106 } 3107 } 3108 return added; 3109 } 3110 3111 @Override 3112 public boolean addPermission(PermissionInfo info) { 3113 synchronized (mPackages) { 3114 return addPermissionLocked(info, false); 3115 } 3116 } 3117 3118 @Override 3119 public boolean addPermissionAsync(PermissionInfo info) { 3120 synchronized (mPackages) { 3121 return addPermissionLocked(info, true); 3122 } 3123 } 3124 3125 @Override 3126 public void removePermission(String name) { 3127 synchronized (mPackages) { 3128 checkPermissionTreeLP(name); 3129 BasePermission bp = mSettings.mPermissions.get(name); 3130 if (bp != null) { 3131 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3132 throw new SecurityException( 3133 "Not allowed to modify non-dynamic permission " 3134 + name); 3135 } 3136 mSettings.mPermissions.remove(name); 3137 mSettings.writeLPr(); 3138 } 3139 } 3140 } 3141 3142 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3143 BasePermission bp) { 3144 int index = pkg.requestedPermissions.indexOf(bp.name); 3145 if (index == -1) { 3146 throw new SecurityException("Package " + pkg.packageName 3147 + " has not requested permission " + bp.name); 3148 } 3149 if (!bp.isRuntime()) { 3150 throw new SecurityException("Permission " + bp.name 3151 + " is not a changeable permission type"); 3152 } 3153 } 3154 3155 @Override 3156 public void grantRuntimePermission(String packageName, String name, int userId) { 3157 if (!sUserManager.exists(userId)) { 3158 Log.e(TAG, "No such user:" + userId); 3159 return; 3160 } 3161 3162 mContext.enforceCallingOrSelfPermission( 3163 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3164 "grantRuntimePermission"); 3165 3166 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3167 "grantRuntimePermission"); 3168 3169 boolean gidsChanged = false; 3170 final SettingBase sb; 3171 3172 synchronized (mPackages) { 3173 final PackageParser.Package pkg = mPackages.get(packageName); 3174 if (pkg == null) { 3175 throw new IllegalArgumentException("Unknown package: " + packageName); 3176 } 3177 3178 final BasePermission bp = mSettings.mPermissions.get(name); 3179 if (bp == null) { 3180 throw new IllegalArgumentException("Unknown permission: " + name); 3181 } 3182 3183 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3184 3185 sb = (SettingBase) pkg.mExtras; 3186 if (sb == null) { 3187 throw new IllegalArgumentException("Unknown package: " + packageName); 3188 } 3189 3190 final PermissionsState permissionsState = sb.getPermissionsState(); 3191 3192 final int flags = permissionsState.getPermissionFlags(name, userId); 3193 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3194 throw new SecurityException("Cannot grant system fixed permission: " 3195 + name + " for package: " + packageName); 3196 } 3197 3198 final int result = permissionsState.grantRuntimePermission(bp, userId); 3199 switch (result) { 3200 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3201 return; 3202 } 3203 3204 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3205 gidsChanged = true; 3206 } break; 3207 } 3208 3209 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3210 3211 // Not critical if that is lost - app has to request again. 3212 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3213 } 3214 3215 if (gidsChanged) { 3216 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3217 } 3218 } 3219 3220 @Override 3221 public void revokeRuntimePermission(String packageName, String name, int userId) { 3222 if (!sUserManager.exists(userId)) { 3223 Log.e(TAG, "No such user:" + userId); 3224 return; 3225 } 3226 3227 mContext.enforceCallingOrSelfPermission( 3228 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3229 "revokeRuntimePermission"); 3230 3231 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3232 "revokeRuntimePermission"); 3233 3234 final SettingBase sb; 3235 3236 synchronized (mPackages) { 3237 final PackageParser.Package pkg = mPackages.get(packageName); 3238 if (pkg == null) { 3239 throw new IllegalArgumentException("Unknown package: " + packageName); 3240 } 3241 3242 final BasePermission bp = mSettings.mPermissions.get(name); 3243 if (bp == null) { 3244 throw new IllegalArgumentException("Unknown permission: " + name); 3245 } 3246 3247 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3248 3249 sb = (SettingBase) pkg.mExtras; 3250 if (sb == null) { 3251 throw new IllegalArgumentException("Unknown package: " + packageName); 3252 } 3253 3254 final PermissionsState permissionsState = sb.getPermissionsState(); 3255 3256 final int flags = permissionsState.getPermissionFlags(name, userId); 3257 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3258 throw new SecurityException("Cannot revoke system fixed permission: " 3259 + name + " for package: " + packageName); 3260 } 3261 3262 if (permissionsState.revokeRuntimePermission(bp, userId) == 3263 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3264 return; 3265 } 3266 3267 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3268 3269 // Critical, after this call app should never have the permission. 3270 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3271 } 3272 3273 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3274 } 3275 3276 @Override 3277 public int getPermissionFlags(String name, String packageName, int userId) { 3278 if (!sUserManager.exists(userId)) { 3279 return 0; 3280 } 3281 3282 mContext.enforceCallingOrSelfPermission( 3283 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3284 "getPermissionFlags"); 3285 3286 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3287 "getPermissionFlags"); 3288 3289 synchronized (mPackages) { 3290 final PackageParser.Package pkg = mPackages.get(packageName); 3291 if (pkg == null) { 3292 throw new IllegalArgumentException("Unknown package: " + packageName); 3293 } 3294 3295 final BasePermission bp = mSettings.mPermissions.get(name); 3296 if (bp == null) { 3297 throw new IllegalArgumentException("Unknown permission: " + name); 3298 } 3299 3300 SettingBase sb = (SettingBase) pkg.mExtras; 3301 if (sb == null) { 3302 throw new IllegalArgumentException("Unknown package: " + packageName); 3303 } 3304 3305 PermissionsState permissionsState = sb.getPermissionsState(); 3306 return permissionsState.getPermissionFlags(name, userId); 3307 } 3308 } 3309 3310 @Override 3311 public void updatePermissionFlags(String name, String packageName, int flagMask, 3312 int flagValues, int userId) { 3313 if (!sUserManager.exists(userId)) { 3314 return; 3315 } 3316 3317 mContext.enforceCallingOrSelfPermission( 3318 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3319 "updatePermissionFlags"); 3320 3321 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3322 "updatePermissionFlags"); 3323 3324 // Only the system can change policy flags. 3325 if (getCallingUid() != Process.SYSTEM_UID) { 3326 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3327 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3328 } 3329 3330 // Only the package manager can change system flags. 3331 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3332 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3333 3334 synchronized (mPackages) { 3335 final PackageParser.Package pkg = mPackages.get(packageName); 3336 if (pkg == null) { 3337 throw new IllegalArgumentException("Unknown package: " + packageName); 3338 } 3339 3340 final BasePermission bp = mSettings.mPermissions.get(name); 3341 if (bp == null) { 3342 throw new IllegalArgumentException("Unknown permission: " + name); 3343 } 3344 3345 SettingBase sb = (SettingBase) pkg.mExtras; 3346 if (sb == null) { 3347 throw new IllegalArgumentException("Unknown package: " + packageName); 3348 } 3349 3350 PermissionsState permissionsState = sb.getPermissionsState(); 3351 3352 // Only the package manager can change flags for system component permissions. 3353 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3354 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3355 return; 3356 } 3357 3358 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3359 // Install and runtime permissions are stored in different places, 3360 // so figure out what permission changed and persist the change. 3361 if (permissionsState.getInstallPermissionState(name) != null) { 3362 scheduleWriteSettingsLocked(); 3363 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3365 } 3366 } 3367 } 3368 } 3369 3370 @Override 3371 public boolean shouldShowRequestPermissionRationale(String permissionName, 3372 String packageName, int userId) { 3373 if (UserHandle.getCallingUserId() != userId) { 3374 mContext.enforceCallingPermission( 3375 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3376 "canShowRequestPermissionRationale for user " + userId); 3377 } 3378 3379 final int uid = getPackageUid(packageName, userId); 3380 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3381 return false; 3382 } 3383 3384 if (checkPermission(permissionName, packageName, userId) 3385 == PackageManager.PERMISSION_GRANTED) { 3386 return false; 3387 } 3388 3389 final int flags; 3390 3391 final long identity = Binder.clearCallingIdentity(); 3392 try { 3393 flags = getPermissionFlags(permissionName, 3394 packageName, userId); 3395 } finally { 3396 Binder.restoreCallingIdentity(identity); 3397 } 3398 3399 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3400 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3401 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3402 3403 if ((flags & fixedFlags) != 0) { 3404 return false; 3405 } 3406 3407 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3408 } 3409 3410 @Override 3411 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3412 mContext.enforceCallingOrSelfPermission( 3413 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3414 "addOnPermissionsChangeListener"); 3415 3416 synchronized (mPackages) { 3417 mOnPermissionChangeListeners.addListenerLocked(listener); 3418 } 3419 } 3420 3421 @Override 3422 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3423 synchronized (mPackages) { 3424 mOnPermissionChangeListeners.removeListenerLocked(listener); 3425 } 3426 } 3427 3428 @Override 3429 public boolean isProtectedBroadcast(String actionName) { 3430 synchronized (mPackages) { 3431 return mProtectedBroadcasts.contains(actionName); 3432 } 3433 } 3434 3435 @Override 3436 public int checkSignatures(String pkg1, String pkg2) { 3437 synchronized (mPackages) { 3438 final PackageParser.Package p1 = mPackages.get(pkg1); 3439 final PackageParser.Package p2 = mPackages.get(pkg2); 3440 if (p1 == null || p1.mExtras == null 3441 || p2 == null || p2.mExtras == null) { 3442 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3443 } 3444 return compareSignatures(p1.mSignatures, p2.mSignatures); 3445 } 3446 } 3447 3448 @Override 3449 public int checkUidSignatures(int uid1, int uid2) { 3450 // Map to base uids. 3451 uid1 = UserHandle.getAppId(uid1); 3452 uid2 = UserHandle.getAppId(uid2); 3453 // reader 3454 synchronized (mPackages) { 3455 Signature[] s1; 3456 Signature[] s2; 3457 Object obj = mSettings.getUserIdLPr(uid1); 3458 if (obj != null) { 3459 if (obj instanceof SharedUserSetting) { 3460 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3461 } else if (obj instanceof PackageSetting) { 3462 s1 = ((PackageSetting)obj).signatures.mSignatures; 3463 } else { 3464 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3465 } 3466 } else { 3467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3468 } 3469 obj = mSettings.getUserIdLPr(uid2); 3470 if (obj != null) { 3471 if (obj instanceof SharedUserSetting) { 3472 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3473 } else if (obj instanceof PackageSetting) { 3474 s2 = ((PackageSetting)obj).signatures.mSignatures; 3475 } else { 3476 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3477 } 3478 } else { 3479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3480 } 3481 return compareSignatures(s1, s2); 3482 } 3483 } 3484 3485 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3486 final long identity = Binder.clearCallingIdentity(); 3487 try { 3488 if (sb instanceof SharedUserSetting) { 3489 SharedUserSetting sus = (SharedUserSetting) sb; 3490 final int packageCount = sus.packages.size(); 3491 for (int i = 0; i < packageCount; i++) { 3492 PackageSetting susPs = sus.packages.valueAt(i); 3493 if (userId == UserHandle.USER_ALL) { 3494 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3495 } else { 3496 final int uid = UserHandle.getUid(userId, susPs.appId); 3497 killUid(uid, reason); 3498 } 3499 } 3500 } else if (sb instanceof PackageSetting) { 3501 PackageSetting ps = (PackageSetting) sb; 3502 if (userId == UserHandle.USER_ALL) { 3503 killApplication(ps.pkg.packageName, ps.appId, reason); 3504 } else { 3505 final int uid = UserHandle.getUid(userId, ps.appId); 3506 killUid(uid, reason); 3507 } 3508 } 3509 } finally { 3510 Binder.restoreCallingIdentity(identity); 3511 } 3512 } 3513 3514 private static void killUid(int uid, String reason) { 3515 IActivityManager am = ActivityManagerNative.getDefault(); 3516 if (am != null) { 3517 try { 3518 am.killUid(uid, reason); 3519 } catch (RemoteException e) { 3520 /* ignore - same process */ 3521 } 3522 } 3523 } 3524 3525 /** 3526 * Compares two sets of signatures. Returns: 3527 * <br /> 3528 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3529 * <br /> 3530 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3531 * <br /> 3532 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3533 * <br /> 3534 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3535 * <br /> 3536 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3537 */ 3538 static int compareSignatures(Signature[] s1, Signature[] s2) { 3539 if (s1 == null) { 3540 return s2 == null 3541 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3542 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3543 } 3544 3545 if (s2 == null) { 3546 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3547 } 3548 3549 if (s1.length != s2.length) { 3550 return PackageManager.SIGNATURE_NO_MATCH; 3551 } 3552 3553 // Since both signature sets are of size 1, we can compare without HashSets. 3554 if (s1.length == 1) { 3555 return s1[0].equals(s2[0]) ? 3556 PackageManager.SIGNATURE_MATCH : 3557 PackageManager.SIGNATURE_NO_MATCH; 3558 } 3559 3560 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3561 for (Signature sig : s1) { 3562 set1.add(sig); 3563 } 3564 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3565 for (Signature sig : s2) { 3566 set2.add(sig); 3567 } 3568 // Make sure s2 contains all signatures in s1. 3569 if (set1.equals(set2)) { 3570 return PackageManager.SIGNATURE_MATCH; 3571 } 3572 return PackageManager.SIGNATURE_NO_MATCH; 3573 } 3574 3575 /** 3576 * If the database version for this type of package (internal storage or 3577 * external storage) is less than the version where package signatures 3578 * were updated, return true. 3579 */ 3580 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3581 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3582 DatabaseVersion.SIGNATURE_END_ENTITY)) 3583 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3584 DatabaseVersion.SIGNATURE_END_ENTITY)); 3585 } 3586 3587 /** 3588 * Used for backward compatibility to make sure any packages with 3589 * certificate chains get upgraded to the new style. {@code existingSigs} 3590 * will be in the old format (since they were stored on disk from before the 3591 * system upgrade) and {@code scannedSigs} will be in the newer format. 3592 */ 3593 private int compareSignaturesCompat(PackageSignatures existingSigs, 3594 PackageParser.Package scannedPkg) { 3595 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3596 return PackageManager.SIGNATURE_NO_MATCH; 3597 } 3598 3599 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3600 for (Signature sig : existingSigs.mSignatures) { 3601 existingSet.add(sig); 3602 } 3603 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3604 for (Signature sig : scannedPkg.mSignatures) { 3605 try { 3606 Signature[] chainSignatures = sig.getChainSignatures(); 3607 for (Signature chainSig : chainSignatures) { 3608 scannedCompatSet.add(chainSig); 3609 } 3610 } catch (CertificateEncodingException e) { 3611 scannedCompatSet.add(sig); 3612 } 3613 } 3614 /* 3615 * Make sure the expanded scanned set contains all signatures in the 3616 * existing one. 3617 */ 3618 if (scannedCompatSet.equals(existingSet)) { 3619 // Migrate the old signatures to the new scheme. 3620 existingSigs.assignSignatures(scannedPkg.mSignatures); 3621 // The new KeySets will be re-added later in the scanning process. 3622 synchronized (mPackages) { 3623 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3624 } 3625 return PackageManager.SIGNATURE_MATCH; 3626 } 3627 return PackageManager.SIGNATURE_NO_MATCH; 3628 } 3629 3630 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3631 if (isExternal(scannedPkg)) { 3632 return mSettings.isExternalDatabaseVersionOlderThan( 3633 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3634 } else { 3635 return mSettings.isInternalDatabaseVersionOlderThan( 3636 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3637 } 3638 } 3639 3640 private int compareSignaturesRecover(PackageSignatures existingSigs, 3641 PackageParser.Package scannedPkg) { 3642 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3643 return PackageManager.SIGNATURE_NO_MATCH; 3644 } 3645 3646 String msg = null; 3647 try { 3648 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3649 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3650 + scannedPkg.packageName); 3651 return PackageManager.SIGNATURE_MATCH; 3652 } 3653 } catch (CertificateException e) { 3654 msg = e.getMessage(); 3655 } 3656 3657 logCriticalInfo(Log.INFO, 3658 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3659 return PackageManager.SIGNATURE_NO_MATCH; 3660 } 3661 3662 @Override 3663 public String[] getPackagesForUid(int uid) { 3664 uid = UserHandle.getAppId(uid); 3665 // reader 3666 synchronized (mPackages) { 3667 Object obj = mSettings.getUserIdLPr(uid); 3668 if (obj instanceof SharedUserSetting) { 3669 final SharedUserSetting sus = (SharedUserSetting) obj; 3670 final int N = sus.packages.size(); 3671 final String[] res = new String[N]; 3672 final Iterator<PackageSetting> it = sus.packages.iterator(); 3673 int i = 0; 3674 while (it.hasNext()) { 3675 res[i++] = it.next().name; 3676 } 3677 return res; 3678 } else if (obj instanceof PackageSetting) { 3679 final PackageSetting ps = (PackageSetting) obj; 3680 return new String[] { ps.name }; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 @Override 3687 public String getNameForUid(int uid) { 3688 // reader 3689 synchronized (mPackages) { 3690 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3691 if (obj instanceof SharedUserSetting) { 3692 final SharedUserSetting sus = (SharedUserSetting) obj; 3693 return sus.name + ":" + sus.userId; 3694 } else if (obj instanceof PackageSetting) { 3695 final PackageSetting ps = (PackageSetting) obj; 3696 return ps.name; 3697 } 3698 } 3699 return null; 3700 } 3701 3702 @Override 3703 public int getUidForSharedUser(String sharedUserName) { 3704 if(sharedUserName == null) { 3705 return -1; 3706 } 3707 // reader 3708 synchronized (mPackages) { 3709 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3710 if (suid == null) { 3711 return -1; 3712 } 3713 return suid.userId; 3714 } 3715 } 3716 3717 @Override 3718 public int getFlagsForUid(int uid) { 3719 synchronized (mPackages) { 3720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3721 if (obj instanceof SharedUserSetting) { 3722 final SharedUserSetting sus = (SharedUserSetting) obj; 3723 return sus.pkgFlags; 3724 } else if (obj instanceof PackageSetting) { 3725 final PackageSetting ps = (PackageSetting) obj; 3726 return ps.pkgFlags; 3727 } 3728 } 3729 return 0; 3730 } 3731 3732 @Override 3733 public int getPrivateFlagsForUid(int uid) { 3734 synchronized (mPackages) { 3735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3736 if (obj instanceof SharedUserSetting) { 3737 final SharedUserSetting sus = (SharedUserSetting) obj; 3738 return sus.pkgPrivateFlags; 3739 } else if (obj instanceof PackageSetting) { 3740 final PackageSetting ps = (PackageSetting) obj; 3741 return ps.pkgPrivateFlags; 3742 } 3743 } 3744 return 0; 3745 } 3746 3747 @Override 3748 public boolean isUidPrivileged(int uid) { 3749 uid = UserHandle.getAppId(uid); 3750 // reader 3751 synchronized (mPackages) { 3752 Object obj = mSettings.getUserIdLPr(uid); 3753 if (obj instanceof SharedUserSetting) { 3754 final SharedUserSetting sus = (SharedUserSetting) obj; 3755 final Iterator<PackageSetting> it = sus.packages.iterator(); 3756 while (it.hasNext()) { 3757 if (it.next().isPrivileged()) { 3758 return true; 3759 } 3760 } 3761 } else if (obj instanceof PackageSetting) { 3762 final PackageSetting ps = (PackageSetting) obj; 3763 return ps.isPrivileged(); 3764 } 3765 } 3766 return false; 3767 } 3768 3769 @Override 3770 public String[] getAppOpPermissionPackages(String permissionName) { 3771 synchronized (mPackages) { 3772 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3773 if (pkgs == null) { 3774 return null; 3775 } 3776 return pkgs.toArray(new String[pkgs.size()]); 3777 } 3778 } 3779 3780 @Override 3781 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3782 int flags, int userId) { 3783 if (!sUserManager.exists(userId)) return null; 3784 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3785 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3786 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3787 } 3788 3789 @Override 3790 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3791 IntentFilter filter, int match, ComponentName activity) { 3792 final int userId = UserHandle.getCallingUserId(); 3793 if (DEBUG_PREFERRED) { 3794 Log.v(TAG, "setLastChosenActivity intent=" + intent 3795 + " resolvedType=" + resolvedType 3796 + " flags=" + flags 3797 + " filter=" + filter 3798 + " match=" + match 3799 + " activity=" + activity); 3800 filter.dump(new PrintStreamPrinter(System.out), " "); 3801 } 3802 intent.setComponent(null); 3803 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3804 // Find any earlier preferred or last chosen entries and nuke them 3805 findPreferredActivity(intent, resolvedType, 3806 flags, query, 0, false, true, false, userId); 3807 // Add the new activity as the last chosen for this filter 3808 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3809 "Setting last chosen"); 3810 } 3811 3812 @Override 3813 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3814 final int userId = UserHandle.getCallingUserId(); 3815 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3816 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3817 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3818 false, false, false, userId); 3819 } 3820 3821 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3822 int flags, List<ResolveInfo> query, int userId) { 3823 if (query != null) { 3824 final int N = query.size(); 3825 if (N == 1) { 3826 return query.get(0); 3827 } else if (N > 1) { 3828 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3829 // If there is more than one activity with the same priority, 3830 // then let the user decide between them. 3831 ResolveInfo r0 = query.get(0); 3832 ResolveInfo r1 = query.get(1); 3833 if (DEBUG_INTENT_MATCHING || debug) { 3834 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3835 + r1.activityInfo.name + "=" + r1.priority); 3836 } 3837 // If the first activity has a higher priority, or a different 3838 // default, then it is always desireable to pick it. 3839 if (r0.priority != r1.priority 3840 || r0.preferredOrder != r1.preferredOrder 3841 || r0.isDefault != r1.isDefault) { 3842 return query.get(0); 3843 } 3844 // If we have saved a preference for a preferred activity for 3845 // this Intent, use that. 3846 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3847 flags, query, r0.priority, true, false, debug, userId); 3848 if (ri != null) { 3849 return ri; 3850 } 3851 if (userId != 0) { 3852 ri = new ResolveInfo(mResolveInfo); 3853 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3854 ri.activityInfo.applicationInfo = new ApplicationInfo( 3855 ri.activityInfo.applicationInfo); 3856 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3857 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3858 return ri; 3859 } 3860 return mResolveInfo; 3861 } 3862 } 3863 return null; 3864 } 3865 3866 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3867 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3868 final int N = query.size(); 3869 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3870 .get(userId); 3871 // Get the list of persistent preferred activities that handle the intent 3872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3873 List<PersistentPreferredActivity> pprefs = ppir != null 3874 ? ppir.queryIntent(intent, resolvedType, 3875 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3876 : null; 3877 if (pprefs != null && pprefs.size() > 0) { 3878 final int M = pprefs.size(); 3879 for (int i=0; i<M; i++) { 3880 final PersistentPreferredActivity ppa = pprefs.get(i); 3881 if (DEBUG_PREFERRED || debug) { 3882 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3883 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3884 + "\n component=" + ppa.mComponent); 3885 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3886 } 3887 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3888 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3889 if (DEBUG_PREFERRED || debug) { 3890 Slog.v(TAG, "Found persistent preferred activity:"); 3891 if (ai != null) { 3892 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3893 } else { 3894 Slog.v(TAG, " null"); 3895 } 3896 } 3897 if (ai == null) { 3898 // This previously registered persistent preferred activity 3899 // component is no longer known. Ignore it and do NOT remove it. 3900 continue; 3901 } 3902 for (int j=0; j<N; j++) { 3903 final ResolveInfo ri = query.get(j); 3904 if (!ri.activityInfo.applicationInfo.packageName 3905 .equals(ai.applicationInfo.packageName)) { 3906 continue; 3907 } 3908 if (!ri.activityInfo.name.equals(ai.name)) { 3909 continue; 3910 } 3911 // Found a persistent preference that can handle the intent. 3912 if (DEBUG_PREFERRED || debug) { 3913 Slog.v(TAG, "Returning persistent preferred activity: " + 3914 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3915 } 3916 return ri; 3917 } 3918 } 3919 } 3920 return null; 3921 } 3922 3923 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3924 List<ResolveInfo> query, int priority, boolean always, 3925 boolean removeMatches, boolean debug, int userId) { 3926 if (!sUserManager.exists(userId)) return null; 3927 // writer 3928 synchronized (mPackages) { 3929 if (intent.getSelector() != null) { 3930 intent = intent.getSelector(); 3931 } 3932 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3933 3934 // Try to find a matching persistent preferred activity. 3935 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3936 debug, userId); 3937 3938 // If a persistent preferred activity matched, use it. 3939 if (pri != null) { 3940 return pri; 3941 } 3942 3943 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3944 // Get the list of preferred activities that handle the intent 3945 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3946 List<PreferredActivity> prefs = pir != null 3947 ? pir.queryIntent(intent, resolvedType, 3948 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3949 : null; 3950 if (prefs != null && prefs.size() > 0) { 3951 boolean changed = false; 3952 try { 3953 // First figure out how good the original match set is. 3954 // We will only allow preferred activities that came 3955 // from the same match quality. 3956 int match = 0; 3957 3958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3959 3960 final int N = query.size(); 3961 for (int j=0; j<N; j++) { 3962 final ResolveInfo ri = query.get(j); 3963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3964 + ": 0x" + Integer.toHexString(match)); 3965 if (ri.match > match) { 3966 match = ri.match; 3967 } 3968 } 3969 3970 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3971 + Integer.toHexString(match)); 3972 3973 match &= IntentFilter.MATCH_CATEGORY_MASK; 3974 final int M = prefs.size(); 3975 for (int i=0; i<M; i++) { 3976 final PreferredActivity pa = prefs.get(i); 3977 if (DEBUG_PREFERRED || debug) { 3978 Slog.v(TAG, "Checking PreferredActivity ds=" 3979 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3980 + "\n component=" + pa.mPref.mComponent); 3981 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3982 } 3983 if (pa.mPref.mMatch != match) { 3984 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3985 + Integer.toHexString(pa.mPref.mMatch)); 3986 continue; 3987 } 3988 // If it's not an "always" type preferred activity and that's what we're 3989 // looking for, skip it. 3990 if (always && !pa.mPref.mAlways) { 3991 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3992 continue; 3993 } 3994 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3995 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3996 if (DEBUG_PREFERRED || debug) { 3997 Slog.v(TAG, "Found preferred activity:"); 3998 if (ai != null) { 3999 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4000 } else { 4001 Slog.v(TAG, " null"); 4002 } 4003 } 4004 if (ai == null) { 4005 // This previously registered preferred activity 4006 // component is no longer known. Most likely an update 4007 // to the app was installed and in the new version this 4008 // component no longer exists. Clean it up by removing 4009 // it from the preferred activities list, and skip it. 4010 Slog.w(TAG, "Removing dangling preferred activity: " 4011 + pa.mPref.mComponent); 4012 pir.removeFilter(pa); 4013 changed = true; 4014 continue; 4015 } 4016 for (int j=0; j<N; j++) { 4017 final ResolveInfo ri = query.get(j); 4018 if (!ri.activityInfo.applicationInfo.packageName 4019 .equals(ai.applicationInfo.packageName)) { 4020 continue; 4021 } 4022 if (!ri.activityInfo.name.equals(ai.name)) { 4023 continue; 4024 } 4025 4026 if (removeMatches) { 4027 pir.removeFilter(pa); 4028 changed = true; 4029 if (DEBUG_PREFERRED) { 4030 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4031 } 4032 break; 4033 } 4034 4035 // Okay we found a previously set preferred or last chosen app. 4036 // If the result set is different from when this 4037 // was created, we need to clear it and re-ask the 4038 // user their preference, if we're looking for an "always" type entry. 4039 if (always && !pa.mPref.sameSet(query)) { 4040 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4041 + intent + " type " + resolvedType); 4042 if (DEBUG_PREFERRED) { 4043 Slog.v(TAG, "Removing preferred activity since set changed " 4044 + pa.mPref.mComponent); 4045 } 4046 pir.removeFilter(pa); 4047 // Re-add the filter as a "last chosen" entry (!always) 4048 PreferredActivity lastChosen = new PreferredActivity( 4049 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4050 pir.addFilter(lastChosen); 4051 changed = true; 4052 return null; 4053 } 4054 4055 // Yay! Either the set matched or we're looking for the last chosen 4056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4057 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4058 return ri; 4059 } 4060 } 4061 } finally { 4062 if (changed) { 4063 if (DEBUG_PREFERRED) { 4064 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4065 } 4066 scheduleWritePackageRestrictionsLocked(userId); 4067 } 4068 } 4069 } 4070 } 4071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4072 return null; 4073 } 4074 4075 /* 4076 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4077 */ 4078 @Override 4079 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4080 int targetUserId) { 4081 mContext.enforceCallingOrSelfPermission( 4082 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4083 List<CrossProfileIntentFilter> matches = 4084 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4085 if (matches != null) { 4086 int size = matches.size(); 4087 for (int i = 0; i < size; i++) { 4088 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4089 } 4090 } 4091 return false; 4092 } 4093 4094 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4095 String resolvedType, int userId) { 4096 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4097 if (resolver != null) { 4098 return resolver.queryIntent(intent, resolvedType, false, userId); 4099 } 4100 return null; 4101 } 4102 4103 @Override 4104 public List<ResolveInfo> queryIntentActivities(Intent intent, 4105 String resolvedType, int flags, int userId) { 4106 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4107 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4108 ComponentName comp = intent.getComponent(); 4109 if (comp == null) { 4110 if (intent.getSelector() != null) { 4111 intent = intent.getSelector(); 4112 comp = intent.getComponent(); 4113 } 4114 } 4115 4116 if (comp != null) { 4117 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4118 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4119 if (ai != null) { 4120 final ResolveInfo ri = new ResolveInfo(); 4121 ri.activityInfo = ai; 4122 list.add(ri); 4123 } 4124 return list; 4125 } 4126 4127 // reader 4128 synchronized (mPackages) { 4129 final String pkgName = intent.getPackage(); 4130 if (pkgName == null) { 4131 List<CrossProfileIntentFilter> matchingFilters = 4132 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4133 // Check for results that need to skip the current profile. 4134 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4135 resolvedType, flags, userId); 4136 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4137 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4138 result.add(resolveInfo); 4139 return filterIfNotPrimaryUser(result, userId); 4140 } 4141 4142 // Check for results in the current profile. 4143 List<ResolveInfo> result = mActivities.queryIntent( 4144 intent, resolvedType, flags, userId); 4145 4146 // Check for cross profile results. 4147 resolveInfo = queryCrossProfileIntents( 4148 matchingFilters, intent, resolvedType, flags, userId); 4149 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4150 result.add(resolveInfo); 4151 Collections.sort(result, mResolvePrioritySorter); 4152 } 4153 result = filterIfNotPrimaryUser(result, userId); 4154 if (result.size() > 1 && hasWebURI(intent)) { 4155 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4156 } 4157 return result; 4158 } 4159 final PackageParser.Package pkg = mPackages.get(pkgName); 4160 if (pkg != null) { 4161 return filterIfNotPrimaryUser( 4162 mActivities.queryIntentForPackage( 4163 intent, resolvedType, flags, pkg.activities, userId), 4164 userId); 4165 } 4166 return new ArrayList<ResolveInfo>(); 4167 } 4168 } 4169 4170 private boolean isUserEnabled(int userId) { 4171 long callingId = Binder.clearCallingIdentity(); 4172 try { 4173 UserInfo userInfo = sUserManager.getUserInfo(userId); 4174 return userInfo != null && userInfo.isEnabled(); 4175 } finally { 4176 Binder.restoreCallingIdentity(callingId); 4177 } 4178 } 4179 4180 /** 4181 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4182 * 4183 * @return filtered list 4184 */ 4185 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4186 if (userId == UserHandle.USER_OWNER) { 4187 return resolveInfos; 4188 } 4189 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4190 ResolveInfo info = resolveInfos.get(i); 4191 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4192 resolveInfos.remove(i); 4193 } 4194 } 4195 return resolveInfos; 4196 } 4197 4198 private static boolean hasWebURI(Intent intent) { 4199 if (intent.getData() == null) { 4200 return false; 4201 } 4202 final String scheme = intent.getScheme(); 4203 if (TextUtils.isEmpty(scheme)) { 4204 return false; 4205 } 4206 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4207 } 4208 4209 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4210 int flags, List<ResolveInfo> candidates) { 4211 if (DEBUG_PREFERRED) { 4212 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4213 candidates.size()); 4214 } 4215 4216 final int userId = UserHandle.getCallingUserId(); 4217 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4218 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4219 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4220 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4221 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4222 4223 synchronized (mPackages) { 4224 final int count = candidates.size(); 4225 // First, try to use the domain prefered App. Partition the candidates into four lists: 4226 // one for the final results, one for the "do not use ever", one for "undefined status" 4227 // and finally one for "Browser App type". 4228 for (int n=0; n<count; n++) { 4229 ResolveInfo info = candidates.get(n); 4230 String packageName = info.activityInfo.packageName; 4231 PackageSetting ps = mSettings.mPackages.get(packageName); 4232 if (ps != null) { 4233 // Add to the special match all list (Browser use case) 4234 if (info.handleAllWebDataURI) { 4235 matchAllList.add(info); 4236 continue; 4237 } 4238 // Try to get the status from User settings first 4239 int status = getDomainVerificationStatusLPr(ps, userId); 4240 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4241 alwaysList.add(info); 4242 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4243 neverList.add(info); 4244 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4245 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4246 undefinedList.add(info); 4247 } 4248 } 4249 } 4250 // First try to add the "always" if there is any 4251 if (alwaysList.size() > 0) { 4252 result.addAll(alwaysList); 4253 } else { 4254 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4255 result.addAll(undefinedList); 4256 // Also add Browsers (all of them or only the default one) 4257 if ((flags & MATCH_ALL) != 0) { 4258 result.addAll(matchAllList); 4259 } else { 4260 // Try to add the Default Browser if we can 4261 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4262 UserHandle.myUserId()); 4263 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4264 boolean defaultBrowserFound = false; 4265 final int browserCount = matchAllList.size(); 4266 for (int n=0; n<browserCount; n++) { 4267 ResolveInfo browser = matchAllList.get(n); 4268 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4269 result.add(browser); 4270 defaultBrowserFound = true; 4271 break; 4272 } 4273 } 4274 if (!defaultBrowserFound) { 4275 result.addAll(matchAllList); 4276 } 4277 } else { 4278 result.addAll(matchAllList); 4279 } 4280 } 4281 4282 // If there is nothing selected, add all candidates and remove the ones that the User 4283 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4284 if (result.size() == 0) { 4285 result.addAll(candidates); 4286 result.removeAll(neverList); 4287 } 4288 } 4289 } 4290 if (DEBUG_PREFERRED) { 4291 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4292 result.size()); 4293 } 4294 return result; 4295 } 4296 4297 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4298 int status = ps.getDomainVerificationStatusForUser(userId); 4299 // if none available, get the master status 4300 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4301 if (ps.getIntentFilterVerificationInfo() != null) { 4302 status = ps.getIntentFilterVerificationInfo().getStatus(); 4303 } 4304 } 4305 return status; 4306 } 4307 4308 private ResolveInfo querySkipCurrentProfileIntents( 4309 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4310 int flags, int sourceUserId) { 4311 if (matchingFilters != null) { 4312 int size = matchingFilters.size(); 4313 for (int i = 0; i < size; i ++) { 4314 CrossProfileIntentFilter filter = matchingFilters.get(i); 4315 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4316 // Checking if there are activities in the target user that can handle the 4317 // intent. 4318 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4319 flags, sourceUserId); 4320 if (resolveInfo != null) { 4321 return resolveInfo; 4322 } 4323 } 4324 } 4325 } 4326 return null; 4327 } 4328 4329 // Return matching ResolveInfo if any for skip current profile intent filters. 4330 private ResolveInfo queryCrossProfileIntents( 4331 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4332 int flags, int sourceUserId) { 4333 if (matchingFilters != null) { 4334 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4335 // match the same intent. For performance reasons, it is better not to 4336 // run queryIntent twice for the same userId 4337 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4338 int size = matchingFilters.size(); 4339 for (int i = 0; i < size; i++) { 4340 CrossProfileIntentFilter filter = matchingFilters.get(i); 4341 int targetUserId = filter.getTargetUserId(); 4342 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4343 && !alreadyTriedUserIds.get(targetUserId)) { 4344 // Checking if there are activities in the target user that can handle the 4345 // intent. 4346 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4347 flags, sourceUserId); 4348 if (resolveInfo != null) return resolveInfo; 4349 alreadyTriedUserIds.put(targetUserId, true); 4350 } 4351 } 4352 } 4353 return null; 4354 } 4355 4356 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4357 String resolvedType, int flags, int sourceUserId) { 4358 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4359 resolvedType, flags, filter.getTargetUserId()); 4360 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4361 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4362 } 4363 return null; 4364 } 4365 4366 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4367 int sourceUserId, int targetUserId) { 4368 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4369 String className; 4370 if (targetUserId == UserHandle.USER_OWNER) { 4371 className = FORWARD_INTENT_TO_USER_OWNER; 4372 } else { 4373 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4374 } 4375 ComponentName forwardingActivityComponentName = new ComponentName( 4376 mAndroidApplication.packageName, className); 4377 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4378 sourceUserId); 4379 if (targetUserId == UserHandle.USER_OWNER) { 4380 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4381 forwardingResolveInfo.noResourceId = true; 4382 } 4383 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4384 forwardingResolveInfo.priority = 0; 4385 forwardingResolveInfo.preferredOrder = 0; 4386 forwardingResolveInfo.match = 0; 4387 forwardingResolveInfo.isDefault = true; 4388 forwardingResolveInfo.filter = filter; 4389 forwardingResolveInfo.targetUserId = targetUserId; 4390 return forwardingResolveInfo; 4391 } 4392 4393 @Override 4394 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4395 Intent[] specifics, String[] specificTypes, Intent intent, 4396 String resolvedType, int flags, int userId) { 4397 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4398 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4399 false, "query intent activity options"); 4400 final String resultsAction = intent.getAction(); 4401 4402 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4403 | PackageManager.GET_RESOLVED_FILTER, userId); 4404 4405 if (DEBUG_INTENT_MATCHING) { 4406 Log.v(TAG, "Query " + intent + ": " + results); 4407 } 4408 4409 int specificsPos = 0; 4410 int N; 4411 4412 // todo: note that the algorithm used here is O(N^2). This 4413 // isn't a problem in our current environment, but if we start running 4414 // into situations where we have more than 5 or 10 matches then this 4415 // should probably be changed to something smarter... 4416 4417 // First we go through and resolve each of the specific items 4418 // that were supplied, taking care of removing any corresponding 4419 // duplicate items in the generic resolve list. 4420 if (specifics != null) { 4421 for (int i=0; i<specifics.length; i++) { 4422 final Intent sintent = specifics[i]; 4423 if (sintent == null) { 4424 continue; 4425 } 4426 4427 if (DEBUG_INTENT_MATCHING) { 4428 Log.v(TAG, "Specific #" + i + ": " + sintent); 4429 } 4430 4431 String action = sintent.getAction(); 4432 if (resultsAction != null && resultsAction.equals(action)) { 4433 // If this action was explicitly requested, then don't 4434 // remove things that have it. 4435 action = null; 4436 } 4437 4438 ResolveInfo ri = null; 4439 ActivityInfo ai = null; 4440 4441 ComponentName comp = sintent.getComponent(); 4442 if (comp == null) { 4443 ri = resolveIntent( 4444 sintent, 4445 specificTypes != null ? specificTypes[i] : null, 4446 flags, userId); 4447 if (ri == null) { 4448 continue; 4449 } 4450 if (ri == mResolveInfo) { 4451 // ACK! Must do something better with this. 4452 } 4453 ai = ri.activityInfo; 4454 comp = new ComponentName(ai.applicationInfo.packageName, 4455 ai.name); 4456 } else { 4457 ai = getActivityInfo(comp, flags, userId); 4458 if (ai == null) { 4459 continue; 4460 } 4461 } 4462 4463 // Look for any generic query activities that are duplicates 4464 // of this specific one, and remove them from the results. 4465 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4466 N = results.size(); 4467 int j; 4468 for (j=specificsPos; j<N; j++) { 4469 ResolveInfo sri = results.get(j); 4470 if ((sri.activityInfo.name.equals(comp.getClassName()) 4471 && sri.activityInfo.applicationInfo.packageName.equals( 4472 comp.getPackageName())) 4473 || (action != null && sri.filter.matchAction(action))) { 4474 results.remove(j); 4475 if (DEBUG_INTENT_MATCHING) Log.v( 4476 TAG, "Removing duplicate item from " + j 4477 + " due to specific " + specificsPos); 4478 if (ri == null) { 4479 ri = sri; 4480 } 4481 j--; 4482 N--; 4483 } 4484 } 4485 4486 // Add this specific item to its proper place. 4487 if (ri == null) { 4488 ri = new ResolveInfo(); 4489 ri.activityInfo = ai; 4490 } 4491 results.add(specificsPos, ri); 4492 ri.specificIndex = i; 4493 specificsPos++; 4494 } 4495 } 4496 4497 // Now we go through the remaining generic results and remove any 4498 // duplicate actions that are found here. 4499 N = results.size(); 4500 for (int i=specificsPos; i<N-1; i++) { 4501 final ResolveInfo rii = results.get(i); 4502 if (rii.filter == null) { 4503 continue; 4504 } 4505 4506 // Iterate over all of the actions of this result's intent 4507 // filter... typically this should be just one. 4508 final Iterator<String> it = rii.filter.actionsIterator(); 4509 if (it == null) { 4510 continue; 4511 } 4512 while (it.hasNext()) { 4513 final String action = it.next(); 4514 if (resultsAction != null && resultsAction.equals(action)) { 4515 // If this action was explicitly requested, then don't 4516 // remove things that have it. 4517 continue; 4518 } 4519 for (int j=i+1; j<N; j++) { 4520 final ResolveInfo rij = results.get(j); 4521 if (rij.filter != null && rij.filter.hasAction(action)) { 4522 results.remove(j); 4523 if (DEBUG_INTENT_MATCHING) Log.v( 4524 TAG, "Removing duplicate item from " + j 4525 + " due to action " + action + " at " + i); 4526 j--; 4527 N--; 4528 } 4529 } 4530 } 4531 4532 // If the caller didn't request filter information, drop it now 4533 // so we don't have to marshall/unmarshall it. 4534 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4535 rii.filter = null; 4536 } 4537 } 4538 4539 // Filter out the caller activity if so requested. 4540 if (caller != null) { 4541 N = results.size(); 4542 for (int i=0; i<N; i++) { 4543 ActivityInfo ainfo = results.get(i).activityInfo; 4544 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4545 && caller.getClassName().equals(ainfo.name)) { 4546 results.remove(i); 4547 break; 4548 } 4549 } 4550 } 4551 4552 // If the caller didn't request filter information, 4553 // drop them now so we don't have to 4554 // marshall/unmarshall it. 4555 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4556 N = results.size(); 4557 for (int i=0; i<N; i++) { 4558 results.get(i).filter = null; 4559 } 4560 } 4561 4562 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4563 return results; 4564 } 4565 4566 @Override 4567 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4568 int userId) { 4569 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4570 ComponentName comp = intent.getComponent(); 4571 if (comp == null) { 4572 if (intent.getSelector() != null) { 4573 intent = intent.getSelector(); 4574 comp = intent.getComponent(); 4575 } 4576 } 4577 if (comp != null) { 4578 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4579 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4580 if (ai != null) { 4581 ResolveInfo ri = new ResolveInfo(); 4582 ri.activityInfo = ai; 4583 list.add(ri); 4584 } 4585 return list; 4586 } 4587 4588 // reader 4589 synchronized (mPackages) { 4590 String pkgName = intent.getPackage(); 4591 if (pkgName == null) { 4592 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4593 } 4594 final PackageParser.Package pkg = mPackages.get(pkgName); 4595 if (pkg != null) { 4596 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4597 userId); 4598 } 4599 return null; 4600 } 4601 } 4602 4603 @Override 4604 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4605 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4606 if (!sUserManager.exists(userId)) return null; 4607 if (query != null) { 4608 if (query.size() >= 1) { 4609 // If there is more than one service with the same priority, 4610 // just arbitrarily pick the first one. 4611 return query.get(0); 4612 } 4613 } 4614 return null; 4615 } 4616 4617 @Override 4618 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4619 int userId) { 4620 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4621 ComponentName comp = intent.getComponent(); 4622 if (comp == null) { 4623 if (intent.getSelector() != null) { 4624 intent = intent.getSelector(); 4625 comp = intent.getComponent(); 4626 } 4627 } 4628 if (comp != null) { 4629 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4630 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4631 if (si != null) { 4632 final ResolveInfo ri = new ResolveInfo(); 4633 ri.serviceInfo = si; 4634 list.add(ri); 4635 } 4636 return list; 4637 } 4638 4639 // reader 4640 synchronized (mPackages) { 4641 String pkgName = intent.getPackage(); 4642 if (pkgName == null) { 4643 return mServices.queryIntent(intent, resolvedType, flags, userId); 4644 } 4645 final PackageParser.Package pkg = mPackages.get(pkgName); 4646 if (pkg != null) { 4647 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4648 userId); 4649 } 4650 return null; 4651 } 4652 } 4653 4654 @Override 4655 public List<ResolveInfo> queryIntentContentProviders( 4656 Intent intent, String resolvedType, int flags, int userId) { 4657 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4658 ComponentName comp = intent.getComponent(); 4659 if (comp == null) { 4660 if (intent.getSelector() != null) { 4661 intent = intent.getSelector(); 4662 comp = intent.getComponent(); 4663 } 4664 } 4665 if (comp != null) { 4666 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4667 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4668 if (pi != null) { 4669 final ResolveInfo ri = new ResolveInfo(); 4670 ri.providerInfo = pi; 4671 list.add(ri); 4672 } 4673 return list; 4674 } 4675 4676 // reader 4677 synchronized (mPackages) { 4678 String pkgName = intent.getPackage(); 4679 if (pkgName == null) { 4680 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4681 } 4682 final PackageParser.Package pkg = mPackages.get(pkgName); 4683 if (pkg != null) { 4684 return mProviders.queryIntentForPackage( 4685 intent, resolvedType, flags, pkg.providers, userId); 4686 } 4687 return null; 4688 } 4689 } 4690 4691 @Override 4692 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4693 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4694 4695 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4696 4697 // writer 4698 synchronized (mPackages) { 4699 ArrayList<PackageInfo> list; 4700 if (listUninstalled) { 4701 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4702 for (PackageSetting ps : mSettings.mPackages.values()) { 4703 PackageInfo pi; 4704 if (ps.pkg != null) { 4705 pi = generatePackageInfo(ps.pkg, flags, userId); 4706 } else { 4707 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4708 } 4709 if (pi != null) { 4710 list.add(pi); 4711 } 4712 } 4713 } else { 4714 list = new ArrayList<PackageInfo>(mPackages.size()); 4715 for (PackageParser.Package p : mPackages.values()) { 4716 PackageInfo pi = generatePackageInfo(p, flags, userId); 4717 if (pi != null) { 4718 list.add(pi); 4719 } 4720 } 4721 } 4722 4723 return new ParceledListSlice<PackageInfo>(list); 4724 } 4725 } 4726 4727 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4728 String[] permissions, boolean[] tmp, int flags, int userId) { 4729 int numMatch = 0; 4730 final PermissionsState permissionsState = ps.getPermissionsState(); 4731 for (int i=0; i<permissions.length; i++) { 4732 final String permission = permissions[i]; 4733 if (permissionsState.hasPermission(permission, userId)) { 4734 tmp[i] = true; 4735 numMatch++; 4736 } else { 4737 tmp[i] = false; 4738 } 4739 } 4740 if (numMatch == 0) { 4741 return; 4742 } 4743 PackageInfo pi; 4744 if (ps.pkg != null) { 4745 pi = generatePackageInfo(ps.pkg, flags, userId); 4746 } else { 4747 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4748 } 4749 // The above might return null in cases of uninstalled apps or install-state 4750 // skew across users/profiles. 4751 if (pi != null) { 4752 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4753 if (numMatch == permissions.length) { 4754 pi.requestedPermissions = permissions; 4755 } else { 4756 pi.requestedPermissions = new String[numMatch]; 4757 numMatch = 0; 4758 for (int i=0; i<permissions.length; i++) { 4759 if (tmp[i]) { 4760 pi.requestedPermissions[numMatch] = permissions[i]; 4761 numMatch++; 4762 } 4763 } 4764 } 4765 } 4766 list.add(pi); 4767 } 4768 } 4769 4770 @Override 4771 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4772 String[] permissions, int flags, int userId) { 4773 if (!sUserManager.exists(userId)) return null; 4774 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4775 4776 // writer 4777 synchronized (mPackages) { 4778 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4779 boolean[] tmpBools = new boolean[permissions.length]; 4780 if (listUninstalled) { 4781 for (PackageSetting ps : mSettings.mPackages.values()) { 4782 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4783 } 4784 } else { 4785 for (PackageParser.Package pkg : mPackages.values()) { 4786 PackageSetting ps = (PackageSetting)pkg.mExtras; 4787 if (ps != null) { 4788 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4789 userId); 4790 } 4791 } 4792 } 4793 4794 return new ParceledListSlice<PackageInfo>(list); 4795 } 4796 } 4797 4798 @Override 4799 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4800 if (!sUserManager.exists(userId)) return null; 4801 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4802 4803 // writer 4804 synchronized (mPackages) { 4805 ArrayList<ApplicationInfo> list; 4806 if (listUninstalled) { 4807 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4808 for (PackageSetting ps : mSettings.mPackages.values()) { 4809 ApplicationInfo ai; 4810 if (ps.pkg != null) { 4811 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4812 ps.readUserState(userId), userId); 4813 } else { 4814 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4815 } 4816 if (ai != null) { 4817 list.add(ai); 4818 } 4819 } 4820 } else { 4821 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4822 for (PackageParser.Package p : mPackages.values()) { 4823 if (p.mExtras != null) { 4824 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4825 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4826 if (ai != null) { 4827 list.add(ai); 4828 } 4829 } 4830 } 4831 } 4832 4833 return new ParceledListSlice<ApplicationInfo>(list); 4834 } 4835 } 4836 4837 public List<ApplicationInfo> getPersistentApplications(int flags) { 4838 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4839 4840 // reader 4841 synchronized (mPackages) { 4842 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4843 final int userId = UserHandle.getCallingUserId(); 4844 while (i.hasNext()) { 4845 final PackageParser.Package p = i.next(); 4846 if (p.applicationInfo != null 4847 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4848 && (!mSafeMode || isSystemApp(p))) { 4849 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4850 if (ps != null) { 4851 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4852 ps.readUserState(userId), userId); 4853 if (ai != null) { 4854 finalList.add(ai); 4855 } 4856 } 4857 } 4858 } 4859 } 4860 4861 return finalList; 4862 } 4863 4864 @Override 4865 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4866 if (!sUserManager.exists(userId)) return null; 4867 // reader 4868 synchronized (mPackages) { 4869 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4870 PackageSetting ps = provider != null 4871 ? mSettings.mPackages.get(provider.owner.packageName) 4872 : null; 4873 return ps != null 4874 && mSettings.isEnabledLPr(provider.info, flags, userId) 4875 && (!mSafeMode || (provider.info.applicationInfo.flags 4876 &ApplicationInfo.FLAG_SYSTEM) != 0) 4877 ? PackageParser.generateProviderInfo(provider, flags, 4878 ps.readUserState(userId), userId) 4879 : null; 4880 } 4881 } 4882 4883 /** 4884 * @deprecated 4885 */ 4886 @Deprecated 4887 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4888 // reader 4889 synchronized (mPackages) { 4890 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4891 .entrySet().iterator(); 4892 final int userId = UserHandle.getCallingUserId(); 4893 while (i.hasNext()) { 4894 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4895 PackageParser.Provider p = entry.getValue(); 4896 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4897 4898 if (ps != null && p.syncable 4899 && (!mSafeMode || (p.info.applicationInfo.flags 4900 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4901 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4902 ps.readUserState(userId), userId); 4903 if (info != null) { 4904 outNames.add(entry.getKey()); 4905 outInfo.add(info); 4906 } 4907 } 4908 } 4909 } 4910 } 4911 4912 @Override 4913 public List<ProviderInfo> queryContentProviders(String processName, 4914 int uid, int flags) { 4915 ArrayList<ProviderInfo> finalList = null; 4916 // reader 4917 synchronized (mPackages) { 4918 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4919 final int userId = processName != null ? 4920 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4921 while (i.hasNext()) { 4922 final PackageParser.Provider p = i.next(); 4923 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4924 if (ps != null && p.info.authority != null 4925 && (processName == null 4926 || (p.info.processName.equals(processName) 4927 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4928 && mSettings.isEnabledLPr(p.info, flags, userId) 4929 && (!mSafeMode 4930 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4931 if (finalList == null) { 4932 finalList = new ArrayList<ProviderInfo>(3); 4933 } 4934 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4935 ps.readUserState(userId), userId); 4936 if (info != null) { 4937 finalList.add(info); 4938 } 4939 } 4940 } 4941 } 4942 4943 if (finalList != null) { 4944 Collections.sort(finalList, mProviderInitOrderSorter); 4945 } 4946 4947 return finalList; 4948 } 4949 4950 @Override 4951 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4952 int flags) { 4953 // reader 4954 synchronized (mPackages) { 4955 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4956 return PackageParser.generateInstrumentationInfo(i, flags); 4957 } 4958 } 4959 4960 @Override 4961 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4962 int flags) { 4963 ArrayList<InstrumentationInfo> finalList = 4964 new ArrayList<InstrumentationInfo>(); 4965 4966 // reader 4967 synchronized (mPackages) { 4968 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4969 while (i.hasNext()) { 4970 final PackageParser.Instrumentation p = i.next(); 4971 if (targetPackage == null 4972 || targetPackage.equals(p.info.targetPackage)) { 4973 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4974 flags); 4975 if (ii != null) { 4976 finalList.add(ii); 4977 } 4978 } 4979 } 4980 } 4981 4982 return finalList; 4983 } 4984 4985 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4986 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4987 if (overlays == null) { 4988 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4989 return; 4990 } 4991 for (PackageParser.Package opkg : overlays.values()) { 4992 // Not much to do if idmap fails: we already logged the error 4993 // and we certainly don't want to abort installation of pkg simply 4994 // because an overlay didn't fit properly. For these reasons, 4995 // ignore the return value of createIdmapForPackagePairLI. 4996 createIdmapForPackagePairLI(pkg, opkg); 4997 } 4998 } 4999 5000 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5001 PackageParser.Package opkg) { 5002 if (!opkg.mTrustedOverlay) { 5003 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5004 opkg.baseCodePath + ": overlay not trusted"); 5005 return false; 5006 } 5007 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5008 if (overlaySet == null) { 5009 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5010 opkg.baseCodePath + " but target package has no known overlays"); 5011 return false; 5012 } 5013 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5014 // TODO: generate idmap for split APKs 5015 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5016 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5017 + opkg.baseCodePath); 5018 return false; 5019 } 5020 PackageParser.Package[] overlayArray = 5021 overlaySet.values().toArray(new PackageParser.Package[0]); 5022 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5023 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5024 return p1.mOverlayPriority - p2.mOverlayPriority; 5025 } 5026 }; 5027 Arrays.sort(overlayArray, cmp); 5028 5029 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5030 int i = 0; 5031 for (PackageParser.Package p : overlayArray) { 5032 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5033 } 5034 return true; 5035 } 5036 5037 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5038 final File[] files = dir.listFiles(); 5039 if (ArrayUtils.isEmpty(files)) { 5040 Log.d(TAG, "No files in app dir " + dir); 5041 return; 5042 } 5043 5044 if (DEBUG_PACKAGE_SCANNING) { 5045 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5046 + " flags=0x" + Integer.toHexString(parseFlags)); 5047 } 5048 5049 for (File file : files) { 5050 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5051 && !PackageInstallerService.isStageName(file.getName()); 5052 if (!isPackage) { 5053 // Ignore entries which are not packages 5054 continue; 5055 } 5056 try { 5057 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5058 scanFlags, currentTime, null); 5059 } catch (PackageManagerException e) { 5060 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5061 5062 // Delete invalid userdata apps 5063 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5064 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5065 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5066 if (file.isDirectory()) { 5067 mInstaller.rmPackageDir(file.getAbsolutePath()); 5068 } else { 5069 file.delete(); 5070 } 5071 } 5072 } 5073 } 5074 } 5075 5076 private static File getSettingsProblemFile() { 5077 File dataDir = Environment.getDataDirectory(); 5078 File systemDir = new File(dataDir, "system"); 5079 File fname = new File(systemDir, "uiderrors.txt"); 5080 return fname; 5081 } 5082 5083 static void reportSettingsProblem(int priority, String msg) { 5084 logCriticalInfo(priority, msg); 5085 } 5086 5087 static void logCriticalInfo(int priority, String msg) { 5088 Slog.println(priority, TAG, msg); 5089 EventLogTags.writePmCriticalInfo(msg); 5090 try { 5091 File fname = getSettingsProblemFile(); 5092 FileOutputStream out = new FileOutputStream(fname, true); 5093 PrintWriter pw = new FastPrintWriter(out); 5094 SimpleDateFormat formatter = new SimpleDateFormat(); 5095 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5096 pw.println(dateString + ": " + msg); 5097 pw.close(); 5098 FileUtils.setPermissions( 5099 fname.toString(), 5100 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5101 -1, -1); 5102 } catch (java.io.IOException e) { 5103 } 5104 } 5105 5106 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5107 PackageParser.Package pkg, File srcFile, int parseFlags) 5108 throws PackageManagerException { 5109 if (ps != null 5110 && ps.codePath.equals(srcFile) 5111 && ps.timeStamp == srcFile.lastModified() 5112 && !isCompatSignatureUpdateNeeded(pkg) 5113 && !isRecoverSignatureUpdateNeeded(pkg)) { 5114 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5116 ArraySet<PublicKey> signingKs; 5117 synchronized (mPackages) { 5118 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5119 } 5120 if (ps.signatures.mSignatures != null 5121 && ps.signatures.mSignatures.length != 0 5122 && signingKs != null) { 5123 // Optimization: reuse the existing cached certificates 5124 // if the package appears to be unchanged. 5125 pkg.mSignatures = ps.signatures.mSignatures; 5126 pkg.mSigningKeys = signingKs; 5127 return; 5128 } 5129 5130 Slog.w(TAG, "PackageSetting for " + ps.name 5131 + " is missing signatures. Collecting certs again to recover them."); 5132 } else { 5133 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5134 } 5135 5136 try { 5137 pp.collectCertificates(pkg, parseFlags); 5138 pp.collectManifestDigest(pkg); 5139 } catch (PackageParserException e) { 5140 throw PackageManagerException.from(e); 5141 } 5142 } 5143 5144 /* 5145 * Scan a package and return the newly parsed package. 5146 * Returns null in case of errors and the error code is stored in mLastScanError 5147 */ 5148 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5149 long currentTime, UserHandle user) throws PackageManagerException { 5150 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5151 parseFlags |= mDefParseFlags; 5152 PackageParser pp = new PackageParser(); 5153 pp.setSeparateProcesses(mSeparateProcesses); 5154 pp.setOnlyCoreApps(mOnlyCore); 5155 pp.setDisplayMetrics(mMetrics); 5156 5157 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5158 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5159 } 5160 5161 final PackageParser.Package pkg; 5162 try { 5163 pkg = pp.parsePackage(scanFile, parseFlags); 5164 } catch (PackageParserException e) { 5165 throw PackageManagerException.from(e); 5166 } 5167 5168 PackageSetting ps = null; 5169 PackageSetting updatedPkg; 5170 // reader 5171 synchronized (mPackages) { 5172 // Look to see if we already know about this package. 5173 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5174 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5175 // This package has been renamed to its original name. Let's 5176 // use that. 5177 ps = mSettings.peekPackageLPr(oldName); 5178 } 5179 // If there was no original package, see one for the real package name. 5180 if (ps == null) { 5181 ps = mSettings.peekPackageLPr(pkg.packageName); 5182 } 5183 // Check to see if this package could be hiding/updating a system 5184 // package. Must look for it either under the original or real 5185 // package name depending on our state. 5186 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5187 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5188 } 5189 boolean updatedPkgBetter = false; 5190 // First check if this is a system package that may involve an update 5191 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5192 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5193 // it needs to drop FLAG_PRIVILEGED. 5194 if (locationIsPrivileged(scanFile)) { 5195 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5196 } else { 5197 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5198 } 5199 5200 if (ps != null && !ps.codePath.equals(scanFile)) { 5201 // The path has changed from what was last scanned... check the 5202 // version of the new path against what we have stored to determine 5203 // what to do. 5204 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5205 if (pkg.mVersionCode <= ps.versionCode) { 5206 // The system package has been updated and the code path does not match 5207 // Ignore entry. Skip it. 5208 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5209 + " ignored: updated version " + ps.versionCode 5210 + " better than this " + pkg.mVersionCode); 5211 if (!updatedPkg.codePath.equals(scanFile)) { 5212 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5213 + ps.name + " changing from " + updatedPkg.codePathString 5214 + " to " + scanFile); 5215 updatedPkg.codePath = scanFile; 5216 updatedPkg.codePathString = scanFile.toString(); 5217 updatedPkg.resourcePath = scanFile; 5218 updatedPkg.resourcePathString = scanFile.toString(); 5219 } 5220 updatedPkg.pkg = pkg; 5221 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5222 } else { 5223 // The current app on the system partition is better than 5224 // what we have updated to on the data partition; switch 5225 // back to the system partition version. 5226 // At this point, its safely assumed that package installation for 5227 // apps in system partition will go through. If not there won't be a working 5228 // version of the app 5229 // writer 5230 synchronized (mPackages) { 5231 // Just remove the loaded entries from package lists. 5232 mPackages.remove(ps.name); 5233 } 5234 5235 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5236 + " reverting from " + ps.codePathString 5237 + ": new version " + pkg.mVersionCode 5238 + " better than installed " + ps.versionCode); 5239 5240 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5241 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5242 synchronized (mInstallLock) { 5243 args.cleanUpResourcesLI(); 5244 } 5245 synchronized (mPackages) { 5246 mSettings.enableSystemPackageLPw(ps.name); 5247 } 5248 updatedPkgBetter = true; 5249 } 5250 } 5251 } 5252 5253 if (updatedPkg != null) { 5254 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5255 // initially 5256 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5257 5258 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5259 // flag set initially 5260 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5261 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5262 } 5263 } 5264 5265 // Verify certificates against what was last scanned 5266 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5267 5268 /* 5269 * A new system app appeared, but we already had a non-system one of the 5270 * same name installed earlier. 5271 */ 5272 boolean shouldHideSystemApp = false; 5273 if (updatedPkg == null && ps != null 5274 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5275 /* 5276 * Check to make sure the signatures match first. If they don't, 5277 * wipe the installed application and its data. 5278 */ 5279 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5280 != PackageManager.SIGNATURE_MATCH) { 5281 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5282 + " signatures don't match existing userdata copy; removing"); 5283 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5284 ps = null; 5285 } else { 5286 /* 5287 * If the newly-added system app is an older version than the 5288 * already installed version, hide it. It will be scanned later 5289 * and re-added like an update. 5290 */ 5291 if (pkg.mVersionCode <= ps.versionCode) { 5292 shouldHideSystemApp = true; 5293 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5294 + " but new version " + pkg.mVersionCode + " better than installed " 5295 + ps.versionCode + "; hiding system"); 5296 } else { 5297 /* 5298 * The newly found system app is a newer version that the 5299 * one previously installed. Simply remove the 5300 * already-installed application and replace it with our own 5301 * while keeping the application data. 5302 */ 5303 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5304 + " reverting from " + ps.codePathString + ": new version " 5305 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5306 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5307 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5308 synchronized (mInstallLock) { 5309 args.cleanUpResourcesLI(); 5310 } 5311 } 5312 } 5313 } 5314 5315 // The apk is forward locked (not public) if its code and resources 5316 // are kept in different files. (except for app in either system or 5317 // vendor path). 5318 // TODO grab this value from PackageSettings 5319 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5320 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5321 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5322 } 5323 } 5324 5325 // TODO: extend to support forward-locked splits 5326 String resourcePath = null; 5327 String baseResourcePath = null; 5328 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5329 if (ps != null && ps.resourcePathString != null) { 5330 resourcePath = ps.resourcePathString; 5331 baseResourcePath = ps.resourcePathString; 5332 } else { 5333 // Should not happen at all. Just log an error. 5334 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5335 } 5336 } else { 5337 resourcePath = pkg.codePath; 5338 baseResourcePath = pkg.baseCodePath; 5339 } 5340 5341 // Set application objects path explicitly. 5342 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5343 pkg.applicationInfo.setCodePath(pkg.codePath); 5344 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5345 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5346 pkg.applicationInfo.setResourcePath(resourcePath); 5347 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5348 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5349 5350 // Note that we invoke the following method only if we are about to unpack an application 5351 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5352 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5353 5354 /* 5355 * If the system app should be overridden by a previously installed 5356 * data, hide the system app now and let the /data/app scan pick it up 5357 * again. 5358 */ 5359 if (shouldHideSystemApp) { 5360 synchronized (mPackages) { 5361 /* 5362 * We have to grant systems permissions before we hide, because 5363 * grantPermissions will assume the package update is trying to 5364 * expand its permissions. 5365 */ 5366 grantPermissionsLPw(pkg, true, pkg.packageName); 5367 mSettings.disableSystemPackageLPw(pkg.packageName); 5368 } 5369 } 5370 5371 return scannedPkg; 5372 } 5373 5374 private static String fixProcessName(String defProcessName, 5375 String processName, int uid) { 5376 if (processName == null) { 5377 return defProcessName; 5378 } 5379 return processName; 5380 } 5381 5382 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5383 throws PackageManagerException { 5384 if (pkgSetting.signatures.mSignatures != null) { 5385 // Already existing package. Make sure signatures match 5386 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5387 == PackageManager.SIGNATURE_MATCH; 5388 if (!match) { 5389 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5390 == PackageManager.SIGNATURE_MATCH; 5391 } 5392 if (!match) { 5393 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5394 == PackageManager.SIGNATURE_MATCH; 5395 } 5396 if (!match) { 5397 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5398 + pkg.packageName + " signatures do not match the " 5399 + "previously installed version; ignoring!"); 5400 } 5401 } 5402 5403 // Check for shared user signatures 5404 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5405 // Already existing package. Make sure signatures match 5406 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5407 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5408 if (!match) { 5409 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5410 == PackageManager.SIGNATURE_MATCH; 5411 } 5412 if (!match) { 5413 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5414 == PackageManager.SIGNATURE_MATCH; 5415 } 5416 if (!match) { 5417 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5418 "Package " + pkg.packageName 5419 + " has no signatures that match those in shared user " 5420 + pkgSetting.sharedUser.name + "; ignoring!"); 5421 } 5422 } 5423 } 5424 5425 /** 5426 * Enforces that only the system UID or root's UID can call a method exposed 5427 * via Binder. 5428 * 5429 * @param message used as message if SecurityException is thrown 5430 * @throws SecurityException if the caller is not system or root 5431 */ 5432 private static final void enforceSystemOrRoot(String message) { 5433 final int uid = Binder.getCallingUid(); 5434 if (uid != Process.SYSTEM_UID && uid != 0) { 5435 throw new SecurityException(message); 5436 } 5437 } 5438 5439 @Override 5440 public void performBootDexOpt() { 5441 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5442 5443 // Before everything else, see whether we need to fstrim. 5444 try { 5445 IMountService ms = PackageHelper.getMountService(); 5446 if (ms != null) { 5447 final boolean isUpgrade = isUpgrade(); 5448 boolean doTrim = isUpgrade; 5449 if (doTrim) { 5450 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5451 } else { 5452 final long interval = android.provider.Settings.Global.getLong( 5453 mContext.getContentResolver(), 5454 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5455 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5456 if (interval > 0) { 5457 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5458 if (timeSinceLast > interval) { 5459 doTrim = true; 5460 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5461 + "; running immediately"); 5462 } 5463 } 5464 } 5465 if (doTrim) { 5466 if (!isFirstBoot()) { 5467 try { 5468 ActivityManagerNative.getDefault().showBootMessage( 5469 mContext.getResources().getString( 5470 R.string.android_upgrading_fstrim), true); 5471 } catch (RemoteException e) { 5472 } 5473 } 5474 ms.runMaintenance(); 5475 } 5476 } else { 5477 Slog.e(TAG, "Mount service unavailable!"); 5478 } 5479 } catch (RemoteException e) { 5480 // Can't happen; MountService is local 5481 } 5482 5483 final ArraySet<PackageParser.Package> pkgs; 5484 synchronized (mPackages) { 5485 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5486 } 5487 5488 if (pkgs != null) { 5489 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5490 // in case the device runs out of space. 5491 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5492 // Give priority to core apps. 5493 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5494 PackageParser.Package pkg = it.next(); 5495 if (pkg.coreApp) { 5496 if (DEBUG_DEXOPT) { 5497 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5498 } 5499 sortedPkgs.add(pkg); 5500 it.remove(); 5501 } 5502 } 5503 // Give priority to system apps that listen for pre boot complete. 5504 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5505 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5506 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5507 PackageParser.Package pkg = it.next(); 5508 if (pkgNames.contains(pkg.packageName)) { 5509 if (DEBUG_DEXOPT) { 5510 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5511 } 5512 sortedPkgs.add(pkg); 5513 it.remove(); 5514 } 5515 } 5516 // Give priority to system apps. 5517 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5518 PackageParser.Package pkg = it.next(); 5519 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5520 if (DEBUG_DEXOPT) { 5521 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5522 } 5523 sortedPkgs.add(pkg); 5524 it.remove(); 5525 } 5526 } 5527 // Give priority to updated system apps. 5528 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5529 PackageParser.Package pkg = it.next(); 5530 if (pkg.isUpdatedSystemApp()) { 5531 if (DEBUG_DEXOPT) { 5532 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5533 } 5534 sortedPkgs.add(pkg); 5535 it.remove(); 5536 } 5537 } 5538 // Give priority to apps that listen for boot complete. 5539 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5540 pkgNames = getPackageNamesForIntent(intent); 5541 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5542 PackageParser.Package pkg = it.next(); 5543 if (pkgNames.contains(pkg.packageName)) { 5544 if (DEBUG_DEXOPT) { 5545 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5546 } 5547 sortedPkgs.add(pkg); 5548 it.remove(); 5549 } 5550 } 5551 // Filter out packages that aren't recently used. 5552 filterRecentlyUsedApps(pkgs); 5553 // Add all remaining apps. 5554 for (PackageParser.Package pkg : pkgs) { 5555 if (DEBUG_DEXOPT) { 5556 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5557 } 5558 sortedPkgs.add(pkg); 5559 } 5560 5561 // If we want to be lazy, filter everything that wasn't recently used. 5562 if (mLazyDexOpt) { 5563 filterRecentlyUsedApps(sortedPkgs); 5564 } 5565 5566 int i = 0; 5567 int total = sortedPkgs.size(); 5568 File dataDir = Environment.getDataDirectory(); 5569 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5570 if (lowThreshold == 0) { 5571 throw new IllegalStateException("Invalid low memory threshold"); 5572 } 5573 for (PackageParser.Package pkg : sortedPkgs) { 5574 long usableSpace = dataDir.getUsableSpace(); 5575 if (usableSpace < lowThreshold) { 5576 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5577 break; 5578 } 5579 performBootDexOpt(pkg, ++i, total); 5580 } 5581 } 5582 } 5583 5584 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5585 // Filter out packages that aren't recently used. 5586 // 5587 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5588 // should do a full dexopt. 5589 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5590 int total = pkgs.size(); 5591 int skipped = 0; 5592 long now = System.currentTimeMillis(); 5593 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5594 PackageParser.Package pkg = i.next(); 5595 long then = pkg.mLastPackageUsageTimeInMills; 5596 if (then + mDexOptLRUThresholdInMills < now) { 5597 if (DEBUG_DEXOPT) { 5598 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5599 ((then == 0) ? "never" : new Date(then))); 5600 } 5601 i.remove(); 5602 skipped++; 5603 } 5604 } 5605 if (DEBUG_DEXOPT) { 5606 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5607 } 5608 } 5609 } 5610 5611 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5612 List<ResolveInfo> ris = null; 5613 try { 5614 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5615 intent, null, 0, UserHandle.USER_OWNER); 5616 } catch (RemoteException e) { 5617 } 5618 ArraySet<String> pkgNames = new ArraySet<String>(); 5619 if (ris != null) { 5620 for (ResolveInfo ri : ris) { 5621 pkgNames.add(ri.activityInfo.packageName); 5622 } 5623 } 5624 return pkgNames; 5625 } 5626 5627 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5628 if (DEBUG_DEXOPT) { 5629 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5630 } 5631 if (!isFirstBoot()) { 5632 try { 5633 ActivityManagerNative.getDefault().showBootMessage( 5634 mContext.getResources().getString(R.string.android_upgrading_apk, 5635 curr, total), true); 5636 } catch (RemoteException e) { 5637 } 5638 } 5639 PackageParser.Package p = pkg; 5640 synchronized (mInstallLock) { 5641 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5642 false /* force dex */, false /* defer */, true /* include dependencies */); 5643 } 5644 } 5645 5646 @Override 5647 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5648 return performDexOpt(packageName, instructionSet, false); 5649 } 5650 5651 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5652 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5653 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5654 if (!dexopt && !updateUsage) { 5655 // We aren't going to dexopt or update usage, so bail early. 5656 return false; 5657 } 5658 PackageParser.Package p; 5659 final String targetInstructionSet; 5660 synchronized (mPackages) { 5661 p = mPackages.get(packageName); 5662 if (p == null) { 5663 return false; 5664 } 5665 if (updateUsage) { 5666 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5667 } 5668 mPackageUsage.write(false); 5669 if (!dexopt) { 5670 // We aren't going to dexopt, so bail early. 5671 return false; 5672 } 5673 5674 targetInstructionSet = instructionSet != null ? instructionSet : 5675 getPrimaryInstructionSet(p.applicationInfo); 5676 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5677 return false; 5678 } 5679 } 5680 5681 synchronized (mInstallLock) { 5682 final String[] instructionSets = new String[] { targetInstructionSet }; 5683 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5684 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5685 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5686 } 5687 } 5688 5689 public ArraySet<String> getPackagesThatNeedDexOpt() { 5690 ArraySet<String> pkgs = null; 5691 synchronized (mPackages) { 5692 for (PackageParser.Package p : mPackages.values()) { 5693 if (DEBUG_DEXOPT) { 5694 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5695 } 5696 if (!p.mDexOptPerformed.isEmpty()) { 5697 continue; 5698 } 5699 if (pkgs == null) { 5700 pkgs = new ArraySet<String>(); 5701 } 5702 pkgs.add(p.packageName); 5703 } 5704 } 5705 return pkgs; 5706 } 5707 5708 public void shutdown() { 5709 mPackageUsage.write(true); 5710 } 5711 5712 @Override 5713 public void forceDexOpt(String packageName) { 5714 enforceSystemOrRoot("forceDexOpt"); 5715 5716 PackageParser.Package pkg; 5717 synchronized (mPackages) { 5718 pkg = mPackages.get(packageName); 5719 if (pkg == null) { 5720 throw new IllegalArgumentException("Missing package: " + packageName); 5721 } 5722 } 5723 5724 synchronized (mInstallLock) { 5725 final String[] instructionSets = new String[] { 5726 getPrimaryInstructionSet(pkg.applicationInfo) }; 5727 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5728 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5729 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5730 throw new IllegalStateException("Failed to dexopt: " + res); 5731 } 5732 } 5733 } 5734 5735 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5736 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5737 Slog.w(TAG, "Unable to update from " + oldPkg.name 5738 + " to " + newPkg.packageName 5739 + ": old package not in system partition"); 5740 return false; 5741 } else if (mPackages.get(oldPkg.name) != null) { 5742 Slog.w(TAG, "Unable to update from " + oldPkg.name 5743 + " to " + newPkg.packageName 5744 + ": old package still exists"); 5745 return false; 5746 } 5747 return true; 5748 } 5749 5750 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5751 int[] users = sUserManager.getUserIds(); 5752 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5753 if (res < 0) { 5754 return res; 5755 } 5756 for (int user : users) { 5757 if (user != 0) { 5758 res = mInstaller.createUserData(volumeUuid, packageName, 5759 UserHandle.getUid(user, uid), user, seinfo); 5760 if (res < 0) { 5761 return res; 5762 } 5763 } 5764 } 5765 return res; 5766 } 5767 5768 private int removeDataDirsLI(String volumeUuid, String packageName) { 5769 int[] users = sUserManager.getUserIds(); 5770 int res = 0; 5771 for (int user : users) { 5772 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5773 if (resInner < 0) { 5774 res = resInner; 5775 } 5776 } 5777 5778 return res; 5779 } 5780 5781 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5782 int[] users = sUserManager.getUserIds(); 5783 int res = 0; 5784 for (int user : users) { 5785 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5786 if (resInner < 0) { 5787 res = resInner; 5788 } 5789 } 5790 return res; 5791 } 5792 5793 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5794 PackageParser.Package changingLib) { 5795 if (file.path != null) { 5796 usesLibraryFiles.add(file.path); 5797 return; 5798 } 5799 PackageParser.Package p = mPackages.get(file.apk); 5800 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5801 // If we are doing this while in the middle of updating a library apk, 5802 // then we need to make sure to use that new apk for determining the 5803 // dependencies here. (We haven't yet finished committing the new apk 5804 // to the package manager state.) 5805 if (p == null || p.packageName.equals(changingLib.packageName)) { 5806 p = changingLib; 5807 } 5808 } 5809 if (p != null) { 5810 usesLibraryFiles.addAll(p.getAllCodePaths()); 5811 } 5812 } 5813 5814 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5815 PackageParser.Package changingLib) throws PackageManagerException { 5816 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5817 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5818 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5819 for (int i=0; i<N; i++) { 5820 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5821 if (file == null) { 5822 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5823 "Package " + pkg.packageName + " requires unavailable shared library " 5824 + pkg.usesLibraries.get(i) + "; failing!"); 5825 } 5826 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5827 } 5828 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5829 for (int i=0; i<N; i++) { 5830 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5831 if (file == null) { 5832 Slog.w(TAG, "Package " + pkg.packageName 5833 + " desires unavailable shared library " 5834 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5835 } else { 5836 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5837 } 5838 } 5839 N = usesLibraryFiles.size(); 5840 if (N > 0) { 5841 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5842 } else { 5843 pkg.usesLibraryFiles = null; 5844 } 5845 } 5846 } 5847 5848 private static boolean hasString(List<String> list, List<String> which) { 5849 if (list == null) { 5850 return false; 5851 } 5852 for (int i=list.size()-1; i>=0; i--) { 5853 for (int j=which.size()-1; j>=0; j--) { 5854 if (which.get(j).equals(list.get(i))) { 5855 return true; 5856 } 5857 } 5858 } 5859 return false; 5860 } 5861 5862 private void updateAllSharedLibrariesLPw() { 5863 for (PackageParser.Package pkg : mPackages.values()) { 5864 try { 5865 updateSharedLibrariesLPw(pkg, null); 5866 } catch (PackageManagerException e) { 5867 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5868 } 5869 } 5870 } 5871 5872 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5873 PackageParser.Package changingPkg) { 5874 ArrayList<PackageParser.Package> res = null; 5875 for (PackageParser.Package pkg : mPackages.values()) { 5876 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5877 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5878 if (res == null) { 5879 res = new ArrayList<PackageParser.Package>(); 5880 } 5881 res.add(pkg); 5882 try { 5883 updateSharedLibrariesLPw(pkg, changingPkg); 5884 } catch (PackageManagerException e) { 5885 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5886 } 5887 } 5888 } 5889 return res; 5890 } 5891 5892 /** 5893 * Derive the value of the {@code cpuAbiOverride} based on the provided 5894 * value and an optional stored value from the package settings. 5895 */ 5896 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5897 String cpuAbiOverride = null; 5898 5899 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5900 cpuAbiOverride = null; 5901 } else if (abiOverride != null) { 5902 cpuAbiOverride = abiOverride; 5903 } else if (settings != null) { 5904 cpuAbiOverride = settings.cpuAbiOverrideString; 5905 } 5906 5907 return cpuAbiOverride; 5908 } 5909 5910 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5911 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5912 boolean success = false; 5913 try { 5914 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5915 currentTime, user); 5916 success = true; 5917 return res; 5918 } finally { 5919 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5920 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5921 } 5922 } 5923 } 5924 5925 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5926 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5927 final File scanFile = new File(pkg.codePath); 5928 if (pkg.applicationInfo.getCodePath() == null || 5929 pkg.applicationInfo.getResourcePath() == null) { 5930 // Bail out. The resource and code paths haven't been set. 5931 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5932 "Code and resource paths haven't been set correctly"); 5933 } 5934 5935 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5936 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5937 } else { 5938 // Only allow system apps to be flagged as core apps. 5939 pkg.coreApp = false; 5940 } 5941 5942 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5943 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5944 } 5945 5946 if (mCustomResolverComponentName != null && 5947 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5948 setUpCustomResolverActivity(pkg); 5949 } 5950 5951 if (pkg.packageName.equals("android")) { 5952 synchronized (mPackages) { 5953 if (mAndroidApplication != null) { 5954 Slog.w(TAG, "*************************************************"); 5955 Slog.w(TAG, "Core android package being redefined. Skipping."); 5956 Slog.w(TAG, " file=" + scanFile); 5957 Slog.w(TAG, "*************************************************"); 5958 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5959 "Core android package being redefined. Skipping."); 5960 } 5961 5962 // Set up information for our fall-back user intent resolution activity. 5963 mPlatformPackage = pkg; 5964 pkg.mVersionCode = mSdkVersion; 5965 mAndroidApplication = pkg.applicationInfo; 5966 5967 if (!mResolverReplaced) { 5968 mResolveActivity.applicationInfo = mAndroidApplication; 5969 mResolveActivity.name = ResolverActivity.class.getName(); 5970 mResolveActivity.packageName = mAndroidApplication.packageName; 5971 mResolveActivity.processName = "system:ui"; 5972 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5973 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5974 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5975 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5976 mResolveActivity.exported = true; 5977 mResolveActivity.enabled = true; 5978 mResolveInfo.activityInfo = mResolveActivity; 5979 mResolveInfo.priority = 0; 5980 mResolveInfo.preferredOrder = 0; 5981 mResolveInfo.match = 0; 5982 mResolveComponentName = new ComponentName( 5983 mAndroidApplication.packageName, mResolveActivity.name); 5984 } 5985 } 5986 } 5987 5988 if (DEBUG_PACKAGE_SCANNING) { 5989 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5990 Log.d(TAG, "Scanning package " + pkg.packageName); 5991 } 5992 5993 if (mPackages.containsKey(pkg.packageName) 5994 || mSharedLibraries.containsKey(pkg.packageName)) { 5995 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5996 "Application package " + pkg.packageName 5997 + " already installed. Skipping duplicate."); 5998 } 5999 6000 // If we're only installing presumed-existing packages, require that the 6001 // scanned APK is both already known and at the path previously established 6002 // for it. Previously unknown packages we pick up normally, but if we have an 6003 // a priori expectation about this package's install presence, enforce it. 6004 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6005 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6006 if (known != null) { 6007 if (DEBUG_PACKAGE_SCANNING) { 6008 Log.d(TAG, "Examining " + pkg.codePath 6009 + " and requiring known paths " + known.codePathString 6010 + " & " + known.resourcePathString); 6011 } 6012 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6013 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6014 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6015 "Application package " + pkg.packageName 6016 + " found at " + pkg.applicationInfo.getCodePath() 6017 + " but expected at " + known.codePathString + "; ignoring."); 6018 } 6019 } 6020 } 6021 6022 // Initialize package source and resource directories 6023 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6024 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6025 6026 SharedUserSetting suid = null; 6027 PackageSetting pkgSetting = null; 6028 6029 if (!isSystemApp(pkg)) { 6030 // Only system apps can use these features. 6031 pkg.mOriginalPackages = null; 6032 pkg.mRealPackage = null; 6033 pkg.mAdoptPermissions = null; 6034 } 6035 6036 // writer 6037 synchronized (mPackages) { 6038 if (pkg.mSharedUserId != null) { 6039 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6040 if (suid == null) { 6041 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6042 "Creating application package " + pkg.packageName 6043 + " for shared user failed"); 6044 } 6045 if (DEBUG_PACKAGE_SCANNING) { 6046 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6047 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6048 + "): packages=" + suid.packages); 6049 } 6050 } 6051 6052 // Check if we are renaming from an original package name. 6053 PackageSetting origPackage = null; 6054 String realName = null; 6055 if (pkg.mOriginalPackages != null) { 6056 // This package may need to be renamed to a previously 6057 // installed name. Let's check on that... 6058 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6059 if (pkg.mOriginalPackages.contains(renamed)) { 6060 // This package had originally been installed as the 6061 // original name, and we have already taken care of 6062 // transitioning to the new one. Just update the new 6063 // one to continue using the old name. 6064 realName = pkg.mRealPackage; 6065 if (!pkg.packageName.equals(renamed)) { 6066 // Callers into this function may have already taken 6067 // care of renaming the package; only do it here if 6068 // it is not already done. 6069 pkg.setPackageName(renamed); 6070 } 6071 6072 } else { 6073 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6074 if ((origPackage = mSettings.peekPackageLPr( 6075 pkg.mOriginalPackages.get(i))) != null) { 6076 // We do have the package already installed under its 6077 // original name... should we use it? 6078 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6079 // New package is not compatible with original. 6080 origPackage = null; 6081 continue; 6082 } else if (origPackage.sharedUser != null) { 6083 // Make sure uid is compatible between packages. 6084 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6085 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6086 + " to " + pkg.packageName + ": old uid " 6087 + origPackage.sharedUser.name 6088 + " differs from " + pkg.mSharedUserId); 6089 origPackage = null; 6090 continue; 6091 } 6092 } else { 6093 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6094 + pkg.packageName + " to old name " + origPackage.name); 6095 } 6096 break; 6097 } 6098 } 6099 } 6100 } 6101 6102 if (mTransferedPackages.contains(pkg.packageName)) { 6103 Slog.w(TAG, "Package " + pkg.packageName 6104 + " was transferred to another, but its .apk remains"); 6105 } 6106 6107 // Just create the setting, don't add it yet. For already existing packages 6108 // the PkgSetting exists already and doesn't have to be created. 6109 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6110 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6111 pkg.applicationInfo.primaryCpuAbi, 6112 pkg.applicationInfo.secondaryCpuAbi, 6113 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6114 user, false); 6115 if (pkgSetting == null) { 6116 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6117 "Creating application package " + pkg.packageName + " failed"); 6118 } 6119 6120 if (pkgSetting.origPackage != null) { 6121 // If we are first transitioning from an original package, 6122 // fix up the new package's name now. We need to do this after 6123 // looking up the package under its new name, so getPackageLP 6124 // can take care of fiddling things correctly. 6125 pkg.setPackageName(origPackage.name); 6126 6127 // File a report about this. 6128 String msg = "New package " + pkgSetting.realName 6129 + " renamed to replace old package " + pkgSetting.name; 6130 reportSettingsProblem(Log.WARN, msg); 6131 6132 // Make a note of it. 6133 mTransferedPackages.add(origPackage.name); 6134 6135 // No longer need to retain this. 6136 pkgSetting.origPackage = null; 6137 } 6138 6139 if (realName != null) { 6140 // Make a note of it. 6141 mTransferedPackages.add(pkg.packageName); 6142 } 6143 6144 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6145 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6146 } 6147 6148 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6149 // Check all shared libraries and map to their actual file path. 6150 // We only do this here for apps not on a system dir, because those 6151 // are the only ones that can fail an install due to this. We 6152 // will take care of the system apps by updating all of their 6153 // library paths after the scan is done. 6154 updateSharedLibrariesLPw(pkg, null); 6155 } 6156 6157 if (mFoundPolicyFile) { 6158 SELinuxMMAC.assignSeinfoValue(pkg); 6159 } 6160 6161 pkg.applicationInfo.uid = pkgSetting.appId; 6162 pkg.mExtras = pkgSetting; 6163 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6164 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6165 // We just determined the app is signed correctly, so bring 6166 // over the latest parsed certs. 6167 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6168 } else { 6169 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6170 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6171 "Package " + pkg.packageName + " upgrade keys do not match the " 6172 + "previously installed version"); 6173 } else { 6174 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6175 String msg = "System package " + pkg.packageName 6176 + " signature changed; retaining data."; 6177 reportSettingsProblem(Log.WARN, msg); 6178 } 6179 } 6180 } else { 6181 try { 6182 verifySignaturesLP(pkgSetting, pkg); 6183 // We just determined the app is signed correctly, so bring 6184 // over the latest parsed certs. 6185 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6186 } catch (PackageManagerException e) { 6187 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6188 throw e; 6189 } 6190 // The signature has changed, but this package is in the system 6191 // image... let's recover! 6192 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6193 // However... if this package is part of a shared user, but it 6194 // doesn't match the signature of the shared user, let's fail. 6195 // What this means is that you can't change the signatures 6196 // associated with an overall shared user, which doesn't seem all 6197 // that unreasonable. 6198 if (pkgSetting.sharedUser != null) { 6199 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6200 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6201 throw new PackageManagerException( 6202 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6203 "Signature mismatch for shared user : " 6204 + pkgSetting.sharedUser); 6205 } 6206 } 6207 // File a report about this. 6208 String msg = "System package " + pkg.packageName 6209 + " signature changed; retaining data."; 6210 reportSettingsProblem(Log.WARN, msg); 6211 } 6212 } 6213 // Verify that this new package doesn't have any content providers 6214 // that conflict with existing packages. Only do this if the 6215 // package isn't already installed, since we don't want to break 6216 // things that are installed. 6217 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6218 final int N = pkg.providers.size(); 6219 int i; 6220 for (i=0; i<N; i++) { 6221 PackageParser.Provider p = pkg.providers.get(i); 6222 if (p.info.authority != null) { 6223 String names[] = p.info.authority.split(";"); 6224 for (int j = 0; j < names.length; j++) { 6225 if (mProvidersByAuthority.containsKey(names[j])) { 6226 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6227 final String otherPackageName = 6228 ((other != null && other.getComponentName() != null) ? 6229 other.getComponentName().getPackageName() : "?"); 6230 throw new PackageManagerException( 6231 INSTALL_FAILED_CONFLICTING_PROVIDER, 6232 "Can't install because provider name " + names[j] 6233 + " (in package " + pkg.applicationInfo.packageName 6234 + ") is already used by " + otherPackageName); 6235 } 6236 } 6237 } 6238 } 6239 } 6240 6241 if (pkg.mAdoptPermissions != null) { 6242 // This package wants to adopt ownership of permissions from 6243 // another package. 6244 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6245 final String origName = pkg.mAdoptPermissions.get(i); 6246 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6247 if (orig != null) { 6248 if (verifyPackageUpdateLPr(orig, pkg)) { 6249 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6250 + pkg.packageName); 6251 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6252 } 6253 } 6254 } 6255 } 6256 } 6257 6258 final String pkgName = pkg.packageName; 6259 6260 final long scanFileTime = scanFile.lastModified(); 6261 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6262 pkg.applicationInfo.processName = fixProcessName( 6263 pkg.applicationInfo.packageName, 6264 pkg.applicationInfo.processName, 6265 pkg.applicationInfo.uid); 6266 6267 File dataPath; 6268 if (mPlatformPackage == pkg) { 6269 // The system package is special. 6270 dataPath = new File(Environment.getDataDirectory(), "system"); 6271 6272 pkg.applicationInfo.dataDir = dataPath.getPath(); 6273 6274 } else { 6275 // This is a normal package, need to make its data directory. 6276 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6277 UserHandle.USER_OWNER); 6278 6279 boolean uidError = false; 6280 if (dataPath.exists()) { 6281 int currentUid = 0; 6282 try { 6283 StructStat stat = Os.stat(dataPath.getPath()); 6284 currentUid = stat.st_uid; 6285 } catch (ErrnoException e) { 6286 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6287 } 6288 6289 // If we have mismatched owners for the data path, we have a problem. 6290 if (currentUid != pkg.applicationInfo.uid) { 6291 boolean recovered = false; 6292 if (currentUid == 0) { 6293 // The directory somehow became owned by root. Wow. 6294 // This is probably because the system was stopped while 6295 // installd was in the middle of messing with its libs 6296 // directory. Ask installd to fix that. 6297 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6298 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6299 if (ret >= 0) { 6300 recovered = true; 6301 String msg = "Package " + pkg.packageName 6302 + " unexpectedly changed to uid 0; recovered to " + 6303 + pkg.applicationInfo.uid; 6304 reportSettingsProblem(Log.WARN, msg); 6305 } 6306 } 6307 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6308 || (scanFlags&SCAN_BOOTING) != 0)) { 6309 // If this is a system app, we can at least delete its 6310 // current data so the application will still work. 6311 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6312 if (ret >= 0) { 6313 // TODO: Kill the processes first 6314 // Old data gone! 6315 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6316 ? "System package " : "Third party package "; 6317 String msg = prefix + pkg.packageName 6318 + " has changed from uid: " 6319 + currentUid + " to " 6320 + pkg.applicationInfo.uid + "; old data erased"; 6321 reportSettingsProblem(Log.WARN, msg); 6322 recovered = true; 6323 6324 // And now re-install the app. 6325 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6326 pkg.applicationInfo.seinfo); 6327 if (ret == -1) { 6328 // Ack should not happen! 6329 msg = prefix + pkg.packageName 6330 + " could not have data directory re-created after delete."; 6331 reportSettingsProblem(Log.WARN, msg); 6332 throw new PackageManagerException( 6333 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6334 } 6335 } 6336 if (!recovered) { 6337 mHasSystemUidErrors = true; 6338 } 6339 } else if (!recovered) { 6340 // If we allow this install to proceed, we will be broken. 6341 // Abort, abort! 6342 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6343 "scanPackageLI"); 6344 } 6345 if (!recovered) { 6346 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6347 + pkg.applicationInfo.uid + "/fs_" 6348 + currentUid; 6349 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6350 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6351 String msg = "Package " + pkg.packageName 6352 + " has mismatched uid: " 6353 + currentUid + " on disk, " 6354 + pkg.applicationInfo.uid + " in settings"; 6355 // writer 6356 synchronized (mPackages) { 6357 mSettings.mReadMessages.append(msg); 6358 mSettings.mReadMessages.append('\n'); 6359 uidError = true; 6360 if (!pkgSetting.uidError) { 6361 reportSettingsProblem(Log.ERROR, msg); 6362 } 6363 } 6364 } 6365 } 6366 pkg.applicationInfo.dataDir = dataPath.getPath(); 6367 if (mShouldRestoreconData) { 6368 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6369 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6370 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6371 } 6372 } else { 6373 if (DEBUG_PACKAGE_SCANNING) { 6374 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6375 Log.v(TAG, "Want this data dir: " + dataPath); 6376 } 6377 //invoke installer to do the actual installation 6378 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6379 pkg.applicationInfo.seinfo); 6380 if (ret < 0) { 6381 // Error from installer 6382 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6383 "Unable to create data dirs [errorCode=" + ret + "]"); 6384 } 6385 6386 if (dataPath.exists()) { 6387 pkg.applicationInfo.dataDir = dataPath.getPath(); 6388 } else { 6389 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6390 pkg.applicationInfo.dataDir = null; 6391 } 6392 } 6393 6394 pkgSetting.uidError = uidError; 6395 } 6396 6397 final String path = scanFile.getPath(); 6398 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6399 6400 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6401 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6402 6403 // Some system apps still use directory structure for native libraries 6404 // in which case we might end up not detecting abi solely based on apk 6405 // structure. Try to detect abi based on directory structure. 6406 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6407 pkg.applicationInfo.primaryCpuAbi == null) { 6408 setBundledAppAbisAndRoots(pkg, pkgSetting); 6409 setNativeLibraryPaths(pkg); 6410 } 6411 6412 } else { 6413 if ((scanFlags & SCAN_MOVE) != 0) { 6414 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6415 // but we already have this packages package info in the PackageSetting. We just 6416 // use that and derive the native library path based on the new codepath. 6417 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6418 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6419 } 6420 6421 // Set native library paths again. For moves, the path will be updated based on the 6422 // ABIs we've determined above. For non-moves, the path will be updated based on the 6423 // ABIs we determined during compilation, but the path will depend on the final 6424 // package path (after the rename away from the stage path). 6425 setNativeLibraryPaths(pkg); 6426 } 6427 6428 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6429 final int[] userIds = sUserManager.getUserIds(); 6430 synchronized (mInstallLock) { 6431 // Create a native library symlink only if we have native libraries 6432 // and if the native libraries are 32 bit libraries. We do not provide 6433 // this symlink for 64 bit libraries. 6434 if (pkg.applicationInfo.primaryCpuAbi != null && 6435 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6436 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6437 for (int userId : userIds) { 6438 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6439 nativeLibPath, userId) < 0) { 6440 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6441 "Failed linking native library dir (user=" + userId + ")"); 6442 } 6443 } 6444 } 6445 } 6446 6447 // This is a special case for the "system" package, where the ABI is 6448 // dictated by the zygote configuration (and init.rc). We should keep track 6449 // of this ABI so that we can deal with "normal" applications that run under 6450 // the same UID correctly. 6451 if (mPlatformPackage == pkg) { 6452 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6453 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6454 } 6455 6456 // If there's a mismatch between the abi-override in the package setting 6457 // and the abiOverride specified for the install. Warn about this because we 6458 // would've already compiled the app without taking the package setting into 6459 // account. 6460 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6461 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6462 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6463 " for package: " + pkg.packageName); 6464 } 6465 } 6466 6467 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6468 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6469 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6470 6471 // Copy the derived override back to the parsed package, so that we can 6472 // update the package settings accordingly. 6473 pkg.cpuAbiOverride = cpuAbiOverride; 6474 6475 if (DEBUG_ABI_SELECTION) { 6476 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6477 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6478 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6479 } 6480 6481 // Push the derived path down into PackageSettings so we know what to 6482 // clean up at uninstall time. 6483 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6484 6485 if (DEBUG_ABI_SELECTION) { 6486 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6487 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6488 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6489 } 6490 6491 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6492 // We don't do this here during boot because we can do it all 6493 // at once after scanning all existing packages. 6494 // 6495 // We also do this *before* we perform dexopt on this package, so that 6496 // we can avoid redundant dexopts, and also to make sure we've got the 6497 // code and package path correct. 6498 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6499 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6500 } 6501 6502 if ((scanFlags & SCAN_NO_DEX) == 0) { 6503 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6504 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6505 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6506 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6507 } 6508 } 6509 if (mFactoryTest && pkg.requestedPermissions.contains( 6510 android.Manifest.permission.FACTORY_TEST)) { 6511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6512 } 6513 6514 ArrayList<PackageParser.Package> clientLibPkgs = null; 6515 6516 // writer 6517 synchronized (mPackages) { 6518 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6519 // Only system apps can add new shared libraries. 6520 if (pkg.libraryNames != null) { 6521 for (int i=0; i<pkg.libraryNames.size(); i++) { 6522 String name = pkg.libraryNames.get(i); 6523 boolean allowed = false; 6524 if (pkg.isUpdatedSystemApp()) { 6525 // New library entries can only be added through the 6526 // system image. This is important to get rid of a lot 6527 // of nasty edge cases: for example if we allowed a non- 6528 // system update of the app to add a library, then uninstalling 6529 // the update would make the library go away, and assumptions 6530 // we made such as through app install filtering would now 6531 // have allowed apps on the device which aren't compatible 6532 // with it. Better to just have the restriction here, be 6533 // conservative, and create many fewer cases that can negatively 6534 // impact the user experience. 6535 final PackageSetting sysPs = mSettings 6536 .getDisabledSystemPkgLPr(pkg.packageName); 6537 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6538 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6539 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6540 allowed = true; 6541 allowed = true; 6542 break; 6543 } 6544 } 6545 } 6546 } else { 6547 allowed = true; 6548 } 6549 if (allowed) { 6550 if (!mSharedLibraries.containsKey(name)) { 6551 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6552 } else if (!name.equals(pkg.packageName)) { 6553 Slog.w(TAG, "Package " + pkg.packageName + " library " 6554 + name + " already exists; skipping"); 6555 } 6556 } else { 6557 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6558 + name + " that is not declared on system image; skipping"); 6559 } 6560 } 6561 if ((scanFlags&SCAN_BOOTING) == 0) { 6562 // If we are not booting, we need to update any applications 6563 // that are clients of our shared library. If we are booting, 6564 // this will all be done once the scan is complete. 6565 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6566 } 6567 } 6568 } 6569 } 6570 6571 // We also need to dexopt any apps that are dependent on this library. Note that 6572 // if these fail, we should abort the install since installing the library will 6573 // result in some apps being broken. 6574 if (clientLibPkgs != null) { 6575 if ((scanFlags & SCAN_NO_DEX) == 0) { 6576 for (int i = 0; i < clientLibPkgs.size(); i++) { 6577 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6578 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6579 null /* instruction sets */, forceDex, 6580 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6581 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6582 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6583 "scanPackageLI failed to dexopt clientLibPkgs"); 6584 } 6585 } 6586 } 6587 } 6588 6589 // Also need to kill any apps that are dependent on the library. 6590 if (clientLibPkgs != null) { 6591 for (int i=0; i<clientLibPkgs.size(); i++) { 6592 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6593 killApplication(clientPkg.applicationInfo.packageName, 6594 clientPkg.applicationInfo.uid, "update lib"); 6595 } 6596 } 6597 6598 // Make sure we're not adding any bogus keyset info 6599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6600 ksms.assertScannedPackageValid(pkg); 6601 6602 // writer 6603 synchronized (mPackages) { 6604 // We don't expect installation to fail beyond this point 6605 6606 // Add the new setting to mSettings 6607 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6608 // Add the new setting to mPackages 6609 mPackages.put(pkg.applicationInfo.packageName, pkg); 6610 // Make sure we don't accidentally delete its data. 6611 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6612 while (iter.hasNext()) { 6613 PackageCleanItem item = iter.next(); 6614 if (pkgName.equals(item.packageName)) { 6615 iter.remove(); 6616 } 6617 } 6618 6619 // Take care of first install / last update times. 6620 if (currentTime != 0) { 6621 if (pkgSetting.firstInstallTime == 0) { 6622 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6623 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6624 pkgSetting.lastUpdateTime = currentTime; 6625 } 6626 } else if (pkgSetting.firstInstallTime == 0) { 6627 // We need *something*. Take time time stamp of the file. 6628 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6629 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6630 if (scanFileTime != pkgSetting.timeStamp) { 6631 // A package on the system image has changed; consider this 6632 // to be an update. 6633 pkgSetting.lastUpdateTime = scanFileTime; 6634 } 6635 } 6636 6637 // Add the package's KeySets to the global KeySetManagerService 6638 ksms.addScannedPackageLPw(pkg); 6639 6640 int N = pkg.providers.size(); 6641 StringBuilder r = null; 6642 int i; 6643 for (i=0; i<N; i++) { 6644 PackageParser.Provider p = pkg.providers.get(i); 6645 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6646 p.info.processName, pkg.applicationInfo.uid); 6647 mProviders.addProvider(p); 6648 p.syncable = p.info.isSyncable; 6649 if (p.info.authority != null) { 6650 String names[] = p.info.authority.split(";"); 6651 p.info.authority = null; 6652 for (int j = 0; j < names.length; j++) { 6653 if (j == 1 && p.syncable) { 6654 // We only want the first authority for a provider to possibly be 6655 // syncable, so if we already added this provider using a different 6656 // authority clear the syncable flag. We copy the provider before 6657 // changing it because the mProviders object contains a reference 6658 // to a provider that we don't want to change. 6659 // Only do this for the second authority since the resulting provider 6660 // object can be the same for all future authorities for this provider. 6661 p = new PackageParser.Provider(p); 6662 p.syncable = false; 6663 } 6664 if (!mProvidersByAuthority.containsKey(names[j])) { 6665 mProvidersByAuthority.put(names[j], p); 6666 if (p.info.authority == null) { 6667 p.info.authority = names[j]; 6668 } else { 6669 p.info.authority = p.info.authority + ";" + names[j]; 6670 } 6671 if (DEBUG_PACKAGE_SCANNING) { 6672 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6673 Log.d(TAG, "Registered content provider: " + names[j] 6674 + ", className = " + p.info.name + ", isSyncable = " 6675 + p.info.isSyncable); 6676 } 6677 } else { 6678 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6679 Slog.w(TAG, "Skipping provider name " + names[j] + 6680 " (in package " + pkg.applicationInfo.packageName + 6681 "): name already used by " 6682 + ((other != null && other.getComponentName() != null) 6683 ? other.getComponentName().getPackageName() : "?")); 6684 } 6685 } 6686 } 6687 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(p.info.name); 6694 } 6695 } 6696 if (r != null) { 6697 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6698 } 6699 6700 N = pkg.services.size(); 6701 r = null; 6702 for (i=0; i<N; i++) { 6703 PackageParser.Service s = pkg.services.get(i); 6704 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6705 s.info.processName, pkg.applicationInfo.uid); 6706 mServices.addService(s); 6707 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6708 if (r == null) { 6709 r = new StringBuilder(256); 6710 } else { 6711 r.append(' '); 6712 } 6713 r.append(s.info.name); 6714 } 6715 } 6716 if (r != null) { 6717 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6718 } 6719 6720 N = pkg.receivers.size(); 6721 r = null; 6722 for (i=0; i<N; i++) { 6723 PackageParser.Activity a = pkg.receivers.get(i); 6724 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6725 a.info.processName, pkg.applicationInfo.uid); 6726 mReceivers.addActivity(a, "receiver"); 6727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append(a.info.name); 6734 } 6735 } 6736 if (r != null) { 6737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6738 } 6739 6740 N = pkg.activities.size(); 6741 r = null; 6742 for (i=0; i<N; i++) { 6743 PackageParser.Activity a = pkg.activities.get(i); 6744 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6745 a.info.processName, pkg.applicationInfo.uid); 6746 mActivities.addActivity(a, "activity"); 6747 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6748 if (r == null) { 6749 r = new StringBuilder(256); 6750 } else { 6751 r.append(' '); 6752 } 6753 r.append(a.info.name); 6754 } 6755 } 6756 if (r != null) { 6757 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6758 } 6759 6760 N = pkg.permissionGroups.size(); 6761 r = null; 6762 for (i=0; i<N; i++) { 6763 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6764 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6765 if (cur == null) { 6766 mPermissionGroups.put(pg.info.name, pg); 6767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6768 if (r == null) { 6769 r = new StringBuilder(256); 6770 } else { 6771 r.append(' '); 6772 } 6773 r.append(pg.info.name); 6774 } 6775 } else { 6776 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6777 + pg.info.packageName + " ignored: original from " 6778 + cur.info.packageName); 6779 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6780 if (r == null) { 6781 r = new StringBuilder(256); 6782 } else { 6783 r.append(' '); 6784 } 6785 r.append("DUP:"); 6786 r.append(pg.info.name); 6787 } 6788 } 6789 } 6790 if (r != null) { 6791 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6792 } 6793 6794 N = pkg.permissions.size(); 6795 r = null; 6796 for (i=0; i<N; i++) { 6797 PackageParser.Permission p = pkg.permissions.get(i); 6798 6799 // Now that permission groups have a special meaning, we ignore permission 6800 // groups for legacy apps to prevent unexpected behavior. In particular, 6801 // permissions for one app being granted to someone just becuase they happen 6802 // to be in a group defined by another app (before this had no implications). 6803 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6804 p.group = mPermissionGroups.get(p.info.group); 6805 // Warn for a permission in an unknown group. 6806 if (p.info.group != null && p.group == null) { 6807 Slog.w(TAG, "Permission " + p.info.name + " from package " 6808 + p.info.packageName + " in an unknown group " + p.info.group); 6809 } 6810 } 6811 6812 ArrayMap<String, BasePermission> permissionMap = 6813 p.tree ? mSettings.mPermissionTrees 6814 : mSettings.mPermissions; 6815 BasePermission bp = permissionMap.get(p.info.name); 6816 6817 // Allow system apps to redefine non-system permissions 6818 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6819 final boolean currentOwnerIsSystem = (bp.perm != null 6820 && isSystemApp(bp.perm.owner)); 6821 if (isSystemApp(p.owner)) { 6822 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6823 // It's a built-in permission and no owner, take ownership now 6824 bp.packageSetting = pkgSetting; 6825 bp.perm = p; 6826 bp.uid = pkg.applicationInfo.uid; 6827 bp.sourcePackage = p.info.packageName; 6828 } else if (!currentOwnerIsSystem) { 6829 String msg = "New decl " + p.owner + " of permission " 6830 + p.info.name + " is system; overriding " + bp.sourcePackage; 6831 reportSettingsProblem(Log.WARN, msg); 6832 bp = null; 6833 } 6834 } 6835 } 6836 6837 if (bp == null) { 6838 bp = new BasePermission(p.info.name, p.info.packageName, 6839 BasePermission.TYPE_NORMAL); 6840 permissionMap.put(p.info.name, bp); 6841 } 6842 6843 if (bp.perm == null) { 6844 if (bp.sourcePackage == null 6845 || bp.sourcePackage.equals(p.info.packageName)) { 6846 BasePermission tree = findPermissionTreeLP(p.info.name); 6847 if (tree == null 6848 || tree.sourcePackage.equals(p.info.packageName)) { 6849 bp.packageSetting = pkgSetting; 6850 bp.perm = p; 6851 bp.uid = pkg.applicationInfo.uid; 6852 bp.sourcePackage = p.info.packageName; 6853 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6854 if (r == null) { 6855 r = new StringBuilder(256); 6856 } else { 6857 r.append(' '); 6858 } 6859 r.append(p.info.name); 6860 } 6861 } else { 6862 Slog.w(TAG, "Permission " + p.info.name + " from package " 6863 + p.info.packageName + " ignored: base tree " 6864 + tree.name + " is from package " 6865 + tree.sourcePackage); 6866 } 6867 } else { 6868 Slog.w(TAG, "Permission " + p.info.name + " from package " 6869 + p.info.packageName + " ignored: original from " 6870 + bp.sourcePackage); 6871 } 6872 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6873 if (r == null) { 6874 r = new StringBuilder(256); 6875 } else { 6876 r.append(' '); 6877 } 6878 r.append("DUP:"); 6879 r.append(p.info.name); 6880 } 6881 if (bp.perm == p) { 6882 bp.protectionLevel = p.info.protectionLevel; 6883 } 6884 } 6885 6886 if (r != null) { 6887 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6888 } 6889 6890 N = pkg.instrumentation.size(); 6891 r = null; 6892 for (i=0; i<N; i++) { 6893 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6894 a.info.packageName = pkg.applicationInfo.packageName; 6895 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6896 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6897 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6898 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6899 a.info.dataDir = pkg.applicationInfo.dataDir; 6900 6901 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6902 // need other information about the application, like the ABI and what not ? 6903 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6904 mInstrumentation.put(a.getComponentName(), a); 6905 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6906 if (r == null) { 6907 r = new StringBuilder(256); 6908 } else { 6909 r.append(' '); 6910 } 6911 r.append(a.info.name); 6912 } 6913 } 6914 if (r != null) { 6915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6916 } 6917 6918 if (pkg.protectedBroadcasts != null) { 6919 N = pkg.protectedBroadcasts.size(); 6920 for (i=0; i<N; i++) { 6921 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6922 } 6923 } 6924 6925 pkgSetting.setTimeStamp(scanFileTime); 6926 6927 // Create idmap files for pairs of (packages, overlay packages). 6928 // Note: "android", ie framework-res.apk, is handled by native layers. 6929 if (pkg.mOverlayTarget != null) { 6930 // This is an overlay package. 6931 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6932 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6933 mOverlays.put(pkg.mOverlayTarget, 6934 new ArrayMap<String, PackageParser.Package>()); 6935 } 6936 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6937 map.put(pkg.packageName, pkg); 6938 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6939 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6940 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6941 "scanPackageLI failed to createIdmap"); 6942 } 6943 } 6944 } else if (mOverlays.containsKey(pkg.packageName) && 6945 !pkg.packageName.equals("android")) { 6946 // This is a regular package, with one or more known overlay packages. 6947 createIdmapsForPackageLI(pkg); 6948 } 6949 } 6950 6951 return pkg; 6952 } 6953 6954 /** 6955 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6956 * is derived purely on the basis of the contents of {@code scanFile} and 6957 * {@code cpuAbiOverride}. 6958 * 6959 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6960 */ 6961 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6962 String cpuAbiOverride, boolean extractLibs) 6963 throws PackageManagerException { 6964 // TODO: We can probably be smarter about this stuff. For installed apps, 6965 // we can calculate this information at install time once and for all. For 6966 // system apps, we can probably assume that this information doesn't change 6967 // after the first boot scan. As things stand, we do lots of unnecessary work. 6968 6969 // Give ourselves some initial paths; we'll come back for another 6970 // pass once we've determined ABI below. 6971 setNativeLibraryPaths(pkg); 6972 6973 // We would never need to extract libs for forward-locked and external packages, 6974 // since the container service will do it for us. We shouldn't attempt to 6975 // extract libs from system app when it was not updated. 6976 if (pkg.isForwardLocked() || isExternal(pkg) || 6977 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6978 extractLibs = false; 6979 } 6980 6981 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6982 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6983 6984 NativeLibraryHelper.Handle handle = null; 6985 try { 6986 handle = NativeLibraryHelper.Handle.create(scanFile); 6987 // TODO(multiArch): This can be null for apps that didn't go through the 6988 // usual installation process. We can calculate it again, like we 6989 // do during install time. 6990 // 6991 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6992 // unnecessary. 6993 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6994 6995 // Null out the abis so that they can be recalculated. 6996 pkg.applicationInfo.primaryCpuAbi = null; 6997 pkg.applicationInfo.secondaryCpuAbi = null; 6998 if (isMultiArch(pkg.applicationInfo)) { 6999 // Warn if we've set an abiOverride for multi-lib packages.. 7000 // By definition, we need to copy both 32 and 64 bit libraries for 7001 // such packages. 7002 if (pkg.cpuAbiOverride != null 7003 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7004 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7005 } 7006 7007 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7008 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7009 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7010 if (extractLibs) { 7011 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7012 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7013 useIsaSpecificSubdirs); 7014 } else { 7015 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7016 } 7017 } 7018 7019 maybeThrowExceptionForMultiArchCopy( 7020 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7021 7022 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7023 if (extractLibs) { 7024 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7025 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7026 useIsaSpecificSubdirs); 7027 } else { 7028 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7029 } 7030 } 7031 7032 maybeThrowExceptionForMultiArchCopy( 7033 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7034 7035 if (abi64 >= 0) { 7036 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7037 } 7038 7039 if (abi32 >= 0) { 7040 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7041 if (abi64 >= 0) { 7042 pkg.applicationInfo.secondaryCpuAbi = abi; 7043 } else { 7044 pkg.applicationInfo.primaryCpuAbi = abi; 7045 } 7046 } 7047 } else { 7048 String[] abiList = (cpuAbiOverride != null) ? 7049 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7050 7051 // Enable gross and lame hacks for apps that are built with old 7052 // SDK tools. We must scan their APKs for renderscript bitcode and 7053 // not launch them if it's present. Don't bother checking on devices 7054 // that don't have 64 bit support. 7055 boolean needsRenderScriptOverride = false; 7056 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7057 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7058 abiList = Build.SUPPORTED_32_BIT_ABIS; 7059 needsRenderScriptOverride = true; 7060 } 7061 7062 final int copyRet; 7063 if (extractLibs) { 7064 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7065 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7066 } else { 7067 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7068 } 7069 7070 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7071 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7072 "Error unpackaging native libs for app, errorCode=" + copyRet); 7073 } 7074 7075 if (copyRet >= 0) { 7076 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7077 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7078 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7079 } else if (needsRenderScriptOverride) { 7080 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7081 } 7082 } 7083 } catch (IOException ioe) { 7084 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7085 } finally { 7086 IoUtils.closeQuietly(handle); 7087 } 7088 7089 // Now that we've calculated the ABIs and determined if it's an internal app, 7090 // we will go ahead and populate the nativeLibraryPath. 7091 setNativeLibraryPaths(pkg); 7092 } 7093 7094 /** 7095 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7096 * i.e, so that all packages can be run inside a single process if required. 7097 * 7098 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7099 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7100 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7101 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7102 * updating a package that belongs to a shared user. 7103 * 7104 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7105 * adds unnecessary complexity. 7106 */ 7107 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7108 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7109 String requiredInstructionSet = null; 7110 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7111 requiredInstructionSet = VMRuntime.getInstructionSet( 7112 scannedPackage.applicationInfo.primaryCpuAbi); 7113 } 7114 7115 PackageSetting requirer = null; 7116 for (PackageSetting ps : packagesForUser) { 7117 // If packagesForUser contains scannedPackage, we skip it. This will happen 7118 // when scannedPackage is an update of an existing package. Without this check, 7119 // we will never be able to change the ABI of any package belonging to a shared 7120 // user, even if it's compatible with other packages. 7121 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7122 if (ps.primaryCpuAbiString == null) { 7123 continue; 7124 } 7125 7126 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7127 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7128 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7129 // this but there's not much we can do. 7130 String errorMessage = "Instruction set mismatch, " 7131 + ((requirer == null) ? "[caller]" : requirer) 7132 + " requires " + requiredInstructionSet + " whereas " + ps 7133 + " requires " + instructionSet; 7134 Slog.w(TAG, errorMessage); 7135 } 7136 7137 if (requiredInstructionSet == null) { 7138 requiredInstructionSet = instructionSet; 7139 requirer = ps; 7140 } 7141 } 7142 } 7143 7144 if (requiredInstructionSet != null) { 7145 String adjustedAbi; 7146 if (requirer != null) { 7147 // requirer != null implies that either scannedPackage was null or that scannedPackage 7148 // did not require an ABI, in which case we have to adjust scannedPackage to match 7149 // the ABI of the set (which is the same as requirer's ABI) 7150 adjustedAbi = requirer.primaryCpuAbiString; 7151 if (scannedPackage != null) { 7152 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7153 } 7154 } else { 7155 // requirer == null implies that we're updating all ABIs in the set to 7156 // match scannedPackage. 7157 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7158 } 7159 7160 for (PackageSetting ps : packagesForUser) { 7161 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7162 if (ps.primaryCpuAbiString != null) { 7163 continue; 7164 } 7165 7166 ps.primaryCpuAbiString = adjustedAbi; 7167 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7168 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7169 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7170 7171 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7172 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7173 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7174 ps.primaryCpuAbiString = null; 7175 ps.pkg.applicationInfo.primaryCpuAbi = null; 7176 return; 7177 } else { 7178 mInstaller.rmdex(ps.codePathString, 7179 getDexCodeInstructionSet(getPreferredInstructionSet())); 7180 } 7181 } 7182 } 7183 } 7184 } 7185 } 7186 7187 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7188 synchronized (mPackages) { 7189 mResolverReplaced = true; 7190 // Set up information for custom user intent resolution activity. 7191 mResolveActivity.applicationInfo = pkg.applicationInfo; 7192 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7193 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7194 mResolveActivity.processName = pkg.applicationInfo.packageName; 7195 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7196 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7197 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7198 mResolveActivity.theme = 0; 7199 mResolveActivity.exported = true; 7200 mResolveActivity.enabled = true; 7201 mResolveInfo.activityInfo = mResolveActivity; 7202 mResolveInfo.priority = 0; 7203 mResolveInfo.preferredOrder = 0; 7204 mResolveInfo.match = 0; 7205 mResolveComponentName = mCustomResolverComponentName; 7206 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7207 mResolveComponentName); 7208 } 7209 } 7210 7211 private static String calculateBundledApkRoot(final String codePathString) { 7212 final File codePath = new File(codePathString); 7213 final File codeRoot; 7214 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7215 codeRoot = Environment.getRootDirectory(); 7216 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7217 codeRoot = Environment.getOemDirectory(); 7218 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7219 codeRoot = Environment.getVendorDirectory(); 7220 } else { 7221 // Unrecognized code path; take its top real segment as the apk root: 7222 // e.g. /something/app/blah.apk => /something 7223 try { 7224 File f = codePath.getCanonicalFile(); 7225 File parent = f.getParentFile(); // non-null because codePath is a file 7226 File tmp; 7227 while ((tmp = parent.getParentFile()) != null) { 7228 f = parent; 7229 parent = tmp; 7230 } 7231 codeRoot = f; 7232 Slog.w(TAG, "Unrecognized code path " 7233 + codePath + " - using " + codeRoot); 7234 } catch (IOException e) { 7235 // Can't canonicalize the code path -- shenanigans? 7236 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7237 return Environment.getRootDirectory().getPath(); 7238 } 7239 } 7240 return codeRoot.getPath(); 7241 } 7242 7243 /** 7244 * Derive and set the location of native libraries for the given package, 7245 * which varies depending on where and how the package was installed. 7246 */ 7247 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7248 final ApplicationInfo info = pkg.applicationInfo; 7249 final String codePath = pkg.codePath; 7250 final File codeFile = new File(codePath); 7251 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7252 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7253 7254 info.nativeLibraryRootDir = null; 7255 info.nativeLibraryRootRequiresIsa = false; 7256 info.nativeLibraryDir = null; 7257 info.secondaryNativeLibraryDir = null; 7258 7259 if (isApkFile(codeFile)) { 7260 // Monolithic install 7261 if (bundledApp) { 7262 // If "/system/lib64/apkname" exists, assume that is the per-package 7263 // native library directory to use; otherwise use "/system/lib/apkname". 7264 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7265 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7266 getPrimaryInstructionSet(info)); 7267 7268 // This is a bundled system app so choose the path based on the ABI. 7269 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7270 // is just the default path. 7271 final String apkName = deriveCodePathName(codePath); 7272 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7273 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7274 apkName).getAbsolutePath(); 7275 7276 if (info.secondaryCpuAbi != null) { 7277 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7278 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7279 secondaryLibDir, apkName).getAbsolutePath(); 7280 } 7281 } else if (asecApp) { 7282 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7283 .getAbsolutePath(); 7284 } else { 7285 final String apkName = deriveCodePathName(codePath); 7286 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7287 .getAbsolutePath(); 7288 } 7289 7290 info.nativeLibraryRootRequiresIsa = false; 7291 info.nativeLibraryDir = info.nativeLibraryRootDir; 7292 } else { 7293 // Cluster install 7294 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7295 info.nativeLibraryRootRequiresIsa = true; 7296 7297 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7298 getPrimaryInstructionSet(info)).getAbsolutePath(); 7299 7300 if (info.secondaryCpuAbi != null) { 7301 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7302 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7303 } 7304 } 7305 } 7306 7307 /** 7308 * Calculate the abis and roots for a bundled app. These can uniquely 7309 * be determined from the contents of the system partition, i.e whether 7310 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7311 * of this information, and instead assume that the system was built 7312 * sensibly. 7313 */ 7314 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7315 PackageSetting pkgSetting) { 7316 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7317 7318 // If "/system/lib64/apkname" exists, assume that is the per-package 7319 // native library directory to use; otherwise use "/system/lib/apkname". 7320 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7321 setBundledAppAbi(pkg, apkRoot, apkName); 7322 // pkgSetting might be null during rescan following uninstall of updates 7323 // to a bundled app, so accommodate that possibility. The settings in 7324 // that case will be established later from the parsed package. 7325 // 7326 // If the settings aren't null, sync them up with what we've just derived. 7327 // note that apkRoot isn't stored in the package settings. 7328 if (pkgSetting != null) { 7329 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7330 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7331 } 7332 } 7333 7334 /** 7335 * Deduces the ABI of a bundled app and sets the relevant fields on the 7336 * parsed pkg object. 7337 * 7338 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7339 * under which system libraries are installed. 7340 * @param apkName the name of the installed package. 7341 */ 7342 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7343 final File codeFile = new File(pkg.codePath); 7344 7345 final boolean has64BitLibs; 7346 final boolean has32BitLibs; 7347 if (isApkFile(codeFile)) { 7348 // Monolithic install 7349 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7350 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7351 } else { 7352 // Cluster install 7353 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7354 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7355 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7356 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7357 has64BitLibs = (new File(rootDir, isa)).exists(); 7358 } else { 7359 has64BitLibs = false; 7360 } 7361 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7362 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7363 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7364 has32BitLibs = (new File(rootDir, isa)).exists(); 7365 } else { 7366 has32BitLibs = false; 7367 } 7368 } 7369 7370 if (has64BitLibs && !has32BitLibs) { 7371 // The package has 64 bit libs, but not 32 bit libs. Its primary 7372 // ABI should be 64 bit. We can safely assume here that the bundled 7373 // native libraries correspond to the most preferred ABI in the list. 7374 7375 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7376 pkg.applicationInfo.secondaryCpuAbi = null; 7377 } else if (has32BitLibs && !has64BitLibs) { 7378 // The package has 32 bit libs but not 64 bit libs. Its primary 7379 // ABI should be 32 bit. 7380 7381 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7382 pkg.applicationInfo.secondaryCpuAbi = null; 7383 } else if (has32BitLibs && has64BitLibs) { 7384 // The application has both 64 and 32 bit bundled libraries. We check 7385 // here that the app declares multiArch support, and warn if it doesn't. 7386 // 7387 // We will be lenient here and record both ABIs. The primary will be the 7388 // ABI that's higher on the list, i.e, a device that's configured to prefer 7389 // 64 bit apps will see a 64 bit primary ABI, 7390 7391 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7392 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7393 } 7394 7395 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7396 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7397 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7398 } else { 7399 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7400 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7401 } 7402 } else { 7403 pkg.applicationInfo.primaryCpuAbi = null; 7404 pkg.applicationInfo.secondaryCpuAbi = null; 7405 } 7406 } 7407 7408 private void killApplication(String pkgName, int appId, String reason) { 7409 // Request the ActivityManager to kill the process(only for existing packages) 7410 // so that we do not end up in a confused state while the user is still using the older 7411 // version of the application while the new one gets installed. 7412 IActivityManager am = ActivityManagerNative.getDefault(); 7413 if (am != null) { 7414 try { 7415 am.killApplicationWithAppId(pkgName, appId, reason); 7416 } catch (RemoteException e) { 7417 } 7418 } 7419 } 7420 7421 void removePackageLI(PackageSetting ps, boolean chatty) { 7422 if (DEBUG_INSTALL) { 7423 if (chatty) 7424 Log.d(TAG, "Removing package " + ps.name); 7425 } 7426 7427 // writer 7428 synchronized (mPackages) { 7429 mPackages.remove(ps.name); 7430 final PackageParser.Package pkg = ps.pkg; 7431 if (pkg != null) { 7432 cleanPackageDataStructuresLILPw(pkg, chatty); 7433 } 7434 } 7435 } 7436 7437 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7438 if (DEBUG_INSTALL) { 7439 if (chatty) 7440 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7441 } 7442 7443 // writer 7444 synchronized (mPackages) { 7445 mPackages.remove(pkg.applicationInfo.packageName); 7446 cleanPackageDataStructuresLILPw(pkg, chatty); 7447 } 7448 } 7449 7450 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7451 int N = pkg.providers.size(); 7452 StringBuilder r = null; 7453 int i; 7454 for (i=0; i<N; i++) { 7455 PackageParser.Provider p = pkg.providers.get(i); 7456 mProviders.removeProvider(p); 7457 if (p.info.authority == null) { 7458 7459 /* There was another ContentProvider with this authority when 7460 * this app was installed so this authority is null, 7461 * Ignore it as we don't have to unregister the provider. 7462 */ 7463 continue; 7464 } 7465 String names[] = p.info.authority.split(";"); 7466 for (int j = 0; j < names.length; j++) { 7467 if (mProvidersByAuthority.get(names[j]) == p) { 7468 mProvidersByAuthority.remove(names[j]); 7469 if (DEBUG_REMOVE) { 7470 if (chatty) 7471 Log.d(TAG, "Unregistered content provider: " + names[j] 7472 + ", className = " + p.info.name + ", isSyncable = " 7473 + p.info.isSyncable); 7474 } 7475 } 7476 } 7477 if (DEBUG_REMOVE && chatty) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append(p.info.name); 7484 } 7485 } 7486 if (r != null) { 7487 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7488 } 7489 7490 N = pkg.services.size(); 7491 r = null; 7492 for (i=0; i<N; i++) { 7493 PackageParser.Service s = pkg.services.get(i); 7494 mServices.removeService(s); 7495 if (chatty) { 7496 if (r == null) { 7497 r = new StringBuilder(256); 7498 } else { 7499 r.append(' '); 7500 } 7501 r.append(s.info.name); 7502 } 7503 } 7504 if (r != null) { 7505 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7506 } 7507 7508 N = pkg.receivers.size(); 7509 r = null; 7510 for (i=0; i<N; i++) { 7511 PackageParser.Activity a = pkg.receivers.get(i); 7512 mReceivers.removeActivity(a, "receiver"); 7513 if (DEBUG_REMOVE && chatty) { 7514 if (r == null) { 7515 r = new StringBuilder(256); 7516 } else { 7517 r.append(' '); 7518 } 7519 r.append(a.info.name); 7520 } 7521 } 7522 if (r != null) { 7523 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7524 } 7525 7526 N = pkg.activities.size(); 7527 r = null; 7528 for (i=0; i<N; i++) { 7529 PackageParser.Activity a = pkg.activities.get(i); 7530 mActivities.removeActivity(a, "activity"); 7531 if (DEBUG_REMOVE && chatty) { 7532 if (r == null) { 7533 r = new StringBuilder(256); 7534 } else { 7535 r.append(' '); 7536 } 7537 r.append(a.info.name); 7538 } 7539 } 7540 if (r != null) { 7541 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7542 } 7543 7544 N = pkg.permissions.size(); 7545 r = null; 7546 for (i=0; i<N; i++) { 7547 PackageParser.Permission p = pkg.permissions.get(i); 7548 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7549 if (bp == null) { 7550 bp = mSettings.mPermissionTrees.get(p.info.name); 7551 } 7552 if (bp != null && bp.perm == p) { 7553 bp.perm = null; 7554 if (DEBUG_REMOVE && chatty) { 7555 if (r == null) { 7556 r = new StringBuilder(256); 7557 } else { 7558 r.append(' '); 7559 } 7560 r.append(p.info.name); 7561 } 7562 } 7563 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7564 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7565 if (appOpPerms != null) { 7566 appOpPerms.remove(pkg.packageName); 7567 } 7568 } 7569 } 7570 if (r != null) { 7571 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7572 } 7573 7574 N = pkg.requestedPermissions.size(); 7575 r = null; 7576 for (i=0; i<N; i++) { 7577 String perm = pkg.requestedPermissions.get(i); 7578 BasePermission bp = mSettings.mPermissions.get(perm); 7579 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7580 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7581 if (appOpPerms != null) { 7582 appOpPerms.remove(pkg.packageName); 7583 if (appOpPerms.isEmpty()) { 7584 mAppOpPermissionPackages.remove(perm); 7585 } 7586 } 7587 } 7588 } 7589 if (r != null) { 7590 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7591 } 7592 7593 N = pkg.instrumentation.size(); 7594 r = null; 7595 for (i=0; i<N; i++) { 7596 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7597 mInstrumentation.remove(a.getComponentName()); 7598 if (DEBUG_REMOVE && chatty) { 7599 if (r == null) { 7600 r = new StringBuilder(256); 7601 } else { 7602 r.append(' '); 7603 } 7604 r.append(a.info.name); 7605 } 7606 } 7607 if (r != null) { 7608 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7609 } 7610 7611 r = null; 7612 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7613 // Only system apps can hold shared libraries. 7614 if (pkg.libraryNames != null) { 7615 for (i=0; i<pkg.libraryNames.size(); i++) { 7616 String name = pkg.libraryNames.get(i); 7617 SharedLibraryEntry cur = mSharedLibraries.get(name); 7618 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7619 mSharedLibraries.remove(name); 7620 if (DEBUG_REMOVE && chatty) { 7621 if (r == null) { 7622 r = new StringBuilder(256); 7623 } else { 7624 r.append(' '); 7625 } 7626 r.append(name); 7627 } 7628 } 7629 } 7630 } 7631 } 7632 if (r != null) { 7633 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7634 } 7635 } 7636 7637 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7638 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7639 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7640 return true; 7641 } 7642 } 7643 return false; 7644 } 7645 7646 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7647 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7648 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7649 7650 private void updatePermissionsLPw(String changingPkg, 7651 PackageParser.Package pkgInfo, int flags) { 7652 // Make sure there are no dangling permission trees. 7653 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7654 while (it.hasNext()) { 7655 final BasePermission bp = it.next(); 7656 if (bp.packageSetting == null) { 7657 // We may not yet have parsed the package, so just see if 7658 // we still know about its settings. 7659 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7660 } 7661 if (bp.packageSetting == null) { 7662 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7663 + " from package " + bp.sourcePackage); 7664 it.remove(); 7665 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7666 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7667 Slog.i(TAG, "Removing old permission tree: " + bp.name 7668 + " from package " + bp.sourcePackage); 7669 flags |= UPDATE_PERMISSIONS_ALL; 7670 it.remove(); 7671 } 7672 } 7673 } 7674 7675 // Make sure all dynamic permissions have been assigned to a package, 7676 // and make sure there are no dangling permissions. 7677 it = mSettings.mPermissions.values().iterator(); 7678 while (it.hasNext()) { 7679 final BasePermission bp = it.next(); 7680 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7681 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7682 + bp.name + " pkg=" + bp.sourcePackage 7683 + " info=" + bp.pendingInfo); 7684 if (bp.packageSetting == null && bp.pendingInfo != null) { 7685 final BasePermission tree = findPermissionTreeLP(bp.name); 7686 if (tree != null && tree.perm != null) { 7687 bp.packageSetting = tree.packageSetting; 7688 bp.perm = new PackageParser.Permission(tree.perm.owner, 7689 new PermissionInfo(bp.pendingInfo)); 7690 bp.perm.info.packageName = tree.perm.info.packageName; 7691 bp.perm.info.name = bp.name; 7692 bp.uid = tree.uid; 7693 } 7694 } 7695 } 7696 if (bp.packageSetting == null) { 7697 // We may not yet have parsed the package, so just see if 7698 // we still know about its settings. 7699 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7700 } 7701 if (bp.packageSetting == null) { 7702 Slog.w(TAG, "Removing dangling permission: " + bp.name 7703 + " from package " + bp.sourcePackage); 7704 it.remove(); 7705 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7706 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7707 Slog.i(TAG, "Removing old permission: " + bp.name 7708 + " from package " + bp.sourcePackage); 7709 flags |= UPDATE_PERMISSIONS_ALL; 7710 it.remove(); 7711 } 7712 } 7713 } 7714 7715 // Now update the permissions for all packages, in particular 7716 // replace the granted permissions of the system packages. 7717 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7718 for (PackageParser.Package pkg : mPackages.values()) { 7719 if (pkg != pkgInfo) { 7720 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7721 changingPkg); 7722 } 7723 } 7724 } 7725 7726 if (pkgInfo != null) { 7727 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7728 } 7729 } 7730 7731 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7732 String packageOfInterest) { 7733 // IMPORTANT: There are two types of permissions: install and runtime. 7734 // Install time permissions are granted when the app is installed to 7735 // all device users and users added in the future. Runtime permissions 7736 // are granted at runtime explicitly to specific users. Normal and signature 7737 // protected permissions are install time permissions. Dangerous permissions 7738 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7739 // otherwise they are runtime permissions. This function does not manage 7740 // runtime permissions except for the case an app targeting Lollipop MR1 7741 // being upgraded to target a newer SDK, in which case dangerous permissions 7742 // are transformed from install time to runtime ones. 7743 7744 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7745 if (ps == null) { 7746 return; 7747 } 7748 7749 PermissionsState permissionsState = ps.getPermissionsState(); 7750 PermissionsState origPermissions = permissionsState; 7751 7752 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7753 7754 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7755 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7756 7757 boolean changedInstallPermission = false; 7758 7759 if (replace) { 7760 ps.installPermissionsFixed = false; 7761 if (!ps.isSharedUser()) { 7762 origPermissions = new PermissionsState(permissionsState); 7763 permissionsState.reset(); 7764 } 7765 } 7766 7767 permissionsState.setGlobalGids(mGlobalGids); 7768 7769 final int N = pkg.requestedPermissions.size(); 7770 for (int i=0; i<N; i++) { 7771 final String name = pkg.requestedPermissions.get(i); 7772 final BasePermission bp = mSettings.mPermissions.get(name); 7773 7774 if (DEBUG_INSTALL) { 7775 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7776 } 7777 7778 if (bp == null || bp.packageSetting == null) { 7779 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7780 Slog.w(TAG, "Unknown permission " + name 7781 + " in package " + pkg.packageName); 7782 } 7783 continue; 7784 } 7785 7786 final String perm = bp.name; 7787 boolean allowedSig = false; 7788 int grant = GRANT_DENIED; 7789 7790 // Keep track of app op permissions. 7791 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7792 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7793 if (pkgs == null) { 7794 pkgs = new ArraySet<>(); 7795 mAppOpPermissionPackages.put(bp.name, pkgs); 7796 } 7797 pkgs.add(pkg.packageName); 7798 } 7799 7800 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7801 switch (level) { 7802 case PermissionInfo.PROTECTION_NORMAL: { 7803 // For all apps normal permissions are install time ones. 7804 grant = GRANT_INSTALL; 7805 } break; 7806 7807 case PermissionInfo.PROTECTION_DANGEROUS: { 7808 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7809 // For legacy apps dangerous permissions are install time ones. 7810 grant = GRANT_INSTALL_LEGACY; 7811 } else if (ps.isSystem()) { 7812 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7813 if (origPermissions.hasInstallPermission(bp.name)) { 7814 // If a system app had an install permission, then the app was 7815 // upgraded and we grant the permissions as runtime to all users. 7816 grant = GRANT_UPGRADE; 7817 upgradeUserIds = currentUserIds; 7818 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7819 // If users changed since the last permissions update for a 7820 // system app, we grant the permission as runtime to the new users. 7821 grant = GRANT_UPGRADE; 7822 upgradeUserIds = currentUserIds; 7823 for (int userId : updatedUserIds) { 7824 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7825 } 7826 } else { 7827 // Otherwise, we grant the permission as runtime if the app 7828 // already had it, i.e. we preserve runtime permissions. 7829 grant = GRANT_RUNTIME; 7830 } 7831 } else if (origPermissions.hasInstallPermission(bp.name)) { 7832 // For legacy apps that became modern, install becomes runtime. 7833 grant = GRANT_UPGRADE; 7834 upgradeUserIds = currentUserIds; 7835 } else if (replace) { 7836 // For upgraded 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 permssion 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 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7903 PermissionState permissionState = origPermissions 7904 .getRuntimePermissionState(bp.name, userId); 7905 final int flags = permissionState.getFlags(); 7906 if (permissionsState.grantRuntimePermission(bp, userId) == 7907 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7908 // If we cannot put the permission as it was, we have to write. 7909 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7910 changedRuntimePermissionUserIds, userId); 7911 } else { 7912 // System components not only get the permissions but 7913 // they are also fixed, so nothing can change that. 7914 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7915 ? flags 7916 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7917 // Propagate the permission flags. 7918 permissionsState.updatePermissionFlags(bp, userId, 7919 newFlags, newFlags); 7920 } 7921 } 7922 } 7923 } break; 7924 7925 case GRANT_UPGRADE: { 7926 // Grant runtime permissions for a previously held install permission. 7927 PermissionState permissionState = origPermissions 7928 .getInstallPermissionState(bp.name); 7929 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7930 7931 origPermissions.revokeInstallPermission(bp); 7932 // We will be transferring the permission flags, so clear them. 7933 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7934 PackageManager.MASK_PERMISSION_FLAGS, 0); 7935 7936 // If the permission is not to be promoted to runtime we ignore it and 7937 // also its other flags as they are not applicable to install permissions. 7938 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7939 for (int userId : upgradeUserIds) { 7940 if (permissionsState.grantRuntimePermission(bp, userId) != 7941 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7942 // System components not only get the permissions but 7943 // they are also fixed so nothing can change that. 7944 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7945 ? flags 7946 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7947 // Transfer the permission flags. 7948 permissionsState.updatePermissionFlags(bp, userId, 7949 newFlags, newFlags); 7950 // If we granted the permission, we have to write. 7951 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7952 changedRuntimePermissionUserIds, userId); 7953 } 7954 } 7955 } 7956 } break; 7957 7958 default: { 7959 if (packageOfInterest == null 7960 || packageOfInterest.equals(pkg.packageName)) { 7961 Slog.w(TAG, "Not granting permission " + perm 7962 + " to package " + pkg.packageName 7963 + " because it was previously installed without"); 7964 } 7965 } break; 7966 } 7967 } else { 7968 if (permissionsState.revokeInstallPermission(bp) != 7969 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7970 // Also drop the permission flags. 7971 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7972 PackageManager.MASK_PERMISSION_FLAGS, 0); 7973 changedInstallPermission = true; 7974 Slog.i(TAG, "Un-granting permission " + perm 7975 + " from package " + pkg.packageName 7976 + " (protectionLevel=" + bp.protectionLevel 7977 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7978 + ")"); 7979 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7980 // Don't print warning for app op permissions, since it is fine for them 7981 // not to be granted, there is a UI for the user to decide. 7982 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7983 Slog.w(TAG, "Not granting permission " + perm 7984 + " to package " + pkg.packageName 7985 + " (protectionLevel=" + bp.protectionLevel 7986 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7987 + ")"); 7988 } 7989 } 7990 } 7991 } 7992 7993 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7994 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7995 // This is the first that we have heard about this package, so the 7996 // permissions we have now selected are fixed until explicitly 7997 // changed. 7998 ps.installPermissionsFixed = true; 7999 } 8000 8001 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8002 8003 // Persist the runtime permissions state for users with changes. 8004 for (int userId : changedRuntimePermissionUserIds) { 8005 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8006 } 8007 } 8008 8009 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8010 boolean allowed = false; 8011 final int NP = PackageParser.NEW_PERMISSIONS.length; 8012 for (int ip=0; ip<NP; ip++) { 8013 final PackageParser.NewPermissionInfo npi 8014 = PackageParser.NEW_PERMISSIONS[ip]; 8015 if (npi.name.equals(perm) 8016 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8017 allowed = true; 8018 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8019 + pkg.packageName); 8020 break; 8021 } 8022 } 8023 return allowed; 8024 } 8025 8026 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8027 BasePermission bp, PermissionsState origPermissions) { 8028 boolean allowed; 8029 allowed = (compareSignatures( 8030 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8031 == PackageManager.SIGNATURE_MATCH) 8032 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8033 == PackageManager.SIGNATURE_MATCH); 8034 if (!allowed && (bp.protectionLevel 8035 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8036 if (isSystemApp(pkg)) { 8037 // For updated system applications, a system permission 8038 // is granted only if it had been defined by the original application. 8039 if (pkg.isUpdatedSystemApp()) { 8040 final PackageSetting sysPs = mSettings 8041 .getDisabledSystemPkgLPr(pkg.packageName); 8042 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8043 // If the original was granted this permission, we take 8044 // that grant decision as read and propagate it to the 8045 // update. 8046 if (sysPs.isPrivileged()) { 8047 allowed = true; 8048 } 8049 } else { 8050 // The system apk may have been updated with an older 8051 // version of the one on the data partition, but which 8052 // granted a new system permission that it didn't have 8053 // before. In this case we do want to allow the app to 8054 // now get the new permission if the ancestral apk is 8055 // privileged to get it. 8056 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8057 for (int j=0; 8058 j<sysPs.pkg.requestedPermissions.size(); j++) { 8059 if (perm.equals( 8060 sysPs.pkg.requestedPermissions.get(j))) { 8061 allowed = true; 8062 break; 8063 } 8064 } 8065 } 8066 } 8067 } else { 8068 allowed = isPrivilegedApp(pkg); 8069 } 8070 } 8071 } 8072 if (!allowed && (bp.protectionLevel 8073 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8074 // For development permissions, a development permission 8075 // is granted only if it was already granted. 8076 allowed = origPermissions.hasInstallPermission(perm); 8077 } 8078 return allowed; 8079 } 8080 8081 final class ActivityIntentResolver 8082 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8084 boolean defaultOnly, int userId) { 8085 if (!sUserManager.exists(userId)) return null; 8086 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8087 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8088 } 8089 8090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8091 int userId) { 8092 if (!sUserManager.exists(userId)) return null; 8093 mFlags = flags; 8094 return super.queryIntent(intent, resolvedType, 8095 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8096 } 8097 8098 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8099 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8100 if (!sUserManager.exists(userId)) return null; 8101 if (packageActivities == null) { 8102 return null; 8103 } 8104 mFlags = flags; 8105 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8106 final int N = packageActivities.size(); 8107 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8108 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8109 8110 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8111 for (int i = 0; i < N; ++i) { 8112 intentFilters = packageActivities.get(i).intents; 8113 if (intentFilters != null && intentFilters.size() > 0) { 8114 PackageParser.ActivityIntentInfo[] array = 8115 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8116 intentFilters.toArray(array); 8117 listCut.add(array); 8118 } 8119 } 8120 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8121 } 8122 8123 public final void addActivity(PackageParser.Activity a, String type) { 8124 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8125 mActivities.put(a.getComponentName(), a); 8126 if (DEBUG_SHOW_INFO) 8127 Log.v( 8128 TAG, " " + type + " " + 8129 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8130 if (DEBUG_SHOW_INFO) 8131 Log.v(TAG, " Class=" + a.info.name); 8132 final int NI = a.intents.size(); 8133 for (int j=0; j<NI; j++) { 8134 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8135 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8136 intent.setPriority(0); 8137 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8138 + a.className + " with priority > 0, forcing to 0"); 8139 } 8140 if (DEBUG_SHOW_INFO) { 8141 Log.v(TAG, " IntentFilter:"); 8142 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8143 } 8144 if (!intent.debugCheck()) { 8145 Log.w(TAG, "==> For Activity " + a.info.name); 8146 } 8147 addFilter(intent); 8148 } 8149 } 8150 8151 public final void removeActivity(PackageParser.Activity a, String type) { 8152 mActivities.remove(a.getComponentName()); 8153 if (DEBUG_SHOW_INFO) { 8154 Log.v(TAG, " " + type + " " 8155 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8156 : a.info.name) + ":"); 8157 Log.v(TAG, " Class=" + a.info.name); 8158 } 8159 final int NI = a.intents.size(); 8160 for (int j=0; j<NI; j++) { 8161 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8162 if (DEBUG_SHOW_INFO) { 8163 Log.v(TAG, " IntentFilter:"); 8164 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8165 } 8166 removeFilter(intent); 8167 } 8168 } 8169 8170 @Override 8171 protected boolean allowFilterResult( 8172 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8173 ActivityInfo filterAi = filter.activity.info; 8174 for (int i=dest.size()-1; i>=0; i--) { 8175 ActivityInfo destAi = dest.get(i).activityInfo; 8176 if (destAi.name == filterAi.name 8177 && destAi.packageName == filterAi.packageName) { 8178 return false; 8179 } 8180 } 8181 return true; 8182 } 8183 8184 @Override 8185 protected ActivityIntentInfo[] newArray(int size) { 8186 return new ActivityIntentInfo[size]; 8187 } 8188 8189 @Override 8190 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8191 if (!sUserManager.exists(userId)) return true; 8192 PackageParser.Package p = filter.activity.owner; 8193 if (p != null) { 8194 PackageSetting ps = (PackageSetting)p.mExtras; 8195 if (ps != null) { 8196 // System apps are never considered stopped for purposes of 8197 // filtering, because there may be no way for the user to 8198 // actually re-launch them. 8199 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8200 && ps.getStopped(userId); 8201 } 8202 } 8203 return false; 8204 } 8205 8206 @Override 8207 protected boolean isPackageForFilter(String packageName, 8208 PackageParser.ActivityIntentInfo info) { 8209 return packageName.equals(info.activity.owner.packageName); 8210 } 8211 8212 @Override 8213 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8214 int match, int userId) { 8215 if (!sUserManager.exists(userId)) return null; 8216 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8217 return null; 8218 } 8219 final PackageParser.Activity activity = info.activity; 8220 if (mSafeMode && (activity.info.applicationInfo.flags 8221 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8222 return null; 8223 } 8224 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8225 if (ps == null) { 8226 return null; 8227 } 8228 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8229 ps.readUserState(userId), userId); 8230 if (ai == null) { 8231 return null; 8232 } 8233 final ResolveInfo res = new ResolveInfo(); 8234 res.activityInfo = ai; 8235 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8236 res.filter = info; 8237 } 8238 if (info != null) { 8239 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8240 } 8241 res.priority = info.getPriority(); 8242 res.preferredOrder = activity.owner.mPreferredOrder; 8243 //System.out.println("Result: " + res.activityInfo.className + 8244 // " = " + res.priority); 8245 res.match = match; 8246 res.isDefault = info.hasDefault; 8247 res.labelRes = info.labelRes; 8248 res.nonLocalizedLabel = info.nonLocalizedLabel; 8249 if (userNeedsBadging(userId)) { 8250 res.noResourceId = true; 8251 } else { 8252 res.icon = info.icon; 8253 } 8254 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8255 return res; 8256 } 8257 8258 @Override 8259 protected void sortResults(List<ResolveInfo> results) { 8260 Collections.sort(results, mResolvePrioritySorter); 8261 } 8262 8263 @Override 8264 protected void dumpFilter(PrintWriter out, String prefix, 8265 PackageParser.ActivityIntentInfo filter) { 8266 out.print(prefix); out.print( 8267 Integer.toHexString(System.identityHashCode(filter.activity))); 8268 out.print(' '); 8269 filter.activity.printComponentShortName(out); 8270 out.print(" filter "); 8271 out.println(Integer.toHexString(System.identityHashCode(filter))); 8272 } 8273 8274 @Override 8275 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8276 return filter.activity; 8277 } 8278 8279 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8280 PackageParser.Activity activity = (PackageParser.Activity)label; 8281 out.print(prefix); out.print( 8282 Integer.toHexString(System.identityHashCode(activity))); 8283 out.print(' '); 8284 activity.printComponentShortName(out); 8285 if (count > 1) { 8286 out.print(" ("); out.print(count); out.print(" filters)"); 8287 } 8288 out.println(); 8289 } 8290 8291// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8292// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8293// final List<ResolveInfo> retList = Lists.newArrayList(); 8294// while (i.hasNext()) { 8295// final ResolveInfo resolveInfo = i.next(); 8296// if (isEnabledLP(resolveInfo.activityInfo)) { 8297// retList.add(resolveInfo); 8298// } 8299// } 8300// return retList; 8301// } 8302 8303 // Keys are String (activity class name), values are Activity. 8304 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8305 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8306 private int mFlags; 8307 } 8308 8309 private final class ServiceIntentResolver 8310 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8311 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8312 boolean defaultOnly, int userId) { 8313 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8314 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8315 } 8316 8317 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8318 int userId) { 8319 if (!sUserManager.exists(userId)) return null; 8320 mFlags = flags; 8321 return super.queryIntent(intent, resolvedType, 8322 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8323 } 8324 8325 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8326 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8327 if (!sUserManager.exists(userId)) return null; 8328 if (packageServices == null) { 8329 return null; 8330 } 8331 mFlags = flags; 8332 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8333 final int N = packageServices.size(); 8334 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8335 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8336 8337 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8338 for (int i = 0; i < N; ++i) { 8339 intentFilters = packageServices.get(i).intents; 8340 if (intentFilters != null && intentFilters.size() > 0) { 8341 PackageParser.ServiceIntentInfo[] array = 8342 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8343 intentFilters.toArray(array); 8344 listCut.add(array); 8345 } 8346 } 8347 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8348 } 8349 8350 public final void addService(PackageParser.Service s) { 8351 mServices.put(s.getComponentName(), s); 8352 if (DEBUG_SHOW_INFO) { 8353 Log.v(TAG, " " 8354 + (s.info.nonLocalizedLabel != null 8355 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8356 Log.v(TAG, " Class=" + s.info.name); 8357 } 8358 final int NI = s.intents.size(); 8359 int j; 8360 for (j=0; j<NI; j++) { 8361 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8362 if (DEBUG_SHOW_INFO) { 8363 Log.v(TAG, " IntentFilter:"); 8364 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8365 } 8366 if (!intent.debugCheck()) { 8367 Log.w(TAG, "==> For Service " + s.info.name); 8368 } 8369 addFilter(intent); 8370 } 8371 } 8372 8373 public final void removeService(PackageParser.Service s) { 8374 mServices.remove(s.getComponentName()); 8375 if (DEBUG_SHOW_INFO) { 8376 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8377 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8378 Log.v(TAG, " Class=" + s.info.name); 8379 } 8380 final int NI = s.intents.size(); 8381 int j; 8382 for (j=0; j<NI; j++) { 8383 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8384 if (DEBUG_SHOW_INFO) { 8385 Log.v(TAG, " IntentFilter:"); 8386 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8387 } 8388 removeFilter(intent); 8389 } 8390 } 8391 8392 @Override 8393 protected boolean allowFilterResult( 8394 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8395 ServiceInfo filterSi = filter.service.info; 8396 for (int i=dest.size()-1; i>=0; i--) { 8397 ServiceInfo destAi = dest.get(i).serviceInfo; 8398 if (destAi.name == filterSi.name 8399 && destAi.packageName == filterSi.packageName) { 8400 return false; 8401 } 8402 } 8403 return true; 8404 } 8405 8406 @Override 8407 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8408 return new PackageParser.ServiceIntentInfo[size]; 8409 } 8410 8411 @Override 8412 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8413 if (!sUserManager.exists(userId)) return true; 8414 PackageParser.Package p = filter.service.owner; 8415 if (p != null) { 8416 PackageSetting ps = (PackageSetting)p.mExtras; 8417 if (ps != null) { 8418 // System apps are never considered stopped for purposes of 8419 // filtering, because there may be no way for the user to 8420 // actually re-launch them. 8421 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8422 && ps.getStopped(userId); 8423 } 8424 } 8425 return false; 8426 } 8427 8428 @Override 8429 protected boolean isPackageForFilter(String packageName, 8430 PackageParser.ServiceIntentInfo info) { 8431 return packageName.equals(info.service.owner.packageName); 8432 } 8433 8434 @Override 8435 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8436 int match, int userId) { 8437 if (!sUserManager.exists(userId)) return null; 8438 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8439 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8440 return null; 8441 } 8442 final PackageParser.Service service = info.service; 8443 if (mSafeMode && (service.info.applicationInfo.flags 8444 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8445 return null; 8446 } 8447 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8448 if (ps == null) { 8449 return null; 8450 } 8451 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8452 ps.readUserState(userId), userId); 8453 if (si == null) { 8454 return null; 8455 } 8456 final ResolveInfo res = new ResolveInfo(); 8457 res.serviceInfo = si; 8458 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8459 res.filter = filter; 8460 } 8461 res.priority = info.getPriority(); 8462 res.preferredOrder = service.owner.mPreferredOrder; 8463 res.match = match; 8464 res.isDefault = info.hasDefault; 8465 res.labelRes = info.labelRes; 8466 res.nonLocalizedLabel = info.nonLocalizedLabel; 8467 res.icon = info.icon; 8468 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8469 return res; 8470 } 8471 8472 @Override 8473 protected void sortResults(List<ResolveInfo> results) { 8474 Collections.sort(results, mResolvePrioritySorter); 8475 } 8476 8477 @Override 8478 protected void dumpFilter(PrintWriter out, String prefix, 8479 PackageParser.ServiceIntentInfo filter) { 8480 out.print(prefix); out.print( 8481 Integer.toHexString(System.identityHashCode(filter.service))); 8482 out.print(' '); 8483 filter.service.printComponentShortName(out); 8484 out.print(" filter "); 8485 out.println(Integer.toHexString(System.identityHashCode(filter))); 8486 } 8487 8488 @Override 8489 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8490 return filter.service; 8491 } 8492 8493 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8494 PackageParser.Service service = (PackageParser.Service)label; 8495 out.print(prefix); out.print( 8496 Integer.toHexString(System.identityHashCode(service))); 8497 out.print(' '); 8498 service.printComponentShortName(out); 8499 if (count > 1) { 8500 out.print(" ("); out.print(count); out.print(" filters)"); 8501 } 8502 out.println(); 8503 } 8504 8505// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8506// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8507// final List<ResolveInfo> retList = Lists.newArrayList(); 8508// while (i.hasNext()) { 8509// final ResolveInfo resolveInfo = (ResolveInfo) i; 8510// if (isEnabledLP(resolveInfo.serviceInfo)) { 8511// retList.add(resolveInfo); 8512// } 8513// } 8514// return retList; 8515// } 8516 8517 // Keys are String (activity class name), values are Activity. 8518 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8519 = new ArrayMap<ComponentName, PackageParser.Service>(); 8520 private int mFlags; 8521 }; 8522 8523 private final class ProviderIntentResolver 8524 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8525 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8526 boolean defaultOnly, int userId) { 8527 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8528 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8529 } 8530 8531 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8532 int userId) { 8533 if (!sUserManager.exists(userId)) 8534 return null; 8535 mFlags = flags; 8536 return super.queryIntent(intent, resolvedType, 8537 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8538 } 8539 8540 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8541 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8542 if (!sUserManager.exists(userId)) 8543 return null; 8544 if (packageProviders == null) { 8545 return null; 8546 } 8547 mFlags = flags; 8548 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8549 final int N = packageProviders.size(); 8550 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8551 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8552 8553 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8554 for (int i = 0; i < N; ++i) { 8555 intentFilters = packageProviders.get(i).intents; 8556 if (intentFilters != null && intentFilters.size() > 0) { 8557 PackageParser.ProviderIntentInfo[] array = 8558 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8559 intentFilters.toArray(array); 8560 listCut.add(array); 8561 } 8562 } 8563 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8564 } 8565 8566 public final void addProvider(PackageParser.Provider p) { 8567 if (mProviders.containsKey(p.getComponentName())) { 8568 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8569 return; 8570 } 8571 8572 mProviders.put(p.getComponentName(), p); 8573 if (DEBUG_SHOW_INFO) { 8574 Log.v(TAG, " " 8575 + (p.info.nonLocalizedLabel != null 8576 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8577 Log.v(TAG, " Class=" + p.info.name); 8578 } 8579 final int NI = p.intents.size(); 8580 int j; 8581 for (j = 0; j < NI; j++) { 8582 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8583 if (DEBUG_SHOW_INFO) { 8584 Log.v(TAG, " IntentFilter:"); 8585 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8586 } 8587 if (!intent.debugCheck()) { 8588 Log.w(TAG, "==> For Provider " + p.info.name); 8589 } 8590 addFilter(intent); 8591 } 8592 } 8593 8594 public final void removeProvider(PackageParser.Provider p) { 8595 mProviders.remove(p.getComponentName()); 8596 if (DEBUG_SHOW_INFO) { 8597 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8598 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8599 Log.v(TAG, " Class=" + p.info.name); 8600 } 8601 final int NI = p.intents.size(); 8602 int j; 8603 for (j = 0; j < NI; j++) { 8604 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8605 if (DEBUG_SHOW_INFO) { 8606 Log.v(TAG, " IntentFilter:"); 8607 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8608 } 8609 removeFilter(intent); 8610 } 8611 } 8612 8613 @Override 8614 protected boolean allowFilterResult( 8615 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8616 ProviderInfo filterPi = filter.provider.info; 8617 for (int i = dest.size() - 1; i >= 0; i--) { 8618 ProviderInfo destPi = dest.get(i).providerInfo; 8619 if (destPi.name == filterPi.name 8620 && destPi.packageName == filterPi.packageName) { 8621 return false; 8622 } 8623 } 8624 return true; 8625 } 8626 8627 @Override 8628 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8629 return new PackageParser.ProviderIntentInfo[size]; 8630 } 8631 8632 @Override 8633 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8634 if (!sUserManager.exists(userId)) 8635 return true; 8636 PackageParser.Package p = filter.provider.owner; 8637 if (p != null) { 8638 PackageSetting ps = (PackageSetting) p.mExtras; 8639 if (ps != null) { 8640 // System apps are never considered stopped for purposes of 8641 // filtering, because there may be no way for the user to 8642 // actually re-launch them. 8643 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8644 && ps.getStopped(userId); 8645 } 8646 } 8647 return false; 8648 } 8649 8650 @Override 8651 protected boolean isPackageForFilter(String packageName, 8652 PackageParser.ProviderIntentInfo info) { 8653 return packageName.equals(info.provider.owner.packageName); 8654 } 8655 8656 @Override 8657 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8658 int match, int userId) { 8659 if (!sUserManager.exists(userId)) 8660 return null; 8661 final PackageParser.ProviderIntentInfo info = filter; 8662 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8663 return null; 8664 } 8665 final PackageParser.Provider provider = info.provider; 8666 if (mSafeMode && (provider.info.applicationInfo.flags 8667 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8668 return null; 8669 } 8670 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8671 if (ps == null) { 8672 return null; 8673 } 8674 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8675 ps.readUserState(userId), userId); 8676 if (pi == null) { 8677 return null; 8678 } 8679 final ResolveInfo res = new ResolveInfo(); 8680 res.providerInfo = pi; 8681 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8682 res.filter = filter; 8683 } 8684 res.priority = info.getPriority(); 8685 res.preferredOrder = provider.owner.mPreferredOrder; 8686 res.match = match; 8687 res.isDefault = info.hasDefault; 8688 res.labelRes = info.labelRes; 8689 res.nonLocalizedLabel = info.nonLocalizedLabel; 8690 res.icon = info.icon; 8691 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8692 return res; 8693 } 8694 8695 @Override 8696 protected void sortResults(List<ResolveInfo> results) { 8697 Collections.sort(results, mResolvePrioritySorter); 8698 } 8699 8700 @Override 8701 protected void dumpFilter(PrintWriter out, String prefix, 8702 PackageParser.ProviderIntentInfo filter) { 8703 out.print(prefix); 8704 out.print( 8705 Integer.toHexString(System.identityHashCode(filter.provider))); 8706 out.print(' '); 8707 filter.provider.printComponentShortName(out); 8708 out.print(" filter "); 8709 out.println(Integer.toHexString(System.identityHashCode(filter))); 8710 } 8711 8712 @Override 8713 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8714 return filter.provider; 8715 } 8716 8717 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8718 PackageParser.Provider provider = (PackageParser.Provider)label; 8719 out.print(prefix); out.print( 8720 Integer.toHexString(System.identityHashCode(provider))); 8721 out.print(' '); 8722 provider.printComponentShortName(out); 8723 if (count > 1) { 8724 out.print(" ("); out.print(count); out.print(" filters)"); 8725 } 8726 out.println(); 8727 } 8728 8729 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8730 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8731 private int mFlags; 8732 }; 8733 8734 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8735 new Comparator<ResolveInfo>() { 8736 public int compare(ResolveInfo r1, ResolveInfo r2) { 8737 int v1 = r1.priority; 8738 int v2 = r2.priority; 8739 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8740 if (v1 != v2) { 8741 return (v1 > v2) ? -1 : 1; 8742 } 8743 v1 = r1.preferredOrder; 8744 v2 = r2.preferredOrder; 8745 if (v1 != v2) { 8746 return (v1 > v2) ? -1 : 1; 8747 } 8748 if (r1.isDefault != r2.isDefault) { 8749 return r1.isDefault ? -1 : 1; 8750 } 8751 v1 = r1.match; 8752 v2 = r2.match; 8753 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8754 if (v1 != v2) { 8755 return (v1 > v2) ? -1 : 1; 8756 } 8757 if (r1.system != r2.system) { 8758 return r1.system ? -1 : 1; 8759 } 8760 return 0; 8761 } 8762 }; 8763 8764 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8765 new Comparator<ProviderInfo>() { 8766 public int compare(ProviderInfo p1, ProviderInfo p2) { 8767 final int v1 = p1.initOrder; 8768 final int v2 = p2.initOrder; 8769 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8770 } 8771 }; 8772 8773 final void sendPackageBroadcast(final String action, final String pkg, 8774 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8775 final int[] userIds) { 8776 mHandler.post(new Runnable() { 8777 @Override 8778 public void run() { 8779 try { 8780 final IActivityManager am = ActivityManagerNative.getDefault(); 8781 if (am == null) return; 8782 final int[] resolvedUserIds; 8783 if (userIds == null) { 8784 resolvedUserIds = am.getRunningUserIds(); 8785 } else { 8786 resolvedUserIds = userIds; 8787 } 8788 for (int id : resolvedUserIds) { 8789 final Intent intent = new Intent(action, 8790 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8791 if (extras != null) { 8792 intent.putExtras(extras); 8793 } 8794 if (targetPkg != null) { 8795 intent.setPackage(targetPkg); 8796 } 8797 // Modify the UID when posting to other users 8798 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8799 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8800 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8801 intent.putExtra(Intent.EXTRA_UID, uid); 8802 } 8803 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8804 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8805 if (DEBUG_BROADCASTS) { 8806 RuntimeException here = new RuntimeException("here"); 8807 here.fillInStackTrace(); 8808 Slog.d(TAG, "Sending to user " + id + ": " 8809 + intent.toShortString(false, true, false, false) 8810 + " " + intent.getExtras(), here); 8811 } 8812 am.broadcastIntent(null, intent, null, finishedReceiver, 8813 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8814 null, finishedReceiver != null, false, id); 8815 } 8816 } catch (RemoteException ex) { 8817 } 8818 } 8819 }); 8820 } 8821 8822 /** 8823 * Check if the external storage media is available. This is true if there 8824 * is a mounted external storage medium or if the external storage is 8825 * emulated. 8826 */ 8827 private boolean isExternalMediaAvailable() { 8828 return mMediaMounted || Environment.isExternalStorageEmulated(); 8829 } 8830 8831 @Override 8832 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8833 // writer 8834 synchronized (mPackages) { 8835 if (!isExternalMediaAvailable()) { 8836 // If the external storage is no longer mounted at this point, 8837 // the caller may not have been able to delete all of this 8838 // packages files and can not delete any more. Bail. 8839 return null; 8840 } 8841 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8842 if (lastPackage != null) { 8843 pkgs.remove(lastPackage); 8844 } 8845 if (pkgs.size() > 0) { 8846 return pkgs.get(0); 8847 } 8848 } 8849 return null; 8850 } 8851 8852 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8853 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8854 userId, andCode ? 1 : 0, packageName); 8855 if (mSystemReady) { 8856 msg.sendToTarget(); 8857 } else { 8858 if (mPostSystemReadyMessages == null) { 8859 mPostSystemReadyMessages = new ArrayList<>(); 8860 } 8861 mPostSystemReadyMessages.add(msg); 8862 } 8863 } 8864 8865 void startCleaningPackages() { 8866 // reader 8867 synchronized (mPackages) { 8868 if (!isExternalMediaAvailable()) { 8869 return; 8870 } 8871 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8872 return; 8873 } 8874 } 8875 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8876 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8877 IActivityManager am = ActivityManagerNative.getDefault(); 8878 if (am != null) { 8879 try { 8880 am.startService(null, intent, null, UserHandle.USER_OWNER); 8881 } catch (RemoteException e) { 8882 } 8883 } 8884 } 8885 8886 @Override 8887 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8888 int installFlags, String installerPackageName, VerificationParams verificationParams, 8889 String packageAbiOverride) { 8890 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8891 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8892 } 8893 8894 @Override 8895 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8896 int installFlags, String installerPackageName, VerificationParams verificationParams, 8897 String packageAbiOverride, int userId) { 8898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8899 8900 final int callingUid = Binder.getCallingUid(); 8901 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8902 8903 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8904 try { 8905 if (observer != null) { 8906 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8907 } 8908 } catch (RemoteException re) { 8909 } 8910 return; 8911 } 8912 8913 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8914 installFlags |= PackageManager.INSTALL_FROM_ADB; 8915 8916 } else { 8917 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8918 // about installerPackageName. 8919 8920 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8921 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8922 } 8923 8924 UserHandle user; 8925 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8926 user = UserHandle.ALL; 8927 } else { 8928 user = new UserHandle(userId); 8929 } 8930 8931 // Only system components can circumvent runtime permissions when installing. 8932 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8933 && mContext.checkCallingOrSelfPermission(Manifest.permission 8934 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8935 throw new SecurityException("You need the " 8936 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8937 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8938 } 8939 8940 verificationParams.setInstallerUid(callingUid); 8941 8942 final File originFile = new File(originPath); 8943 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8944 8945 final Message msg = mHandler.obtainMessage(INIT_COPY); 8946 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8947 null, verificationParams, user, packageAbiOverride); 8948 mHandler.sendMessage(msg); 8949 } 8950 8951 void installStage(String packageName, File stagedDir, String stagedCid, 8952 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8953 String installerPackageName, int installerUid, UserHandle user) { 8954 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8955 params.referrerUri, installerUid, null); 8956 8957 final OriginInfo origin; 8958 if (stagedDir != null) { 8959 origin = OriginInfo.fromStagedFile(stagedDir); 8960 } else { 8961 origin = OriginInfo.fromStagedContainer(stagedCid); 8962 } 8963 8964 final Message msg = mHandler.obtainMessage(INIT_COPY); 8965 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8966 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8967 mHandler.sendMessage(msg); 8968 } 8969 8970 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8971 Bundle extras = new Bundle(1); 8972 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8973 8974 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8975 packageName, extras, null, null, new int[] {userId}); 8976 try { 8977 IActivityManager am = ActivityManagerNative.getDefault(); 8978 final boolean isSystem = 8979 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8980 if (isSystem && am.isUserRunning(userId, false)) { 8981 // The just-installed/enabled app is bundled on the system, so presumed 8982 // to be able to run automatically without needing an explicit launch. 8983 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8984 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8985 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8986 .setPackage(packageName); 8987 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8988 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8989 } 8990 } catch (RemoteException e) { 8991 // shouldn't happen 8992 Slog.w(TAG, "Unable to bootstrap installed package", e); 8993 } 8994 } 8995 8996 @Override 8997 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8998 int userId) { 8999 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9000 PackageSetting pkgSetting; 9001 final int uid = Binder.getCallingUid(); 9002 enforceCrossUserPermission(uid, userId, true, true, 9003 "setApplicationHiddenSetting for user " + userId); 9004 9005 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9006 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9007 return false; 9008 } 9009 9010 long callingId = Binder.clearCallingIdentity(); 9011 try { 9012 boolean sendAdded = false; 9013 boolean sendRemoved = false; 9014 // writer 9015 synchronized (mPackages) { 9016 pkgSetting = mSettings.mPackages.get(packageName); 9017 if (pkgSetting == null) { 9018 return false; 9019 } 9020 if (pkgSetting.getHidden(userId) != hidden) { 9021 pkgSetting.setHidden(hidden, userId); 9022 mSettings.writePackageRestrictionsLPr(userId); 9023 if (hidden) { 9024 sendRemoved = true; 9025 } else { 9026 sendAdded = true; 9027 } 9028 } 9029 } 9030 if (sendAdded) { 9031 sendPackageAddedForUser(packageName, pkgSetting, userId); 9032 return true; 9033 } 9034 if (sendRemoved) { 9035 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9036 "hiding pkg"); 9037 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9038 } 9039 } finally { 9040 Binder.restoreCallingIdentity(callingId); 9041 } 9042 return false; 9043 } 9044 9045 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9046 int userId) { 9047 final PackageRemovedInfo info = new PackageRemovedInfo(); 9048 info.removedPackage = packageName; 9049 info.removedUsers = new int[] {userId}; 9050 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9051 info.sendBroadcast(false, false, false); 9052 } 9053 9054 /** 9055 * Returns true if application is not found or there was an error. Otherwise it returns 9056 * the hidden state of the package for the given user. 9057 */ 9058 @Override 9059 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9060 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9061 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9062 false, "getApplicationHidden for user " + userId); 9063 PackageSetting pkgSetting; 9064 long callingId = Binder.clearCallingIdentity(); 9065 try { 9066 // writer 9067 synchronized (mPackages) { 9068 pkgSetting = mSettings.mPackages.get(packageName); 9069 if (pkgSetting == null) { 9070 return true; 9071 } 9072 return pkgSetting.getHidden(userId); 9073 } 9074 } finally { 9075 Binder.restoreCallingIdentity(callingId); 9076 } 9077 } 9078 9079 /** 9080 * @hide 9081 */ 9082 @Override 9083 public int installExistingPackageAsUser(String packageName, int userId) { 9084 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9085 null); 9086 PackageSetting pkgSetting; 9087 final int uid = Binder.getCallingUid(); 9088 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9089 + userId); 9090 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9091 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9092 } 9093 9094 long callingId = Binder.clearCallingIdentity(); 9095 try { 9096 boolean sendAdded = false; 9097 9098 // writer 9099 synchronized (mPackages) { 9100 pkgSetting = mSettings.mPackages.get(packageName); 9101 if (pkgSetting == null) { 9102 return PackageManager.INSTALL_FAILED_INVALID_URI; 9103 } 9104 if (!pkgSetting.getInstalled(userId)) { 9105 pkgSetting.setInstalled(true, userId); 9106 pkgSetting.setHidden(false, userId); 9107 mSettings.writePackageRestrictionsLPr(userId); 9108 sendAdded = true; 9109 } 9110 } 9111 9112 if (sendAdded) { 9113 sendPackageAddedForUser(packageName, pkgSetting, userId); 9114 } 9115 } finally { 9116 Binder.restoreCallingIdentity(callingId); 9117 } 9118 9119 return PackageManager.INSTALL_SUCCEEDED; 9120 } 9121 9122 boolean isUserRestricted(int userId, String restrictionKey) { 9123 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9124 if (restrictions.getBoolean(restrictionKey, false)) { 9125 Log.w(TAG, "User is restricted: " + restrictionKey); 9126 return true; 9127 } 9128 return false; 9129 } 9130 9131 @Override 9132 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9133 mContext.enforceCallingOrSelfPermission( 9134 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9135 "Only package verification agents can verify applications"); 9136 9137 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9138 final PackageVerificationResponse response = new PackageVerificationResponse( 9139 verificationCode, Binder.getCallingUid()); 9140 msg.arg1 = id; 9141 msg.obj = response; 9142 mHandler.sendMessage(msg); 9143 } 9144 9145 @Override 9146 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9147 long millisecondsToDelay) { 9148 mContext.enforceCallingOrSelfPermission( 9149 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9150 "Only package verification agents can extend verification timeouts"); 9151 9152 final PackageVerificationState state = mPendingVerification.get(id); 9153 final PackageVerificationResponse response = new PackageVerificationResponse( 9154 verificationCodeAtTimeout, Binder.getCallingUid()); 9155 9156 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9157 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9158 } 9159 if (millisecondsToDelay < 0) { 9160 millisecondsToDelay = 0; 9161 } 9162 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9163 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9164 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9165 } 9166 9167 if ((state != null) && !state.timeoutExtended()) { 9168 state.extendTimeout(); 9169 9170 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9171 msg.arg1 = id; 9172 msg.obj = response; 9173 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9174 } 9175 } 9176 9177 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9178 int verificationCode, UserHandle user) { 9179 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9180 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9181 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9182 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9183 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9184 9185 mContext.sendBroadcastAsUser(intent, user, 9186 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9187 } 9188 9189 private ComponentName matchComponentForVerifier(String packageName, 9190 List<ResolveInfo> receivers) { 9191 ActivityInfo targetReceiver = null; 9192 9193 final int NR = receivers.size(); 9194 for (int i = 0; i < NR; i++) { 9195 final ResolveInfo info = receivers.get(i); 9196 if (info.activityInfo == null) { 9197 continue; 9198 } 9199 9200 if (packageName.equals(info.activityInfo.packageName)) { 9201 targetReceiver = info.activityInfo; 9202 break; 9203 } 9204 } 9205 9206 if (targetReceiver == null) { 9207 return null; 9208 } 9209 9210 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9211 } 9212 9213 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9214 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9215 if (pkgInfo.verifiers.length == 0) { 9216 return null; 9217 } 9218 9219 final int N = pkgInfo.verifiers.length; 9220 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9221 for (int i = 0; i < N; i++) { 9222 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9223 9224 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9225 receivers); 9226 if (comp == null) { 9227 continue; 9228 } 9229 9230 final int verifierUid = getUidForVerifier(verifierInfo); 9231 if (verifierUid == -1) { 9232 continue; 9233 } 9234 9235 if (DEBUG_VERIFY) { 9236 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9237 + " with the correct signature"); 9238 } 9239 sufficientVerifiers.add(comp); 9240 verificationState.addSufficientVerifier(verifierUid); 9241 } 9242 9243 return sufficientVerifiers; 9244 } 9245 9246 private int getUidForVerifier(VerifierInfo verifierInfo) { 9247 synchronized (mPackages) { 9248 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9249 if (pkg == null) { 9250 return -1; 9251 } else if (pkg.mSignatures.length != 1) { 9252 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9253 + " has more than one signature; ignoring"); 9254 return -1; 9255 } 9256 9257 /* 9258 * If the public key of the package's signature does not match 9259 * our expected public key, then this is a different package and 9260 * we should skip. 9261 */ 9262 9263 final byte[] expectedPublicKey; 9264 try { 9265 final Signature verifierSig = pkg.mSignatures[0]; 9266 final PublicKey publicKey = verifierSig.getPublicKey(); 9267 expectedPublicKey = publicKey.getEncoded(); 9268 } catch (CertificateException e) { 9269 return -1; 9270 } 9271 9272 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9273 9274 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9275 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9276 + " does not have the expected public key; ignoring"); 9277 return -1; 9278 } 9279 9280 return pkg.applicationInfo.uid; 9281 } 9282 } 9283 9284 @Override 9285 public void finishPackageInstall(int token) { 9286 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9287 9288 if (DEBUG_INSTALL) { 9289 Slog.v(TAG, "BM finishing package install for " + token); 9290 } 9291 9292 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9293 mHandler.sendMessage(msg); 9294 } 9295 9296 /** 9297 * Get the verification agent timeout. 9298 * 9299 * @return verification timeout in milliseconds 9300 */ 9301 private long getVerificationTimeout() { 9302 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9303 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9304 DEFAULT_VERIFICATION_TIMEOUT); 9305 } 9306 9307 /** 9308 * Get the default verification agent response code. 9309 * 9310 * @return default verification response code 9311 */ 9312 private int getDefaultVerificationResponse() { 9313 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9314 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9315 DEFAULT_VERIFICATION_RESPONSE); 9316 } 9317 9318 /** 9319 * Check whether or not package verification has been enabled. 9320 * 9321 * @return true if verification should be performed 9322 */ 9323 private boolean isVerificationEnabled(int userId, int installFlags) { 9324 if (!DEFAULT_VERIFY_ENABLE) { 9325 return false; 9326 } 9327 9328 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9329 9330 // Check if installing from ADB 9331 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9332 // Do not run verification in a test harness environment 9333 if (ActivityManager.isRunningInTestHarness()) { 9334 return false; 9335 } 9336 if (ensureVerifyAppsEnabled) { 9337 return true; 9338 } 9339 // Check if the developer does not want package verification for ADB installs 9340 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9341 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9342 return false; 9343 } 9344 } 9345 9346 if (ensureVerifyAppsEnabled) { 9347 return true; 9348 } 9349 9350 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9351 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9352 } 9353 9354 @Override 9355 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9356 throws RemoteException { 9357 mContext.enforceCallingOrSelfPermission( 9358 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9359 "Only intentfilter verification agents can verify applications"); 9360 9361 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9362 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9363 Binder.getCallingUid(), verificationCode, failedDomains); 9364 msg.arg1 = id; 9365 msg.obj = response; 9366 mHandler.sendMessage(msg); 9367 } 9368 9369 @Override 9370 public int getIntentVerificationStatus(String packageName, int userId) { 9371 synchronized (mPackages) { 9372 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9373 } 9374 } 9375 9376 @Override 9377 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9378 boolean result = false; 9379 synchronized (mPackages) { 9380 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9381 } 9382 if (result) { 9383 scheduleWritePackageRestrictionsLocked(userId); 9384 } 9385 return result; 9386 } 9387 9388 @Override 9389 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9390 synchronized (mPackages) { 9391 return mSettings.getIntentFilterVerificationsLPr(packageName); 9392 } 9393 } 9394 9395 @Override 9396 public List<IntentFilter> getAllIntentFilters(String packageName) { 9397 if (TextUtils.isEmpty(packageName)) { 9398 return Collections.<IntentFilter>emptyList(); 9399 } 9400 synchronized (mPackages) { 9401 PackageParser.Package pkg = mPackages.get(packageName); 9402 if (pkg == null || pkg.activities == null) { 9403 return Collections.<IntentFilter>emptyList(); 9404 } 9405 final int count = pkg.activities.size(); 9406 ArrayList<IntentFilter> result = new ArrayList<>(); 9407 for (int n=0; n<count; n++) { 9408 PackageParser.Activity activity = pkg.activities.get(n); 9409 if (activity.intents != null || activity.intents.size() > 0) { 9410 result.addAll(activity.intents); 9411 } 9412 } 9413 return result; 9414 } 9415 } 9416 9417 @Override 9418 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9419 synchronized (mPackages) { 9420 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9421 if (packageName != null) { 9422 result |= updateIntentVerificationStatus(packageName, 9423 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9424 UserHandle.myUserId()); 9425 } 9426 return result; 9427 } 9428 } 9429 9430 @Override 9431 public String getDefaultBrowserPackageName(int userId) { 9432 synchronized (mPackages) { 9433 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9434 } 9435 } 9436 9437 /** 9438 * Get the "allow unknown sources" setting. 9439 * 9440 * @return the current "allow unknown sources" setting 9441 */ 9442 private int getUnknownSourcesSettings() { 9443 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9444 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9445 -1); 9446 } 9447 9448 @Override 9449 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9450 final int uid = Binder.getCallingUid(); 9451 // writer 9452 synchronized (mPackages) { 9453 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9454 if (targetPackageSetting == null) { 9455 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9456 } 9457 9458 PackageSetting installerPackageSetting; 9459 if (installerPackageName != null) { 9460 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9461 if (installerPackageSetting == null) { 9462 throw new IllegalArgumentException("Unknown installer package: " 9463 + installerPackageName); 9464 } 9465 } else { 9466 installerPackageSetting = null; 9467 } 9468 9469 Signature[] callerSignature; 9470 Object obj = mSettings.getUserIdLPr(uid); 9471 if (obj != null) { 9472 if (obj instanceof SharedUserSetting) { 9473 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9474 } else if (obj instanceof PackageSetting) { 9475 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9476 } else { 9477 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9478 } 9479 } else { 9480 throw new SecurityException("Unknown calling uid " + uid); 9481 } 9482 9483 // Verify: can't set installerPackageName to a package that is 9484 // not signed with the same cert as the caller. 9485 if (installerPackageSetting != null) { 9486 if (compareSignatures(callerSignature, 9487 installerPackageSetting.signatures.mSignatures) 9488 != PackageManager.SIGNATURE_MATCH) { 9489 throw new SecurityException( 9490 "Caller does not have same cert as new installer package " 9491 + installerPackageName); 9492 } 9493 } 9494 9495 // Verify: if target already has an installer package, it must 9496 // be signed with the same cert as the caller. 9497 if (targetPackageSetting.installerPackageName != null) { 9498 PackageSetting setting = mSettings.mPackages.get( 9499 targetPackageSetting.installerPackageName); 9500 // If the currently set package isn't valid, then it's always 9501 // okay to change it. 9502 if (setting != null) { 9503 if (compareSignatures(callerSignature, 9504 setting.signatures.mSignatures) 9505 != PackageManager.SIGNATURE_MATCH) { 9506 throw new SecurityException( 9507 "Caller does not have same cert as old installer package " 9508 + targetPackageSetting.installerPackageName); 9509 } 9510 } 9511 } 9512 9513 // Okay! 9514 targetPackageSetting.installerPackageName = installerPackageName; 9515 scheduleWriteSettingsLocked(); 9516 } 9517 } 9518 9519 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9520 // Queue up an async operation since the package installation may take a little while. 9521 mHandler.post(new Runnable() { 9522 public void run() { 9523 mHandler.removeCallbacks(this); 9524 // Result object to be returned 9525 PackageInstalledInfo res = new PackageInstalledInfo(); 9526 res.returnCode = currentStatus; 9527 res.uid = -1; 9528 res.pkg = null; 9529 res.removedInfo = new PackageRemovedInfo(); 9530 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9531 args.doPreInstall(res.returnCode); 9532 synchronized (mInstallLock) { 9533 installPackageLI(args, res); 9534 } 9535 args.doPostInstall(res.returnCode, res.uid); 9536 } 9537 9538 // A restore should be performed at this point if (a) the install 9539 // succeeded, (b) the operation is not an update, and (c) the new 9540 // package has not opted out of backup participation. 9541 final boolean update = res.removedInfo.removedPackage != null; 9542 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9543 boolean doRestore = !update 9544 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9545 9546 // Set up the post-install work request bookkeeping. This will be used 9547 // and cleaned up by the post-install event handling regardless of whether 9548 // there's a restore pass performed. Token values are >= 1. 9549 int token; 9550 if (mNextInstallToken < 0) mNextInstallToken = 1; 9551 token = mNextInstallToken++; 9552 9553 PostInstallData data = new PostInstallData(args, res); 9554 mRunningInstalls.put(token, data); 9555 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9556 9557 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9558 // Pass responsibility to the Backup Manager. It will perform a 9559 // restore if appropriate, then pass responsibility back to the 9560 // Package Manager to run the post-install observer callbacks 9561 // and broadcasts. 9562 IBackupManager bm = IBackupManager.Stub.asInterface( 9563 ServiceManager.getService(Context.BACKUP_SERVICE)); 9564 if (bm != null) { 9565 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9566 + " to BM for possible restore"); 9567 try { 9568 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9569 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9570 } else { 9571 doRestore = false; 9572 } 9573 } catch (RemoteException e) { 9574 // can't happen; the backup manager is local 9575 } catch (Exception e) { 9576 Slog.e(TAG, "Exception trying to enqueue restore", e); 9577 doRestore = false; 9578 } 9579 } else { 9580 Slog.e(TAG, "Backup Manager not found!"); 9581 doRestore = false; 9582 } 9583 } 9584 9585 if (!doRestore) { 9586 // No restore possible, or the Backup Manager was mysteriously not 9587 // available -- just fire the post-install work request directly. 9588 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9589 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9590 mHandler.sendMessage(msg); 9591 } 9592 } 9593 }); 9594 } 9595 9596 private abstract class HandlerParams { 9597 private static final int MAX_RETRIES = 4; 9598 9599 /** 9600 * Number of times startCopy() has been attempted and had a non-fatal 9601 * error. 9602 */ 9603 private int mRetries = 0; 9604 9605 /** User handle for the user requesting the information or installation. */ 9606 private final UserHandle mUser; 9607 9608 HandlerParams(UserHandle user) { 9609 mUser = user; 9610 } 9611 9612 UserHandle getUser() { 9613 return mUser; 9614 } 9615 9616 final boolean startCopy() { 9617 boolean res; 9618 try { 9619 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9620 9621 if (++mRetries > MAX_RETRIES) { 9622 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9623 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9624 handleServiceError(); 9625 return false; 9626 } else { 9627 handleStartCopy(); 9628 res = true; 9629 } 9630 } catch (RemoteException e) { 9631 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9632 mHandler.sendEmptyMessage(MCS_RECONNECT); 9633 res = false; 9634 } 9635 handleReturnCode(); 9636 return res; 9637 } 9638 9639 final void serviceError() { 9640 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9641 handleServiceError(); 9642 handleReturnCode(); 9643 } 9644 9645 abstract void handleStartCopy() throws RemoteException; 9646 abstract void handleServiceError(); 9647 abstract void handleReturnCode(); 9648 } 9649 9650 class MeasureParams extends HandlerParams { 9651 private final PackageStats mStats; 9652 private boolean mSuccess; 9653 9654 private final IPackageStatsObserver mObserver; 9655 9656 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9657 super(new UserHandle(stats.userHandle)); 9658 mObserver = observer; 9659 mStats = stats; 9660 } 9661 9662 @Override 9663 public String toString() { 9664 return "MeasureParams{" 9665 + Integer.toHexString(System.identityHashCode(this)) 9666 + " " + mStats.packageName + "}"; 9667 } 9668 9669 @Override 9670 void handleStartCopy() throws RemoteException { 9671 synchronized (mInstallLock) { 9672 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9673 } 9674 9675 if (mSuccess) { 9676 final boolean mounted; 9677 if (Environment.isExternalStorageEmulated()) { 9678 mounted = true; 9679 } else { 9680 final String status = Environment.getExternalStorageState(); 9681 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9682 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9683 } 9684 9685 if (mounted) { 9686 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9687 9688 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9689 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9690 9691 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9692 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9693 9694 // Always subtract cache size, since it's a subdirectory 9695 mStats.externalDataSize -= mStats.externalCacheSize; 9696 9697 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9698 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9699 9700 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9701 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9702 } 9703 } 9704 } 9705 9706 @Override 9707 void handleReturnCode() { 9708 if (mObserver != null) { 9709 try { 9710 mObserver.onGetStatsCompleted(mStats, mSuccess); 9711 } catch (RemoteException e) { 9712 Slog.i(TAG, "Observer no longer exists."); 9713 } 9714 } 9715 } 9716 9717 @Override 9718 void handleServiceError() { 9719 Slog.e(TAG, "Could not measure application " + mStats.packageName 9720 + " external storage"); 9721 } 9722 } 9723 9724 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9725 throws RemoteException { 9726 long result = 0; 9727 for (File path : paths) { 9728 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9729 } 9730 return result; 9731 } 9732 9733 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9734 for (File path : paths) { 9735 try { 9736 mcs.clearDirectory(path.getAbsolutePath()); 9737 } catch (RemoteException e) { 9738 } 9739 } 9740 } 9741 9742 static class OriginInfo { 9743 /** 9744 * Location where install is coming from, before it has been 9745 * copied/renamed into place. This could be a single monolithic APK 9746 * file, or a cluster directory. This location may be untrusted. 9747 */ 9748 final File file; 9749 final String cid; 9750 9751 /** 9752 * Flag indicating that {@link #file} or {@link #cid} has already been 9753 * staged, meaning downstream users don't need to defensively copy the 9754 * contents. 9755 */ 9756 final boolean staged; 9757 9758 /** 9759 * Flag indicating that {@link #file} or {@link #cid} is an already 9760 * installed app that is being moved. 9761 */ 9762 final boolean existing; 9763 9764 final String resolvedPath; 9765 final File resolvedFile; 9766 9767 static OriginInfo fromNothing() { 9768 return new OriginInfo(null, null, false, false); 9769 } 9770 9771 static OriginInfo fromUntrustedFile(File file) { 9772 return new OriginInfo(file, null, false, false); 9773 } 9774 9775 static OriginInfo fromExistingFile(File file) { 9776 return new OriginInfo(file, null, false, true); 9777 } 9778 9779 static OriginInfo fromStagedFile(File file) { 9780 return new OriginInfo(file, null, true, false); 9781 } 9782 9783 static OriginInfo fromStagedContainer(String cid) { 9784 return new OriginInfo(null, cid, true, false); 9785 } 9786 9787 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9788 this.file = file; 9789 this.cid = cid; 9790 this.staged = staged; 9791 this.existing = existing; 9792 9793 if (cid != null) { 9794 resolvedPath = PackageHelper.getSdDir(cid); 9795 resolvedFile = new File(resolvedPath); 9796 } else if (file != null) { 9797 resolvedPath = file.getAbsolutePath(); 9798 resolvedFile = file; 9799 } else { 9800 resolvedPath = null; 9801 resolvedFile = null; 9802 } 9803 } 9804 } 9805 9806 class MoveInfo { 9807 final int moveId; 9808 final String fromUuid; 9809 final String toUuid; 9810 final String packageName; 9811 final String dataAppName; 9812 final int appId; 9813 final String seinfo; 9814 9815 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9816 String dataAppName, int appId, String seinfo) { 9817 this.moveId = moveId; 9818 this.fromUuid = fromUuid; 9819 this.toUuid = toUuid; 9820 this.packageName = packageName; 9821 this.dataAppName = dataAppName; 9822 this.appId = appId; 9823 this.seinfo = seinfo; 9824 } 9825 } 9826 9827 class InstallParams extends HandlerParams { 9828 final OriginInfo origin; 9829 final MoveInfo move; 9830 final IPackageInstallObserver2 observer; 9831 int installFlags; 9832 final String installerPackageName; 9833 final String volumeUuid; 9834 final VerificationParams verificationParams; 9835 private InstallArgs mArgs; 9836 private int mRet; 9837 final String packageAbiOverride; 9838 9839 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9840 int installFlags, String installerPackageName, String volumeUuid, 9841 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9842 super(user); 9843 this.origin = origin; 9844 this.move = move; 9845 this.observer = observer; 9846 this.installFlags = installFlags; 9847 this.installerPackageName = installerPackageName; 9848 this.volumeUuid = volumeUuid; 9849 this.verificationParams = verificationParams; 9850 this.packageAbiOverride = packageAbiOverride; 9851 } 9852 9853 @Override 9854 public String toString() { 9855 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9856 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9857 } 9858 9859 public ManifestDigest getManifestDigest() { 9860 if (verificationParams == null) { 9861 return null; 9862 } 9863 return verificationParams.getManifestDigest(); 9864 } 9865 9866 private int installLocationPolicy(PackageInfoLite pkgLite) { 9867 String packageName = pkgLite.packageName; 9868 int installLocation = pkgLite.installLocation; 9869 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9870 // reader 9871 synchronized (mPackages) { 9872 PackageParser.Package pkg = mPackages.get(packageName); 9873 if (pkg != null) { 9874 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9875 // Check for downgrading. 9876 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9877 try { 9878 checkDowngrade(pkg, pkgLite); 9879 } catch (PackageManagerException e) { 9880 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9881 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9882 } 9883 } 9884 // Check for updated system application. 9885 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9886 if (onSd) { 9887 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9888 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9889 } 9890 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9891 } else { 9892 if (onSd) { 9893 // Install flag overrides everything. 9894 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9895 } 9896 // If current upgrade specifies particular preference 9897 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9898 // Application explicitly specified internal. 9899 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9900 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9901 // App explictly prefers external. Let policy decide 9902 } else { 9903 // Prefer previous location 9904 if (isExternal(pkg)) { 9905 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9906 } 9907 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9908 } 9909 } 9910 } else { 9911 // Invalid install. Return error code 9912 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9913 } 9914 } 9915 } 9916 // All the special cases have been taken care of. 9917 // Return result based on recommended install location. 9918 if (onSd) { 9919 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9920 } 9921 return pkgLite.recommendedInstallLocation; 9922 } 9923 9924 /* 9925 * Invoke remote method to get package information and install 9926 * location values. Override install location based on default 9927 * policy if needed and then create install arguments based 9928 * on the install location. 9929 */ 9930 public void handleStartCopy() throws RemoteException { 9931 int ret = PackageManager.INSTALL_SUCCEEDED; 9932 9933 // If we're already staged, we've firmly committed to an install location 9934 if (origin.staged) { 9935 if (origin.file != null) { 9936 installFlags |= PackageManager.INSTALL_INTERNAL; 9937 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9938 } else if (origin.cid != null) { 9939 installFlags |= PackageManager.INSTALL_EXTERNAL; 9940 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9941 } else { 9942 throw new IllegalStateException("Invalid stage location"); 9943 } 9944 } 9945 9946 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9947 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9948 9949 PackageInfoLite pkgLite = null; 9950 9951 if (onInt && onSd) { 9952 // Check if both bits are set. 9953 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9954 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9955 } else { 9956 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9957 packageAbiOverride); 9958 9959 /* 9960 * If we have too little free space, try to free cache 9961 * before giving up. 9962 */ 9963 if (!origin.staged && pkgLite.recommendedInstallLocation 9964 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9965 // TODO: focus freeing disk space on the target device 9966 final StorageManager storage = StorageManager.from(mContext); 9967 final long lowThreshold = storage.getStorageLowBytes( 9968 Environment.getDataDirectory()); 9969 9970 final long sizeBytes = mContainerService.calculateInstalledSize( 9971 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9972 9973 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9974 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9975 installFlags, packageAbiOverride); 9976 } 9977 9978 /* 9979 * The cache free must have deleted the file we 9980 * downloaded to install. 9981 * 9982 * TODO: fix the "freeCache" call to not delete 9983 * the file we care about. 9984 */ 9985 if (pkgLite.recommendedInstallLocation 9986 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9987 pkgLite.recommendedInstallLocation 9988 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9989 } 9990 } 9991 } 9992 9993 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9994 int loc = pkgLite.recommendedInstallLocation; 9995 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9996 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9997 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9998 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9999 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10000 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10001 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10002 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10003 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10004 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10005 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10006 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10007 } else { 10008 // Override with defaults if needed. 10009 loc = installLocationPolicy(pkgLite); 10010 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10011 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10012 } else if (!onSd && !onInt) { 10013 // Override install location with flags 10014 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10015 // Set the flag to install on external media. 10016 installFlags |= PackageManager.INSTALL_EXTERNAL; 10017 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10018 } else { 10019 // Make sure the flag for installing on external 10020 // media is unset 10021 installFlags |= PackageManager.INSTALL_INTERNAL; 10022 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10023 } 10024 } 10025 } 10026 } 10027 10028 final InstallArgs args = createInstallArgs(this); 10029 mArgs = args; 10030 10031 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10032 /* 10033 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10034 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10035 */ 10036 int userIdentifier = getUser().getIdentifier(); 10037 if (userIdentifier == UserHandle.USER_ALL 10038 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10039 userIdentifier = UserHandle.USER_OWNER; 10040 } 10041 10042 /* 10043 * Determine if we have any installed package verifiers. If we 10044 * do, then we'll defer to them to verify the packages. 10045 */ 10046 final int requiredUid = mRequiredVerifierPackage == null ? -1 10047 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10048 if (!origin.existing && requiredUid != -1 10049 && isVerificationEnabled(userIdentifier, installFlags)) { 10050 final Intent verification = new Intent( 10051 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10052 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10053 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10054 PACKAGE_MIME_TYPE); 10055 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10056 10057 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10058 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10059 0 /* TODO: Which userId? */); 10060 10061 if (DEBUG_VERIFY) { 10062 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10063 + verification.toString() + " with " + pkgLite.verifiers.length 10064 + " optional verifiers"); 10065 } 10066 10067 final int verificationId = mPendingVerificationToken++; 10068 10069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10070 10071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10072 installerPackageName); 10073 10074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10075 installFlags); 10076 10077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10078 pkgLite.packageName); 10079 10080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10081 pkgLite.versionCode); 10082 10083 if (verificationParams != null) { 10084 if (verificationParams.getVerificationURI() != null) { 10085 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10086 verificationParams.getVerificationURI()); 10087 } 10088 if (verificationParams.getOriginatingURI() != null) { 10089 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10090 verificationParams.getOriginatingURI()); 10091 } 10092 if (verificationParams.getReferrer() != null) { 10093 verification.putExtra(Intent.EXTRA_REFERRER, 10094 verificationParams.getReferrer()); 10095 } 10096 if (verificationParams.getOriginatingUid() >= 0) { 10097 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10098 verificationParams.getOriginatingUid()); 10099 } 10100 if (verificationParams.getInstallerUid() >= 0) { 10101 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10102 verificationParams.getInstallerUid()); 10103 } 10104 } 10105 10106 final PackageVerificationState verificationState = new PackageVerificationState( 10107 requiredUid, args); 10108 10109 mPendingVerification.append(verificationId, verificationState); 10110 10111 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10112 receivers, verificationState); 10113 10114 /* 10115 * If any sufficient verifiers were listed in the package 10116 * manifest, attempt to ask them. 10117 */ 10118 if (sufficientVerifiers != null) { 10119 final int N = sufficientVerifiers.size(); 10120 if (N == 0) { 10121 Slog.i(TAG, "Additional verifiers required, but none installed."); 10122 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10123 } else { 10124 for (int i = 0; i < N; i++) { 10125 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10126 10127 final Intent sufficientIntent = new Intent(verification); 10128 sufficientIntent.setComponent(verifierComponent); 10129 10130 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10131 } 10132 } 10133 } 10134 10135 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10136 mRequiredVerifierPackage, receivers); 10137 if (ret == PackageManager.INSTALL_SUCCEEDED 10138 && mRequiredVerifierPackage != null) { 10139 /* 10140 * Send the intent to the required verification agent, 10141 * but only start the verification timeout after the 10142 * target BroadcastReceivers have run. 10143 */ 10144 verification.setComponent(requiredVerifierComponent); 10145 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10146 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10147 new BroadcastReceiver() { 10148 @Override 10149 public void onReceive(Context context, Intent intent) { 10150 final Message msg = mHandler 10151 .obtainMessage(CHECK_PENDING_VERIFICATION); 10152 msg.arg1 = verificationId; 10153 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10154 } 10155 }, null, 0, null, null); 10156 10157 /* 10158 * We don't want the copy to proceed until verification 10159 * succeeds, so null out this field. 10160 */ 10161 mArgs = null; 10162 } 10163 } else { 10164 /* 10165 * No package verification is enabled, so immediately start 10166 * the remote call to initiate copy using temporary file. 10167 */ 10168 ret = args.copyApk(mContainerService, true); 10169 } 10170 } 10171 10172 mRet = ret; 10173 } 10174 10175 @Override 10176 void handleReturnCode() { 10177 // If mArgs is null, then MCS couldn't be reached. When it 10178 // reconnects, it will try again to install. At that point, this 10179 // will succeed. 10180 if (mArgs != null) { 10181 processPendingInstall(mArgs, mRet); 10182 } 10183 } 10184 10185 @Override 10186 void handleServiceError() { 10187 mArgs = createInstallArgs(this); 10188 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10189 } 10190 10191 public boolean isForwardLocked() { 10192 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10193 } 10194 } 10195 10196 /** 10197 * Used during creation of InstallArgs 10198 * 10199 * @param installFlags package installation flags 10200 * @return true if should be installed on external storage 10201 */ 10202 private static boolean installOnExternalAsec(int installFlags) { 10203 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10204 return false; 10205 } 10206 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10207 return true; 10208 } 10209 return false; 10210 } 10211 10212 /** 10213 * Used during creation of InstallArgs 10214 * 10215 * @param installFlags package installation flags 10216 * @return true if should be installed as forward locked 10217 */ 10218 private static boolean installForwardLocked(int installFlags) { 10219 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10220 } 10221 10222 private InstallArgs createInstallArgs(InstallParams params) { 10223 if (params.move != null) { 10224 return new MoveInstallArgs(params); 10225 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10226 return new AsecInstallArgs(params); 10227 } else { 10228 return new FileInstallArgs(params); 10229 } 10230 } 10231 10232 /** 10233 * Create args that describe an existing installed package. Typically used 10234 * when cleaning up old installs, or used as a move source. 10235 */ 10236 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10237 String resourcePath, String[] instructionSets) { 10238 final boolean isInAsec; 10239 if (installOnExternalAsec(installFlags)) { 10240 /* Apps on SD card are always in ASEC containers. */ 10241 isInAsec = true; 10242 } else if (installForwardLocked(installFlags) 10243 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10244 /* 10245 * Forward-locked apps are only in ASEC containers if they're the 10246 * new style 10247 */ 10248 isInAsec = true; 10249 } else { 10250 isInAsec = false; 10251 } 10252 10253 if (isInAsec) { 10254 return new AsecInstallArgs(codePath, instructionSets, 10255 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10256 } else { 10257 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10258 } 10259 } 10260 10261 static abstract class InstallArgs { 10262 /** @see InstallParams#origin */ 10263 final OriginInfo origin; 10264 /** @see InstallParams#move */ 10265 final MoveInfo move; 10266 10267 final IPackageInstallObserver2 observer; 10268 // Always refers to PackageManager flags only 10269 final int installFlags; 10270 final String installerPackageName; 10271 final String volumeUuid; 10272 final ManifestDigest manifestDigest; 10273 final UserHandle user; 10274 final String abiOverride; 10275 10276 // The list of instruction sets supported by this app. This is currently 10277 // only used during the rmdex() phase to clean up resources. We can get rid of this 10278 // if we move dex files under the common app path. 10279 /* nullable */ String[] instructionSets; 10280 10281 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10282 int installFlags, String installerPackageName, String volumeUuid, 10283 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10284 String abiOverride) { 10285 this.origin = origin; 10286 this.move = move; 10287 this.installFlags = installFlags; 10288 this.observer = observer; 10289 this.installerPackageName = installerPackageName; 10290 this.volumeUuid = volumeUuid; 10291 this.manifestDigest = manifestDigest; 10292 this.user = user; 10293 this.instructionSets = instructionSets; 10294 this.abiOverride = abiOverride; 10295 } 10296 10297 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10298 abstract int doPreInstall(int status); 10299 10300 /** 10301 * Rename package into final resting place. All paths on the given 10302 * scanned package should be updated to reflect the rename. 10303 */ 10304 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10305 abstract int doPostInstall(int status, int uid); 10306 10307 /** @see PackageSettingBase#codePathString */ 10308 abstract String getCodePath(); 10309 /** @see PackageSettingBase#resourcePathString */ 10310 abstract String getResourcePath(); 10311 10312 // Need installer lock especially for dex file removal. 10313 abstract void cleanUpResourcesLI(); 10314 abstract boolean doPostDeleteLI(boolean delete); 10315 10316 /** 10317 * Called before the source arguments are copied. This is used mostly 10318 * for MoveParams when it needs to read the source file to put it in the 10319 * destination. 10320 */ 10321 int doPreCopy() { 10322 return PackageManager.INSTALL_SUCCEEDED; 10323 } 10324 10325 /** 10326 * Called after the source arguments are copied. This is used mostly for 10327 * MoveParams when it needs to read the source file to put it in the 10328 * destination. 10329 * 10330 * @return 10331 */ 10332 int doPostCopy(int uid) { 10333 return PackageManager.INSTALL_SUCCEEDED; 10334 } 10335 10336 protected boolean isFwdLocked() { 10337 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10338 } 10339 10340 protected boolean isExternalAsec() { 10341 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10342 } 10343 10344 UserHandle getUser() { 10345 return user; 10346 } 10347 } 10348 10349 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10350 if (!allCodePaths.isEmpty()) { 10351 if (instructionSets == null) { 10352 throw new IllegalStateException("instructionSet == null"); 10353 } 10354 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10355 for (String codePath : allCodePaths) { 10356 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10357 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10358 if (retCode < 0) { 10359 Slog.w(TAG, "Couldn't remove dex file for package: " 10360 + " at location " + codePath + ", retcode=" + retCode); 10361 // we don't consider this to be a failure of the core package deletion 10362 } 10363 } 10364 } 10365 } 10366 } 10367 10368 /** 10369 * Logic to handle installation of non-ASEC applications, including copying 10370 * and renaming logic. 10371 */ 10372 class FileInstallArgs extends InstallArgs { 10373 private File codeFile; 10374 private File resourceFile; 10375 10376 // Example topology: 10377 // /data/app/com.example/base.apk 10378 // /data/app/com.example/split_foo.apk 10379 // /data/app/com.example/lib/arm/libfoo.so 10380 // /data/app/com.example/lib/arm64/libfoo.so 10381 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10382 10383 /** New install */ 10384 FileInstallArgs(InstallParams params) { 10385 super(params.origin, params.move, params.observer, params.installFlags, 10386 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10387 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10388 if (isFwdLocked()) { 10389 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10390 } 10391 } 10392 10393 /** Existing install */ 10394 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10395 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10396 null); 10397 this.codeFile = (codePath != null) ? new File(codePath) : null; 10398 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10399 } 10400 10401 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10402 if (origin.staged) { 10403 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10404 codeFile = origin.file; 10405 resourceFile = origin.file; 10406 return PackageManager.INSTALL_SUCCEEDED; 10407 } 10408 10409 try { 10410 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10411 codeFile = tempDir; 10412 resourceFile = tempDir; 10413 } catch (IOException e) { 10414 Slog.w(TAG, "Failed to create copy file: " + e); 10415 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10416 } 10417 10418 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10419 @Override 10420 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10421 if (!FileUtils.isValidExtFilename(name)) { 10422 throw new IllegalArgumentException("Invalid filename: " + name); 10423 } 10424 try { 10425 final File file = new File(codeFile, name); 10426 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10427 O_RDWR | O_CREAT, 0644); 10428 Os.chmod(file.getAbsolutePath(), 0644); 10429 return new ParcelFileDescriptor(fd); 10430 } catch (ErrnoException e) { 10431 throw new RemoteException("Failed to open: " + e.getMessage()); 10432 } 10433 } 10434 }; 10435 10436 int ret = PackageManager.INSTALL_SUCCEEDED; 10437 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10438 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10439 Slog.e(TAG, "Failed to copy package"); 10440 return ret; 10441 } 10442 10443 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10444 NativeLibraryHelper.Handle handle = null; 10445 try { 10446 handle = NativeLibraryHelper.Handle.create(codeFile); 10447 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10448 abiOverride); 10449 } catch (IOException e) { 10450 Slog.e(TAG, "Copying native libraries failed", e); 10451 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10452 } finally { 10453 IoUtils.closeQuietly(handle); 10454 } 10455 10456 return ret; 10457 } 10458 10459 int doPreInstall(int status) { 10460 if (status != PackageManager.INSTALL_SUCCEEDED) { 10461 cleanUp(); 10462 } 10463 return status; 10464 } 10465 10466 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10467 if (status != PackageManager.INSTALL_SUCCEEDED) { 10468 cleanUp(); 10469 return false; 10470 } 10471 10472 final File targetDir = codeFile.getParentFile(); 10473 final File beforeCodeFile = codeFile; 10474 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10475 10476 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10477 try { 10478 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10479 } catch (ErrnoException e) { 10480 Slog.w(TAG, "Failed to rename", e); 10481 return false; 10482 } 10483 10484 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10485 Slog.w(TAG, "Failed to restorecon"); 10486 return false; 10487 } 10488 10489 // Reflect the rename internally 10490 codeFile = afterCodeFile; 10491 resourceFile = afterCodeFile; 10492 10493 // Reflect the rename in scanned details 10494 pkg.codePath = afterCodeFile.getAbsolutePath(); 10495 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10496 pkg.baseCodePath); 10497 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10498 pkg.splitCodePaths); 10499 10500 // Reflect the rename in app info 10501 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10502 pkg.applicationInfo.setCodePath(pkg.codePath); 10503 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10504 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10505 pkg.applicationInfo.setResourcePath(pkg.codePath); 10506 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10507 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10508 10509 return true; 10510 } 10511 10512 int doPostInstall(int status, int uid) { 10513 if (status != PackageManager.INSTALL_SUCCEEDED) { 10514 cleanUp(); 10515 } 10516 return status; 10517 } 10518 10519 @Override 10520 String getCodePath() { 10521 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10522 } 10523 10524 @Override 10525 String getResourcePath() { 10526 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10527 } 10528 10529 private boolean cleanUp() { 10530 if (codeFile == null || !codeFile.exists()) { 10531 return false; 10532 } 10533 10534 if (codeFile.isDirectory()) { 10535 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10536 } else { 10537 codeFile.delete(); 10538 } 10539 10540 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10541 resourceFile.delete(); 10542 } 10543 10544 return true; 10545 } 10546 10547 void cleanUpResourcesLI() { 10548 // Try enumerating all code paths before deleting 10549 List<String> allCodePaths = Collections.EMPTY_LIST; 10550 if (codeFile != null && codeFile.exists()) { 10551 try { 10552 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10553 allCodePaths = pkg.getAllCodePaths(); 10554 } catch (PackageParserException e) { 10555 // Ignored; we tried our best 10556 } 10557 } 10558 10559 cleanUp(); 10560 removeDexFiles(allCodePaths, instructionSets); 10561 } 10562 10563 boolean doPostDeleteLI(boolean delete) { 10564 // XXX err, shouldn't we respect the delete flag? 10565 cleanUpResourcesLI(); 10566 return true; 10567 } 10568 } 10569 10570 private boolean isAsecExternal(String cid) { 10571 final String asecPath = PackageHelper.getSdFilesystem(cid); 10572 return !asecPath.startsWith(mAsecInternalPath); 10573 } 10574 10575 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10576 PackageManagerException { 10577 if (copyRet < 0) { 10578 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10579 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10580 throw new PackageManagerException(copyRet, message); 10581 } 10582 } 10583 } 10584 10585 /** 10586 * Extract the MountService "container ID" from the full code path of an 10587 * .apk. 10588 */ 10589 static String cidFromCodePath(String fullCodePath) { 10590 int eidx = fullCodePath.lastIndexOf("/"); 10591 String subStr1 = fullCodePath.substring(0, eidx); 10592 int sidx = subStr1.lastIndexOf("/"); 10593 return subStr1.substring(sidx+1, eidx); 10594 } 10595 10596 /** 10597 * Logic to handle installation of ASEC applications, including copying and 10598 * renaming logic. 10599 */ 10600 class AsecInstallArgs extends InstallArgs { 10601 static final String RES_FILE_NAME = "pkg.apk"; 10602 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10603 10604 String cid; 10605 String packagePath; 10606 String resourcePath; 10607 10608 /** New install */ 10609 AsecInstallArgs(InstallParams params) { 10610 super(params.origin, params.move, params.observer, params.installFlags, 10611 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10612 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10613 } 10614 10615 /** Existing install */ 10616 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10617 boolean isExternal, boolean isForwardLocked) { 10618 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10619 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10620 instructionSets, null); 10621 // Hackily pretend we're still looking at a full code path 10622 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10623 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10624 } 10625 10626 // Extract cid from fullCodePath 10627 int eidx = fullCodePath.lastIndexOf("/"); 10628 String subStr1 = fullCodePath.substring(0, eidx); 10629 int sidx = subStr1.lastIndexOf("/"); 10630 cid = subStr1.substring(sidx+1, eidx); 10631 setMountPath(subStr1); 10632 } 10633 10634 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10635 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10636 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10637 instructionSets, null); 10638 this.cid = cid; 10639 setMountPath(PackageHelper.getSdDir(cid)); 10640 } 10641 10642 void createCopyFile() { 10643 cid = mInstallerService.allocateExternalStageCidLegacy(); 10644 } 10645 10646 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10647 if (origin.staged) { 10648 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10649 cid = origin.cid; 10650 setMountPath(PackageHelper.getSdDir(cid)); 10651 return PackageManager.INSTALL_SUCCEEDED; 10652 } 10653 10654 if (temp) { 10655 createCopyFile(); 10656 } else { 10657 /* 10658 * Pre-emptively destroy the container since it's destroyed if 10659 * copying fails due to it existing anyway. 10660 */ 10661 PackageHelper.destroySdDir(cid); 10662 } 10663 10664 final String newMountPath = imcs.copyPackageToContainer( 10665 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10666 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10667 10668 if (newMountPath != null) { 10669 setMountPath(newMountPath); 10670 return PackageManager.INSTALL_SUCCEEDED; 10671 } else { 10672 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10673 } 10674 } 10675 10676 @Override 10677 String getCodePath() { 10678 return packagePath; 10679 } 10680 10681 @Override 10682 String getResourcePath() { 10683 return resourcePath; 10684 } 10685 10686 int doPreInstall(int status) { 10687 if (status != PackageManager.INSTALL_SUCCEEDED) { 10688 // Destroy container 10689 PackageHelper.destroySdDir(cid); 10690 } else { 10691 boolean mounted = PackageHelper.isContainerMounted(cid); 10692 if (!mounted) { 10693 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10694 Process.SYSTEM_UID); 10695 if (newMountPath != null) { 10696 setMountPath(newMountPath); 10697 } else { 10698 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10699 } 10700 } 10701 } 10702 return status; 10703 } 10704 10705 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10706 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10707 String newMountPath = null; 10708 if (PackageHelper.isContainerMounted(cid)) { 10709 // Unmount the container 10710 if (!PackageHelper.unMountSdDir(cid)) { 10711 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10712 return false; 10713 } 10714 } 10715 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10716 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10717 " which might be stale. Will try to clean up."); 10718 // Clean up the stale container and proceed to recreate. 10719 if (!PackageHelper.destroySdDir(newCacheId)) { 10720 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10721 return false; 10722 } 10723 // Successfully cleaned up stale container. Try to rename again. 10724 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10725 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10726 + " inspite of cleaning it up."); 10727 return false; 10728 } 10729 } 10730 if (!PackageHelper.isContainerMounted(newCacheId)) { 10731 Slog.w(TAG, "Mounting container " + newCacheId); 10732 newMountPath = PackageHelper.mountSdDir(newCacheId, 10733 getEncryptKey(), Process.SYSTEM_UID); 10734 } else { 10735 newMountPath = PackageHelper.getSdDir(newCacheId); 10736 } 10737 if (newMountPath == null) { 10738 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10739 return false; 10740 } 10741 Log.i(TAG, "Succesfully renamed " + cid + 10742 " to " + newCacheId + 10743 " at new path: " + newMountPath); 10744 cid = newCacheId; 10745 10746 final File beforeCodeFile = new File(packagePath); 10747 setMountPath(newMountPath); 10748 final File afterCodeFile = new File(packagePath); 10749 10750 // Reflect the rename in scanned details 10751 pkg.codePath = afterCodeFile.getAbsolutePath(); 10752 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10753 pkg.baseCodePath); 10754 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10755 pkg.splitCodePaths); 10756 10757 // Reflect the rename in app info 10758 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10759 pkg.applicationInfo.setCodePath(pkg.codePath); 10760 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10761 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10762 pkg.applicationInfo.setResourcePath(pkg.codePath); 10763 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10764 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10765 10766 return true; 10767 } 10768 10769 private void setMountPath(String mountPath) { 10770 final File mountFile = new File(mountPath); 10771 10772 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10773 if (monolithicFile.exists()) { 10774 packagePath = monolithicFile.getAbsolutePath(); 10775 if (isFwdLocked()) { 10776 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10777 } else { 10778 resourcePath = packagePath; 10779 } 10780 } else { 10781 packagePath = mountFile.getAbsolutePath(); 10782 resourcePath = packagePath; 10783 } 10784 } 10785 10786 int doPostInstall(int status, int uid) { 10787 if (status != PackageManager.INSTALL_SUCCEEDED) { 10788 cleanUp(); 10789 } else { 10790 final int groupOwner; 10791 final String protectedFile; 10792 if (isFwdLocked()) { 10793 groupOwner = UserHandle.getSharedAppGid(uid); 10794 protectedFile = RES_FILE_NAME; 10795 } else { 10796 groupOwner = -1; 10797 protectedFile = null; 10798 } 10799 10800 if (uid < Process.FIRST_APPLICATION_UID 10801 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10802 Slog.e(TAG, "Failed to finalize " + cid); 10803 PackageHelper.destroySdDir(cid); 10804 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10805 } 10806 10807 boolean mounted = PackageHelper.isContainerMounted(cid); 10808 if (!mounted) { 10809 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10810 } 10811 } 10812 return status; 10813 } 10814 10815 private void cleanUp() { 10816 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10817 10818 // Destroy secure container 10819 PackageHelper.destroySdDir(cid); 10820 } 10821 10822 private List<String> getAllCodePaths() { 10823 final File codeFile = new File(getCodePath()); 10824 if (codeFile != null && codeFile.exists()) { 10825 try { 10826 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10827 return pkg.getAllCodePaths(); 10828 } catch (PackageParserException e) { 10829 // Ignored; we tried our best 10830 } 10831 } 10832 return Collections.EMPTY_LIST; 10833 } 10834 10835 void cleanUpResourcesLI() { 10836 // Enumerate all code paths before deleting 10837 cleanUpResourcesLI(getAllCodePaths()); 10838 } 10839 10840 private void cleanUpResourcesLI(List<String> allCodePaths) { 10841 cleanUp(); 10842 removeDexFiles(allCodePaths, instructionSets); 10843 } 10844 10845 String getPackageName() { 10846 return getAsecPackageName(cid); 10847 } 10848 10849 boolean doPostDeleteLI(boolean delete) { 10850 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10851 final List<String> allCodePaths = getAllCodePaths(); 10852 boolean mounted = PackageHelper.isContainerMounted(cid); 10853 if (mounted) { 10854 // Unmount first 10855 if (PackageHelper.unMountSdDir(cid)) { 10856 mounted = false; 10857 } 10858 } 10859 if (!mounted && delete) { 10860 cleanUpResourcesLI(allCodePaths); 10861 } 10862 return !mounted; 10863 } 10864 10865 @Override 10866 int doPreCopy() { 10867 if (isFwdLocked()) { 10868 if (!PackageHelper.fixSdPermissions(cid, 10869 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10870 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10871 } 10872 } 10873 10874 return PackageManager.INSTALL_SUCCEEDED; 10875 } 10876 10877 @Override 10878 int doPostCopy(int uid) { 10879 if (isFwdLocked()) { 10880 if (uid < Process.FIRST_APPLICATION_UID 10881 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10882 RES_FILE_NAME)) { 10883 Slog.e(TAG, "Failed to finalize " + cid); 10884 PackageHelper.destroySdDir(cid); 10885 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10886 } 10887 } 10888 10889 return PackageManager.INSTALL_SUCCEEDED; 10890 } 10891 } 10892 10893 /** 10894 * Logic to handle movement of existing installed applications. 10895 */ 10896 class MoveInstallArgs extends InstallArgs { 10897 private File codeFile; 10898 private File resourceFile; 10899 10900 /** New install */ 10901 MoveInstallArgs(InstallParams params) { 10902 super(params.origin, params.move, params.observer, params.installFlags, 10903 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10904 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10905 } 10906 10907 int copyApk(IMediaContainerService imcs, boolean temp) { 10908 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10909 + move.fromUuid + " to " + move.toUuid); 10910 synchronized (mInstaller) { 10911 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10912 move.dataAppName, move.appId, move.seinfo) != 0) { 10913 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10914 } 10915 } 10916 10917 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10918 resourceFile = codeFile; 10919 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10920 10921 return PackageManager.INSTALL_SUCCEEDED; 10922 } 10923 10924 int doPreInstall(int status) { 10925 if (status != PackageManager.INSTALL_SUCCEEDED) { 10926 cleanUp(); 10927 } 10928 return status; 10929 } 10930 10931 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10932 if (status != PackageManager.INSTALL_SUCCEEDED) { 10933 cleanUp(); 10934 return false; 10935 } 10936 10937 // Reflect the move in app info 10938 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10939 pkg.applicationInfo.setCodePath(pkg.codePath); 10940 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10941 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10942 pkg.applicationInfo.setResourcePath(pkg.codePath); 10943 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10944 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10945 10946 return true; 10947 } 10948 10949 int doPostInstall(int status, int uid) { 10950 if (status != PackageManager.INSTALL_SUCCEEDED) { 10951 cleanUp(); 10952 } 10953 return status; 10954 } 10955 10956 @Override 10957 String getCodePath() { 10958 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10959 } 10960 10961 @Override 10962 String getResourcePath() { 10963 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10964 } 10965 10966 private boolean cleanUp() { 10967 if (codeFile == null || !codeFile.exists()) { 10968 return false; 10969 } 10970 10971 if (codeFile.isDirectory()) { 10972 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10973 } else { 10974 codeFile.delete(); 10975 } 10976 10977 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10978 resourceFile.delete(); 10979 } 10980 10981 return true; 10982 } 10983 10984 void cleanUpResourcesLI() { 10985 cleanUp(); 10986 } 10987 10988 boolean doPostDeleteLI(boolean delete) { 10989 // XXX err, shouldn't we respect the delete flag? 10990 cleanUpResourcesLI(); 10991 return true; 10992 } 10993 } 10994 10995 static String getAsecPackageName(String packageCid) { 10996 int idx = packageCid.lastIndexOf("-"); 10997 if (idx == -1) { 10998 return packageCid; 10999 } 11000 return packageCid.substring(0, idx); 11001 } 11002 11003 // Utility method used to create code paths based on package name and available index. 11004 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11005 String idxStr = ""; 11006 int idx = 1; 11007 // Fall back to default value of idx=1 if prefix is not 11008 // part of oldCodePath 11009 if (oldCodePath != null) { 11010 String subStr = oldCodePath; 11011 // Drop the suffix right away 11012 if (suffix != null && subStr.endsWith(suffix)) { 11013 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11014 } 11015 // If oldCodePath already contains prefix find out the 11016 // ending index to either increment or decrement. 11017 int sidx = subStr.lastIndexOf(prefix); 11018 if (sidx != -1) { 11019 subStr = subStr.substring(sidx + prefix.length()); 11020 if (subStr != null) { 11021 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11022 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11023 } 11024 try { 11025 idx = Integer.parseInt(subStr); 11026 if (idx <= 1) { 11027 idx++; 11028 } else { 11029 idx--; 11030 } 11031 } catch(NumberFormatException e) { 11032 } 11033 } 11034 } 11035 } 11036 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11037 return prefix + idxStr; 11038 } 11039 11040 private File getNextCodePath(File targetDir, String packageName) { 11041 int suffix = 1; 11042 File result; 11043 do { 11044 result = new File(targetDir, packageName + "-" + suffix); 11045 suffix++; 11046 } while (result.exists()); 11047 return result; 11048 } 11049 11050 // Utility method that returns the relative package path with respect 11051 // to the installation directory. Like say for /data/data/com.test-1.apk 11052 // string com.test-1 is returned. 11053 static String deriveCodePathName(String codePath) { 11054 if (codePath == null) { 11055 return null; 11056 } 11057 final File codeFile = new File(codePath); 11058 final String name = codeFile.getName(); 11059 if (codeFile.isDirectory()) { 11060 return name; 11061 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11062 final int lastDot = name.lastIndexOf('.'); 11063 return name.substring(0, lastDot); 11064 } else { 11065 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11066 return null; 11067 } 11068 } 11069 11070 class PackageInstalledInfo { 11071 String name; 11072 int uid; 11073 // The set of users that originally had this package installed. 11074 int[] origUsers; 11075 // The set of users that now have this package installed. 11076 int[] newUsers; 11077 PackageParser.Package pkg; 11078 int returnCode; 11079 String returnMsg; 11080 PackageRemovedInfo removedInfo; 11081 11082 public void setError(int code, String msg) { 11083 returnCode = code; 11084 returnMsg = msg; 11085 Slog.w(TAG, msg); 11086 } 11087 11088 public void setError(String msg, PackageParserException e) { 11089 returnCode = e.error; 11090 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11091 Slog.w(TAG, msg, e); 11092 } 11093 11094 public void setError(String msg, PackageManagerException e) { 11095 returnCode = e.error; 11096 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11097 Slog.w(TAG, msg, e); 11098 } 11099 11100 // In some error cases we want to convey more info back to the observer 11101 String origPackage; 11102 String origPermission; 11103 } 11104 11105 /* 11106 * Install a non-existing package. 11107 */ 11108 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11109 UserHandle user, String installerPackageName, String volumeUuid, 11110 PackageInstalledInfo res) { 11111 // Remember this for later, in case we need to rollback this install 11112 String pkgName = pkg.packageName; 11113 11114 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11115 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11116 UserHandle.USER_OWNER).exists(); 11117 synchronized(mPackages) { 11118 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11119 // A package with the same name is already installed, though 11120 // it has been renamed to an older name. The package we 11121 // are trying to install should be installed as an update to 11122 // the existing one, but that has not been requested, so bail. 11123 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11124 + " without first uninstalling package running as " 11125 + mSettings.mRenamedPackages.get(pkgName)); 11126 return; 11127 } 11128 if (mPackages.containsKey(pkgName)) { 11129 // Don't allow installation over an existing package with the same name. 11130 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11131 + " without first uninstalling."); 11132 return; 11133 } 11134 } 11135 11136 try { 11137 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11138 System.currentTimeMillis(), user); 11139 11140 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11141 // delete the partially installed application. the data directory will have to be 11142 // restored if it was already existing 11143 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11144 // remove package from internal structures. Note that we want deletePackageX to 11145 // delete the package data and cache directories that it created in 11146 // scanPackageLocked, unless those directories existed before we even tried to 11147 // install. 11148 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11149 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11150 res.removedInfo, true); 11151 } 11152 11153 } catch (PackageManagerException e) { 11154 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11155 } 11156 } 11157 11158 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11159 // Can't rotate keys during boot or if sharedUser. 11160 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11161 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11162 return false; 11163 } 11164 // app is using upgradeKeySets; make sure all are valid 11165 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11166 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11167 for (int i = 0; i < upgradeKeySets.length; i++) { 11168 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11169 Slog.wtf(TAG, "Package " 11170 + (oldPs.name != null ? oldPs.name : "<null>") 11171 + " contains upgrade-key-set reference to unknown key-set: " 11172 + upgradeKeySets[i] 11173 + " reverting to signatures check."); 11174 return false; 11175 } 11176 } 11177 return true; 11178 } 11179 11180 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11181 // Upgrade keysets are being used. Determine if new package has a superset of the 11182 // required keys. 11183 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11184 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11185 for (int i = 0; i < upgradeKeySets.length; i++) { 11186 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11187 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11188 return true; 11189 } 11190 } 11191 return false; 11192 } 11193 11194 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11195 UserHandle user, String installerPackageName, String volumeUuid, 11196 PackageInstalledInfo res) { 11197 final PackageParser.Package oldPackage; 11198 final String pkgName = pkg.packageName; 11199 final int[] allUsers; 11200 final boolean[] perUserInstalled; 11201 final boolean weFroze; 11202 11203 // First find the old package info and check signatures 11204 synchronized(mPackages) { 11205 oldPackage = mPackages.get(pkgName); 11206 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11207 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11208 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11209 if(!checkUpgradeKeySetLP(ps, pkg)) { 11210 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11211 "New package not signed by keys specified by upgrade-keysets: " 11212 + pkgName); 11213 return; 11214 } 11215 } else { 11216 // default to original signature matching 11217 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11218 != PackageManager.SIGNATURE_MATCH) { 11219 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11220 "New package has a different signature: " + pkgName); 11221 return; 11222 } 11223 } 11224 11225 // In case of rollback, remember per-user/profile install state 11226 allUsers = sUserManager.getUserIds(); 11227 perUserInstalled = new boolean[allUsers.length]; 11228 for (int i = 0; i < allUsers.length; i++) { 11229 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11230 } 11231 11232 // Mark the app as frozen to prevent launching during the upgrade 11233 // process, and then kill all running instances 11234 if (!ps.frozen) { 11235 ps.frozen = true; 11236 weFroze = true; 11237 } else { 11238 weFroze = false; 11239 } 11240 } 11241 11242 // Now that we're guarded by frozen state, kill app during upgrade 11243 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11244 11245 try { 11246 boolean sysPkg = (isSystemApp(oldPackage)); 11247 if (sysPkg) { 11248 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11249 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11250 } else { 11251 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11252 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11253 } 11254 } finally { 11255 // Regardless of success or failure of upgrade steps above, always 11256 // unfreeze the package if we froze it 11257 if (weFroze) { 11258 unfreezePackage(pkgName); 11259 } 11260 } 11261 } 11262 11263 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11264 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11265 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11266 String volumeUuid, PackageInstalledInfo res) { 11267 String pkgName = deletedPackage.packageName; 11268 boolean deletedPkg = true; 11269 boolean updatedSettings = false; 11270 11271 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11272 + deletedPackage); 11273 long origUpdateTime; 11274 if (pkg.mExtras != null) { 11275 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11276 } else { 11277 origUpdateTime = 0; 11278 } 11279 11280 // First delete the existing package while retaining the data directory 11281 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11282 res.removedInfo, true)) { 11283 // If the existing package wasn't successfully deleted 11284 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11285 deletedPkg = false; 11286 } else { 11287 // Successfully deleted the old package; proceed with replace. 11288 11289 // If deleted package lived in a container, give users a chance to 11290 // relinquish resources before killing. 11291 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11292 if (DEBUG_INSTALL) { 11293 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11294 } 11295 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11296 final ArrayList<String> pkgList = new ArrayList<String>(1); 11297 pkgList.add(deletedPackage.applicationInfo.packageName); 11298 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11299 } 11300 11301 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11302 try { 11303 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11304 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11305 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11306 perUserInstalled, res, user); 11307 updatedSettings = true; 11308 } catch (PackageManagerException e) { 11309 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11310 } 11311 } 11312 11313 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11314 // remove package from internal structures. Note that we want deletePackageX to 11315 // delete the package data and cache directories that it created in 11316 // scanPackageLocked, unless those directories existed before we even tried to 11317 // install. 11318 if(updatedSettings) { 11319 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11320 deletePackageLI( 11321 pkgName, null, true, allUsers, perUserInstalled, 11322 PackageManager.DELETE_KEEP_DATA, 11323 res.removedInfo, true); 11324 } 11325 // Since we failed to install the new package we need to restore the old 11326 // package that we deleted. 11327 if (deletedPkg) { 11328 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11329 File restoreFile = new File(deletedPackage.codePath); 11330 // Parse old package 11331 boolean oldExternal = isExternal(deletedPackage); 11332 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11333 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11334 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11335 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11336 try { 11337 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11338 } catch (PackageManagerException e) { 11339 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11340 + e.getMessage()); 11341 return; 11342 } 11343 // Restore of old package succeeded. Update permissions. 11344 // writer 11345 synchronized (mPackages) { 11346 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11347 UPDATE_PERMISSIONS_ALL); 11348 // can downgrade to reader 11349 mSettings.writeLPr(); 11350 } 11351 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11352 } 11353 } 11354 } 11355 11356 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11357 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11358 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11359 String volumeUuid, PackageInstalledInfo res) { 11360 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11361 + ", old=" + deletedPackage); 11362 boolean disabledSystem = false; 11363 boolean updatedSettings = false; 11364 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11365 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11366 != 0) { 11367 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11368 } 11369 String packageName = deletedPackage.packageName; 11370 if (packageName == null) { 11371 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11372 "Attempt to delete null packageName."); 11373 return; 11374 } 11375 PackageParser.Package oldPkg; 11376 PackageSetting oldPkgSetting; 11377 // reader 11378 synchronized (mPackages) { 11379 oldPkg = mPackages.get(packageName); 11380 oldPkgSetting = mSettings.mPackages.get(packageName); 11381 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11382 (oldPkgSetting == null)) { 11383 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11384 "Couldn't find package:" + packageName + " information"); 11385 return; 11386 } 11387 } 11388 11389 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11390 res.removedInfo.removedPackage = packageName; 11391 // Remove existing system package 11392 removePackageLI(oldPkgSetting, true); 11393 // writer 11394 synchronized (mPackages) { 11395 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11396 if (!disabledSystem && deletedPackage != null) { 11397 // We didn't need to disable the .apk as a current system package, 11398 // which means we are replacing another update that is already 11399 // installed. We need to make sure to delete the older one's .apk. 11400 res.removedInfo.args = createInstallArgsForExisting(0, 11401 deletedPackage.applicationInfo.getCodePath(), 11402 deletedPackage.applicationInfo.getResourcePath(), 11403 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11404 } else { 11405 res.removedInfo.args = null; 11406 } 11407 } 11408 11409 // Successfully disabled the old package. Now proceed with re-installation 11410 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11411 11412 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11413 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11414 11415 PackageParser.Package newPackage = null; 11416 try { 11417 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11418 if (newPackage.mExtras != null) { 11419 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11420 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11421 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11422 11423 // is the update attempting to change shared user? that isn't going to work... 11424 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11425 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11426 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11427 + " to " + newPkgSetting.sharedUser); 11428 updatedSettings = true; 11429 } 11430 } 11431 11432 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11433 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11434 perUserInstalled, res, user); 11435 updatedSettings = true; 11436 } 11437 11438 } catch (PackageManagerException e) { 11439 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11440 } 11441 11442 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11443 // Re installation failed. Restore old information 11444 // Remove new pkg information 11445 if (newPackage != null) { 11446 removeInstalledPackageLI(newPackage, true); 11447 } 11448 // Add back the old system package 11449 try { 11450 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11451 } catch (PackageManagerException e) { 11452 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11453 } 11454 // Restore the old system information in Settings 11455 synchronized (mPackages) { 11456 if (disabledSystem) { 11457 mSettings.enableSystemPackageLPw(packageName); 11458 } 11459 if (updatedSettings) { 11460 mSettings.setInstallerPackageName(packageName, 11461 oldPkgSetting.installerPackageName); 11462 } 11463 mSettings.writeLPr(); 11464 } 11465 } 11466 } 11467 11468 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11469 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11470 UserHandle user) { 11471 String pkgName = newPackage.packageName; 11472 synchronized (mPackages) { 11473 //write settings. the installStatus will be incomplete at this stage. 11474 //note that the new package setting would have already been 11475 //added to mPackages. It hasn't been persisted yet. 11476 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11477 mSettings.writeLPr(); 11478 } 11479 11480 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11481 11482 synchronized (mPackages) { 11483 updatePermissionsLPw(newPackage.packageName, newPackage, 11484 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11485 ? UPDATE_PERMISSIONS_ALL : 0)); 11486 // For system-bundled packages, we assume that installing an upgraded version 11487 // of the package implies that the user actually wants to run that new code, 11488 // so we enable the package. 11489 PackageSetting ps = mSettings.mPackages.get(pkgName); 11490 if (ps != null) { 11491 if (isSystemApp(newPackage)) { 11492 // NB: implicit assumption that system package upgrades apply to all users 11493 if (DEBUG_INSTALL) { 11494 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11495 } 11496 if (res.origUsers != null) { 11497 for (int userHandle : res.origUsers) { 11498 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11499 userHandle, installerPackageName); 11500 } 11501 } 11502 // Also convey the prior install/uninstall state 11503 if (allUsers != null && perUserInstalled != null) { 11504 for (int i = 0; i < allUsers.length; i++) { 11505 if (DEBUG_INSTALL) { 11506 Slog.d(TAG, " user " + allUsers[i] 11507 + " => " + perUserInstalled[i]); 11508 } 11509 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11510 } 11511 // these install state changes will be persisted in the 11512 // upcoming call to mSettings.writeLPr(). 11513 } 11514 } 11515 // It's implied that when a user requests installation, they want the app to be 11516 // installed and enabled. 11517 int userId = user.getIdentifier(); 11518 if (userId != UserHandle.USER_ALL) { 11519 ps.setInstalled(true, userId); 11520 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11521 } 11522 } 11523 res.name = pkgName; 11524 res.uid = newPackage.applicationInfo.uid; 11525 res.pkg = newPackage; 11526 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11527 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11528 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11529 //to update install status 11530 mSettings.writeLPr(); 11531 } 11532 } 11533 11534 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11535 final int installFlags = args.installFlags; 11536 final String installerPackageName = args.installerPackageName; 11537 final String volumeUuid = args.volumeUuid; 11538 final File tmpPackageFile = new File(args.getCodePath()); 11539 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11540 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11541 || (args.volumeUuid != null)); 11542 boolean replace = false; 11543 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11544 // Result object to be returned 11545 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11546 11547 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11548 // Retrieve PackageSettings and parse package 11549 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11550 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11551 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11552 PackageParser pp = new PackageParser(); 11553 pp.setSeparateProcesses(mSeparateProcesses); 11554 pp.setDisplayMetrics(mMetrics); 11555 11556 final PackageParser.Package pkg; 11557 try { 11558 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11559 } catch (PackageParserException e) { 11560 res.setError("Failed parse during installPackageLI", e); 11561 return; 11562 } 11563 11564 // Mark that we have an install time CPU ABI override. 11565 pkg.cpuAbiOverride = args.abiOverride; 11566 11567 String pkgName = res.name = pkg.packageName; 11568 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11569 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11570 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11571 return; 11572 } 11573 } 11574 11575 try { 11576 pp.collectCertificates(pkg, parseFlags); 11577 pp.collectManifestDigest(pkg); 11578 } catch (PackageParserException e) { 11579 res.setError("Failed collect during installPackageLI", e); 11580 return; 11581 } 11582 11583 /* If the installer passed in a manifest digest, compare it now. */ 11584 if (args.manifestDigest != null) { 11585 if (DEBUG_INSTALL) { 11586 final String parsedManifest = pkg.manifestDigest == null ? "null" 11587 : pkg.manifestDigest.toString(); 11588 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11589 + parsedManifest); 11590 } 11591 11592 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11593 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11594 return; 11595 } 11596 } else if (DEBUG_INSTALL) { 11597 final String parsedManifest = pkg.manifestDigest == null 11598 ? "null" : pkg.manifestDigest.toString(); 11599 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11600 } 11601 11602 // Get rid of all references to package scan path via parser. 11603 pp = null; 11604 String oldCodePath = null; 11605 boolean systemApp = false; 11606 synchronized (mPackages) { 11607 // Check if installing already existing package 11608 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11609 String oldName = mSettings.mRenamedPackages.get(pkgName); 11610 if (pkg.mOriginalPackages != null 11611 && pkg.mOriginalPackages.contains(oldName) 11612 && mPackages.containsKey(oldName)) { 11613 // This package is derived from an original package, 11614 // and this device has been updating from that original 11615 // name. We must continue using the original name, so 11616 // rename the new package here. 11617 pkg.setPackageName(oldName); 11618 pkgName = pkg.packageName; 11619 replace = true; 11620 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11621 + oldName + " pkgName=" + pkgName); 11622 } else if (mPackages.containsKey(pkgName)) { 11623 // This package, under its official name, already exists 11624 // on the device; we should replace it. 11625 replace = true; 11626 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11627 } 11628 11629 // Prevent apps opting out from runtime permissions 11630 if (replace) { 11631 PackageParser.Package oldPackage = mPackages.get(pkgName); 11632 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11633 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11634 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11635 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11636 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11637 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11638 + " doesn't support runtime permissions but the old" 11639 + " target SDK " + oldTargetSdk + " does."); 11640 return; 11641 } 11642 } 11643 } 11644 11645 PackageSetting ps = mSettings.mPackages.get(pkgName); 11646 if (ps != null) { 11647 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11648 11649 // Quick sanity check that we're signed correctly if updating; 11650 // we'll check this again later when scanning, but we want to 11651 // bail early here before tripping over redefined permissions. 11652 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11653 if (!checkUpgradeKeySetLP(ps, pkg)) { 11654 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11655 + pkg.packageName + " upgrade keys do not match the " 11656 + "previously installed version"); 11657 return; 11658 } 11659 } else { 11660 try { 11661 verifySignaturesLP(ps, pkg); 11662 } catch (PackageManagerException e) { 11663 res.setError(e.error, e.getMessage()); 11664 return; 11665 } 11666 } 11667 11668 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11669 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11670 systemApp = (ps.pkg.applicationInfo.flags & 11671 ApplicationInfo.FLAG_SYSTEM) != 0; 11672 } 11673 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11674 } 11675 11676 // Check whether the newly-scanned package wants to define an already-defined perm 11677 int N = pkg.permissions.size(); 11678 for (int i = N-1; i >= 0; i--) { 11679 PackageParser.Permission perm = pkg.permissions.get(i); 11680 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11681 if (bp != null) { 11682 // If the defining package is signed with our cert, it's okay. This 11683 // also includes the "updating the same package" case, of course. 11684 // "updating same package" could also involve key-rotation. 11685 final boolean sigsOk; 11686 if (bp.sourcePackage.equals(pkg.packageName) 11687 && (bp.packageSetting instanceof PackageSetting) 11688 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11689 scanFlags))) { 11690 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11691 } else { 11692 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11693 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11694 } 11695 if (!sigsOk) { 11696 // If the owning package is the system itself, we log but allow 11697 // install to proceed; we fail the install on all other permission 11698 // redefinitions. 11699 if (!bp.sourcePackage.equals("android")) { 11700 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11701 + pkg.packageName + " attempting to redeclare permission " 11702 + perm.info.name + " already owned by " + bp.sourcePackage); 11703 res.origPermission = perm.info.name; 11704 res.origPackage = bp.sourcePackage; 11705 return; 11706 } else { 11707 Slog.w(TAG, "Package " + pkg.packageName 11708 + " attempting to redeclare system permission " 11709 + perm.info.name + "; ignoring new declaration"); 11710 pkg.permissions.remove(i); 11711 } 11712 } 11713 } 11714 } 11715 11716 } 11717 11718 if (systemApp && onExternal) { 11719 // Disable updates to system apps on sdcard 11720 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11721 "Cannot install updates to system apps on sdcard"); 11722 return; 11723 } 11724 11725 if (args.move != null) { 11726 // We did an in-place move, so dex is ready to roll 11727 scanFlags |= SCAN_NO_DEX; 11728 scanFlags |= SCAN_MOVE; 11729 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11730 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11731 scanFlags |= SCAN_NO_DEX; 11732 11733 try { 11734 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11735 true /* extract libs */); 11736 } catch (PackageManagerException pme) { 11737 Slog.e(TAG, "Error deriving application ABI", pme); 11738 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11739 return; 11740 } 11741 11742 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11743 int result = mPackageDexOptimizer 11744 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11745 false /* defer */, false /* inclDependencies */); 11746 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11747 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11748 return; 11749 } 11750 } 11751 11752 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11753 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11754 return; 11755 } 11756 11757 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11758 11759 if (replace) { 11760 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11761 installerPackageName, volumeUuid, res); 11762 } else { 11763 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11764 args.user, installerPackageName, volumeUuid, res); 11765 } 11766 synchronized (mPackages) { 11767 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11768 if (ps != null) { 11769 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11770 } 11771 } 11772 } 11773 11774 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11775 if (mIntentFilterVerifierComponent == null) { 11776 Slog.w(TAG, "No IntentFilter verification will not be done as " 11777 + "there is no IntentFilterVerifier available!"); 11778 return; 11779 } 11780 11781 final int verifierUid = getPackageUid( 11782 mIntentFilterVerifierComponent.getPackageName(), 11783 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11784 11785 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11786 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11787 msg.obj = pkg; 11788 msg.arg1 = userId; 11789 msg.arg2 = verifierUid; 11790 11791 mHandler.sendMessage(msg); 11792 } 11793 11794 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11795 PackageParser.Package pkg) { 11796 int size = pkg.activities.size(); 11797 if (size == 0) { 11798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11799 "No activity, so no need to verify any IntentFilter!"); 11800 return; 11801 } 11802 11803 final boolean hasDomainURLs = hasDomainURLs(pkg); 11804 if (!hasDomainURLs) { 11805 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11806 "No domain URLs, so no need to verify any IntentFilter!"); 11807 return; 11808 } 11809 11810 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11811 + " if any IntentFilter from the " + size 11812 + " Activities needs verification ..."); 11813 11814 final int verificationId = mIntentFilterVerificationToken++; 11815 int count = 0; 11816 final String packageName = pkg.packageName; 11817 boolean needToVerify = false; 11818 11819 synchronized (mPackages) { 11820 // If any filters need to be verified, then all need to be. 11821 for (PackageParser.Activity a : pkg.activities) { 11822 for (ActivityIntentInfo filter : a.intents) { 11823 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11824 if (DEBUG_DOMAIN_VERIFICATION) { 11825 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11826 } 11827 needToVerify = true; 11828 break; 11829 } 11830 } 11831 } 11832 if (needToVerify) { 11833 for (PackageParser.Activity a : pkg.activities) { 11834 for (ActivityIntentInfo filter : a.intents) { 11835 boolean needsFilterVerification = filter.hasWebDataURI(); 11836 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11838 "Verification needed for IntentFilter:" + filter.toString()); 11839 mIntentFilterVerifier.addOneIntentFilterVerification( 11840 verifierUid, userId, verificationId, filter, packageName); 11841 count++; 11842 } 11843 } 11844 } 11845 } 11846 } 11847 11848 if (count > 0) { 11849 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11850 + " IntentFilter verification" + (count > 1 ? "s" : "") 11851 + " for userId:" + userId); 11852 mIntentFilterVerifier.startVerifications(userId); 11853 } else { 11854 if (DEBUG_DOMAIN_VERIFICATION) { 11855 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11856 } 11857 } 11858 } 11859 11860 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11861 final ComponentName cn = filter.activity.getComponentName(); 11862 final String packageName = cn.getPackageName(); 11863 11864 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11865 packageName); 11866 if (ivi == null) { 11867 return true; 11868 } 11869 int status = ivi.getStatus(); 11870 switch (status) { 11871 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11872 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11873 return true; 11874 11875 default: 11876 // Nothing to do 11877 return false; 11878 } 11879 } 11880 11881 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11882 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11883 || ((pkg.applicationInfo.privateFlags 11884 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11885 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11886 } 11887 11888 private static boolean isMultiArch(PackageSetting ps) { 11889 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11890 } 11891 11892 private static boolean isMultiArch(ApplicationInfo info) { 11893 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11894 } 11895 11896 private static boolean isExternal(PackageParser.Package pkg) { 11897 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11898 } 11899 11900 private static boolean isExternal(PackageSetting ps) { 11901 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11902 } 11903 11904 private static boolean isExternal(ApplicationInfo info) { 11905 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11906 } 11907 11908 private static boolean isSystemApp(PackageParser.Package pkg) { 11909 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11910 } 11911 11912 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11913 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11914 } 11915 11916 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11917 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11918 } 11919 11920 private static boolean isSystemApp(PackageSetting ps) { 11921 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11922 } 11923 11924 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11925 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11926 } 11927 11928 private int packageFlagsToInstallFlags(PackageSetting ps) { 11929 int installFlags = 0; 11930 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11931 // This existing package was an external ASEC install when we have 11932 // the external flag without a UUID 11933 installFlags |= PackageManager.INSTALL_EXTERNAL; 11934 } 11935 if (ps.isForwardLocked()) { 11936 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11937 } 11938 return installFlags; 11939 } 11940 11941 private void deleteTempPackageFiles() { 11942 final FilenameFilter filter = new FilenameFilter() { 11943 public boolean accept(File dir, String name) { 11944 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11945 } 11946 }; 11947 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11948 file.delete(); 11949 } 11950 } 11951 11952 @Override 11953 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11954 int flags) { 11955 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11956 flags); 11957 } 11958 11959 @Override 11960 public void deletePackage(final String packageName, 11961 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11962 mContext.enforceCallingOrSelfPermission( 11963 android.Manifest.permission.DELETE_PACKAGES, null); 11964 final int uid = Binder.getCallingUid(); 11965 if (UserHandle.getUserId(uid) != userId) { 11966 mContext.enforceCallingPermission( 11967 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11968 "deletePackage for user " + userId); 11969 } 11970 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11971 try { 11972 observer.onPackageDeleted(packageName, 11973 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11974 } catch (RemoteException re) { 11975 } 11976 return; 11977 } 11978 11979 boolean uninstallBlocked = false; 11980 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11981 int[] users = sUserManager.getUserIds(); 11982 for (int i = 0; i < users.length; ++i) { 11983 if (getBlockUninstallForUser(packageName, users[i])) { 11984 uninstallBlocked = true; 11985 break; 11986 } 11987 } 11988 } else { 11989 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11990 } 11991 if (uninstallBlocked) { 11992 try { 11993 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11994 null); 11995 } catch (RemoteException re) { 11996 } 11997 return; 11998 } 11999 12000 if (DEBUG_REMOVE) { 12001 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12002 } 12003 // Queue up an async operation since the package deletion may take a little while. 12004 mHandler.post(new Runnable() { 12005 public void run() { 12006 mHandler.removeCallbacks(this); 12007 final int returnCode = deletePackageX(packageName, userId, flags); 12008 if (observer != null) { 12009 try { 12010 observer.onPackageDeleted(packageName, returnCode, null); 12011 } catch (RemoteException e) { 12012 Log.i(TAG, "Observer no longer exists."); 12013 } //end catch 12014 } //end if 12015 } //end run 12016 }); 12017 } 12018 12019 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12020 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12021 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12022 try { 12023 if (dpm != null) { 12024 if (dpm.isDeviceOwner(packageName)) { 12025 return true; 12026 } 12027 int[] users; 12028 if (userId == UserHandle.USER_ALL) { 12029 users = sUserManager.getUserIds(); 12030 } else { 12031 users = new int[]{userId}; 12032 } 12033 for (int i = 0; i < users.length; ++i) { 12034 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12035 return true; 12036 } 12037 } 12038 } 12039 } catch (RemoteException e) { 12040 } 12041 return false; 12042 } 12043 12044 /** 12045 * This method is an internal method that could be get invoked either 12046 * to delete an installed package or to clean up a failed installation. 12047 * After deleting an installed package, a broadcast is sent to notify any 12048 * listeners that the package has been installed. For cleaning up a failed 12049 * installation, the broadcast is not necessary since the package's 12050 * installation wouldn't have sent the initial broadcast either 12051 * The key steps in deleting a package are 12052 * deleting the package information in internal structures like mPackages, 12053 * deleting the packages base directories through installd 12054 * updating mSettings to reflect current status 12055 * persisting settings for later use 12056 * sending a broadcast if necessary 12057 */ 12058 private int deletePackageX(String packageName, int userId, int flags) { 12059 final PackageRemovedInfo info = new PackageRemovedInfo(); 12060 final boolean res; 12061 12062 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12063 ? UserHandle.ALL : new UserHandle(userId); 12064 12065 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12066 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12067 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12068 } 12069 12070 boolean removedForAllUsers = false; 12071 boolean systemUpdate = false; 12072 12073 // for the uninstall-updates case and restricted profiles, remember the per- 12074 // userhandle installed state 12075 int[] allUsers; 12076 boolean[] perUserInstalled; 12077 synchronized (mPackages) { 12078 PackageSetting ps = mSettings.mPackages.get(packageName); 12079 allUsers = sUserManager.getUserIds(); 12080 perUserInstalled = new boolean[allUsers.length]; 12081 for (int i = 0; i < allUsers.length; i++) { 12082 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12083 } 12084 } 12085 12086 synchronized (mInstallLock) { 12087 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12088 res = deletePackageLI(packageName, removeForUser, 12089 true, allUsers, perUserInstalled, 12090 flags | REMOVE_CHATTY, info, true); 12091 systemUpdate = info.isRemovedPackageSystemUpdate; 12092 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12093 removedForAllUsers = true; 12094 } 12095 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12096 + " removedForAllUsers=" + removedForAllUsers); 12097 } 12098 12099 if (res) { 12100 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12101 12102 // If the removed package was a system update, the old system package 12103 // was re-enabled; we need to broadcast this information 12104 if (systemUpdate) { 12105 Bundle extras = new Bundle(1); 12106 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12107 ? info.removedAppId : info.uid); 12108 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12109 12110 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12111 extras, null, null, null); 12112 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12113 extras, null, null, null); 12114 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12115 null, packageName, null, null); 12116 } 12117 } 12118 // Force a gc here. 12119 Runtime.getRuntime().gc(); 12120 // Delete the resources here after sending the broadcast to let 12121 // other processes clean up before deleting resources. 12122 if (info.args != null) { 12123 synchronized (mInstallLock) { 12124 info.args.doPostDeleteLI(true); 12125 } 12126 } 12127 12128 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12129 } 12130 12131 class PackageRemovedInfo { 12132 String removedPackage; 12133 int uid = -1; 12134 int removedAppId = -1; 12135 int[] removedUsers = null; 12136 boolean isRemovedPackageSystemUpdate = false; 12137 // Clean up resources deleted packages. 12138 InstallArgs args = null; 12139 12140 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12141 Bundle extras = new Bundle(1); 12142 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12143 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12144 if (replacing) { 12145 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12146 } 12147 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12148 if (removedPackage != null) { 12149 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12150 extras, null, null, removedUsers); 12151 if (fullRemove && !replacing) { 12152 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12153 extras, null, null, removedUsers); 12154 } 12155 } 12156 if (removedAppId >= 0) { 12157 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12158 removedUsers); 12159 } 12160 } 12161 } 12162 12163 /* 12164 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12165 * flag is not set, the data directory is removed as well. 12166 * make sure this flag is set for partially installed apps. If not its meaningless to 12167 * delete a partially installed application. 12168 */ 12169 private void removePackageDataLI(PackageSetting ps, 12170 int[] allUserHandles, boolean[] perUserInstalled, 12171 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12172 String packageName = ps.name; 12173 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12174 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12175 // Retrieve object to delete permissions for shared user later on 12176 final PackageSetting deletedPs; 12177 // reader 12178 synchronized (mPackages) { 12179 deletedPs = mSettings.mPackages.get(packageName); 12180 if (outInfo != null) { 12181 outInfo.removedPackage = packageName; 12182 outInfo.removedUsers = deletedPs != null 12183 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12184 : null; 12185 } 12186 } 12187 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12188 removeDataDirsLI(ps.volumeUuid, packageName); 12189 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12190 } 12191 // writer 12192 synchronized (mPackages) { 12193 if (deletedPs != null) { 12194 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12195 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12196 clearDefaultBrowserIfNeeded(packageName); 12197 if (outInfo != null) { 12198 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12199 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12200 } 12201 updatePermissionsLPw(deletedPs.name, null, 0); 12202 if (deletedPs.sharedUser != null) { 12203 // Remove permissions associated with package. Since runtime 12204 // permissions are per user we have to kill the removed package 12205 // or packages running under the shared user of the removed 12206 // package if revoking the permissions requested only by the removed 12207 // package is successful and this causes a change in gids. 12208 for (int userId : UserManagerService.getInstance().getUserIds()) { 12209 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12210 userId); 12211 if (userIdToKill == UserHandle.USER_ALL 12212 || userIdToKill >= UserHandle.USER_OWNER) { 12213 // If gids changed for this user, kill all affected packages. 12214 mHandler.post(new Runnable() { 12215 @Override 12216 public void run() { 12217 // This has to happen with no lock held. 12218 killSettingPackagesForUser(deletedPs, userIdToKill, 12219 KILL_APP_REASON_GIDS_CHANGED); 12220 } 12221 }); 12222 break; 12223 } 12224 } 12225 } 12226 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12227 } 12228 // make sure to preserve per-user disabled state if this removal was just 12229 // a downgrade of a system app to the factory package 12230 if (allUserHandles != null && perUserInstalled != null) { 12231 if (DEBUG_REMOVE) { 12232 Slog.d(TAG, "Propagating install state across downgrade"); 12233 } 12234 for (int i = 0; i < allUserHandles.length; i++) { 12235 if (DEBUG_REMOVE) { 12236 Slog.d(TAG, " user " + allUserHandles[i] 12237 + " => " + perUserInstalled[i]); 12238 } 12239 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12240 } 12241 } 12242 } 12243 // can downgrade to reader 12244 if (writeSettings) { 12245 // Save settings now 12246 mSettings.writeLPr(); 12247 } 12248 } 12249 if (outInfo != null) { 12250 // A user ID was deleted here. Go through all users and remove it 12251 // from KeyStore. 12252 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12253 } 12254 } 12255 12256 static boolean locationIsPrivileged(File path) { 12257 try { 12258 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12259 .getCanonicalPath(); 12260 return path.getCanonicalPath().startsWith(privilegedAppDir); 12261 } catch (IOException e) { 12262 Slog.e(TAG, "Unable to access code path " + path); 12263 } 12264 return false; 12265 } 12266 12267 /* 12268 * Tries to delete system package. 12269 */ 12270 private boolean deleteSystemPackageLI(PackageSetting newPs, 12271 int[] allUserHandles, boolean[] perUserInstalled, 12272 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12273 final boolean applyUserRestrictions 12274 = (allUserHandles != null) && (perUserInstalled != null); 12275 PackageSetting disabledPs = null; 12276 // Confirm if the system package has been updated 12277 // An updated system app can be deleted. This will also have to restore 12278 // the system pkg from system partition 12279 // reader 12280 synchronized (mPackages) { 12281 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12282 } 12283 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12284 + " disabledPs=" + disabledPs); 12285 if (disabledPs == null) { 12286 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12287 return false; 12288 } else if (DEBUG_REMOVE) { 12289 Slog.d(TAG, "Deleting system pkg from data partition"); 12290 } 12291 if (DEBUG_REMOVE) { 12292 if (applyUserRestrictions) { 12293 Slog.d(TAG, "Remembering install states:"); 12294 for (int i = 0; i < allUserHandles.length; i++) { 12295 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12296 } 12297 } 12298 } 12299 // Delete the updated package 12300 outInfo.isRemovedPackageSystemUpdate = true; 12301 if (disabledPs.versionCode < newPs.versionCode) { 12302 // Delete data for downgrades 12303 flags &= ~PackageManager.DELETE_KEEP_DATA; 12304 } else { 12305 // Preserve data by setting flag 12306 flags |= PackageManager.DELETE_KEEP_DATA; 12307 } 12308 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12309 allUserHandles, perUserInstalled, outInfo, writeSettings); 12310 if (!ret) { 12311 return false; 12312 } 12313 // writer 12314 synchronized (mPackages) { 12315 // Reinstate the old system package 12316 mSettings.enableSystemPackageLPw(newPs.name); 12317 // Remove any native libraries from the upgraded package. 12318 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12319 } 12320 // Install the system package 12321 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12322 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12323 if (locationIsPrivileged(disabledPs.codePath)) { 12324 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12325 } 12326 12327 final PackageParser.Package newPkg; 12328 try { 12329 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12330 } catch (PackageManagerException e) { 12331 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12332 return false; 12333 } 12334 12335 // writer 12336 synchronized (mPackages) { 12337 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12338 updatePermissionsLPw(newPkg.packageName, newPkg, 12339 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12340 if (applyUserRestrictions) { 12341 if (DEBUG_REMOVE) { 12342 Slog.d(TAG, "Propagating install state across reinstall"); 12343 } 12344 for (int i = 0; i < allUserHandles.length; i++) { 12345 if (DEBUG_REMOVE) { 12346 Slog.d(TAG, " user " + allUserHandles[i] 12347 + " => " + perUserInstalled[i]); 12348 } 12349 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12350 } 12351 // Regardless of writeSettings we need to ensure that this restriction 12352 // state propagation is persisted 12353 mSettings.writeAllUsersPackageRestrictionsLPr(); 12354 } 12355 // can downgrade to reader here 12356 if (writeSettings) { 12357 mSettings.writeLPr(); 12358 } 12359 } 12360 return true; 12361 } 12362 12363 private boolean deleteInstalledPackageLI(PackageSetting ps, 12364 boolean deleteCodeAndResources, int flags, 12365 int[] allUserHandles, boolean[] perUserInstalled, 12366 PackageRemovedInfo outInfo, boolean writeSettings) { 12367 if (outInfo != null) { 12368 outInfo.uid = ps.appId; 12369 } 12370 12371 // Delete package data from internal structures and also remove data if flag is set 12372 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12373 12374 // Delete application code and resources 12375 if (deleteCodeAndResources && (outInfo != null)) { 12376 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12377 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12378 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12379 } 12380 return true; 12381 } 12382 12383 @Override 12384 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12385 int userId) { 12386 mContext.enforceCallingOrSelfPermission( 12387 android.Manifest.permission.DELETE_PACKAGES, null); 12388 synchronized (mPackages) { 12389 PackageSetting ps = mSettings.mPackages.get(packageName); 12390 if (ps == null) { 12391 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12392 return false; 12393 } 12394 if (!ps.getInstalled(userId)) { 12395 // Can't block uninstall for an app that is not installed or enabled. 12396 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12397 return false; 12398 } 12399 ps.setBlockUninstall(blockUninstall, userId); 12400 mSettings.writePackageRestrictionsLPr(userId); 12401 } 12402 return true; 12403 } 12404 12405 @Override 12406 public boolean getBlockUninstallForUser(String packageName, int userId) { 12407 synchronized (mPackages) { 12408 PackageSetting ps = mSettings.mPackages.get(packageName); 12409 if (ps == null) { 12410 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12411 return false; 12412 } 12413 return ps.getBlockUninstall(userId); 12414 } 12415 } 12416 12417 /* 12418 * This method handles package deletion in general 12419 */ 12420 private boolean deletePackageLI(String packageName, UserHandle user, 12421 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12422 int flags, PackageRemovedInfo outInfo, 12423 boolean writeSettings) { 12424 if (packageName == null) { 12425 Slog.w(TAG, "Attempt to delete null packageName."); 12426 return false; 12427 } 12428 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12429 PackageSetting ps; 12430 boolean dataOnly = false; 12431 int removeUser = -1; 12432 int appId = -1; 12433 synchronized (mPackages) { 12434 ps = mSettings.mPackages.get(packageName); 12435 if (ps == null) { 12436 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12437 return false; 12438 } 12439 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12440 && user.getIdentifier() != UserHandle.USER_ALL) { 12441 // The caller is asking that the package only be deleted for a single 12442 // user. To do this, we just mark its uninstalled state and delete 12443 // its data. If this is a system app, we only allow this to happen if 12444 // they have set the special DELETE_SYSTEM_APP which requests different 12445 // semantics than normal for uninstalling system apps. 12446 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12447 ps.setUserState(user.getIdentifier(), 12448 COMPONENT_ENABLED_STATE_DEFAULT, 12449 false, //installed 12450 true, //stopped 12451 true, //notLaunched 12452 false, //hidden 12453 null, null, null, 12454 false, // blockUninstall 12455 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12456 if (!isSystemApp(ps)) { 12457 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12458 // Other user still have this package installed, so all 12459 // we need to do is clear this user's data and save that 12460 // it is uninstalled. 12461 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12462 removeUser = user.getIdentifier(); 12463 appId = ps.appId; 12464 scheduleWritePackageRestrictionsLocked(removeUser); 12465 } else { 12466 // We need to set it back to 'installed' so the uninstall 12467 // broadcasts will be sent correctly. 12468 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12469 ps.setInstalled(true, user.getIdentifier()); 12470 } 12471 } else { 12472 // This is a system app, so we assume that the 12473 // other users still have this package installed, so all 12474 // we need to do is clear this user's data and save that 12475 // it is uninstalled. 12476 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12477 removeUser = user.getIdentifier(); 12478 appId = ps.appId; 12479 scheduleWritePackageRestrictionsLocked(removeUser); 12480 } 12481 } 12482 } 12483 12484 if (removeUser >= 0) { 12485 // From above, we determined that we are deleting this only 12486 // for a single user. Continue the work here. 12487 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12488 if (outInfo != null) { 12489 outInfo.removedPackage = packageName; 12490 outInfo.removedAppId = appId; 12491 outInfo.removedUsers = new int[] {removeUser}; 12492 } 12493 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12494 removeKeystoreDataIfNeeded(removeUser, appId); 12495 schedulePackageCleaning(packageName, removeUser, false); 12496 synchronized (mPackages) { 12497 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12498 scheduleWritePackageRestrictionsLocked(removeUser); 12499 } 12500 } 12501 return true; 12502 } 12503 12504 if (dataOnly) { 12505 // Delete application data first 12506 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12507 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12508 return true; 12509 } 12510 12511 boolean ret = false; 12512 if (isSystemApp(ps)) { 12513 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12514 // When an updated system application is deleted we delete the existing resources as well and 12515 // fall back to existing code in system partition 12516 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12517 flags, outInfo, writeSettings); 12518 } else { 12519 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12520 // Kill application pre-emptively especially for apps on sd. 12521 killApplication(packageName, ps.appId, "uninstall pkg"); 12522 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12523 allUserHandles, perUserInstalled, 12524 outInfo, writeSettings); 12525 } 12526 12527 return ret; 12528 } 12529 12530 private final class ClearStorageConnection implements ServiceConnection { 12531 IMediaContainerService mContainerService; 12532 12533 @Override 12534 public void onServiceConnected(ComponentName name, IBinder service) { 12535 synchronized (this) { 12536 mContainerService = IMediaContainerService.Stub.asInterface(service); 12537 notifyAll(); 12538 } 12539 } 12540 12541 @Override 12542 public void onServiceDisconnected(ComponentName name) { 12543 } 12544 } 12545 12546 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12547 final boolean mounted; 12548 if (Environment.isExternalStorageEmulated()) { 12549 mounted = true; 12550 } else { 12551 final String status = Environment.getExternalStorageState(); 12552 12553 mounted = status.equals(Environment.MEDIA_MOUNTED) 12554 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12555 } 12556 12557 if (!mounted) { 12558 return; 12559 } 12560 12561 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12562 int[] users; 12563 if (userId == UserHandle.USER_ALL) { 12564 users = sUserManager.getUserIds(); 12565 } else { 12566 users = new int[] { userId }; 12567 } 12568 final ClearStorageConnection conn = new ClearStorageConnection(); 12569 if (mContext.bindServiceAsUser( 12570 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12571 try { 12572 for (int curUser : users) { 12573 long timeout = SystemClock.uptimeMillis() + 5000; 12574 synchronized (conn) { 12575 long now = SystemClock.uptimeMillis(); 12576 while (conn.mContainerService == null && now < timeout) { 12577 try { 12578 conn.wait(timeout - now); 12579 } catch (InterruptedException e) { 12580 } 12581 } 12582 } 12583 if (conn.mContainerService == null) { 12584 return; 12585 } 12586 12587 final UserEnvironment userEnv = new UserEnvironment(curUser); 12588 clearDirectory(conn.mContainerService, 12589 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12590 if (allData) { 12591 clearDirectory(conn.mContainerService, 12592 userEnv.buildExternalStorageAppDataDirs(packageName)); 12593 clearDirectory(conn.mContainerService, 12594 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12595 } 12596 } 12597 } finally { 12598 mContext.unbindService(conn); 12599 } 12600 } 12601 } 12602 12603 @Override 12604 public void clearApplicationUserData(final String packageName, 12605 final IPackageDataObserver observer, final int userId) { 12606 mContext.enforceCallingOrSelfPermission( 12607 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12608 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12609 // Queue up an async operation since the package deletion may take a little while. 12610 mHandler.post(new Runnable() { 12611 public void run() { 12612 mHandler.removeCallbacks(this); 12613 final boolean succeeded; 12614 synchronized (mInstallLock) { 12615 succeeded = clearApplicationUserDataLI(packageName, userId); 12616 } 12617 clearExternalStorageDataSync(packageName, userId, true); 12618 if (succeeded) { 12619 // invoke DeviceStorageMonitor's update method to clear any notifications 12620 DeviceStorageMonitorInternal 12621 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12622 if (dsm != null) { 12623 dsm.checkMemory(); 12624 } 12625 } 12626 if(observer != null) { 12627 try { 12628 observer.onRemoveCompleted(packageName, succeeded); 12629 } catch (RemoteException e) { 12630 Log.i(TAG, "Observer no longer exists."); 12631 } 12632 } //end if observer 12633 } //end run 12634 }); 12635 } 12636 12637 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12638 if (packageName == null) { 12639 Slog.w(TAG, "Attempt to delete null packageName."); 12640 return false; 12641 } 12642 12643 // Try finding details about the requested package 12644 PackageParser.Package pkg; 12645 synchronized (mPackages) { 12646 pkg = mPackages.get(packageName); 12647 if (pkg == null) { 12648 final PackageSetting ps = mSettings.mPackages.get(packageName); 12649 if (ps != null) { 12650 pkg = ps.pkg; 12651 } 12652 } 12653 12654 if (pkg == null) { 12655 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12656 return false; 12657 } 12658 12659 PackageSetting ps = (PackageSetting) pkg.mExtras; 12660 PermissionsState permissionsState = ps.getPermissionsState(); 12661 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12662 } 12663 12664 // Always delete data directories for package, even if we found no other 12665 // record of app. This helps users recover from UID mismatches without 12666 // resorting to a full data wipe. 12667 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12668 if (retCode < 0) { 12669 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12670 return false; 12671 } 12672 12673 final int appId = pkg.applicationInfo.uid; 12674 removeKeystoreDataIfNeeded(userId, appId); 12675 12676 // Create a native library symlink only if we have native libraries 12677 // and if the native libraries are 32 bit libraries. We do not provide 12678 // this symlink for 64 bit libraries. 12679 if (pkg.applicationInfo.primaryCpuAbi != null && 12680 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12681 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12682 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12683 nativeLibPath, userId) < 0) { 12684 Slog.w(TAG, "Failed linking native library dir"); 12685 return false; 12686 } 12687 } 12688 12689 return true; 12690 } 12691 12692 12693 /** 12694 * Revokes granted runtime permissions and clears resettable flags 12695 * which are flags that can be set by a user interaction. 12696 * 12697 * @param permissionsState The permission state to reset. 12698 * @param userId The device user for which to do a reset. 12699 */ 12700 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12701 PermissionsState permissionsState, int userId) { 12702 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12703 | PackageManager.FLAG_PERMISSION_USER_FIXED 12704 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12705 12706 boolean needsWrite = false; 12707 12708 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12709 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12710 if (bp != null) { 12711 permissionsState.revokeRuntimePermission(bp, userId); 12712 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12713 needsWrite = true; 12714 } 12715 } 12716 12717 if (needsWrite) { 12718 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12719 } 12720 } 12721 12722 /** 12723 * Remove entries from the keystore daemon. Will only remove it if the 12724 * {@code appId} is valid. 12725 */ 12726 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12727 if (appId < 0) { 12728 return; 12729 } 12730 12731 final KeyStore keyStore = KeyStore.getInstance(); 12732 if (keyStore != null) { 12733 if (userId == UserHandle.USER_ALL) { 12734 for (final int individual : sUserManager.getUserIds()) { 12735 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12736 } 12737 } else { 12738 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12739 } 12740 } else { 12741 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12742 } 12743 } 12744 12745 @Override 12746 public void deleteApplicationCacheFiles(final String packageName, 12747 final IPackageDataObserver observer) { 12748 mContext.enforceCallingOrSelfPermission( 12749 android.Manifest.permission.DELETE_CACHE_FILES, null); 12750 // Queue up an async operation since the package deletion may take a little while. 12751 final int userId = UserHandle.getCallingUserId(); 12752 mHandler.post(new Runnable() { 12753 public void run() { 12754 mHandler.removeCallbacks(this); 12755 final boolean succeded; 12756 synchronized (mInstallLock) { 12757 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12758 } 12759 clearExternalStorageDataSync(packageName, userId, false); 12760 if (observer != null) { 12761 try { 12762 observer.onRemoveCompleted(packageName, succeded); 12763 } catch (RemoteException e) { 12764 Log.i(TAG, "Observer no longer exists."); 12765 } 12766 } //end if observer 12767 } //end run 12768 }); 12769 } 12770 12771 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12772 if (packageName == null) { 12773 Slog.w(TAG, "Attempt to delete null packageName."); 12774 return false; 12775 } 12776 PackageParser.Package p; 12777 synchronized (mPackages) { 12778 p = mPackages.get(packageName); 12779 } 12780 if (p == null) { 12781 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12782 return false; 12783 } 12784 final ApplicationInfo applicationInfo = p.applicationInfo; 12785 if (applicationInfo == null) { 12786 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12787 return false; 12788 } 12789 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12790 if (retCode < 0) { 12791 Slog.w(TAG, "Couldn't remove cache files for package: " 12792 + packageName + " u" + userId); 12793 return false; 12794 } 12795 return true; 12796 } 12797 12798 @Override 12799 public void getPackageSizeInfo(final String packageName, int userHandle, 12800 final IPackageStatsObserver observer) { 12801 mContext.enforceCallingOrSelfPermission( 12802 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12803 if (packageName == null) { 12804 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12805 } 12806 12807 PackageStats stats = new PackageStats(packageName, userHandle); 12808 12809 /* 12810 * Queue up an async operation since the package measurement may take a 12811 * little while. 12812 */ 12813 Message msg = mHandler.obtainMessage(INIT_COPY); 12814 msg.obj = new MeasureParams(stats, observer); 12815 mHandler.sendMessage(msg); 12816 } 12817 12818 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12819 PackageStats pStats) { 12820 if (packageName == null) { 12821 Slog.w(TAG, "Attempt to get size of null packageName."); 12822 return false; 12823 } 12824 PackageParser.Package p; 12825 boolean dataOnly = false; 12826 String libDirRoot = null; 12827 String asecPath = null; 12828 PackageSetting ps = null; 12829 synchronized (mPackages) { 12830 p = mPackages.get(packageName); 12831 ps = mSettings.mPackages.get(packageName); 12832 if(p == null) { 12833 dataOnly = true; 12834 if((ps == null) || (ps.pkg == null)) { 12835 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12836 return false; 12837 } 12838 p = ps.pkg; 12839 } 12840 if (ps != null) { 12841 libDirRoot = ps.legacyNativeLibraryPathString; 12842 } 12843 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12844 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12845 if (secureContainerId != null) { 12846 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12847 } 12848 } 12849 } 12850 String publicSrcDir = null; 12851 if(!dataOnly) { 12852 final ApplicationInfo applicationInfo = p.applicationInfo; 12853 if (applicationInfo == null) { 12854 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12855 return false; 12856 } 12857 if (p.isForwardLocked()) { 12858 publicSrcDir = applicationInfo.getBaseResourcePath(); 12859 } 12860 } 12861 // TODO: extend to measure size of split APKs 12862 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12863 // not just the first level. 12864 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12865 // just the primary. 12866 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12867 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12868 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12869 if (res < 0) { 12870 return false; 12871 } 12872 12873 // Fix-up for forward-locked applications in ASEC containers. 12874 if (!isExternal(p)) { 12875 pStats.codeSize += pStats.externalCodeSize; 12876 pStats.externalCodeSize = 0L; 12877 } 12878 12879 return true; 12880 } 12881 12882 12883 @Override 12884 public void addPackageToPreferred(String packageName) { 12885 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12886 } 12887 12888 @Override 12889 public void removePackageFromPreferred(String packageName) { 12890 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12891 } 12892 12893 @Override 12894 public List<PackageInfo> getPreferredPackages(int flags) { 12895 return new ArrayList<PackageInfo>(); 12896 } 12897 12898 private int getUidTargetSdkVersionLockedLPr(int uid) { 12899 Object obj = mSettings.getUserIdLPr(uid); 12900 if (obj instanceof SharedUserSetting) { 12901 final SharedUserSetting sus = (SharedUserSetting) obj; 12902 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12903 final Iterator<PackageSetting> it = sus.packages.iterator(); 12904 while (it.hasNext()) { 12905 final PackageSetting ps = it.next(); 12906 if (ps.pkg != null) { 12907 int v = ps.pkg.applicationInfo.targetSdkVersion; 12908 if (v < vers) vers = v; 12909 } 12910 } 12911 return vers; 12912 } else if (obj instanceof PackageSetting) { 12913 final PackageSetting ps = (PackageSetting) obj; 12914 if (ps.pkg != null) { 12915 return ps.pkg.applicationInfo.targetSdkVersion; 12916 } 12917 } 12918 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12919 } 12920 12921 @Override 12922 public void addPreferredActivity(IntentFilter filter, int match, 12923 ComponentName[] set, ComponentName activity, int userId) { 12924 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12925 "Adding preferred"); 12926 } 12927 12928 private void addPreferredActivityInternal(IntentFilter filter, int match, 12929 ComponentName[] set, ComponentName activity, boolean always, int userId, 12930 String opname) { 12931 // writer 12932 int callingUid = Binder.getCallingUid(); 12933 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12934 if (filter.countActions() == 0) { 12935 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12936 return; 12937 } 12938 synchronized (mPackages) { 12939 if (mContext.checkCallingOrSelfPermission( 12940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12941 != PackageManager.PERMISSION_GRANTED) { 12942 if (getUidTargetSdkVersionLockedLPr(callingUid) 12943 < Build.VERSION_CODES.FROYO) { 12944 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12945 + callingUid); 12946 return; 12947 } 12948 mContext.enforceCallingOrSelfPermission( 12949 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12950 } 12951 12952 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12953 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12954 + userId + ":"); 12955 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12956 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12957 scheduleWritePackageRestrictionsLocked(userId); 12958 } 12959 } 12960 12961 @Override 12962 public void replacePreferredActivity(IntentFilter filter, int match, 12963 ComponentName[] set, ComponentName activity, int userId) { 12964 if (filter.countActions() != 1) { 12965 throw new IllegalArgumentException( 12966 "replacePreferredActivity expects filter to have only 1 action."); 12967 } 12968 if (filter.countDataAuthorities() != 0 12969 || filter.countDataPaths() != 0 12970 || filter.countDataSchemes() > 1 12971 || filter.countDataTypes() != 0) { 12972 throw new IllegalArgumentException( 12973 "replacePreferredActivity expects filter to have no data authorities, " + 12974 "paths, or types; and at most one scheme."); 12975 } 12976 12977 final int callingUid = Binder.getCallingUid(); 12978 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12979 synchronized (mPackages) { 12980 if (mContext.checkCallingOrSelfPermission( 12981 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12982 != PackageManager.PERMISSION_GRANTED) { 12983 if (getUidTargetSdkVersionLockedLPr(callingUid) 12984 < Build.VERSION_CODES.FROYO) { 12985 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12986 + Binder.getCallingUid()); 12987 return; 12988 } 12989 mContext.enforceCallingOrSelfPermission( 12990 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12991 } 12992 12993 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12994 if (pir != null) { 12995 // Get all of the existing entries that exactly match this filter. 12996 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12997 if (existing != null && existing.size() == 1) { 12998 PreferredActivity cur = existing.get(0); 12999 if (DEBUG_PREFERRED) { 13000 Slog.i(TAG, "Checking replace of preferred:"); 13001 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13002 if (!cur.mPref.mAlways) { 13003 Slog.i(TAG, " -- CUR; not mAlways!"); 13004 } else { 13005 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13006 Slog.i(TAG, " -- CUR: mSet=" 13007 + Arrays.toString(cur.mPref.mSetComponents)); 13008 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13009 Slog.i(TAG, " -- NEW: mMatch=" 13010 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13011 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13012 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13013 } 13014 } 13015 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13016 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13017 && cur.mPref.sameSet(set)) { 13018 // Setting the preferred activity to what it happens to be already 13019 if (DEBUG_PREFERRED) { 13020 Slog.i(TAG, "Replacing with same preferred activity " 13021 + cur.mPref.mShortComponent + " for user " 13022 + userId + ":"); 13023 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13024 } 13025 return; 13026 } 13027 } 13028 13029 if (existing != null) { 13030 if (DEBUG_PREFERRED) { 13031 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13032 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13033 } 13034 for (int i = 0; i < existing.size(); i++) { 13035 PreferredActivity pa = existing.get(i); 13036 if (DEBUG_PREFERRED) { 13037 Slog.i(TAG, "Removing existing preferred activity " 13038 + pa.mPref.mComponent + ":"); 13039 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13040 } 13041 pir.removeFilter(pa); 13042 } 13043 } 13044 } 13045 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13046 "Replacing preferred"); 13047 } 13048 } 13049 13050 @Override 13051 public void clearPackagePreferredActivities(String packageName) { 13052 final int uid = Binder.getCallingUid(); 13053 // writer 13054 synchronized (mPackages) { 13055 PackageParser.Package pkg = mPackages.get(packageName); 13056 if (pkg == null || pkg.applicationInfo.uid != uid) { 13057 if (mContext.checkCallingOrSelfPermission( 13058 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13059 != PackageManager.PERMISSION_GRANTED) { 13060 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13061 < Build.VERSION_CODES.FROYO) { 13062 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13063 + Binder.getCallingUid()); 13064 return; 13065 } 13066 mContext.enforceCallingOrSelfPermission( 13067 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13068 } 13069 } 13070 13071 int user = UserHandle.getCallingUserId(); 13072 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13073 scheduleWritePackageRestrictionsLocked(user); 13074 } 13075 } 13076 } 13077 13078 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13079 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13080 ArrayList<PreferredActivity> removed = null; 13081 boolean changed = false; 13082 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13083 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13084 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13085 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13086 continue; 13087 } 13088 Iterator<PreferredActivity> it = pir.filterIterator(); 13089 while (it.hasNext()) { 13090 PreferredActivity pa = it.next(); 13091 // Mark entry for removal only if it matches the package name 13092 // and the entry is of type "always". 13093 if (packageName == null || 13094 (pa.mPref.mComponent.getPackageName().equals(packageName) 13095 && pa.mPref.mAlways)) { 13096 if (removed == null) { 13097 removed = new ArrayList<PreferredActivity>(); 13098 } 13099 removed.add(pa); 13100 } 13101 } 13102 if (removed != null) { 13103 for (int j=0; j<removed.size(); j++) { 13104 PreferredActivity pa = removed.get(j); 13105 pir.removeFilter(pa); 13106 } 13107 changed = true; 13108 } 13109 } 13110 return changed; 13111 } 13112 13113 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13114 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13115 if (userId == UserHandle.USER_ALL) { 13116 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13117 sUserManager.getUserIds())) { 13118 for (int oneUserId : sUserManager.getUserIds()) { 13119 scheduleWritePackageRestrictionsLocked(oneUserId); 13120 } 13121 } 13122 } else { 13123 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13124 scheduleWritePackageRestrictionsLocked(userId); 13125 } 13126 } 13127 } 13128 13129 13130 void clearDefaultBrowserIfNeeded(String packageName) { 13131 for (int oneUserId : sUserManager.getUserIds()) { 13132 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13133 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13134 if (packageName.equals(defaultBrowserPackageName)) { 13135 setDefaultBrowserPackageName(null, oneUserId); 13136 } 13137 } 13138 } 13139 13140 @Override 13141 public void resetPreferredActivities(int userId) { 13142 /* TODO: Actually use userId. Why is it being passed in? */ 13143 mContext.enforceCallingOrSelfPermission( 13144 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13145 // writer 13146 synchronized (mPackages) { 13147 int user = UserHandle.getCallingUserId(); 13148 clearPackagePreferredActivitiesLPw(null, user); 13149 mSettings.readDefaultPreferredAppsLPw(this, user); 13150 scheduleWritePackageRestrictionsLocked(user); 13151 } 13152 } 13153 13154 @Override 13155 public int getPreferredActivities(List<IntentFilter> outFilters, 13156 List<ComponentName> outActivities, String packageName) { 13157 13158 int num = 0; 13159 final int userId = UserHandle.getCallingUserId(); 13160 // reader 13161 synchronized (mPackages) { 13162 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13163 if (pir != null) { 13164 final Iterator<PreferredActivity> it = pir.filterIterator(); 13165 while (it.hasNext()) { 13166 final PreferredActivity pa = it.next(); 13167 if (packageName == null 13168 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13169 && pa.mPref.mAlways)) { 13170 if (outFilters != null) { 13171 outFilters.add(new IntentFilter(pa)); 13172 } 13173 if (outActivities != null) { 13174 outActivities.add(pa.mPref.mComponent); 13175 } 13176 } 13177 } 13178 } 13179 } 13180 13181 return num; 13182 } 13183 13184 @Override 13185 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13186 int userId) { 13187 int callingUid = Binder.getCallingUid(); 13188 if (callingUid != Process.SYSTEM_UID) { 13189 throw new SecurityException( 13190 "addPersistentPreferredActivity can only be run by the system"); 13191 } 13192 if (filter.countActions() == 0) { 13193 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13194 return; 13195 } 13196 synchronized (mPackages) { 13197 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13198 " :"); 13199 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13200 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13201 new PersistentPreferredActivity(filter, activity)); 13202 scheduleWritePackageRestrictionsLocked(userId); 13203 } 13204 } 13205 13206 @Override 13207 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13208 int callingUid = Binder.getCallingUid(); 13209 if (callingUid != Process.SYSTEM_UID) { 13210 throw new SecurityException( 13211 "clearPackagePersistentPreferredActivities can only be run by the system"); 13212 } 13213 ArrayList<PersistentPreferredActivity> removed = null; 13214 boolean changed = false; 13215 synchronized (mPackages) { 13216 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13217 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13218 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13219 .valueAt(i); 13220 if (userId != thisUserId) { 13221 continue; 13222 } 13223 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13224 while (it.hasNext()) { 13225 PersistentPreferredActivity ppa = it.next(); 13226 // Mark entry for removal only if it matches the package name. 13227 if (ppa.mComponent.getPackageName().equals(packageName)) { 13228 if (removed == null) { 13229 removed = new ArrayList<PersistentPreferredActivity>(); 13230 } 13231 removed.add(ppa); 13232 } 13233 } 13234 if (removed != null) { 13235 for (int j=0; j<removed.size(); j++) { 13236 PersistentPreferredActivity ppa = removed.get(j); 13237 ppir.removeFilter(ppa); 13238 } 13239 changed = true; 13240 } 13241 } 13242 13243 if (changed) { 13244 scheduleWritePackageRestrictionsLocked(userId); 13245 } 13246 } 13247 } 13248 13249 /** 13250 * Non-Binder method, support for the backup/restore mechanism: write the 13251 * full set of preferred activities in its canonical XML format. Returns true 13252 * on success; false otherwise. 13253 */ 13254 @Override 13255 public byte[] getPreferredActivityBackup(int userId) { 13256 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13257 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13258 } 13259 13260 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13261 try { 13262 final XmlSerializer serializer = new FastXmlSerializer(); 13263 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13264 serializer.startDocument(null, true); 13265 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13266 13267 synchronized (mPackages) { 13268 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13269 } 13270 13271 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13272 serializer.endDocument(); 13273 serializer.flush(); 13274 } catch (Exception e) { 13275 if (DEBUG_BACKUP) { 13276 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13277 } 13278 return null; 13279 } 13280 13281 return dataStream.toByteArray(); 13282 } 13283 13284 @Override 13285 public void restorePreferredActivities(byte[] backup, int userId) { 13286 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13287 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13288 } 13289 13290 try { 13291 final XmlPullParser parser = Xml.newPullParser(); 13292 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13293 13294 int type; 13295 while ((type = parser.next()) != XmlPullParser.START_TAG 13296 && type != XmlPullParser.END_DOCUMENT) { 13297 } 13298 if (type != XmlPullParser.START_TAG) { 13299 // oops didn't find a start tag?! 13300 if (DEBUG_BACKUP) { 13301 Slog.e(TAG, "Didn't find start tag during restore"); 13302 } 13303 return; 13304 } 13305 13306 // this is supposed to be TAG_PREFERRED_BACKUP 13307 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13308 if (DEBUG_BACKUP) { 13309 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13310 } 13311 return; 13312 } 13313 13314 // skip interfering stuff, then we're aligned with the backing implementation 13315 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13316 synchronized (mPackages) { 13317 mSettings.readPreferredActivitiesLPw(parser, userId); 13318 } 13319 } catch (Exception e) { 13320 if (DEBUG_BACKUP) { 13321 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13322 } 13323 } 13324 } 13325 13326 @Override 13327 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13328 int sourceUserId, int targetUserId, int flags) { 13329 mContext.enforceCallingOrSelfPermission( 13330 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13331 int callingUid = Binder.getCallingUid(); 13332 enforceOwnerRights(ownerPackage, callingUid); 13333 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13334 if (intentFilter.countActions() == 0) { 13335 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13336 return; 13337 } 13338 synchronized (mPackages) { 13339 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13340 ownerPackage, targetUserId, flags); 13341 CrossProfileIntentResolver resolver = 13342 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13343 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13344 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13345 if (existing != null) { 13346 int size = existing.size(); 13347 for (int i = 0; i < size; i++) { 13348 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13349 return; 13350 } 13351 } 13352 } 13353 resolver.addFilter(newFilter); 13354 scheduleWritePackageRestrictionsLocked(sourceUserId); 13355 } 13356 } 13357 13358 @Override 13359 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13360 mContext.enforceCallingOrSelfPermission( 13361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13362 int callingUid = Binder.getCallingUid(); 13363 enforceOwnerRights(ownerPackage, callingUid); 13364 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13365 synchronized (mPackages) { 13366 CrossProfileIntentResolver resolver = 13367 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13368 ArraySet<CrossProfileIntentFilter> set = 13369 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13370 for (CrossProfileIntentFilter filter : set) { 13371 if (filter.getOwnerPackage().equals(ownerPackage)) { 13372 resolver.removeFilter(filter); 13373 } 13374 } 13375 scheduleWritePackageRestrictionsLocked(sourceUserId); 13376 } 13377 } 13378 13379 // Enforcing that callingUid is owning pkg on userId 13380 private void enforceOwnerRights(String pkg, int callingUid) { 13381 // The system owns everything. 13382 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13383 return; 13384 } 13385 int callingUserId = UserHandle.getUserId(callingUid); 13386 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13387 if (pi == null) { 13388 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13389 + callingUserId); 13390 } 13391 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13392 throw new SecurityException("Calling uid " + callingUid 13393 + " does not own package " + pkg); 13394 } 13395 } 13396 13397 @Override 13398 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13399 Intent intent = new Intent(Intent.ACTION_MAIN); 13400 intent.addCategory(Intent.CATEGORY_HOME); 13401 13402 final int callingUserId = UserHandle.getCallingUserId(); 13403 List<ResolveInfo> list = queryIntentActivities(intent, null, 13404 PackageManager.GET_META_DATA, callingUserId); 13405 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13406 true, false, false, callingUserId); 13407 13408 allHomeCandidates.clear(); 13409 if (list != null) { 13410 for (ResolveInfo ri : list) { 13411 allHomeCandidates.add(ri); 13412 } 13413 } 13414 return (preferred == null || preferred.activityInfo == null) 13415 ? null 13416 : new ComponentName(preferred.activityInfo.packageName, 13417 preferred.activityInfo.name); 13418 } 13419 13420 @Override 13421 public void setApplicationEnabledSetting(String appPackageName, 13422 int newState, int flags, int userId, String callingPackage) { 13423 if (!sUserManager.exists(userId)) return; 13424 if (callingPackage == null) { 13425 callingPackage = Integer.toString(Binder.getCallingUid()); 13426 } 13427 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13428 } 13429 13430 @Override 13431 public void setComponentEnabledSetting(ComponentName componentName, 13432 int newState, int flags, int userId) { 13433 if (!sUserManager.exists(userId)) return; 13434 setEnabledSetting(componentName.getPackageName(), 13435 componentName.getClassName(), newState, flags, userId, null); 13436 } 13437 13438 private void setEnabledSetting(final String packageName, String className, int newState, 13439 final int flags, int userId, String callingPackage) { 13440 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13441 || newState == COMPONENT_ENABLED_STATE_ENABLED 13442 || newState == COMPONENT_ENABLED_STATE_DISABLED 13443 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13444 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13445 throw new IllegalArgumentException("Invalid new component state: " 13446 + newState); 13447 } 13448 PackageSetting pkgSetting; 13449 final int uid = Binder.getCallingUid(); 13450 final int permission = mContext.checkCallingOrSelfPermission( 13451 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13452 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13453 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13454 boolean sendNow = false; 13455 boolean isApp = (className == null); 13456 String componentName = isApp ? packageName : className; 13457 int packageUid = -1; 13458 ArrayList<String> components; 13459 13460 // writer 13461 synchronized (mPackages) { 13462 pkgSetting = mSettings.mPackages.get(packageName); 13463 if (pkgSetting == null) { 13464 if (className == null) { 13465 throw new IllegalArgumentException( 13466 "Unknown package: " + packageName); 13467 } 13468 throw new IllegalArgumentException( 13469 "Unknown component: " + packageName 13470 + "/" + className); 13471 } 13472 // Allow root and verify that userId is not being specified by a different user 13473 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13474 throw new SecurityException( 13475 "Permission Denial: attempt to change component state from pid=" 13476 + Binder.getCallingPid() 13477 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13478 } 13479 if (className == null) { 13480 // We're dealing with an application/package level state change 13481 if (pkgSetting.getEnabled(userId) == newState) { 13482 // Nothing to do 13483 return; 13484 } 13485 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13486 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13487 // Don't care about who enables an app. 13488 callingPackage = null; 13489 } 13490 pkgSetting.setEnabled(newState, userId, callingPackage); 13491 // pkgSetting.pkg.mSetEnabled = newState; 13492 } else { 13493 // We're dealing with a component level state change 13494 // First, verify that this is a valid class name. 13495 PackageParser.Package pkg = pkgSetting.pkg; 13496 if (pkg == null || !pkg.hasComponentClassName(className)) { 13497 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13498 throw new IllegalArgumentException("Component class " + className 13499 + " does not exist in " + packageName); 13500 } else { 13501 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13502 + className + " does not exist in " + packageName); 13503 } 13504 } 13505 switch (newState) { 13506 case COMPONENT_ENABLED_STATE_ENABLED: 13507 if (!pkgSetting.enableComponentLPw(className, userId)) { 13508 return; 13509 } 13510 break; 13511 case COMPONENT_ENABLED_STATE_DISABLED: 13512 if (!pkgSetting.disableComponentLPw(className, userId)) { 13513 return; 13514 } 13515 break; 13516 case COMPONENT_ENABLED_STATE_DEFAULT: 13517 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13518 return; 13519 } 13520 break; 13521 default: 13522 Slog.e(TAG, "Invalid new component state: " + newState); 13523 return; 13524 } 13525 } 13526 scheduleWritePackageRestrictionsLocked(userId); 13527 components = mPendingBroadcasts.get(userId, packageName); 13528 final boolean newPackage = components == null; 13529 if (newPackage) { 13530 components = new ArrayList<String>(); 13531 } 13532 if (!components.contains(componentName)) { 13533 components.add(componentName); 13534 } 13535 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13536 sendNow = true; 13537 // Purge entry from pending broadcast list if another one exists already 13538 // since we are sending one right away. 13539 mPendingBroadcasts.remove(userId, packageName); 13540 } else { 13541 if (newPackage) { 13542 mPendingBroadcasts.put(userId, packageName, components); 13543 } 13544 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13545 // Schedule a message 13546 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13547 } 13548 } 13549 } 13550 13551 long callingId = Binder.clearCallingIdentity(); 13552 try { 13553 if (sendNow) { 13554 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13555 sendPackageChangedBroadcast(packageName, 13556 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13557 } 13558 } finally { 13559 Binder.restoreCallingIdentity(callingId); 13560 } 13561 } 13562 13563 private void sendPackageChangedBroadcast(String packageName, 13564 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13565 if (DEBUG_INSTALL) 13566 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13567 + componentNames); 13568 Bundle extras = new Bundle(4); 13569 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13570 String nameList[] = new String[componentNames.size()]; 13571 componentNames.toArray(nameList); 13572 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13573 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13574 extras.putInt(Intent.EXTRA_UID, packageUid); 13575 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13576 new int[] {UserHandle.getUserId(packageUid)}); 13577 } 13578 13579 @Override 13580 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13581 if (!sUserManager.exists(userId)) return; 13582 final int uid = Binder.getCallingUid(); 13583 final int permission = mContext.checkCallingOrSelfPermission( 13584 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13585 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13586 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13587 // writer 13588 synchronized (mPackages) { 13589 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13590 allowedByPermission, uid, userId)) { 13591 scheduleWritePackageRestrictionsLocked(userId); 13592 } 13593 } 13594 } 13595 13596 @Override 13597 public String getInstallerPackageName(String packageName) { 13598 // reader 13599 synchronized (mPackages) { 13600 return mSettings.getInstallerPackageNameLPr(packageName); 13601 } 13602 } 13603 13604 @Override 13605 public int getApplicationEnabledSetting(String packageName, int userId) { 13606 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13607 int uid = Binder.getCallingUid(); 13608 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13609 // reader 13610 synchronized (mPackages) { 13611 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13612 } 13613 } 13614 13615 @Override 13616 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13617 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13618 int uid = Binder.getCallingUid(); 13619 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13620 // reader 13621 synchronized (mPackages) { 13622 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13623 } 13624 } 13625 13626 @Override 13627 public void enterSafeMode() { 13628 enforceSystemOrRoot("Only the system can request entering safe mode"); 13629 13630 if (!mSystemReady) { 13631 mSafeMode = true; 13632 } 13633 } 13634 13635 @Override 13636 public void systemReady() { 13637 mSystemReady = true; 13638 13639 // Read the compatibilty setting when the system is ready. 13640 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13641 mContext.getContentResolver(), 13642 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13643 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13644 if (DEBUG_SETTINGS) { 13645 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13646 } 13647 13648 synchronized (mPackages) { 13649 // Verify that all of the preferred activity components actually 13650 // exist. It is possible for applications to be updated and at 13651 // that point remove a previously declared activity component that 13652 // had been set as a preferred activity. We try to clean this up 13653 // the next time we encounter that preferred activity, but it is 13654 // possible for the user flow to never be able to return to that 13655 // situation so here we do a sanity check to make sure we haven't 13656 // left any junk around. 13657 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13658 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13659 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13660 removed.clear(); 13661 for (PreferredActivity pa : pir.filterSet()) { 13662 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13663 removed.add(pa); 13664 } 13665 } 13666 if (removed.size() > 0) { 13667 for (int r=0; r<removed.size(); r++) { 13668 PreferredActivity pa = removed.get(r); 13669 Slog.w(TAG, "Removing dangling preferred activity: " 13670 + pa.mPref.mComponent); 13671 pir.removeFilter(pa); 13672 } 13673 mSettings.writePackageRestrictionsLPr( 13674 mSettings.mPreferredActivities.keyAt(i)); 13675 } 13676 } 13677 } 13678 sUserManager.systemReady(); 13679 13680 // Kick off any messages waiting for system ready 13681 if (mPostSystemReadyMessages != null) { 13682 for (Message msg : mPostSystemReadyMessages) { 13683 msg.sendToTarget(); 13684 } 13685 mPostSystemReadyMessages = null; 13686 } 13687 13688 // Watch for external volumes that come and go over time 13689 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13690 storage.registerListener(mStorageListener); 13691 13692 mInstallerService.systemReady(); 13693 mPackageDexOptimizer.systemReady(); 13694 } 13695 13696 @Override 13697 public boolean isSafeMode() { 13698 return mSafeMode; 13699 } 13700 13701 @Override 13702 public boolean hasSystemUidErrors() { 13703 return mHasSystemUidErrors; 13704 } 13705 13706 static String arrayToString(int[] array) { 13707 StringBuffer buf = new StringBuffer(128); 13708 buf.append('['); 13709 if (array != null) { 13710 for (int i=0; i<array.length; i++) { 13711 if (i > 0) buf.append(", "); 13712 buf.append(array[i]); 13713 } 13714 } 13715 buf.append(']'); 13716 return buf.toString(); 13717 } 13718 13719 static class DumpState { 13720 public static final int DUMP_LIBS = 1 << 0; 13721 public static final int DUMP_FEATURES = 1 << 1; 13722 public static final int DUMP_RESOLVERS = 1 << 2; 13723 public static final int DUMP_PERMISSIONS = 1 << 3; 13724 public static final int DUMP_PACKAGES = 1 << 4; 13725 public static final int DUMP_SHARED_USERS = 1 << 5; 13726 public static final int DUMP_MESSAGES = 1 << 6; 13727 public static final int DUMP_PROVIDERS = 1 << 7; 13728 public static final int DUMP_VERIFIERS = 1 << 8; 13729 public static final int DUMP_PREFERRED = 1 << 9; 13730 public static final int DUMP_PREFERRED_XML = 1 << 10; 13731 public static final int DUMP_KEYSETS = 1 << 11; 13732 public static final int DUMP_VERSION = 1 << 12; 13733 public static final int DUMP_INSTALLS = 1 << 13; 13734 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13735 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13736 13737 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13738 13739 private int mTypes; 13740 13741 private int mOptions; 13742 13743 private boolean mTitlePrinted; 13744 13745 private SharedUserSetting mSharedUser; 13746 13747 public boolean isDumping(int type) { 13748 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13749 return true; 13750 } 13751 13752 return (mTypes & type) != 0; 13753 } 13754 13755 public void setDump(int type) { 13756 mTypes |= type; 13757 } 13758 13759 public boolean isOptionEnabled(int option) { 13760 return (mOptions & option) != 0; 13761 } 13762 13763 public void setOptionEnabled(int option) { 13764 mOptions |= option; 13765 } 13766 13767 public boolean onTitlePrinted() { 13768 final boolean printed = mTitlePrinted; 13769 mTitlePrinted = true; 13770 return printed; 13771 } 13772 13773 public boolean getTitlePrinted() { 13774 return mTitlePrinted; 13775 } 13776 13777 public void setTitlePrinted(boolean enabled) { 13778 mTitlePrinted = enabled; 13779 } 13780 13781 public SharedUserSetting getSharedUser() { 13782 return mSharedUser; 13783 } 13784 13785 public void setSharedUser(SharedUserSetting user) { 13786 mSharedUser = user; 13787 } 13788 } 13789 13790 @Override 13791 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13793 != PackageManager.PERMISSION_GRANTED) { 13794 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13795 + Binder.getCallingPid() 13796 + ", uid=" + Binder.getCallingUid() 13797 + " without permission " 13798 + android.Manifest.permission.DUMP); 13799 return; 13800 } 13801 13802 DumpState dumpState = new DumpState(); 13803 boolean fullPreferred = false; 13804 boolean checkin = false; 13805 13806 String packageName = null; 13807 13808 int opti = 0; 13809 while (opti < args.length) { 13810 String opt = args[opti]; 13811 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13812 break; 13813 } 13814 opti++; 13815 13816 if ("-a".equals(opt)) { 13817 // Right now we only know how to print all. 13818 } else if ("-h".equals(opt)) { 13819 pw.println("Package manager dump options:"); 13820 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13821 pw.println(" --checkin: dump for a checkin"); 13822 pw.println(" -f: print details of intent filters"); 13823 pw.println(" -h: print this help"); 13824 pw.println(" cmd may be one of:"); 13825 pw.println(" l[ibraries]: list known shared libraries"); 13826 pw.println(" f[ibraries]: list device features"); 13827 pw.println(" k[eysets]: print known keysets"); 13828 pw.println(" r[esolvers]: dump intent resolvers"); 13829 pw.println(" perm[issions]: dump permissions"); 13830 pw.println(" pref[erred]: print preferred package settings"); 13831 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13832 pw.println(" prov[iders]: dump content providers"); 13833 pw.println(" p[ackages]: dump installed packages"); 13834 pw.println(" s[hared-users]: dump shared user IDs"); 13835 pw.println(" m[essages]: print collected runtime messages"); 13836 pw.println(" v[erifiers]: print package verifier info"); 13837 pw.println(" version: print database version info"); 13838 pw.println(" write: write current settings now"); 13839 pw.println(" <package.name>: info about given package"); 13840 pw.println(" installs: details about install sessions"); 13841 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13842 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13843 return; 13844 } else if ("--checkin".equals(opt)) { 13845 checkin = true; 13846 } else if ("-f".equals(opt)) { 13847 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13848 } else { 13849 pw.println("Unknown argument: " + opt + "; use -h for help"); 13850 } 13851 } 13852 13853 // Is the caller requesting to dump a particular piece of data? 13854 if (opti < args.length) { 13855 String cmd = args[opti]; 13856 opti++; 13857 // Is this a package name? 13858 if ("android".equals(cmd) || cmd.contains(".")) { 13859 packageName = cmd; 13860 // When dumping a single package, we always dump all of its 13861 // filter information since the amount of data will be reasonable. 13862 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13863 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13864 dumpState.setDump(DumpState.DUMP_LIBS); 13865 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13866 dumpState.setDump(DumpState.DUMP_FEATURES); 13867 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13868 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13869 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13870 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13871 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13872 dumpState.setDump(DumpState.DUMP_PREFERRED); 13873 } else if ("preferred-xml".equals(cmd)) { 13874 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13875 if (opti < args.length && "--full".equals(args[opti])) { 13876 fullPreferred = true; 13877 opti++; 13878 } 13879 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13880 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13881 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13882 dumpState.setDump(DumpState.DUMP_PACKAGES); 13883 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13884 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13885 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13886 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13887 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13888 dumpState.setDump(DumpState.DUMP_MESSAGES); 13889 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13890 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13891 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13892 || "intent-filter-verifiers".equals(cmd)) { 13893 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13894 } else if ("version".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_VERSION); 13896 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13897 dumpState.setDump(DumpState.DUMP_KEYSETS); 13898 } else if ("installs".equals(cmd)) { 13899 dumpState.setDump(DumpState.DUMP_INSTALLS); 13900 } else if ("write".equals(cmd)) { 13901 synchronized (mPackages) { 13902 mSettings.writeLPr(); 13903 pw.println("Settings written."); 13904 return; 13905 } 13906 } 13907 } 13908 13909 if (checkin) { 13910 pw.println("vers,1"); 13911 } 13912 13913 // reader 13914 synchronized (mPackages) { 13915 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13916 if (!checkin) { 13917 if (dumpState.onTitlePrinted()) 13918 pw.println(); 13919 pw.println("Database versions:"); 13920 pw.print(" SDK Version:"); 13921 pw.print(" internal="); 13922 pw.print(mSettings.mInternalSdkPlatform); 13923 pw.print(" external="); 13924 pw.println(mSettings.mExternalSdkPlatform); 13925 pw.print(" DB Version:"); 13926 pw.print(" internal="); 13927 pw.print(mSettings.mInternalDatabaseVersion); 13928 pw.print(" external="); 13929 pw.println(mSettings.mExternalDatabaseVersion); 13930 } 13931 } 13932 13933 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13934 if (!checkin) { 13935 if (dumpState.onTitlePrinted()) 13936 pw.println(); 13937 pw.println("Verifiers:"); 13938 pw.print(" Required: "); 13939 pw.print(mRequiredVerifierPackage); 13940 pw.print(" (uid="); 13941 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13942 pw.println(")"); 13943 } else if (mRequiredVerifierPackage != null) { 13944 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13945 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13946 } 13947 } 13948 13949 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13950 packageName == null) { 13951 if (mIntentFilterVerifierComponent != null) { 13952 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13953 if (!checkin) { 13954 if (dumpState.onTitlePrinted()) 13955 pw.println(); 13956 pw.println("Intent Filter Verifier:"); 13957 pw.print(" Using: "); 13958 pw.print(verifierPackageName); 13959 pw.print(" (uid="); 13960 pw.print(getPackageUid(verifierPackageName, 0)); 13961 pw.println(")"); 13962 } else if (verifierPackageName != null) { 13963 pw.print("ifv,"); pw.print(verifierPackageName); 13964 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13965 } 13966 } else { 13967 pw.println(); 13968 pw.println("No Intent Filter Verifier available!"); 13969 } 13970 } 13971 13972 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13973 boolean printedHeader = false; 13974 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13975 while (it.hasNext()) { 13976 String name = it.next(); 13977 SharedLibraryEntry ent = mSharedLibraries.get(name); 13978 if (!checkin) { 13979 if (!printedHeader) { 13980 if (dumpState.onTitlePrinted()) 13981 pw.println(); 13982 pw.println("Libraries:"); 13983 printedHeader = true; 13984 } 13985 pw.print(" "); 13986 } else { 13987 pw.print("lib,"); 13988 } 13989 pw.print(name); 13990 if (!checkin) { 13991 pw.print(" -> "); 13992 } 13993 if (ent.path != null) { 13994 if (!checkin) { 13995 pw.print("(jar) "); 13996 pw.print(ent.path); 13997 } else { 13998 pw.print(",jar,"); 13999 pw.print(ent.path); 14000 } 14001 } else { 14002 if (!checkin) { 14003 pw.print("(apk) "); 14004 pw.print(ent.apk); 14005 } else { 14006 pw.print(",apk,"); 14007 pw.print(ent.apk); 14008 } 14009 } 14010 pw.println(); 14011 } 14012 } 14013 14014 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14015 if (dumpState.onTitlePrinted()) 14016 pw.println(); 14017 if (!checkin) { 14018 pw.println("Features:"); 14019 } 14020 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14021 while (it.hasNext()) { 14022 String name = it.next(); 14023 if (!checkin) { 14024 pw.print(" "); 14025 } else { 14026 pw.print("feat,"); 14027 } 14028 pw.println(name); 14029 } 14030 } 14031 14032 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14033 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14034 : "Activity Resolver Table:", " ", packageName, 14035 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14036 dumpState.setTitlePrinted(true); 14037 } 14038 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14039 : "Receiver Resolver Table:", " ", packageName, 14040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14041 dumpState.setTitlePrinted(true); 14042 } 14043 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14044 : "Service Resolver Table:", " ", packageName, 14045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14046 dumpState.setTitlePrinted(true); 14047 } 14048 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14049 : "Provider Resolver Table:", " ", packageName, 14050 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14051 dumpState.setTitlePrinted(true); 14052 } 14053 } 14054 14055 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14056 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14057 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14058 int user = mSettings.mPreferredActivities.keyAt(i); 14059 if (pir.dump(pw, 14060 dumpState.getTitlePrinted() 14061 ? "\nPreferred Activities User " + user + ":" 14062 : "Preferred Activities User " + user + ":", " ", 14063 packageName, true, false)) { 14064 dumpState.setTitlePrinted(true); 14065 } 14066 } 14067 } 14068 14069 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14070 pw.flush(); 14071 FileOutputStream fout = new FileOutputStream(fd); 14072 BufferedOutputStream str = new BufferedOutputStream(fout); 14073 XmlSerializer serializer = new FastXmlSerializer(); 14074 try { 14075 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14076 serializer.startDocument(null, true); 14077 serializer.setFeature( 14078 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14079 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14080 serializer.endDocument(); 14081 serializer.flush(); 14082 } catch (IllegalArgumentException e) { 14083 pw.println("Failed writing: " + e); 14084 } catch (IllegalStateException e) { 14085 pw.println("Failed writing: " + e); 14086 } catch (IOException e) { 14087 pw.println("Failed writing: " + e); 14088 } 14089 } 14090 14091 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14092 pw.println(); 14093 int count = mSettings.mPackages.size(); 14094 if (count == 0) { 14095 pw.println("No domain preferred apps!"); 14096 pw.println(); 14097 } else { 14098 final String prefix = " "; 14099 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14100 if (allPackageSettings.size() == 0) { 14101 pw.println("No domain preferred apps!"); 14102 pw.println(); 14103 } else { 14104 pw.println("Domain preferred apps status:"); 14105 pw.println(); 14106 count = 0; 14107 for (PackageSetting ps : allPackageSettings) { 14108 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14109 if (ivi == null || ivi.getPackageName() == null) continue; 14110 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14111 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14112 pw.println(prefix + "Status: " + ivi.getStatusString()); 14113 pw.println(); 14114 count++; 14115 } 14116 if (count == 0) { 14117 pw.println(prefix + "No domain preferred app status!"); 14118 pw.println(); 14119 } 14120 for (int userId : sUserManager.getUserIds()) { 14121 pw.println("Domain preferred apps for User " + userId + ":"); 14122 pw.println(); 14123 count = 0; 14124 for (PackageSetting ps : allPackageSettings) { 14125 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14126 if (ivi == null || ivi.getPackageName() == null) { 14127 continue; 14128 } 14129 final int status = ps.getDomainVerificationStatusForUser(userId); 14130 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14131 continue; 14132 } 14133 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14134 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14135 String statusStr = IntentFilterVerificationInfo. 14136 getStatusStringFromValue(status); 14137 pw.println(prefix + "Status: " + statusStr); 14138 pw.println(); 14139 count++; 14140 } 14141 if (count == 0) { 14142 pw.println(prefix + "No domain preferred apps!"); 14143 pw.println(); 14144 } 14145 } 14146 } 14147 } 14148 } 14149 14150 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14151 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14152 if (packageName == null) { 14153 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14154 if (iperm == 0) { 14155 if (dumpState.onTitlePrinted()) 14156 pw.println(); 14157 pw.println("AppOp Permissions:"); 14158 } 14159 pw.print(" AppOp Permission "); 14160 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14161 pw.println(":"); 14162 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14163 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14164 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14165 } 14166 } 14167 } 14168 } 14169 14170 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14171 boolean printedSomething = false; 14172 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14173 if (packageName != null && !packageName.equals(p.info.packageName)) { 14174 continue; 14175 } 14176 if (!printedSomething) { 14177 if (dumpState.onTitlePrinted()) 14178 pw.println(); 14179 pw.println("Registered ContentProviders:"); 14180 printedSomething = true; 14181 } 14182 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14183 pw.print(" "); pw.println(p.toString()); 14184 } 14185 printedSomething = false; 14186 for (Map.Entry<String, PackageParser.Provider> entry : 14187 mProvidersByAuthority.entrySet()) { 14188 PackageParser.Provider p = entry.getValue(); 14189 if (packageName != null && !packageName.equals(p.info.packageName)) { 14190 continue; 14191 } 14192 if (!printedSomething) { 14193 if (dumpState.onTitlePrinted()) 14194 pw.println(); 14195 pw.println("ContentProvider Authorities:"); 14196 printedSomething = true; 14197 } 14198 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14199 pw.print(" "); pw.println(p.toString()); 14200 if (p.info != null && p.info.applicationInfo != null) { 14201 final String appInfo = p.info.applicationInfo.toString(); 14202 pw.print(" applicationInfo="); pw.println(appInfo); 14203 } 14204 } 14205 } 14206 14207 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14208 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14209 } 14210 14211 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14212 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14213 } 14214 14215 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14216 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14217 } 14218 14219 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14220 // XXX should handle packageName != null by dumping only install data that 14221 // the given package is involved with. 14222 if (dumpState.onTitlePrinted()) pw.println(); 14223 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14224 } 14225 14226 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14227 if (dumpState.onTitlePrinted()) pw.println(); 14228 mSettings.dumpReadMessagesLPr(pw, dumpState); 14229 14230 pw.println(); 14231 pw.println("Package warning messages:"); 14232 BufferedReader in = null; 14233 String line = null; 14234 try { 14235 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14236 while ((line = in.readLine()) != null) { 14237 if (line.contains("ignored: updated version")) continue; 14238 pw.println(line); 14239 } 14240 } catch (IOException ignored) { 14241 } finally { 14242 IoUtils.closeQuietly(in); 14243 } 14244 } 14245 14246 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14247 BufferedReader in = null; 14248 String line = null; 14249 try { 14250 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14251 while ((line = in.readLine()) != null) { 14252 if (line.contains("ignored: updated version")) continue; 14253 pw.print("msg,"); 14254 pw.println(line); 14255 } 14256 } catch (IOException ignored) { 14257 } finally { 14258 IoUtils.closeQuietly(in); 14259 } 14260 } 14261 } 14262 } 14263 14264 // ------- apps on sdcard specific code ------- 14265 static final boolean DEBUG_SD_INSTALL = false; 14266 14267 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14268 14269 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14270 14271 private boolean mMediaMounted = false; 14272 14273 static String getEncryptKey() { 14274 try { 14275 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14276 SD_ENCRYPTION_KEYSTORE_NAME); 14277 if (sdEncKey == null) { 14278 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14279 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14280 if (sdEncKey == null) { 14281 Slog.e(TAG, "Failed to create encryption keys"); 14282 return null; 14283 } 14284 } 14285 return sdEncKey; 14286 } catch (NoSuchAlgorithmException nsae) { 14287 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14288 return null; 14289 } catch (IOException ioe) { 14290 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14291 return null; 14292 } 14293 } 14294 14295 /* 14296 * Update media status on PackageManager. 14297 */ 14298 @Override 14299 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14300 int callingUid = Binder.getCallingUid(); 14301 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14302 throw new SecurityException("Media status can only be updated by the system"); 14303 } 14304 // reader; this apparently protects mMediaMounted, but should probably 14305 // be a different lock in that case. 14306 synchronized (mPackages) { 14307 Log.i(TAG, "Updating external media status from " 14308 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14309 + (mediaStatus ? "mounted" : "unmounted")); 14310 if (DEBUG_SD_INSTALL) 14311 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14312 + ", mMediaMounted=" + mMediaMounted); 14313 if (mediaStatus == mMediaMounted) { 14314 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14315 : 0, -1); 14316 mHandler.sendMessage(msg); 14317 return; 14318 } 14319 mMediaMounted = mediaStatus; 14320 } 14321 // Queue up an async operation since the package installation may take a 14322 // little while. 14323 mHandler.post(new Runnable() { 14324 public void run() { 14325 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14326 } 14327 }); 14328 } 14329 14330 /** 14331 * Called by MountService when the initial ASECs to scan are available. 14332 * Should block until all the ASEC containers are finished being scanned. 14333 */ 14334 public void scanAvailableAsecs() { 14335 updateExternalMediaStatusInner(true, false, false); 14336 if (mShouldRestoreconData) { 14337 SELinuxMMAC.setRestoreconDone(); 14338 mShouldRestoreconData = false; 14339 } 14340 } 14341 14342 /* 14343 * Collect information of applications on external media, map them against 14344 * existing containers and update information based on current mount status. 14345 * Please note that we always have to report status if reportStatus has been 14346 * set to true especially when unloading packages. 14347 */ 14348 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14349 boolean externalStorage) { 14350 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14351 int[] uidArr = EmptyArray.INT; 14352 14353 final String[] list = PackageHelper.getSecureContainerList(); 14354 if (ArrayUtils.isEmpty(list)) { 14355 Log.i(TAG, "No secure containers found"); 14356 } else { 14357 // Process list of secure containers and categorize them 14358 // as active or stale based on their package internal state. 14359 14360 // reader 14361 synchronized (mPackages) { 14362 for (String cid : list) { 14363 // Leave stages untouched for now; installer service owns them 14364 if (PackageInstallerService.isStageName(cid)) continue; 14365 14366 if (DEBUG_SD_INSTALL) 14367 Log.i(TAG, "Processing container " + cid); 14368 String pkgName = getAsecPackageName(cid); 14369 if (pkgName == null) { 14370 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14371 continue; 14372 } 14373 if (DEBUG_SD_INSTALL) 14374 Log.i(TAG, "Looking for pkg : " + pkgName); 14375 14376 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14377 if (ps == null) { 14378 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14379 continue; 14380 } 14381 14382 /* 14383 * Skip packages that are not external if we're unmounting 14384 * external storage. 14385 */ 14386 if (externalStorage && !isMounted && !isExternal(ps)) { 14387 continue; 14388 } 14389 14390 final AsecInstallArgs args = new AsecInstallArgs(cid, 14391 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14392 // The package status is changed only if the code path 14393 // matches between settings and the container id. 14394 if (ps.codePathString != null 14395 && ps.codePathString.startsWith(args.getCodePath())) { 14396 if (DEBUG_SD_INSTALL) { 14397 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14398 + " at code path: " + ps.codePathString); 14399 } 14400 14401 // We do have a valid package installed on sdcard 14402 processCids.put(args, ps.codePathString); 14403 final int uid = ps.appId; 14404 if (uid != -1) { 14405 uidArr = ArrayUtils.appendInt(uidArr, uid); 14406 } 14407 } else { 14408 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14409 + ps.codePathString); 14410 } 14411 } 14412 } 14413 14414 Arrays.sort(uidArr); 14415 } 14416 14417 // Process packages with valid entries. 14418 if (isMounted) { 14419 if (DEBUG_SD_INSTALL) 14420 Log.i(TAG, "Loading packages"); 14421 loadMediaPackages(processCids, uidArr); 14422 startCleaningPackages(); 14423 mInstallerService.onSecureContainersAvailable(); 14424 } else { 14425 if (DEBUG_SD_INSTALL) 14426 Log.i(TAG, "Unloading packages"); 14427 unloadMediaPackages(processCids, uidArr, reportStatus); 14428 } 14429 } 14430 14431 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14432 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14433 final int size = infos.size(); 14434 final String[] packageNames = new String[size]; 14435 final int[] packageUids = new int[size]; 14436 for (int i = 0; i < size; i++) { 14437 final ApplicationInfo info = infos.get(i); 14438 packageNames[i] = info.packageName; 14439 packageUids[i] = info.uid; 14440 } 14441 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14442 finishedReceiver); 14443 } 14444 14445 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14446 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14447 sendResourcesChangedBroadcast(mediaStatus, replacing, 14448 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14449 } 14450 14451 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14452 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14453 int size = pkgList.length; 14454 if (size > 0) { 14455 // Send broadcasts here 14456 Bundle extras = new Bundle(); 14457 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14458 if (uidArr != null) { 14459 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14460 } 14461 if (replacing) { 14462 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14463 } 14464 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14465 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14466 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14467 } 14468 } 14469 14470 /* 14471 * Look at potentially valid container ids from processCids If package 14472 * information doesn't match the one on record or package scanning fails, 14473 * the cid is added to list of removeCids. We currently don't delete stale 14474 * containers. 14475 */ 14476 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14477 ArrayList<String> pkgList = new ArrayList<String>(); 14478 Set<AsecInstallArgs> keys = processCids.keySet(); 14479 14480 for (AsecInstallArgs args : keys) { 14481 String codePath = processCids.get(args); 14482 if (DEBUG_SD_INSTALL) 14483 Log.i(TAG, "Loading container : " + args.cid); 14484 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14485 try { 14486 // Make sure there are no container errors first. 14487 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14488 Slog.e(TAG, "Failed to mount cid : " + args.cid 14489 + " when installing from sdcard"); 14490 continue; 14491 } 14492 // Check code path here. 14493 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14494 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14495 + " does not match one in settings " + codePath); 14496 continue; 14497 } 14498 // Parse package 14499 int parseFlags = mDefParseFlags; 14500 if (args.isExternalAsec()) { 14501 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14502 } 14503 if (args.isFwdLocked()) { 14504 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14505 } 14506 14507 synchronized (mInstallLock) { 14508 PackageParser.Package pkg = null; 14509 try { 14510 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14511 } catch (PackageManagerException e) { 14512 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14513 } 14514 // Scan the package 14515 if (pkg != null) { 14516 /* 14517 * TODO why is the lock being held? doPostInstall is 14518 * called in other places without the lock. This needs 14519 * to be straightened out. 14520 */ 14521 // writer 14522 synchronized (mPackages) { 14523 retCode = PackageManager.INSTALL_SUCCEEDED; 14524 pkgList.add(pkg.packageName); 14525 // Post process args 14526 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14527 pkg.applicationInfo.uid); 14528 } 14529 } else { 14530 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14531 } 14532 } 14533 14534 } finally { 14535 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14536 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14537 } 14538 } 14539 } 14540 // writer 14541 synchronized (mPackages) { 14542 // If the platform SDK has changed since the last time we booted, 14543 // we need to re-grant app permission to catch any new ones that 14544 // appear. This is really a hack, and means that apps can in some 14545 // cases get permissions that the user didn't initially explicitly 14546 // allow... it would be nice to have some better way to handle 14547 // this situation. 14548 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14549 if (regrantPermissions) 14550 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14551 + mSdkVersion + "; regranting permissions for external storage"); 14552 mSettings.mExternalSdkPlatform = mSdkVersion; 14553 14554 // Make sure group IDs have been assigned, and any permission 14555 // changes in other apps are accounted for 14556 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14557 | (regrantPermissions 14558 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14559 : 0)); 14560 14561 mSettings.updateExternalDatabaseVersion(); 14562 14563 // can downgrade to reader 14564 // Persist settings 14565 mSettings.writeLPr(); 14566 } 14567 // Send a broadcast to let everyone know we are done processing 14568 if (pkgList.size() > 0) { 14569 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14570 } 14571 } 14572 14573 /* 14574 * Utility method to unload a list of specified containers 14575 */ 14576 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14577 // Just unmount all valid containers. 14578 for (AsecInstallArgs arg : cidArgs) { 14579 synchronized (mInstallLock) { 14580 arg.doPostDeleteLI(false); 14581 } 14582 } 14583 } 14584 14585 /* 14586 * Unload packages mounted on external media. This involves deleting package 14587 * data from internal structures, sending broadcasts about diabled packages, 14588 * gc'ing to free up references, unmounting all secure containers 14589 * corresponding to packages on external media, and posting a 14590 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14591 * that we always have to post this message if status has been requested no 14592 * matter what. 14593 */ 14594 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14595 final boolean reportStatus) { 14596 if (DEBUG_SD_INSTALL) 14597 Log.i(TAG, "unloading media packages"); 14598 ArrayList<String> pkgList = new ArrayList<String>(); 14599 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14600 final Set<AsecInstallArgs> keys = processCids.keySet(); 14601 for (AsecInstallArgs args : keys) { 14602 String pkgName = args.getPackageName(); 14603 if (DEBUG_SD_INSTALL) 14604 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14605 // Delete package internally 14606 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14607 synchronized (mInstallLock) { 14608 boolean res = deletePackageLI(pkgName, null, false, null, null, 14609 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14610 if (res) { 14611 pkgList.add(pkgName); 14612 } else { 14613 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14614 failedList.add(args); 14615 } 14616 } 14617 } 14618 14619 // reader 14620 synchronized (mPackages) { 14621 // We didn't update the settings after removing each package; 14622 // write them now for all packages. 14623 mSettings.writeLPr(); 14624 } 14625 14626 // We have to absolutely send UPDATED_MEDIA_STATUS only 14627 // after confirming that all the receivers processed the ordered 14628 // broadcast when packages get disabled, force a gc to clean things up. 14629 // and unload all the containers. 14630 if (pkgList.size() > 0) { 14631 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14632 new IIntentReceiver.Stub() { 14633 public void performReceive(Intent intent, int resultCode, String data, 14634 Bundle extras, boolean ordered, boolean sticky, 14635 int sendingUser) throws RemoteException { 14636 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14637 reportStatus ? 1 : 0, 1, keys); 14638 mHandler.sendMessage(msg); 14639 } 14640 }); 14641 } else { 14642 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14643 keys); 14644 mHandler.sendMessage(msg); 14645 } 14646 } 14647 14648 private void loadPrivatePackages(VolumeInfo vol) { 14649 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14650 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14651 synchronized (mInstallLock) { 14652 synchronized (mPackages) { 14653 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14654 for (PackageSetting ps : packages) { 14655 final PackageParser.Package pkg; 14656 try { 14657 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14658 loaded.add(pkg.applicationInfo); 14659 } catch (PackageManagerException e) { 14660 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14661 } 14662 } 14663 14664 // TODO: regrant any permissions that changed based since original install 14665 14666 mSettings.writeLPr(); 14667 } 14668 } 14669 14670 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14671 sendResourcesChangedBroadcast(true, false, loaded, null); 14672 } 14673 14674 private void unloadPrivatePackages(VolumeInfo vol) { 14675 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14676 synchronized (mInstallLock) { 14677 synchronized (mPackages) { 14678 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14679 for (PackageSetting ps : packages) { 14680 if (ps.pkg == null) continue; 14681 14682 final ApplicationInfo info = ps.pkg.applicationInfo; 14683 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14684 if (deletePackageLI(ps.name, null, false, null, null, 14685 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14686 unloaded.add(info); 14687 } else { 14688 Slog.w(TAG, "Failed to unload " + ps.codePath); 14689 } 14690 } 14691 14692 mSettings.writeLPr(); 14693 } 14694 } 14695 14696 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14697 sendResourcesChangedBroadcast(false, false, unloaded, null); 14698 } 14699 14700 private void unfreezePackage(String packageName) { 14701 synchronized (mPackages) { 14702 final PackageSetting ps = mSettings.mPackages.get(packageName); 14703 if (ps != null) { 14704 ps.frozen = false; 14705 } 14706 } 14707 } 14708 14709 @Override 14710 public int movePackage(final String packageName, final String volumeUuid) { 14711 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14712 14713 final int moveId = mNextMoveId.getAndIncrement(); 14714 try { 14715 movePackageInternal(packageName, volumeUuid, moveId); 14716 } catch (PackageManagerException e) { 14717 Slog.w(TAG, "Failed to move " + packageName, e); 14718 mMoveCallbacks.notifyStatusChanged(moveId, 14719 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14720 } 14721 return moveId; 14722 } 14723 14724 private void movePackageInternal(final String packageName, final String volumeUuid, 14725 final int moveId) throws PackageManagerException { 14726 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14727 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14728 final PackageManager pm = mContext.getPackageManager(); 14729 14730 final boolean currentAsec; 14731 final String currentVolumeUuid; 14732 final File codeFile; 14733 final String installerPackageName; 14734 final String packageAbiOverride; 14735 final int appId; 14736 final String seinfo; 14737 final String label; 14738 14739 // reader 14740 synchronized (mPackages) { 14741 final PackageParser.Package pkg = mPackages.get(packageName); 14742 final PackageSetting ps = mSettings.mPackages.get(packageName); 14743 if (pkg == null || ps == null) { 14744 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14745 } 14746 14747 if (pkg.applicationInfo.isSystemApp()) { 14748 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14749 "Cannot move system application"); 14750 } 14751 14752 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14753 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14754 "Package already moved to " + volumeUuid); 14755 } 14756 14757 final File probe = new File(pkg.codePath); 14758 final File probeOat = new File(probe, "oat"); 14759 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14760 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14761 "Move only supported for modern cluster style installs"); 14762 } 14763 14764 if (ps.frozen) { 14765 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14766 "Failed to move already frozen package"); 14767 } 14768 ps.frozen = true; 14769 14770 currentAsec = pkg.applicationInfo.isForwardLocked() 14771 || pkg.applicationInfo.isExternalAsec(); 14772 currentVolumeUuid = ps.volumeUuid; 14773 codeFile = new File(pkg.codePath); 14774 installerPackageName = ps.installerPackageName; 14775 packageAbiOverride = ps.cpuAbiOverrideString; 14776 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14777 seinfo = pkg.applicationInfo.seinfo; 14778 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14779 } 14780 14781 // Now that we're guarded by frozen state, kill app during move 14782 killApplication(packageName, appId, "move pkg"); 14783 14784 final Bundle extras = new Bundle(); 14785 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14786 extras.putString(Intent.EXTRA_TITLE, label); 14787 mMoveCallbacks.notifyCreated(moveId, extras); 14788 14789 int installFlags; 14790 final boolean moveCompleteApp; 14791 final File measurePath; 14792 14793 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14794 installFlags = INSTALL_INTERNAL; 14795 moveCompleteApp = !currentAsec; 14796 measurePath = Environment.getDataAppDirectory(volumeUuid); 14797 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14798 installFlags = INSTALL_EXTERNAL; 14799 moveCompleteApp = false; 14800 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14801 } else { 14802 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14803 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14804 || !volume.isMountedWritable()) { 14805 unfreezePackage(packageName); 14806 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14807 "Move location not mounted private volume"); 14808 } 14809 14810 Preconditions.checkState(!currentAsec); 14811 14812 installFlags = INSTALL_INTERNAL; 14813 moveCompleteApp = true; 14814 measurePath = Environment.getDataAppDirectory(volumeUuid); 14815 } 14816 14817 final PackageStats stats = new PackageStats(null, -1); 14818 synchronized (mInstaller) { 14819 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14820 unfreezePackage(packageName); 14821 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14822 "Failed to measure package size"); 14823 } 14824 } 14825 14826 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14827 + stats.dataSize); 14828 14829 final long startFreeBytes = measurePath.getFreeSpace(); 14830 final long sizeBytes; 14831 if (moveCompleteApp) { 14832 sizeBytes = stats.codeSize + stats.dataSize; 14833 } else { 14834 sizeBytes = stats.codeSize; 14835 } 14836 14837 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14838 unfreezePackage(packageName); 14839 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14840 "Not enough free space to move"); 14841 } 14842 14843 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14844 14845 final CountDownLatch installedLatch = new CountDownLatch(1); 14846 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14847 @Override 14848 public void onUserActionRequired(Intent intent) throws RemoteException { 14849 throw new IllegalStateException(); 14850 } 14851 14852 @Override 14853 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14854 Bundle extras) throws RemoteException { 14855 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14856 + PackageManager.installStatusToString(returnCode, msg)); 14857 14858 installedLatch.countDown(); 14859 14860 // Regardless of success or failure of the move operation, 14861 // always unfreeze the package 14862 unfreezePackage(packageName); 14863 14864 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14865 switch (status) { 14866 case PackageInstaller.STATUS_SUCCESS: 14867 mMoveCallbacks.notifyStatusChanged(moveId, 14868 PackageManager.MOVE_SUCCEEDED); 14869 break; 14870 case PackageInstaller.STATUS_FAILURE_STORAGE: 14871 mMoveCallbacks.notifyStatusChanged(moveId, 14872 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14873 break; 14874 default: 14875 mMoveCallbacks.notifyStatusChanged(moveId, 14876 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14877 break; 14878 } 14879 } 14880 }; 14881 14882 final MoveInfo move; 14883 if (moveCompleteApp) { 14884 // Kick off a thread to report progress estimates 14885 new Thread() { 14886 @Override 14887 public void run() { 14888 while (true) { 14889 try { 14890 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14891 break; 14892 } 14893 } catch (InterruptedException ignored) { 14894 } 14895 14896 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14897 final int progress = 10 + (int) MathUtils.constrain( 14898 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14899 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14900 } 14901 } 14902 }.start(); 14903 14904 final String dataAppName = codeFile.getName(); 14905 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14906 dataAppName, appId, seinfo); 14907 } else { 14908 move = null; 14909 } 14910 14911 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14912 14913 final Message msg = mHandler.obtainMessage(INIT_COPY); 14914 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14915 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14916 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14917 mHandler.sendMessage(msg); 14918 } 14919 14920 @Override 14921 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14923 14924 final int realMoveId = mNextMoveId.getAndIncrement(); 14925 final Bundle extras = new Bundle(); 14926 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14927 mMoveCallbacks.notifyCreated(realMoveId, extras); 14928 14929 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14930 @Override 14931 public void onCreated(int moveId, Bundle extras) { 14932 // Ignored 14933 } 14934 14935 @Override 14936 public void onStatusChanged(int moveId, int status, long estMillis) { 14937 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14938 } 14939 }; 14940 14941 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14942 storage.setPrimaryStorageUuid(volumeUuid, callback); 14943 return realMoveId; 14944 } 14945 14946 @Override 14947 public int getMoveStatus(int moveId) { 14948 mContext.enforceCallingOrSelfPermission( 14949 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14950 return mMoveCallbacks.mLastStatus.get(moveId); 14951 } 14952 14953 @Override 14954 public void registerMoveCallback(IPackageMoveObserver callback) { 14955 mContext.enforceCallingOrSelfPermission( 14956 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14957 mMoveCallbacks.register(callback); 14958 } 14959 14960 @Override 14961 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14962 mContext.enforceCallingOrSelfPermission( 14963 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14964 mMoveCallbacks.unregister(callback); 14965 } 14966 14967 @Override 14968 public boolean setInstallLocation(int loc) { 14969 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14970 null); 14971 if (getInstallLocation() == loc) { 14972 return true; 14973 } 14974 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14975 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14976 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14977 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14978 return true; 14979 } 14980 return false; 14981 } 14982 14983 @Override 14984 public int getInstallLocation() { 14985 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14986 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14987 PackageHelper.APP_INSTALL_AUTO); 14988 } 14989 14990 /** Called by UserManagerService */ 14991 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14992 mDirtyUsers.remove(userHandle); 14993 mSettings.removeUserLPw(userHandle); 14994 mPendingBroadcasts.remove(userHandle); 14995 if (mInstaller != null) { 14996 // Technically, we shouldn't be doing this with the package lock 14997 // held. However, this is very rare, and there is already so much 14998 // other disk I/O going on, that we'll let it slide for now. 14999 final StorageManager storage = StorageManager.from(mContext); 15000 final List<VolumeInfo> vols = storage.getVolumes(); 15001 for (VolumeInfo vol : vols) { 15002 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15003 final String volumeUuid = vol.getFsUuid(); 15004 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15005 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15006 } 15007 } 15008 } 15009 mUserNeedsBadging.delete(userHandle); 15010 removeUnusedPackagesLILPw(userManager, userHandle); 15011 } 15012 15013 /** 15014 * We're removing userHandle and would like to remove any downloaded packages 15015 * that are no longer in use by any other user. 15016 * @param userHandle the user being removed 15017 */ 15018 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15019 final boolean DEBUG_CLEAN_APKS = false; 15020 int [] users = userManager.getUserIdsLPr(); 15021 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15022 while (psit.hasNext()) { 15023 PackageSetting ps = psit.next(); 15024 if (ps.pkg == null) { 15025 continue; 15026 } 15027 final String packageName = ps.pkg.packageName; 15028 // Skip over if system app 15029 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15030 continue; 15031 } 15032 if (DEBUG_CLEAN_APKS) { 15033 Slog.i(TAG, "Checking package " + packageName); 15034 } 15035 boolean keep = false; 15036 for (int i = 0; i < users.length; i++) { 15037 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15038 keep = true; 15039 if (DEBUG_CLEAN_APKS) { 15040 Slog.i(TAG, " Keeping package " + packageName + " for user " 15041 + users[i]); 15042 } 15043 break; 15044 } 15045 } 15046 if (!keep) { 15047 if (DEBUG_CLEAN_APKS) { 15048 Slog.i(TAG, " Removing package " + packageName); 15049 } 15050 mHandler.post(new Runnable() { 15051 public void run() { 15052 deletePackageX(packageName, userHandle, 0); 15053 } //end run 15054 }); 15055 } 15056 } 15057 } 15058 15059 /** Called by UserManagerService */ 15060 void createNewUserLILPw(int userHandle, File path) { 15061 if (mInstaller != null) { 15062 mInstaller.createUserConfig(userHandle); 15063 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15064 } 15065 } 15066 15067 void newUserCreatedLILPw(int userHandle) { 15068 // Adding a user requires updating runtime permissions for system apps. 15069 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15070 } 15071 15072 @Override 15073 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15074 mContext.enforceCallingOrSelfPermission( 15075 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15076 "Only package verification agents can read the verifier device identity"); 15077 15078 synchronized (mPackages) { 15079 return mSettings.getVerifierDeviceIdentityLPw(); 15080 } 15081 } 15082 15083 @Override 15084 public void setPermissionEnforced(String permission, boolean enforced) { 15085 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15086 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15087 synchronized (mPackages) { 15088 if (mSettings.mReadExternalStorageEnforced == null 15089 || mSettings.mReadExternalStorageEnforced != enforced) { 15090 mSettings.mReadExternalStorageEnforced = enforced; 15091 mSettings.writeLPr(); 15092 } 15093 } 15094 // kill any non-foreground processes so we restart them and 15095 // grant/revoke the GID. 15096 final IActivityManager am = ActivityManagerNative.getDefault(); 15097 if (am != null) { 15098 final long token = Binder.clearCallingIdentity(); 15099 try { 15100 am.killProcessesBelowForeground("setPermissionEnforcement"); 15101 } catch (RemoteException e) { 15102 } finally { 15103 Binder.restoreCallingIdentity(token); 15104 } 15105 } 15106 } else { 15107 throw new IllegalArgumentException("No selective enforcement for " + permission); 15108 } 15109 } 15110 15111 @Override 15112 @Deprecated 15113 public boolean isPermissionEnforced(String permission) { 15114 return true; 15115 } 15116 15117 @Override 15118 public boolean isStorageLow() { 15119 final long token = Binder.clearCallingIdentity(); 15120 try { 15121 final DeviceStorageMonitorInternal 15122 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15123 if (dsm != null) { 15124 return dsm.isMemoryLow(); 15125 } else { 15126 return false; 15127 } 15128 } finally { 15129 Binder.restoreCallingIdentity(token); 15130 } 15131 } 15132 15133 @Override 15134 public IPackageInstaller getPackageInstaller() { 15135 return mInstallerService; 15136 } 15137 15138 private boolean userNeedsBadging(int userId) { 15139 int index = mUserNeedsBadging.indexOfKey(userId); 15140 if (index < 0) { 15141 final UserInfo userInfo; 15142 final long token = Binder.clearCallingIdentity(); 15143 try { 15144 userInfo = sUserManager.getUserInfo(userId); 15145 } finally { 15146 Binder.restoreCallingIdentity(token); 15147 } 15148 final boolean b; 15149 if (userInfo != null && userInfo.isManagedProfile()) { 15150 b = true; 15151 } else { 15152 b = false; 15153 } 15154 mUserNeedsBadging.put(userId, b); 15155 return b; 15156 } 15157 return mUserNeedsBadging.valueAt(index); 15158 } 15159 15160 @Override 15161 public KeySet getKeySetByAlias(String packageName, String alias) { 15162 if (packageName == null || alias == null) { 15163 return null; 15164 } 15165 synchronized(mPackages) { 15166 final PackageParser.Package pkg = mPackages.get(packageName); 15167 if (pkg == null) { 15168 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15169 throw new IllegalArgumentException("Unknown package: " + packageName); 15170 } 15171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15172 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15173 } 15174 } 15175 15176 @Override 15177 public KeySet getSigningKeySet(String packageName) { 15178 if (packageName == null) { 15179 return null; 15180 } 15181 synchronized(mPackages) { 15182 final PackageParser.Package pkg = mPackages.get(packageName); 15183 if (pkg == null) { 15184 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15185 throw new IllegalArgumentException("Unknown package: " + packageName); 15186 } 15187 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15188 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15189 throw new SecurityException("May not access signing KeySet of other apps."); 15190 } 15191 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15192 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15193 } 15194 } 15195 15196 @Override 15197 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15198 if (packageName == null || ks == null) { 15199 return false; 15200 } 15201 synchronized(mPackages) { 15202 final PackageParser.Package pkg = mPackages.get(packageName); 15203 if (pkg == null) { 15204 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15205 throw new IllegalArgumentException("Unknown package: " + packageName); 15206 } 15207 IBinder ksh = ks.getToken(); 15208 if (ksh instanceof KeySetHandle) { 15209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15210 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15211 } 15212 return false; 15213 } 15214 } 15215 15216 @Override 15217 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15218 if (packageName == null || ks == null) { 15219 return false; 15220 } 15221 synchronized(mPackages) { 15222 final PackageParser.Package pkg = mPackages.get(packageName); 15223 if (pkg == null) { 15224 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15225 throw new IllegalArgumentException("Unknown package: " + packageName); 15226 } 15227 IBinder ksh = ks.getToken(); 15228 if (ksh instanceof KeySetHandle) { 15229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15230 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15231 } 15232 return false; 15233 } 15234 } 15235 15236 public void getUsageStatsIfNoPackageUsageInfo() { 15237 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15238 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15239 if (usm == null) { 15240 throw new IllegalStateException("UsageStatsManager must be initialized"); 15241 } 15242 long now = System.currentTimeMillis(); 15243 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15244 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15245 String packageName = entry.getKey(); 15246 PackageParser.Package pkg = mPackages.get(packageName); 15247 if (pkg == null) { 15248 continue; 15249 } 15250 UsageStats usage = entry.getValue(); 15251 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15252 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15253 } 15254 } 15255 } 15256 15257 /** 15258 * Check and throw if the given before/after packages would be considered a 15259 * downgrade. 15260 */ 15261 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15262 throws PackageManagerException { 15263 if (after.versionCode < before.mVersionCode) { 15264 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15265 "Update version code " + after.versionCode + " is older than current " 15266 + before.mVersionCode); 15267 } else if (after.versionCode == before.mVersionCode) { 15268 if (after.baseRevisionCode < before.baseRevisionCode) { 15269 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15270 "Update base revision code " + after.baseRevisionCode 15271 + " is older than current " + before.baseRevisionCode); 15272 } 15273 15274 if (!ArrayUtils.isEmpty(after.splitNames)) { 15275 for (int i = 0; i < after.splitNames.length; i++) { 15276 final String splitName = after.splitNames[i]; 15277 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15278 if (j != -1) { 15279 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15280 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15281 "Update split " + splitName + " revision code " 15282 + after.splitRevisionCodes[i] + " is older than current " 15283 + before.splitRevisionCodes[j]); 15284 } 15285 } 15286 } 15287 } 15288 } 15289 } 15290 15291 private static class MoveCallbacks extends Handler { 15292 private static final int MSG_CREATED = 1; 15293 private static final int MSG_STATUS_CHANGED = 2; 15294 15295 private final RemoteCallbackList<IPackageMoveObserver> 15296 mCallbacks = new RemoteCallbackList<>(); 15297 15298 private final SparseIntArray mLastStatus = new SparseIntArray(); 15299 15300 public MoveCallbacks(Looper looper) { 15301 super(looper); 15302 } 15303 15304 public void register(IPackageMoveObserver callback) { 15305 mCallbacks.register(callback); 15306 } 15307 15308 public void unregister(IPackageMoveObserver callback) { 15309 mCallbacks.unregister(callback); 15310 } 15311 15312 @Override 15313 public void handleMessage(Message msg) { 15314 final SomeArgs args = (SomeArgs) msg.obj; 15315 final int n = mCallbacks.beginBroadcast(); 15316 for (int i = 0; i < n; i++) { 15317 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15318 try { 15319 invokeCallback(callback, msg.what, args); 15320 } catch (RemoteException ignored) { 15321 } 15322 } 15323 mCallbacks.finishBroadcast(); 15324 args.recycle(); 15325 } 15326 15327 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15328 throws RemoteException { 15329 switch (what) { 15330 case MSG_CREATED: { 15331 callback.onCreated(args.argi1, (Bundle) args.arg2); 15332 break; 15333 } 15334 case MSG_STATUS_CHANGED: { 15335 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15336 break; 15337 } 15338 } 15339 } 15340 15341 private void notifyCreated(int moveId, Bundle extras) { 15342 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15343 15344 final SomeArgs args = SomeArgs.obtain(); 15345 args.argi1 = moveId; 15346 args.arg2 = extras; 15347 obtainMessage(MSG_CREATED, args).sendToTarget(); 15348 } 15349 15350 private void notifyStatusChanged(int moveId, int status) { 15351 notifyStatusChanged(moveId, status, -1); 15352 } 15353 15354 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15355 Slog.v(TAG, "Move " + moveId + " status " + status); 15356 15357 final SomeArgs args = SomeArgs.obtain(); 15358 args.argi1 = moveId; 15359 args.argi2 = status; 15360 args.arg3 = estMillis; 15361 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15362 15363 synchronized (mLastStatus) { 15364 mLastStatus.put(moveId, status); 15365 } 15366 } 15367 } 15368 15369 private final class OnPermissionChangeListeners extends Handler { 15370 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15371 15372 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15373 new RemoteCallbackList<>(); 15374 15375 public OnPermissionChangeListeners(Looper looper) { 15376 super(looper); 15377 } 15378 15379 @Override 15380 public void handleMessage(Message msg) { 15381 switch (msg.what) { 15382 case MSG_ON_PERMISSIONS_CHANGED: { 15383 final int uid = msg.arg1; 15384 handleOnPermissionsChanged(uid); 15385 } break; 15386 } 15387 } 15388 15389 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15390 mPermissionListeners.register(listener); 15391 15392 } 15393 15394 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15395 mPermissionListeners.unregister(listener); 15396 } 15397 15398 public void onPermissionsChanged(int uid) { 15399 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15400 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15401 } 15402 } 15403 15404 private void handleOnPermissionsChanged(int uid) { 15405 final int count = mPermissionListeners.beginBroadcast(); 15406 try { 15407 for (int i = 0; i < count; i++) { 15408 IOnPermissionsChangeListener callback = mPermissionListeners 15409 .getBroadcastItem(i); 15410 try { 15411 callback.onPermissionsChanged(uid); 15412 } catch (RemoteException e) { 15413 Log.e(TAG, "Permission listener is dead", e); 15414 } 15415 } 15416 } finally { 15417 mPermissionListeners.finishBroadcast(); 15418 } 15419 } 15420 } 15421} 15422