PackageManagerService.java revision 13ae6679e1d68263f9196de1bcf7cf16c0f6599f
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 1589 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1590 SettingBase sb = (SettingBase) pkg.mExtras; 1591 if (sb == null) { 1592 return; 1593 } 1594 1595 PermissionsState permissionsState = sb.getPermissionsState(); 1596 1597 for (String permission : pkg.requestedPermissions) { 1598 BasePermission bp = mSettings.mPermissions.get(permission); 1599 if (bp != null && bp.isRuntime()) { 1600 permissionsState.grantRuntimePermission(bp, userId); 1601 } 1602 } 1603 } 1604 1605 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1606 Bundle extras = null; 1607 switch (res.returnCode) { 1608 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1609 extras = new Bundle(); 1610 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1611 res.origPermission); 1612 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1613 res.origPackage); 1614 break; 1615 } 1616 case PackageManager.INSTALL_SUCCEEDED: { 1617 extras = new Bundle(); 1618 extras.putBoolean(Intent.EXTRA_REPLACING, 1619 res.removedInfo != null && res.removedInfo.removedPackage != null); 1620 break; 1621 } 1622 } 1623 return extras; 1624 } 1625 1626 void scheduleWriteSettingsLocked() { 1627 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1628 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1629 } 1630 } 1631 1632 void scheduleWritePackageRestrictionsLocked(int userId) { 1633 if (!sUserManager.exists(userId)) return; 1634 mDirtyUsers.add(userId); 1635 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1636 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1637 } 1638 } 1639 1640 public static PackageManagerService main(Context context, Installer installer, 1641 boolean factoryTest, boolean onlyCore) { 1642 PackageManagerService m = new PackageManagerService(context, installer, 1643 factoryTest, onlyCore); 1644 ServiceManager.addService("package", m); 1645 return m; 1646 } 1647 1648 static String[] splitString(String str, char sep) { 1649 int count = 1; 1650 int i = 0; 1651 while ((i=str.indexOf(sep, i)) >= 0) { 1652 count++; 1653 i++; 1654 } 1655 1656 String[] res = new String[count]; 1657 i=0; 1658 count = 0; 1659 int lastI=0; 1660 while ((i=str.indexOf(sep, i)) >= 0) { 1661 res[count] = str.substring(lastI, i); 1662 count++; 1663 i++; 1664 lastI = i; 1665 } 1666 res[count] = str.substring(lastI, str.length()); 1667 return res; 1668 } 1669 1670 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1671 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1672 Context.DISPLAY_SERVICE); 1673 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1674 } 1675 1676 public PackageManagerService(Context context, Installer installer, 1677 boolean factoryTest, boolean onlyCore) { 1678 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1679 SystemClock.uptimeMillis()); 1680 1681 if (mSdkVersion <= 0) { 1682 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1683 } 1684 1685 mContext = context; 1686 mFactoryTest = factoryTest; 1687 mOnlyCore = onlyCore; 1688 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1689 mMetrics = new DisplayMetrics(); 1690 mSettings = new Settings(mPackages); 1691 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1702 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1703 1704 // TODO: add a property to control this? 1705 long dexOptLRUThresholdInMinutes; 1706 if (mLazyDexOpt) { 1707 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1708 } else { 1709 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1710 } 1711 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1712 1713 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1714 if (separateProcesses != null && separateProcesses.length() > 0) { 1715 if ("*".equals(separateProcesses)) { 1716 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1717 mSeparateProcesses = null; 1718 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1719 } else { 1720 mDefParseFlags = 0; 1721 mSeparateProcesses = separateProcesses.split(","); 1722 Slog.w(TAG, "Running with debug.separate_processes: " 1723 + separateProcesses); 1724 } 1725 } else { 1726 mDefParseFlags = 0; 1727 mSeparateProcesses = null; 1728 } 1729 1730 mInstaller = installer; 1731 mPackageDexOptimizer = new PackageDexOptimizer(this); 1732 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1733 1734 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1735 FgThread.get().getLooper()); 1736 1737 getDefaultDisplayMetrics(context, mMetrics); 1738 1739 SystemConfig systemConfig = SystemConfig.getInstance(); 1740 mGlobalGids = systemConfig.getGlobalGids(); 1741 mSystemPermissions = systemConfig.getSystemPermissions(); 1742 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1743 1744 synchronized (mInstallLock) { 1745 // writer 1746 synchronized (mPackages) { 1747 mHandlerThread = new ServiceThread(TAG, 1748 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1749 mHandlerThread.start(); 1750 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1751 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1752 1753 File dataDir = Environment.getDataDirectory(); 1754 mAppDataDir = new File(dataDir, "data"); 1755 mAppInstallDir = new File(dataDir, "app"); 1756 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1757 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1758 mUserAppDataDir = new File(dataDir, "user"); 1759 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1760 1761 sUserManager = new UserManagerService(context, this, 1762 mInstallLock, mPackages); 1763 1764 // Propagate permission configuration in to package manager. 1765 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1766 = systemConfig.getPermissions(); 1767 for (int i=0; i<permConfig.size(); i++) { 1768 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1769 BasePermission bp = mSettings.mPermissions.get(perm.name); 1770 if (bp == null) { 1771 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1772 mSettings.mPermissions.put(perm.name, bp); 1773 } 1774 if (perm.gids != null) { 1775 bp.setGids(perm.gids, perm.perUser); 1776 } 1777 } 1778 1779 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1780 for (int i=0; i<libConfig.size(); i++) { 1781 mSharedLibraries.put(libConfig.keyAt(i), 1782 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1783 } 1784 1785 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1786 1787 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1788 mSdkVersion, mOnlyCore); 1789 1790 String customResolverActivity = Resources.getSystem().getString( 1791 R.string.config_customResolverActivity); 1792 if (TextUtils.isEmpty(customResolverActivity)) { 1793 customResolverActivity = null; 1794 } else { 1795 mCustomResolverComponentName = ComponentName.unflattenFromString( 1796 customResolverActivity); 1797 } 1798 1799 long startTime = SystemClock.uptimeMillis(); 1800 1801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1802 startTime); 1803 1804 // Set flag to monitor and not change apk file paths when 1805 // scanning install directories. 1806 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1807 1808 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1809 1810 /** 1811 * Add everything in the in the boot class path to the 1812 * list of process files because dexopt will have been run 1813 * if necessary during zygote startup. 1814 */ 1815 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1816 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1817 1818 if (bootClassPath != null) { 1819 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1820 for (String element : bootClassPathElements) { 1821 alreadyDexOpted.add(element); 1822 } 1823 } else { 1824 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1825 } 1826 1827 if (systemServerClassPath != null) { 1828 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1829 for (String element : systemServerClassPathElements) { 1830 alreadyDexOpted.add(element); 1831 } 1832 } else { 1833 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1834 } 1835 1836 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1837 final String[] dexCodeInstructionSets = 1838 getDexCodeInstructionSets( 1839 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1840 1841 /** 1842 * Ensure all external libraries have had dexopt run on them. 1843 */ 1844 if (mSharedLibraries.size() > 0) { 1845 // NOTE: For now, we're compiling these system "shared libraries" 1846 // (and framework jars) into all available architectures. It's possible 1847 // to compile them only when we come across an app that uses them (there's 1848 // already logic for that in scanPackageLI) but that adds some complexity. 1849 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1850 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1851 final String lib = libEntry.path; 1852 if (lib == null) { 1853 continue; 1854 } 1855 1856 try { 1857 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1858 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1859 alreadyDexOpted.add(lib); 1860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1861 } 1862 } catch (FileNotFoundException e) { 1863 Slog.w(TAG, "Library not found: " + lib); 1864 } catch (IOException e) { 1865 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1866 + e.getMessage()); 1867 } 1868 } 1869 } 1870 } 1871 1872 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1873 1874 // Gross hack for now: we know this file doesn't contain any 1875 // code, so don't dexopt it to avoid the resulting log spew. 1876 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1877 1878 // Gross hack for now: we know this file is only part of 1879 // the boot class path for art, so don't dexopt it to 1880 // avoid the resulting log spew. 1881 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1882 1883 /** 1884 * There are a number of commands implemented in Java, which 1885 * we currently need to do the dexopt on so that they can be 1886 * run from a non-root shell. 1887 */ 1888 String[] frameworkFiles = frameworkDir.list(); 1889 if (frameworkFiles != null) { 1890 // TODO: We could compile these only for the most preferred ABI. We should 1891 // first double check that the dex files for these commands are not referenced 1892 // by other system apps. 1893 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1894 for (int i=0; i<frameworkFiles.length; i++) { 1895 File libPath = new File(frameworkDir, frameworkFiles[i]); 1896 String path = libPath.getPath(); 1897 // Skip the file if we already did it. 1898 if (alreadyDexOpted.contains(path)) { 1899 continue; 1900 } 1901 // Skip the file if it is not a type we want to dexopt. 1902 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1903 continue; 1904 } 1905 try { 1906 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1907 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1908 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1909 } 1910 } catch (FileNotFoundException e) { 1911 Slog.w(TAG, "Jar not found: " + path); 1912 } catch (IOException e) { 1913 Slog.w(TAG, "Exception reading jar: " + path, e); 1914 } 1915 } 1916 } 1917 } 1918 1919 // Collect vendor overlay packages. 1920 // (Do this before scanning any apps.) 1921 // For security and version matching reason, only consider 1922 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1923 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1924 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1925 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1926 1927 // Find base frameworks (resource packages without code). 1928 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR 1930 | PackageParser.PARSE_IS_PRIVILEGED, 1931 scanFlags | SCAN_NO_DEX, 0); 1932 1933 // Collected privileged system packages. 1934 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1935 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1936 | PackageParser.PARSE_IS_SYSTEM_DIR 1937 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1938 1939 // Collect ordinary system packages. 1940 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1941 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1942 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1943 1944 // Collect all vendor packages. 1945 File vendorAppDir = new File("/vendor/app"); 1946 try { 1947 vendorAppDir = vendorAppDir.getCanonicalFile(); 1948 } catch (IOException e) { 1949 // failed to look up canonical path, continue with original one 1950 } 1951 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1952 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1953 1954 // Collect all OEM packages. 1955 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1956 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1957 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1958 1959 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1960 mInstaller.moveFiles(); 1961 1962 // Prune any system packages that no longer exist. 1963 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1964 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1965 if (!mOnlyCore) { 1966 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1967 while (psit.hasNext()) { 1968 PackageSetting ps = psit.next(); 1969 1970 /* 1971 * If this is not a system app, it can't be a 1972 * disable system app. 1973 */ 1974 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1975 continue; 1976 } 1977 1978 /* 1979 * If the package is scanned, it's not erased. 1980 */ 1981 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1982 if (scannedPkg != null) { 1983 /* 1984 * If the system app is both scanned and in the 1985 * disabled packages list, then it must have been 1986 * added via OTA. Remove it from the currently 1987 * scanned package so the previously user-installed 1988 * application can be scanned. 1989 */ 1990 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1991 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1992 + ps.name + "; removing system app. Last known codePath=" 1993 + ps.codePathString + ", installStatus=" + ps.installStatus 1994 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1995 + scannedPkg.mVersionCode); 1996 removePackageLI(ps, true); 1997 expectingBetter.put(ps.name, ps.codePath); 1998 } 1999 2000 continue; 2001 } 2002 2003 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2004 psit.remove(); 2005 logCriticalInfo(Log.WARN, "System package " + ps.name 2006 + " no longer exists; wiping its data"); 2007 removeDataDirsLI(null, ps.name); 2008 } else { 2009 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2010 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2011 possiblyDeletedUpdatedSystemApps.add(ps.name); 2012 } 2013 } 2014 } 2015 } 2016 2017 //look for any incomplete package installations 2018 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2019 //clean up list 2020 for(int i = 0; i < deletePkgsList.size(); i++) { 2021 //clean up here 2022 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2023 } 2024 //delete tmp files 2025 deleteTempPackageFiles(); 2026 2027 // Remove any shared userIDs that have no associated packages 2028 mSettings.pruneSharedUsersLPw(); 2029 2030 if (!mOnlyCore) { 2031 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2032 SystemClock.uptimeMillis()); 2033 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2034 2035 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2036 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2037 2038 /** 2039 * Remove disable package settings for any updated system 2040 * apps that were removed via an OTA. If they're not a 2041 * previously-updated app, remove them completely. 2042 * Otherwise, just revoke their system-level permissions. 2043 */ 2044 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2045 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2046 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2047 2048 String msg; 2049 if (deletedPkg == null) { 2050 msg = "Updated system package " + deletedAppName 2051 + " no longer exists; wiping its data"; 2052 removeDataDirsLI(null, deletedAppName); 2053 } else { 2054 msg = "Updated system app + " + deletedAppName 2055 + " no longer present; removing system privileges for " 2056 + deletedAppName; 2057 2058 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2059 2060 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2061 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2062 } 2063 logCriticalInfo(Log.WARN, msg); 2064 } 2065 2066 /** 2067 * Make sure all system apps that we expected to appear on 2068 * the userdata partition actually showed up. If they never 2069 * appeared, crawl back and revive the system version. 2070 */ 2071 for (int i = 0; i < expectingBetter.size(); i++) { 2072 final String packageName = expectingBetter.keyAt(i); 2073 if (!mPackages.containsKey(packageName)) { 2074 final File scanFile = expectingBetter.valueAt(i); 2075 2076 logCriticalInfo(Log.WARN, "Expected better " + packageName 2077 + " but never showed up; reverting to system"); 2078 2079 final int reparseFlags; 2080 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR 2083 | PackageParser.PARSE_IS_PRIVILEGED; 2084 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2085 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR; 2087 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2088 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR; 2090 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2091 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR; 2093 } else { 2094 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2095 continue; 2096 } 2097 2098 mSettings.enableSystemPackageLPw(packageName); 2099 2100 try { 2101 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2102 } catch (PackageManagerException e) { 2103 Slog.e(TAG, "Failed to parse original system package: " 2104 + e.getMessage()); 2105 } 2106 } 2107 } 2108 } 2109 2110 // Now that we know all of the shared libraries, update all clients to have 2111 // the correct library paths. 2112 updateAllSharedLibrariesLPw(); 2113 2114 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2115 // NOTE: We ignore potential failures here during a system scan (like 2116 // the rest of the commands above) because there's precious little we 2117 // can do about it. A settings error is reported, though. 2118 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2119 false /* force dexopt */, false /* defer dexopt */); 2120 } 2121 2122 // Now that we know all the packages we are keeping, 2123 // read and update their last usage times. 2124 mPackageUsage.readLP(); 2125 2126 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2127 SystemClock.uptimeMillis()); 2128 Slog.i(TAG, "Time to scan packages: " 2129 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2130 + " seconds"); 2131 2132 // If the platform SDK has changed since the last time we booted, 2133 // we need to re-grant app permission to catch any new ones that 2134 // appear. This is really a hack, and means that apps can in some 2135 // cases get permissions that the user didn't initially explicitly 2136 // allow... it would be nice to have some better way to handle 2137 // this situation. 2138 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2139 != mSdkVersion; 2140 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2141 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2142 + "; regranting permissions for internal storage"); 2143 mSettings.mInternalSdkPlatform = mSdkVersion; 2144 2145 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2146 | (regrantPermissions 2147 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2148 : 0)); 2149 2150 // If this is the first boot, and it is a normal boot, then 2151 // we need to initialize the default preferred apps. 2152 if (!mRestoredSettings && !onlyCore) { 2153 mSettings.readDefaultPreferredAppsLPw(this, 0); 2154 } 2155 2156 // If this is first boot after an OTA, and a normal boot, then 2157 // we need to clear code cache directories. 2158 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2159 if (mIsUpgrade && !onlyCore) { 2160 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2161 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2162 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2163 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2164 } 2165 mSettings.mFingerprint = Build.FINGERPRINT; 2166 } 2167 2168 primeDomainVerificationsLPw(); 2169 checkDefaultBrowser(); 2170 2171 // All the changes are done during package scanning. 2172 mSettings.updateInternalDatabaseVersion(); 2173 2174 // can downgrade to reader 2175 mSettings.writeLPr(); 2176 2177 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2178 SystemClock.uptimeMillis()); 2179 2180 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2181 2182 mInstallerService = new PackageInstallerService(context, this); 2183 2184 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2185 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2186 mIntentFilterVerifierComponent); 2187 2188 } // synchronized (mPackages) 2189 } // synchronized (mInstallLock) 2190 2191 // Now after opening every single application zip, make sure they 2192 // are all flushed. Not really needed, but keeps things nice and 2193 // tidy. 2194 Runtime.getRuntime().gc(); 2195 } 2196 2197 @Override 2198 public boolean isFirstBoot() { 2199 return !mRestoredSettings; 2200 } 2201 2202 @Override 2203 public boolean isOnlyCoreApps() { 2204 return mOnlyCore; 2205 } 2206 2207 @Override 2208 public boolean isUpgrade() { 2209 return mIsUpgrade; 2210 } 2211 2212 private String getRequiredVerifierLPr() { 2213 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2214 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2215 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2216 2217 String requiredVerifier = null; 2218 2219 final int N = receivers.size(); 2220 for (int i = 0; i < N; i++) { 2221 final ResolveInfo info = receivers.get(i); 2222 2223 if (info.activityInfo == null) { 2224 continue; 2225 } 2226 2227 final String packageName = info.activityInfo.packageName; 2228 2229 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2230 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2231 continue; 2232 } 2233 2234 if (requiredVerifier != null) { 2235 throw new RuntimeException("There can be only one required verifier"); 2236 } 2237 2238 requiredVerifier = packageName; 2239 } 2240 2241 return requiredVerifier; 2242 } 2243 2244 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2245 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2246 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2247 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2248 2249 ComponentName verifierComponentName = null; 2250 2251 int priority = -1000; 2252 final int N = receivers.size(); 2253 for (int i = 0; i < N; i++) { 2254 final ResolveInfo info = receivers.get(i); 2255 2256 if (info.activityInfo == null) { 2257 continue; 2258 } 2259 2260 final String packageName = info.activityInfo.packageName; 2261 2262 final PackageSetting ps = mSettings.mPackages.get(packageName); 2263 if (ps == null) { 2264 continue; 2265 } 2266 2267 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2268 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2269 continue; 2270 } 2271 2272 // Select the IntentFilterVerifier with the highest priority 2273 if (priority < info.priority) { 2274 priority = info.priority; 2275 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2276 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2277 + verifierComponentName + " with priority: " + info.priority); 2278 } 2279 } 2280 2281 return verifierComponentName; 2282 } 2283 2284 private void primeDomainVerificationsLPw() { 2285 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2286 boolean updated = false; 2287 ArraySet<String> allHostsSet = new ArraySet<>(); 2288 for (PackageParser.Package pkg : mPackages.values()) { 2289 final String packageName = pkg.packageName; 2290 if (!hasDomainURLs(pkg)) { 2291 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2292 "package with no domain URLs: " + packageName); 2293 continue; 2294 } 2295 if (!pkg.isSystemApp()) { 2296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2297 "No priming domain verifications for a non system package : " + 2298 packageName); 2299 continue; 2300 } 2301 for (PackageParser.Activity a : pkg.activities) { 2302 for (ActivityIntentInfo filter : a.intents) { 2303 if (hasValidDomains(filter)) { 2304 allHostsSet.addAll(filter.getHostsList()); 2305 } 2306 } 2307 } 2308 if (allHostsSet.size() == 0) { 2309 allHostsSet.add("*"); 2310 } 2311 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2312 IntentFilterVerificationInfo ivi = 2313 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2314 if (ivi != null) { 2315 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2316 "Priming domain verifications for package: " + packageName + 2317 " with hosts:" + ivi.getDomainsString()); 2318 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2319 updated = true; 2320 } 2321 else { 2322 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2323 "No priming domain verifications for package: " + packageName); 2324 } 2325 allHostsSet.clear(); 2326 } 2327 if (updated) { 2328 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2329 "Will need to write primed domain verifications"); 2330 } 2331 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2332 } 2333 2334 private void checkDefaultBrowser() { 2335 final int myUserId = UserHandle.myUserId(); 2336 final String packageName = getDefaultBrowserPackageName(myUserId); 2337 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2338 if (info == null) { 2339 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2340 packageName); 2341 setDefaultBrowserPackageName(null, myUserId); 2342 } 2343 } 2344 2345 @Override 2346 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2347 throws RemoteException { 2348 try { 2349 return super.onTransact(code, data, reply, flags); 2350 } catch (RuntimeException e) { 2351 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2352 Slog.wtf(TAG, "Package Manager Crash", e); 2353 } 2354 throw e; 2355 } 2356 } 2357 2358 void cleanupInstallFailedPackage(PackageSetting ps) { 2359 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2360 2361 removeDataDirsLI(ps.volumeUuid, ps.name); 2362 if (ps.codePath != null) { 2363 if (ps.codePath.isDirectory()) { 2364 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2365 } else { 2366 ps.codePath.delete(); 2367 } 2368 } 2369 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2370 if (ps.resourcePath.isDirectory()) { 2371 FileUtils.deleteContents(ps.resourcePath); 2372 } 2373 ps.resourcePath.delete(); 2374 } 2375 mSettings.removePackageLPw(ps.name); 2376 } 2377 2378 static int[] appendInts(int[] cur, int[] add) { 2379 if (add == null) return cur; 2380 if (cur == null) return add; 2381 final int N = add.length; 2382 for (int i=0; i<N; i++) { 2383 cur = appendInt(cur, add[i]); 2384 } 2385 return cur; 2386 } 2387 2388 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2389 if (!sUserManager.exists(userId)) return null; 2390 final PackageSetting ps = (PackageSetting) p.mExtras; 2391 if (ps == null) { 2392 return null; 2393 } 2394 2395 final PermissionsState permissionsState = ps.getPermissionsState(); 2396 2397 final int[] gids = permissionsState.computeGids(userId); 2398 final Set<String> permissions = permissionsState.getPermissions(userId); 2399 final PackageUserState state = ps.readUserState(userId); 2400 2401 return PackageParser.generatePackageInfo(p, gids, flags, 2402 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2403 } 2404 2405 @Override 2406 public boolean isPackageFrozen(String packageName) { 2407 synchronized (mPackages) { 2408 final PackageSetting ps = mSettings.mPackages.get(packageName); 2409 if (ps != null) { 2410 return ps.frozen; 2411 } 2412 } 2413 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2414 return true; 2415 } 2416 2417 @Override 2418 public boolean isPackageAvailable(String packageName, int userId) { 2419 if (!sUserManager.exists(userId)) return false; 2420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2421 synchronized (mPackages) { 2422 PackageParser.Package p = mPackages.get(packageName); 2423 if (p != null) { 2424 final PackageSetting ps = (PackageSetting) p.mExtras; 2425 if (ps != null) { 2426 final PackageUserState state = ps.readUserState(userId); 2427 if (state != null) { 2428 return PackageParser.isAvailable(state); 2429 } 2430 } 2431 } 2432 } 2433 return false; 2434 } 2435 2436 @Override 2437 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2438 if (!sUserManager.exists(userId)) return null; 2439 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2440 // reader 2441 synchronized (mPackages) { 2442 PackageParser.Package p = mPackages.get(packageName); 2443 if (DEBUG_PACKAGE_INFO) 2444 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2445 if (p != null) { 2446 return generatePackageInfo(p, flags, userId); 2447 } 2448 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2449 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2450 } 2451 } 2452 return null; 2453 } 2454 2455 @Override 2456 public String[] currentToCanonicalPackageNames(String[] names) { 2457 String[] out = new String[names.length]; 2458 // reader 2459 synchronized (mPackages) { 2460 for (int i=names.length-1; i>=0; i--) { 2461 PackageSetting ps = mSettings.mPackages.get(names[i]); 2462 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2463 } 2464 } 2465 return out; 2466 } 2467 2468 @Override 2469 public String[] canonicalToCurrentPackageNames(String[] names) { 2470 String[] out = new String[names.length]; 2471 // reader 2472 synchronized (mPackages) { 2473 for (int i=names.length-1; i>=0; i--) { 2474 String cur = mSettings.mRenamedPackages.get(names[i]); 2475 out[i] = cur != null ? cur : names[i]; 2476 } 2477 } 2478 return out; 2479 } 2480 2481 @Override 2482 public int getPackageUid(String packageName, int userId) { 2483 if (!sUserManager.exists(userId)) return -1; 2484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2485 2486 // reader 2487 synchronized (mPackages) { 2488 PackageParser.Package p = mPackages.get(packageName); 2489 if(p != null) { 2490 return UserHandle.getUid(userId, p.applicationInfo.uid); 2491 } 2492 PackageSetting ps = mSettings.mPackages.get(packageName); 2493 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2494 return -1; 2495 } 2496 p = ps.pkg; 2497 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2498 } 2499 } 2500 2501 @Override 2502 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2503 if (!sUserManager.exists(userId)) { 2504 return null; 2505 } 2506 2507 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2508 "getPackageGids"); 2509 2510 // reader 2511 synchronized (mPackages) { 2512 PackageParser.Package p = mPackages.get(packageName); 2513 if (DEBUG_PACKAGE_INFO) { 2514 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2515 } 2516 if (p != null) { 2517 PackageSetting ps = (PackageSetting) p.mExtras; 2518 return ps.getPermissionsState().computeGids(userId); 2519 } 2520 } 2521 2522 return null; 2523 } 2524 2525 static PermissionInfo generatePermissionInfo( 2526 BasePermission bp, int flags) { 2527 if (bp.perm != null) { 2528 return PackageParser.generatePermissionInfo(bp.perm, flags); 2529 } 2530 PermissionInfo pi = new PermissionInfo(); 2531 pi.name = bp.name; 2532 pi.packageName = bp.sourcePackage; 2533 pi.nonLocalizedLabel = bp.name; 2534 pi.protectionLevel = bp.protectionLevel; 2535 return pi; 2536 } 2537 2538 @Override 2539 public PermissionInfo getPermissionInfo(String name, int flags) { 2540 // reader 2541 synchronized (mPackages) { 2542 final BasePermission p = mSettings.mPermissions.get(name); 2543 if (p != null) { 2544 return generatePermissionInfo(p, flags); 2545 } 2546 return null; 2547 } 2548 } 2549 2550 @Override 2551 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2552 // reader 2553 synchronized (mPackages) { 2554 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2555 for (BasePermission p : mSettings.mPermissions.values()) { 2556 if (group == null) { 2557 if (p.perm == null || p.perm.info.group == null) { 2558 out.add(generatePermissionInfo(p, flags)); 2559 } 2560 } else { 2561 if (p.perm != null && group.equals(p.perm.info.group)) { 2562 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2563 } 2564 } 2565 } 2566 2567 if (out.size() > 0) { 2568 return out; 2569 } 2570 return mPermissionGroups.containsKey(group) ? out : null; 2571 } 2572 } 2573 2574 @Override 2575 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2576 // reader 2577 synchronized (mPackages) { 2578 return PackageParser.generatePermissionGroupInfo( 2579 mPermissionGroups.get(name), flags); 2580 } 2581 } 2582 2583 @Override 2584 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2585 // reader 2586 synchronized (mPackages) { 2587 final int N = mPermissionGroups.size(); 2588 ArrayList<PermissionGroupInfo> out 2589 = new ArrayList<PermissionGroupInfo>(N); 2590 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2591 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2592 } 2593 return out; 2594 } 2595 } 2596 2597 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2598 int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 PackageSetting ps = mSettings.mPackages.get(packageName); 2601 if (ps != null) { 2602 if (ps.pkg == null) { 2603 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2604 flags, userId); 2605 if (pInfo != null) { 2606 return pInfo.applicationInfo; 2607 } 2608 return null; 2609 } 2610 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2611 ps.readUserState(userId), userId); 2612 } 2613 return null; 2614 } 2615 2616 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2617 int userId) { 2618 if (!sUserManager.exists(userId)) return null; 2619 PackageSetting ps = mSettings.mPackages.get(packageName); 2620 if (ps != null) { 2621 PackageParser.Package pkg = ps.pkg; 2622 if (pkg == null) { 2623 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2624 return null; 2625 } 2626 // Only data remains, so we aren't worried about code paths 2627 pkg = new PackageParser.Package(packageName); 2628 pkg.applicationInfo.packageName = packageName; 2629 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2630 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2631 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2632 packageName, userId).getAbsolutePath(); 2633 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2634 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2635 } 2636 return generatePackageInfo(pkg, flags, userId); 2637 } 2638 return null; 2639 } 2640 2641 @Override 2642 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2645 // writer 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) Log.v( 2649 TAG, "getApplicationInfo " + packageName 2650 + ": " + p); 2651 if (p != null) { 2652 PackageSetting ps = mSettings.mPackages.get(packageName); 2653 if (ps == null) return null; 2654 // Note: isEnabledLP() does not apply here - always return info 2655 return PackageParser.generateApplicationInfo( 2656 p, flags, ps.readUserState(userId), userId); 2657 } 2658 if ("android".equals(packageName)||"system".equals(packageName)) { 2659 return mAndroidApplication; 2660 } 2661 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2662 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2663 } 2664 } 2665 return null; 2666 } 2667 2668 @Override 2669 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2670 final IPackageDataObserver observer) { 2671 mContext.enforceCallingOrSelfPermission( 2672 android.Manifest.permission.CLEAR_APP_CACHE, null); 2673 // Queue up an async operation since clearing cache may take a little while. 2674 mHandler.post(new Runnable() { 2675 public void run() { 2676 mHandler.removeCallbacks(this); 2677 int retCode = -1; 2678 synchronized (mInstallLock) { 2679 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2680 if (retCode < 0) { 2681 Slog.w(TAG, "Couldn't clear application caches"); 2682 } 2683 } 2684 if (observer != null) { 2685 try { 2686 observer.onRemoveCompleted(null, (retCode >= 0)); 2687 } catch (RemoteException e) { 2688 Slog.w(TAG, "RemoveException when invoking call back"); 2689 } 2690 } 2691 } 2692 }); 2693 } 2694 2695 @Override 2696 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2697 final IntentSender pi) { 2698 mContext.enforceCallingOrSelfPermission( 2699 android.Manifest.permission.CLEAR_APP_CACHE, null); 2700 // Queue up an async operation since clearing cache may take a little while. 2701 mHandler.post(new Runnable() { 2702 public void run() { 2703 mHandler.removeCallbacks(this); 2704 int retCode = -1; 2705 synchronized (mInstallLock) { 2706 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2707 if (retCode < 0) { 2708 Slog.w(TAG, "Couldn't clear application caches"); 2709 } 2710 } 2711 if(pi != null) { 2712 try { 2713 // Callback via pending intent 2714 int code = (retCode >= 0) ? 1 : 0; 2715 pi.sendIntent(null, code, null, 2716 null, null); 2717 } catch (SendIntentException e1) { 2718 Slog.i(TAG, "Failed to send pending intent"); 2719 } 2720 } 2721 } 2722 }); 2723 } 2724 2725 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2726 synchronized (mInstallLock) { 2727 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2728 throw new IOException("Failed to free enough space"); 2729 } 2730 } 2731 } 2732 2733 @Override 2734 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2737 synchronized (mPackages) { 2738 PackageParser.Activity a = mActivities.mActivities.get(component); 2739 2740 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2741 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2742 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2743 if (ps == null) return null; 2744 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2745 userId); 2746 } 2747 if (mResolveComponentName.equals(component)) { 2748 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2749 new PackageUserState(), userId); 2750 } 2751 } 2752 return null; 2753 } 2754 2755 @Override 2756 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2757 String resolvedType) { 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 if (a == null) { 2761 return false; 2762 } 2763 for (int i=0; i<a.intents.size(); i++) { 2764 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2765 intent.getData(), intent.getCategories(), TAG) >= 0) { 2766 return true; 2767 } 2768 } 2769 return false; 2770 } 2771 } 2772 2773 @Override 2774 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2775 if (!sUserManager.exists(userId)) return null; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2777 synchronized (mPackages) { 2778 PackageParser.Activity a = mReceivers.mActivities.get(component); 2779 if (DEBUG_PACKAGE_INFO) Log.v( 2780 TAG, "getReceiverInfo " + component + ": " + a); 2781 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2782 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2783 if (ps == null) return null; 2784 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2785 userId); 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2795 synchronized (mPackages) { 2796 PackageParser.Service s = mServices.mServices.get(component); 2797 if (DEBUG_PACKAGE_INFO) Log.v( 2798 TAG, "getServiceInfo " + component + ": " + s); 2799 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2800 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2801 if (ps == null) return null; 2802 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2803 userId); 2804 } 2805 } 2806 return null; 2807 } 2808 2809 @Override 2810 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2811 if (!sUserManager.exists(userId)) return null; 2812 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2813 synchronized (mPackages) { 2814 PackageParser.Provider p = mProviders.mProviders.get(component); 2815 if (DEBUG_PACKAGE_INFO) Log.v( 2816 TAG, "getProviderInfo " + component + ": " + p); 2817 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2818 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2819 if (ps == null) return null; 2820 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2821 userId); 2822 } 2823 } 2824 return null; 2825 } 2826 2827 @Override 2828 public String[] getSystemSharedLibraryNames() { 2829 Set<String> libSet; 2830 synchronized (mPackages) { 2831 libSet = mSharedLibraries.keySet(); 2832 int size = libSet.size(); 2833 if (size > 0) { 2834 String[] libs = new String[size]; 2835 libSet.toArray(libs); 2836 return libs; 2837 } 2838 } 2839 return null; 2840 } 2841 2842 /** 2843 * @hide 2844 */ 2845 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2846 synchronized (mPackages) { 2847 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2848 if (lib != null && lib.apk != null) { 2849 return mPackages.get(lib.apk); 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public FeatureInfo[] getSystemAvailableFeatures() { 2857 Collection<FeatureInfo> featSet; 2858 synchronized (mPackages) { 2859 featSet = mAvailableFeatures.values(); 2860 int size = featSet.size(); 2861 if (size > 0) { 2862 FeatureInfo[] features = new FeatureInfo[size+1]; 2863 featSet.toArray(features); 2864 FeatureInfo fi = new FeatureInfo(); 2865 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2866 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2867 features[size] = fi; 2868 return features; 2869 } 2870 } 2871 return null; 2872 } 2873 2874 @Override 2875 public boolean hasSystemFeature(String name) { 2876 synchronized (mPackages) { 2877 return mAvailableFeatures.containsKey(name); 2878 } 2879 } 2880 2881 private void checkValidCaller(int uid, int userId) { 2882 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2883 return; 2884 2885 throw new SecurityException("Caller uid=" + uid 2886 + " is not privileged to communicate with user=" + userId); 2887 } 2888 2889 @Override 2890 public int checkPermission(String permName, String pkgName, int userId) { 2891 if (!sUserManager.exists(userId)) { 2892 return PackageManager.PERMISSION_DENIED; 2893 } 2894 2895 synchronized (mPackages) { 2896 final PackageParser.Package p = mPackages.get(pkgName); 2897 if (p != null && p.mExtras != null) { 2898 final PackageSetting ps = (PackageSetting) p.mExtras; 2899 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2900 return PackageManager.PERMISSION_GRANTED; 2901 } 2902 } 2903 } 2904 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 @Override 2909 public int checkUidPermission(String permName, int uid) { 2910 final int userId = UserHandle.getUserId(uid); 2911 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2918 if (obj != null) { 2919 final SettingBase ps = (SettingBase) obj; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } else { 2924 ArraySet<String> perms = mSystemPermissions.get(uid); 2925 if (perms != null && perms.contains(permName)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } 2929 } 2930 2931 return PackageManager.PERMISSION_DENIED; 2932 } 2933 2934 /** 2935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2937 * @param checkShell TODO(yamasani): 2938 * @param message the message to log on security exception 2939 */ 2940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2941 boolean checkShell, String message) { 2942 if (userId < 0) { 2943 throw new IllegalArgumentException("Invalid userId " + userId); 2944 } 2945 if (checkShell) { 2946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2947 } 2948 if (userId == UserHandle.getUserId(callingUid)) return; 2949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2950 if (requireFullPermission) { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } else { 2954 try { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2957 } catch (SecurityException se) { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2960 } 2961 } 2962 } 2963 } 2964 2965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2966 if (callingUid == Process.SHELL_UID) { 2967 if (userHandle >= 0 2968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2969 throw new SecurityException("Shell does not have permission to access user " 2970 + userHandle); 2971 } else if (userHandle < 0) { 2972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2973 + Debug.getCallers(3)); 2974 } 2975 } 2976 } 2977 2978 private BasePermission findPermissionTreeLP(String permName) { 2979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2980 if (permName.startsWith(bp.name) && 2981 permName.length() > bp.name.length() && 2982 permName.charAt(bp.name.length()) == '.') { 2983 return bp; 2984 } 2985 } 2986 return null; 2987 } 2988 2989 private BasePermission checkPermissionTreeLP(String permName) { 2990 if (permName != null) { 2991 BasePermission bp = findPermissionTreeLP(permName); 2992 if (bp != null) { 2993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2994 return bp; 2995 } 2996 throw new SecurityException("Calling uid " 2997 + Binder.getCallingUid() 2998 + " is not allowed to add to permission tree " 2999 + bp.name + " owned by uid " + bp.uid); 3000 } 3001 } 3002 throw new SecurityException("No permission tree found for " + permName); 3003 } 3004 3005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3006 if (s1 == null) { 3007 return s2 == null; 3008 } 3009 if (s2 == null) { 3010 return false; 3011 } 3012 if (s1.getClass() != s2.getClass()) { 3013 return false; 3014 } 3015 return s1.equals(s2); 3016 } 3017 3018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3019 if (pi1.icon != pi2.icon) return false; 3020 if (pi1.logo != pi2.logo) return false; 3021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3022 if (!compareStrings(pi1.name, pi2.name)) return false; 3023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3024 // We'll take care of setting this one. 3025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3026 // These are not currently stored in settings. 3027 //if (!compareStrings(pi1.group, pi2.group)) return false; 3028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3029 //if (pi1.labelRes != pi2.labelRes) return false; 3030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3031 return true; 3032 } 3033 3034 int permissionInfoFootprint(PermissionInfo info) { 3035 int size = info.name.length(); 3036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3038 return size; 3039 } 3040 3041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3042 int size = 0; 3043 for (BasePermission perm : mSettings.mPermissions.values()) { 3044 if (perm.uid == tree.uid) { 3045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3046 } 3047 } 3048 return size; 3049 } 3050 3051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3052 // We calculate the max size of permissions defined by this uid and throw 3053 // if that plus the size of 'info' would exceed our stated maximum. 3054 if (tree.uid != Process.SYSTEM_UID) { 3055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3057 throw new SecurityException("Permission tree size cap exceeded"); 3058 } 3059 } 3060 } 3061 3062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3064 throw new SecurityException("Label must be specified in permission"); 3065 } 3066 BasePermission tree = checkPermissionTreeLP(info.name); 3067 BasePermission bp = mSettings.mPermissions.get(info.name); 3068 boolean added = bp == null; 3069 boolean changed = true; 3070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3071 if (added) { 3072 enforcePermissionCapLocked(info, tree); 3073 bp = new BasePermission(info.name, tree.sourcePackage, 3074 BasePermission.TYPE_DYNAMIC); 3075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3076 throw new SecurityException( 3077 "Not allowed to modify non-dynamic permission " 3078 + info.name); 3079 } else { 3080 if (bp.protectionLevel == fixedLevel 3081 && bp.perm.owner.equals(tree.perm.owner) 3082 && bp.uid == tree.uid 3083 && comparePermissionInfos(bp.perm.info, info)) { 3084 changed = false; 3085 } 3086 } 3087 bp.protectionLevel = fixedLevel; 3088 info = new PermissionInfo(info); 3089 info.protectionLevel = fixedLevel; 3090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3091 bp.perm.info.packageName = tree.perm.info.packageName; 3092 bp.uid = tree.uid; 3093 if (added) { 3094 mSettings.mPermissions.put(info.name, bp); 3095 } 3096 if (changed) { 3097 if (!async) { 3098 mSettings.writeLPr(); 3099 } else { 3100 scheduleWriteSettingsLocked(); 3101 } 3102 } 3103 return added; 3104 } 3105 3106 @Override 3107 public boolean addPermission(PermissionInfo info) { 3108 synchronized (mPackages) { 3109 return addPermissionLocked(info, false); 3110 } 3111 } 3112 3113 @Override 3114 public boolean addPermissionAsync(PermissionInfo info) { 3115 synchronized (mPackages) { 3116 return addPermissionLocked(info, true); 3117 } 3118 } 3119 3120 @Override 3121 public void removePermission(String name) { 3122 synchronized (mPackages) { 3123 checkPermissionTreeLP(name); 3124 BasePermission bp = mSettings.mPermissions.get(name); 3125 if (bp != null) { 3126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3127 throw new SecurityException( 3128 "Not allowed to modify non-dynamic permission " 3129 + name); 3130 } 3131 mSettings.mPermissions.remove(name); 3132 mSettings.writeLPr(); 3133 } 3134 } 3135 } 3136 3137 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3138 BasePermission bp) { 3139 int index = pkg.requestedPermissions.indexOf(bp.name); 3140 if (index == -1) { 3141 throw new SecurityException("Package " + pkg.packageName 3142 + " has not requested permission " + bp.name); 3143 } 3144 if (!bp.isRuntime()) { 3145 throw new SecurityException("Permission " + bp.name 3146 + " is not a changeable permission type"); 3147 } 3148 } 3149 3150 @Override 3151 public void grantRuntimePermission(String packageName, String name, int userId) { 3152 if (!sUserManager.exists(userId)) { 3153 Log.e(TAG, "No such user:" + userId); 3154 return; 3155 } 3156 3157 mContext.enforceCallingOrSelfPermission( 3158 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3159 "grantRuntimePermission"); 3160 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3162 "grantRuntimePermission"); 3163 3164 boolean gidsChanged = false; 3165 final SettingBase sb; 3166 3167 synchronized (mPackages) { 3168 final PackageParser.Package pkg = mPackages.get(packageName); 3169 if (pkg == null) { 3170 throw new IllegalArgumentException("Unknown package: " + packageName); 3171 } 3172 3173 final BasePermission bp = mSettings.mPermissions.get(name); 3174 if (bp == null) { 3175 throw new IllegalArgumentException("Unknown permission: " + name); 3176 } 3177 3178 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3179 3180 sb = (SettingBase) pkg.mExtras; 3181 if (sb == null) { 3182 throw new IllegalArgumentException("Unknown package: " + packageName); 3183 } 3184 3185 final PermissionsState permissionsState = sb.getPermissionsState(); 3186 3187 final int flags = permissionsState.getPermissionFlags(name, userId); 3188 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3189 throw new SecurityException("Cannot grant system fixed permission: " 3190 + name + " for package: " + packageName); 3191 } 3192 3193 final int result = permissionsState.grantRuntimePermission(bp, userId); 3194 switch (result) { 3195 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3196 return; 3197 } 3198 3199 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3200 gidsChanged = true; 3201 } break; 3202 } 3203 3204 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3205 3206 // Not critical if that is lost - app has to request again. 3207 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3208 } 3209 3210 if (gidsChanged) { 3211 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3212 } 3213 } 3214 3215 @Override 3216 public void revokeRuntimePermission(String packageName, String name, int userId) { 3217 if (!sUserManager.exists(userId)) { 3218 Log.e(TAG, "No such user:" + userId); 3219 return; 3220 } 3221 3222 mContext.enforceCallingOrSelfPermission( 3223 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3224 "revokeRuntimePermission"); 3225 3226 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3227 "revokeRuntimePermission"); 3228 3229 final SettingBase sb; 3230 3231 synchronized (mPackages) { 3232 final PackageParser.Package pkg = mPackages.get(packageName); 3233 if (pkg == null) { 3234 throw new IllegalArgumentException("Unknown package: " + packageName); 3235 } 3236 3237 final BasePermission bp = mSettings.mPermissions.get(name); 3238 if (bp == null) { 3239 throw new IllegalArgumentException("Unknown permission: " + name); 3240 } 3241 3242 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3243 3244 sb = (SettingBase) pkg.mExtras; 3245 if (sb == null) { 3246 throw new IllegalArgumentException("Unknown package: " + packageName); 3247 } 3248 3249 final PermissionsState permissionsState = sb.getPermissionsState(); 3250 3251 final int flags = permissionsState.getPermissionFlags(name, userId); 3252 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3253 throw new SecurityException("Cannot revoke system fixed permission: " 3254 + name + " for package: " + packageName); 3255 } 3256 3257 if (permissionsState.revokeRuntimePermission(bp, userId) == 3258 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3259 return; 3260 } 3261 3262 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3263 3264 // Critical, after this call app should never have the permission. 3265 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3266 } 3267 3268 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3269 } 3270 3271 @Override 3272 public int getPermissionFlags(String name, String packageName, int userId) { 3273 if (!sUserManager.exists(userId)) { 3274 return 0; 3275 } 3276 3277 mContext.enforceCallingOrSelfPermission( 3278 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3279 "getPermissionFlags"); 3280 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3282 "getPermissionFlags"); 3283 3284 synchronized (mPackages) { 3285 final PackageParser.Package pkg = mPackages.get(packageName); 3286 if (pkg == null) { 3287 throw new IllegalArgumentException("Unknown package: " + packageName); 3288 } 3289 3290 final BasePermission bp = mSettings.mPermissions.get(name); 3291 if (bp == null) { 3292 throw new IllegalArgumentException("Unknown permission: " + name); 3293 } 3294 3295 SettingBase sb = (SettingBase) pkg.mExtras; 3296 if (sb == null) { 3297 throw new IllegalArgumentException("Unknown package: " + packageName); 3298 } 3299 3300 PermissionsState permissionsState = sb.getPermissionsState(); 3301 return permissionsState.getPermissionFlags(name, userId); 3302 } 3303 } 3304 3305 @Override 3306 public void updatePermissionFlags(String name, String packageName, int flagMask, 3307 int flagValues, int userId) { 3308 if (!sUserManager.exists(userId)) { 3309 return; 3310 } 3311 3312 mContext.enforceCallingOrSelfPermission( 3313 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3314 "updatePermissionFlags"); 3315 3316 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3317 "updatePermissionFlags"); 3318 3319 // Only the system can change policy flags. 3320 if (getCallingUid() != Process.SYSTEM_UID) { 3321 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3322 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3323 } 3324 3325 // Only the package manager can change system flags. 3326 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3327 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3328 3329 synchronized (mPackages) { 3330 final PackageParser.Package pkg = mPackages.get(packageName); 3331 if (pkg == null) { 3332 throw new IllegalArgumentException("Unknown package: " + packageName); 3333 } 3334 3335 final BasePermission bp = mSettings.mPermissions.get(name); 3336 if (bp == null) { 3337 throw new IllegalArgumentException("Unknown permission: " + name); 3338 } 3339 3340 SettingBase sb = (SettingBase) pkg.mExtras; 3341 if (sb == null) { 3342 throw new IllegalArgumentException("Unknown package: " + packageName); 3343 } 3344 3345 PermissionsState permissionsState = sb.getPermissionsState(); 3346 3347 // Only the package manager can change flags for system component permissions. 3348 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3349 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3350 return; 3351 } 3352 3353 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3354 // Install and runtime permissions are stored in different places, 3355 // so figure out what permission changed and persist the change. 3356 if (permissionsState.getInstallPermissionState(name) != null) { 3357 scheduleWriteSettingsLocked(); 3358 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3359 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3360 } 3361 } 3362 } 3363 } 3364 3365 @Override 3366 public boolean shouldShowRequestPermissionRationale(String permissionName, 3367 String packageName, int userId) { 3368 if (UserHandle.getCallingUserId() != userId) { 3369 mContext.enforceCallingPermission( 3370 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3371 "canShowRequestPermissionRationale for user " + userId); 3372 } 3373 3374 final int uid = getPackageUid(packageName, userId); 3375 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3376 return false; 3377 } 3378 3379 if (checkPermission(permissionName, packageName, userId) 3380 == PackageManager.PERMISSION_GRANTED) { 3381 return false; 3382 } 3383 3384 final int flags; 3385 3386 final long identity = Binder.clearCallingIdentity(); 3387 try { 3388 flags = getPermissionFlags(permissionName, 3389 packageName, userId); 3390 } finally { 3391 Binder.restoreCallingIdentity(identity); 3392 } 3393 3394 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3395 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3396 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3397 3398 if ((flags & fixedFlags) != 0) { 3399 return false; 3400 } 3401 3402 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3403 } 3404 3405 @Override 3406 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3407 mContext.enforceCallingOrSelfPermission( 3408 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3409 "addOnPermissionsChangeListener"); 3410 3411 synchronized (mPackages) { 3412 mOnPermissionChangeListeners.addListenerLocked(listener); 3413 } 3414 } 3415 3416 @Override 3417 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3418 synchronized (mPackages) { 3419 mOnPermissionChangeListeners.removeListenerLocked(listener); 3420 } 3421 } 3422 3423 @Override 3424 public boolean isProtectedBroadcast(String actionName) { 3425 synchronized (mPackages) { 3426 return mProtectedBroadcasts.contains(actionName); 3427 } 3428 } 3429 3430 @Override 3431 public int checkSignatures(String pkg1, String pkg2) { 3432 synchronized (mPackages) { 3433 final PackageParser.Package p1 = mPackages.get(pkg1); 3434 final PackageParser.Package p2 = mPackages.get(pkg2); 3435 if (p1 == null || p1.mExtras == null 3436 || p2 == null || p2.mExtras == null) { 3437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3438 } 3439 return compareSignatures(p1.mSignatures, p2.mSignatures); 3440 } 3441 } 3442 3443 @Override 3444 public int checkUidSignatures(int uid1, int uid2) { 3445 // Map to base uids. 3446 uid1 = UserHandle.getAppId(uid1); 3447 uid2 = UserHandle.getAppId(uid2); 3448 // reader 3449 synchronized (mPackages) { 3450 Signature[] s1; 3451 Signature[] s2; 3452 Object obj = mSettings.getUserIdLPr(uid1); 3453 if (obj != null) { 3454 if (obj instanceof SharedUserSetting) { 3455 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3456 } else if (obj instanceof PackageSetting) { 3457 s1 = ((PackageSetting)obj).signatures.mSignatures; 3458 } else { 3459 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3460 } 3461 } else { 3462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3463 } 3464 obj = mSettings.getUserIdLPr(uid2); 3465 if (obj != null) { 3466 if (obj instanceof SharedUserSetting) { 3467 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3468 } else if (obj instanceof PackageSetting) { 3469 s2 = ((PackageSetting)obj).signatures.mSignatures; 3470 } else { 3471 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3472 } 3473 } else { 3474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3475 } 3476 return compareSignatures(s1, s2); 3477 } 3478 } 3479 3480 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3481 final long identity = Binder.clearCallingIdentity(); 3482 try { 3483 if (sb instanceof SharedUserSetting) { 3484 SharedUserSetting sus = (SharedUserSetting) sb; 3485 final int packageCount = sus.packages.size(); 3486 for (int i = 0; i < packageCount; i++) { 3487 PackageSetting susPs = sus.packages.valueAt(i); 3488 if (userId == UserHandle.USER_ALL) { 3489 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3490 } else { 3491 final int uid = UserHandle.getUid(userId, susPs.appId); 3492 killUid(uid, reason); 3493 } 3494 } 3495 } else if (sb instanceof PackageSetting) { 3496 PackageSetting ps = (PackageSetting) sb; 3497 if (userId == UserHandle.USER_ALL) { 3498 killApplication(ps.pkg.packageName, ps.appId, reason); 3499 } else { 3500 final int uid = UserHandle.getUid(userId, ps.appId); 3501 killUid(uid, reason); 3502 } 3503 } 3504 } finally { 3505 Binder.restoreCallingIdentity(identity); 3506 } 3507 } 3508 3509 private static void killUid(int uid, String reason) { 3510 IActivityManager am = ActivityManagerNative.getDefault(); 3511 if (am != null) { 3512 try { 3513 am.killUid(uid, reason); 3514 } catch (RemoteException e) { 3515 /* ignore - same process */ 3516 } 3517 } 3518 } 3519 3520 /** 3521 * Compares two sets of signatures. Returns: 3522 * <br /> 3523 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3524 * <br /> 3525 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3526 * <br /> 3527 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3528 * <br /> 3529 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3530 * <br /> 3531 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3532 */ 3533 static int compareSignatures(Signature[] s1, Signature[] s2) { 3534 if (s1 == null) { 3535 return s2 == null 3536 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3537 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3538 } 3539 3540 if (s2 == null) { 3541 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3542 } 3543 3544 if (s1.length != s2.length) { 3545 return PackageManager.SIGNATURE_NO_MATCH; 3546 } 3547 3548 // Since both signature sets are of size 1, we can compare without HashSets. 3549 if (s1.length == 1) { 3550 return s1[0].equals(s2[0]) ? 3551 PackageManager.SIGNATURE_MATCH : 3552 PackageManager.SIGNATURE_NO_MATCH; 3553 } 3554 3555 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3556 for (Signature sig : s1) { 3557 set1.add(sig); 3558 } 3559 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3560 for (Signature sig : s2) { 3561 set2.add(sig); 3562 } 3563 // Make sure s2 contains all signatures in s1. 3564 if (set1.equals(set2)) { 3565 return PackageManager.SIGNATURE_MATCH; 3566 } 3567 return PackageManager.SIGNATURE_NO_MATCH; 3568 } 3569 3570 /** 3571 * If the database version for this type of package (internal storage or 3572 * external storage) is less than the version where package signatures 3573 * were updated, return true. 3574 */ 3575 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3576 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3577 DatabaseVersion.SIGNATURE_END_ENTITY)) 3578 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3579 DatabaseVersion.SIGNATURE_END_ENTITY)); 3580 } 3581 3582 /** 3583 * Used for backward compatibility to make sure any packages with 3584 * certificate chains get upgraded to the new style. {@code existingSigs} 3585 * will be in the old format (since they were stored on disk from before the 3586 * system upgrade) and {@code scannedSigs} will be in the newer format. 3587 */ 3588 private int compareSignaturesCompat(PackageSignatures existingSigs, 3589 PackageParser.Package scannedPkg) { 3590 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3591 return PackageManager.SIGNATURE_NO_MATCH; 3592 } 3593 3594 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3595 for (Signature sig : existingSigs.mSignatures) { 3596 existingSet.add(sig); 3597 } 3598 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3599 for (Signature sig : scannedPkg.mSignatures) { 3600 try { 3601 Signature[] chainSignatures = sig.getChainSignatures(); 3602 for (Signature chainSig : chainSignatures) { 3603 scannedCompatSet.add(chainSig); 3604 } 3605 } catch (CertificateEncodingException e) { 3606 scannedCompatSet.add(sig); 3607 } 3608 } 3609 /* 3610 * Make sure the expanded scanned set contains all signatures in the 3611 * existing one. 3612 */ 3613 if (scannedCompatSet.equals(existingSet)) { 3614 // Migrate the old signatures to the new scheme. 3615 existingSigs.assignSignatures(scannedPkg.mSignatures); 3616 // The new KeySets will be re-added later in the scanning process. 3617 synchronized (mPackages) { 3618 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3619 } 3620 return PackageManager.SIGNATURE_MATCH; 3621 } 3622 return PackageManager.SIGNATURE_NO_MATCH; 3623 } 3624 3625 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3626 if (isExternal(scannedPkg)) { 3627 return mSettings.isExternalDatabaseVersionOlderThan( 3628 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3629 } else { 3630 return mSettings.isInternalDatabaseVersionOlderThan( 3631 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3632 } 3633 } 3634 3635 private int compareSignaturesRecover(PackageSignatures existingSigs, 3636 PackageParser.Package scannedPkg) { 3637 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3638 return PackageManager.SIGNATURE_NO_MATCH; 3639 } 3640 3641 String msg = null; 3642 try { 3643 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3644 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3645 + scannedPkg.packageName); 3646 return PackageManager.SIGNATURE_MATCH; 3647 } 3648 } catch (CertificateException e) { 3649 msg = e.getMessage(); 3650 } 3651 3652 logCriticalInfo(Log.INFO, 3653 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3654 return PackageManager.SIGNATURE_NO_MATCH; 3655 } 3656 3657 @Override 3658 public String[] getPackagesForUid(int uid) { 3659 uid = UserHandle.getAppId(uid); 3660 // reader 3661 synchronized (mPackages) { 3662 Object obj = mSettings.getUserIdLPr(uid); 3663 if (obj instanceof SharedUserSetting) { 3664 final SharedUserSetting sus = (SharedUserSetting) obj; 3665 final int N = sus.packages.size(); 3666 final String[] res = new String[N]; 3667 final Iterator<PackageSetting> it = sus.packages.iterator(); 3668 int i = 0; 3669 while (it.hasNext()) { 3670 res[i++] = it.next().name; 3671 } 3672 return res; 3673 } else if (obj instanceof PackageSetting) { 3674 final PackageSetting ps = (PackageSetting) obj; 3675 return new String[] { ps.name }; 3676 } 3677 } 3678 return null; 3679 } 3680 3681 @Override 3682 public String getNameForUid(int uid) { 3683 // reader 3684 synchronized (mPackages) { 3685 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3686 if (obj instanceof SharedUserSetting) { 3687 final SharedUserSetting sus = (SharedUserSetting) obj; 3688 return sus.name + ":" + sus.userId; 3689 } else if (obj instanceof PackageSetting) { 3690 final PackageSetting ps = (PackageSetting) obj; 3691 return ps.name; 3692 } 3693 } 3694 return null; 3695 } 3696 3697 @Override 3698 public int getUidForSharedUser(String sharedUserName) { 3699 if(sharedUserName == null) { 3700 return -1; 3701 } 3702 // reader 3703 synchronized (mPackages) { 3704 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3705 if (suid == null) { 3706 return -1; 3707 } 3708 return suid.userId; 3709 } 3710 } 3711 3712 @Override 3713 public int getFlagsForUid(int uid) { 3714 synchronized (mPackages) { 3715 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3716 if (obj instanceof SharedUserSetting) { 3717 final SharedUserSetting sus = (SharedUserSetting) obj; 3718 return sus.pkgFlags; 3719 } else if (obj instanceof PackageSetting) { 3720 final PackageSetting ps = (PackageSetting) obj; 3721 return ps.pkgFlags; 3722 } 3723 } 3724 return 0; 3725 } 3726 3727 @Override 3728 public int getPrivateFlagsForUid(int uid) { 3729 synchronized (mPackages) { 3730 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3731 if (obj instanceof SharedUserSetting) { 3732 final SharedUserSetting sus = (SharedUserSetting) obj; 3733 return sus.pkgPrivateFlags; 3734 } else if (obj instanceof PackageSetting) { 3735 final PackageSetting ps = (PackageSetting) obj; 3736 return ps.pkgPrivateFlags; 3737 } 3738 } 3739 return 0; 3740 } 3741 3742 @Override 3743 public boolean isUidPrivileged(int uid) { 3744 uid = UserHandle.getAppId(uid); 3745 // reader 3746 synchronized (mPackages) { 3747 Object obj = mSettings.getUserIdLPr(uid); 3748 if (obj instanceof SharedUserSetting) { 3749 final SharedUserSetting sus = (SharedUserSetting) obj; 3750 final Iterator<PackageSetting> it = sus.packages.iterator(); 3751 while (it.hasNext()) { 3752 if (it.next().isPrivileged()) { 3753 return true; 3754 } 3755 } 3756 } else if (obj instanceof PackageSetting) { 3757 final PackageSetting ps = (PackageSetting) obj; 3758 return ps.isPrivileged(); 3759 } 3760 } 3761 return false; 3762 } 3763 3764 @Override 3765 public String[] getAppOpPermissionPackages(String permissionName) { 3766 synchronized (mPackages) { 3767 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3768 if (pkgs == null) { 3769 return null; 3770 } 3771 return pkgs.toArray(new String[pkgs.size()]); 3772 } 3773 } 3774 3775 @Override 3776 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3777 int flags, int userId) { 3778 if (!sUserManager.exists(userId)) return null; 3779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3780 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3781 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3782 } 3783 3784 @Override 3785 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3786 IntentFilter filter, int match, ComponentName activity) { 3787 final int userId = UserHandle.getCallingUserId(); 3788 if (DEBUG_PREFERRED) { 3789 Log.v(TAG, "setLastChosenActivity intent=" + intent 3790 + " resolvedType=" + resolvedType 3791 + " flags=" + flags 3792 + " filter=" + filter 3793 + " match=" + match 3794 + " activity=" + activity); 3795 filter.dump(new PrintStreamPrinter(System.out), " "); 3796 } 3797 intent.setComponent(null); 3798 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3799 // Find any earlier preferred or last chosen entries and nuke them 3800 findPreferredActivity(intent, resolvedType, 3801 flags, query, 0, false, true, false, userId); 3802 // Add the new activity as the last chosen for this filter 3803 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3804 "Setting last chosen"); 3805 } 3806 3807 @Override 3808 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3809 final int userId = UserHandle.getCallingUserId(); 3810 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3811 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3812 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3813 false, false, false, userId); 3814 } 3815 3816 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3817 int flags, List<ResolveInfo> query, int userId) { 3818 if (query != null) { 3819 final int N = query.size(); 3820 if (N == 1) { 3821 return query.get(0); 3822 } else if (N > 1) { 3823 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3824 // If there is more than one activity with the same priority, 3825 // then let the user decide between them. 3826 ResolveInfo r0 = query.get(0); 3827 ResolveInfo r1 = query.get(1); 3828 if (DEBUG_INTENT_MATCHING || debug) { 3829 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3830 + r1.activityInfo.name + "=" + r1.priority); 3831 } 3832 // If the first activity has a higher priority, or a different 3833 // default, then it is always desireable to pick it. 3834 if (r0.priority != r1.priority 3835 || r0.preferredOrder != r1.preferredOrder 3836 || r0.isDefault != r1.isDefault) { 3837 return query.get(0); 3838 } 3839 // If we have saved a preference for a preferred activity for 3840 // this Intent, use that. 3841 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3842 flags, query, r0.priority, true, false, debug, userId); 3843 if (ri != null) { 3844 return ri; 3845 } 3846 if (userId != 0) { 3847 ri = new ResolveInfo(mResolveInfo); 3848 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3849 ri.activityInfo.applicationInfo = new ApplicationInfo( 3850 ri.activityInfo.applicationInfo); 3851 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3852 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3853 return ri; 3854 } 3855 return mResolveInfo; 3856 } 3857 } 3858 return null; 3859 } 3860 3861 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3862 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3863 final int N = query.size(); 3864 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3865 .get(userId); 3866 // Get the list of persistent preferred activities that handle the intent 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3868 List<PersistentPreferredActivity> pprefs = ppir != null 3869 ? ppir.queryIntent(intent, resolvedType, 3870 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3871 : null; 3872 if (pprefs != null && pprefs.size() > 0) { 3873 final int M = pprefs.size(); 3874 for (int i=0; i<M; i++) { 3875 final PersistentPreferredActivity ppa = pprefs.get(i); 3876 if (DEBUG_PREFERRED || debug) { 3877 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3878 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3879 + "\n component=" + ppa.mComponent); 3880 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3881 } 3882 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3883 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3884 if (DEBUG_PREFERRED || debug) { 3885 Slog.v(TAG, "Found persistent preferred activity:"); 3886 if (ai != null) { 3887 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3888 } else { 3889 Slog.v(TAG, " null"); 3890 } 3891 } 3892 if (ai == null) { 3893 // This previously registered persistent preferred activity 3894 // component is no longer known. Ignore it and do NOT remove it. 3895 continue; 3896 } 3897 for (int j=0; j<N; j++) { 3898 final ResolveInfo ri = query.get(j); 3899 if (!ri.activityInfo.applicationInfo.packageName 3900 .equals(ai.applicationInfo.packageName)) { 3901 continue; 3902 } 3903 if (!ri.activityInfo.name.equals(ai.name)) { 3904 continue; 3905 } 3906 // Found a persistent preference that can handle the intent. 3907 if (DEBUG_PREFERRED || debug) { 3908 Slog.v(TAG, "Returning persistent preferred activity: " + 3909 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3910 } 3911 return ri; 3912 } 3913 } 3914 } 3915 return null; 3916 } 3917 3918 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3919 List<ResolveInfo> query, int priority, boolean always, 3920 boolean removeMatches, boolean debug, int userId) { 3921 if (!sUserManager.exists(userId)) return null; 3922 // writer 3923 synchronized (mPackages) { 3924 if (intent.getSelector() != null) { 3925 intent = intent.getSelector(); 3926 } 3927 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3928 3929 // Try to find a matching persistent preferred activity. 3930 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3931 debug, userId); 3932 3933 // If a persistent preferred activity matched, use it. 3934 if (pri != null) { 3935 return pri; 3936 } 3937 3938 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3939 // Get the list of preferred activities that handle the intent 3940 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3941 List<PreferredActivity> prefs = pir != null 3942 ? pir.queryIntent(intent, resolvedType, 3943 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3944 : null; 3945 if (prefs != null && prefs.size() > 0) { 3946 boolean changed = false; 3947 try { 3948 // First figure out how good the original match set is. 3949 // We will only allow preferred activities that came 3950 // from the same match quality. 3951 int match = 0; 3952 3953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3954 3955 final int N = query.size(); 3956 for (int j=0; j<N; j++) { 3957 final ResolveInfo ri = query.get(j); 3958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3959 + ": 0x" + Integer.toHexString(match)); 3960 if (ri.match > match) { 3961 match = ri.match; 3962 } 3963 } 3964 3965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3966 + Integer.toHexString(match)); 3967 3968 match &= IntentFilter.MATCH_CATEGORY_MASK; 3969 final int M = prefs.size(); 3970 for (int i=0; i<M; i++) { 3971 final PreferredActivity pa = prefs.get(i); 3972 if (DEBUG_PREFERRED || debug) { 3973 Slog.v(TAG, "Checking PreferredActivity ds=" 3974 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3975 + "\n component=" + pa.mPref.mComponent); 3976 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3977 } 3978 if (pa.mPref.mMatch != match) { 3979 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3980 + Integer.toHexString(pa.mPref.mMatch)); 3981 continue; 3982 } 3983 // If it's not an "always" type preferred activity and that's what we're 3984 // looking for, skip it. 3985 if (always && !pa.mPref.mAlways) { 3986 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3987 continue; 3988 } 3989 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3990 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3991 if (DEBUG_PREFERRED || debug) { 3992 Slog.v(TAG, "Found preferred activity:"); 3993 if (ai != null) { 3994 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3995 } else { 3996 Slog.v(TAG, " null"); 3997 } 3998 } 3999 if (ai == null) { 4000 // This previously registered preferred activity 4001 // component is no longer known. Most likely an update 4002 // to the app was installed and in the new version this 4003 // component no longer exists. Clean it up by removing 4004 // it from the preferred activities list, and skip it. 4005 Slog.w(TAG, "Removing dangling preferred activity: " 4006 + pa.mPref.mComponent); 4007 pir.removeFilter(pa); 4008 changed = true; 4009 continue; 4010 } 4011 for (int j=0; j<N; j++) { 4012 final ResolveInfo ri = query.get(j); 4013 if (!ri.activityInfo.applicationInfo.packageName 4014 .equals(ai.applicationInfo.packageName)) { 4015 continue; 4016 } 4017 if (!ri.activityInfo.name.equals(ai.name)) { 4018 continue; 4019 } 4020 4021 if (removeMatches) { 4022 pir.removeFilter(pa); 4023 changed = true; 4024 if (DEBUG_PREFERRED) { 4025 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4026 } 4027 break; 4028 } 4029 4030 // Okay we found a previously set preferred or last chosen app. 4031 // If the result set is different from when this 4032 // was created, we need to clear it and re-ask the 4033 // user their preference, if we're looking for an "always" type entry. 4034 if (always && !pa.mPref.sameSet(query)) { 4035 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4036 + intent + " type " + resolvedType); 4037 if (DEBUG_PREFERRED) { 4038 Slog.v(TAG, "Removing preferred activity since set changed " 4039 + pa.mPref.mComponent); 4040 } 4041 pir.removeFilter(pa); 4042 // Re-add the filter as a "last chosen" entry (!always) 4043 PreferredActivity lastChosen = new PreferredActivity( 4044 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4045 pir.addFilter(lastChosen); 4046 changed = true; 4047 return null; 4048 } 4049 4050 // Yay! Either the set matched or we're looking for the last chosen 4051 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4052 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4053 return ri; 4054 } 4055 } 4056 } finally { 4057 if (changed) { 4058 if (DEBUG_PREFERRED) { 4059 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4060 } 4061 scheduleWritePackageRestrictionsLocked(userId); 4062 } 4063 } 4064 } 4065 } 4066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4067 return null; 4068 } 4069 4070 /* 4071 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4072 */ 4073 @Override 4074 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4075 int targetUserId) { 4076 mContext.enforceCallingOrSelfPermission( 4077 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4078 List<CrossProfileIntentFilter> matches = 4079 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4080 if (matches != null) { 4081 int size = matches.size(); 4082 for (int i = 0; i < size; i++) { 4083 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4084 } 4085 } 4086 return false; 4087 } 4088 4089 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4090 String resolvedType, int userId) { 4091 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4092 if (resolver != null) { 4093 return resolver.queryIntent(intent, resolvedType, false, userId); 4094 } 4095 return null; 4096 } 4097 4098 @Override 4099 public List<ResolveInfo> queryIntentActivities(Intent intent, 4100 String resolvedType, int flags, int userId) { 4101 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4102 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4103 ComponentName comp = intent.getComponent(); 4104 if (comp == null) { 4105 if (intent.getSelector() != null) { 4106 intent = intent.getSelector(); 4107 comp = intent.getComponent(); 4108 } 4109 } 4110 4111 if (comp != null) { 4112 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4113 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4114 if (ai != null) { 4115 final ResolveInfo ri = new ResolveInfo(); 4116 ri.activityInfo = ai; 4117 list.add(ri); 4118 } 4119 return list; 4120 } 4121 4122 // reader 4123 synchronized (mPackages) { 4124 final String pkgName = intent.getPackage(); 4125 if (pkgName == null) { 4126 List<CrossProfileIntentFilter> matchingFilters = 4127 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4128 // Check for results that need to skip the current profile. 4129 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4130 resolvedType, flags, userId); 4131 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4132 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4133 result.add(resolveInfo); 4134 return filterIfNotPrimaryUser(result, userId); 4135 } 4136 4137 // Check for results in the current profile. 4138 List<ResolveInfo> result = mActivities.queryIntent( 4139 intent, resolvedType, flags, userId); 4140 4141 // Check for cross profile results. 4142 resolveInfo = queryCrossProfileIntents( 4143 matchingFilters, intent, resolvedType, flags, userId); 4144 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4145 result.add(resolveInfo); 4146 Collections.sort(result, mResolvePrioritySorter); 4147 } 4148 result = filterIfNotPrimaryUser(result, userId); 4149 if (result.size() > 1 && hasWebURI(intent)) { 4150 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4151 } 4152 return result; 4153 } 4154 final PackageParser.Package pkg = mPackages.get(pkgName); 4155 if (pkg != null) { 4156 return filterIfNotPrimaryUser( 4157 mActivities.queryIntentForPackage( 4158 intent, resolvedType, flags, pkg.activities, userId), 4159 userId); 4160 } 4161 return new ArrayList<ResolveInfo>(); 4162 } 4163 } 4164 4165 private boolean isUserEnabled(int userId) { 4166 long callingId = Binder.clearCallingIdentity(); 4167 try { 4168 UserInfo userInfo = sUserManager.getUserInfo(userId); 4169 return userInfo != null && userInfo.isEnabled(); 4170 } finally { 4171 Binder.restoreCallingIdentity(callingId); 4172 } 4173 } 4174 4175 /** 4176 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4177 * 4178 * @return filtered list 4179 */ 4180 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4181 if (userId == UserHandle.USER_OWNER) { 4182 return resolveInfos; 4183 } 4184 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4185 ResolveInfo info = resolveInfos.get(i); 4186 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4187 resolveInfos.remove(i); 4188 } 4189 } 4190 return resolveInfos; 4191 } 4192 4193 private static boolean hasWebURI(Intent intent) { 4194 if (intent.getData() == null) { 4195 return false; 4196 } 4197 final String scheme = intent.getScheme(); 4198 if (TextUtils.isEmpty(scheme)) { 4199 return false; 4200 } 4201 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4202 } 4203 4204 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4205 int flags, List<ResolveInfo> candidates) { 4206 if (DEBUG_PREFERRED) { 4207 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4208 candidates.size()); 4209 } 4210 4211 final int userId = UserHandle.getCallingUserId(); 4212 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4213 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4214 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4215 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4216 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4217 4218 synchronized (mPackages) { 4219 final int count = candidates.size(); 4220 // First, try to use the domain prefered App. Partition the candidates into four lists: 4221 // one for the final results, one for the "do not use ever", one for "undefined status" 4222 // and finally one for "Browser App type". 4223 for (int n=0; n<count; n++) { 4224 ResolveInfo info = candidates.get(n); 4225 String packageName = info.activityInfo.packageName; 4226 PackageSetting ps = mSettings.mPackages.get(packageName); 4227 if (ps != null) { 4228 // Add to the special match all list (Browser use case) 4229 if (info.handleAllWebDataURI) { 4230 matchAllList.add(info); 4231 continue; 4232 } 4233 // Try to get the status from User settings first 4234 int status = getDomainVerificationStatusLPr(ps, userId); 4235 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4236 alwaysList.add(info); 4237 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4238 neverList.add(info); 4239 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4240 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4241 undefinedList.add(info); 4242 } 4243 } 4244 } 4245 // First try to add the "always" if there is any 4246 if (alwaysList.size() > 0) { 4247 result.addAll(alwaysList); 4248 } else { 4249 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4250 result.addAll(undefinedList); 4251 // Also add Browsers (all of them or only the default one) 4252 if ((flags & MATCH_ALL) != 0) { 4253 result.addAll(matchAllList); 4254 } else { 4255 // Try to add the Default Browser if we can 4256 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4257 UserHandle.myUserId()); 4258 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4259 boolean defaultBrowserFound = false; 4260 final int browserCount = matchAllList.size(); 4261 for (int n=0; n<browserCount; n++) { 4262 ResolveInfo browser = matchAllList.get(n); 4263 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4264 result.add(browser); 4265 defaultBrowserFound = true; 4266 break; 4267 } 4268 } 4269 if (!defaultBrowserFound) { 4270 result.addAll(matchAllList); 4271 } 4272 } else { 4273 result.addAll(matchAllList); 4274 } 4275 } 4276 4277 // If there is nothing selected, add all candidates and remove the ones that the User 4278 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4279 if (result.size() == 0) { 4280 result.addAll(candidates); 4281 result.removeAll(neverList); 4282 } 4283 } 4284 } 4285 if (DEBUG_PREFERRED) { 4286 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4287 result.size()); 4288 } 4289 return result; 4290 } 4291 4292 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4293 int status = ps.getDomainVerificationStatusForUser(userId); 4294 // if none available, get the master status 4295 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4296 if (ps.getIntentFilterVerificationInfo() != null) { 4297 status = ps.getIntentFilterVerificationInfo().getStatus(); 4298 } 4299 } 4300 return status; 4301 } 4302 4303 private ResolveInfo querySkipCurrentProfileIntents( 4304 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4305 int flags, int sourceUserId) { 4306 if (matchingFilters != null) { 4307 int size = matchingFilters.size(); 4308 for (int i = 0; i < size; i ++) { 4309 CrossProfileIntentFilter filter = matchingFilters.get(i); 4310 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4311 // Checking if there are activities in the target user that can handle the 4312 // intent. 4313 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4314 flags, sourceUserId); 4315 if (resolveInfo != null) { 4316 return resolveInfo; 4317 } 4318 } 4319 } 4320 } 4321 return null; 4322 } 4323 4324 // Return matching ResolveInfo if any for skip current profile intent filters. 4325 private ResolveInfo queryCrossProfileIntents( 4326 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4327 int flags, int sourceUserId) { 4328 if (matchingFilters != null) { 4329 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4330 // match the same intent. For performance reasons, it is better not to 4331 // run queryIntent twice for the same userId 4332 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4333 int size = matchingFilters.size(); 4334 for (int i = 0; i < size; i++) { 4335 CrossProfileIntentFilter filter = matchingFilters.get(i); 4336 int targetUserId = filter.getTargetUserId(); 4337 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4338 && !alreadyTriedUserIds.get(targetUserId)) { 4339 // Checking if there are activities in the target user that can handle the 4340 // intent. 4341 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4342 flags, sourceUserId); 4343 if (resolveInfo != null) return resolveInfo; 4344 alreadyTriedUserIds.put(targetUserId, true); 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4352 String resolvedType, int flags, int sourceUserId) { 4353 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4354 resolvedType, flags, filter.getTargetUserId()); 4355 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4356 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4357 } 4358 return null; 4359 } 4360 4361 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4362 int sourceUserId, int targetUserId) { 4363 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4364 String className; 4365 if (targetUserId == UserHandle.USER_OWNER) { 4366 className = FORWARD_INTENT_TO_USER_OWNER; 4367 } else { 4368 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4369 } 4370 ComponentName forwardingActivityComponentName = new ComponentName( 4371 mAndroidApplication.packageName, className); 4372 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4373 sourceUserId); 4374 if (targetUserId == UserHandle.USER_OWNER) { 4375 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4376 forwardingResolveInfo.noResourceId = true; 4377 } 4378 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4379 forwardingResolveInfo.priority = 0; 4380 forwardingResolveInfo.preferredOrder = 0; 4381 forwardingResolveInfo.match = 0; 4382 forwardingResolveInfo.isDefault = true; 4383 forwardingResolveInfo.filter = filter; 4384 forwardingResolveInfo.targetUserId = targetUserId; 4385 return forwardingResolveInfo; 4386 } 4387 4388 @Override 4389 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4390 Intent[] specifics, String[] specificTypes, Intent intent, 4391 String resolvedType, int flags, int userId) { 4392 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4393 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4394 false, "query intent activity options"); 4395 final String resultsAction = intent.getAction(); 4396 4397 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4398 | PackageManager.GET_RESOLVED_FILTER, userId); 4399 4400 if (DEBUG_INTENT_MATCHING) { 4401 Log.v(TAG, "Query " + intent + ": " + results); 4402 } 4403 4404 int specificsPos = 0; 4405 int N; 4406 4407 // todo: note that the algorithm used here is O(N^2). This 4408 // isn't a problem in our current environment, but if we start running 4409 // into situations where we have more than 5 or 10 matches then this 4410 // should probably be changed to something smarter... 4411 4412 // First we go through and resolve each of the specific items 4413 // that were supplied, taking care of removing any corresponding 4414 // duplicate items in the generic resolve list. 4415 if (specifics != null) { 4416 for (int i=0; i<specifics.length; i++) { 4417 final Intent sintent = specifics[i]; 4418 if (sintent == null) { 4419 continue; 4420 } 4421 4422 if (DEBUG_INTENT_MATCHING) { 4423 Log.v(TAG, "Specific #" + i + ": " + sintent); 4424 } 4425 4426 String action = sintent.getAction(); 4427 if (resultsAction != null && resultsAction.equals(action)) { 4428 // If this action was explicitly requested, then don't 4429 // remove things that have it. 4430 action = null; 4431 } 4432 4433 ResolveInfo ri = null; 4434 ActivityInfo ai = null; 4435 4436 ComponentName comp = sintent.getComponent(); 4437 if (comp == null) { 4438 ri = resolveIntent( 4439 sintent, 4440 specificTypes != null ? specificTypes[i] : null, 4441 flags, userId); 4442 if (ri == null) { 4443 continue; 4444 } 4445 if (ri == mResolveInfo) { 4446 // ACK! Must do something better with this. 4447 } 4448 ai = ri.activityInfo; 4449 comp = new ComponentName(ai.applicationInfo.packageName, 4450 ai.name); 4451 } else { 4452 ai = getActivityInfo(comp, flags, userId); 4453 if (ai == null) { 4454 continue; 4455 } 4456 } 4457 4458 // Look for any generic query activities that are duplicates 4459 // of this specific one, and remove them from the results. 4460 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4461 N = results.size(); 4462 int j; 4463 for (j=specificsPos; j<N; j++) { 4464 ResolveInfo sri = results.get(j); 4465 if ((sri.activityInfo.name.equals(comp.getClassName()) 4466 && sri.activityInfo.applicationInfo.packageName.equals( 4467 comp.getPackageName())) 4468 || (action != null && sri.filter.matchAction(action))) { 4469 results.remove(j); 4470 if (DEBUG_INTENT_MATCHING) Log.v( 4471 TAG, "Removing duplicate item from " + j 4472 + " due to specific " + specificsPos); 4473 if (ri == null) { 4474 ri = sri; 4475 } 4476 j--; 4477 N--; 4478 } 4479 } 4480 4481 // Add this specific item to its proper place. 4482 if (ri == null) { 4483 ri = new ResolveInfo(); 4484 ri.activityInfo = ai; 4485 } 4486 results.add(specificsPos, ri); 4487 ri.specificIndex = i; 4488 specificsPos++; 4489 } 4490 } 4491 4492 // Now we go through the remaining generic results and remove any 4493 // duplicate actions that are found here. 4494 N = results.size(); 4495 for (int i=specificsPos; i<N-1; i++) { 4496 final ResolveInfo rii = results.get(i); 4497 if (rii.filter == null) { 4498 continue; 4499 } 4500 4501 // Iterate over all of the actions of this result's intent 4502 // filter... typically this should be just one. 4503 final Iterator<String> it = rii.filter.actionsIterator(); 4504 if (it == null) { 4505 continue; 4506 } 4507 while (it.hasNext()) { 4508 final String action = it.next(); 4509 if (resultsAction != null && resultsAction.equals(action)) { 4510 // If this action was explicitly requested, then don't 4511 // remove things that have it. 4512 continue; 4513 } 4514 for (int j=i+1; j<N; j++) { 4515 final ResolveInfo rij = results.get(j); 4516 if (rij.filter != null && rij.filter.hasAction(action)) { 4517 results.remove(j); 4518 if (DEBUG_INTENT_MATCHING) Log.v( 4519 TAG, "Removing duplicate item from " + j 4520 + " due to action " + action + " at " + i); 4521 j--; 4522 N--; 4523 } 4524 } 4525 } 4526 4527 // If the caller didn't request filter information, drop it now 4528 // so we don't have to marshall/unmarshall it. 4529 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4530 rii.filter = null; 4531 } 4532 } 4533 4534 // Filter out the caller activity if so requested. 4535 if (caller != null) { 4536 N = results.size(); 4537 for (int i=0; i<N; i++) { 4538 ActivityInfo ainfo = results.get(i).activityInfo; 4539 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4540 && caller.getClassName().equals(ainfo.name)) { 4541 results.remove(i); 4542 break; 4543 } 4544 } 4545 } 4546 4547 // If the caller didn't request filter information, 4548 // drop them now so we don't have to 4549 // marshall/unmarshall it. 4550 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4551 N = results.size(); 4552 for (int i=0; i<N; i++) { 4553 results.get(i).filter = null; 4554 } 4555 } 4556 4557 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4558 return results; 4559 } 4560 4561 @Override 4562 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4563 int userId) { 4564 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4565 ComponentName comp = intent.getComponent(); 4566 if (comp == null) { 4567 if (intent.getSelector() != null) { 4568 intent = intent.getSelector(); 4569 comp = intent.getComponent(); 4570 } 4571 } 4572 if (comp != null) { 4573 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4574 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4575 if (ai != null) { 4576 ResolveInfo ri = new ResolveInfo(); 4577 ri.activityInfo = ai; 4578 list.add(ri); 4579 } 4580 return list; 4581 } 4582 4583 // reader 4584 synchronized (mPackages) { 4585 String pkgName = intent.getPackage(); 4586 if (pkgName == null) { 4587 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4588 } 4589 final PackageParser.Package pkg = mPackages.get(pkgName); 4590 if (pkg != null) { 4591 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4592 userId); 4593 } 4594 return null; 4595 } 4596 } 4597 4598 @Override 4599 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4600 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4601 if (!sUserManager.exists(userId)) return null; 4602 if (query != null) { 4603 if (query.size() >= 1) { 4604 // If there is more than one service with the same priority, 4605 // just arbitrarily pick the first one. 4606 return query.get(0); 4607 } 4608 } 4609 return null; 4610 } 4611 4612 @Override 4613 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4614 int userId) { 4615 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4616 ComponentName comp = intent.getComponent(); 4617 if (comp == null) { 4618 if (intent.getSelector() != null) { 4619 intent = intent.getSelector(); 4620 comp = intent.getComponent(); 4621 } 4622 } 4623 if (comp != null) { 4624 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4625 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4626 if (si != null) { 4627 final ResolveInfo ri = new ResolveInfo(); 4628 ri.serviceInfo = si; 4629 list.add(ri); 4630 } 4631 return list; 4632 } 4633 4634 // reader 4635 synchronized (mPackages) { 4636 String pkgName = intent.getPackage(); 4637 if (pkgName == null) { 4638 return mServices.queryIntent(intent, resolvedType, flags, userId); 4639 } 4640 final PackageParser.Package pkg = mPackages.get(pkgName); 4641 if (pkg != null) { 4642 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4643 userId); 4644 } 4645 return null; 4646 } 4647 } 4648 4649 @Override 4650 public List<ResolveInfo> queryIntentContentProviders( 4651 Intent intent, String resolvedType, int flags, int userId) { 4652 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4653 ComponentName comp = intent.getComponent(); 4654 if (comp == null) { 4655 if (intent.getSelector() != null) { 4656 intent = intent.getSelector(); 4657 comp = intent.getComponent(); 4658 } 4659 } 4660 if (comp != null) { 4661 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4662 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4663 if (pi != null) { 4664 final ResolveInfo ri = new ResolveInfo(); 4665 ri.providerInfo = pi; 4666 list.add(ri); 4667 } 4668 return list; 4669 } 4670 4671 // reader 4672 synchronized (mPackages) { 4673 String pkgName = intent.getPackage(); 4674 if (pkgName == null) { 4675 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4676 } 4677 final PackageParser.Package pkg = mPackages.get(pkgName); 4678 if (pkg != null) { 4679 return mProviders.queryIntentForPackage( 4680 intent, resolvedType, flags, pkg.providers, userId); 4681 } 4682 return null; 4683 } 4684 } 4685 4686 @Override 4687 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4688 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4689 4690 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4691 4692 // writer 4693 synchronized (mPackages) { 4694 ArrayList<PackageInfo> list; 4695 if (listUninstalled) { 4696 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4697 for (PackageSetting ps : mSettings.mPackages.values()) { 4698 PackageInfo pi; 4699 if (ps.pkg != null) { 4700 pi = generatePackageInfo(ps.pkg, flags, userId); 4701 } else { 4702 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4703 } 4704 if (pi != null) { 4705 list.add(pi); 4706 } 4707 } 4708 } else { 4709 list = new ArrayList<PackageInfo>(mPackages.size()); 4710 for (PackageParser.Package p : mPackages.values()) { 4711 PackageInfo pi = generatePackageInfo(p, flags, userId); 4712 if (pi != null) { 4713 list.add(pi); 4714 } 4715 } 4716 } 4717 4718 return new ParceledListSlice<PackageInfo>(list); 4719 } 4720 } 4721 4722 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4723 String[] permissions, boolean[] tmp, int flags, int userId) { 4724 int numMatch = 0; 4725 final PermissionsState permissionsState = ps.getPermissionsState(); 4726 for (int i=0; i<permissions.length; i++) { 4727 final String permission = permissions[i]; 4728 if (permissionsState.hasPermission(permission, userId)) { 4729 tmp[i] = true; 4730 numMatch++; 4731 } else { 4732 tmp[i] = false; 4733 } 4734 } 4735 if (numMatch == 0) { 4736 return; 4737 } 4738 PackageInfo pi; 4739 if (ps.pkg != null) { 4740 pi = generatePackageInfo(ps.pkg, flags, userId); 4741 } else { 4742 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4743 } 4744 // The above might return null in cases of uninstalled apps or install-state 4745 // skew across users/profiles. 4746 if (pi != null) { 4747 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4748 if (numMatch == permissions.length) { 4749 pi.requestedPermissions = permissions; 4750 } else { 4751 pi.requestedPermissions = new String[numMatch]; 4752 numMatch = 0; 4753 for (int i=0; i<permissions.length; i++) { 4754 if (tmp[i]) { 4755 pi.requestedPermissions[numMatch] = permissions[i]; 4756 numMatch++; 4757 } 4758 } 4759 } 4760 } 4761 list.add(pi); 4762 } 4763 } 4764 4765 @Override 4766 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4767 String[] permissions, int flags, int userId) { 4768 if (!sUserManager.exists(userId)) return null; 4769 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4770 4771 // writer 4772 synchronized (mPackages) { 4773 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4774 boolean[] tmpBools = new boolean[permissions.length]; 4775 if (listUninstalled) { 4776 for (PackageSetting ps : mSettings.mPackages.values()) { 4777 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4778 } 4779 } else { 4780 for (PackageParser.Package pkg : mPackages.values()) { 4781 PackageSetting ps = (PackageSetting)pkg.mExtras; 4782 if (ps != null) { 4783 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4784 userId); 4785 } 4786 } 4787 } 4788 4789 return new ParceledListSlice<PackageInfo>(list); 4790 } 4791 } 4792 4793 @Override 4794 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4795 if (!sUserManager.exists(userId)) return null; 4796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4797 4798 // writer 4799 synchronized (mPackages) { 4800 ArrayList<ApplicationInfo> list; 4801 if (listUninstalled) { 4802 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4803 for (PackageSetting ps : mSettings.mPackages.values()) { 4804 ApplicationInfo ai; 4805 if (ps.pkg != null) { 4806 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4807 ps.readUserState(userId), userId); 4808 } else { 4809 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4810 } 4811 if (ai != null) { 4812 list.add(ai); 4813 } 4814 } 4815 } else { 4816 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4817 for (PackageParser.Package p : mPackages.values()) { 4818 if (p.mExtras != null) { 4819 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4820 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4821 if (ai != null) { 4822 list.add(ai); 4823 } 4824 } 4825 } 4826 } 4827 4828 return new ParceledListSlice<ApplicationInfo>(list); 4829 } 4830 } 4831 4832 public List<ApplicationInfo> getPersistentApplications(int flags) { 4833 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4834 4835 // reader 4836 synchronized (mPackages) { 4837 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4838 final int userId = UserHandle.getCallingUserId(); 4839 while (i.hasNext()) { 4840 final PackageParser.Package p = i.next(); 4841 if (p.applicationInfo != null 4842 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4843 && (!mSafeMode || isSystemApp(p))) { 4844 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4845 if (ps != null) { 4846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4847 ps.readUserState(userId), userId); 4848 if (ai != null) { 4849 finalList.add(ai); 4850 } 4851 } 4852 } 4853 } 4854 } 4855 4856 return finalList; 4857 } 4858 4859 @Override 4860 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4861 if (!sUserManager.exists(userId)) return null; 4862 // reader 4863 synchronized (mPackages) { 4864 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4865 PackageSetting ps = provider != null 4866 ? mSettings.mPackages.get(provider.owner.packageName) 4867 : null; 4868 return ps != null 4869 && mSettings.isEnabledLPr(provider.info, flags, userId) 4870 && (!mSafeMode || (provider.info.applicationInfo.flags 4871 &ApplicationInfo.FLAG_SYSTEM) != 0) 4872 ? PackageParser.generateProviderInfo(provider, flags, 4873 ps.readUserState(userId), userId) 4874 : null; 4875 } 4876 } 4877 4878 /** 4879 * @deprecated 4880 */ 4881 @Deprecated 4882 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4883 // reader 4884 synchronized (mPackages) { 4885 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4886 .entrySet().iterator(); 4887 final int userId = UserHandle.getCallingUserId(); 4888 while (i.hasNext()) { 4889 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4890 PackageParser.Provider p = entry.getValue(); 4891 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4892 4893 if (ps != null && p.syncable 4894 && (!mSafeMode || (p.info.applicationInfo.flags 4895 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4896 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4897 ps.readUserState(userId), userId); 4898 if (info != null) { 4899 outNames.add(entry.getKey()); 4900 outInfo.add(info); 4901 } 4902 } 4903 } 4904 } 4905 } 4906 4907 @Override 4908 public List<ProviderInfo> queryContentProviders(String processName, 4909 int uid, int flags) { 4910 ArrayList<ProviderInfo> finalList = null; 4911 // reader 4912 synchronized (mPackages) { 4913 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4914 final int userId = processName != null ? 4915 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4916 while (i.hasNext()) { 4917 final PackageParser.Provider p = i.next(); 4918 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4919 if (ps != null && p.info.authority != null 4920 && (processName == null 4921 || (p.info.processName.equals(processName) 4922 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4923 && mSettings.isEnabledLPr(p.info, flags, userId) 4924 && (!mSafeMode 4925 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4926 if (finalList == null) { 4927 finalList = new ArrayList<ProviderInfo>(3); 4928 } 4929 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4930 ps.readUserState(userId), userId); 4931 if (info != null) { 4932 finalList.add(info); 4933 } 4934 } 4935 } 4936 } 4937 4938 if (finalList != null) { 4939 Collections.sort(finalList, mProviderInitOrderSorter); 4940 } 4941 4942 return finalList; 4943 } 4944 4945 @Override 4946 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4947 int flags) { 4948 // reader 4949 synchronized (mPackages) { 4950 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4951 return PackageParser.generateInstrumentationInfo(i, flags); 4952 } 4953 } 4954 4955 @Override 4956 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4957 int flags) { 4958 ArrayList<InstrumentationInfo> finalList = 4959 new ArrayList<InstrumentationInfo>(); 4960 4961 // reader 4962 synchronized (mPackages) { 4963 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4964 while (i.hasNext()) { 4965 final PackageParser.Instrumentation p = i.next(); 4966 if (targetPackage == null 4967 || targetPackage.equals(p.info.targetPackage)) { 4968 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4969 flags); 4970 if (ii != null) { 4971 finalList.add(ii); 4972 } 4973 } 4974 } 4975 } 4976 4977 return finalList; 4978 } 4979 4980 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4981 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4982 if (overlays == null) { 4983 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4984 return; 4985 } 4986 for (PackageParser.Package opkg : overlays.values()) { 4987 // Not much to do if idmap fails: we already logged the error 4988 // and we certainly don't want to abort installation of pkg simply 4989 // because an overlay didn't fit properly. For these reasons, 4990 // ignore the return value of createIdmapForPackagePairLI. 4991 createIdmapForPackagePairLI(pkg, opkg); 4992 } 4993 } 4994 4995 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4996 PackageParser.Package opkg) { 4997 if (!opkg.mTrustedOverlay) { 4998 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4999 opkg.baseCodePath + ": overlay not trusted"); 5000 return false; 5001 } 5002 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5003 if (overlaySet == null) { 5004 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5005 opkg.baseCodePath + " but target package has no known overlays"); 5006 return false; 5007 } 5008 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5009 // TODO: generate idmap for split APKs 5010 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5011 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5012 + opkg.baseCodePath); 5013 return false; 5014 } 5015 PackageParser.Package[] overlayArray = 5016 overlaySet.values().toArray(new PackageParser.Package[0]); 5017 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5018 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5019 return p1.mOverlayPriority - p2.mOverlayPriority; 5020 } 5021 }; 5022 Arrays.sort(overlayArray, cmp); 5023 5024 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5025 int i = 0; 5026 for (PackageParser.Package p : overlayArray) { 5027 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5028 } 5029 return true; 5030 } 5031 5032 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5033 final File[] files = dir.listFiles(); 5034 if (ArrayUtils.isEmpty(files)) { 5035 Log.d(TAG, "No files in app dir " + dir); 5036 return; 5037 } 5038 5039 if (DEBUG_PACKAGE_SCANNING) { 5040 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5041 + " flags=0x" + Integer.toHexString(parseFlags)); 5042 } 5043 5044 for (File file : files) { 5045 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5046 && !PackageInstallerService.isStageName(file.getName()); 5047 if (!isPackage) { 5048 // Ignore entries which are not packages 5049 continue; 5050 } 5051 try { 5052 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5053 scanFlags, currentTime, null); 5054 } catch (PackageManagerException e) { 5055 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5056 5057 // Delete invalid userdata apps 5058 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5059 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5060 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5061 if (file.isDirectory()) { 5062 mInstaller.rmPackageDir(file.getAbsolutePath()); 5063 } else { 5064 file.delete(); 5065 } 5066 } 5067 } 5068 } 5069 } 5070 5071 private static File getSettingsProblemFile() { 5072 File dataDir = Environment.getDataDirectory(); 5073 File systemDir = new File(dataDir, "system"); 5074 File fname = new File(systemDir, "uiderrors.txt"); 5075 return fname; 5076 } 5077 5078 static void reportSettingsProblem(int priority, String msg) { 5079 logCriticalInfo(priority, msg); 5080 } 5081 5082 static void logCriticalInfo(int priority, String msg) { 5083 Slog.println(priority, TAG, msg); 5084 EventLogTags.writePmCriticalInfo(msg); 5085 try { 5086 File fname = getSettingsProblemFile(); 5087 FileOutputStream out = new FileOutputStream(fname, true); 5088 PrintWriter pw = new FastPrintWriter(out); 5089 SimpleDateFormat formatter = new SimpleDateFormat(); 5090 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5091 pw.println(dateString + ": " + msg); 5092 pw.close(); 5093 FileUtils.setPermissions( 5094 fname.toString(), 5095 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5096 -1, -1); 5097 } catch (java.io.IOException e) { 5098 } 5099 } 5100 5101 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5102 PackageParser.Package pkg, File srcFile, int parseFlags) 5103 throws PackageManagerException { 5104 if (ps != null 5105 && ps.codePath.equals(srcFile) 5106 && ps.timeStamp == srcFile.lastModified() 5107 && !isCompatSignatureUpdateNeeded(pkg) 5108 && !isRecoverSignatureUpdateNeeded(pkg)) { 5109 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5110 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5111 ArraySet<PublicKey> signingKs; 5112 synchronized (mPackages) { 5113 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5114 } 5115 if (ps.signatures.mSignatures != null 5116 && ps.signatures.mSignatures.length != 0 5117 && signingKs != null) { 5118 // Optimization: reuse the existing cached certificates 5119 // if the package appears to be unchanged. 5120 pkg.mSignatures = ps.signatures.mSignatures; 5121 pkg.mSigningKeys = signingKs; 5122 return; 5123 } 5124 5125 Slog.w(TAG, "PackageSetting for " + ps.name 5126 + " is missing signatures. Collecting certs again to recover them."); 5127 } else { 5128 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5129 } 5130 5131 try { 5132 pp.collectCertificates(pkg, parseFlags); 5133 pp.collectManifestDigest(pkg); 5134 } catch (PackageParserException e) { 5135 throw PackageManagerException.from(e); 5136 } 5137 } 5138 5139 /* 5140 * Scan a package and return the newly parsed package. 5141 * Returns null in case of errors and the error code is stored in mLastScanError 5142 */ 5143 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5144 long currentTime, UserHandle user) throws PackageManagerException { 5145 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5146 parseFlags |= mDefParseFlags; 5147 PackageParser pp = new PackageParser(); 5148 pp.setSeparateProcesses(mSeparateProcesses); 5149 pp.setOnlyCoreApps(mOnlyCore); 5150 pp.setDisplayMetrics(mMetrics); 5151 5152 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5153 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5154 } 5155 5156 final PackageParser.Package pkg; 5157 try { 5158 pkg = pp.parsePackage(scanFile, parseFlags); 5159 } catch (PackageParserException e) { 5160 throw PackageManagerException.from(e); 5161 } 5162 5163 PackageSetting ps = null; 5164 PackageSetting updatedPkg; 5165 // reader 5166 synchronized (mPackages) { 5167 // Look to see if we already know about this package. 5168 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5169 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5170 // This package has been renamed to its original name. Let's 5171 // use that. 5172 ps = mSettings.peekPackageLPr(oldName); 5173 } 5174 // If there was no original package, see one for the real package name. 5175 if (ps == null) { 5176 ps = mSettings.peekPackageLPr(pkg.packageName); 5177 } 5178 // Check to see if this package could be hiding/updating a system 5179 // package. Must look for it either under the original or real 5180 // package name depending on our state. 5181 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5182 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5183 } 5184 boolean updatedPkgBetter = false; 5185 // First check if this is a system package that may involve an update 5186 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5187 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5188 // it needs to drop FLAG_PRIVILEGED. 5189 if (locationIsPrivileged(scanFile)) { 5190 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5191 } else { 5192 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5193 } 5194 5195 if (ps != null && !ps.codePath.equals(scanFile)) { 5196 // The path has changed from what was last scanned... check the 5197 // version of the new path against what we have stored to determine 5198 // what to do. 5199 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5200 if (pkg.mVersionCode <= ps.versionCode) { 5201 // The system package has been updated and the code path does not match 5202 // Ignore entry. Skip it. 5203 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5204 + " ignored: updated version " + ps.versionCode 5205 + " better than this " + pkg.mVersionCode); 5206 if (!updatedPkg.codePath.equals(scanFile)) { 5207 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5208 + ps.name + " changing from " + updatedPkg.codePathString 5209 + " to " + scanFile); 5210 updatedPkg.codePath = scanFile; 5211 updatedPkg.codePathString = scanFile.toString(); 5212 updatedPkg.resourcePath = scanFile; 5213 updatedPkg.resourcePathString = scanFile.toString(); 5214 } 5215 updatedPkg.pkg = pkg; 5216 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5217 } else { 5218 // The current app on the system partition is better than 5219 // what we have updated to on the data partition; switch 5220 // back to the system partition version. 5221 // At this point, its safely assumed that package installation for 5222 // apps in system partition will go through. If not there won't be a working 5223 // version of the app 5224 // writer 5225 synchronized (mPackages) { 5226 // Just remove the loaded entries from package lists. 5227 mPackages.remove(ps.name); 5228 } 5229 5230 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5231 + " reverting from " + ps.codePathString 5232 + ": new version " + pkg.mVersionCode 5233 + " better than installed " + ps.versionCode); 5234 5235 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5236 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5237 synchronized (mInstallLock) { 5238 args.cleanUpResourcesLI(); 5239 } 5240 synchronized (mPackages) { 5241 mSettings.enableSystemPackageLPw(ps.name); 5242 } 5243 updatedPkgBetter = true; 5244 } 5245 } 5246 } 5247 5248 if (updatedPkg != null) { 5249 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5250 // initially 5251 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5252 5253 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5254 // flag set initially 5255 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5256 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5257 } 5258 } 5259 5260 // Verify certificates against what was last scanned 5261 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5262 5263 /* 5264 * A new system app appeared, but we already had a non-system one of the 5265 * same name installed earlier. 5266 */ 5267 boolean shouldHideSystemApp = false; 5268 if (updatedPkg == null && ps != null 5269 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5270 /* 5271 * Check to make sure the signatures match first. If they don't, 5272 * wipe the installed application and its data. 5273 */ 5274 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5275 != PackageManager.SIGNATURE_MATCH) { 5276 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5277 + " signatures don't match existing userdata copy; removing"); 5278 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5279 ps = null; 5280 } else { 5281 /* 5282 * If the newly-added system app is an older version than the 5283 * already installed version, hide it. It will be scanned later 5284 * and re-added like an update. 5285 */ 5286 if (pkg.mVersionCode <= ps.versionCode) { 5287 shouldHideSystemApp = true; 5288 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5289 + " but new version " + pkg.mVersionCode + " better than installed " 5290 + ps.versionCode + "; hiding system"); 5291 } else { 5292 /* 5293 * The newly found system app is a newer version that the 5294 * one previously installed. Simply remove the 5295 * already-installed application and replace it with our own 5296 * while keeping the application data. 5297 */ 5298 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5299 + " reverting from " + ps.codePathString + ": new version " 5300 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5301 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5302 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5303 synchronized (mInstallLock) { 5304 args.cleanUpResourcesLI(); 5305 } 5306 } 5307 } 5308 } 5309 5310 // The apk is forward locked (not public) if its code and resources 5311 // are kept in different files. (except for app in either system or 5312 // vendor path). 5313 // TODO grab this value from PackageSettings 5314 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5315 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5316 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5317 } 5318 } 5319 5320 // TODO: extend to support forward-locked splits 5321 String resourcePath = null; 5322 String baseResourcePath = null; 5323 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5324 if (ps != null && ps.resourcePathString != null) { 5325 resourcePath = ps.resourcePathString; 5326 baseResourcePath = ps.resourcePathString; 5327 } else { 5328 // Should not happen at all. Just log an error. 5329 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5330 } 5331 } else { 5332 resourcePath = pkg.codePath; 5333 baseResourcePath = pkg.baseCodePath; 5334 } 5335 5336 // Set application objects path explicitly. 5337 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5338 pkg.applicationInfo.setCodePath(pkg.codePath); 5339 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5340 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5341 pkg.applicationInfo.setResourcePath(resourcePath); 5342 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5343 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5344 5345 // Note that we invoke the following method only if we are about to unpack an application 5346 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5347 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5348 5349 /* 5350 * If the system app should be overridden by a previously installed 5351 * data, hide the system app now and let the /data/app scan pick it up 5352 * again. 5353 */ 5354 if (shouldHideSystemApp) { 5355 synchronized (mPackages) { 5356 /* 5357 * We have to grant systems permissions before we hide, because 5358 * grantPermissions will assume the package update is trying to 5359 * expand its permissions. 5360 */ 5361 grantPermissionsLPw(pkg, true, pkg.packageName); 5362 mSettings.disableSystemPackageLPw(pkg.packageName); 5363 } 5364 } 5365 5366 return scannedPkg; 5367 } 5368 5369 private static String fixProcessName(String defProcessName, 5370 String processName, int uid) { 5371 if (processName == null) { 5372 return defProcessName; 5373 } 5374 return processName; 5375 } 5376 5377 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5378 throws PackageManagerException { 5379 if (pkgSetting.signatures.mSignatures != null) { 5380 // Already existing package. Make sure signatures match 5381 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5382 == PackageManager.SIGNATURE_MATCH; 5383 if (!match) { 5384 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5385 == PackageManager.SIGNATURE_MATCH; 5386 } 5387 if (!match) { 5388 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5389 == PackageManager.SIGNATURE_MATCH; 5390 } 5391 if (!match) { 5392 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5393 + pkg.packageName + " signatures do not match the " 5394 + "previously installed version; ignoring!"); 5395 } 5396 } 5397 5398 // Check for shared user signatures 5399 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5400 // Already existing package. Make sure signatures match 5401 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5402 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5403 if (!match) { 5404 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5405 == PackageManager.SIGNATURE_MATCH; 5406 } 5407 if (!match) { 5408 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5409 == PackageManager.SIGNATURE_MATCH; 5410 } 5411 if (!match) { 5412 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5413 "Package " + pkg.packageName 5414 + " has no signatures that match those in shared user " 5415 + pkgSetting.sharedUser.name + "; ignoring!"); 5416 } 5417 } 5418 } 5419 5420 /** 5421 * Enforces that only the system UID or root's UID can call a method exposed 5422 * via Binder. 5423 * 5424 * @param message used as message if SecurityException is thrown 5425 * @throws SecurityException if the caller is not system or root 5426 */ 5427 private static final void enforceSystemOrRoot(String message) { 5428 final int uid = Binder.getCallingUid(); 5429 if (uid != Process.SYSTEM_UID && uid != 0) { 5430 throw new SecurityException(message); 5431 } 5432 } 5433 5434 @Override 5435 public void performBootDexOpt() { 5436 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5437 5438 // Before everything else, see whether we need to fstrim. 5439 try { 5440 IMountService ms = PackageHelper.getMountService(); 5441 if (ms != null) { 5442 final boolean isUpgrade = isUpgrade(); 5443 boolean doTrim = isUpgrade; 5444 if (doTrim) { 5445 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5446 } else { 5447 final long interval = android.provider.Settings.Global.getLong( 5448 mContext.getContentResolver(), 5449 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5450 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5451 if (interval > 0) { 5452 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5453 if (timeSinceLast > interval) { 5454 doTrim = true; 5455 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5456 + "; running immediately"); 5457 } 5458 } 5459 } 5460 if (doTrim) { 5461 if (!isFirstBoot()) { 5462 try { 5463 ActivityManagerNative.getDefault().showBootMessage( 5464 mContext.getResources().getString( 5465 R.string.android_upgrading_fstrim), true); 5466 } catch (RemoteException e) { 5467 } 5468 } 5469 ms.runMaintenance(); 5470 } 5471 } else { 5472 Slog.e(TAG, "Mount service unavailable!"); 5473 } 5474 } catch (RemoteException e) { 5475 // Can't happen; MountService is local 5476 } 5477 5478 final ArraySet<PackageParser.Package> pkgs; 5479 synchronized (mPackages) { 5480 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5481 } 5482 5483 if (pkgs != null) { 5484 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5485 // in case the device runs out of space. 5486 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5487 // Give priority to core apps. 5488 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5489 PackageParser.Package pkg = it.next(); 5490 if (pkg.coreApp) { 5491 if (DEBUG_DEXOPT) { 5492 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5493 } 5494 sortedPkgs.add(pkg); 5495 it.remove(); 5496 } 5497 } 5498 // Give priority to system apps that listen for pre boot complete. 5499 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5500 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5501 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5502 PackageParser.Package pkg = it.next(); 5503 if (pkgNames.contains(pkg.packageName)) { 5504 if (DEBUG_DEXOPT) { 5505 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5506 } 5507 sortedPkgs.add(pkg); 5508 it.remove(); 5509 } 5510 } 5511 // Give priority to system apps. 5512 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5513 PackageParser.Package pkg = it.next(); 5514 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5515 if (DEBUG_DEXOPT) { 5516 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5517 } 5518 sortedPkgs.add(pkg); 5519 it.remove(); 5520 } 5521 } 5522 // Give priority to updated system apps. 5523 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5524 PackageParser.Package pkg = it.next(); 5525 if (pkg.isUpdatedSystemApp()) { 5526 if (DEBUG_DEXOPT) { 5527 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5528 } 5529 sortedPkgs.add(pkg); 5530 it.remove(); 5531 } 5532 } 5533 // Give priority to apps that listen for boot complete. 5534 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5535 pkgNames = getPackageNamesForIntent(intent); 5536 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5537 PackageParser.Package pkg = it.next(); 5538 if (pkgNames.contains(pkg.packageName)) { 5539 if (DEBUG_DEXOPT) { 5540 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5541 } 5542 sortedPkgs.add(pkg); 5543 it.remove(); 5544 } 5545 } 5546 // Filter out packages that aren't recently used. 5547 filterRecentlyUsedApps(pkgs); 5548 // Add all remaining apps. 5549 for (PackageParser.Package pkg : pkgs) { 5550 if (DEBUG_DEXOPT) { 5551 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5552 } 5553 sortedPkgs.add(pkg); 5554 } 5555 5556 // If we want to be lazy, filter everything that wasn't recently used. 5557 if (mLazyDexOpt) { 5558 filterRecentlyUsedApps(sortedPkgs); 5559 } 5560 5561 int i = 0; 5562 int total = sortedPkgs.size(); 5563 File dataDir = Environment.getDataDirectory(); 5564 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5565 if (lowThreshold == 0) { 5566 throw new IllegalStateException("Invalid low memory threshold"); 5567 } 5568 for (PackageParser.Package pkg : sortedPkgs) { 5569 long usableSpace = dataDir.getUsableSpace(); 5570 if (usableSpace < lowThreshold) { 5571 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5572 break; 5573 } 5574 performBootDexOpt(pkg, ++i, total); 5575 } 5576 } 5577 } 5578 5579 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5580 // Filter out packages that aren't recently used. 5581 // 5582 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5583 // should do a full dexopt. 5584 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5585 int total = pkgs.size(); 5586 int skipped = 0; 5587 long now = System.currentTimeMillis(); 5588 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5589 PackageParser.Package pkg = i.next(); 5590 long then = pkg.mLastPackageUsageTimeInMills; 5591 if (then + mDexOptLRUThresholdInMills < now) { 5592 if (DEBUG_DEXOPT) { 5593 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5594 ((then == 0) ? "never" : new Date(then))); 5595 } 5596 i.remove(); 5597 skipped++; 5598 } 5599 } 5600 if (DEBUG_DEXOPT) { 5601 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5602 } 5603 } 5604 } 5605 5606 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5607 List<ResolveInfo> ris = null; 5608 try { 5609 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5610 intent, null, 0, UserHandle.USER_OWNER); 5611 } catch (RemoteException e) { 5612 } 5613 ArraySet<String> pkgNames = new ArraySet<String>(); 5614 if (ris != null) { 5615 for (ResolveInfo ri : ris) { 5616 pkgNames.add(ri.activityInfo.packageName); 5617 } 5618 } 5619 return pkgNames; 5620 } 5621 5622 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5623 if (DEBUG_DEXOPT) { 5624 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5625 } 5626 if (!isFirstBoot()) { 5627 try { 5628 ActivityManagerNative.getDefault().showBootMessage( 5629 mContext.getResources().getString(R.string.android_upgrading_apk, 5630 curr, total), true); 5631 } catch (RemoteException e) { 5632 } 5633 } 5634 PackageParser.Package p = pkg; 5635 synchronized (mInstallLock) { 5636 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5637 false /* force dex */, false /* defer */, true /* include dependencies */); 5638 } 5639 } 5640 5641 @Override 5642 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5643 return performDexOpt(packageName, instructionSet, false); 5644 } 5645 5646 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5647 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5648 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5649 if (!dexopt && !updateUsage) { 5650 // We aren't going to dexopt or update usage, so bail early. 5651 return false; 5652 } 5653 PackageParser.Package p; 5654 final String targetInstructionSet; 5655 synchronized (mPackages) { 5656 p = mPackages.get(packageName); 5657 if (p == null) { 5658 return false; 5659 } 5660 if (updateUsage) { 5661 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5662 } 5663 mPackageUsage.write(false); 5664 if (!dexopt) { 5665 // We aren't going to dexopt, so bail early. 5666 return false; 5667 } 5668 5669 targetInstructionSet = instructionSet != null ? instructionSet : 5670 getPrimaryInstructionSet(p.applicationInfo); 5671 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5672 return false; 5673 } 5674 } 5675 5676 synchronized (mInstallLock) { 5677 final String[] instructionSets = new String[] { targetInstructionSet }; 5678 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5679 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5680 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5681 } 5682 } 5683 5684 public ArraySet<String> getPackagesThatNeedDexOpt() { 5685 ArraySet<String> pkgs = null; 5686 synchronized (mPackages) { 5687 for (PackageParser.Package p : mPackages.values()) { 5688 if (DEBUG_DEXOPT) { 5689 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5690 } 5691 if (!p.mDexOptPerformed.isEmpty()) { 5692 continue; 5693 } 5694 if (pkgs == null) { 5695 pkgs = new ArraySet<String>(); 5696 } 5697 pkgs.add(p.packageName); 5698 } 5699 } 5700 return pkgs; 5701 } 5702 5703 public void shutdown() { 5704 mPackageUsage.write(true); 5705 } 5706 5707 @Override 5708 public void forceDexOpt(String packageName) { 5709 enforceSystemOrRoot("forceDexOpt"); 5710 5711 PackageParser.Package pkg; 5712 synchronized (mPackages) { 5713 pkg = mPackages.get(packageName); 5714 if (pkg == null) { 5715 throw new IllegalArgumentException("Missing package: " + packageName); 5716 } 5717 } 5718 5719 synchronized (mInstallLock) { 5720 final String[] instructionSets = new String[] { 5721 getPrimaryInstructionSet(pkg.applicationInfo) }; 5722 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5723 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5724 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5725 throw new IllegalStateException("Failed to dexopt: " + res); 5726 } 5727 } 5728 } 5729 5730 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5731 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5732 Slog.w(TAG, "Unable to update from " + oldPkg.name 5733 + " to " + newPkg.packageName 5734 + ": old package not in system partition"); 5735 return false; 5736 } else if (mPackages.get(oldPkg.name) != null) { 5737 Slog.w(TAG, "Unable to update from " + oldPkg.name 5738 + " to " + newPkg.packageName 5739 + ": old package still exists"); 5740 return false; 5741 } 5742 return true; 5743 } 5744 5745 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5746 int[] users = sUserManager.getUserIds(); 5747 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5748 if (res < 0) { 5749 return res; 5750 } 5751 for (int user : users) { 5752 if (user != 0) { 5753 res = mInstaller.createUserData(volumeUuid, packageName, 5754 UserHandle.getUid(user, uid), user, seinfo); 5755 if (res < 0) { 5756 return res; 5757 } 5758 } 5759 } 5760 return res; 5761 } 5762 5763 private int removeDataDirsLI(String volumeUuid, String packageName) { 5764 int[] users = sUserManager.getUserIds(); 5765 int res = 0; 5766 for (int user : users) { 5767 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5768 if (resInner < 0) { 5769 res = resInner; 5770 } 5771 } 5772 5773 return res; 5774 } 5775 5776 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5777 int[] users = sUserManager.getUserIds(); 5778 int res = 0; 5779 for (int user : users) { 5780 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5781 if (resInner < 0) { 5782 res = resInner; 5783 } 5784 } 5785 return res; 5786 } 5787 5788 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5789 PackageParser.Package changingLib) { 5790 if (file.path != null) { 5791 usesLibraryFiles.add(file.path); 5792 return; 5793 } 5794 PackageParser.Package p = mPackages.get(file.apk); 5795 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5796 // If we are doing this while in the middle of updating a library apk, 5797 // then we need to make sure to use that new apk for determining the 5798 // dependencies here. (We haven't yet finished committing the new apk 5799 // to the package manager state.) 5800 if (p == null || p.packageName.equals(changingLib.packageName)) { 5801 p = changingLib; 5802 } 5803 } 5804 if (p != null) { 5805 usesLibraryFiles.addAll(p.getAllCodePaths()); 5806 } 5807 } 5808 5809 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5810 PackageParser.Package changingLib) throws PackageManagerException { 5811 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5812 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5813 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5814 for (int i=0; i<N; i++) { 5815 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5816 if (file == null) { 5817 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5818 "Package " + pkg.packageName + " requires unavailable shared library " 5819 + pkg.usesLibraries.get(i) + "; failing!"); 5820 } 5821 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5822 } 5823 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5824 for (int i=0; i<N; i++) { 5825 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5826 if (file == null) { 5827 Slog.w(TAG, "Package " + pkg.packageName 5828 + " desires unavailable shared library " 5829 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5830 } else { 5831 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5832 } 5833 } 5834 N = usesLibraryFiles.size(); 5835 if (N > 0) { 5836 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5837 } else { 5838 pkg.usesLibraryFiles = null; 5839 } 5840 } 5841 } 5842 5843 private static boolean hasString(List<String> list, List<String> which) { 5844 if (list == null) { 5845 return false; 5846 } 5847 for (int i=list.size()-1; i>=0; i--) { 5848 for (int j=which.size()-1; j>=0; j--) { 5849 if (which.get(j).equals(list.get(i))) { 5850 return true; 5851 } 5852 } 5853 } 5854 return false; 5855 } 5856 5857 private void updateAllSharedLibrariesLPw() { 5858 for (PackageParser.Package pkg : mPackages.values()) { 5859 try { 5860 updateSharedLibrariesLPw(pkg, null); 5861 } catch (PackageManagerException e) { 5862 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5863 } 5864 } 5865 } 5866 5867 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5868 PackageParser.Package changingPkg) { 5869 ArrayList<PackageParser.Package> res = null; 5870 for (PackageParser.Package pkg : mPackages.values()) { 5871 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5872 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5873 if (res == null) { 5874 res = new ArrayList<PackageParser.Package>(); 5875 } 5876 res.add(pkg); 5877 try { 5878 updateSharedLibrariesLPw(pkg, changingPkg); 5879 } catch (PackageManagerException e) { 5880 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5881 } 5882 } 5883 } 5884 return res; 5885 } 5886 5887 /** 5888 * Derive the value of the {@code cpuAbiOverride} based on the provided 5889 * value and an optional stored value from the package settings. 5890 */ 5891 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5892 String cpuAbiOverride = null; 5893 5894 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5895 cpuAbiOverride = null; 5896 } else if (abiOverride != null) { 5897 cpuAbiOverride = abiOverride; 5898 } else if (settings != null) { 5899 cpuAbiOverride = settings.cpuAbiOverrideString; 5900 } 5901 5902 return cpuAbiOverride; 5903 } 5904 5905 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5906 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5907 boolean success = false; 5908 try { 5909 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5910 currentTime, user); 5911 success = true; 5912 return res; 5913 } finally { 5914 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5915 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5916 } 5917 } 5918 } 5919 5920 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5921 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5922 final File scanFile = new File(pkg.codePath); 5923 if (pkg.applicationInfo.getCodePath() == null || 5924 pkg.applicationInfo.getResourcePath() == null) { 5925 // Bail out. The resource and code paths haven't been set. 5926 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5927 "Code and resource paths haven't been set correctly"); 5928 } 5929 5930 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5931 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5932 } else { 5933 // Only allow system apps to be flagged as core apps. 5934 pkg.coreApp = false; 5935 } 5936 5937 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5938 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5939 } 5940 5941 if (mCustomResolverComponentName != null && 5942 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5943 setUpCustomResolverActivity(pkg); 5944 } 5945 5946 if (pkg.packageName.equals("android")) { 5947 synchronized (mPackages) { 5948 if (mAndroidApplication != null) { 5949 Slog.w(TAG, "*************************************************"); 5950 Slog.w(TAG, "Core android package being redefined. Skipping."); 5951 Slog.w(TAG, " file=" + scanFile); 5952 Slog.w(TAG, "*************************************************"); 5953 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5954 "Core android package being redefined. Skipping."); 5955 } 5956 5957 // Set up information for our fall-back user intent resolution activity. 5958 mPlatformPackage = pkg; 5959 pkg.mVersionCode = mSdkVersion; 5960 mAndroidApplication = pkg.applicationInfo; 5961 5962 if (!mResolverReplaced) { 5963 mResolveActivity.applicationInfo = mAndroidApplication; 5964 mResolveActivity.name = ResolverActivity.class.getName(); 5965 mResolveActivity.packageName = mAndroidApplication.packageName; 5966 mResolveActivity.processName = "system:ui"; 5967 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5968 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5969 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5970 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5971 mResolveActivity.exported = true; 5972 mResolveActivity.enabled = true; 5973 mResolveInfo.activityInfo = mResolveActivity; 5974 mResolveInfo.priority = 0; 5975 mResolveInfo.preferredOrder = 0; 5976 mResolveInfo.match = 0; 5977 mResolveComponentName = new ComponentName( 5978 mAndroidApplication.packageName, mResolveActivity.name); 5979 } 5980 } 5981 } 5982 5983 if (DEBUG_PACKAGE_SCANNING) { 5984 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5985 Log.d(TAG, "Scanning package " + pkg.packageName); 5986 } 5987 5988 if (mPackages.containsKey(pkg.packageName) 5989 || mSharedLibraries.containsKey(pkg.packageName)) { 5990 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5991 "Application package " + pkg.packageName 5992 + " already installed. Skipping duplicate."); 5993 } 5994 5995 // If we're only installing presumed-existing packages, require that the 5996 // scanned APK is both already known and at the path previously established 5997 // for it. Previously unknown packages we pick up normally, but if we have an 5998 // a priori expectation about this package's install presence, enforce it. 5999 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6000 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6001 if (known != null) { 6002 if (DEBUG_PACKAGE_SCANNING) { 6003 Log.d(TAG, "Examining " + pkg.codePath 6004 + " and requiring known paths " + known.codePathString 6005 + " & " + known.resourcePathString); 6006 } 6007 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6008 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6009 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6010 "Application package " + pkg.packageName 6011 + " found at " + pkg.applicationInfo.getCodePath() 6012 + " but expected at " + known.codePathString + "; ignoring."); 6013 } 6014 } 6015 } 6016 6017 // Initialize package source and resource directories 6018 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6019 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6020 6021 SharedUserSetting suid = null; 6022 PackageSetting pkgSetting = null; 6023 6024 if (!isSystemApp(pkg)) { 6025 // Only system apps can use these features. 6026 pkg.mOriginalPackages = null; 6027 pkg.mRealPackage = null; 6028 pkg.mAdoptPermissions = null; 6029 } 6030 6031 // writer 6032 synchronized (mPackages) { 6033 if (pkg.mSharedUserId != null) { 6034 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6035 if (suid == null) { 6036 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6037 "Creating application package " + pkg.packageName 6038 + " for shared user failed"); 6039 } 6040 if (DEBUG_PACKAGE_SCANNING) { 6041 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6042 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6043 + "): packages=" + suid.packages); 6044 } 6045 } 6046 6047 // Check if we are renaming from an original package name. 6048 PackageSetting origPackage = null; 6049 String realName = null; 6050 if (pkg.mOriginalPackages != null) { 6051 // This package may need to be renamed to a previously 6052 // installed name. Let's check on that... 6053 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6054 if (pkg.mOriginalPackages.contains(renamed)) { 6055 // This package had originally been installed as the 6056 // original name, and we have already taken care of 6057 // transitioning to the new one. Just update the new 6058 // one to continue using the old name. 6059 realName = pkg.mRealPackage; 6060 if (!pkg.packageName.equals(renamed)) { 6061 // Callers into this function may have already taken 6062 // care of renaming the package; only do it here if 6063 // it is not already done. 6064 pkg.setPackageName(renamed); 6065 } 6066 6067 } else { 6068 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6069 if ((origPackage = mSettings.peekPackageLPr( 6070 pkg.mOriginalPackages.get(i))) != null) { 6071 // We do have the package already installed under its 6072 // original name... should we use it? 6073 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6074 // New package is not compatible with original. 6075 origPackage = null; 6076 continue; 6077 } else if (origPackage.sharedUser != null) { 6078 // Make sure uid is compatible between packages. 6079 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6080 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6081 + " to " + pkg.packageName + ": old uid " 6082 + origPackage.sharedUser.name 6083 + " differs from " + pkg.mSharedUserId); 6084 origPackage = null; 6085 continue; 6086 } 6087 } else { 6088 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6089 + pkg.packageName + " to old name " + origPackage.name); 6090 } 6091 break; 6092 } 6093 } 6094 } 6095 } 6096 6097 if (mTransferedPackages.contains(pkg.packageName)) { 6098 Slog.w(TAG, "Package " + pkg.packageName 6099 + " was transferred to another, but its .apk remains"); 6100 } 6101 6102 // Just create the setting, don't add it yet. For already existing packages 6103 // the PkgSetting exists already and doesn't have to be created. 6104 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6105 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6106 pkg.applicationInfo.primaryCpuAbi, 6107 pkg.applicationInfo.secondaryCpuAbi, 6108 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6109 user, false); 6110 if (pkgSetting == null) { 6111 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6112 "Creating application package " + pkg.packageName + " failed"); 6113 } 6114 6115 if (pkgSetting.origPackage != null) { 6116 // If we are first transitioning from an original package, 6117 // fix up the new package's name now. We need to do this after 6118 // looking up the package under its new name, so getPackageLP 6119 // can take care of fiddling things correctly. 6120 pkg.setPackageName(origPackage.name); 6121 6122 // File a report about this. 6123 String msg = "New package " + pkgSetting.realName 6124 + " renamed to replace old package " + pkgSetting.name; 6125 reportSettingsProblem(Log.WARN, msg); 6126 6127 // Make a note of it. 6128 mTransferedPackages.add(origPackage.name); 6129 6130 // No longer need to retain this. 6131 pkgSetting.origPackage = null; 6132 } 6133 6134 if (realName != null) { 6135 // Make a note of it. 6136 mTransferedPackages.add(pkg.packageName); 6137 } 6138 6139 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6140 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6141 } 6142 6143 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6144 // Check all shared libraries and map to their actual file path. 6145 // We only do this here for apps not on a system dir, because those 6146 // are the only ones that can fail an install due to this. We 6147 // will take care of the system apps by updating all of their 6148 // library paths after the scan is done. 6149 updateSharedLibrariesLPw(pkg, null); 6150 } 6151 6152 if (mFoundPolicyFile) { 6153 SELinuxMMAC.assignSeinfoValue(pkg); 6154 } 6155 6156 pkg.applicationInfo.uid = pkgSetting.appId; 6157 pkg.mExtras = pkgSetting; 6158 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6159 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6160 // We just determined the app is signed correctly, so bring 6161 // over the latest parsed certs. 6162 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6163 } else { 6164 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6165 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6166 "Package " + pkg.packageName + " upgrade keys do not match the " 6167 + "previously installed version"); 6168 } else { 6169 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6170 String msg = "System package " + pkg.packageName 6171 + " signature changed; retaining data."; 6172 reportSettingsProblem(Log.WARN, msg); 6173 } 6174 } 6175 } else { 6176 try { 6177 verifySignaturesLP(pkgSetting, pkg); 6178 // We just determined the app is signed correctly, so bring 6179 // over the latest parsed certs. 6180 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6181 } catch (PackageManagerException e) { 6182 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6183 throw e; 6184 } 6185 // The signature has changed, but this package is in the system 6186 // image... let's recover! 6187 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6188 // However... if this package is part of a shared user, but it 6189 // doesn't match the signature of the shared user, let's fail. 6190 // What this means is that you can't change the signatures 6191 // associated with an overall shared user, which doesn't seem all 6192 // that unreasonable. 6193 if (pkgSetting.sharedUser != null) { 6194 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6195 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6196 throw new PackageManagerException( 6197 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6198 "Signature mismatch for shared user : " 6199 + pkgSetting.sharedUser); 6200 } 6201 } 6202 // File a report about this. 6203 String msg = "System package " + pkg.packageName 6204 + " signature changed; retaining data."; 6205 reportSettingsProblem(Log.WARN, msg); 6206 } 6207 } 6208 // Verify that this new package doesn't have any content providers 6209 // that conflict with existing packages. Only do this if the 6210 // package isn't already installed, since we don't want to break 6211 // things that are installed. 6212 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6213 final int N = pkg.providers.size(); 6214 int i; 6215 for (i=0; i<N; i++) { 6216 PackageParser.Provider p = pkg.providers.get(i); 6217 if (p.info.authority != null) { 6218 String names[] = p.info.authority.split(";"); 6219 for (int j = 0; j < names.length; j++) { 6220 if (mProvidersByAuthority.containsKey(names[j])) { 6221 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6222 final String otherPackageName = 6223 ((other != null && other.getComponentName() != null) ? 6224 other.getComponentName().getPackageName() : "?"); 6225 throw new PackageManagerException( 6226 INSTALL_FAILED_CONFLICTING_PROVIDER, 6227 "Can't install because provider name " + names[j] 6228 + " (in package " + pkg.applicationInfo.packageName 6229 + ") is already used by " + otherPackageName); 6230 } 6231 } 6232 } 6233 } 6234 } 6235 6236 if (pkg.mAdoptPermissions != null) { 6237 // This package wants to adopt ownership of permissions from 6238 // another package. 6239 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6240 final String origName = pkg.mAdoptPermissions.get(i); 6241 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6242 if (orig != null) { 6243 if (verifyPackageUpdateLPr(orig, pkg)) { 6244 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6245 + pkg.packageName); 6246 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6247 } 6248 } 6249 } 6250 } 6251 } 6252 6253 final String pkgName = pkg.packageName; 6254 6255 final long scanFileTime = scanFile.lastModified(); 6256 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6257 pkg.applicationInfo.processName = fixProcessName( 6258 pkg.applicationInfo.packageName, 6259 pkg.applicationInfo.processName, 6260 pkg.applicationInfo.uid); 6261 6262 File dataPath; 6263 if (mPlatformPackage == pkg) { 6264 // The system package is special. 6265 dataPath = new File(Environment.getDataDirectory(), "system"); 6266 6267 pkg.applicationInfo.dataDir = dataPath.getPath(); 6268 6269 } else { 6270 // This is a normal package, need to make its data directory. 6271 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6272 UserHandle.USER_OWNER); 6273 6274 boolean uidError = false; 6275 if (dataPath.exists()) { 6276 int currentUid = 0; 6277 try { 6278 StructStat stat = Os.stat(dataPath.getPath()); 6279 currentUid = stat.st_uid; 6280 } catch (ErrnoException e) { 6281 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6282 } 6283 6284 // If we have mismatched owners for the data path, we have a problem. 6285 if (currentUid != pkg.applicationInfo.uid) { 6286 boolean recovered = false; 6287 if (currentUid == 0) { 6288 // The directory somehow became owned by root. Wow. 6289 // This is probably because the system was stopped while 6290 // installd was in the middle of messing with its libs 6291 // directory. Ask installd to fix that. 6292 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6293 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6294 if (ret >= 0) { 6295 recovered = true; 6296 String msg = "Package " + pkg.packageName 6297 + " unexpectedly changed to uid 0; recovered to " + 6298 + pkg.applicationInfo.uid; 6299 reportSettingsProblem(Log.WARN, msg); 6300 } 6301 } 6302 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6303 || (scanFlags&SCAN_BOOTING) != 0)) { 6304 // If this is a system app, we can at least delete its 6305 // current data so the application will still work. 6306 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6307 if (ret >= 0) { 6308 // TODO: Kill the processes first 6309 // Old data gone! 6310 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6311 ? "System package " : "Third party package "; 6312 String msg = prefix + pkg.packageName 6313 + " has changed from uid: " 6314 + currentUid + " to " 6315 + pkg.applicationInfo.uid + "; old data erased"; 6316 reportSettingsProblem(Log.WARN, msg); 6317 recovered = true; 6318 6319 // And now re-install the app. 6320 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6321 pkg.applicationInfo.seinfo); 6322 if (ret == -1) { 6323 // Ack should not happen! 6324 msg = prefix + pkg.packageName 6325 + " could not have data directory re-created after delete."; 6326 reportSettingsProblem(Log.WARN, msg); 6327 throw new PackageManagerException( 6328 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6329 } 6330 } 6331 if (!recovered) { 6332 mHasSystemUidErrors = true; 6333 } 6334 } else if (!recovered) { 6335 // If we allow this install to proceed, we will be broken. 6336 // Abort, abort! 6337 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6338 "scanPackageLI"); 6339 } 6340 if (!recovered) { 6341 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6342 + pkg.applicationInfo.uid + "/fs_" 6343 + currentUid; 6344 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6345 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6346 String msg = "Package " + pkg.packageName 6347 + " has mismatched uid: " 6348 + currentUid + " on disk, " 6349 + pkg.applicationInfo.uid + " in settings"; 6350 // writer 6351 synchronized (mPackages) { 6352 mSettings.mReadMessages.append(msg); 6353 mSettings.mReadMessages.append('\n'); 6354 uidError = true; 6355 if (!pkgSetting.uidError) { 6356 reportSettingsProblem(Log.ERROR, msg); 6357 } 6358 } 6359 } 6360 } 6361 pkg.applicationInfo.dataDir = dataPath.getPath(); 6362 if (mShouldRestoreconData) { 6363 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6364 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6365 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6366 } 6367 } else { 6368 if (DEBUG_PACKAGE_SCANNING) { 6369 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6370 Log.v(TAG, "Want this data dir: " + dataPath); 6371 } 6372 //invoke installer to do the actual installation 6373 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6374 pkg.applicationInfo.seinfo); 6375 if (ret < 0) { 6376 // Error from installer 6377 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6378 "Unable to create data dirs [errorCode=" + ret + "]"); 6379 } 6380 6381 if (dataPath.exists()) { 6382 pkg.applicationInfo.dataDir = dataPath.getPath(); 6383 } else { 6384 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6385 pkg.applicationInfo.dataDir = null; 6386 } 6387 } 6388 6389 pkgSetting.uidError = uidError; 6390 } 6391 6392 final String path = scanFile.getPath(); 6393 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6394 6395 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6396 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6397 6398 // Some system apps still use directory structure for native libraries 6399 // in which case we might end up not detecting abi solely based on apk 6400 // structure. Try to detect abi based on directory structure. 6401 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6402 pkg.applicationInfo.primaryCpuAbi == null) { 6403 setBundledAppAbisAndRoots(pkg, pkgSetting); 6404 setNativeLibraryPaths(pkg); 6405 } 6406 6407 } else { 6408 if ((scanFlags & SCAN_MOVE) != 0) { 6409 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6410 // but we already have this packages package info in the PackageSetting. We just 6411 // use that and derive the native library path based on the new codepath. 6412 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6413 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6414 } 6415 6416 // Set native library paths again. For moves, the path will be updated based on the 6417 // ABIs we've determined above. For non-moves, the path will be updated based on the 6418 // ABIs we determined during compilation, but the path will depend on the final 6419 // package path (after the rename away from the stage path). 6420 setNativeLibraryPaths(pkg); 6421 } 6422 6423 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6424 final int[] userIds = sUserManager.getUserIds(); 6425 synchronized (mInstallLock) { 6426 // Create a native library symlink only if we have native libraries 6427 // and if the native libraries are 32 bit libraries. We do not provide 6428 // this symlink for 64 bit libraries. 6429 if (pkg.applicationInfo.primaryCpuAbi != null && 6430 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6431 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6432 for (int userId : userIds) { 6433 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6434 nativeLibPath, userId) < 0) { 6435 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6436 "Failed linking native library dir (user=" + userId + ")"); 6437 } 6438 } 6439 } 6440 } 6441 6442 // This is a special case for the "system" package, where the ABI is 6443 // dictated by the zygote configuration (and init.rc). We should keep track 6444 // of this ABI so that we can deal with "normal" applications that run under 6445 // the same UID correctly. 6446 if (mPlatformPackage == pkg) { 6447 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6448 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6449 } 6450 6451 // If there's a mismatch between the abi-override in the package setting 6452 // and the abiOverride specified for the install. Warn about this because we 6453 // would've already compiled the app without taking the package setting into 6454 // account. 6455 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6456 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6457 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6458 " for package: " + pkg.packageName); 6459 } 6460 } 6461 6462 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6463 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6464 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6465 6466 // Copy the derived override back to the parsed package, so that we can 6467 // update the package settings accordingly. 6468 pkg.cpuAbiOverride = cpuAbiOverride; 6469 6470 if (DEBUG_ABI_SELECTION) { 6471 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6472 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6473 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6474 } 6475 6476 // Push the derived path down into PackageSettings so we know what to 6477 // clean up at uninstall time. 6478 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6479 6480 if (DEBUG_ABI_SELECTION) { 6481 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6482 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6483 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6484 } 6485 6486 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6487 // We don't do this here during boot because we can do it all 6488 // at once after scanning all existing packages. 6489 // 6490 // We also do this *before* we perform dexopt on this package, so that 6491 // we can avoid redundant dexopts, and also to make sure we've got the 6492 // code and package path correct. 6493 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6494 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6495 } 6496 6497 if ((scanFlags & SCAN_NO_DEX) == 0) { 6498 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6499 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6500 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6501 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6502 } 6503 } 6504 if (mFactoryTest && pkg.requestedPermissions.contains( 6505 android.Manifest.permission.FACTORY_TEST)) { 6506 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6507 } 6508 6509 ArrayList<PackageParser.Package> clientLibPkgs = null; 6510 6511 // writer 6512 synchronized (mPackages) { 6513 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6514 // Only system apps can add new shared libraries. 6515 if (pkg.libraryNames != null) { 6516 for (int i=0; i<pkg.libraryNames.size(); i++) { 6517 String name = pkg.libraryNames.get(i); 6518 boolean allowed = false; 6519 if (pkg.isUpdatedSystemApp()) { 6520 // New library entries can only be added through the 6521 // system image. This is important to get rid of a lot 6522 // of nasty edge cases: for example if we allowed a non- 6523 // system update of the app to add a library, then uninstalling 6524 // the update would make the library go away, and assumptions 6525 // we made such as through app install filtering would now 6526 // have allowed apps on the device which aren't compatible 6527 // with it. Better to just have the restriction here, be 6528 // conservative, and create many fewer cases that can negatively 6529 // impact the user experience. 6530 final PackageSetting sysPs = mSettings 6531 .getDisabledSystemPkgLPr(pkg.packageName); 6532 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6533 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6534 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6535 allowed = true; 6536 allowed = true; 6537 break; 6538 } 6539 } 6540 } 6541 } else { 6542 allowed = true; 6543 } 6544 if (allowed) { 6545 if (!mSharedLibraries.containsKey(name)) { 6546 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6547 } else if (!name.equals(pkg.packageName)) { 6548 Slog.w(TAG, "Package " + pkg.packageName + " library " 6549 + name + " already exists; skipping"); 6550 } 6551 } else { 6552 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6553 + name + " that is not declared on system image; skipping"); 6554 } 6555 } 6556 if ((scanFlags&SCAN_BOOTING) == 0) { 6557 // If we are not booting, we need to update any applications 6558 // that are clients of our shared library. If we are booting, 6559 // this will all be done once the scan is complete. 6560 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6561 } 6562 } 6563 } 6564 } 6565 6566 // We also need to dexopt any apps that are dependent on this library. Note that 6567 // if these fail, we should abort the install since installing the library will 6568 // result in some apps being broken. 6569 if (clientLibPkgs != null) { 6570 if ((scanFlags & SCAN_NO_DEX) == 0) { 6571 for (int i = 0; i < clientLibPkgs.size(); i++) { 6572 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6573 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6574 null /* instruction sets */, forceDex, 6575 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6576 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6577 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6578 "scanPackageLI failed to dexopt clientLibPkgs"); 6579 } 6580 } 6581 } 6582 } 6583 6584 // Also need to kill any apps that are dependent on the library. 6585 if (clientLibPkgs != null) { 6586 for (int i=0; i<clientLibPkgs.size(); i++) { 6587 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6588 killApplication(clientPkg.applicationInfo.packageName, 6589 clientPkg.applicationInfo.uid, "update lib"); 6590 } 6591 } 6592 6593 // Make sure we're not adding any bogus keyset info 6594 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6595 ksms.assertScannedPackageValid(pkg); 6596 6597 // writer 6598 synchronized (mPackages) { 6599 // We don't expect installation to fail beyond this point 6600 6601 // Add the new setting to mSettings 6602 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6603 // Add the new setting to mPackages 6604 mPackages.put(pkg.applicationInfo.packageName, pkg); 6605 // Make sure we don't accidentally delete its data. 6606 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6607 while (iter.hasNext()) { 6608 PackageCleanItem item = iter.next(); 6609 if (pkgName.equals(item.packageName)) { 6610 iter.remove(); 6611 } 6612 } 6613 6614 // Take care of first install / last update times. 6615 if (currentTime != 0) { 6616 if (pkgSetting.firstInstallTime == 0) { 6617 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6618 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6619 pkgSetting.lastUpdateTime = currentTime; 6620 } 6621 } else if (pkgSetting.firstInstallTime == 0) { 6622 // We need *something*. Take time time stamp of the file. 6623 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6624 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6625 if (scanFileTime != pkgSetting.timeStamp) { 6626 // A package on the system image has changed; consider this 6627 // to be an update. 6628 pkgSetting.lastUpdateTime = scanFileTime; 6629 } 6630 } 6631 6632 // Add the package's KeySets to the global KeySetManagerService 6633 ksms.addScannedPackageLPw(pkg); 6634 6635 int N = pkg.providers.size(); 6636 StringBuilder r = null; 6637 int i; 6638 for (i=0; i<N; i++) { 6639 PackageParser.Provider p = pkg.providers.get(i); 6640 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6641 p.info.processName, pkg.applicationInfo.uid); 6642 mProviders.addProvider(p); 6643 p.syncable = p.info.isSyncable; 6644 if (p.info.authority != null) { 6645 String names[] = p.info.authority.split(";"); 6646 p.info.authority = null; 6647 for (int j = 0; j < names.length; j++) { 6648 if (j == 1 && p.syncable) { 6649 // We only want the first authority for a provider to possibly be 6650 // syncable, so if we already added this provider using a different 6651 // authority clear the syncable flag. We copy the provider before 6652 // changing it because the mProviders object contains a reference 6653 // to a provider that we don't want to change. 6654 // Only do this for the second authority since the resulting provider 6655 // object can be the same for all future authorities for this provider. 6656 p = new PackageParser.Provider(p); 6657 p.syncable = false; 6658 } 6659 if (!mProvidersByAuthority.containsKey(names[j])) { 6660 mProvidersByAuthority.put(names[j], p); 6661 if (p.info.authority == null) { 6662 p.info.authority = names[j]; 6663 } else { 6664 p.info.authority = p.info.authority + ";" + names[j]; 6665 } 6666 if (DEBUG_PACKAGE_SCANNING) { 6667 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6668 Log.d(TAG, "Registered content provider: " + names[j] 6669 + ", className = " + p.info.name + ", isSyncable = " 6670 + p.info.isSyncable); 6671 } 6672 } else { 6673 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6674 Slog.w(TAG, "Skipping provider name " + names[j] + 6675 " (in package " + pkg.applicationInfo.packageName + 6676 "): name already used by " 6677 + ((other != null && other.getComponentName() != null) 6678 ? other.getComponentName().getPackageName() : "?")); 6679 } 6680 } 6681 } 6682 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6683 if (r == null) { 6684 r = new StringBuilder(256); 6685 } else { 6686 r.append(' '); 6687 } 6688 r.append(p.info.name); 6689 } 6690 } 6691 if (r != null) { 6692 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6693 } 6694 6695 N = pkg.services.size(); 6696 r = null; 6697 for (i=0; i<N; i++) { 6698 PackageParser.Service s = pkg.services.get(i); 6699 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6700 s.info.processName, pkg.applicationInfo.uid); 6701 mServices.addService(s); 6702 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6703 if (r == null) { 6704 r = new StringBuilder(256); 6705 } else { 6706 r.append(' '); 6707 } 6708 r.append(s.info.name); 6709 } 6710 } 6711 if (r != null) { 6712 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6713 } 6714 6715 N = pkg.receivers.size(); 6716 r = null; 6717 for (i=0; i<N; i++) { 6718 PackageParser.Activity a = pkg.receivers.get(i); 6719 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6720 a.info.processName, pkg.applicationInfo.uid); 6721 mReceivers.addActivity(a, "receiver"); 6722 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6723 if (r == null) { 6724 r = new StringBuilder(256); 6725 } else { 6726 r.append(' '); 6727 } 6728 r.append(a.info.name); 6729 } 6730 } 6731 if (r != null) { 6732 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6733 } 6734 6735 N = pkg.activities.size(); 6736 r = null; 6737 for (i=0; i<N; i++) { 6738 PackageParser.Activity a = pkg.activities.get(i); 6739 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6740 a.info.processName, pkg.applicationInfo.uid); 6741 mActivities.addActivity(a, "activity"); 6742 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6743 if (r == null) { 6744 r = new StringBuilder(256); 6745 } else { 6746 r.append(' '); 6747 } 6748 r.append(a.info.name); 6749 } 6750 } 6751 if (r != null) { 6752 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6753 } 6754 6755 N = pkg.permissionGroups.size(); 6756 r = null; 6757 for (i=0; i<N; i++) { 6758 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6759 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6760 if (cur == null) { 6761 mPermissionGroups.put(pg.info.name, pg); 6762 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6763 if (r == null) { 6764 r = new StringBuilder(256); 6765 } else { 6766 r.append(' '); 6767 } 6768 r.append(pg.info.name); 6769 } 6770 } else { 6771 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6772 + pg.info.packageName + " ignored: original from " 6773 + cur.info.packageName); 6774 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6775 if (r == null) { 6776 r = new StringBuilder(256); 6777 } else { 6778 r.append(' '); 6779 } 6780 r.append("DUP:"); 6781 r.append(pg.info.name); 6782 } 6783 } 6784 } 6785 if (r != null) { 6786 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6787 } 6788 6789 N = pkg.permissions.size(); 6790 r = null; 6791 for (i=0; i<N; i++) { 6792 PackageParser.Permission p = pkg.permissions.get(i); 6793 6794 // Now that permission groups have a special meaning, we ignore permission 6795 // groups for legacy apps to prevent unexpected behavior. In particular, 6796 // permissions for one app being granted to someone just becuase they happen 6797 // to be in a group defined by another app (before this had no implications). 6798 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6799 p.group = mPermissionGroups.get(p.info.group); 6800 // Warn for a permission in an unknown group. 6801 if (p.info.group != null && p.group == null) { 6802 Slog.w(TAG, "Permission " + p.info.name + " from package " 6803 + p.info.packageName + " in an unknown group " + p.info.group); 6804 } 6805 } 6806 6807 ArrayMap<String, BasePermission> permissionMap = 6808 p.tree ? mSettings.mPermissionTrees 6809 : mSettings.mPermissions; 6810 BasePermission bp = permissionMap.get(p.info.name); 6811 6812 // Allow system apps to redefine non-system permissions 6813 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6814 final boolean currentOwnerIsSystem = (bp.perm != null 6815 && isSystemApp(bp.perm.owner)); 6816 if (isSystemApp(p.owner)) { 6817 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6818 // It's a built-in permission and no owner, take ownership now 6819 bp.packageSetting = pkgSetting; 6820 bp.perm = p; 6821 bp.uid = pkg.applicationInfo.uid; 6822 bp.sourcePackage = p.info.packageName; 6823 } else if (!currentOwnerIsSystem) { 6824 String msg = "New decl " + p.owner + " of permission " 6825 + p.info.name + " is system; overriding " + bp.sourcePackage; 6826 reportSettingsProblem(Log.WARN, msg); 6827 bp = null; 6828 } 6829 } 6830 } 6831 6832 if (bp == null) { 6833 bp = new BasePermission(p.info.name, p.info.packageName, 6834 BasePermission.TYPE_NORMAL); 6835 permissionMap.put(p.info.name, bp); 6836 } 6837 6838 if (bp.perm == null) { 6839 if (bp.sourcePackage == null 6840 || bp.sourcePackage.equals(p.info.packageName)) { 6841 BasePermission tree = findPermissionTreeLP(p.info.name); 6842 if (tree == null 6843 || tree.sourcePackage.equals(p.info.packageName)) { 6844 bp.packageSetting = pkgSetting; 6845 bp.perm = p; 6846 bp.uid = pkg.applicationInfo.uid; 6847 bp.sourcePackage = p.info.packageName; 6848 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6849 if (r == null) { 6850 r = new StringBuilder(256); 6851 } else { 6852 r.append(' '); 6853 } 6854 r.append(p.info.name); 6855 } 6856 } else { 6857 Slog.w(TAG, "Permission " + p.info.name + " from package " 6858 + p.info.packageName + " ignored: base tree " 6859 + tree.name + " is from package " 6860 + tree.sourcePackage); 6861 } 6862 } else { 6863 Slog.w(TAG, "Permission " + p.info.name + " from package " 6864 + p.info.packageName + " ignored: original from " 6865 + bp.sourcePackage); 6866 } 6867 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6868 if (r == null) { 6869 r = new StringBuilder(256); 6870 } else { 6871 r.append(' '); 6872 } 6873 r.append("DUP:"); 6874 r.append(p.info.name); 6875 } 6876 if (bp.perm == p) { 6877 bp.protectionLevel = p.info.protectionLevel; 6878 } 6879 } 6880 6881 if (r != null) { 6882 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6883 } 6884 6885 N = pkg.instrumentation.size(); 6886 r = null; 6887 for (i=0; i<N; i++) { 6888 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6889 a.info.packageName = pkg.applicationInfo.packageName; 6890 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6891 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6892 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6893 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6894 a.info.dataDir = pkg.applicationInfo.dataDir; 6895 6896 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6897 // need other information about the application, like the ABI and what not ? 6898 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6899 mInstrumentation.put(a.getComponentName(), a); 6900 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6901 if (r == null) { 6902 r = new StringBuilder(256); 6903 } else { 6904 r.append(' '); 6905 } 6906 r.append(a.info.name); 6907 } 6908 } 6909 if (r != null) { 6910 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6911 } 6912 6913 if (pkg.protectedBroadcasts != null) { 6914 N = pkg.protectedBroadcasts.size(); 6915 for (i=0; i<N; i++) { 6916 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6917 } 6918 } 6919 6920 pkgSetting.setTimeStamp(scanFileTime); 6921 6922 // Create idmap files for pairs of (packages, overlay packages). 6923 // Note: "android", ie framework-res.apk, is handled by native layers. 6924 if (pkg.mOverlayTarget != null) { 6925 // This is an overlay package. 6926 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6927 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6928 mOverlays.put(pkg.mOverlayTarget, 6929 new ArrayMap<String, PackageParser.Package>()); 6930 } 6931 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6932 map.put(pkg.packageName, pkg); 6933 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6934 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6935 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6936 "scanPackageLI failed to createIdmap"); 6937 } 6938 } 6939 } else if (mOverlays.containsKey(pkg.packageName) && 6940 !pkg.packageName.equals("android")) { 6941 // This is a regular package, with one or more known overlay packages. 6942 createIdmapsForPackageLI(pkg); 6943 } 6944 } 6945 6946 return pkg; 6947 } 6948 6949 /** 6950 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6951 * is derived purely on the basis of the contents of {@code scanFile} and 6952 * {@code cpuAbiOverride}. 6953 * 6954 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6955 */ 6956 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6957 String cpuAbiOverride, boolean extractLibs) 6958 throws PackageManagerException { 6959 // TODO: We can probably be smarter about this stuff. For installed apps, 6960 // we can calculate this information at install time once and for all. For 6961 // system apps, we can probably assume that this information doesn't change 6962 // after the first boot scan. As things stand, we do lots of unnecessary work. 6963 6964 // Give ourselves some initial paths; we'll come back for another 6965 // pass once we've determined ABI below. 6966 setNativeLibraryPaths(pkg); 6967 6968 // We would never need to extract libs for forward-locked and external packages, 6969 // since the container service will do it for us. We shouldn't attempt to 6970 // extract libs from system app when it was not updated. 6971 if (pkg.isForwardLocked() || isExternal(pkg) || 6972 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6973 extractLibs = false; 6974 } 6975 6976 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6977 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6978 6979 NativeLibraryHelper.Handle handle = null; 6980 try { 6981 handle = NativeLibraryHelper.Handle.create(scanFile); 6982 // TODO(multiArch): This can be null for apps that didn't go through the 6983 // usual installation process. We can calculate it again, like we 6984 // do during install time. 6985 // 6986 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6987 // unnecessary. 6988 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6989 6990 // Null out the abis so that they can be recalculated. 6991 pkg.applicationInfo.primaryCpuAbi = null; 6992 pkg.applicationInfo.secondaryCpuAbi = null; 6993 if (isMultiArch(pkg.applicationInfo)) { 6994 // Warn if we've set an abiOverride for multi-lib packages.. 6995 // By definition, we need to copy both 32 and 64 bit libraries for 6996 // such packages. 6997 if (pkg.cpuAbiOverride != null 6998 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6999 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7000 } 7001 7002 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7003 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7004 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7005 if (extractLibs) { 7006 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7007 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7008 useIsaSpecificSubdirs); 7009 } else { 7010 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7011 } 7012 } 7013 7014 maybeThrowExceptionForMultiArchCopy( 7015 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7016 7017 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7018 if (extractLibs) { 7019 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7020 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7021 useIsaSpecificSubdirs); 7022 } else { 7023 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7024 } 7025 } 7026 7027 maybeThrowExceptionForMultiArchCopy( 7028 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7029 7030 if (abi64 >= 0) { 7031 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7032 } 7033 7034 if (abi32 >= 0) { 7035 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7036 if (abi64 >= 0) { 7037 pkg.applicationInfo.secondaryCpuAbi = abi; 7038 } else { 7039 pkg.applicationInfo.primaryCpuAbi = abi; 7040 } 7041 } 7042 } else { 7043 String[] abiList = (cpuAbiOverride != null) ? 7044 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7045 7046 // Enable gross and lame hacks for apps that are built with old 7047 // SDK tools. We must scan their APKs for renderscript bitcode and 7048 // not launch them if it's present. Don't bother checking on devices 7049 // that don't have 64 bit support. 7050 boolean needsRenderScriptOverride = false; 7051 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7052 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7053 abiList = Build.SUPPORTED_32_BIT_ABIS; 7054 needsRenderScriptOverride = true; 7055 } 7056 7057 final int copyRet; 7058 if (extractLibs) { 7059 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7060 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7061 } else { 7062 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7063 } 7064 7065 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7066 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7067 "Error unpackaging native libs for app, errorCode=" + copyRet); 7068 } 7069 7070 if (copyRet >= 0) { 7071 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7072 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7073 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7074 } else if (needsRenderScriptOverride) { 7075 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7076 } 7077 } 7078 } catch (IOException ioe) { 7079 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7080 } finally { 7081 IoUtils.closeQuietly(handle); 7082 } 7083 7084 // Now that we've calculated the ABIs and determined if it's an internal app, 7085 // we will go ahead and populate the nativeLibraryPath. 7086 setNativeLibraryPaths(pkg); 7087 } 7088 7089 /** 7090 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7091 * i.e, so that all packages can be run inside a single process if required. 7092 * 7093 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7094 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7095 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7096 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7097 * updating a package that belongs to a shared user. 7098 * 7099 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7100 * adds unnecessary complexity. 7101 */ 7102 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7103 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7104 String requiredInstructionSet = null; 7105 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7106 requiredInstructionSet = VMRuntime.getInstructionSet( 7107 scannedPackage.applicationInfo.primaryCpuAbi); 7108 } 7109 7110 PackageSetting requirer = null; 7111 for (PackageSetting ps : packagesForUser) { 7112 // If packagesForUser contains scannedPackage, we skip it. This will happen 7113 // when scannedPackage is an update of an existing package. Without this check, 7114 // we will never be able to change the ABI of any package belonging to a shared 7115 // user, even if it's compatible with other packages. 7116 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7117 if (ps.primaryCpuAbiString == null) { 7118 continue; 7119 } 7120 7121 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7122 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7123 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7124 // this but there's not much we can do. 7125 String errorMessage = "Instruction set mismatch, " 7126 + ((requirer == null) ? "[caller]" : requirer) 7127 + " requires " + requiredInstructionSet + " whereas " + ps 7128 + " requires " + instructionSet; 7129 Slog.w(TAG, errorMessage); 7130 } 7131 7132 if (requiredInstructionSet == null) { 7133 requiredInstructionSet = instructionSet; 7134 requirer = ps; 7135 } 7136 } 7137 } 7138 7139 if (requiredInstructionSet != null) { 7140 String adjustedAbi; 7141 if (requirer != null) { 7142 // requirer != null implies that either scannedPackage was null or that scannedPackage 7143 // did not require an ABI, in which case we have to adjust scannedPackage to match 7144 // the ABI of the set (which is the same as requirer's ABI) 7145 adjustedAbi = requirer.primaryCpuAbiString; 7146 if (scannedPackage != null) { 7147 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7148 } 7149 } else { 7150 // requirer == null implies that we're updating all ABIs in the set to 7151 // match scannedPackage. 7152 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7153 } 7154 7155 for (PackageSetting ps : packagesForUser) { 7156 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7157 if (ps.primaryCpuAbiString != null) { 7158 continue; 7159 } 7160 7161 ps.primaryCpuAbiString = adjustedAbi; 7162 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7163 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7164 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7165 7166 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7167 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7168 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7169 ps.primaryCpuAbiString = null; 7170 ps.pkg.applicationInfo.primaryCpuAbi = null; 7171 return; 7172 } else { 7173 mInstaller.rmdex(ps.codePathString, 7174 getDexCodeInstructionSet(getPreferredInstructionSet())); 7175 } 7176 } 7177 } 7178 } 7179 } 7180 } 7181 7182 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7183 synchronized (mPackages) { 7184 mResolverReplaced = true; 7185 // Set up information for custom user intent resolution activity. 7186 mResolveActivity.applicationInfo = pkg.applicationInfo; 7187 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7188 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7189 mResolveActivity.processName = pkg.applicationInfo.packageName; 7190 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7191 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7192 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7193 mResolveActivity.theme = 0; 7194 mResolveActivity.exported = true; 7195 mResolveActivity.enabled = true; 7196 mResolveInfo.activityInfo = mResolveActivity; 7197 mResolveInfo.priority = 0; 7198 mResolveInfo.preferredOrder = 0; 7199 mResolveInfo.match = 0; 7200 mResolveComponentName = mCustomResolverComponentName; 7201 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7202 mResolveComponentName); 7203 } 7204 } 7205 7206 private static String calculateBundledApkRoot(final String codePathString) { 7207 final File codePath = new File(codePathString); 7208 final File codeRoot; 7209 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7210 codeRoot = Environment.getRootDirectory(); 7211 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7212 codeRoot = Environment.getOemDirectory(); 7213 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7214 codeRoot = Environment.getVendorDirectory(); 7215 } else { 7216 // Unrecognized code path; take its top real segment as the apk root: 7217 // e.g. /something/app/blah.apk => /something 7218 try { 7219 File f = codePath.getCanonicalFile(); 7220 File parent = f.getParentFile(); // non-null because codePath is a file 7221 File tmp; 7222 while ((tmp = parent.getParentFile()) != null) { 7223 f = parent; 7224 parent = tmp; 7225 } 7226 codeRoot = f; 7227 Slog.w(TAG, "Unrecognized code path " 7228 + codePath + " - using " + codeRoot); 7229 } catch (IOException e) { 7230 // Can't canonicalize the code path -- shenanigans? 7231 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7232 return Environment.getRootDirectory().getPath(); 7233 } 7234 } 7235 return codeRoot.getPath(); 7236 } 7237 7238 /** 7239 * Derive and set the location of native libraries for the given package, 7240 * which varies depending on where and how the package was installed. 7241 */ 7242 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7243 final ApplicationInfo info = pkg.applicationInfo; 7244 final String codePath = pkg.codePath; 7245 final File codeFile = new File(codePath); 7246 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7247 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7248 7249 info.nativeLibraryRootDir = null; 7250 info.nativeLibraryRootRequiresIsa = false; 7251 info.nativeLibraryDir = null; 7252 info.secondaryNativeLibraryDir = null; 7253 7254 if (isApkFile(codeFile)) { 7255 // Monolithic install 7256 if (bundledApp) { 7257 // If "/system/lib64/apkname" exists, assume that is the per-package 7258 // native library directory to use; otherwise use "/system/lib/apkname". 7259 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7260 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7261 getPrimaryInstructionSet(info)); 7262 7263 // This is a bundled system app so choose the path based on the ABI. 7264 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7265 // is just the default path. 7266 final String apkName = deriveCodePathName(codePath); 7267 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7268 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7269 apkName).getAbsolutePath(); 7270 7271 if (info.secondaryCpuAbi != null) { 7272 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7273 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7274 secondaryLibDir, apkName).getAbsolutePath(); 7275 } 7276 } else if (asecApp) { 7277 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7278 .getAbsolutePath(); 7279 } else { 7280 final String apkName = deriveCodePathName(codePath); 7281 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7282 .getAbsolutePath(); 7283 } 7284 7285 info.nativeLibraryRootRequiresIsa = false; 7286 info.nativeLibraryDir = info.nativeLibraryRootDir; 7287 } else { 7288 // Cluster install 7289 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7290 info.nativeLibraryRootRequiresIsa = true; 7291 7292 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7293 getPrimaryInstructionSet(info)).getAbsolutePath(); 7294 7295 if (info.secondaryCpuAbi != null) { 7296 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7297 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7298 } 7299 } 7300 } 7301 7302 /** 7303 * Calculate the abis and roots for a bundled app. These can uniquely 7304 * be determined from the contents of the system partition, i.e whether 7305 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7306 * of this information, and instead assume that the system was built 7307 * sensibly. 7308 */ 7309 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7310 PackageSetting pkgSetting) { 7311 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7312 7313 // If "/system/lib64/apkname" exists, assume that is the per-package 7314 // native library directory to use; otherwise use "/system/lib/apkname". 7315 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7316 setBundledAppAbi(pkg, apkRoot, apkName); 7317 // pkgSetting might be null during rescan following uninstall of updates 7318 // to a bundled app, so accommodate that possibility. The settings in 7319 // that case will be established later from the parsed package. 7320 // 7321 // If the settings aren't null, sync them up with what we've just derived. 7322 // note that apkRoot isn't stored in the package settings. 7323 if (pkgSetting != null) { 7324 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7325 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7326 } 7327 } 7328 7329 /** 7330 * Deduces the ABI of a bundled app and sets the relevant fields on the 7331 * parsed pkg object. 7332 * 7333 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7334 * under which system libraries are installed. 7335 * @param apkName the name of the installed package. 7336 */ 7337 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7338 final File codeFile = new File(pkg.codePath); 7339 7340 final boolean has64BitLibs; 7341 final boolean has32BitLibs; 7342 if (isApkFile(codeFile)) { 7343 // Monolithic install 7344 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7345 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7346 } else { 7347 // Cluster install 7348 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7349 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7350 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7351 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7352 has64BitLibs = (new File(rootDir, isa)).exists(); 7353 } else { 7354 has64BitLibs = false; 7355 } 7356 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7357 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7358 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7359 has32BitLibs = (new File(rootDir, isa)).exists(); 7360 } else { 7361 has32BitLibs = false; 7362 } 7363 } 7364 7365 if (has64BitLibs && !has32BitLibs) { 7366 // The package has 64 bit libs, but not 32 bit libs. Its primary 7367 // ABI should be 64 bit. We can safely assume here that the bundled 7368 // native libraries correspond to the most preferred ABI in the list. 7369 7370 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7371 pkg.applicationInfo.secondaryCpuAbi = null; 7372 } else if (has32BitLibs && !has64BitLibs) { 7373 // The package has 32 bit libs but not 64 bit libs. Its primary 7374 // ABI should be 32 bit. 7375 7376 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7377 pkg.applicationInfo.secondaryCpuAbi = null; 7378 } else if (has32BitLibs && has64BitLibs) { 7379 // The application has both 64 and 32 bit bundled libraries. We check 7380 // here that the app declares multiArch support, and warn if it doesn't. 7381 // 7382 // We will be lenient here and record both ABIs. The primary will be the 7383 // ABI that's higher on the list, i.e, a device that's configured to prefer 7384 // 64 bit apps will see a 64 bit primary ABI, 7385 7386 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7387 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7388 } 7389 7390 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7391 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7392 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7393 } else { 7394 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7395 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7396 } 7397 } else { 7398 pkg.applicationInfo.primaryCpuAbi = null; 7399 pkg.applicationInfo.secondaryCpuAbi = null; 7400 } 7401 } 7402 7403 private void killApplication(String pkgName, int appId, String reason) { 7404 // Request the ActivityManager to kill the process(only for existing packages) 7405 // so that we do not end up in a confused state while the user is still using the older 7406 // version of the application while the new one gets installed. 7407 IActivityManager am = ActivityManagerNative.getDefault(); 7408 if (am != null) { 7409 try { 7410 am.killApplicationWithAppId(pkgName, appId, reason); 7411 } catch (RemoteException e) { 7412 } 7413 } 7414 } 7415 7416 void removePackageLI(PackageSetting ps, boolean chatty) { 7417 if (DEBUG_INSTALL) { 7418 if (chatty) 7419 Log.d(TAG, "Removing package " + ps.name); 7420 } 7421 7422 // writer 7423 synchronized (mPackages) { 7424 mPackages.remove(ps.name); 7425 final PackageParser.Package pkg = ps.pkg; 7426 if (pkg != null) { 7427 cleanPackageDataStructuresLILPw(pkg, chatty); 7428 } 7429 } 7430 } 7431 7432 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7433 if (DEBUG_INSTALL) { 7434 if (chatty) 7435 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7436 } 7437 7438 // writer 7439 synchronized (mPackages) { 7440 mPackages.remove(pkg.applicationInfo.packageName); 7441 cleanPackageDataStructuresLILPw(pkg, chatty); 7442 } 7443 } 7444 7445 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7446 int N = pkg.providers.size(); 7447 StringBuilder r = null; 7448 int i; 7449 for (i=0; i<N; i++) { 7450 PackageParser.Provider p = pkg.providers.get(i); 7451 mProviders.removeProvider(p); 7452 if (p.info.authority == null) { 7453 7454 /* There was another ContentProvider with this authority when 7455 * this app was installed so this authority is null, 7456 * Ignore it as we don't have to unregister the provider. 7457 */ 7458 continue; 7459 } 7460 String names[] = p.info.authority.split(";"); 7461 for (int j = 0; j < names.length; j++) { 7462 if (mProvidersByAuthority.get(names[j]) == p) { 7463 mProvidersByAuthority.remove(names[j]); 7464 if (DEBUG_REMOVE) { 7465 if (chatty) 7466 Log.d(TAG, "Unregistered content provider: " + names[j] 7467 + ", className = " + p.info.name + ", isSyncable = " 7468 + p.info.isSyncable); 7469 } 7470 } 7471 } 7472 if (DEBUG_REMOVE && chatty) { 7473 if (r == null) { 7474 r = new StringBuilder(256); 7475 } else { 7476 r.append(' '); 7477 } 7478 r.append(p.info.name); 7479 } 7480 } 7481 if (r != null) { 7482 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7483 } 7484 7485 N = pkg.services.size(); 7486 r = null; 7487 for (i=0; i<N; i++) { 7488 PackageParser.Service s = pkg.services.get(i); 7489 mServices.removeService(s); 7490 if (chatty) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(s.info.name); 7497 } 7498 } 7499 if (r != null) { 7500 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7501 } 7502 7503 N = pkg.receivers.size(); 7504 r = null; 7505 for (i=0; i<N; i++) { 7506 PackageParser.Activity a = pkg.receivers.get(i); 7507 mReceivers.removeActivity(a, "receiver"); 7508 if (DEBUG_REMOVE && chatty) { 7509 if (r == null) { 7510 r = new StringBuilder(256); 7511 } else { 7512 r.append(' '); 7513 } 7514 r.append(a.info.name); 7515 } 7516 } 7517 if (r != null) { 7518 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7519 } 7520 7521 N = pkg.activities.size(); 7522 r = null; 7523 for (i=0; i<N; i++) { 7524 PackageParser.Activity a = pkg.activities.get(i); 7525 mActivities.removeActivity(a, "activity"); 7526 if (DEBUG_REMOVE && chatty) { 7527 if (r == null) { 7528 r = new StringBuilder(256); 7529 } else { 7530 r.append(' '); 7531 } 7532 r.append(a.info.name); 7533 } 7534 } 7535 if (r != null) { 7536 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7537 } 7538 7539 N = pkg.permissions.size(); 7540 r = null; 7541 for (i=0; i<N; i++) { 7542 PackageParser.Permission p = pkg.permissions.get(i); 7543 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7544 if (bp == null) { 7545 bp = mSettings.mPermissionTrees.get(p.info.name); 7546 } 7547 if (bp != null && bp.perm == p) { 7548 bp.perm = null; 7549 if (DEBUG_REMOVE && chatty) { 7550 if (r == null) { 7551 r = new StringBuilder(256); 7552 } else { 7553 r.append(' '); 7554 } 7555 r.append(p.info.name); 7556 } 7557 } 7558 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7559 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7560 if (appOpPerms != null) { 7561 appOpPerms.remove(pkg.packageName); 7562 } 7563 } 7564 } 7565 if (r != null) { 7566 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7567 } 7568 7569 N = pkg.requestedPermissions.size(); 7570 r = null; 7571 for (i=0; i<N; i++) { 7572 String perm = pkg.requestedPermissions.get(i); 7573 BasePermission bp = mSettings.mPermissions.get(perm); 7574 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7575 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7576 if (appOpPerms != null) { 7577 appOpPerms.remove(pkg.packageName); 7578 if (appOpPerms.isEmpty()) { 7579 mAppOpPermissionPackages.remove(perm); 7580 } 7581 } 7582 } 7583 } 7584 if (r != null) { 7585 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7586 } 7587 7588 N = pkg.instrumentation.size(); 7589 r = null; 7590 for (i=0; i<N; i++) { 7591 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7592 mInstrumentation.remove(a.getComponentName()); 7593 if (DEBUG_REMOVE && chatty) { 7594 if (r == null) { 7595 r = new StringBuilder(256); 7596 } else { 7597 r.append(' '); 7598 } 7599 r.append(a.info.name); 7600 } 7601 } 7602 if (r != null) { 7603 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7604 } 7605 7606 r = null; 7607 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7608 // Only system apps can hold shared libraries. 7609 if (pkg.libraryNames != null) { 7610 for (i=0; i<pkg.libraryNames.size(); i++) { 7611 String name = pkg.libraryNames.get(i); 7612 SharedLibraryEntry cur = mSharedLibraries.get(name); 7613 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7614 mSharedLibraries.remove(name); 7615 if (DEBUG_REMOVE && chatty) { 7616 if (r == null) { 7617 r = new StringBuilder(256); 7618 } else { 7619 r.append(' '); 7620 } 7621 r.append(name); 7622 } 7623 } 7624 } 7625 } 7626 } 7627 if (r != null) { 7628 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7629 } 7630 } 7631 7632 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7633 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7634 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7635 return true; 7636 } 7637 } 7638 return false; 7639 } 7640 7641 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7642 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7643 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7644 7645 private void updatePermissionsLPw(String changingPkg, 7646 PackageParser.Package pkgInfo, int flags) { 7647 // Make sure there are no dangling permission trees. 7648 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7649 while (it.hasNext()) { 7650 final BasePermission bp = it.next(); 7651 if (bp.packageSetting == null) { 7652 // We may not yet have parsed the package, so just see if 7653 // we still know about its settings. 7654 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7655 } 7656 if (bp.packageSetting == null) { 7657 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7658 + " from package " + bp.sourcePackage); 7659 it.remove(); 7660 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7661 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7662 Slog.i(TAG, "Removing old permission tree: " + bp.name 7663 + " from package " + bp.sourcePackage); 7664 flags |= UPDATE_PERMISSIONS_ALL; 7665 it.remove(); 7666 } 7667 } 7668 } 7669 7670 // Make sure all dynamic permissions have been assigned to a package, 7671 // and make sure there are no dangling permissions. 7672 it = mSettings.mPermissions.values().iterator(); 7673 while (it.hasNext()) { 7674 final BasePermission bp = it.next(); 7675 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7676 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7677 + bp.name + " pkg=" + bp.sourcePackage 7678 + " info=" + bp.pendingInfo); 7679 if (bp.packageSetting == null && bp.pendingInfo != null) { 7680 final BasePermission tree = findPermissionTreeLP(bp.name); 7681 if (tree != null && tree.perm != null) { 7682 bp.packageSetting = tree.packageSetting; 7683 bp.perm = new PackageParser.Permission(tree.perm.owner, 7684 new PermissionInfo(bp.pendingInfo)); 7685 bp.perm.info.packageName = tree.perm.info.packageName; 7686 bp.perm.info.name = bp.name; 7687 bp.uid = tree.uid; 7688 } 7689 } 7690 } 7691 if (bp.packageSetting == null) { 7692 // We may not yet have parsed the package, so just see if 7693 // we still know about its settings. 7694 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7695 } 7696 if (bp.packageSetting == null) { 7697 Slog.w(TAG, "Removing dangling permission: " + bp.name 7698 + " from package " + bp.sourcePackage); 7699 it.remove(); 7700 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7701 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7702 Slog.i(TAG, "Removing old permission: " + bp.name 7703 + " from package " + bp.sourcePackage); 7704 flags |= UPDATE_PERMISSIONS_ALL; 7705 it.remove(); 7706 } 7707 } 7708 } 7709 7710 // Now update the permissions for all packages, in particular 7711 // replace the granted permissions of the system packages. 7712 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7713 for (PackageParser.Package pkg : mPackages.values()) { 7714 if (pkg != pkgInfo) { 7715 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7716 changingPkg); 7717 } 7718 } 7719 } 7720 7721 if (pkgInfo != null) { 7722 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7723 } 7724 } 7725 7726 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7727 String packageOfInterest) { 7728 // IMPORTANT: There are two types of permissions: install and runtime. 7729 // Install time permissions are granted when the app is installed to 7730 // all device users and users added in the future. Runtime permissions 7731 // are granted at runtime explicitly to specific users. Normal and signature 7732 // protected permissions are install time permissions. Dangerous permissions 7733 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7734 // otherwise they are runtime permissions. This function does not manage 7735 // runtime permissions except for the case an app targeting Lollipop MR1 7736 // being upgraded to target a newer SDK, in which case dangerous permissions 7737 // are transformed from install time to runtime ones. 7738 7739 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7740 if (ps == null) { 7741 return; 7742 } 7743 7744 PermissionsState permissionsState = ps.getPermissionsState(); 7745 PermissionsState origPermissions = permissionsState; 7746 7747 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7748 7749 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7750 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7751 7752 boolean changedInstallPermission = false; 7753 7754 if (replace) { 7755 ps.installPermissionsFixed = false; 7756 if (!ps.isSharedUser()) { 7757 origPermissions = new PermissionsState(permissionsState); 7758 permissionsState.reset(); 7759 } 7760 } 7761 7762 permissionsState.setGlobalGids(mGlobalGids); 7763 7764 final int N = pkg.requestedPermissions.size(); 7765 for (int i=0; i<N; i++) { 7766 final String name = pkg.requestedPermissions.get(i); 7767 final BasePermission bp = mSettings.mPermissions.get(name); 7768 7769 if (DEBUG_INSTALL) { 7770 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7771 } 7772 7773 if (bp == null || bp.packageSetting == null) { 7774 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7775 Slog.w(TAG, "Unknown permission " + name 7776 + " in package " + pkg.packageName); 7777 } 7778 continue; 7779 } 7780 7781 final String perm = bp.name; 7782 boolean allowedSig = false; 7783 int grant = GRANT_DENIED; 7784 7785 // Keep track of app op permissions. 7786 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7787 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7788 if (pkgs == null) { 7789 pkgs = new ArraySet<>(); 7790 mAppOpPermissionPackages.put(bp.name, pkgs); 7791 } 7792 pkgs.add(pkg.packageName); 7793 } 7794 7795 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7796 switch (level) { 7797 case PermissionInfo.PROTECTION_NORMAL: { 7798 // For all apps normal permissions are install time ones. 7799 grant = GRANT_INSTALL; 7800 } break; 7801 7802 case PermissionInfo.PROTECTION_DANGEROUS: { 7803 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7804 // For legacy apps dangerous permissions are install time ones. 7805 grant = GRANT_INSTALL_LEGACY; 7806 } else if (ps.isSystem()) { 7807 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7808 if (origPermissions.hasInstallPermission(bp.name)) { 7809 // If a system app had an install permission, then the app was 7810 // upgraded and we grant the permissions as runtime to all users. 7811 grant = GRANT_UPGRADE; 7812 upgradeUserIds = currentUserIds; 7813 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7814 // If users changed since the last permissions update for a 7815 // system app, we grant the permission as runtime to the new users. 7816 grant = GRANT_UPGRADE; 7817 upgradeUserIds = currentUserIds; 7818 for (int userId : updatedUserIds) { 7819 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7820 } 7821 } else { 7822 // Otherwise, we grant the permission as runtime if the app 7823 // already had it, i.e. we preserve runtime permissions. 7824 grant = GRANT_RUNTIME; 7825 } 7826 } else if (origPermissions.hasInstallPermission(bp.name)) { 7827 // For legacy apps that became modern, install becomes runtime. 7828 grant = GRANT_UPGRADE; 7829 upgradeUserIds = currentUserIds; 7830 } else if (replace) { 7831 // For upgraded modern apps keep runtime permissions unchanged. 7832 grant = GRANT_RUNTIME; 7833 } 7834 } break; 7835 7836 case PermissionInfo.PROTECTION_SIGNATURE: { 7837 // For all apps signature permissions are install time ones. 7838 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7839 if (allowedSig) { 7840 grant = GRANT_INSTALL; 7841 } 7842 } break; 7843 } 7844 7845 if (DEBUG_INSTALL) { 7846 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7847 } 7848 7849 if (grant != GRANT_DENIED) { 7850 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7851 // If this is an existing, non-system package, then 7852 // we can't add any new permissions to it. 7853 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7854 // Except... if this is a permission that was added 7855 // to the platform (note: need to only do this when 7856 // updating the platform). 7857 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7858 grant = GRANT_DENIED; 7859 } 7860 } 7861 } 7862 7863 switch (grant) { 7864 case GRANT_INSTALL: { 7865 // Revoke this as runtime permission to handle the case of 7866 // a runtime permssion being downgraded to an install one. 7867 for (int userId : UserManagerService.getInstance().getUserIds()) { 7868 if (origPermissions.getRuntimePermissionState( 7869 bp.name, userId) != null) { 7870 // Revoke the runtime permission and clear the flags. 7871 origPermissions.revokeRuntimePermission(bp, userId); 7872 origPermissions.updatePermissionFlags(bp, userId, 7873 PackageManager.MASK_PERMISSION_FLAGS, 0); 7874 // If we revoked a permission permission, we have to write. 7875 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7876 changedRuntimePermissionUserIds, userId); 7877 } 7878 } 7879 // Grant an install permission. 7880 if (permissionsState.grantInstallPermission(bp) != 7881 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7882 changedInstallPermission = true; 7883 } 7884 } break; 7885 7886 case GRANT_INSTALL_LEGACY: { 7887 // Grant an install permission. 7888 if (permissionsState.grantInstallPermission(bp) != 7889 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7890 changedInstallPermission = true; 7891 } 7892 } break; 7893 7894 case GRANT_RUNTIME: { 7895 // Grant previously granted runtime permissions. 7896 for (int userId : UserManagerService.getInstance().getUserIds()) { 7897 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7898 PermissionState permissionState = origPermissions 7899 .getRuntimePermissionState(bp.name, userId); 7900 final int flags = permissionState.getFlags(); 7901 if (permissionsState.grantRuntimePermission(bp, userId) == 7902 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7903 // If we cannot put the permission as it was, we have to write. 7904 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7905 changedRuntimePermissionUserIds, userId); 7906 } else { 7907 // System components not only get the permissions but 7908 // they are also fixed, so nothing can change that. 7909 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7910 ? flags 7911 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7912 // Propagate the permission flags. 7913 permissionsState.updatePermissionFlags(bp, userId, 7914 newFlags, newFlags); 7915 } 7916 } 7917 } 7918 } break; 7919 7920 case GRANT_UPGRADE: { 7921 // Grant runtime permissions for a previously held install permission. 7922 PermissionState permissionState = origPermissions 7923 .getInstallPermissionState(bp.name); 7924 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7925 7926 origPermissions.revokeInstallPermission(bp); 7927 // We will be transferring the permission flags, so clear them. 7928 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7929 PackageManager.MASK_PERMISSION_FLAGS, 0); 7930 7931 // If the permission is not to be promoted to runtime we ignore it and 7932 // also its other flags as they are not applicable to install permissions. 7933 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7934 for (int userId : upgradeUserIds) { 7935 if (permissionsState.grantRuntimePermission(bp, userId) != 7936 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7937 // System components not only get the permissions but 7938 // they are also fixed so nothing can change that. 7939 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7940 ? flags 7941 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7942 // Transfer the permission flags. 7943 permissionsState.updatePermissionFlags(bp, userId, 7944 newFlags, newFlags); 7945 // If we granted the permission, we have to write. 7946 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7947 changedRuntimePermissionUserIds, userId); 7948 } 7949 } 7950 } 7951 } break; 7952 7953 default: { 7954 if (packageOfInterest == null 7955 || packageOfInterest.equals(pkg.packageName)) { 7956 Slog.w(TAG, "Not granting permission " + perm 7957 + " to package " + pkg.packageName 7958 + " because it was previously installed without"); 7959 } 7960 } break; 7961 } 7962 } else { 7963 if (permissionsState.revokeInstallPermission(bp) != 7964 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7965 // Also drop the permission flags. 7966 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7967 PackageManager.MASK_PERMISSION_FLAGS, 0); 7968 changedInstallPermission = true; 7969 Slog.i(TAG, "Un-granting permission " + perm 7970 + " from package " + pkg.packageName 7971 + " (protectionLevel=" + bp.protectionLevel 7972 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7973 + ")"); 7974 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7975 // Don't print warning for app op permissions, since it is fine for them 7976 // not to be granted, there is a UI for the user to decide. 7977 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7978 Slog.w(TAG, "Not granting permission " + perm 7979 + " to package " + pkg.packageName 7980 + " (protectionLevel=" + bp.protectionLevel 7981 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7982 + ")"); 7983 } 7984 } 7985 } 7986 } 7987 7988 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7989 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7990 // This is the first that we have heard about this package, so the 7991 // permissions we have now selected are fixed until explicitly 7992 // changed. 7993 ps.installPermissionsFixed = true; 7994 } 7995 7996 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7997 7998 // Persist the runtime permissions state for users with changes. 7999 for (int userId : changedRuntimePermissionUserIds) { 8000 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8001 } 8002 } 8003 8004 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8005 boolean allowed = false; 8006 final int NP = PackageParser.NEW_PERMISSIONS.length; 8007 for (int ip=0; ip<NP; ip++) { 8008 final PackageParser.NewPermissionInfo npi 8009 = PackageParser.NEW_PERMISSIONS[ip]; 8010 if (npi.name.equals(perm) 8011 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8012 allowed = true; 8013 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8014 + pkg.packageName); 8015 break; 8016 } 8017 } 8018 return allowed; 8019 } 8020 8021 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8022 BasePermission bp, PermissionsState origPermissions) { 8023 boolean allowed; 8024 allowed = (compareSignatures( 8025 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8026 == PackageManager.SIGNATURE_MATCH) 8027 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8028 == PackageManager.SIGNATURE_MATCH); 8029 if (!allowed && (bp.protectionLevel 8030 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8031 if (isSystemApp(pkg)) { 8032 // For updated system applications, a system permission 8033 // is granted only if it had been defined by the original application. 8034 if (pkg.isUpdatedSystemApp()) { 8035 final PackageSetting sysPs = mSettings 8036 .getDisabledSystemPkgLPr(pkg.packageName); 8037 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8038 // If the original was granted this permission, we take 8039 // that grant decision as read and propagate it to the 8040 // update. 8041 if (sysPs.isPrivileged()) { 8042 allowed = true; 8043 } 8044 } else { 8045 // The system apk may have been updated with an older 8046 // version of the one on the data partition, but which 8047 // granted a new system permission that it didn't have 8048 // before. In this case we do want to allow the app to 8049 // now get the new permission if the ancestral apk is 8050 // privileged to get it. 8051 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8052 for (int j=0; 8053 j<sysPs.pkg.requestedPermissions.size(); j++) { 8054 if (perm.equals( 8055 sysPs.pkg.requestedPermissions.get(j))) { 8056 allowed = true; 8057 break; 8058 } 8059 } 8060 } 8061 } 8062 } else { 8063 allowed = isPrivilegedApp(pkg); 8064 } 8065 } 8066 } 8067 if (!allowed && (bp.protectionLevel 8068 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8069 // For development permissions, a development permission 8070 // is granted only if it was already granted. 8071 allowed = origPermissions.hasInstallPermission(perm); 8072 } 8073 return allowed; 8074 } 8075 8076 final class ActivityIntentResolver 8077 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8078 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8079 boolean defaultOnly, int userId) { 8080 if (!sUserManager.exists(userId)) return null; 8081 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8082 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8083 } 8084 8085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8086 int userId) { 8087 if (!sUserManager.exists(userId)) return null; 8088 mFlags = flags; 8089 return super.queryIntent(intent, resolvedType, 8090 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8091 } 8092 8093 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8094 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8095 if (!sUserManager.exists(userId)) return null; 8096 if (packageActivities == null) { 8097 return null; 8098 } 8099 mFlags = flags; 8100 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8101 final int N = packageActivities.size(); 8102 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8103 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8104 8105 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8106 for (int i = 0; i < N; ++i) { 8107 intentFilters = packageActivities.get(i).intents; 8108 if (intentFilters != null && intentFilters.size() > 0) { 8109 PackageParser.ActivityIntentInfo[] array = 8110 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8111 intentFilters.toArray(array); 8112 listCut.add(array); 8113 } 8114 } 8115 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8116 } 8117 8118 public final void addActivity(PackageParser.Activity a, String type) { 8119 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8120 mActivities.put(a.getComponentName(), a); 8121 if (DEBUG_SHOW_INFO) 8122 Log.v( 8123 TAG, " " + type + " " + 8124 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8125 if (DEBUG_SHOW_INFO) 8126 Log.v(TAG, " Class=" + a.info.name); 8127 final int NI = a.intents.size(); 8128 for (int j=0; j<NI; j++) { 8129 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8130 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8131 intent.setPriority(0); 8132 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8133 + a.className + " with priority > 0, forcing to 0"); 8134 } 8135 if (DEBUG_SHOW_INFO) { 8136 Log.v(TAG, " IntentFilter:"); 8137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8138 } 8139 if (!intent.debugCheck()) { 8140 Log.w(TAG, "==> For Activity " + a.info.name); 8141 } 8142 addFilter(intent); 8143 } 8144 } 8145 8146 public final void removeActivity(PackageParser.Activity a, String type) { 8147 mActivities.remove(a.getComponentName()); 8148 if (DEBUG_SHOW_INFO) { 8149 Log.v(TAG, " " + type + " " 8150 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8151 : a.info.name) + ":"); 8152 Log.v(TAG, " Class=" + a.info.name); 8153 } 8154 final int NI = a.intents.size(); 8155 for (int j=0; j<NI; j++) { 8156 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8157 if (DEBUG_SHOW_INFO) { 8158 Log.v(TAG, " IntentFilter:"); 8159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8160 } 8161 removeFilter(intent); 8162 } 8163 } 8164 8165 @Override 8166 protected boolean allowFilterResult( 8167 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8168 ActivityInfo filterAi = filter.activity.info; 8169 for (int i=dest.size()-1; i>=0; i--) { 8170 ActivityInfo destAi = dest.get(i).activityInfo; 8171 if (destAi.name == filterAi.name 8172 && destAi.packageName == filterAi.packageName) { 8173 return false; 8174 } 8175 } 8176 return true; 8177 } 8178 8179 @Override 8180 protected ActivityIntentInfo[] newArray(int size) { 8181 return new ActivityIntentInfo[size]; 8182 } 8183 8184 @Override 8185 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8186 if (!sUserManager.exists(userId)) return true; 8187 PackageParser.Package p = filter.activity.owner; 8188 if (p != null) { 8189 PackageSetting ps = (PackageSetting)p.mExtras; 8190 if (ps != null) { 8191 // System apps are never considered stopped for purposes of 8192 // filtering, because there may be no way for the user to 8193 // actually re-launch them. 8194 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8195 && ps.getStopped(userId); 8196 } 8197 } 8198 return false; 8199 } 8200 8201 @Override 8202 protected boolean isPackageForFilter(String packageName, 8203 PackageParser.ActivityIntentInfo info) { 8204 return packageName.equals(info.activity.owner.packageName); 8205 } 8206 8207 @Override 8208 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8209 int match, int userId) { 8210 if (!sUserManager.exists(userId)) return null; 8211 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8212 return null; 8213 } 8214 final PackageParser.Activity activity = info.activity; 8215 if (mSafeMode && (activity.info.applicationInfo.flags 8216 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8217 return null; 8218 } 8219 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8220 if (ps == null) { 8221 return null; 8222 } 8223 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8224 ps.readUserState(userId), userId); 8225 if (ai == null) { 8226 return null; 8227 } 8228 final ResolveInfo res = new ResolveInfo(); 8229 res.activityInfo = ai; 8230 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8231 res.filter = info; 8232 } 8233 if (info != null) { 8234 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8235 } 8236 res.priority = info.getPriority(); 8237 res.preferredOrder = activity.owner.mPreferredOrder; 8238 //System.out.println("Result: " + res.activityInfo.className + 8239 // " = " + res.priority); 8240 res.match = match; 8241 res.isDefault = info.hasDefault; 8242 res.labelRes = info.labelRes; 8243 res.nonLocalizedLabel = info.nonLocalizedLabel; 8244 if (userNeedsBadging(userId)) { 8245 res.noResourceId = true; 8246 } else { 8247 res.icon = info.icon; 8248 } 8249 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8250 return res; 8251 } 8252 8253 @Override 8254 protected void sortResults(List<ResolveInfo> results) { 8255 Collections.sort(results, mResolvePrioritySorter); 8256 } 8257 8258 @Override 8259 protected void dumpFilter(PrintWriter out, String prefix, 8260 PackageParser.ActivityIntentInfo filter) { 8261 out.print(prefix); out.print( 8262 Integer.toHexString(System.identityHashCode(filter.activity))); 8263 out.print(' '); 8264 filter.activity.printComponentShortName(out); 8265 out.print(" filter "); 8266 out.println(Integer.toHexString(System.identityHashCode(filter))); 8267 } 8268 8269 @Override 8270 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8271 return filter.activity; 8272 } 8273 8274 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8275 PackageParser.Activity activity = (PackageParser.Activity)label; 8276 out.print(prefix); out.print( 8277 Integer.toHexString(System.identityHashCode(activity))); 8278 out.print(' '); 8279 activity.printComponentShortName(out); 8280 if (count > 1) { 8281 out.print(" ("); out.print(count); out.print(" filters)"); 8282 } 8283 out.println(); 8284 } 8285 8286// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8287// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8288// final List<ResolveInfo> retList = Lists.newArrayList(); 8289// while (i.hasNext()) { 8290// final ResolveInfo resolveInfo = i.next(); 8291// if (isEnabledLP(resolveInfo.activityInfo)) { 8292// retList.add(resolveInfo); 8293// } 8294// } 8295// return retList; 8296// } 8297 8298 // Keys are String (activity class name), values are Activity. 8299 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8300 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8301 private int mFlags; 8302 } 8303 8304 private final class ServiceIntentResolver 8305 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8306 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8307 boolean defaultOnly, int userId) { 8308 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8309 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8310 } 8311 8312 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8313 int userId) { 8314 if (!sUserManager.exists(userId)) return null; 8315 mFlags = flags; 8316 return super.queryIntent(intent, resolvedType, 8317 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8318 } 8319 8320 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8321 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8322 if (!sUserManager.exists(userId)) return null; 8323 if (packageServices == null) { 8324 return null; 8325 } 8326 mFlags = flags; 8327 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8328 final int N = packageServices.size(); 8329 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8330 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8331 8332 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8333 for (int i = 0; i < N; ++i) { 8334 intentFilters = packageServices.get(i).intents; 8335 if (intentFilters != null && intentFilters.size() > 0) { 8336 PackageParser.ServiceIntentInfo[] array = 8337 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8338 intentFilters.toArray(array); 8339 listCut.add(array); 8340 } 8341 } 8342 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8343 } 8344 8345 public final void addService(PackageParser.Service s) { 8346 mServices.put(s.getComponentName(), s); 8347 if (DEBUG_SHOW_INFO) { 8348 Log.v(TAG, " " 8349 + (s.info.nonLocalizedLabel != null 8350 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8351 Log.v(TAG, " Class=" + s.info.name); 8352 } 8353 final int NI = s.intents.size(); 8354 int j; 8355 for (j=0; j<NI; j++) { 8356 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8357 if (DEBUG_SHOW_INFO) { 8358 Log.v(TAG, " IntentFilter:"); 8359 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8360 } 8361 if (!intent.debugCheck()) { 8362 Log.w(TAG, "==> For Service " + s.info.name); 8363 } 8364 addFilter(intent); 8365 } 8366 } 8367 8368 public final void removeService(PackageParser.Service s) { 8369 mServices.remove(s.getComponentName()); 8370 if (DEBUG_SHOW_INFO) { 8371 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8372 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8373 Log.v(TAG, " Class=" + s.info.name); 8374 } 8375 final int NI = s.intents.size(); 8376 int j; 8377 for (j=0; j<NI; j++) { 8378 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8379 if (DEBUG_SHOW_INFO) { 8380 Log.v(TAG, " IntentFilter:"); 8381 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8382 } 8383 removeFilter(intent); 8384 } 8385 } 8386 8387 @Override 8388 protected boolean allowFilterResult( 8389 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8390 ServiceInfo filterSi = filter.service.info; 8391 for (int i=dest.size()-1; i>=0; i--) { 8392 ServiceInfo destAi = dest.get(i).serviceInfo; 8393 if (destAi.name == filterSi.name 8394 && destAi.packageName == filterSi.packageName) { 8395 return false; 8396 } 8397 } 8398 return true; 8399 } 8400 8401 @Override 8402 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8403 return new PackageParser.ServiceIntentInfo[size]; 8404 } 8405 8406 @Override 8407 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8408 if (!sUserManager.exists(userId)) return true; 8409 PackageParser.Package p = filter.service.owner; 8410 if (p != null) { 8411 PackageSetting ps = (PackageSetting)p.mExtras; 8412 if (ps != null) { 8413 // System apps are never considered stopped for purposes of 8414 // filtering, because there may be no way for the user to 8415 // actually re-launch them. 8416 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8417 && ps.getStopped(userId); 8418 } 8419 } 8420 return false; 8421 } 8422 8423 @Override 8424 protected boolean isPackageForFilter(String packageName, 8425 PackageParser.ServiceIntentInfo info) { 8426 return packageName.equals(info.service.owner.packageName); 8427 } 8428 8429 @Override 8430 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8431 int match, int userId) { 8432 if (!sUserManager.exists(userId)) return null; 8433 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8434 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8435 return null; 8436 } 8437 final PackageParser.Service service = info.service; 8438 if (mSafeMode && (service.info.applicationInfo.flags 8439 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8440 return null; 8441 } 8442 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8443 if (ps == null) { 8444 return null; 8445 } 8446 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8447 ps.readUserState(userId), userId); 8448 if (si == null) { 8449 return null; 8450 } 8451 final ResolveInfo res = new ResolveInfo(); 8452 res.serviceInfo = si; 8453 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8454 res.filter = filter; 8455 } 8456 res.priority = info.getPriority(); 8457 res.preferredOrder = service.owner.mPreferredOrder; 8458 res.match = match; 8459 res.isDefault = info.hasDefault; 8460 res.labelRes = info.labelRes; 8461 res.nonLocalizedLabel = info.nonLocalizedLabel; 8462 res.icon = info.icon; 8463 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8464 return res; 8465 } 8466 8467 @Override 8468 protected void sortResults(List<ResolveInfo> results) { 8469 Collections.sort(results, mResolvePrioritySorter); 8470 } 8471 8472 @Override 8473 protected void dumpFilter(PrintWriter out, String prefix, 8474 PackageParser.ServiceIntentInfo filter) { 8475 out.print(prefix); out.print( 8476 Integer.toHexString(System.identityHashCode(filter.service))); 8477 out.print(' '); 8478 filter.service.printComponentShortName(out); 8479 out.print(" filter "); 8480 out.println(Integer.toHexString(System.identityHashCode(filter))); 8481 } 8482 8483 @Override 8484 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8485 return filter.service; 8486 } 8487 8488 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8489 PackageParser.Service service = (PackageParser.Service)label; 8490 out.print(prefix); out.print( 8491 Integer.toHexString(System.identityHashCode(service))); 8492 out.print(' '); 8493 service.printComponentShortName(out); 8494 if (count > 1) { 8495 out.print(" ("); out.print(count); out.print(" filters)"); 8496 } 8497 out.println(); 8498 } 8499 8500// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8501// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8502// final List<ResolveInfo> retList = Lists.newArrayList(); 8503// while (i.hasNext()) { 8504// final ResolveInfo resolveInfo = (ResolveInfo) i; 8505// if (isEnabledLP(resolveInfo.serviceInfo)) { 8506// retList.add(resolveInfo); 8507// } 8508// } 8509// return retList; 8510// } 8511 8512 // Keys are String (activity class name), values are Activity. 8513 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8514 = new ArrayMap<ComponentName, PackageParser.Service>(); 8515 private int mFlags; 8516 }; 8517 8518 private final class ProviderIntentResolver 8519 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8520 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8521 boolean defaultOnly, int userId) { 8522 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8523 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8524 } 8525 8526 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8527 int userId) { 8528 if (!sUserManager.exists(userId)) 8529 return null; 8530 mFlags = flags; 8531 return super.queryIntent(intent, resolvedType, 8532 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8533 } 8534 8535 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8536 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8537 if (!sUserManager.exists(userId)) 8538 return null; 8539 if (packageProviders == null) { 8540 return null; 8541 } 8542 mFlags = flags; 8543 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8544 final int N = packageProviders.size(); 8545 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8546 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8547 8548 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8549 for (int i = 0; i < N; ++i) { 8550 intentFilters = packageProviders.get(i).intents; 8551 if (intentFilters != null && intentFilters.size() > 0) { 8552 PackageParser.ProviderIntentInfo[] array = 8553 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8554 intentFilters.toArray(array); 8555 listCut.add(array); 8556 } 8557 } 8558 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8559 } 8560 8561 public final void addProvider(PackageParser.Provider p) { 8562 if (mProviders.containsKey(p.getComponentName())) { 8563 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8564 return; 8565 } 8566 8567 mProviders.put(p.getComponentName(), p); 8568 if (DEBUG_SHOW_INFO) { 8569 Log.v(TAG, " " 8570 + (p.info.nonLocalizedLabel != null 8571 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8572 Log.v(TAG, " Class=" + p.info.name); 8573 } 8574 final int NI = p.intents.size(); 8575 int j; 8576 for (j = 0; j < NI; j++) { 8577 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8578 if (DEBUG_SHOW_INFO) { 8579 Log.v(TAG, " IntentFilter:"); 8580 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8581 } 8582 if (!intent.debugCheck()) { 8583 Log.w(TAG, "==> For Provider " + p.info.name); 8584 } 8585 addFilter(intent); 8586 } 8587 } 8588 8589 public final void removeProvider(PackageParser.Provider p) { 8590 mProviders.remove(p.getComponentName()); 8591 if (DEBUG_SHOW_INFO) { 8592 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8593 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8594 Log.v(TAG, " Class=" + p.info.name); 8595 } 8596 final int NI = p.intents.size(); 8597 int j; 8598 for (j = 0; j < NI; j++) { 8599 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8600 if (DEBUG_SHOW_INFO) { 8601 Log.v(TAG, " IntentFilter:"); 8602 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8603 } 8604 removeFilter(intent); 8605 } 8606 } 8607 8608 @Override 8609 protected boolean allowFilterResult( 8610 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8611 ProviderInfo filterPi = filter.provider.info; 8612 for (int i = dest.size() - 1; i >= 0; i--) { 8613 ProviderInfo destPi = dest.get(i).providerInfo; 8614 if (destPi.name == filterPi.name 8615 && destPi.packageName == filterPi.packageName) { 8616 return false; 8617 } 8618 } 8619 return true; 8620 } 8621 8622 @Override 8623 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8624 return new PackageParser.ProviderIntentInfo[size]; 8625 } 8626 8627 @Override 8628 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8629 if (!sUserManager.exists(userId)) 8630 return true; 8631 PackageParser.Package p = filter.provider.owner; 8632 if (p != null) { 8633 PackageSetting ps = (PackageSetting) p.mExtras; 8634 if (ps != null) { 8635 // System apps are never considered stopped for purposes of 8636 // filtering, because there may be no way for the user to 8637 // actually re-launch them. 8638 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8639 && ps.getStopped(userId); 8640 } 8641 } 8642 return false; 8643 } 8644 8645 @Override 8646 protected boolean isPackageForFilter(String packageName, 8647 PackageParser.ProviderIntentInfo info) { 8648 return packageName.equals(info.provider.owner.packageName); 8649 } 8650 8651 @Override 8652 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8653 int match, int userId) { 8654 if (!sUserManager.exists(userId)) 8655 return null; 8656 final PackageParser.ProviderIntentInfo info = filter; 8657 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8658 return null; 8659 } 8660 final PackageParser.Provider provider = info.provider; 8661 if (mSafeMode && (provider.info.applicationInfo.flags 8662 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8663 return null; 8664 } 8665 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8666 if (ps == null) { 8667 return null; 8668 } 8669 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8670 ps.readUserState(userId), userId); 8671 if (pi == null) { 8672 return null; 8673 } 8674 final ResolveInfo res = new ResolveInfo(); 8675 res.providerInfo = pi; 8676 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8677 res.filter = filter; 8678 } 8679 res.priority = info.getPriority(); 8680 res.preferredOrder = provider.owner.mPreferredOrder; 8681 res.match = match; 8682 res.isDefault = info.hasDefault; 8683 res.labelRes = info.labelRes; 8684 res.nonLocalizedLabel = info.nonLocalizedLabel; 8685 res.icon = info.icon; 8686 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8687 return res; 8688 } 8689 8690 @Override 8691 protected void sortResults(List<ResolveInfo> results) { 8692 Collections.sort(results, mResolvePrioritySorter); 8693 } 8694 8695 @Override 8696 protected void dumpFilter(PrintWriter out, String prefix, 8697 PackageParser.ProviderIntentInfo filter) { 8698 out.print(prefix); 8699 out.print( 8700 Integer.toHexString(System.identityHashCode(filter.provider))); 8701 out.print(' '); 8702 filter.provider.printComponentShortName(out); 8703 out.print(" filter "); 8704 out.println(Integer.toHexString(System.identityHashCode(filter))); 8705 } 8706 8707 @Override 8708 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8709 return filter.provider; 8710 } 8711 8712 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8713 PackageParser.Provider provider = (PackageParser.Provider)label; 8714 out.print(prefix); out.print( 8715 Integer.toHexString(System.identityHashCode(provider))); 8716 out.print(' '); 8717 provider.printComponentShortName(out); 8718 if (count > 1) { 8719 out.print(" ("); out.print(count); out.print(" filters)"); 8720 } 8721 out.println(); 8722 } 8723 8724 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8725 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8726 private int mFlags; 8727 }; 8728 8729 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8730 new Comparator<ResolveInfo>() { 8731 public int compare(ResolveInfo r1, ResolveInfo r2) { 8732 int v1 = r1.priority; 8733 int v2 = r2.priority; 8734 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8735 if (v1 != v2) { 8736 return (v1 > v2) ? -1 : 1; 8737 } 8738 v1 = r1.preferredOrder; 8739 v2 = r2.preferredOrder; 8740 if (v1 != v2) { 8741 return (v1 > v2) ? -1 : 1; 8742 } 8743 if (r1.isDefault != r2.isDefault) { 8744 return r1.isDefault ? -1 : 1; 8745 } 8746 v1 = r1.match; 8747 v2 = r2.match; 8748 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8749 if (v1 != v2) { 8750 return (v1 > v2) ? -1 : 1; 8751 } 8752 if (r1.system != r2.system) { 8753 return r1.system ? -1 : 1; 8754 } 8755 return 0; 8756 } 8757 }; 8758 8759 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8760 new Comparator<ProviderInfo>() { 8761 public int compare(ProviderInfo p1, ProviderInfo p2) { 8762 final int v1 = p1.initOrder; 8763 final int v2 = p2.initOrder; 8764 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8765 } 8766 }; 8767 8768 final void sendPackageBroadcast(final String action, final String pkg, 8769 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8770 final int[] userIds) { 8771 mHandler.post(new Runnable() { 8772 @Override 8773 public void run() { 8774 try { 8775 final IActivityManager am = ActivityManagerNative.getDefault(); 8776 if (am == null) return; 8777 final int[] resolvedUserIds; 8778 if (userIds == null) { 8779 resolvedUserIds = am.getRunningUserIds(); 8780 } else { 8781 resolvedUserIds = userIds; 8782 } 8783 for (int id : resolvedUserIds) { 8784 final Intent intent = new Intent(action, 8785 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8786 if (extras != null) { 8787 intent.putExtras(extras); 8788 } 8789 if (targetPkg != null) { 8790 intent.setPackage(targetPkg); 8791 } 8792 // Modify the UID when posting to other users 8793 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8794 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8795 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8796 intent.putExtra(Intent.EXTRA_UID, uid); 8797 } 8798 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8799 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8800 if (DEBUG_BROADCASTS) { 8801 RuntimeException here = new RuntimeException("here"); 8802 here.fillInStackTrace(); 8803 Slog.d(TAG, "Sending to user " + id + ": " 8804 + intent.toShortString(false, true, false, false) 8805 + " " + intent.getExtras(), here); 8806 } 8807 am.broadcastIntent(null, intent, null, finishedReceiver, 8808 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8809 finishedReceiver != null, false, id); 8810 } 8811 } catch (RemoteException ex) { 8812 } 8813 } 8814 }); 8815 } 8816 8817 /** 8818 * Check if the external storage media is available. This is true if there 8819 * is a mounted external storage medium or if the external storage is 8820 * emulated. 8821 */ 8822 private boolean isExternalMediaAvailable() { 8823 return mMediaMounted || Environment.isExternalStorageEmulated(); 8824 } 8825 8826 @Override 8827 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8828 // writer 8829 synchronized (mPackages) { 8830 if (!isExternalMediaAvailable()) { 8831 // If the external storage is no longer mounted at this point, 8832 // the caller may not have been able to delete all of this 8833 // packages files and can not delete any more. Bail. 8834 return null; 8835 } 8836 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8837 if (lastPackage != null) { 8838 pkgs.remove(lastPackage); 8839 } 8840 if (pkgs.size() > 0) { 8841 return pkgs.get(0); 8842 } 8843 } 8844 return null; 8845 } 8846 8847 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8848 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8849 userId, andCode ? 1 : 0, packageName); 8850 if (mSystemReady) { 8851 msg.sendToTarget(); 8852 } else { 8853 if (mPostSystemReadyMessages == null) { 8854 mPostSystemReadyMessages = new ArrayList<>(); 8855 } 8856 mPostSystemReadyMessages.add(msg); 8857 } 8858 } 8859 8860 void startCleaningPackages() { 8861 // reader 8862 synchronized (mPackages) { 8863 if (!isExternalMediaAvailable()) { 8864 return; 8865 } 8866 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8867 return; 8868 } 8869 } 8870 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8871 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8872 IActivityManager am = ActivityManagerNative.getDefault(); 8873 if (am != null) { 8874 try { 8875 am.startService(null, intent, null, UserHandle.USER_OWNER); 8876 } catch (RemoteException e) { 8877 } 8878 } 8879 } 8880 8881 @Override 8882 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8883 int installFlags, String installerPackageName, VerificationParams verificationParams, 8884 String packageAbiOverride) { 8885 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8886 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8887 } 8888 8889 @Override 8890 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8891 int installFlags, String installerPackageName, VerificationParams verificationParams, 8892 String packageAbiOverride, int userId) { 8893 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8894 8895 final int callingUid = Binder.getCallingUid(); 8896 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8897 8898 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8899 try { 8900 if (observer != null) { 8901 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8902 } 8903 } catch (RemoteException re) { 8904 } 8905 return; 8906 } 8907 8908 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8909 installFlags |= PackageManager.INSTALL_FROM_ADB; 8910 8911 } else { 8912 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8913 // about installerPackageName. 8914 8915 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8916 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8917 } 8918 8919 UserHandle user; 8920 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8921 user = UserHandle.ALL; 8922 } else { 8923 user = new UserHandle(userId); 8924 } 8925 8926 // Only system components can circumvent runtime permissions when installing. 8927 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8928 && mContext.checkCallingOrSelfPermission(Manifest.permission 8929 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8930 throw new SecurityException("You need the " 8931 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8932 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8933 } 8934 8935 verificationParams.setInstallerUid(callingUid); 8936 8937 final File originFile = new File(originPath); 8938 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8939 8940 final Message msg = mHandler.obtainMessage(INIT_COPY); 8941 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8942 null, verificationParams, user, packageAbiOverride); 8943 mHandler.sendMessage(msg); 8944 } 8945 8946 void installStage(String packageName, File stagedDir, String stagedCid, 8947 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8948 String installerPackageName, int installerUid, UserHandle user) { 8949 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8950 params.referrerUri, installerUid, null); 8951 8952 final OriginInfo origin; 8953 if (stagedDir != null) { 8954 origin = OriginInfo.fromStagedFile(stagedDir); 8955 } else { 8956 origin = OriginInfo.fromStagedContainer(stagedCid); 8957 } 8958 8959 final Message msg = mHandler.obtainMessage(INIT_COPY); 8960 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8961 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8962 mHandler.sendMessage(msg); 8963 } 8964 8965 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8966 Bundle extras = new Bundle(1); 8967 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8968 8969 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8970 packageName, extras, null, null, new int[] {userId}); 8971 try { 8972 IActivityManager am = ActivityManagerNative.getDefault(); 8973 final boolean isSystem = 8974 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8975 if (isSystem && am.isUserRunning(userId, false)) { 8976 // The just-installed/enabled app is bundled on the system, so presumed 8977 // to be able to run automatically without needing an explicit launch. 8978 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8979 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8980 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8981 .setPackage(packageName); 8982 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8983 android.app.AppOpsManager.OP_NONE, false, false, userId); 8984 } 8985 } catch (RemoteException e) { 8986 // shouldn't happen 8987 Slog.w(TAG, "Unable to bootstrap installed package", e); 8988 } 8989 } 8990 8991 @Override 8992 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8993 int userId) { 8994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8995 PackageSetting pkgSetting; 8996 final int uid = Binder.getCallingUid(); 8997 enforceCrossUserPermission(uid, userId, true, true, 8998 "setApplicationHiddenSetting for user " + userId); 8999 9000 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9001 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9002 return false; 9003 } 9004 9005 long callingId = Binder.clearCallingIdentity(); 9006 try { 9007 boolean sendAdded = false; 9008 boolean sendRemoved = false; 9009 // writer 9010 synchronized (mPackages) { 9011 pkgSetting = mSettings.mPackages.get(packageName); 9012 if (pkgSetting == null) { 9013 return false; 9014 } 9015 if (pkgSetting.getHidden(userId) != hidden) { 9016 pkgSetting.setHidden(hidden, userId); 9017 mSettings.writePackageRestrictionsLPr(userId); 9018 if (hidden) { 9019 sendRemoved = true; 9020 } else { 9021 sendAdded = true; 9022 } 9023 } 9024 } 9025 if (sendAdded) { 9026 sendPackageAddedForUser(packageName, pkgSetting, userId); 9027 return true; 9028 } 9029 if (sendRemoved) { 9030 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9031 "hiding pkg"); 9032 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9033 } 9034 } finally { 9035 Binder.restoreCallingIdentity(callingId); 9036 } 9037 return false; 9038 } 9039 9040 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9041 int userId) { 9042 final PackageRemovedInfo info = new PackageRemovedInfo(); 9043 info.removedPackage = packageName; 9044 info.removedUsers = new int[] {userId}; 9045 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9046 info.sendBroadcast(false, false, false); 9047 } 9048 9049 /** 9050 * Returns true if application is not found or there was an error. Otherwise it returns 9051 * the hidden state of the package for the given user. 9052 */ 9053 @Override 9054 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9055 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9056 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9057 false, "getApplicationHidden for user " + userId); 9058 PackageSetting pkgSetting; 9059 long callingId = Binder.clearCallingIdentity(); 9060 try { 9061 // writer 9062 synchronized (mPackages) { 9063 pkgSetting = mSettings.mPackages.get(packageName); 9064 if (pkgSetting == null) { 9065 return true; 9066 } 9067 return pkgSetting.getHidden(userId); 9068 } 9069 } finally { 9070 Binder.restoreCallingIdentity(callingId); 9071 } 9072 } 9073 9074 /** 9075 * @hide 9076 */ 9077 @Override 9078 public int installExistingPackageAsUser(String packageName, int userId) { 9079 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9080 null); 9081 PackageSetting pkgSetting; 9082 final int uid = Binder.getCallingUid(); 9083 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9084 + userId); 9085 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9086 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9087 } 9088 9089 long callingId = Binder.clearCallingIdentity(); 9090 try { 9091 boolean sendAdded = false; 9092 9093 // writer 9094 synchronized (mPackages) { 9095 pkgSetting = mSettings.mPackages.get(packageName); 9096 if (pkgSetting == null) { 9097 return PackageManager.INSTALL_FAILED_INVALID_URI; 9098 } 9099 if (!pkgSetting.getInstalled(userId)) { 9100 pkgSetting.setInstalled(true, userId); 9101 pkgSetting.setHidden(false, userId); 9102 mSettings.writePackageRestrictionsLPr(userId); 9103 sendAdded = true; 9104 } 9105 } 9106 9107 if (sendAdded) { 9108 sendPackageAddedForUser(packageName, pkgSetting, userId); 9109 } 9110 } finally { 9111 Binder.restoreCallingIdentity(callingId); 9112 } 9113 9114 return PackageManager.INSTALL_SUCCEEDED; 9115 } 9116 9117 boolean isUserRestricted(int userId, String restrictionKey) { 9118 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9119 if (restrictions.getBoolean(restrictionKey, false)) { 9120 Log.w(TAG, "User is restricted: " + restrictionKey); 9121 return true; 9122 } 9123 return false; 9124 } 9125 9126 @Override 9127 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9128 mContext.enforceCallingOrSelfPermission( 9129 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9130 "Only package verification agents can verify applications"); 9131 9132 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9133 final PackageVerificationResponse response = new PackageVerificationResponse( 9134 verificationCode, Binder.getCallingUid()); 9135 msg.arg1 = id; 9136 msg.obj = response; 9137 mHandler.sendMessage(msg); 9138 } 9139 9140 @Override 9141 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9142 long millisecondsToDelay) { 9143 mContext.enforceCallingOrSelfPermission( 9144 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9145 "Only package verification agents can extend verification timeouts"); 9146 9147 final PackageVerificationState state = mPendingVerification.get(id); 9148 final PackageVerificationResponse response = new PackageVerificationResponse( 9149 verificationCodeAtTimeout, Binder.getCallingUid()); 9150 9151 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9152 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9153 } 9154 if (millisecondsToDelay < 0) { 9155 millisecondsToDelay = 0; 9156 } 9157 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9158 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9159 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9160 } 9161 9162 if ((state != null) && !state.timeoutExtended()) { 9163 state.extendTimeout(); 9164 9165 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9166 msg.arg1 = id; 9167 msg.obj = response; 9168 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9169 } 9170 } 9171 9172 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9173 int verificationCode, UserHandle user) { 9174 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9175 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9176 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9177 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9178 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9179 9180 mContext.sendBroadcastAsUser(intent, user, 9181 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9182 } 9183 9184 private ComponentName matchComponentForVerifier(String packageName, 9185 List<ResolveInfo> receivers) { 9186 ActivityInfo targetReceiver = null; 9187 9188 final int NR = receivers.size(); 9189 for (int i = 0; i < NR; i++) { 9190 final ResolveInfo info = receivers.get(i); 9191 if (info.activityInfo == null) { 9192 continue; 9193 } 9194 9195 if (packageName.equals(info.activityInfo.packageName)) { 9196 targetReceiver = info.activityInfo; 9197 break; 9198 } 9199 } 9200 9201 if (targetReceiver == null) { 9202 return null; 9203 } 9204 9205 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9206 } 9207 9208 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9209 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9210 if (pkgInfo.verifiers.length == 0) { 9211 return null; 9212 } 9213 9214 final int N = pkgInfo.verifiers.length; 9215 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9216 for (int i = 0; i < N; i++) { 9217 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9218 9219 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9220 receivers); 9221 if (comp == null) { 9222 continue; 9223 } 9224 9225 final int verifierUid = getUidForVerifier(verifierInfo); 9226 if (verifierUid == -1) { 9227 continue; 9228 } 9229 9230 if (DEBUG_VERIFY) { 9231 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9232 + " with the correct signature"); 9233 } 9234 sufficientVerifiers.add(comp); 9235 verificationState.addSufficientVerifier(verifierUid); 9236 } 9237 9238 return sufficientVerifiers; 9239 } 9240 9241 private int getUidForVerifier(VerifierInfo verifierInfo) { 9242 synchronized (mPackages) { 9243 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9244 if (pkg == null) { 9245 return -1; 9246 } else if (pkg.mSignatures.length != 1) { 9247 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9248 + " has more than one signature; ignoring"); 9249 return -1; 9250 } 9251 9252 /* 9253 * If the public key of the package's signature does not match 9254 * our expected public key, then this is a different package and 9255 * we should skip. 9256 */ 9257 9258 final byte[] expectedPublicKey; 9259 try { 9260 final Signature verifierSig = pkg.mSignatures[0]; 9261 final PublicKey publicKey = verifierSig.getPublicKey(); 9262 expectedPublicKey = publicKey.getEncoded(); 9263 } catch (CertificateException e) { 9264 return -1; 9265 } 9266 9267 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9268 9269 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9270 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9271 + " does not have the expected public key; ignoring"); 9272 return -1; 9273 } 9274 9275 return pkg.applicationInfo.uid; 9276 } 9277 } 9278 9279 @Override 9280 public void finishPackageInstall(int token) { 9281 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9282 9283 if (DEBUG_INSTALL) { 9284 Slog.v(TAG, "BM finishing package install for " + token); 9285 } 9286 9287 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9288 mHandler.sendMessage(msg); 9289 } 9290 9291 /** 9292 * Get the verification agent timeout. 9293 * 9294 * @return verification timeout in milliseconds 9295 */ 9296 private long getVerificationTimeout() { 9297 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9298 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9299 DEFAULT_VERIFICATION_TIMEOUT); 9300 } 9301 9302 /** 9303 * Get the default verification agent response code. 9304 * 9305 * @return default verification response code 9306 */ 9307 private int getDefaultVerificationResponse() { 9308 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9309 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9310 DEFAULT_VERIFICATION_RESPONSE); 9311 } 9312 9313 /** 9314 * Check whether or not package verification has been enabled. 9315 * 9316 * @return true if verification should be performed 9317 */ 9318 private boolean isVerificationEnabled(int userId, int installFlags) { 9319 if (!DEFAULT_VERIFY_ENABLE) { 9320 return false; 9321 } 9322 9323 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9324 9325 // Check if installing from ADB 9326 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9327 // Do not run verification in a test harness environment 9328 if (ActivityManager.isRunningInTestHarness()) { 9329 return false; 9330 } 9331 if (ensureVerifyAppsEnabled) { 9332 return true; 9333 } 9334 // Check if the developer does not want package verification for ADB installs 9335 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9336 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9337 return false; 9338 } 9339 } 9340 9341 if (ensureVerifyAppsEnabled) { 9342 return true; 9343 } 9344 9345 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9346 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9347 } 9348 9349 @Override 9350 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9351 throws RemoteException { 9352 mContext.enforceCallingOrSelfPermission( 9353 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9354 "Only intentfilter verification agents can verify applications"); 9355 9356 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9357 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9358 Binder.getCallingUid(), verificationCode, failedDomains); 9359 msg.arg1 = id; 9360 msg.obj = response; 9361 mHandler.sendMessage(msg); 9362 } 9363 9364 @Override 9365 public int getIntentVerificationStatus(String packageName, int userId) { 9366 synchronized (mPackages) { 9367 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9368 } 9369 } 9370 9371 @Override 9372 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9373 boolean result = false; 9374 synchronized (mPackages) { 9375 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9376 } 9377 if (result) { 9378 scheduleWritePackageRestrictionsLocked(userId); 9379 } 9380 return result; 9381 } 9382 9383 @Override 9384 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9385 synchronized (mPackages) { 9386 return mSettings.getIntentFilterVerificationsLPr(packageName); 9387 } 9388 } 9389 9390 @Override 9391 public List<IntentFilter> getAllIntentFilters(String packageName) { 9392 if (TextUtils.isEmpty(packageName)) { 9393 return Collections.<IntentFilter>emptyList(); 9394 } 9395 synchronized (mPackages) { 9396 PackageParser.Package pkg = mPackages.get(packageName); 9397 if (pkg == null || pkg.activities == null) { 9398 return Collections.<IntentFilter>emptyList(); 9399 } 9400 final int count = pkg.activities.size(); 9401 ArrayList<IntentFilter> result = new ArrayList<>(); 9402 for (int n=0; n<count; n++) { 9403 PackageParser.Activity activity = pkg.activities.get(n); 9404 if (activity.intents != null || activity.intents.size() > 0) { 9405 result.addAll(activity.intents); 9406 } 9407 } 9408 return result; 9409 } 9410 } 9411 9412 @Override 9413 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9414 synchronized (mPackages) { 9415 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9416 if (packageName != null) { 9417 result |= updateIntentVerificationStatus(packageName, 9418 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9419 UserHandle.myUserId()); 9420 } 9421 return result; 9422 } 9423 } 9424 9425 @Override 9426 public String getDefaultBrowserPackageName(int userId) { 9427 synchronized (mPackages) { 9428 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9429 } 9430 } 9431 9432 /** 9433 * Get the "allow unknown sources" setting. 9434 * 9435 * @return the current "allow unknown sources" setting 9436 */ 9437 private int getUnknownSourcesSettings() { 9438 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9439 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9440 -1); 9441 } 9442 9443 @Override 9444 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9445 final int uid = Binder.getCallingUid(); 9446 // writer 9447 synchronized (mPackages) { 9448 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9449 if (targetPackageSetting == null) { 9450 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9451 } 9452 9453 PackageSetting installerPackageSetting; 9454 if (installerPackageName != null) { 9455 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9456 if (installerPackageSetting == null) { 9457 throw new IllegalArgumentException("Unknown installer package: " 9458 + installerPackageName); 9459 } 9460 } else { 9461 installerPackageSetting = null; 9462 } 9463 9464 Signature[] callerSignature; 9465 Object obj = mSettings.getUserIdLPr(uid); 9466 if (obj != null) { 9467 if (obj instanceof SharedUserSetting) { 9468 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9469 } else if (obj instanceof PackageSetting) { 9470 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9471 } else { 9472 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9473 } 9474 } else { 9475 throw new SecurityException("Unknown calling uid " + uid); 9476 } 9477 9478 // Verify: can't set installerPackageName to a package that is 9479 // not signed with the same cert as the caller. 9480 if (installerPackageSetting != null) { 9481 if (compareSignatures(callerSignature, 9482 installerPackageSetting.signatures.mSignatures) 9483 != PackageManager.SIGNATURE_MATCH) { 9484 throw new SecurityException( 9485 "Caller does not have same cert as new installer package " 9486 + installerPackageName); 9487 } 9488 } 9489 9490 // Verify: if target already has an installer package, it must 9491 // be signed with the same cert as the caller. 9492 if (targetPackageSetting.installerPackageName != null) { 9493 PackageSetting setting = mSettings.mPackages.get( 9494 targetPackageSetting.installerPackageName); 9495 // If the currently set package isn't valid, then it's always 9496 // okay to change it. 9497 if (setting != null) { 9498 if (compareSignatures(callerSignature, 9499 setting.signatures.mSignatures) 9500 != PackageManager.SIGNATURE_MATCH) { 9501 throw new SecurityException( 9502 "Caller does not have same cert as old installer package " 9503 + targetPackageSetting.installerPackageName); 9504 } 9505 } 9506 } 9507 9508 // Okay! 9509 targetPackageSetting.installerPackageName = installerPackageName; 9510 scheduleWriteSettingsLocked(); 9511 } 9512 } 9513 9514 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9515 // Queue up an async operation since the package installation may take a little while. 9516 mHandler.post(new Runnable() { 9517 public void run() { 9518 mHandler.removeCallbacks(this); 9519 // Result object to be returned 9520 PackageInstalledInfo res = new PackageInstalledInfo(); 9521 res.returnCode = currentStatus; 9522 res.uid = -1; 9523 res.pkg = null; 9524 res.removedInfo = new PackageRemovedInfo(); 9525 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9526 args.doPreInstall(res.returnCode); 9527 synchronized (mInstallLock) { 9528 installPackageLI(args, res); 9529 } 9530 args.doPostInstall(res.returnCode, res.uid); 9531 } 9532 9533 // A restore should be performed at this point if (a) the install 9534 // succeeded, (b) the operation is not an update, and (c) the new 9535 // package has not opted out of backup participation. 9536 final boolean update = res.removedInfo.removedPackage != null; 9537 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9538 boolean doRestore = !update 9539 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9540 9541 // Set up the post-install work request bookkeeping. This will be used 9542 // and cleaned up by the post-install event handling regardless of whether 9543 // there's a restore pass performed. Token values are >= 1. 9544 int token; 9545 if (mNextInstallToken < 0) mNextInstallToken = 1; 9546 token = mNextInstallToken++; 9547 9548 PostInstallData data = new PostInstallData(args, res); 9549 mRunningInstalls.put(token, data); 9550 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9551 9552 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9553 // Pass responsibility to the Backup Manager. It will perform a 9554 // restore if appropriate, then pass responsibility back to the 9555 // Package Manager to run the post-install observer callbacks 9556 // and broadcasts. 9557 IBackupManager bm = IBackupManager.Stub.asInterface( 9558 ServiceManager.getService(Context.BACKUP_SERVICE)); 9559 if (bm != null) { 9560 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9561 + " to BM for possible restore"); 9562 try { 9563 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9564 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9565 } else { 9566 doRestore = false; 9567 } 9568 } catch (RemoteException e) { 9569 // can't happen; the backup manager is local 9570 } catch (Exception e) { 9571 Slog.e(TAG, "Exception trying to enqueue restore", e); 9572 doRestore = false; 9573 } 9574 } else { 9575 Slog.e(TAG, "Backup Manager not found!"); 9576 doRestore = false; 9577 } 9578 } 9579 9580 if (!doRestore) { 9581 // No restore possible, or the Backup Manager was mysteriously not 9582 // available -- just fire the post-install work request directly. 9583 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9584 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9585 mHandler.sendMessage(msg); 9586 } 9587 } 9588 }); 9589 } 9590 9591 private abstract class HandlerParams { 9592 private static final int MAX_RETRIES = 4; 9593 9594 /** 9595 * Number of times startCopy() has been attempted and had a non-fatal 9596 * error. 9597 */ 9598 private int mRetries = 0; 9599 9600 /** User handle for the user requesting the information or installation. */ 9601 private final UserHandle mUser; 9602 9603 HandlerParams(UserHandle user) { 9604 mUser = user; 9605 } 9606 9607 UserHandle getUser() { 9608 return mUser; 9609 } 9610 9611 final boolean startCopy() { 9612 boolean res; 9613 try { 9614 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9615 9616 if (++mRetries > MAX_RETRIES) { 9617 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9618 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9619 handleServiceError(); 9620 return false; 9621 } else { 9622 handleStartCopy(); 9623 res = true; 9624 } 9625 } catch (RemoteException e) { 9626 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9627 mHandler.sendEmptyMessage(MCS_RECONNECT); 9628 res = false; 9629 } 9630 handleReturnCode(); 9631 return res; 9632 } 9633 9634 final void serviceError() { 9635 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9636 handleServiceError(); 9637 handleReturnCode(); 9638 } 9639 9640 abstract void handleStartCopy() throws RemoteException; 9641 abstract void handleServiceError(); 9642 abstract void handleReturnCode(); 9643 } 9644 9645 class MeasureParams extends HandlerParams { 9646 private final PackageStats mStats; 9647 private boolean mSuccess; 9648 9649 private final IPackageStatsObserver mObserver; 9650 9651 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9652 super(new UserHandle(stats.userHandle)); 9653 mObserver = observer; 9654 mStats = stats; 9655 } 9656 9657 @Override 9658 public String toString() { 9659 return "MeasureParams{" 9660 + Integer.toHexString(System.identityHashCode(this)) 9661 + " " + mStats.packageName + "}"; 9662 } 9663 9664 @Override 9665 void handleStartCopy() throws RemoteException { 9666 synchronized (mInstallLock) { 9667 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9668 } 9669 9670 if (mSuccess) { 9671 final boolean mounted; 9672 if (Environment.isExternalStorageEmulated()) { 9673 mounted = true; 9674 } else { 9675 final String status = Environment.getExternalStorageState(); 9676 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9677 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9678 } 9679 9680 if (mounted) { 9681 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9682 9683 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9684 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9685 9686 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9687 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9688 9689 // Always subtract cache size, since it's a subdirectory 9690 mStats.externalDataSize -= mStats.externalCacheSize; 9691 9692 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9693 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9694 9695 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9696 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9697 } 9698 } 9699 } 9700 9701 @Override 9702 void handleReturnCode() { 9703 if (mObserver != null) { 9704 try { 9705 mObserver.onGetStatsCompleted(mStats, mSuccess); 9706 } catch (RemoteException e) { 9707 Slog.i(TAG, "Observer no longer exists."); 9708 } 9709 } 9710 } 9711 9712 @Override 9713 void handleServiceError() { 9714 Slog.e(TAG, "Could not measure application " + mStats.packageName 9715 + " external storage"); 9716 } 9717 } 9718 9719 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9720 throws RemoteException { 9721 long result = 0; 9722 for (File path : paths) { 9723 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9724 } 9725 return result; 9726 } 9727 9728 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9729 for (File path : paths) { 9730 try { 9731 mcs.clearDirectory(path.getAbsolutePath()); 9732 } catch (RemoteException e) { 9733 } 9734 } 9735 } 9736 9737 static class OriginInfo { 9738 /** 9739 * Location where install is coming from, before it has been 9740 * copied/renamed into place. This could be a single monolithic APK 9741 * file, or a cluster directory. This location may be untrusted. 9742 */ 9743 final File file; 9744 final String cid; 9745 9746 /** 9747 * Flag indicating that {@link #file} or {@link #cid} has already been 9748 * staged, meaning downstream users don't need to defensively copy the 9749 * contents. 9750 */ 9751 final boolean staged; 9752 9753 /** 9754 * Flag indicating that {@link #file} or {@link #cid} is an already 9755 * installed app that is being moved. 9756 */ 9757 final boolean existing; 9758 9759 final String resolvedPath; 9760 final File resolvedFile; 9761 9762 static OriginInfo fromNothing() { 9763 return new OriginInfo(null, null, false, false); 9764 } 9765 9766 static OriginInfo fromUntrustedFile(File file) { 9767 return new OriginInfo(file, null, false, false); 9768 } 9769 9770 static OriginInfo fromExistingFile(File file) { 9771 return new OriginInfo(file, null, false, true); 9772 } 9773 9774 static OriginInfo fromStagedFile(File file) { 9775 return new OriginInfo(file, null, true, false); 9776 } 9777 9778 static OriginInfo fromStagedContainer(String cid) { 9779 return new OriginInfo(null, cid, true, false); 9780 } 9781 9782 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9783 this.file = file; 9784 this.cid = cid; 9785 this.staged = staged; 9786 this.existing = existing; 9787 9788 if (cid != null) { 9789 resolvedPath = PackageHelper.getSdDir(cid); 9790 resolvedFile = new File(resolvedPath); 9791 } else if (file != null) { 9792 resolvedPath = file.getAbsolutePath(); 9793 resolvedFile = file; 9794 } else { 9795 resolvedPath = null; 9796 resolvedFile = null; 9797 } 9798 } 9799 } 9800 9801 class MoveInfo { 9802 final int moveId; 9803 final String fromUuid; 9804 final String toUuid; 9805 final String packageName; 9806 final String dataAppName; 9807 final int appId; 9808 final String seinfo; 9809 9810 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9811 String dataAppName, int appId, String seinfo) { 9812 this.moveId = moveId; 9813 this.fromUuid = fromUuid; 9814 this.toUuid = toUuid; 9815 this.packageName = packageName; 9816 this.dataAppName = dataAppName; 9817 this.appId = appId; 9818 this.seinfo = seinfo; 9819 } 9820 } 9821 9822 class InstallParams extends HandlerParams { 9823 final OriginInfo origin; 9824 final MoveInfo move; 9825 final IPackageInstallObserver2 observer; 9826 int installFlags; 9827 final String installerPackageName; 9828 final String volumeUuid; 9829 final VerificationParams verificationParams; 9830 private InstallArgs mArgs; 9831 private int mRet; 9832 final String packageAbiOverride; 9833 9834 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9835 int installFlags, String installerPackageName, String volumeUuid, 9836 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9837 super(user); 9838 this.origin = origin; 9839 this.move = move; 9840 this.observer = observer; 9841 this.installFlags = installFlags; 9842 this.installerPackageName = installerPackageName; 9843 this.volumeUuid = volumeUuid; 9844 this.verificationParams = verificationParams; 9845 this.packageAbiOverride = packageAbiOverride; 9846 } 9847 9848 @Override 9849 public String toString() { 9850 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9851 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9852 } 9853 9854 public ManifestDigest getManifestDigest() { 9855 if (verificationParams == null) { 9856 return null; 9857 } 9858 return verificationParams.getManifestDigest(); 9859 } 9860 9861 private int installLocationPolicy(PackageInfoLite pkgLite) { 9862 String packageName = pkgLite.packageName; 9863 int installLocation = pkgLite.installLocation; 9864 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9865 // reader 9866 synchronized (mPackages) { 9867 PackageParser.Package pkg = mPackages.get(packageName); 9868 if (pkg != null) { 9869 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9870 // Check for downgrading. 9871 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9872 try { 9873 checkDowngrade(pkg, pkgLite); 9874 } catch (PackageManagerException e) { 9875 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9876 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9877 } 9878 } 9879 // Check for updated system application. 9880 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9881 if (onSd) { 9882 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9883 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9884 } 9885 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9886 } else { 9887 if (onSd) { 9888 // Install flag overrides everything. 9889 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9890 } 9891 // If current upgrade specifies particular preference 9892 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9893 // Application explicitly specified internal. 9894 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9895 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9896 // App explictly prefers external. Let policy decide 9897 } else { 9898 // Prefer previous location 9899 if (isExternal(pkg)) { 9900 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9901 } 9902 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9903 } 9904 } 9905 } else { 9906 // Invalid install. Return error code 9907 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9908 } 9909 } 9910 } 9911 // All the special cases have been taken care of. 9912 // Return result based on recommended install location. 9913 if (onSd) { 9914 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9915 } 9916 return pkgLite.recommendedInstallLocation; 9917 } 9918 9919 /* 9920 * Invoke remote method to get package information and install 9921 * location values. Override install location based on default 9922 * policy if needed and then create install arguments based 9923 * on the install location. 9924 */ 9925 public void handleStartCopy() throws RemoteException { 9926 int ret = PackageManager.INSTALL_SUCCEEDED; 9927 9928 // If we're already staged, we've firmly committed to an install location 9929 if (origin.staged) { 9930 if (origin.file != null) { 9931 installFlags |= PackageManager.INSTALL_INTERNAL; 9932 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9933 } else if (origin.cid != null) { 9934 installFlags |= PackageManager.INSTALL_EXTERNAL; 9935 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9936 } else { 9937 throw new IllegalStateException("Invalid stage location"); 9938 } 9939 } 9940 9941 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9942 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9943 9944 PackageInfoLite pkgLite = null; 9945 9946 if (onInt && onSd) { 9947 // Check if both bits are set. 9948 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9949 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9950 } else { 9951 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9952 packageAbiOverride); 9953 9954 /* 9955 * If we have too little free space, try to free cache 9956 * before giving up. 9957 */ 9958 if (!origin.staged && pkgLite.recommendedInstallLocation 9959 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9960 // TODO: focus freeing disk space on the target device 9961 final StorageManager storage = StorageManager.from(mContext); 9962 final long lowThreshold = storage.getStorageLowBytes( 9963 Environment.getDataDirectory()); 9964 9965 final long sizeBytes = mContainerService.calculateInstalledSize( 9966 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9967 9968 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9969 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9970 installFlags, packageAbiOverride); 9971 } 9972 9973 /* 9974 * The cache free must have deleted the file we 9975 * downloaded to install. 9976 * 9977 * TODO: fix the "freeCache" call to not delete 9978 * the file we care about. 9979 */ 9980 if (pkgLite.recommendedInstallLocation 9981 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9982 pkgLite.recommendedInstallLocation 9983 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9984 } 9985 } 9986 } 9987 9988 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9989 int loc = pkgLite.recommendedInstallLocation; 9990 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9991 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9992 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9993 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9994 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9995 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9996 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9997 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9998 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9999 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10000 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10001 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10002 } else { 10003 // Override with defaults if needed. 10004 loc = installLocationPolicy(pkgLite); 10005 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10006 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10007 } else if (!onSd && !onInt) { 10008 // Override install location with flags 10009 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10010 // Set the flag to install on external media. 10011 installFlags |= PackageManager.INSTALL_EXTERNAL; 10012 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10013 } else { 10014 // Make sure the flag for installing on external 10015 // media is unset 10016 installFlags |= PackageManager.INSTALL_INTERNAL; 10017 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10018 } 10019 } 10020 } 10021 } 10022 10023 final InstallArgs args = createInstallArgs(this); 10024 mArgs = args; 10025 10026 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10027 /* 10028 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10029 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10030 */ 10031 int userIdentifier = getUser().getIdentifier(); 10032 if (userIdentifier == UserHandle.USER_ALL 10033 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10034 userIdentifier = UserHandle.USER_OWNER; 10035 } 10036 10037 /* 10038 * Determine if we have any installed package verifiers. If we 10039 * do, then we'll defer to them to verify the packages. 10040 */ 10041 final int requiredUid = mRequiredVerifierPackage == null ? -1 10042 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10043 if (!origin.existing && requiredUid != -1 10044 && isVerificationEnabled(userIdentifier, installFlags)) { 10045 final Intent verification = new Intent( 10046 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10047 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10048 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10049 PACKAGE_MIME_TYPE); 10050 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10051 10052 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10053 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10054 0 /* TODO: Which userId? */); 10055 10056 if (DEBUG_VERIFY) { 10057 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10058 + verification.toString() + " with " + pkgLite.verifiers.length 10059 + " optional verifiers"); 10060 } 10061 10062 final int verificationId = mPendingVerificationToken++; 10063 10064 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10065 10066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10067 installerPackageName); 10068 10069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10070 installFlags); 10071 10072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10073 pkgLite.packageName); 10074 10075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10076 pkgLite.versionCode); 10077 10078 if (verificationParams != null) { 10079 if (verificationParams.getVerificationURI() != null) { 10080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10081 verificationParams.getVerificationURI()); 10082 } 10083 if (verificationParams.getOriginatingURI() != null) { 10084 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10085 verificationParams.getOriginatingURI()); 10086 } 10087 if (verificationParams.getReferrer() != null) { 10088 verification.putExtra(Intent.EXTRA_REFERRER, 10089 verificationParams.getReferrer()); 10090 } 10091 if (verificationParams.getOriginatingUid() >= 0) { 10092 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10093 verificationParams.getOriginatingUid()); 10094 } 10095 if (verificationParams.getInstallerUid() >= 0) { 10096 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10097 verificationParams.getInstallerUid()); 10098 } 10099 } 10100 10101 final PackageVerificationState verificationState = new PackageVerificationState( 10102 requiredUid, args); 10103 10104 mPendingVerification.append(verificationId, verificationState); 10105 10106 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10107 receivers, verificationState); 10108 10109 /* 10110 * If any sufficient verifiers were listed in the package 10111 * manifest, attempt to ask them. 10112 */ 10113 if (sufficientVerifiers != null) { 10114 final int N = sufficientVerifiers.size(); 10115 if (N == 0) { 10116 Slog.i(TAG, "Additional verifiers required, but none installed."); 10117 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10118 } else { 10119 for (int i = 0; i < N; i++) { 10120 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10121 10122 final Intent sufficientIntent = new Intent(verification); 10123 sufficientIntent.setComponent(verifierComponent); 10124 10125 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10126 } 10127 } 10128 } 10129 10130 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10131 mRequiredVerifierPackage, receivers); 10132 if (ret == PackageManager.INSTALL_SUCCEEDED 10133 && mRequiredVerifierPackage != null) { 10134 /* 10135 * Send the intent to the required verification agent, 10136 * but only start the verification timeout after the 10137 * target BroadcastReceivers have run. 10138 */ 10139 verification.setComponent(requiredVerifierComponent); 10140 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10141 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10142 new BroadcastReceiver() { 10143 @Override 10144 public void onReceive(Context context, Intent intent) { 10145 final Message msg = mHandler 10146 .obtainMessage(CHECK_PENDING_VERIFICATION); 10147 msg.arg1 = verificationId; 10148 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10149 } 10150 }, null, 0, null, null); 10151 10152 /* 10153 * We don't want the copy to proceed until verification 10154 * succeeds, so null out this field. 10155 */ 10156 mArgs = null; 10157 } 10158 } else { 10159 /* 10160 * No package verification is enabled, so immediately start 10161 * the remote call to initiate copy using temporary file. 10162 */ 10163 ret = args.copyApk(mContainerService, true); 10164 } 10165 } 10166 10167 mRet = ret; 10168 } 10169 10170 @Override 10171 void handleReturnCode() { 10172 // If mArgs is null, then MCS couldn't be reached. When it 10173 // reconnects, it will try again to install. At that point, this 10174 // will succeed. 10175 if (mArgs != null) { 10176 processPendingInstall(mArgs, mRet); 10177 } 10178 } 10179 10180 @Override 10181 void handleServiceError() { 10182 mArgs = createInstallArgs(this); 10183 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10184 } 10185 10186 public boolean isForwardLocked() { 10187 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10188 } 10189 } 10190 10191 /** 10192 * Used during creation of InstallArgs 10193 * 10194 * @param installFlags package installation flags 10195 * @return true if should be installed on external storage 10196 */ 10197 private static boolean installOnExternalAsec(int installFlags) { 10198 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10199 return false; 10200 } 10201 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10202 return true; 10203 } 10204 return false; 10205 } 10206 10207 /** 10208 * Used during creation of InstallArgs 10209 * 10210 * @param installFlags package installation flags 10211 * @return true if should be installed as forward locked 10212 */ 10213 private static boolean installForwardLocked(int installFlags) { 10214 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10215 } 10216 10217 private InstallArgs createInstallArgs(InstallParams params) { 10218 if (params.move != null) { 10219 return new MoveInstallArgs(params); 10220 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10221 return new AsecInstallArgs(params); 10222 } else { 10223 return new FileInstallArgs(params); 10224 } 10225 } 10226 10227 /** 10228 * Create args that describe an existing installed package. Typically used 10229 * when cleaning up old installs, or used as a move source. 10230 */ 10231 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10232 String resourcePath, String[] instructionSets) { 10233 final boolean isInAsec; 10234 if (installOnExternalAsec(installFlags)) { 10235 /* Apps on SD card are always in ASEC containers. */ 10236 isInAsec = true; 10237 } else if (installForwardLocked(installFlags) 10238 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10239 /* 10240 * Forward-locked apps are only in ASEC containers if they're the 10241 * new style 10242 */ 10243 isInAsec = true; 10244 } else { 10245 isInAsec = false; 10246 } 10247 10248 if (isInAsec) { 10249 return new AsecInstallArgs(codePath, instructionSets, 10250 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10251 } else { 10252 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10253 } 10254 } 10255 10256 static abstract class InstallArgs { 10257 /** @see InstallParams#origin */ 10258 final OriginInfo origin; 10259 /** @see InstallParams#move */ 10260 final MoveInfo move; 10261 10262 final IPackageInstallObserver2 observer; 10263 // Always refers to PackageManager flags only 10264 final int installFlags; 10265 final String installerPackageName; 10266 final String volumeUuid; 10267 final ManifestDigest manifestDigest; 10268 final UserHandle user; 10269 final String abiOverride; 10270 10271 // The list of instruction sets supported by this app. This is currently 10272 // only used during the rmdex() phase to clean up resources. We can get rid of this 10273 // if we move dex files under the common app path. 10274 /* nullable */ String[] instructionSets; 10275 10276 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10277 int installFlags, String installerPackageName, String volumeUuid, 10278 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10279 String abiOverride) { 10280 this.origin = origin; 10281 this.move = move; 10282 this.installFlags = installFlags; 10283 this.observer = observer; 10284 this.installerPackageName = installerPackageName; 10285 this.volumeUuid = volumeUuid; 10286 this.manifestDigest = manifestDigest; 10287 this.user = user; 10288 this.instructionSets = instructionSets; 10289 this.abiOverride = abiOverride; 10290 } 10291 10292 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10293 abstract int doPreInstall(int status); 10294 10295 /** 10296 * Rename package into final resting place. All paths on the given 10297 * scanned package should be updated to reflect the rename. 10298 */ 10299 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10300 abstract int doPostInstall(int status, int uid); 10301 10302 /** @see PackageSettingBase#codePathString */ 10303 abstract String getCodePath(); 10304 /** @see PackageSettingBase#resourcePathString */ 10305 abstract String getResourcePath(); 10306 10307 // Need installer lock especially for dex file removal. 10308 abstract void cleanUpResourcesLI(); 10309 abstract boolean doPostDeleteLI(boolean delete); 10310 10311 /** 10312 * Called before the source arguments are copied. This is used mostly 10313 * for MoveParams when it needs to read the source file to put it in the 10314 * destination. 10315 */ 10316 int doPreCopy() { 10317 return PackageManager.INSTALL_SUCCEEDED; 10318 } 10319 10320 /** 10321 * Called after the source arguments are copied. This is used mostly for 10322 * MoveParams when it needs to read the source file to put it in the 10323 * destination. 10324 * 10325 * @return 10326 */ 10327 int doPostCopy(int uid) { 10328 return PackageManager.INSTALL_SUCCEEDED; 10329 } 10330 10331 protected boolean isFwdLocked() { 10332 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10333 } 10334 10335 protected boolean isExternalAsec() { 10336 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10337 } 10338 10339 UserHandle getUser() { 10340 return user; 10341 } 10342 } 10343 10344 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10345 if (!allCodePaths.isEmpty()) { 10346 if (instructionSets == null) { 10347 throw new IllegalStateException("instructionSet == null"); 10348 } 10349 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10350 for (String codePath : allCodePaths) { 10351 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10352 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10353 if (retCode < 0) { 10354 Slog.w(TAG, "Couldn't remove dex file for package: " 10355 + " at location " + codePath + ", retcode=" + retCode); 10356 // we don't consider this to be a failure of the core package deletion 10357 } 10358 } 10359 } 10360 } 10361 } 10362 10363 /** 10364 * Logic to handle installation of non-ASEC applications, including copying 10365 * and renaming logic. 10366 */ 10367 class FileInstallArgs extends InstallArgs { 10368 private File codeFile; 10369 private File resourceFile; 10370 10371 // Example topology: 10372 // /data/app/com.example/base.apk 10373 // /data/app/com.example/split_foo.apk 10374 // /data/app/com.example/lib/arm/libfoo.so 10375 // /data/app/com.example/lib/arm64/libfoo.so 10376 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10377 10378 /** New install */ 10379 FileInstallArgs(InstallParams params) { 10380 super(params.origin, params.move, params.observer, params.installFlags, 10381 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10382 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10383 if (isFwdLocked()) { 10384 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10385 } 10386 } 10387 10388 /** Existing install */ 10389 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10390 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10391 null); 10392 this.codeFile = (codePath != null) ? new File(codePath) : null; 10393 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10394 } 10395 10396 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10397 if (origin.staged) { 10398 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10399 codeFile = origin.file; 10400 resourceFile = origin.file; 10401 return PackageManager.INSTALL_SUCCEEDED; 10402 } 10403 10404 try { 10405 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10406 codeFile = tempDir; 10407 resourceFile = tempDir; 10408 } catch (IOException e) { 10409 Slog.w(TAG, "Failed to create copy file: " + e); 10410 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10411 } 10412 10413 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10414 @Override 10415 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10416 if (!FileUtils.isValidExtFilename(name)) { 10417 throw new IllegalArgumentException("Invalid filename: " + name); 10418 } 10419 try { 10420 final File file = new File(codeFile, name); 10421 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10422 O_RDWR | O_CREAT, 0644); 10423 Os.chmod(file.getAbsolutePath(), 0644); 10424 return new ParcelFileDescriptor(fd); 10425 } catch (ErrnoException e) { 10426 throw new RemoteException("Failed to open: " + e.getMessage()); 10427 } 10428 } 10429 }; 10430 10431 int ret = PackageManager.INSTALL_SUCCEEDED; 10432 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10433 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10434 Slog.e(TAG, "Failed to copy package"); 10435 return ret; 10436 } 10437 10438 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10439 NativeLibraryHelper.Handle handle = null; 10440 try { 10441 handle = NativeLibraryHelper.Handle.create(codeFile); 10442 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10443 abiOverride); 10444 } catch (IOException e) { 10445 Slog.e(TAG, "Copying native libraries failed", e); 10446 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10447 } finally { 10448 IoUtils.closeQuietly(handle); 10449 } 10450 10451 return ret; 10452 } 10453 10454 int doPreInstall(int status) { 10455 if (status != PackageManager.INSTALL_SUCCEEDED) { 10456 cleanUp(); 10457 } 10458 return status; 10459 } 10460 10461 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10462 if (status != PackageManager.INSTALL_SUCCEEDED) { 10463 cleanUp(); 10464 return false; 10465 } 10466 10467 final File targetDir = codeFile.getParentFile(); 10468 final File beforeCodeFile = codeFile; 10469 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10470 10471 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10472 try { 10473 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10474 } catch (ErrnoException e) { 10475 Slog.w(TAG, "Failed to rename", e); 10476 return false; 10477 } 10478 10479 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10480 Slog.w(TAG, "Failed to restorecon"); 10481 return false; 10482 } 10483 10484 // Reflect the rename internally 10485 codeFile = afterCodeFile; 10486 resourceFile = afterCodeFile; 10487 10488 // Reflect the rename in scanned details 10489 pkg.codePath = afterCodeFile.getAbsolutePath(); 10490 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10491 pkg.baseCodePath); 10492 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10493 pkg.splitCodePaths); 10494 10495 // Reflect the rename in app info 10496 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10497 pkg.applicationInfo.setCodePath(pkg.codePath); 10498 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10499 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10500 pkg.applicationInfo.setResourcePath(pkg.codePath); 10501 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10502 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10503 10504 return true; 10505 } 10506 10507 int doPostInstall(int status, int uid) { 10508 if (status != PackageManager.INSTALL_SUCCEEDED) { 10509 cleanUp(); 10510 } 10511 return status; 10512 } 10513 10514 @Override 10515 String getCodePath() { 10516 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10517 } 10518 10519 @Override 10520 String getResourcePath() { 10521 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10522 } 10523 10524 private boolean cleanUp() { 10525 if (codeFile == null || !codeFile.exists()) { 10526 return false; 10527 } 10528 10529 if (codeFile.isDirectory()) { 10530 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10531 } else { 10532 codeFile.delete(); 10533 } 10534 10535 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10536 resourceFile.delete(); 10537 } 10538 10539 return true; 10540 } 10541 10542 void cleanUpResourcesLI() { 10543 // Try enumerating all code paths before deleting 10544 List<String> allCodePaths = Collections.EMPTY_LIST; 10545 if (codeFile != null && codeFile.exists()) { 10546 try { 10547 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10548 allCodePaths = pkg.getAllCodePaths(); 10549 } catch (PackageParserException e) { 10550 // Ignored; we tried our best 10551 } 10552 } 10553 10554 cleanUp(); 10555 removeDexFiles(allCodePaths, instructionSets); 10556 } 10557 10558 boolean doPostDeleteLI(boolean delete) { 10559 // XXX err, shouldn't we respect the delete flag? 10560 cleanUpResourcesLI(); 10561 return true; 10562 } 10563 } 10564 10565 private boolean isAsecExternal(String cid) { 10566 final String asecPath = PackageHelper.getSdFilesystem(cid); 10567 return !asecPath.startsWith(mAsecInternalPath); 10568 } 10569 10570 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10571 PackageManagerException { 10572 if (copyRet < 0) { 10573 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10574 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10575 throw new PackageManagerException(copyRet, message); 10576 } 10577 } 10578 } 10579 10580 /** 10581 * Extract the MountService "container ID" from the full code path of an 10582 * .apk. 10583 */ 10584 static String cidFromCodePath(String fullCodePath) { 10585 int eidx = fullCodePath.lastIndexOf("/"); 10586 String subStr1 = fullCodePath.substring(0, eidx); 10587 int sidx = subStr1.lastIndexOf("/"); 10588 return subStr1.substring(sidx+1, eidx); 10589 } 10590 10591 /** 10592 * Logic to handle installation of ASEC applications, including copying and 10593 * renaming logic. 10594 */ 10595 class AsecInstallArgs extends InstallArgs { 10596 static final String RES_FILE_NAME = "pkg.apk"; 10597 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10598 10599 String cid; 10600 String packagePath; 10601 String resourcePath; 10602 10603 /** New install */ 10604 AsecInstallArgs(InstallParams params) { 10605 super(params.origin, params.move, params.observer, params.installFlags, 10606 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10607 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10608 } 10609 10610 /** Existing install */ 10611 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10612 boolean isExternal, boolean isForwardLocked) { 10613 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10614 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10615 instructionSets, null); 10616 // Hackily pretend we're still looking at a full code path 10617 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10618 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10619 } 10620 10621 // Extract cid from fullCodePath 10622 int eidx = fullCodePath.lastIndexOf("/"); 10623 String subStr1 = fullCodePath.substring(0, eidx); 10624 int sidx = subStr1.lastIndexOf("/"); 10625 cid = subStr1.substring(sidx+1, eidx); 10626 setMountPath(subStr1); 10627 } 10628 10629 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10630 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10631 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10632 instructionSets, null); 10633 this.cid = cid; 10634 setMountPath(PackageHelper.getSdDir(cid)); 10635 } 10636 10637 void createCopyFile() { 10638 cid = mInstallerService.allocateExternalStageCidLegacy(); 10639 } 10640 10641 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10642 if (origin.staged) { 10643 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10644 cid = origin.cid; 10645 setMountPath(PackageHelper.getSdDir(cid)); 10646 return PackageManager.INSTALL_SUCCEEDED; 10647 } 10648 10649 if (temp) { 10650 createCopyFile(); 10651 } else { 10652 /* 10653 * Pre-emptively destroy the container since it's destroyed if 10654 * copying fails due to it existing anyway. 10655 */ 10656 PackageHelper.destroySdDir(cid); 10657 } 10658 10659 final String newMountPath = imcs.copyPackageToContainer( 10660 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10661 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10662 10663 if (newMountPath != null) { 10664 setMountPath(newMountPath); 10665 return PackageManager.INSTALL_SUCCEEDED; 10666 } else { 10667 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10668 } 10669 } 10670 10671 @Override 10672 String getCodePath() { 10673 return packagePath; 10674 } 10675 10676 @Override 10677 String getResourcePath() { 10678 return resourcePath; 10679 } 10680 10681 int doPreInstall(int status) { 10682 if (status != PackageManager.INSTALL_SUCCEEDED) { 10683 // Destroy container 10684 PackageHelper.destroySdDir(cid); 10685 } else { 10686 boolean mounted = PackageHelper.isContainerMounted(cid); 10687 if (!mounted) { 10688 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10689 Process.SYSTEM_UID); 10690 if (newMountPath != null) { 10691 setMountPath(newMountPath); 10692 } else { 10693 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10694 } 10695 } 10696 } 10697 return status; 10698 } 10699 10700 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10701 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10702 String newMountPath = null; 10703 if (PackageHelper.isContainerMounted(cid)) { 10704 // Unmount the container 10705 if (!PackageHelper.unMountSdDir(cid)) { 10706 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10707 return false; 10708 } 10709 } 10710 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10711 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10712 " which might be stale. Will try to clean up."); 10713 // Clean up the stale container and proceed to recreate. 10714 if (!PackageHelper.destroySdDir(newCacheId)) { 10715 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10716 return false; 10717 } 10718 // Successfully cleaned up stale container. Try to rename again. 10719 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10720 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10721 + " inspite of cleaning it up."); 10722 return false; 10723 } 10724 } 10725 if (!PackageHelper.isContainerMounted(newCacheId)) { 10726 Slog.w(TAG, "Mounting container " + newCacheId); 10727 newMountPath = PackageHelper.mountSdDir(newCacheId, 10728 getEncryptKey(), Process.SYSTEM_UID); 10729 } else { 10730 newMountPath = PackageHelper.getSdDir(newCacheId); 10731 } 10732 if (newMountPath == null) { 10733 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10734 return false; 10735 } 10736 Log.i(TAG, "Succesfully renamed " + cid + 10737 " to " + newCacheId + 10738 " at new path: " + newMountPath); 10739 cid = newCacheId; 10740 10741 final File beforeCodeFile = new File(packagePath); 10742 setMountPath(newMountPath); 10743 final File afterCodeFile = new File(packagePath); 10744 10745 // Reflect the rename in scanned details 10746 pkg.codePath = afterCodeFile.getAbsolutePath(); 10747 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10748 pkg.baseCodePath); 10749 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10750 pkg.splitCodePaths); 10751 10752 // Reflect the rename in app info 10753 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10754 pkg.applicationInfo.setCodePath(pkg.codePath); 10755 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10756 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10757 pkg.applicationInfo.setResourcePath(pkg.codePath); 10758 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10759 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10760 10761 return true; 10762 } 10763 10764 private void setMountPath(String mountPath) { 10765 final File mountFile = new File(mountPath); 10766 10767 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10768 if (monolithicFile.exists()) { 10769 packagePath = monolithicFile.getAbsolutePath(); 10770 if (isFwdLocked()) { 10771 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10772 } else { 10773 resourcePath = packagePath; 10774 } 10775 } else { 10776 packagePath = mountFile.getAbsolutePath(); 10777 resourcePath = packagePath; 10778 } 10779 } 10780 10781 int doPostInstall(int status, int uid) { 10782 if (status != PackageManager.INSTALL_SUCCEEDED) { 10783 cleanUp(); 10784 } else { 10785 final int groupOwner; 10786 final String protectedFile; 10787 if (isFwdLocked()) { 10788 groupOwner = UserHandle.getSharedAppGid(uid); 10789 protectedFile = RES_FILE_NAME; 10790 } else { 10791 groupOwner = -1; 10792 protectedFile = null; 10793 } 10794 10795 if (uid < Process.FIRST_APPLICATION_UID 10796 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10797 Slog.e(TAG, "Failed to finalize " + cid); 10798 PackageHelper.destroySdDir(cid); 10799 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10800 } 10801 10802 boolean mounted = PackageHelper.isContainerMounted(cid); 10803 if (!mounted) { 10804 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10805 } 10806 } 10807 return status; 10808 } 10809 10810 private void cleanUp() { 10811 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10812 10813 // Destroy secure container 10814 PackageHelper.destroySdDir(cid); 10815 } 10816 10817 private List<String> getAllCodePaths() { 10818 final File codeFile = new File(getCodePath()); 10819 if (codeFile != null && codeFile.exists()) { 10820 try { 10821 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10822 return pkg.getAllCodePaths(); 10823 } catch (PackageParserException e) { 10824 // Ignored; we tried our best 10825 } 10826 } 10827 return Collections.EMPTY_LIST; 10828 } 10829 10830 void cleanUpResourcesLI() { 10831 // Enumerate all code paths before deleting 10832 cleanUpResourcesLI(getAllCodePaths()); 10833 } 10834 10835 private void cleanUpResourcesLI(List<String> allCodePaths) { 10836 cleanUp(); 10837 removeDexFiles(allCodePaths, instructionSets); 10838 } 10839 10840 String getPackageName() { 10841 return getAsecPackageName(cid); 10842 } 10843 10844 boolean doPostDeleteLI(boolean delete) { 10845 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10846 final List<String> allCodePaths = getAllCodePaths(); 10847 boolean mounted = PackageHelper.isContainerMounted(cid); 10848 if (mounted) { 10849 // Unmount first 10850 if (PackageHelper.unMountSdDir(cid)) { 10851 mounted = false; 10852 } 10853 } 10854 if (!mounted && delete) { 10855 cleanUpResourcesLI(allCodePaths); 10856 } 10857 return !mounted; 10858 } 10859 10860 @Override 10861 int doPreCopy() { 10862 if (isFwdLocked()) { 10863 if (!PackageHelper.fixSdPermissions(cid, 10864 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10865 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10866 } 10867 } 10868 10869 return PackageManager.INSTALL_SUCCEEDED; 10870 } 10871 10872 @Override 10873 int doPostCopy(int uid) { 10874 if (isFwdLocked()) { 10875 if (uid < Process.FIRST_APPLICATION_UID 10876 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10877 RES_FILE_NAME)) { 10878 Slog.e(TAG, "Failed to finalize " + cid); 10879 PackageHelper.destroySdDir(cid); 10880 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10881 } 10882 } 10883 10884 return PackageManager.INSTALL_SUCCEEDED; 10885 } 10886 } 10887 10888 /** 10889 * Logic to handle movement of existing installed applications. 10890 */ 10891 class MoveInstallArgs extends InstallArgs { 10892 private File codeFile; 10893 private File resourceFile; 10894 10895 /** New install */ 10896 MoveInstallArgs(InstallParams params) { 10897 super(params.origin, params.move, params.observer, params.installFlags, 10898 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10899 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10900 } 10901 10902 int copyApk(IMediaContainerService imcs, boolean temp) { 10903 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10904 + move.fromUuid + " to " + move.toUuid); 10905 synchronized (mInstaller) { 10906 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10907 move.dataAppName, move.appId, move.seinfo) != 0) { 10908 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10909 } 10910 } 10911 10912 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10913 resourceFile = codeFile; 10914 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10915 10916 return PackageManager.INSTALL_SUCCEEDED; 10917 } 10918 10919 int doPreInstall(int status) { 10920 if (status != PackageManager.INSTALL_SUCCEEDED) { 10921 cleanUp(); 10922 } 10923 return status; 10924 } 10925 10926 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10927 if (status != PackageManager.INSTALL_SUCCEEDED) { 10928 cleanUp(); 10929 return false; 10930 } 10931 10932 // Reflect the move in app info 10933 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10934 pkg.applicationInfo.setCodePath(pkg.codePath); 10935 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10936 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10937 pkg.applicationInfo.setResourcePath(pkg.codePath); 10938 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10939 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10940 10941 return true; 10942 } 10943 10944 int doPostInstall(int status, int uid) { 10945 if (status != PackageManager.INSTALL_SUCCEEDED) { 10946 cleanUp(); 10947 } 10948 return status; 10949 } 10950 10951 @Override 10952 String getCodePath() { 10953 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10954 } 10955 10956 @Override 10957 String getResourcePath() { 10958 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10959 } 10960 10961 private boolean cleanUp() { 10962 if (codeFile == null || !codeFile.exists()) { 10963 return false; 10964 } 10965 10966 if (codeFile.isDirectory()) { 10967 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10968 } else { 10969 codeFile.delete(); 10970 } 10971 10972 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10973 resourceFile.delete(); 10974 } 10975 10976 return true; 10977 } 10978 10979 void cleanUpResourcesLI() { 10980 cleanUp(); 10981 } 10982 10983 boolean doPostDeleteLI(boolean delete) { 10984 // XXX err, shouldn't we respect the delete flag? 10985 cleanUpResourcesLI(); 10986 return true; 10987 } 10988 } 10989 10990 static String getAsecPackageName(String packageCid) { 10991 int idx = packageCid.lastIndexOf("-"); 10992 if (idx == -1) { 10993 return packageCid; 10994 } 10995 return packageCid.substring(0, idx); 10996 } 10997 10998 // Utility method used to create code paths based on package name and available index. 10999 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11000 String idxStr = ""; 11001 int idx = 1; 11002 // Fall back to default value of idx=1 if prefix is not 11003 // part of oldCodePath 11004 if (oldCodePath != null) { 11005 String subStr = oldCodePath; 11006 // Drop the suffix right away 11007 if (suffix != null && subStr.endsWith(suffix)) { 11008 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11009 } 11010 // If oldCodePath already contains prefix find out the 11011 // ending index to either increment or decrement. 11012 int sidx = subStr.lastIndexOf(prefix); 11013 if (sidx != -1) { 11014 subStr = subStr.substring(sidx + prefix.length()); 11015 if (subStr != null) { 11016 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11017 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11018 } 11019 try { 11020 idx = Integer.parseInt(subStr); 11021 if (idx <= 1) { 11022 idx++; 11023 } else { 11024 idx--; 11025 } 11026 } catch(NumberFormatException e) { 11027 } 11028 } 11029 } 11030 } 11031 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11032 return prefix + idxStr; 11033 } 11034 11035 private File getNextCodePath(File targetDir, String packageName) { 11036 int suffix = 1; 11037 File result; 11038 do { 11039 result = new File(targetDir, packageName + "-" + suffix); 11040 suffix++; 11041 } while (result.exists()); 11042 return result; 11043 } 11044 11045 // Utility method that returns the relative package path with respect 11046 // to the installation directory. Like say for /data/data/com.test-1.apk 11047 // string com.test-1 is returned. 11048 static String deriveCodePathName(String codePath) { 11049 if (codePath == null) { 11050 return null; 11051 } 11052 final File codeFile = new File(codePath); 11053 final String name = codeFile.getName(); 11054 if (codeFile.isDirectory()) { 11055 return name; 11056 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11057 final int lastDot = name.lastIndexOf('.'); 11058 return name.substring(0, lastDot); 11059 } else { 11060 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11061 return null; 11062 } 11063 } 11064 11065 class PackageInstalledInfo { 11066 String name; 11067 int uid; 11068 // The set of users that originally had this package installed. 11069 int[] origUsers; 11070 // The set of users that now have this package installed. 11071 int[] newUsers; 11072 PackageParser.Package pkg; 11073 int returnCode; 11074 String returnMsg; 11075 PackageRemovedInfo removedInfo; 11076 11077 public void setError(int code, String msg) { 11078 returnCode = code; 11079 returnMsg = msg; 11080 Slog.w(TAG, msg); 11081 } 11082 11083 public void setError(String msg, PackageParserException e) { 11084 returnCode = e.error; 11085 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11086 Slog.w(TAG, msg, e); 11087 } 11088 11089 public void setError(String msg, PackageManagerException e) { 11090 returnCode = e.error; 11091 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11092 Slog.w(TAG, msg, e); 11093 } 11094 11095 // In some error cases we want to convey more info back to the observer 11096 String origPackage; 11097 String origPermission; 11098 } 11099 11100 /* 11101 * Install a non-existing package. 11102 */ 11103 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11104 UserHandle user, String installerPackageName, String volumeUuid, 11105 PackageInstalledInfo res) { 11106 // Remember this for later, in case we need to rollback this install 11107 String pkgName = pkg.packageName; 11108 11109 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11110 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11111 UserHandle.USER_OWNER).exists(); 11112 synchronized(mPackages) { 11113 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11114 // A package with the same name is already installed, though 11115 // it has been renamed to an older name. The package we 11116 // are trying to install should be installed as an update to 11117 // the existing one, but that has not been requested, so bail. 11118 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11119 + " without first uninstalling package running as " 11120 + mSettings.mRenamedPackages.get(pkgName)); 11121 return; 11122 } 11123 if (mPackages.containsKey(pkgName)) { 11124 // Don't allow installation over an existing package with the same name. 11125 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11126 + " without first uninstalling."); 11127 return; 11128 } 11129 } 11130 11131 try { 11132 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11133 System.currentTimeMillis(), user); 11134 11135 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11136 // delete the partially installed application. the data directory will have to be 11137 // restored if it was already existing 11138 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11139 // remove package from internal structures. Note that we want deletePackageX to 11140 // delete the package data and cache directories that it created in 11141 // scanPackageLocked, unless those directories existed before we even tried to 11142 // install. 11143 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11144 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11145 res.removedInfo, true); 11146 } 11147 11148 } catch (PackageManagerException e) { 11149 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11150 } 11151 } 11152 11153 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11154 // Can't rotate keys during boot or if sharedUser. 11155 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11156 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11157 return false; 11158 } 11159 // app is using upgradeKeySets; make sure all are valid 11160 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11161 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11162 for (int i = 0; i < upgradeKeySets.length; i++) { 11163 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11164 Slog.wtf(TAG, "Package " 11165 + (oldPs.name != null ? oldPs.name : "<null>") 11166 + " contains upgrade-key-set reference to unknown key-set: " 11167 + upgradeKeySets[i] 11168 + " reverting to signatures check."); 11169 return false; 11170 } 11171 } 11172 return true; 11173 } 11174 11175 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11176 // Upgrade keysets are being used. Determine if new package has a superset of the 11177 // required keys. 11178 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11180 for (int i = 0; i < upgradeKeySets.length; i++) { 11181 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11182 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11183 return true; 11184 } 11185 } 11186 return false; 11187 } 11188 11189 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11190 UserHandle user, String installerPackageName, String volumeUuid, 11191 PackageInstalledInfo res) { 11192 final PackageParser.Package oldPackage; 11193 final String pkgName = pkg.packageName; 11194 final int[] allUsers; 11195 final boolean[] perUserInstalled; 11196 final boolean weFroze; 11197 11198 // First find the old package info and check signatures 11199 synchronized(mPackages) { 11200 oldPackage = mPackages.get(pkgName); 11201 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11202 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11203 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11204 if(!checkUpgradeKeySetLP(ps, pkg)) { 11205 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11206 "New package not signed by keys specified by upgrade-keysets: " 11207 + pkgName); 11208 return; 11209 } 11210 } else { 11211 // default to original signature matching 11212 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11213 != PackageManager.SIGNATURE_MATCH) { 11214 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11215 "New package has a different signature: " + pkgName); 11216 return; 11217 } 11218 } 11219 11220 // In case of rollback, remember per-user/profile install state 11221 allUsers = sUserManager.getUserIds(); 11222 perUserInstalled = new boolean[allUsers.length]; 11223 for (int i = 0; i < allUsers.length; i++) { 11224 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11225 } 11226 11227 // Mark the app as frozen to prevent launching during the upgrade 11228 // process, and then kill all running instances 11229 if (!ps.frozen) { 11230 ps.frozen = true; 11231 weFroze = true; 11232 } else { 11233 weFroze = false; 11234 } 11235 } 11236 11237 // Now that we're guarded by frozen state, kill app during upgrade 11238 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11239 11240 try { 11241 boolean sysPkg = (isSystemApp(oldPackage)); 11242 if (sysPkg) { 11243 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11244 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11245 } else { 11246 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11247 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11248 } 11249 } finally { 11250 // Regardless of success or failure of upgrade steps above, always 11251 // unfreeze the package if we froze it 11252 if (weFroze) { 11253 unfreezePackage(pkgName); 11254 } 11255 } 11256 } 11257 11258 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11259 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11260 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11261 String volumeUuid, PackageInstalledInfo res) { 11262 String pkgName = deletedPackage.packageName; 11263 boolean deletedPkg = true; 11264 boolean updatedSettings = false; 11265 11266 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11267 + deletedPackage); 11268 long origUpdateTime; 11269 if (pkg.mExtras != null) { 11270 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11271 } else { 11272 origUpdateTime = 0; 11273 } 11274 11275 // First delete the existing package while retaining the data directory 11276 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11277 res.removedInfo, true)) { 11278 // If the existing package wasn't successfully deleted 11279 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11280 deletedPkg = false; 11281 } else { 11282 // Successfully deleted the old package; proceed with replace. 11283 11284 // If deleted package lived in a container, give users a chance to 11285 // relinquish resources before killing. 11286 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11287 if (DEBUG_INSTALL) { 11288 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11289 } 11290 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11291 final ArrayList<String> pkgList = new ArrayList<String>(1); 11292 pkgList.add(deletedPackage.applicationInfo.packageName); 11293 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11294 } 11295 11296 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11297 try { 11298 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11299 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11300 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11301 perUserInstalled, res, user); 11302 updatedSettings = true; 11303 } catch (PackageManagerException e) { 11304 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11305 } 11306 } 11307 11308 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11309 // remove package from internal structures. Note that we want deletePackageX to 11310 // delete the package data and cache directories that it created in 11311 // scanPackageLocked, unless those directories existed before we even tried to 11312 // install. 11313 if(updatedSettings) { 11314 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11315 deletePackageLI( 11316 pkgName, null, true, allUsers, perUserInstalled, 11317 PackageManager.DELETE_KEEP_DATA, 11318 res.removedInfo, true); 11319 } 11320 // Since we failed to install the new package we need to restore the old 11321 // package that we deleted. 11322 if (deletedPkg) { 11323 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11324 File restoreFile = new File(deletedPackage.codePath); 11325 // Parse old package 11326 boolean oldExternal = isExternal(deletedPackage); 11327 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11328 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11329 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11330 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11331 try { 11332 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11333 } catch (PackageManagerException e) { 11334 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11335 + e.getMessage()); 11336 return; 11337 } 11338 // Restore of old package succeeded. Update permissions. 11339 // writer 11340 synchronized (mPackages) { 11341 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11342 UPDATE_PERMISSIONS_ALL); 11343 // can downgrade to reader 11344 mSettings.writeLPr(); 11345 } 11346 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11347 } 11348 } 11349 } 11350 11351 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11352 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11353 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11354 String volumeUuid, PackageInstalledInfo res) { 11355 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11356 + ", old=" + deletedPackage); 11357 boolean disabledSystem = false; 11358 boolean updatedSettings = false; 11359 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11360 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11361 != 0) { 11362 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11363 } 11364 String packageName = deletedPackage.packageName; 11365 if (packageName == null) { 11366 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11367 "Attempt to delete null packageName."); 11368 return; 11369 } 11370 PackageParser.Package oldPkg; 11371 PackageSetting oldPkgSetting; 11372 // reader 11373 synchronized (mPackages) { 11374 oldPkg = mPackages.get(packageName); 11375 oldPkgSetting = mSettings.mPackages.get(packageName); 11376 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11377 (oldPkgSetting == null)) { 11378 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11379 "Couldn't find package:" + packageName + " information"); 11380 return; 11381 } 11382 } 11383 11384 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11385 res.removedInfo.removedPackage = packageName; 11386 // Remove existing system package 11387 removePackageLI(oldPkgSetting, true); 11388 // writer 11389 synchronized (mPackages) { 11390 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11391 if (!disabledSystem && deletedPackage != null) { 11392 // We didn't need to disable the .apk as a current system package, 11393 // which means we are replacing another update that is already 11394 // installed. We need to make sure to delete the older one's .apk. 11395 res.removedInfo.args = createInstallArgsForExisting(0, 11396 deletedPackage.applicationInfo.getCodePath(), 11397 deletedPackage.applicationInfo.getResourcePath(), 11398 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11399 } else { 11400 res.removedInfo.args = null; 11401 } 11402 } 11403 11404 // Successfully disabled the old package. Now proceed with re-installation 11405 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11406 11407 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11408 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11409 11410 PackageParser.Package newPackage = null; 11411 try { 11412 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11413 if (newPackage.mExtras != null) { 11414 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11415 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11416 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11417 11418 // is the update attempting to change shared user? that isn't going to work... 11419 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11420 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11421 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11422 + " to " + newPkgSetting.sharedUser); 11423 updatedSettings = true; 11424 } 11425 } 11426 11427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11428 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11429 perUserInstalled, res, user); 11430 updatedSettings = true; 11431 } 11432 11433 } catch (PackageManagerException e) { 11434 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11435 } 11436 11437 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11438 // Re installation failed. Restore old information 11439 // Remove new pkg information 11440 if (newPackage != null) { 11441 removeInstalledPackageLI(newPackage, true); 11442 } 11443 // Add back the old system package 11444 try { 11445 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11446 } catch (PackageManagerException e) { 11447 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11448 } 11449 // Restore the old system information in Settings 11450 synchronized (mPackages) { 11451 if (disabledSystem) { 11452 mSettings.enableSystemPackageLPw(packageName); 11453 } 11454 if (updatedSettings) { 11455 mSettings.setInstallerPackageName(packageName, 11456 oldPkgSetting.installerPackageName); 11457 } 11458 mSettings.writeLPr(); 11459 } 11460 } 11461 } 11462 11463 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11464 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11465 UserHandle user) { 11466 String pkgName = newPackage.packageName; 11467 synchronized (mPackages) { 11468 //write settings. the installStatus will be incomplete at this stage. 11469 //note that the new package setting would have already been 11470 //added to mPackages. It hasn't been persisted yet. 11471 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11472 mSettings.writeLPr(); 11473 } 11474 11475 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11476 11477 synchronized (mPackages) { 11478 updatePermissionsLPw(newPackage.packageName, newPackage, 11479 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11480 ? UPDATE_PERMISSIONS_ALL : 0)); 11481 // For system-bundled packages, we assume that installing an upgraded version 11482 // of the package implies that the user actually wants to run that new code, 11483 // so we enable the package. 11484 PackageSetting ps = mSettings.mPackages.get(pkgName); 11485 if (ps != null) { 11486 if (isSystemApp(newPackage)) { 11487 // NB: implicit assumption that system package upgrades apply to all users 11488 if (DEBUG_INSTALL) { 11489 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11490 } 11491 if (res.origUsers != null) { 11492 for (int userHandle : res.origUsers) { 11493 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11494 userHandle, installerPackageName); 11495 } 11496 } 11497 // Also convey the prior install/uninstall state 11498 if (allUsers != null && perUserInstalled != null) { 11499 for (int i = 0; i < allUsers.length; i++) { 11500 if (DEBUG_INSTALL) { 11501 Slog.d(TAG, " user " + allUsers[i] 11502 + " => " + perUserInstalled[i]); 11503 } 11504 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11505 } 11506 // these install state changes will be persisted in the 11507 // upcoming call to mSettings.writeLPr(). 11508 } 11509 } 11510 // It's implied that when a user requests installation, they want the app to be 11511 // installed and enabled. 11512 int userId = user.getIdentifier(); 11513 if (userId != UserHandle.USER_ALL) { 11514 ps.setInstalled(true, userId); 11515 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11516 } 11517 } 11518 res.name = pkgName; 11519 res.uid = newPackage.applicationInfo.uid; 11520 res.pkg = newPackage; 11521 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11522 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11523 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11524 //to update install status 11525 mSettings.writeLPr(); 11526 } 11527 } 11528 11529 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11530 final int installFlags = args.installFlags; 11531 final String installerPackageName = args.installerPackageName; 11532 final String volumeUuid = args.volumeUuid; 11533 final File tmpPackageFile = new File(args.getCodePath()); 11534 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11535 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11536 || (args.volumeUuid != null)); 11537 boolean replace = false; 11538 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11539 // Result object to be returned 11540 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11541 11542 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11543 // Retrieve PackageSettings and parse package 11544 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11545 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11546 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11547 PackageParser pp = new PackageParser(); 11548 pp.setSeparateProcesses(mSeparateProcesses); 11549 pp.setDisplayMetrics(mMetrics); 11550 11551 final PackageParser.Package pkg; 11552 try { 11553 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11554 } catch (PackageParserException e) { 11555 res.setError("Failed parse during installPackageLI", e); 11556 return; 11557 } 11558 11559 // Mark that we have an install time CPU ABI override. 11560 pkg.cpuAbiOverride = args.abiOverride; 11561 11562 String pkgName = res.name = pkg.packageName; 11563 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11564 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11565 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11566 return; 11567 } 11568 } 11569 11570 try { 11571 pp.collectCertificates(pkg, parseFlags); 11572 pp.collectManifestDigest(pkg); 11573 } catch (PackageParserException e) { 11574 res.setError("Failed collect during installPackageLI", e); 11575 return; 11576 } 11577 11578 /* If the installer passed in a manifest digest, compare it now. */ 11579 if (args.manifestDigest != null) { 11580 if (DEBUG_INSTALL) { 11581 final String parsedManifest = pkg.manifestDigest == null ? "null" 11582 : pkg.manifestDigest.toString(); 11583 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11584 + parsedManifest); 11585 } 11586 11587 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11588 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11589 return; 11590 } 11591 } else if (DEBUG_INSTALL) { 11592 final String parsedManifest = pkg.manifestDigest == null 11593 ? "null" : pkg.manifestDigest.toString(); 11594 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11595 } 11596 11597 // Get rid of all references to package scan path via parser. 11598 pp = null; 11599 String oldCodePath = null; 11600 boolean systemApp = false; 11601 synchronized (mPackages) { 11602 // Check if installing already existing package 11603 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11604 String oldName = mSettings.mRenamedPackages.get(pkgName); 11605 if (pkg.mOriginalPackages != null 11606 && pkg.mOriginalPackages.contains(oldName) 11607 && mPackages.containsKey(oldName)) { 11608 // This package is derived from an original package, 11609 // and this device has been updating from that original 11610 // name. We must continue using the original name, so 11611 // rename the new package here. 11612 pkg.setPackageName(oldName); 11613 pkgName = pkg.packageName; 11614 replace = true; 11615 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11616 + oldName + " pkgName=" + pkgName); 11617 } else if (mPackages.containsKey(pkgName)) { 11618 // This package, under its official name, already exists 11619 // on the device; we should replace it. 11620 replace = true; 11621 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11622 } 11623 11624 // Prevent apps opting out from runtime permissions 11625 if (replace) { 11626 PackageParser.Package oldPackage = mPackages.get(pkgName); 11627 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11628 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11629 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11630 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11631 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11632 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11633 + " doesn't support runtime permissions but the old" 11634 + " target SDK " + oldTargetSdk + " does."); 11635 return; 11636 } 11637 } 11638 } 11639 11640 PackageSetting ps = mSettings.mPackages.get(pkgName); 11641 if (ps != null) { 11642 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11643 11644 // Quick sanity check that we're signed correctly if updating; 11645 // we'll check this again later when scanning, but we want to 11646 // bail early here before tripping over redefined permissions. 11647 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11648 if (!checkUpgradeKeySetLP(ps, pkg)) { 11649 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11650 + pkg.packageName + " upgrade keys do not match the " 11651 + "previously installed version"); 11652 return; 11653 } 11654 } else { 11655 try { 11656 verifySignaturesLP(ps, pkg); 11657 } catch (PackageManagerException e) { 11658 res.setError(e.error, e.getMessage()); 11659 return; 11660 } 11661 } 11662 11663 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11664 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11665 systemApp = (ps.pkg.applicationInfo.flags & 11666 ApplicationInfo.FLAG_SYSTEM) != 0; 11667 } 11668 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11669 } 11670 11671 // Check whether the newly-scanned package wants to define an already-defined perm 11672 int N = pkg.permissions.size(); 11673 for (int i = N-1; i >= 0; i--) { 11674 PackageParser.Permission perm = pkg.permissions.get(i); 11675 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11676 if (bp != null) { 11677 // If the defining package is signed with our cert, it's okay. This 11678 // also includes the "updating the same package" case, of course. 11679 // "updating same package" could also involve key-rotation. 11680 final boolean sigsOk; 11681 if (bp.sourcePackage.equals(pkg.packageName) 11682 && (bp.packageSetting instanceof PackageSetting) 11683 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11684 scanFlags))) { 11685 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11686 } else { 11687 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11688 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11689 } 11690 if (!sigsOk) { 11691 // If the owning package is the system itself, we log but allow 11692 // install to proceed; we fail the install on all other permission 11693 // redefinitions. 11694 if (!bp.sourcePackage.equals("android")) { 11695 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11696 + pkg.packageName + " attempting to redeclare permission " 11697 + perm.info.name + " already owned by " + bp.sourcePackage); 11698 res.origPermission = perm.info.name; 11699 res.origPackage = bp.sourcePackage; 11700 return; 11701 } else { 11702 Slog.w(TAG, "Package " + pkg.packageName 11703 + " attempting to redeclare system permission " 11704 + perm.info.name + "; ignoring new declaration"); 11705 pkg.permissions.remove(i); 11706 } 11707 } 11708 } 11709 } 11710 11711 } 11712 11713 if (systemApp && onExternal) { 11714 // Disable updates to system apps on sdcard 11715 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11716 "Cannot install updates to system apps on sdcard"); 11717 return; 11718 } 11719 11720 if (args.move != null) { 11721 // We did an in-place move, so dex is ready to roll 11722 scanFlags |= SCAN_NO_DEX; 11723 scanFlags |= SCAN_MOVE; 11724 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11725 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11726 scanFlags |= SCAN_NO_DEX; 11727 11728 try { 11729 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11730 true /* extract libs */); 11731 } catch (PackageManagerException pme) { 11732 Slog.e(TAG, "Error deriving application ABI", pme); 11733 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11734 return; 11735 } 11736 11737 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11738 int result = mPackageDexOptimizer 11739 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11740 false /* defer */, false /* inclDependencies */); 11741 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11742 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11743 return; 11744 } 11745 } 11746 11747 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11748 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11749 return; 11750 } 11751 11752 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11753 11754 if (replace) { 11755 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11756 installerPackageName, volumeUuid, res); 11757 } else { 11758 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11759 args.user, installerPackageName, volumeUuid, res); 11760 } 11761 synchronized (mPackages) { 11762 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11763 if (ps != null) { 11764 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11765 } 11766 } 11767 } 11768 11769 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11770 if (mIntentFilterVerifierComponent == null) { 11771 Slog.w(TAG, "No IntentFilter verification will not be done as " 11772 + "there is no IntentFilterVerifier available!"); 11773 return; 11774 } 11775 11776 final int verifierUid = getPackageUid( 11777 mIntentFilterVerifierComponent.getPackageName(), 11778 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11779 11780 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11781 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11782 msg.obj = pkg; 11783 msg.arg1 = userId; 11784 msg.arg2 = verifierUid; 11785 11786 mHandler.sendMessage(msg); 11787 } 11788 11789 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11790 PackageParser.Package pkg) { 11791 int size = pkg.activities.size(); 11792 if (size == 0) { 11793 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11794 "No activity, so no need to verify any IntentFilter!"); 11795 return; 11796 } 11797 11798 final boolean hasDomainURLs = hasDomainURLs(pkg); 11799 if (!hasDomainURLs) { 11800 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11801 "No domain URLs, so no need to verify any IntentFilter!"); 11802 return; 11803 } 11804 11805 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11806 + " if any IntentFilter from the " + size 11807 + " Activities needs verification ..."); 11808 11809 final int verificationId = mIntentFilterVerificationToken++; 11810 int count = 0; 11811 final String packageName = pkg.packageName; 11812 boolean needToVerify = false; 11813 11814 synchronized (mPackages) { 11815 // If any filters need to be verified, then all need to be. 11816 for (PackageParser.Activity a : pkg.activities) { 11817 for (ActivityIntentInfo filter : a.intents) { 11818 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11819 if (DEBUG_DOMAIN_VERIFICATION) { 11820 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11821 } 11822 needToVerify = true; 11823 break; 11824 } 11825 } 11826 } 11827 if (needToVerify) { 11828 for (PackageParser.Activity a : pkg.activities) { 11829 for (ActivityIntentInfo filter : a.intents) { 11830 boolean needsFilterVerification = filter.hasWebDataURI(); 11831 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11833 "Verification needed for IntentFilter:" + filter.toString()); 11834 mIntentFilterVerifier.addOneIntentFilterVerification( 11835 verifierUid, userId, verificationId, filter, packageName); 11836 count++; 11837 } 11838 } 11839 } 11840 } 11841 } 11842 11843 if (count > 0) { 11844 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11845 + " IntentFilter verification" + (count > 1 ? "s" : "") 11846 + " for userId:" + userId); 11847 mIntentFilterVerifier.startVerifications(userId); 11848 } else { 11849 if (DEBUG_DOMAIN_VERIFICATION) { 11850 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11851 } 11852 } 11853 } 11854 11855 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11856 final ComponentName cn = filter.activity.getComponentName(); 11857 final String packageName = cn.getPackageName(); 11858 11859 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11860 packageName); 11861 if (ivi == null) { 11862 return true; 11863 } 11864 int status = ivi.getStatus(); 11865 switch (status) { 11866 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11867 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11868 return true; 11869 11870 default: 11871 // Nothing to do 11872 return false; 11873 } 11874 } 11875 11876 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11877 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11878 || ((pkg.applicationInfo.privateFlags 11879 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11880 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11881 } 11882 11883 private static boolean isMultiArch(PackageSetting ps) { 11884 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11885 } 11886 11887 private static boolean isMultiArch(ApplicationInfo info) { 11888 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11889 } 11890 11891 private static boolean isExternal(PackageParser.Package pkg) { 11892 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11893 } 11894 11895 private static boolean isExternal(PackageSetting ps) { 11896 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11897 } 11898 11899 private static boolean isExternal(ApplicationInfo info) { 11900 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11901 } 11902 11903 private static boolean isSystemApp(PackageParser.Package pkg) { 11904 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11905 } 11906 11907 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11908 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11909 } 11910 11911 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11912 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11913 } 11914 11915 private static boolean isSystemApp(PackageSetting ps) { 11916 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11917 } 11918 11919 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11920 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11921 } 11922 11923 private int packageFlagsToInstallFlags(PackageSetting ps) { 11924 int installFlags = 0; 11925 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11926 // This existing package was an external ASEC install when we have 11927 // the external flag without a UUID 11928 installFlags |= PackageManager.INSTALL_EXTERNAL; 11929 } 11930 if (ps.isForwardLocked()) { 11931 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11932 } 11933 return installFlags; 11934 } 11935 11936 private void deleteTempPackageFiles() { 11937 final FilenameFilter filter = new FilenameFilter() { 11938 public boolean accept(File dir, String name) { 11939 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11940 } 11941 }; 11942 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11943 file.delete(); 11944 } 11945 } 11946 11947 @Override 11948 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11949 int flags) { 11950 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11951 flags); 11952 } 11953 11954 @Override 11955 public void deletePackage(final String packageName, 11956 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11957 mContext.enforceCallingOrSelfPermission( 11958 android.Manifest.permission.DELETE_PACKAGES, null); 11959 final int uid = Binder.getCallingUid(); 11960 if (UserHandle.getUserId(uid) != userId) { 11961 mContext.enforceCallingPermission( 11962 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11963 "deletePackage for user " + userId); 11964 } 11965 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11966 try { 11967 observer.onPackageDeleted(packageName, 11968 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11969 } catch (RemoteException re) { 11970 } 11971 return; 11972 } 11973 11974 boolean uninstallBlocked = false; 11975 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11976 int[] users = sUserManager.getUserIds(); 11977 for (int i = 0; i < users.length; ++i) { 11978 if (getBlockUninstallForUser(packageName, users[i])) { 11979 uninstallBlocked = true; 11980 break; 11981 } 11982 } 11983 } else { 11984 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11985 } 11986 if (uninstallBlocked) { 11987 try { 11988 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11989 null); 11990 } catch (RemoteException re) { 11991 } 11992 return; 11993 } 11994 11995 if (DEBUG_REMOVE) { 11996 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11997 } 11998 // Queue up an async operation since the package deletion may take a little while. 11999 mHandler.post(new Runnable() { 12000 public void run() { 12001 mHandler.removeCallbacks(this); 12002 final int returnCode = deletePackageX(packageName, userId, flags); 12003 if (observer != null) { 12004 try { 12005 observer.onPackageDeleted(packageName, returnCode, null); 12006 } catch (RemoteException e) { 12007 Log.i(TAG, "Observer no longer exists."); 12008 } //end catch 12009 } //end if 12010 } //end run 12011 }); 12012 } 12013 12014 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12015 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12016 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12017 try { 12018 if (dpm != null) { 12019 if (dpm.isDeviceOwner(packageName)) { 12020 return true; 12021 } 12022 int[] users; 12023 if (userId == UserHandle.USER_ALL) { 12024 users = sUserManager.getUserIds(); 12025 } else { 12026 users = new int[]{userId}; 12027 } 12028 for (int i = 0; i < users.length; ++i) { 12029 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12030 return true; 12031 } 12032 } 12033 } 12034 } catch (RemoteException e) { 12035 } 12036 return false; 12037 } 12038 12039 /** 12040 * This method is an internal method that could be get invoked either 12041 * to delete an installed package or to clean up a failed installation. 12042 * After deleting an installed package, a broadcast is sent to notify any 12043 * listeners that the package has been installed. For cleaning up a failed 12044 * installation, the broadcast is not necessary since the package's 12045 * installation wouldn't have sent the initial broadcast either 12046 * The key steps in deleting a package are 12047 * deleting the package information in internal structures like mPackages, 12048 * deleting the packages base directories through installd 12049 * updating mSettings to reflect current status 12050 * persisting settings for later use 12051 * sending a broadcast if necessary 12052 */ 12053 private int deletePackageX(String packageName, int userId, int flags) { 12054 final PackageRemovedInfo info = new PackageRemovedInfo(); 12055 final boolean res; 12056 12057 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12058 ? UserHandle.ALL : new UserHandle(userId); 12059 12060 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12061 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12062 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12063 } 12064 12065 boolean removedForAllUsers = false; 12066 boolean systemUpdate = false; 12067 12068 // for the uninstall-updates case and restricted profiles, remember the per- 12069 // userhandle installed state 12070 int[] allUsers; 12071 boolean[] perUserInstalled; 12072 synchronized (mPackages) { 12073 PackageSetting ps = mSettings.mPackages.get(packageName); 12074 allUsers = sUserManager.getUserIds(); 12075 perUserInstalled = new boolean[allUsers.length]; 12076 for (int i = 0; i < allUsers.length; i++) { 12077 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12078 } 12079 } 12080 12081 synchronized (mInstallLock) { 12082 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12083 res = deletePackageLI(packageName, removeForUser, 12084 true, allUsers, perUserInstalled, 12085 flags | REMOVE_CHATTY, info, true); 12086 systemUpdate = info.isRemovedPackageSystemUpdate; 12087 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12088 removedForAllUsers = true; 12089 } 12090 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12091 + " removedForAllUsers=" + removedForAllUsers); 12092 } 12093 12094 if (res) { 12095 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12096 12097 // If the removed package was a system update, the old system package 12098 // was re-enabled; we need to broadcast this information 12099 if (systemUpdate) { 12100 Bundle extras = new Bundle(1); 12101 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12102 ? info.removedAppId : info.uid); 12103 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12104 12105 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12106 extras, null, null, null); 12107 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12108 extras, null, null, null); 12109 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12110 null, packageName, null, null); 12111 } 12112 } 12113 // Force a gc here. 12114 Runtime.getRuntime().gc(); 12115 // Delete the resources here after sending the broadcast to let 12116 // other processes clean up before deleting resources. 12117 if (info.args != null) { 12118 synchronized (mInstallLock) { 12119 info.args.doPostDeleteLI(true); 12120 } 12121 } 12122 12123 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12124 } 12125 12126 class PackageRemovedInfo { 12127 String removedPackage; 12128 int uid = -1; 12129 int removedAppId = -1; 12130 int[] removedUsers = null; 12131 boolean isRemovedPackageSystemUpdate = false; 12132 // Clean up resources deleted packages. 12133 InstallArgs args = null; 12134 12135 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12136 Bundle extras = new Bundle(1); 12137 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12138 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12139 if (replacing) { 12140 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12141 } 12142 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12143 if (removedPackage != null) { 12144 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12145 extras, null, null, removedUsers); 12146 if (fullRemove && !replacing) { 12147 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12148 extras, null, null, removedUsers); 12149 } 12150 } 12151 if (removedAppId >= 0) { 12152 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12153 removedUsers); 12154 } 12155 } 12156 } 12157 12158 /* 12159 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12160 * flag is not set, the data directory is removed as well. 12161 * make sure this flag is set for partially installed apps. If not its meaningless to 12162 * delete a partially installed application. 12163 */ 12164 private void removePackageDataLI(PackageSetting ps, 12165 int[] allUserHandles, boolean[] perUserInstalled, 12166 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12167 String packageName = ps.name; 12168 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12169 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12170 // Retrieve object to delete permissions for shared user later on 12171 final PackageSetting deletedPs; 12172 // reader 12173 synchronized (mPackages) { 12174 deletedPs = mSettings.mPackages.get(packageName); 12175 if (outInfo != null) { 12176 outInfo.removedPackage = packageName; 12177 outInfo.removedUsers = deletedPs != null 12178 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12179 : null; 12180 } 12181 } 12182 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12183 removeDataDirsLI(ps.volumeUuid, packageName); 12184 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12185 } 12186 // writer 12187 synchronized (mPackages) { 12188 if (deletedPs != null) { 12189 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12190 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12191 clearDefaultBrowserIfNeeded(packageName); 12192 if (outInfo != null) { 12193 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12194 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12195 } 12196 updatePermissionsLPw(deletedPs.name, null, 0); 12197 if (deletedPs.sharedUser != null) { 12198 // Remove permissions associated with package. Since runtime 12199 // permissions are per user we have to kill the removed package 12200 // or packages running under the shared user of the removed 12201 // package if revoking the permissions requested only by the removed 12202 // package is successful and this causes a change in gids. 12203 for (int userId : UserManagerService.getInstance().getUserIds()) { 12204 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12205 userId); 12206 if (userIdToKill == UserHandle.USER_ALL 12207 || userIdToKill >= UserHandle.USER_OWNER) { 12208 // If gids changed for this user, kill all affected packages. 12209 mHandler.post(new Runnable() { 12210 @Override 12211 public void run() { 12212 // This has to happen with no lock held. 12213 killSettingPackagesForUser(deletedPs, userIdToKill, 12214 KILL_APP_REASON_GIDS_CHANGED); 12215 } 12216 }); 12217 break; 12218 } 12219 } 12220 } 12221 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12222 } 12223 // make sure to preserve per-user disabled state if this removal was just 12224 // a downgrade of a system app to the factory package 12225 if (allUserHandles != null && perUserInstalled != null) { 12226 if (DEBUG_REMOVE) { 12227 Slog.d(TAG, "Propagating install state across downgrade"); 12228 } 12229 for (int i = 0; i < allUserHandles.length; i++) { 12230 if (DEBUG_REMOVE) { 12231 Slog.d(TAG, " user " + allUserHandles[i] 12232 + " => " + perUserInstalled[i]); 12233 } 12234 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12235 } 12236 } 12237 } 12238 // can downgrade to reader 12239 if (writeSettings) { 12240 // Save settings now 12241 mSettings.writeLPr(); 12242 } 12243 } 12244 if (outInfo != null) { 12245 // A user ID was deleted here. Go through all users and remove it 12246 // from KeyStore. 12247 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12248 } 12249 } 12250 12251 static boolean locationIsPrivileged(File path) { 12252 try { 12253 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12254 .getCanonicalPath(); 12255 return path.getCanonicalPath().startsWith(privilegedAppDir); 12256 } catch (IOException e) { 12257 Slog.e(TAG, "Unable to access code path " + path); 12258 } 12259 return false; 12260 } 12261 12262 /* 12263 * Tries to delete system package. 12264 */ 12265 private boolean deleteSystemPackageLI(PackageSetting newPs, 12266 int[] allUserHandles, boolean[] perUserInstalled, 12267 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12268 final boolean applyUserRestrictions 12269 = (allUserHandles != null) && (perUserInstalled != null); 12270 PackageSetting disabledPs = null; 12271 // Confirm if the system package has been updated 12272 // An updated system app can be deleted. This will also have to restore 12273 // the system pkg from system partition 12274 // reader 12275 synchronized (mPackages) { 12276 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12277 } 12278 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12279 + " disabledPs=" + disabledPs); 12280 if (disabledPs == null) { 12281 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12282 return false; 12283 } else if (DEBUG_REMOVE) { 12284 Slog.d(TAG, "Deleting system pkg from data partition"); 12285 } 12286 if (DEBUG_REMOVE) { 12287 if (applyUserRestrictions) { 12288 Slog.d(TAG, "Remembering install states:"); 12289 for (int i = 0; i < allUserHandles.length; i++) { 12290 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12291 } 12292 } 12293 } 12294 // Delete the updated package 12295 outInfo.isRemovedPackageSystemUpdate = true; 12296 if (disabledPs.versionCode < newPs.versionCode) { 12297 // Delete data for downgrades 12298 flags &= ~PackageManager.DELETE_KEEP_DATA; 12299 } else { 12300 // Preserve data by setting flag 12301 flags |= PackageManager.DELETE_KEEP_DATA; 12302 } 12303 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12304 allUserHandles, perUserInstalled, outInfo, writeSettings); 12305 if (!ret) { 12306 return false; 12307 } 12308 // writer 12309 synchronized (mPackages) { 12310 // Reinstate the old system package 12311 mSettings.enableSystemPackageLPw(newPs.name); 12312 // Remove any native libraries from the upgraded package. 12313 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12314 } 12315 // Install the system package 12316 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12317 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12318 if (locationIsPrivileged(disabledPs.codePath)) { 12319 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12320 } 12321 12322 final PackageParser.Package newPkg; 12323 try { 12324 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12325 } catch (PackageManagerException e) { 12326 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12327 return false; 12328 } 12329 12330 // writer 12331 synchronized (mPackages) { 12332 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12333 updatePermissionsLPw(newPkg.packageName, newPkg, 12334 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12335 if (applyUserRestrictions) { 12336 if (DEBUG_REMOVE) { 12337 Slog.d(TAG, "Propagating install state across reinstall"); 12338 } 12339 for (int i = 0; i < allUserHandles.length; i++) { 12340 if (DEBUG_REMOVE) { 12341 Slog.d(TAG, " user " + allUserHandles[i] 12342 + " => " + perUserInstalled[i]); 12343 } 12344 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12345 } 12346 // Regardless of writeSettings we need to ensure that this restriction 12347 // state propagation is persisted 12348 mSettings.writeAllUsersPackageRestrictionsLPr(); 12349 } 12350 // can downgrade to reader here 12351 if (writeSettings) { 12352 mSettings.writeLPr(); 12353 } 12354 } 12355 return true; 12356 } 12357 12358 private boolean deleteInstalledPackageLI(PackageSetting ps, 12359 boolean deleteCodeAndResources, int flags, 12360 int[] allUserHandles, boolean[] perUserInstalled, 12361 PackageRemovedInfo outInfo, boolean writeSettings) { 12362 if (outInfo != null) { 12363 outInfo.uid = ps.appId; 12364 } 12365 12366 // Delete package data from internal structures and also remove data if flag is set 12367 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12368 12369 // Delete application code and resources 12370 if (deleteCodeAndResources && (outInfo != null)) { 12371 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12372 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12373 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12374 } 12375 return true; 12376 } 12377 12378 @Override 12379 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12380 int userId) { 12381 mContext.enforceCallingOrSelfPermission( 12382 android.Manifest.permission.DELETE_PACKAGES, null); 12383 synchronized (mPackages) { 12384 PackageSetting ps = mSettings.mPackages.get(packageName); 12385 if (ps == null) { 12386 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12387 return false; 12388 } 12389 if (!ps.getInstalled(userId)) { 12390 // Can't block uninstall for an app that is not installed or enabled. 12391 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12392 return false; 12393 } 12394 ps.setBlockUninstall(blockUninstall, userId); 12395 mSettings.writePackageRestrictionsLPr(userId); 12396 } 12397 return true; 12398 } 12399 12400 @Override 12401 public boolean getBlockUninstallForUser(String packageName, int userId) { 12402 synchronized (mPackages) { 12403 PackageSetting ps = mSettings.mPackages.get(packageName); 12404 if (ps == null) { 12405 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12406 return false; 12407 } 12408 return ps.getBlockUninstall(userId); 12409 } 12410 } 12411 12412 /* 12413 * This method handles package deletion in general 12414 */ 12415 private boolean deletePackageLI(String packageName, UserHandle user, 12416 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12417 int flags, PackageRemovedInfo outInfo, 12418 boolean writeSettings) { 12419 if (packageName == null) { 12420 Slog.w(TAG, "Attempt to delete null packageName."); 12421 return false; 12422 } 12423 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12424 PackageSetting ps; 12425 boolean dataOnly = false; 12426 int removeUser = -1; 12427 int appId = -1; 12428 synchronized (mPackages) { 12429 ps = mSettings.mPackages.get(packageName); 12430 if (ps == null) { 12431 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12432 return false; 12433 } 12434 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12435 && user.getIdentifier() != UserHandle.USER_ALL) { 12436 // The caller is asking that the package only be deleted for a single 12437 // user. To do this, we just mark its uninstalled state and delete 12438 // its data. If this is a system app, we only allow this to happen if 12439 // they have set the special DELETE_SYSTEM_APP which requests different 12440 // semantics than normal for uninstalling system apps. 12441 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12442 ps.setUserState(user.getIdentifier(), 12443 COMPONENT_ENABLED_STATE_DEFAULT, 12444 false, //installed 12445 true, //stopped 12446 true, //notLaunched 12447 false, //hidden 12448 null, null, null, 12449 false, // blockUninstall 12450 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12451 if (!isSystemApp(ps)) { 12452 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12453 // Other user still have this package installed, so all 12454 // we need to do is clear this user's data and save that 12455 // it is uninstalled. 12456 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12457 removeUser = user.getIdentifier(); 12458 appId = ps.appId; 12459 scheduleWritePackageRestrictionsLocked(removeUser); 12460 } else { 12461 // We need to set it back to 'installed' so the uninstall 12462 // broadcasts will be sent correctly. 12463 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12464 ps.setInstalled(true, user.getIdentifier()); 12465 } 12466 } else { 12467 // This is a system app, so we assume that the 12468 // other users still have this package installed, so all 12469 // we need to do is clear this user's data and save that 12470 // it is uninstalled. 12471 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12472 removeUser = user.getIdentifier(); 12473 appId = ps.appId; 12474 scheduleWritePackageRestrictionsLocked(removeUser); 12475 } 12476 } 12477 } 12478 12479 if (removeUser >= 0) { 12480 // From above, we determined that we are deleting this only 12481 // for a single user. Continue the work here. 12482 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12483 if (outInfo != null) { 12484 outInfo.removedPackage = packageName; 12485 outInfo.removedAppId = appId; 12486 outInfo.removedUsers = new int[] {removeUser}; 12487 } 12488 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12489 removeKeystoreDataIfNeeded(removeUser, appId); 12490 schedulePackageCleaning(packageName, removeUser, false); 12491 synchronized (mPackages) { 12492 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12493 scheduleWritePackageRestrictionsLocked(removeUser); 12494 } 12495 } 12496 return true; 12497 } 12498 12499 if (dataOnly) { 12500 // Delete application data first 12501 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12502 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12503 return true; 12504 } 12505 12506 boolean ret = false; 12507 if (isSystemApp(ps)) { 12508 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12509 // When an updated system application is deleted we delete the existing resources as well and 12510 // fall back to existing code in system partition 12511 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12512 flags, outInfo, writeSettings); 12513 } else { 12514 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12515 // Kill application pre-emptively especially for apps on sd. 12516 killApplication(packageName, ps.appId, "uninstall pkg"); 12517 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12518 allUserHandles, perUserInstalled, 12519 outInfo, writeSettings); 12520 } 12521 12522 return ret; 12523 } 12524 12525 private final class ClearStorageConnection implements ServiceConnection { 12526 IMediaContainerService mContainerService; 12527 12528 @Override 12529 public void onServiceConnected(ComponentName name, IBinder service) { 12530 synchronized (this) { 12531 mContainerService = IMediaContainerService.Stub.asInterface(service); 12532 notifyAll(); 12533 } 12534 } 12535 12536 @Override 12537 public void onServiceDisconnected(ComponentName name) { 12538 } 12539 } 12540 12541 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12542 final boolean mounted; 12543 if (Environment.isExternalStorageEmulated()) { 12544 mounted = true; 12545 } else { 12546 final String status = Environment.getExternalStorageState(); 12547 12548 mounted = status.equals(Environment.MEDIA_MOUNTED) 12549 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12550 } 12551 12552 if (!mounted) { 12553 return; 12554 } 12555 12556 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12557 int[] users; 12558 if (userId == UserHandle.USER_ALL) { 12559 users = sUserManager.getUserIds(); 12560 } else { 12561 users = new int[] { userId }; 12562 } 12563 final ClearStorageConnection conn = new ClearStorageConnection(); 12564 if (mContext.bindServiceAsUser( 12565 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12566 try { 12567 for (int curUser : users) { 12568 long timeout = SystemClock.uptimeMillis() + 5000; 12569 synchronized (conn) { 12570 long now = SystemClock.uptimeMillis(); 12571 while (conn.mContainerService == null && now < timeout) { 12572 try { 12573 conn.wait(timeout - now); 12574 } catch (InterruptedException e) { 12575 } 12576 } 12577 } 12578 if (conn.mContainerService == null) { 12579 return; 12580 } 12581 12582 final UserEnvironment userEnv = new UserEnvironment(curUser); 12583 clearDirectory(conn.mContainerService, 12584 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12585 if (allData) { 12586 clearDirectory(conn.mContainerService, 12587 userEnv.buildExternalStorageAppDataDirs(packageName)); 12588 clearDirectory(conn.mContainerService, 12589 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12590 } 12591 } 12592 } finally { 12593 mContext.unbindService(conn); 12594 } 12595 } 12596 } 12597 12598 @Override 12599 public void clearApplicationUserData(final String packageName, 12600 final IPackageDataObserver observer, final int userId) { 12601 mContext.enforceCallingOrSelfPermission( 12602 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12603 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12604 // Queue up an async operation since the package deletion may take a little while. 12605 mHandler.post(new Runnable() { 12606 public void run() { 12607 mHandler.removeCallbacks(this); 12608 final boolean succeeded; 12609 synchronized (mInstallLock) { 12610 succeeded = clearApplicationUserDataLI(packageName, userId); 12611 } 12612 clearExternalStorageDataSync(packageName, userId, true); 12613 if (succeeded) { 12614 // invoke DeviceStorageMonitor's update method to clear any notifications 12615 DeviceStorageMonitorInternal 12616 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12617 if (dsm != null) { 12618 dsm.checkMemory(); 12619 } 12620 } 12621 if(observer != null) { 12622 try { 12623 observer.onRemoveCompleted(packageName, succeeded); 12624 } catch (RemoteException e) { 12625 Log.i(TAG, "Observer no longer exists."); 12626 } 12627 } //end if observer 12628 } //end run 12629 }); 12630 } 12631 12632 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12633 if (packageName == null) { 12634 Slog.w(TAG, "Attempt to delete null packageName."); 12635 return false; 12636 } 12637 12638 // Try finding details about the requested package 12639 PackageParser.Package pkg; 12640 synchronized (mPackages) { 12641 pkg = mPackages.get(packageName); 12642 if (pkg == null) { 12643 final PackageSetting ps = mSettings.mPackages.get(packageName); 12644 if (ps != null) { 12645 pkg = ps.pkg; 12646 } 12647 } 12648 12649 if (pkg == null) { 12650 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12651 return false; 12652 } 12653 12654 PackageSetting ps = (PackageSetting) pkg.mExtras; 12655 PermissionsState permissionsState = ps.getPermissionsState(); 12656 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12657 } 12658 12659 // Always delete data directories for package, even if we found no other 12660 // record of app. This helps users recover from UID mismatches without 12661 // resorting to a full data wipe. 12662 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12663 if (retCode < 0) { 12664 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12665 return false; 12666 } 12667 12668 final int appId = pkg.applicationInfo.uid; 12669 removeKeystoreDataIfNeeded(userId, appId); 12670 12671 // Create a native library symlink only if we have native libraries 12672 // and if the native libraries are 32 bit libraries. We do not provide 12673 // this symlink for 64 bit libraries. 12674 if (pkg.applicationInfo.primaryCpuAbi != null && 12675 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12676 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12677 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12678 nativeLibPath, userId) < 0) { 12679 Slog.w(TAG, "Failed linking native library dir"); 12680 return false; 12681 } 12682 } 12683 12684 return true; 12685 } 12686 12687 12688 /** 12689 * Revokes granted runtime permissions and clears resettable flags 12690 * which are flags that can be set by a user interaction. 12691 * 12692 * @param permissionsState The permission state to reset. 12693 * @param userId The device user for which to do a reset. 12694 */ 12695 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12696 PermissionsState permissionsState, int userId) { 12697 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12698 | PackageManager.FLAG_PERMISSION_USER_FIXED 12699 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12700 12701 boolean needsWrite = false; 12702 12703 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12704 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12705 if (bp != null) { 12706 permissionsState.revokeRuntimePermission(bp, userId); 12707 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12708 needsWrite = true; 12709 } 12710 } 12711 12712 if (needsWrite) { 12713 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12714 } 12715 } 12716 12717 /** 12718 * Remove entries from the keystore daemon. Will only remove it if the 12719 * {@code appId} is valid. 12720 */ 12721 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12722 if (appId < 0) { 12723 return; 12724 } 12725 12726 final KeyStore keyStore = KeyStore.getInstance(); 12727 if (keyStore != null) { 12728 if (userId == UserHandle.USER_ALL) { 12729 for (final int individual : sUserManager.getUserIds()) { 12730 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12731 } 12732 } else { 12733 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12734 } 12735 } else { 12736 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12737 } 12738 } 12739 12740 @Override 12741 public void deleteApplicationCacheFiles(final String packageName, 12742 final IPackageDataObserver observer) { 12743 mContext.enforceCallingOrSelfPermission( 12744 android.Manifest.permission.DELETE_CACHE_FILES, null); 12745 // Queue up an async operation since the package deletion may take a little while. 12746 final int userId = UserHandle.getCallingUserId(); 12747 mHandler.post(new Runnable() { 12748 public void run() { 12749 mHandler.removeCallbacks(this); 12750 final boolean succeded; 12751 synchronized (mInstallLock) { 12752 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12753 } 12754 clearExternalStorageDataSync(packageName, userId, false); 12755 if (observer != null) { 12756 try { 12757 observer.onRemoveCompleted(packageName, succeded); 12758 } catch (RemoteException e) { 12759 Log.i(TAG, "Observer no longer exists."); 12760 } 12761 } //end if observer 12762 } //end run 12763 }); 12764 } 12765 12766 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12767 if (packageName == null) { 12768 Slog.w(TAG, "Attempt to delete null packageName."); 12769 return false; 12770 } 12771 PackageParser.Package p; 12772 synchronized (mPackages) { 12773 p = mPackages.get(packageName); 12774 } 12775 if (p == null) { 12776 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12777 return false; 12778 } 12779 final ApplicationInfo applicationInfo = p.applicationInfo; 12780 if (applicationInfo == null) { 12781 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12782 return false; 12783 } 12784 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12785 if (retCode < 0) { 12786 Slog.w(TAG, "Couldn't remove cache files for package: " 12787 + packageName + " u" + userId); 12788 return false; 12789 } 12790 return true; 12791 } 12792 12793 @Override 12794 public void getPackageSizeInfo(final String packageName, int userHandle, 12795 final IPackageStatsObserver observer) { 12796 mContext.enforceCallingOrSelfPermission( 12797 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12798 if (packageName == null) { 12799 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12800 } 12801 12802 PackageStats stats = new PackageStats(packageName, userHandle); 12803 12804 /* 12805 * Queue up an async operation since the package measurement may take a 12806 * little while. 12807 */ 12808 Message msg = mHandler.obtainMessage(INIT_COPY); 12809 msg.obj = new MeasureParams(stats, observer); 12810 mHandler.sendMessage(msg); 12811 } 12812 12813 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12814 PackageStats pStats) { 12815 if (packageName == null) { 12816 Slog.w(TAG, "Attempt to get size of null packageName."); 12817 return false; 12818 } 12819 PackageParser.Package p; 12820 boolean dataOnly = false; 12821 String libDirRoot = null; 12822 String asecPath = null; 12823 PackageSetting ps = null; 12824 synchronized (mPackages) { 12825 p = mPackages.get(packageName); 12826 ps = mSettings.mPackages.get(packageName); 12827 if(p == null) { 12828 dataOnly = true; 12829 if((ps == null) || (ps.pkg == null)) { 12830 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12831 return false; 12832 } 12833 p = ps.pkg; 12834 } 12835 if (ps != null) { 12836 libDirRoot = ps.legacyNativeLibraryPathString; 12837 } 12838 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12839 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12840 if (secureContainerId != null) { 12841 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12842 } 12843 } 12844 } 12845 String publicSrcDir = null; 12846 if(!dataOnly) { 12847 final ApplicationInfo applicationInfo = p.applicationInfo; 12848 if (applicationInfo == null) { 12849 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12850 return false; 12851 } 12852 if (p.isForwardLocked()) { 12853 publicSrcDir = applicationInfo.getBaseResourcePath(); 12854 } 12855 } 12856 // TODO: extend to measure size of split APKs 12857 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12858 // not just the first level. 12859 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12860 // just the primary. 12861 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12862 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12863 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12864 if (res < 0) { 12865 return false; 12866 } 12867 12868 // Fix-up for forward-locked applications in ASEC containers. 12869 if (!isExternal(p)) { 12870 pStats.codeSize += pStats.externalCodeSize; 12871 pStats.externalCodeSize = 0L; 12872 } 12873 12874 return true; 12875 } 12876 12877 12878 @Override 12879 public void addPackageToPreferred(String packageName) { 12880 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12881 } 12882 12883 @Override 12884 public void removePackageFromPreferred(String packageName) { 12885 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12886 } 12887 12888 @Override 12889 public List<PackageInfo> getPreferredPackages(int flags) { 12890 return new ArrayList<PackageInfo>(); 12891 } 12892 12893 private int getUidTargetSdkVersionLockedLPr(int uid) { 12894 Object obj = mSettings.getUserIdLPr(uid); 12895 if (obj instanceof SharedUserSetting) { 12896 final SharedUserSetting sus = (SharedUserSetting) obj; 12897 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12898 final Iterator<PackageSetting> it = sus.packages.iterator(); 12899 while (it.hasNext()) { 12900 final PackageSetting ps = it.next(); 12901 if (ps.pkg != null) { 12902 int v = ps.pkg.applicationInfo.targetSdkVersion; 12903 if (v < vers) vers = v; 12904 } 12905 } 12906 return vers; 12907 } else if (obj instanceof PackageSetting) { 12908 final PackageSetting ps = (PackageSetting) obj; 12909 if (ps.pkg != null) { 12910 return ps.pkg.applicationInfo.targetSdkVersion; 12911 } 12912 } 12913 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12914 } 12915 12916 @Override 12917 public void addPreferredActivity(IntentFilter filter, int match, 12918 ComponentName[] set, ComponentName activity, int userId) { 12919 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12920 "Adding preferred"); 12921 } 12922 12923 private void addPreferredActivityInternal(IntentFilter filter, int match, 12924 ComponentName[] set, ComponentName activity, boolean always, int userId, 12925 String opname) { 12926 // writer 12927 int callingUid = Binder.getCallingUid(); 12928 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12929 if (filter.countActions() == 0) { 12930 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12931 return; 12932 } 12933 synchronized (mPackages) { 12934 if (mContext.checkCallingOrSelfPermission( 12935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12936 != PackageManager.PERMISSION_GRANTED) { 12937 if (getUidTargetSdkVersionLockedLPr(callingUid) 12938 < Build.VERSION_CODES.FROYO) { 12939 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12940 + callingUid); 12941 return; 12942 } 12943 mContext.enforceCallingOrSelfPermission( 12944 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12945 } 12946 12947 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12948 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12949 + userId + ":"); 12950 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12951 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12952 scheduleWritePackageRestrictionsLocked(userId); 12953 } 12954 } 12955 12956 @Override 12957 public void replacePreferredActivity(IntentFilter filter, int match, 12958 ComponentName[] set, ComponentName activity, int userId) { 12959 if (filter.countActions() != 1) { 12960 throw new IllegalArgumentException( 12961 "replacePreferredActivity expects filter to have only 1 action."); 12962 } 12963 if (filter.countDataAuthorities() != 0 12964 || filter.countDataPaths() != 0 12965 || filter.countDataSchemes() > 1 12966 || filter.countDataTypes() != 0) { 12967 throw new IllegalArgumentException( 12968 "replacePreferredActivity expects filter to have no data authorities, " + 12969 "paths, or types; and at most one scheme."); 12970 } 12971 12972 final int callingUid = Binder.getCallingUid(); 12973 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12974 synchronized (mPackages) { 12975 if (mContext.checkCallingOrSelfPermission( 12976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12977 != PackageManager.PERMISSION_GRANTED) { 12978 if (getUidTargetSdkVersionLockedLPr(callingUid) 12979 < Build.VERSION_CODES.FROYO) { 12980 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12981 + Binder.getCallingUid()); 12982 return; 12983 } 12984 mContext.enforceCallingOrSelfPermission( 12985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12986 } 12987 12988 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12989 if (pir != null) { 12990 // Get all of the existing entries that exactly match this filter. 12991 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12992 if (existing != null && existing.size() == 1) { 12993 PreferredActivity cur = existing.get(0); 12994 if (DEBUG_PREFERRED) { 12995 Slog.i(TAG, "Checking replace of preferred:"); 12996 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12997 if (!cur.mPref.mAlways) { 12998 Slog.i(TAG, " -- CUR; not mAlways!"); 12999 } else { 13000 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13001 Slog.i(TAG, " -- CUR: mSet=" 13002 + Arrays.toString(cur.mPref.mSetComponents)); 13003 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13004 Slog.i(TAG, " -- NEW: mMatch=" 13005 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13006 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13007 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13008 } 13009 } 13010 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13011 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13012 && cur.mPref.sameSet(set)) { 13013 // Setting the preferred activity to what it happens to be already 13014 if (DEBUG_PREFERRED) { 13015 Slog.i(TAG, "Replacing with same preferred activity " 13016 + cur.mPref.mShortComponent + " for user " 13017 + userId + ":"); 13018 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13019 } 13020 return; 13021 } 13022 } 13023 13024 if (existing != null) { 13025 if (DEBUG_PREFERRED) { 13026 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13027 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13028 } 13029 for (int i = 0; i < existing.size(); i++) { 13030 PreferredActivity pa = existing.get(i); 13031 if (DEBUG_PREFERRED) { 13032 Slog.i(TAG, "Removing existing preferred activity " 13033 + pa.mPref.mComponent + ":"); 13034 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13035 } 13036 pir.removeFilter(pa); 13037 } 13038 } 13039 } 13040 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13041 "Replacing preferred"); 13042 } 13043 } 13044 13045 @Override 13046 public void clearPackagePreferredActivities(String packageName) { 13047 final int uid = Binder.getCallingUid(); 13048 // writer 13049 synchronized (mPackages) { 13050 PackageParser.Package pkg = mPackages.get(packageName); 13051 if (pkg == null || pkg.applicationInfo.uid != uid) { 13052 if (mContext.checkCallingOrSelfPermission( 13053 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13054 != PackageManager.PERMISSION_GRANTED) { 13055 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13056 < Build.VERSION_CODES.FROYO) { 13057 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13058 + Binder.getCallingUid()); 13059 return; 13060 } 13061 mContext.enforceCallingOrSelfPermission( 13062 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13063 } 13064 } 13065 13066 int user = UserHandle.getCallingUserId(); 13067 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13068 scheduleWritePackageRestrictionsLocked(user); 13069 } 13070 } 13071 } 13072 13073 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13074 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13075 ArrayList<PreferredActivity> removed = null; 13076 boolean changed = false; 13077 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13078 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13079 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13080 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13081 continue; 13082 } 13083 Iterator<PreferredActivity> it = pir.filterIterator(); 13084 while (it.hasNext()) { 13085 PreferredActivity pa = it.next(); 13086 // Mark entry for removal only if it matches the package name 13087 // and the entry is of type "always". 13088 if (packageName == null || 13089 (pa.mPref.mComponent.getPackageName().equals(packageName) 13090 && pa.mPref.mAlways)) { 13091 if (removed == null) { 13092 removed = new ArrayList<PreferredActivity>(); 13093 } 13094 removed.add(pa); 13095 } 13096 } 13097 if (removed != null) { 13098 for (int j=0; j<removed.size(); j++) { 13099 PreferredActivity pa = removed.get(j); 13100 pir.removeFilter(pa); 13101 } 13102 changed = true; 13103 } 13104 } 13105 return changed; 13106 } 13107 13108 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13109 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13110 if (userId == UserHandle.USER_ALL) { 13111 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13112 sUserManager.getUserIds())) { 13113 for (int oneUserId : sUserManager.getUserIds()) { 13114 scheduleWritePackageRestrictionsLocked(oneUserId); 13115 } 13116 } 13117 } else { 13118 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13119 scheduleWritePackageRestrictionsLocked(userId); 13120 } 13121 } 13122 } 13123 13124 13125 void clearDefaultBrowserIfNeeded(String packageName) { 13126 for (int oneUserId : sUserManager.getUserIds()) { 13127 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13128 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13129 if (packageName.equals(defaultBrowserPackageName)) { 13130 setDefaultBrowserPackageName(null, oneUserId); 13131 } 13132 } 13133 } 13134 13135 @Override 13136 public void resetPreferredActivities(int userId) { 13137 /* TODO: Actually use userId. Why is it being passed in? */ 13138 mContext.enforceCallingOrSelfPermission( 13139 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13140 // writer 13141 synchronized (mPackages) { 13142 int user = UserHandle.getCallingUserId(); 13143 clearPackagePreferredActivitiesLPw(null, user); 13144 mSettings.readDefaultPreferredAppsLPw(this, user); 13145 scheduleWritePackageRestrictionsLocked(user); 13146 } 13147 } 13148 13149 @Override 13150 public int getPreferredActivities(List<IntentFilter> outFilters, 13151 List<ComponentName> outActivities, String packageName) { 13152 13153 int num = 0; 13154 final int userId = UserHandle.getCallingUserId(); 13155 // reader 13156 synchronized (mPackages) { 13157 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13158 if (pir != null) { 13159 final Iterator<PreferredActivity> it = pir.filterIterator(); 13160 while (it.hasNext()) { 13161 final PreferredActivity pa = it.next(); 13162 if (packageName == null 13163 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13164 && pa.mPref.mAlways)) { 13165 if (outFilters != null) { 13166 outFilters.add(new IntentFilter(pa)); 13167 } 13168 if (outActivities != null) { 13169 outActivities.add(pa.mPref.mComponent); 13170 } 13171 } 13172 } 13173 } 13174 } 13175 13176 return num; 13177 } 13178 13179 @Override 13180 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13181 int userId) { 13182 int callingUid = Binder.getCallingUid(); 13183 if (callingUid != Process.SYSTEM_UID) { 13184 throw new SecurityException( 13185 "addPersistentPreferredActivity can only be run by the system"); 13186 } 13187 if (filter.countActions() == 0) { 13188 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13189 return; 13190 } 13191 synchronized (mPackages) { 13192 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13193 " :"); 13194 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13195 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13196 new PersistentPreferredActivity(filter, activity)); 13197 scheduleWritePackageRestrictionsLocked(userId); 13198 } 13199 } 13200 13201 @Override 13202 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13203 int callingUid = Binder.getCallingUid(); 13204 if (callingUid != Process.SYSTEM_UID) { 13205 throw new SecurityException( 13206 "clearPackagePersistentPreferredActivities can only be run by the system"); 13207 } 13208 ArrayList<PersistentPreferredActivity> removed = null; 13209 boolean changed = false; 13210 synchronized (mPackages) { 13211 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13212 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13213 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13214 .valueAt(i); 13215 if (userId != thisUserId) { 13216 continue; 13217 } 13218 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13219 while (it.hasNext()) { 13220 PersistentPreferredActivity ppa = it.next(); 13221 // Mark entry for removal only if it matches the package name. 13222 if (ppa.mComponent.getPackageName().equals(packageName)) { 13223 if (removed == null) { 13224 removed = new ArrayList<PersistentPreferredActivity>(); 13225 } 13226 removed.add(ppa); 13227 } 13228 } 13229 if (removed != null) { 13230 for (int j=0; j<removed.size(); j++) { 13231 PersistentPreferredActivity ppa = removed.get(j); 13232 ppir.removeFilter(ppa); 13233 } 13234 changed = true; 13235 } 13236 } 13237 13238 if (changed) { 13239 scheduleWritePackageRestrictionsLocked(userId); 13240 } 13241 } 13242 } 13243 13244 /** 13245 * Non-Binder method, support for the backup/restore mechanism: write the 13246 * full set of preferred activities in its canonical XML format. Returns true 13247 * on success; false otherwise. 13248 */ 13249 @Override 13250 public byte[] getPreferredActivityBackup(int userId) { 13251 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13252 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13253 } 13254 13255 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13256 try { 13257 final XmlSerializer serializer = new FastXmlSerializer(); 13258 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13259 serializer.startDocument(null, true); 13260 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13261 13262 synchronized (mPackages) { 13263 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13264 } 13265 13266 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13267 serializer.endDocument(); 13268 serializer.flush(); 13269 } catch (Exception e) { 13270 if (DEBUG_BACKUP) { 13271 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13272 } 13273 return null; 13274 } 13275 13276 return dataStream.toByteArray(); 13277 } 13278 13279 @Override 13280 public void restorePreferredActivities(byte[] backup, int userId) { 13281 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13282 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13283 } 13284 13285 try { 13286 final XmlPullParser parser = Xml.newPullParser(); 13287 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13288 13289 int type; 13290 while ((type = parser.next()) != XmlPullParser.START_TAG 13291 && type != XmlPullParser.END_DOCUMENT) { 13292 } 13293 if (type != XmlPullParser.START_TAG) { 13294 // oops didn't find a start tag?! 13295 if (DEBUG_BACKUP) { 13296 Slog.e(TAG, "Didn't find start tag during restore"); 13297 } 13298 return; 13299 } 13300 13301 // this is supposed to be TAG_PREFERRED_BACKUP 13302 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13303 if (DEBUG_BACKUP) { 13304 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13305 } 13306 return; 13307 } 13308 13309 // skip interfering stuff, then we're aligned with the backing implementation 13310 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13311 synchronized (mPackages) { 13312 mSettings.readPreferredActivitiesLPw(parser, userId); 13313 } 13314 } catch (Exception e) { 13315 if (DEBUG_BACKUP) { 13316 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13317 } 13318 } 13319 } 13320 13321 @Override 13322 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13323 int sourceUserId, int targetUserId, int flags) { 13324 mContext.enforceCallingOrSelfPermission( 13325 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13326 int callingUid = Binder.getCallingUid(); 13327 enforceOwnerRights(ownerPackage, callingUid); 13328 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13329 if (intentFilter.countActions() == 0) { 13330 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13331 return; 13332 } 13333 synchronized (mPackages) { 13334 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13335 ownerPackage, targetUserId, flags); 13336 CrossProfileIntentResolver resolver = 13337 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13338 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13339 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13340 if (existing != null) { 13341 int size = existing.size(); 13342 for (int i = 0; i < size; i++) { 13343 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13344 return; 13345 } 13346 } 13347 } 13348 resolver.addFilter(newFilter); 13349 scheduleWritePackageRestrictionsLocked(sourceUserId); 13350 } 13351 } 13352 13353 @Override 13354 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13355 mContext.enforceCallingOrSelfPermission( 13356 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13357 int callingUid = Binder.getCallingUid(); 13358 enforceOwnerRights(ownerPackage, callingUid); 13359 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13360 synchronized (mPackages) { 13361 CrossProfileIntentResolver resolver = 13362 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13363 ArraySet<CrossProfileIntentFilter> set = 13364 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13365 for (CrossProfileIntentFilter filter : set) { 13366 if (filter.getOwnerPackage().equals(ownerPackage)) { 13367 resolver.removeFilter(filter); 13368 } 13369 } 13370 scheduleWritePackageRestrictionsLocked(sourceUserId); 13371 } 13372 } 13373 13374 // Enforcing that callingUid is owning pkg on userId 13375 private void enforceOwnerRights(String pkg, int callingUid) { 13376 // The system owns everything. 13377 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13378 return; 13379 } 13380 int callingUserId = UserHandle.getUserId(callingUid); 13381 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13382 if (pi == null) { 13383 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13384 + callingUserId); 13385 } 13386 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13387 throw new SecurityException("Calling uid " + callingUid 13388 + " does not own package " + pkg); 13389 } 13390 } 13391 13392 @Override 13393 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13394 Intent intent = new Intent(Intent.ACTION_MAIN); 13395 intent.addCategory(Intent.CATEGORY_HOME); 13396 13397 final int callingUserId = UserHandle.getCallingUserId(); 13398 List<ResolveInfo> list = queryIntentActivities(intent, null, 13399 PackageManager.GET_META_DATA, callingUserId); 13400 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13401 true, false, false, callingUserId); 13402 13403 allHomeCandidates.clear(); 13404 if (list != null) { 13405 for (ResolveInfo ri : list) { 13406 allHomeCandidates.add(ri); 13407 } 13408 } 13409 return (preferred == null || preferred.activityInfo == null) 13410 ? null 13411 : new ComponentName(preferred.activityInfo.packageName, 13412 preferred.activityInfo.name); 13413 } 13414 13415 @Override 13416 public void setApplicationEnabledSetting(String appPackageName, 13417 int newState, int flags, int userId, String callingPackage) { 13418 if (!sUserManager.exists(userId)) return; 13419 if (callingPackage == null) { 13420 callingPackage = Integer.toString(Binder.getCallingUid()); 13421 } 13422 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13423 } 13424 13425 @Override 13426 public void setComponentEnabledSetting(ComponentName componentName, 13427 int newState, int flags, int userId) { 13428 if (!sUserManager.exists(userId)) return; 13429 setEnabledSetting(componentName.getPackageName(), 13430 componentName.getClassName(), newState, flags, userId, null); 13431 } 13432 13433 private void setEnabledSetting(final String packageName, String className, int newState, 13434 final int flags, int userId, String callingPackage) { 13435 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13436 || newState == COMPONENT_ENABLED_STATE_ENABLED 13437 || newState == COMPONENT_ENABLED_STATE_DISABLED 13438 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13439 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13440 throw new IllegalArgumentException("Invalid new component state: " 13441 + newState); 13442 } 13443 PackageSetting pkgSetting; 13444 final int uid = Binder.getCallingUid(); 13445 final int permission = mContext.checkCallingOrSelfPermission( 13446 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13447 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13448 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13449 boolean sendNow = false; 13450 boolean isApp = (className == null); 13451 String componentName = isApp ? packageName : className; 13452 int packageUid = -1; 13453 ArrayList<String> components; 13454 13455 // writer 13456 synchronized (mPackages) { 13457 pkgSetting = mSettings.mPackages.get(packageName); 13458 if (pkgSetting == null) { 13459 if (className == null) { 13460 throw new IllegalArgumentException( 13461 "Unknown package: " + packageName); 13462 } 13463 throw new IllegalArgumentException( 13464 "Unknown component: " + packageName 13465 + "/" + className); 13466 } 13467 // Allow root and verify that userId is not being specified by a different user 13468 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13469 throw new SecurityException( 13470 "Permission Denial: attempt to change component state from pid=" 13471 + Binder.getCallingPid() 13472 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13473 } 13474 if (className == null) { 13475 // We're dealing with an application/package level state change 13476 if (pkgSetting.getEnabled(userId) == newState) { 13477 // Nothing to do 13478 return; 13479 } 13480 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13481 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13482 // Don't care about who enables an app. 13483 callingPackage = null; 13484 } 13485 pkgSetting.setEnabled(newState, userId, callingPackage); 13486 // pkgSetting.pkg.mSetEnabled = newState; 13487 } else { 13488 // We're dealing with a component level state change 13489 // First, verify that this is a valid class name. 13490 PackageParser.Package pkg = pkgSetting.pkg; 13491 if (pkg == null || !pkg.hasComponentClassName(className)) { 13492 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13493 throw new IllegalArgumentException("Component class " + className 13494 + " does not exist in " + packageName); 13495 } else { 13496 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13497 + className + " does not exist in " + packageName); 13498 } 13499 } 13500 switch (newState) { 13501 case COMPONENT_ENABLED_STATE_ENABLED: 13502 if (!pkgSetting.enableComponentLPw(className, userId)) { 13503 return; 13504 } 13505 break; 13506 case COMPONENT_ENABLED_STATE_DISABLED: 13507 if (!pkgSetting.disableComponentLPw(className, userId)) { 13508 return; 13509 } 13510 break; 13511 case COMPONENT_ENABLED_STATE_DEFAULT: 13512 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13513 return; 13514 } 13515 break; 13516 default: 13517 Slog.e(TAG, "Invalid new component state: " + newState); 13518 return; 13519 } 13520 } 13521 scheduleWritePackageRestrictionsLocked(userId); 13522 components = mPendingBroadcasts.get(userId, packageName); 13523 final boolean newPackage = components == null; 13524 if (newPackage) { 13525 components = new ArrayList<String>(); 13526 } 13527 if (!components.contains(componentName)) { 13528 components.add(componentName); 13529 } 13530 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13531 sendNow = true; 13532 // Purge entry from pending broadcast list if another one exists already 13533 // since we are sending one right away. 13534 mPendingBroadcasts.remove(userId, packageName); 13535 } else { 13536 if (newPackage) { 13537 mPendingBroadcasts.put(userId, packageName, components); 13538 } 13539 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13540 // Schedule a message 13541 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13542 } 13543 } 13544 } 13545 13546 long callingId = Binder.clearCallingIdentity(); 13547 try { 13548 if (sendNow) { 13549 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13550 sendPackageChangedBroadcast(packageName, 13551 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13552 } 13553 } finally { 13554 Binder.restoreCallingIdentity(callingId); 13555 } 13556 } 13557 13558 private void sendPackageChangedBroadcast(String packageName, 13559 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13560 if (DEBUG_INSTALL) 13561 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13562 + componentNames); 13563 Bundle extras = new Bundle(4); 13564 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13565 String nameList[] = new String[componentNames.size()]; 13566 componentNames.toArray(nameList); 13567 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13568 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13569 extras.putInt(Intent.EXTRA_UID, packageUid); 13570 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13571 new int[] {UserHandle.getUserId(packageUid)}); 13572 } 13573 13574 @Override 13575 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13576 if (!sUserManager.exists(userId)) return; 13577 final int uid = Binder.getCallingUid(); 13578 final int permission = mContext.checkCallingOrSelfPermission( 13579 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13580 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13581 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13582 // writer 13583 synchronized (mPackages) { 13584 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13585 allowedByPermission, uid, userId)) { 13586 scheduleWritePackageRestrictionsLocked(userId); 13587 } 13588 } 13589 } 13590 13591 @Override 13592 public String getInstallerPackageName(String packageName) { 13593 // reader 13594 synchronized (mPackages) { 13595 return mSettings.getInstallerPackageNameLPr(packageName); 13596 } 13597 } 13598 13599 @Override 13600 public int getApplicationEnabledSetting(String packageName, int userId) { 13601 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13602 int uid = Binder.getCallingUid(); 13603 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13604 // reader 13605 synchronized (mPackages) { 13606 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13607 } 13608 } 13609 13610 @Override 13611 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13612 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13613 int uid = Binder.getCallingUid(); 13614 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13615 // reader 13616 synchronized (mPackages) { 13617 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13618 } 13619 } 13620 13621 @Override 13622 public void enterSafeMode() { 13623 enforceSystemOrRoot("Only the system can request entering safe mode"); 13624 13625 if (!mSystemReady) { 13626 mSafeMode = true; 13627 } 13628 } 13629 13630 @Override 13631 public void systemReady() { 13632 mSystemReady = true; 13633 13634 // Read the compatibilty setting when the system is ready. 13635 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13636 mContext.getContentResolver(), 13637 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13638 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13639 if (DEBUG_SETTINGS) { 13640 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13641 } 13642 13643 synchronized (mPackages) { 13644 // Verify that all of the preferred activity components actually 13645 // exist. It is possible for applications to be updated and at 13646 // that point remove a previously declared activity component that 13647 // had been set as a preferred activity. We try to clean this up 13648 // the next time we encounter that preferred activity, but it is 13649 // possible for the user flow to never be able to return to that 13650 // situation so here we do a sanity check to make sure we haven't 13651 // left any junk around. 13652 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13653 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13654 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13655 removed.clear(); 13656 for (PreferredActivity pa : pir.filterSet()) { 13657 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13658 removed.add(pa); 13659 } 13660 } 13661 if (removed.size() > 0) { 13662 for (int r=0; r<removed.size(); r++) { 13663 PreferredActivity pa = removed.get(r); 13664 Slog.w(TAG, "Removing dangling preferred activity: " 13665 + pa.mPref.mComponent); 13666 pir.removeFilter(pa); 13667 } 13668 mSettings.writePackageRestrictionsLPr( 13669 mSettings.mPreferredActivities.keyAt(i)); 13670 } 13671 } 13672 } 13673 sUserManager.systemReady(); 13674 13675 // Kick off any messages waiting for system ready 13676 if (mPostSystemReadyMessages != null) { 13677 for (Message msg : mPostSystemReadyMessages) { 13678 msg.sendToTarget(); 13679 } 13680 mPostSystemReadyMessages = null; 13681 } 13682 13683 // Watch for external volumes that come and go over time 13684 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13685 storage.registerListener(mStorageListener); 13686 13687 mInstallerService.systemReady(); 13688 mPackageDexOptimizer.systemReady(); 13689 } 13690 13691 @Override 13692 public boolean isSafeMode() { 13693 return mSafeMode; 13694 } 13695 13696 @Override 13697 public boolean hasSystemUidErrors() { 13698 return mHasSystemUidErrors; 13699 } 13700 13701 static String arrayToString(int[] array) { 13702 StringBuffer buf = new StringBuffer(128); 13703 buf.append('['); 13704 if (array != null) { 13705 for (int i=0; i<array.length; i++) { 13706 if (i > 0) buf.append(", "); 13707 buf.append(array[i]); 13708 } 13709 } 13710 buf.append(']'); 13711 return buf.toString(); 13712 } 13713 13714 static class DumpState { 13715 public static final int DUMP_LIBS = 1 << 0; 13716 public static final int DUMP_FEATURES = 1 << 1; 13717 public static final int DUMP_RESOLVERS = 1 << 2; 13718 public static final int DUMP_PERMISSIONS = 1 << 3; 13719 public static final int DUMP_PACKAGES = 1 << 4; 13720 public static final int DUMP_SHARED_USERS = 1 << 5; 13721 public static final int DUMP_MESSAGES = 1 << 6; 13722 public static final int DUMP_PROVIDERS = 1 << 7; 13723 public static final int DUMP_VERIFIERS = 1 << 8; 13724 public static final int DUMP_PREFERRED = 1 << 9; 13725 public static final int DUMP_PREFERRED_XML = 1 << 10; 13726 public static final int DUMP_KEYSETS = 1 << 11; 13727 public static final int DUMP_VERSION = 1 << 12; 13728 public static final int DUMP_INSTALLS = 1 << 13; 13729 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13730 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13731 13732 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13733 13734 private int mTypes; 13735 13736 private int mOptions; 13737 13738 private boolean mTitlePrinted; 13739 13740 private SharedUserSetting mSharedUser; 13741 13742 public boolean isDumping(int type) { 13743 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13744 return true; 13745 } 13746 13747 return (mTypes & type) != 0; 13748 } 13749 13750 public void setDump(int type) { 13751 mTypes |= type; 13752 } 13753 13754 public boolean isOptionEnabled(int option) { 13755 return (mOptions & option) != 0; 13756 } 13757 13758 public void setOptionEnabled(int option) { 13759 mOptions |= option; 13760 } 13761 13762 public boolean onTitlePrinted() { 13763 final boolean printed = mTitlePrinted; 13764 mTitlePrinted = true; 13765 return printed; 13766 } 13767 13768 public boolean getTitlePrinted() { 13769 return mTitlePrinted; 13770 } 13771 13772 public void setTitlePrinted(boolean enabled) { 13773 mTitlePrinted = enabled; 13774 } 13775 13776 public SharedUserSetting getSharedUser() { 13777 return mSharedUser; 13778 } 13779 13780 public void setSharedUser(SharedUserSetting user) { 13781 mSharedUser = user; 13782 } 13783 } 13784 13785 @Override 13786 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13787 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13788 != PackageManager.PERMISSION_GRANTED) { 13789 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13790 + Binder.getCallingPid() 13791 + ", uid=" + Binder.getCallingUid() 13792 + " without permission " 13793 + android.Manifest.permission.DUMP); 13794 return; 13795 } 13796 13797 DumpState dumpState = new DumpState(); 13798 boolean fullPreferred = false; 13799 boolean checkin = false; 13800 13801 String packageName = null; 13802 13803 int opti = 0; 13804 while (opti < args.length) { 13805 String opt = args[opti]; 13806 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13807 break; 13808 } 13809 opti++; 13810 13811 if ("-a".equals(opt)) { 13812 // Right now we only know how to print all. 13813 } else if ("-h".equals(opt)) { 13814 pw.println("Package manager dump options:"); 13815 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13816 pw.println(" --checkin: dump for a checkin"); 13817 pw.println(" -f: print details of intent filters"); 13818 pw.println(" -h: print this help"); 13819 pw.println(" cmd may be one of:"); 13820 pw.println(" l[ibraries]: list known shared libraries"); 13821 pw.println(" f[ibraries]: list device features"); 13822 pw.println(" k[eysets]: print known keysets"); 13823 pw.println(" r[esolvers]: dump intent resolvers"); 13824 pw.println(" perm[issions]: dump permissions"); 13825 pw.println(" pref[erred]: print preferred package settings"); 13826 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13827 pw.println(" prov[iders]: dump content providers"); 13828 pw.println(" p[ackages]: dump installed packages"); 13829 pw.println(" s[hared-users]: dump shared user IDs"); 13830 pw.println(" m[essages]: print collected runtime messages"); 13831 pw.println(" v[erifiers]: print package verifier info"); 13832 pw.println(" version: print database version info"); 13833 pw.println(" write: write current settings now"); 13834 pw.println(" <package.name>: info about given package"); 13835 pw.println(" installs: details about install sessions"); 13836 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13837 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13838 return; 13839 } else if ("--checkin".equals(opt)) { 13840 checkin = true; 13841 } else if ("-f".equals(opt)) { 13842 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13843 } else { 13844 pw.println("Unknown argument: " + opt + "; use -h for help"); 13845 } 13846 } 13847 13848 // Is the caller requesting to dump a particular piece of data? 13849 if (opti < args.length) { 13850 String cmd = args[opti]; 13851 opti++; 13852 // Is this a package name? 13853 if ("android".equals(cmd) || cmd.contains(".")) { 13854 packageName = cmd; 13855 // When dumping a single package, we always dump all of its 13856 // filter information since the amount of data will be reasonable. 13857 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13858 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13859 dumpState.setDump(DumpState.DUMP_LIBS); 13860 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13861 dumpState.setDump(DumpState.DUMP_FEATURES); 13862 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13863 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13864 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13865 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13866 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13867 dumpState.setDump(DumpState.DUMP_PREFERRED); 13868 } else if ("preferred-xml".equals(cmd)) { 13869 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13870 if (opti < args.length && "--full".equals(args[opti])) { 13871 fullPreferred = true; 13872 opti++; 13873 } 13874 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13875 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13876 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13877 dumpState.setDump(DumpState.DUMP_PACKAGES); 13878 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13879 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13880 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13881 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13882 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13883 dumpState.setDump(DumpState.DUMP_MESSAGES); 13884 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13885 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13886 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13887 || "intent-filter-verifiers".equals(cmd)) { 13888 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13889 } else if ("version".equals(cmd)) { 13890 dumpState.setDump(DumpState.DUMP_VERSION); 13891 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13892 dumpState.setDump(DumpState.DUMP_KEYSETS); 13893 } else if ("installs".equals(cmd)) { 13894 dumpState.setDump(DumpState.DUMP_INSTALLS); 13895 } else if ("write".equals(cmd)) { 13896 synchronized (mPackages) { 13897 mSettings.writeLPr(); 13898 pw.println("Settings written."); 13899 return; 13900 } 13901 } 13902 } 13903 13904 if (checkin) { 13905 pw.println("vers,1"); 13906 } 13907 13908 // reader 13909 synchronized (mPackages) { 13910 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13911 if (!checkin) { 13912 if (dumpState.onTitlePrinted()) 13913 pw.println(); 13914 pw.println("Database versions:"); 13915 pw.print(" SDK Version:"); 13916 pw.print(" internal="); 13917 pw.print(mSettings.mInternalSdkPlatform); 13918 pw.print(" external="); 13919 pw.println(mSettings.mExternalSdkPlatform); 13920 pw.print(" DB Version:"); 13921 pw.print(" internal="); 13922 pw.print(mSettings.mInternalDatabaseVersion); 13923 pw.print(" external="); 13924 pw.println(mSettings.mExternalDatabaseVersion); 13925 } 13926 } 13927 13928 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13929 if (!checkin) { 13930 if (dumpState.onTitlePrinted()) 13931 pw.println(); 13932 pw.println("Verifiers:"); 13933 pw.print(" Required: "); 13934 pw.print(mRequiredVerifierPackage); 13935 pw.print(" (uid="); 13936 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13937 pw.println(")"); 13938 } else if (mRequiredVerifierPackage != null) { 13939 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13940 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13941 } 13942 } 13943 13944 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13945 packageName == null) { 13946 if (mIntentFilterVerifierComponent != null) { 13947 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13948 if (!checkin) { 13949 if (dumpState.onTitlePrinted()) 13950 pw.println(); 13951 pw.println("Intent Filter Verifier:"); 13952 pw.print(" Using: "); 13953 pw.print(verifierPackageName); 13954 pw.print(" (uid="); 13955 pw.print(getPackageUid(verifierPackageName, 0)); 13956 pw.println(")"); 13957 } else if (verifierPackageName != null) { 13958 pw.print("ifv,"); pw.print(verifierPackageName); 13959 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13960 } 13961 } else { 13962 pw.println(); 13963 pw.println("No Intent Filter Verifier available!"); 13964 } 13965 } 13966 13967 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13968 boolean printedHeader = false; 13969 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13970 while (it.hasNext()) { 13971 String name = it.next(); 13972 SharedLibraryEntry ent = mSharedLibraries.get(name); 13973 if (!checkin) { 13974 if (!printedHeader) { 13975 if (dumpState.onTitlePrinted()) 13976 pw.println(); 13977 pw.println("Libraries:"); 13978 printedHeader = true; 13979 } 13980 pw.print(" "); 13981 } else { 13982 pw.print("lib,"); 13983 } 13984 pw.print(name); 13985 if (!checkin) { 13986 pw.print(" -> "); 13987 } 13988 if (ent.path != null) { 13989 if (!checkin) { 13990 pw.print("(jar) "); 13991 pw.print(ent.path); 13992 } else { 13993 pw.print(",jar,"); 13994 pw.print(ent.path); 13995 } 13996 } else { 13997 if (!checkin) { 13998 pw.print("(apk) "); 13999 pw.print(ent.apk); 14000 } else { 14001 pw.print(",apk,"); 14002 pw.print(ent.apk); 14003 } 14004 } 14005 pw.println(); 14006 } 14007 } 14008 14009 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14010 if (dumpState.onTitlePrinted()) 14011 pw.println(); 14012 if (!checkin) { 14013 pw.println("Features:"); 14014 } 14015 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14016 while (it.hasNext()) { 14017 String name = it.next(); 14018 if (!checkin) { 14019 pw.print(" "); 14020 } else { 14021 pw.print("feat,"); 14022 } 14023 pw.println(name); 14024 } 14025 } 14026 14027 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14028 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14029 : "Activity Resolver Table:", " ", packageName, 14030 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14031 dumpState.setTitlePrinted(true); 14032 } 14033 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14034 : "Receiver Resolver Table:", " ", packageName, 14035 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14036 dumpState.setTitlePrinted(true); 14037 } 14038 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14039 : "Service Resolver Table:", " ", packageName, 14040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14041 dumpState.setTitlePrinted(true); 14042 } 14043 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14044 : "Provider Resolver Table:", " ", packageName, 14045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14046 dumpState.setTitlePrinted(true); 14047 } 14048 } 14049 14050 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14051 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14052 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14053 int user = mSettings.mPreferredActivities.keyAt(i); 14054 if (pir.dump(pw, 14055 dumpState.getTitlePrinted() 14056 ? "\nPreferred Activities User " + user + ":" 14057 : "Preferred Activities User " + user + ":", " ", 14058 packageName, true, false)) { 14059 dumpState.setTitlePrinted(true); 14060 } 14061 } 14062 } 14063 14064 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14065 pw.flush(); 14066 FileOutputStream fout = new FileOutputStream(fd); 14067 BufferedOutputStream str = new BufferedOutputStream(fout); 14068 XmlSerializer serializer = new FastXmlSerializer(); 14069 try { 14070 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14071 serializer.startDocument(null, true); 14072 serializer.setFeature( 14073 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14074 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14075 serializer.endDocument(); 14076 serializer.flush(); 14077 } catch (IllegalArgumentException e) { 14078 pw.println("Failed writing: " + e); 14079 } catch (IllegalStateException e) { 14080 pw.println("Failed writing: " + e); 14081 } catch (IOException e) { 14082 pw.println("Failed writing: " + e); 14083 } 14084 } 14085 14086 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14087 pw.println(); 14088 int count = mSettings.mPackages.size(); 14089 if (count == 0) { 14090 pw.println("No domain preferred apps!"); 14091 pw.println(); 14092 } else { 14093 final String prefix = " "; 14094 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14095 if (allPackageSettings.size() == 0) { 14096 pw.println("No domain preferred apps!"); 14097 pw.println(); 14098 } else { 14099 pw.println("Domain preferred apps status:"); 14100 pw.println(); 14101 count = 0; 14102 for (PackageSetting ps : allPackageSettings) { 14103 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14104 if (ivi == null || ivi.getPackageName() == null) continue; 14105 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14106 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14107 pw.println(prefix + "Status: " + ivi.getStatusString()); 14108 pw.println(); 14109 count++; 14110 } 14111 if (count == 0) { 14112 pw.println(prefix + "No domain preferred app status!"); 14113 pw.println(); 14114 } 14115 for (int userId : sUserManager.getUserIds()) { 14116 pw.println("Domain preferred apps for User " + userId + ":"); 14117 pw.println(); 14118 count = 0; 14119 for (PackageSetting ps : allPackageSettings) { 14120 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14121 if (ivi == null || ivi.getPackageName() == null) { 14122 continue; 14123 } 14124 final int status = ps.getDomainVerificationStatusForUser(userId); 14125 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14126 continue; 14127 } 14128 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14129 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14130 String statusStr = IntentFilterVerificationInfo. 14131 getStatusStringFromValue(status); 14132 pw.println(prefix + "Status: " + statusStr); 14133 pw.println(); 14134 count++; 14135 } 14136 if (count == 0) { 14137 pw.println(prefix + "No domain preferred apps!"); 14138 pw.println(); 14139 } 14140 } 14141 } 14142 } 14143 } 14144 14145 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14146 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14147 if (packageName == null) { 14148 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14149 if (iperm == 0) { 14150 if (dumpState.onTitlePrinted()) 14151 pw.println(); 14152 pw.println("AppOp Permissions:"); 14153 } 14154 pw.print(" AppOp Permission "); 14155 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14156 pw.println(":"); 14157 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14158 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14159 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14160 } 14161 } 14162 } 14163 } 14164 14165 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14166 boolean printedSomething = false; 14167 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14168 if (packageName != null && !packageName.equals(p.info.packageName)) { 14169 continue; 14170 } 14171 if (!printedSomething) { 14172 if (dumpState.onTitlePrinted()) 14173 pw.println(); 14174 pw.println("Registered ContentProviders:"); 14175 printedSomething = true; 14176 } 14177 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14178 pw.print(" "); pw.println(p.toString()); 14179 } 14180 printedSomething = false; 14181 for (Map.Entry<String, PackageParser.Provider> entry : 14182 mProvidersByAuthority.entrySet()) { 14183 PackageParser.Provider p = entry.getValue(); 14184 if (packageName != null && !packageName.equals(p.info.packageName)) { 14185 continue; 14186 } 14187 if (!printedSomething) { 14188 if (dumpState.onTitlePrinted()) 14189 pw.println(); 14190 pw.println("ContentProvider Authorities:"); 14191 printedSomething = true; 14192 } 14193 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14194 pw.print(" "); pw.println(p.toString()); 14195 if (p.info != null && p.info.applicationInfo != null) { 14196 final String appInfo = p.info.applicationInfo.toString(); 14197 pw.print(" applicationInfo="); pw.println(appInfo); 14198 } 14199 } 14200 } 14201 14202 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14203 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14204 } 14205 14206 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14207 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14208 } 14209 14210 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14211 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14212 } 14213 14214 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14215 // XXX should handle packageName != null by dumping only install data that 14216 // the given package is involved with. 14217 if (dumpState.onTitlePrinted()) pw.println(); 14218 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14219 } 14220 14221 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14222 if (dumpState.onTitlePrinted()) pw.println(); 14223 mSettings.dumpReadMessagesLPr(pw, dumpState); 14224 14225 pw.println(); 14226 pw.println("Package warning messages:"); 14227 BufferedReader in = null; 14228 String line = null; 14229 try { 14230 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14231 while ((line = in.readLine()) != null) { 14232 if (line.contains("ignored: updated version")) continue; 14233 pw.println(line); 14234 } 14235 } catch (IOException ignored) { 14236 } finally { 14237 IoUtils.closeQuietly(in); 14238 } 14239 } 14240 14241 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14242 BufferedReader in = null; 14243 String line = null; 14244 try { 14245 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14246 while ((line = in.readLine()) != null) { 14247 if (line.contains("ignored: updated version")) continue; 14248 pw.print("msg,"); 14249 pw.println(line); 14250 } 14251 } catch (IOException ignored) { 14252 } finally { 14253 IoUtils.closeQuietly(in); 14254 } 14255 } 14256 } 14257 } 14258 14259 // ------- apps on sdcard specific code ------- 14260 static final boolean DEBUG_SD_INSTALL = false; 14261 14262 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14263 14264 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14265 14266 private boolean mMediaMounted = false; 14267 14268 static String getEncryptKey() { 14269 try { 14270 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14271 SD_ENCRYPTION_KEYSTORE_NAME); 14272 if (sdEncKey == null) { 14273 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14274 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14275 if (sdEncKey == null) { 14276 Slog.e(TAG, "Failed to create encryption keys"); 14277 return null; 14278 } 14279 } 14280 return sdEncKey; 14281 } catch (NoSuchAlgorithmException nsae) { 14282 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14283 return null; 14284 } catch (IOException ioe) { 14285 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14286 return null; 14287 } 14288 } 14289 14290 /* 14291 * Update media status on PackageManager. 14292 */ 14293 @Override 14294 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14295 int callingUid = Binder.getCallingUid(); 14296 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14297 throw new SecurityException("Media status can only be updated by the system"); 14298 } 14299 // reader; this apparently protects mMediaMounted, but should probably 14300 // be a different lock in that case. 14301 synchronized (mPackages) { 14302 Log.i(TAG, "Updating external media status from " 14303 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14304 + (mediaStatus ? "mounted" : "unmounted")); 14305 if (DEBUG_SD_INSTALL) 14306 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14307 + ", mMediaMounted=" + mMediaMounted); 14308 if (mediaStatus == mMediaMounted) { 14309 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14310 : 0, -1); 14311 mHandler.sendMessage(msg); 14312 return; 14313 } 14314 mMediaMounted = mediaStatus; 14315 } 14316 // Queue up an async operation since the package installation may take a 14317 // little while. 14318 mHandler.post(new Runnable() { 14319 public void run() { 14320 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14321 } 14322 }); 14323 } 14324 14325 /** 14326 * Called by MountService when the initial ASECs to scan are available. 14327 * Should block until all the ASEC containers are finished being scanned. 14328 */ 14329 public void scanAvailableAsecs() { 14330 updateExternalMediaStatusInner(true, false, false); 14331 if (mShouldRestoreconData) { 14332 SELinuxMMAC.setRestoreconDone(); 14333 mShouldRestoreconData = false; 14334 } 14335 } 14336 14337 /* 14338 * Collect information of applications on external media, map them against 14339 * existing containers and update information based on current mount status. 14340 * Please note that we always have to report status if reportStatus has been 14341 * set to true especially when unloading packages. 14342 */ 14343 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14344 boolean externalStorage) { 14345 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14346 int[] uidArr = EmptyArray.INT; 14347 14348 final String[] list = PackageHelper.getSecureContainerList(); 14349 if (ArrayUtils.isEmpty(list)) { 14350 Log.i(TAG, "No secure containers found"); 14351 } else { 14352 // Process list of secure containers and categorize them 14353 // as active or stale based on their package internal state. 14354 14355 // reader 14356 synchronized (mPackages) { 14357 for (String cid : list) { 14358 // Leave stages untouched for now; installer service owns them 14359 if (PackageInstallerService.isStageName(cid)) continue; 14360 14361 if (DEBUG_SD_INSTALL) 14362 Log.i(TAG, "Processing container " + cid); 14363 String pkgName = getAsecPackageName(cid); 14364 if (pkgName == null) { 14365 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14366 continue; 14367 } 14368 if (DEBUG_SD_INSTALL) 14369 Log.i(TAG, "Looking for pkg : " + pkgName); 14370 14371 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14372 if (ps == null) { 14373 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14374 continue; 14375 } 14376 14377 /* 14378 * Skip packages that are not external if we're unmounting 14379 * external storage. 14380 */ 14381 if (externalStorage && !isMounted && !isExternal(ps)) { 14382 continue; 14383 } 14384 14385 final AsecInstallArgs args = new AsecInstallArgs(cid, 14386 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14387 // The package status is changed only if the code path 14388 // matches between settings and the container id. 14389 if (ps.codePathString != null 14390 && ps.codePathString.startsWith(args.getCodePath())) { 14391 if (DEBUG_SD_INSTALL) { 14392 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14393 + " at code path: " + ps.codePathString); 14394 } 14395 14396 // We do have a valid package installed on sdcard 14397 processCids.put(args, ps.codePathString); 14398 final int uid = ps.appId; 14399 if (uid != -1) { 14400 uidArr = ArrayUtils.appendInt(uidArr, uid); 14401 } 14402 } else { 14403 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14404 + ps.codePathString); 14405 } 14406 } 14407 } 14408 14409 Arrays.sort(uidArr); 14410 } 14411 14412 // Process packages with valid entries. 14413 if (isMounted) { 14414 if (DEBUG_SD_INSTALL) 14415 Log.i(TAG, "Loading packages"); 14416 loadMediaPackages(processCids, uidArr); 14417 startCleaningPackages(); 14418 mInstallerService.onSecureContainersAvailable(); 14419 } else { 14420 if (DEBUG_SD_INSTALL) 14421 Log.i(TAG, "Unloading packages"); 14422 unloadMediaPackages(processCids, uidArr, reportStatus); 14423 } 14424 } 14425 14426 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14427 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14428 final int size = infos.size(); 14429 final String[] packageNames = new String[size]; 14430 final int[] packageUids = new int[size]; 14431 for (int i = 0; i < size; i++) { 14432 final ApplicationInfo info = infos.get(i); 14433 packageNames[i] = info.packageName; 14434 packageUids[i] = info.uid; 14435 } 14436 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14437 finishedReceiver); 14438 } 14439 14440 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14441 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14442 sendResourcesChangedBroadcast(mediaStatus, replacing, 14443 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14444 } 14445 14446 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14447 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14448 int size = pkgList.length; 14449 if (size > 0) { 14450 // Send broadcasts here 14451 Bundle extras = new Bundle(); 14452 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14453 if (uidArr != null) { 14454 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14455 } 14456 if (replacing) { 14457 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14458 } 14459 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14460 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14461 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14462 } 14463 } 14464 14465 /* 14466 * Look at potentially valid container ids from processCids If package 14467 * information doesn't match the one on record or package scanning fails, 14468 * the cid is added to list of removeCids. We currently don't delete stale 14469 * containers. 14470 */ 14471 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14472 ArrayList<String> pkgList = new ArrayList<String>(); 14473 Set<AsecInstallArgs> keys = processCids.keySet(); 14474 14475 for (AsecInstallArgs args : keys) { 14476 String codePath = processCids.get(args); 14477 if (DEBUG_SD_INSTALL) 14478 Log.i(TAG, "Loading container : " + args.cid); 14479 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14480 try { 14481 // Make sure there are no container errors first. 14482 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14483 Slog.e(TAG, "Failed to mount cid : " + args.cid 14484 + " when installing from sdcard"); 14485 continue; 14486 } 14487 // Check code path here. 14488 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14489 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14490 + " does not match one in settings " + codePath); 14491 continue; 14492 } 14493 // Parse package 14494 int parseFlags = mDefParseFlags; 14495 if (args.isExternalAsec()) { 14496 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14497 } 14498 if (args.isFwdLocked()) { 14499 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14500 } 14501 14502 synchronized (mInstallLock) { 14503 PackageParser.Package pkg = null; 14504 try { 14505 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14506 } catch (PackageManagerException e) { 14507 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14508 } 14509 // Scan the package 14510 if (pkg != null) { 14511 /* 14512 * TODO why is the lock being held? doPostInstall is 14513 * called in other places without the lock. This needs 14514 * to be straightened out. 14515 */ 14516 // writer 14517 synchronized (mPackages) { 14518 retCode = PackageManager.INSTALL_SUCCEEDED; 14519 pkgList.add(pkg.packageName); 14520 // Post process args 14521 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14522 pkg.applicationInfo.uid); 14523 } 14524 } else { 14525 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14526 } 14527 } 14528 14529 } finally { 14530 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14531 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14532 } 14533 } 14534 } 14535 // writer 14536 synchronized (mPackages) { 14537 // If the platform SDK has changed since the last time we booted, 14538 // we need to re-grant app permission to catch any new ones that 14539 // appear. This is really a hack, and means that apps can in some 14540 // cases get permissions that the user didn't initially explicitly 14541 // allow... it would be nice to have some better way to handle 14542 // this situation. 14543 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14544 if (regrantPermissions) 14545 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14546 + mSdkVersion + "; regranting permissions for external storage"); 14547 mSettings.mExternalSdkPlatform = mSdkVersion; 14548 14549 // Make sure group IDs have been assigned, and any permission 14550 // changes in other apps are accounted for 14551 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14552 | (regrantPermissions 14553 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14554 : 0)); 14555 14556 mSettings.updateExternalDatabaseVersion(); 14557 14558 // can downgrade to reader 14559 // Persist settings 14560 mSettings.writeLPr(); 14561 } 14562 // Send a broadcast to let everyone know we are done processing 14563 if (pkgList.size() > 0) { 14564 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14565 } 14566 } 14567 14568 /* 14569 * Utility method to unload a list of specified containers 14570 */ 14571 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14572 // Just unmount all valid containers. 14573 for (AsecInstallArgs arg : cidArgs) { 14574 synchronized (mInstallLock) { 14575 arg.doPostDeleteLI(false); 14576 } 14577 } 14578 } 14579 14580 /* 14581 * Unload packages mounted on external media. This involves deleting package 14582 * data from internal structures, sending broadcasts about diabled packages, 14583 * gc'ing to free up references, unmounting all secure containers 14584 * corresponding to packages on external media, and posting a 14585 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14586 * that we always have to post this message if status has been requested no 14587 * matter what. 14588 */ 14589 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14590 final boolean reportStatus) { 14591 if (DEBUG_SD_INSTALL) 14592 Log.i(TAG, "unloading media packages"); 14593 ArrayList<String> pkgList = new ArrayList<String>(); 14594 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14595 final Set<AsecInstallArgs> keys = processCids.keySet(); 14596 for (AsecInstallArgs args : keys) { 14597 String pkgName = args.getPackageName(); 14598 if (DEBUG_SD_INSTALL) 14599 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14600 // Delete package internally 14601 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14602 synchronized (mInstallLock) { 14603 boolean res = deletePackageLI(pkgName, null, false, null, null, 14604 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14605 if (res) { 14606 pkgList.add(pkgName); 14607 } else { 14608 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14609 failedList.add(args); 14610 } 14611 } 14612 } 14613 14614 // reader 14615 synchronized (mPackages) { 14616 // We didn't update the settings after removing each package; 14617 // write them now for all packages. 14618 mSettings.writeLPr(); 14619 } 14620 14621 // We have to absolutely send UPDATED_MEDIA_STATUS only 14622 // after confirming that all the receivers processed the ordered 14623 // broadcast when packages get disabled, force a gc to clean things up. 14624 // and unload all the containers. 14625 if (pkgList.size() > 0) { 14626 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14627 new IIntentReceiver.Stub() { 14628 public void performReceive(Intent intent, int resultCode, String data, 14629 Bundle extras, boolean ordered, boolean sticky, 14630 int sendingUser) throws RemoteException { 14631 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14632 reportStatus ? 1 : 0, 1, keys); 14633 mHandler.sendMessage(msg); 14634 } 14635 }); 14636 } else { 14637 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14638 keys); 14639 mHandler.sendMessage(msg); 14640 } 14641 } 14642 14643 private void loadPrivatePackages(VolumeInfo vol) { 14644 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14645 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14646 synchronized (mInstallLock) { 14647 synchronized (mPackages) { 14648 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14649 for (PackageSetting ps : packages) { 14650 final PackageParser.Package pkg; 14651 try { 14652 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14653 loaded.add(pkg.applicationInfo); 14654 } catch (PackageManagerException e) { 14655 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14656 } 14657 } 14658 14659 // TODO: regrant any permissions that changed based since original install 14660 14661 mSettings.writeLPr(); 14662 } 14663 } 14664 14665 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14666 sendResourcesChangedBroadcast(true, false, loaded, null); 14667 } 14668 14669 private void unloadPrivatePackages(VolumeInfo vol) { 14670 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14671 synchronized (mInstallLock) { 14672 synchronized (mPackages) { 14673 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14674 for (PackageSetting ps : packages) { 14675 if (ps.pkg == null) continue; 14676 14677 final ApplicationInfo info = ps.pkg.applicationInfo; 14678 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14679 if (deletePackageLI(ps.name, null, false, null, null, 14680 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14681 unloaded.add(info); 14682 } else { 14683 Slog.w(TAG, "Failed to unload " + ps.codePath); 14684 } 14685 } 14686 14687 mSettings.writeLPr(); 14688 } 14689 } 14690 14691 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14692 sendResourcesChangedBroadcast(false, false, unloaded, null); 14693 } 14694 14695 private void unfreezePackage(String packageName) { 14696 synchronized (mPackages) { 14697 final PackageSetting ps = mSettings.mPackages.get(packageName); 14698 if (ps != null) { 14699 ps.frozen = false; 14700 } 14701 } 14702 } 14703 14704 @Override 14705 public int movePackage(final String packageName, final String volumeUuid) { 14706 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14707 14708 final int moveId = mNextMoveId.getAndIncrement(); 14709 try { 14710 movePackageInternal(packageName, volumeUuid, moveId); 14711 } catch (PackageManagerException e) { 14712 Slog.w(TAG, "Failed to move " + packageName, e); 14713 mMoveCallbacks.notifyStatusChanged(moveId, 14714 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14715 } 14716 return moveId; 14717 } 14718 14719 private void movePackageInternal(final String packageName, final String volumeUuid, 14720 final int moveId) throws PackageManagerException { 14721 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14722 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14723 final PackageManager pm = mContext.getPackageManager(); 14724 14725 final boolean currentAsec; 14726 final String currentVolumeUuid; 14727 final File codeFile; 14728 final String installerPackageName; 14729 final String packageAbiOverride; 14730 final int appId; 14731 final String seinfo; 14732 final String label; 14733 14734 // reader 14735 synchronized (mPackages) { 14736 final PackageParser.Package pkg = mPackages.get(packageName); 14737 final PackageSetting ps = mSettings.mPackages.get(packageName); 14738 if (pkg == null || ps == null) { 14739 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14740 } 14741 14742 if (pkg.applicationInfo.isSystemApp()) { 14743 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14744 "Cannot move system application"); 14745 } 14746 14747 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14748 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14749 "Package already moved to " + volumeUuid); 14750 } 14751 14752 final File probe = new File(pkg.codePath); 14753 final File probeOat = new File(probe, "oat"); 14754 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14756 "Move only supported for modern cluster style installs"); 14757 } 14758 14759 if (ps.frozen) { 14760 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14761 "Failed to move already frozen package"); 14762 } 14763 ps.frozen = true; 14764 14765 currentAsec = pkg.applicationInfo.isForwardLocked() 14766 || pkg.applicationInfo.isExternalAsec(); 14767 currentVolumeUuid = ps.volumeUuid; 14768 codeFile = new File(pkg.codePath); 14769 installerPackageName = ps.installerPackageName; 14770 packageAbiOverride = ps.cpuAbiOverrideString; 14771 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14772 seinfo = pkg.applicationInfo.seinfo; 14773 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14774 } 14775 14776 // Now that we're guarded by frozen state, kill app during move 14777 killApplication(packageName, appId, "move pkg"); 14778 14779 final Bundle extras = new Bundle(); 14780 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14781 extras.putString(Intent.EXTRA_TITLE, label); 14782 mMoveCallbacks.notifyCreated(moveId, extras); 14783 14784 int installFlags; 14785 final boolean moveCompleteApp; 14786 final File measurePath; 14787 14788 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14789 installFlags = INSTALL_INTERNAL; 14790 moveCompleteApp = !currentAsec; 14791 measurePath = Environment.getDataAppDirectory(volumeUuid); 14792 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14793 installFlags = INSTALL_EXTERNAL; 14794 moveCompleteApp = false; 14795 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14796 } else { 14797 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14798 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14799 || !volume.isMountedWritable()) { 14800 unfreezePackage(packageName); 14801 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14802 "Move location not mounted private volume"); 14803 } 14804 14805 Preconditions.checkState(!currentAsec); 14806 14807 installFlags = INSTALL_INTERNAL; 14808 moveCompleteApp = true; 14809 measurePath = Environment.getDataAppDirectory(volumeUuid); 14810 } 14811 14812 final PackageStats stats = new PackageStats(null, -1); 14813 synchronized (mInstaller) { 14814 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14815 unfreezePackage(packageName); 14816 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14817 "Failed to measure package size"); 14818 } 14819 } 14820 14821 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14822 + stats.dataSize); 14823 14824 final long startFreeBytes = measurePath.getFreeSpace(); 14825 final long sizeBytes; 14826 if (moveCompleteApp) { 14827 sizeBytes = stats.codeSize + stats.dataSize; 14828 } else { 14829 sizeBytes = stats.codeSize; 14830 } 14831 14832 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14833 unfreezePackage(packageName); 14834 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14835 "Not enough free space to move"); 14836 } 14837 14838 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14839 14840 final CountDownLatch installedLatch = new CountDownLatch(1); 14841 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14842 @Override 14843 public void onUserActionRequired(Intent intent) throws RemoteException { 14844 throw new IllegalStateException(); 14845 } 14846 14847 @Override 14848 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14849 Bundle extras) throws RemoteException { 14850 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14851 + PackageManager.installStatusToString(returnCode, msg)); 14852 14853 installedLatch.countDown(); 14854 14855 // Regardless of success or failure of the move operation, 14856 // always unfreeze the package 14857 unfreezePackage(packageName); 14858 14859 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14860 switch (status) { 14861 case PackageInstaller.STATUS_SUCCESS: 14862 mMoveCallbacks.notifyStatusChanged(moveId, 14863 PackageManager.MOVE_SUCCEEDED); 14864 break; 14865 case PackageInstaller.STATUS_FAILURE_STORAGE: 14866 mMoveCallbacks.notifyStatusChanged(moveId, 14867 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14868 break; 14869 default: 14870 mMoveCallbacks.notifyStatusChanged(moveId, 14871 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14872 break; 14873 } 14874 } 14875 }; 14876 14877 final MoveInfo move; 14878 if (moveCompleteApp) { 14879 // Kick off a thread to report progress estimates 14880 new Thread() { 14881 @Override 14882 public void run() { 14883 while (true) { 14884 try { 14885 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14886 break; 14887 } 14888 } catch (InterruptedException ignored) { 14889 } 14890 14891 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14892 final int progress = 10 + (int) MathUtils.constrain( 14893 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14894 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14895 } 14896 } 14897 }.start(); 14898 14899 final String dataAppName = codeFile.getName(); 14900 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14901 dataAppName, appId, seinfo); 14902 } else { 14903 move = null; 14904 } 14905 14906 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14907 14908 final Message msg = mHandler.obtainMessage(INIT_COPY); 14909 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14910 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14911 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14912 mHandler.sendMessage(msg); 14913 } 14914 14915 @Override 14916 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14917 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14918 14919 final int realMoveId = mNextMoveId.getAndIncrement(); 14920 final Bundle extras = new Bundle(); 14921 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14922 mMoveCallbacks.notifyCreated(realMoveId, extras); 14923 14924 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14925 @Override 14926 public void onCreated(int moveId, Bundle extras) { 14927 // Ignored 14928 } 14929 14930 @Override 14931 public void onStatusChanged(int moveId, int status, long estMillis) { 14932 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14933 } 14934 }; 14935 14936 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14937 storage.setPrimaryStorageUuid(volumeUuid, callback); 14938 return realMoveId; 14939 } 14940 14941 @Override 14942 public int getMoveStatus(int moveId) { 14943 mContext.enforceCallingOrSelfPermission( 14944 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14945 return mMoveCallbacks.mLastStatus.get(moveId); 14946 } 14947 14948 @Override 14949 public void registerMoveCallback(IPackageMoveObserver callback) { 14950 mContext.enforceCallingOrSelfPermission( 14951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14952 mMoveCallbacks.register(callback); 14953 } 14954 14955 @Override 14956 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14957 mContext.enforceCallingOrSelfPermission( 14958 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14959 mMoveCallbacks.unregister(callback); 14960 } 14961 14962 @Override 14963 public boolean setInstallLocation(int loc) { 14964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14965 null); 14966 if (getInstallLocation() == loc) { 14967 return true; 14968 } 14969 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14970 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14971 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14972 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14973 return true; 14974 } 14975 return false; 14976 } 14977 14978 @Override 14979 public int getInstallLocation() { 14980 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14981 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14982 PackageHelper.APP_INSTALL_AUTO); 14983 } 14984 14985 /** Called by UserManagerService */ 14986 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14987 mDirtyUsers.remove(userHandle); 14988 mSettings.removeUserLPw(userHandle); 14989 mPendingBroadcasts.remove(userHandle); 14990 if (mInstaller != null) { 14991 // Technically, we shouldn't be doing this with the package lock 14992 // held. However, this is very rare, and there is already so much 14993 // other disk I/O going on, that we'll let it slide for now. 14994 final StorageManager storage = StorageManager.from(mContext); 14995 final List<VolumeInfo> vols = storage.getVolumes(); 14996 for (VolumeInfo vol : vols) { 14997 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14998 final String volumeUuid = vol.getFsUuid(); 14999 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15000 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15001 } 15002 } 15003 } 15004 mUserNeedsBadging.delete(userHandle); 15005 removeUnusedPackagesLILPw(userManager, userHandle); 15006 } 15007 15008 /** 15009 * We're removing userHandle and would like to remove any downloaded packages 15010 * that are no longer in use by any other user. 15011 * @param userHandle the user being removed 15012 */ 15013 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15014 final boolean DEBUG_CLEAN_APKS = false; 15015 int [] users = userManager.getUserIdsLPr(); 15016 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15017 while (psit.hasNext()) { 15018 PackageSetting ps = psit.next(); 15019 if (ps.pkg == null) { 15020 continue; 15021 } 15022 final String packageName = ps.pkg.packageName; 15023 // Skip over if system app 15024 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15025 continue; 15026 } 15027 if (DEBUG_CLEAN_APKS) { 15028 Slog.i(TAG, "Checking package " + packageName); 15029 } 15030 boolean keep = false; 15031 for (int i = 0; i < users.length; i++) { 15032 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15033 keep = true; 15034 if (DEBUG_CLEAN_APKS) { 15035 Slog.i(TAG, " Keeping package " + packageName + " for user " 15036 + users[i]); 15037 } 15038 break; 15039 } 15040 } 15041 if (!keep) { 15042 if (DEBUG_CLEAN_APKS) { 15043 Slog.i(TAG, " Removing package " + packageName); 15044 } 15045 mHandler.post(new Runnable() { 15046 public void run() { 15047 deletePackageX(packageName, userHandle, 0); 15048 } //end run 15049 }); 15050 } 15051 } 15052 } 15053 15054 /** Called by UserManagerService */ 15055 void createNewUserLILPw(int userHandle, File path) { 15056 if (mInstaller != null) { 15057 mInstaller.createUserConfig(userHandle); 15058 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15059 } 15060 } 15061 15062 void newUserCreatedLILPw(int userHandle) { 15063 // Adding a user requires updating runtime permissions for system apps. 15064 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15065 } 15066 15067 @Override 15068 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15069 mContext.enforceCallingOrSelfPermission( 15070 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15071 "Only package verification agents can read the verifier device identity"); 15072 15073 synchronized (mPackages) { 15074 return mSettings.getVerifierDeviceIdentityLPw(); 15075 } 15076 } 15077 15078 @Override 15079 public void setPermissionEnforced(String permission, boolean enforced) { 15080 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15081 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15082 synchronized (mPackages) { 15083 if (mSettings.mReadExternalStorageEnforced == null 15084 || mSettings.mReadExternalStorageEnforced != enforced) { 15085 mSettings.mReadExternalStorageEnforced = enforced; 15086 mSettings.writeLPr(); 15087 } 15088 } 15089 // kill any non-foreground processes so we restart them and 15090 // grant/revoke the GID. 15091 final IActivityManager am = ActivityManagerNative.getDefault(); 15092 if (am != null) { 15093 final long token = Binder.clearCallingIdentity(); 15094 try { 15095 am.killProcessesBelowForeground("setPermissionEnforcement"); 15096 } catch (RemoteException e) { 15097 } finally { 15098 Binder.restoreCallingIdentity(token); 15099 } 15100 } 15101 } else { 15102 throw new IllegalArgumentException("No selective enforcement for " + permission); 15103 } 15104 } 15105 15106 @Override 15107 @Deprecated 15108 public boolean isPermissionEnforced(String permission) { 15109 return true; 15110 } 15111 15112 @Override 15113 public boolean isStorageLow() { 15114 final long token = Binder.clearCallingIdentity(); 15115 try { 15116 final DeviceStorageMonitorInternal 15117 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15118 if (dsm != null) { 15119 return dsm.isMemoryLow(); 15120 } else { 15121 return false; 15122 } 15123 } finally { 15124 Binder.restoreCallingIdentity(token); 15125 } 15126 } 15127 15128 @Override 15129 public IPackageInstaller getPackageInstaller() { 15130 return mInstallerService; 15131 } 15132 15133 private boolean userNeedsBadging(int userId) { 15134 int index = mUserNeedsBadging.indexOfKey(userId); 15135 if (index < 0) { 15136 final UserInfo userInfo; 15137 final long token = Binder.clearCallingIdentity(); 15138 try { 15139 userInfo = sUserManager.getUserInfo(userId); 15140 } finally { 15141 Binder.restoreCallingIdentity(token); 15142 } 15143 final boolean b; 15144 if (userInfo != null && userInfo.isManagedProfile()) { 15145 b = true; 15146 } else { 15147 b = false; 15148 } 15149 mUserNeedsBadging.put(userId, b); 15150 return b; 15151 } 15152 return mUserNeedsBadging.valueAt(index); 15153 } 15154 15155 @Override 15156 public KeySet getKeySetByAlias(String packageName, String alias) { 15157 if (packageName == null || alias == null) { 15158 return null; 15159 } 15160 synchronized(mPackages) { 15161 final PackageParser.Package pkg = mPackages.get(packageName); 15162 if (pkg == null) { 15163 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15164 throw new IllegalArgumentException("Unknown package: " + packageName); 15165 } 15166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15167 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15168 } 15169 } 15170 15171 @Override 15172 public KeySet getSigningKeySet(String packageName) { 15173 if (packageName == null) { 15174 return null; 15175 } 15176 synchronized(mPackages) { 15177 final PackageParser.Package pkg = mPackages.get(packageName); 15178 if (pkg == null) { 15179 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15180 throw new IllegalArgumentException("Unknown package: " + packageName); 15181 } 15182 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15183 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15184 throw new SecurityException("May not access signing KeySet of other apps."); 15185 } 15186 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15187 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15188 } 15189 } 15190 15191 @Override 15192 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15193 if (packageName == null || ks == null) { 15194 return false; 15195 } 15196 synchronized(mPackages) { 15197 final PackageParser.Package pkg = mPackages.get(packageName); 15198 if (pkg == null) { 15199 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15200 throw new IllegalArgumentException("Unknown package: " + packageName); 15201 } 15202 IBinder ksh = ks.getToken(); 15203 if (ksh instanceof KeySetHandle) { 15204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15205 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15206 } 15207 return false; 15208 } 15209 } 15210 15211 @Override 15212 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15213 if (packageName == null || ks == null) { 15214 return false; 15215 } 15216 synchronized(mPackages) { 15217 final PackageParser.Package pkg = mPackages.get(packageName); 15218 if (pkg == null) { 15219 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15220 throw new IllegalArgumentException("Unknown package: " + packageName); 15221 } 15222 IBinder ksh = ks.getToken(); 15223 if (ksh instanceof KeySetHandle) { 15224 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15225 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15226 } 15227 return false; 15228 } 15229 } 15230 15231 public void getUsageStatsIfNoPackageUsageInfo() { 15232 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15233 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15234 if (usm == null) { 15235 throw new IllegalStateException("UsageStatsManager must be initialized"); 15236 } 15237 long now = System.currentTimeMillis(); 15238 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15239 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15240 String packageName = entry.getKey(); 15241 PackageParser.Package pkg = mPackages.get(packageName); 15242 if (pkg == null) { 15243 continue; 15244 } 15245 UsageStats usage = entry.getValue(); 15246 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15247 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15248 } 15249 } 15250 } 15251 15252 /** 15253 * Check and throw if the given before/after packages would be considered a 15254 * downgrade. 15255 */ 15256 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15257 throws PackageManagerException { 15258 if (after.versionCode < before.mVersionCode) { 15259 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15260 "Update version code " + after.versionCode + " is older than current " 15261 + before.mVersionCode); 15262 } else if (after.versionCode == before.mVersionCode) { 15263 if (after.baseRevisionCode < before.baseRevisionCode) { 15264 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15265 "Update base revision code " + after.baseRevisionCode 15266 + " is older than current " + before.baseRevisionCode); 15267 } 15268 15269 if (!ArrayUtils.isEmpty(after.splitNames)) { 15270 for (int i = 0; i < after.splitNames.length; i++) { 15271 final String splitName = after.splitNames[i]; 15272 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15273 if (j != -1) { 15274 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15275 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15276 "Update split " + splitName + " revision code " 15277 + after.splitRevisionCodes[i] + " is older than current " 15278 + before.splitRevisionCodes[j]); 15279 } 15280 } 15281 } 15282 } 15283 } 15284 } 15285 15286 private static class MoveCallbacks extends Handler { 15287 private static final int MSG_CREATED = 1; 15288 private static final int MSG_STATUS_CHANGED = 2; 15289 15290 private final RemoteCallbackList<IPackageMoveObserver> 15291 mCallbacks = new RemoteCallbackList<>(); 15292 15293 private final SparseIntArray mLastStatus = new SparseIntArray(); 15294 15295 public MoveCallbacks(Looper looper) { 15296 super(looper); 15297 } 15298 15299 public void register(IPackageMoveObserver callback) { 15300 mCallbacks.register(callback); 15301 } 15302 15303 public void unregister(IPackageMoveObserver callback) { 15304 mCallbacks.unregister(callback); 15305 } 15306 15307 @Override 15308 public void handleMessage(Message msg) { 15309 final SomeArgs args = (SomeArgs) msg.obj; 15310 final int n = mCallbacks.beginBroadcast(); 15311 for (int i = 0; i < n; i++) { 15312 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15313 try { 15314 invokeCallback(callback, msg.what, args); 15315 } catch (RemoteException ignored) { 15316 } 15317 } 15318 mCallbacks.finishBroadcast(); 15319 args.recycle(); 15320 } 15321 15322 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15323 throws RemoteException { 15324 switch (what) { 15325 case MSG_CREATED: { 15326 callback.onCreated(args.argi1, (Bundle) args.arg2); 15327 break; 15328 } 15329 case MSG_STATUS_CHANGED: { 15330 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15331 break; 15332 } 15333 } 15334 } 15335 15336 private void notifyCreated(int moveId, Bundle extras) { 15337 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15338 15339 final SomeArgs args = SomeArgs.obtain(); 15340 args.argi1 = moveId; 15341 args.arg2 = extras; 15342 obtainMessage(MSG_CREATED, args).sendToTarget(); 15343 } 15344 15345 private void notifyStatusChanged(int moveId, int status) { 15346 notifyStatusChanged(moveId, status, -1); 15347 } 15348 15349 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15350 Slog.v(TAG, "Move " + moveId + " status " + status); 15351 15352 final SomeArgs args = SomeArgs.obtain(); 15353 args.argi1 = moveId; 15354 args.argi2 = status; 15355 args.arg3 = estMillis; 15356 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15357 15358 synchronized (mLastStatus) { 15359 mLastStatus.put(moveId, status); 15360 } 15361 } 15362 } 15363 15364 private final class OnPermissionChangeListeners extends Handler { 15365 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15366 15367 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15368 new RemoteCallbackList<>(); 15369 15370 public OnPermissionChangeListeners(Looper looper) { 15371 super(looper); 15372 } 15373 15374 @Override 15375 public void handleMessage(Message msg) { 15376 switch (msg.what) { 15377 case MSG_ON_PERMISSIONS_CHANGED: { 15378 final int uid = msg.arg1; 15379 handleOnPermissionsChanged(uid); 15380 } break; 15381 } 15382 } 15383 15384 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15385 mPermissionListeners.register(listener); 15386 15387 } 15388 15389 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15390 mPermissionListeners.unregister(listener); 15391 } 15392 15393 public void onPermissionsChanged(int uid) { 15394 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15395 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15396 } 15397 } 15398 15399 private void handleOnPermissionsChanged(int uid) { 15400 final int count = mPermissionListeners.beginBroadcast(); 15401 try { 15402 for (int i = 0; i < count; i++) { 15403 IOnPermissionsChangeListener callback = mPermissionListeners 15404 .getBroadcastItem(i); 15405 try { 15406 callback.onPermissionsChanged(uid); 15407 } catch (RemoteException e) { 15408 Log.e(TAG, "Permission listener is dead", e); 15409 } 15410 } 15411 } finally { 15412 mPermissionListeners.finishBroadcast(); 15413 } 15414 } 15415 } 15416} 15417