PackageManagerService.java revision 1c4a44e577c7b8316172d1bf5357d006776ae75e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.text.format.DateUtils; 165import android.util.ArrayMap; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.util.SparseIntArray; 178import android.util.Xml; 179import android.view.Display; 180 181import dalvik.system.DexFile; 182import dalvik.system.VMRuntime; 183 184import libcore.io.IoUtils; 185import libcore.util.EmptyArray; 186 187import com.android.internal.R; 188import com.android.internal.app.IMediaContainerService; 189import com.android.internal.app.ResolverActivity; 190import com.android.internal.content.NativeLibraryHelper; 191import com.android.internal.content.PackageHelper; 192import com.android.internal.os.IParcelFileDescriptorFactory; 193import com.android.internal.os.SomeArgs; 194import com.android.internal.util.ArrayUtils; 195import com.android.internal.util.FastPrintWriter; 196import com.android.internal.util.FastXmlSerializer; 197import com.android.internal.util.IndentingPrintWriter; 198import com.android.internal.util.Preconditions; 199import com.android.server.EventLogTags; 200import com.android.server.FgThread; 201import com.android.server.IntentResolver; 202import com.android.server.LocalServices; 203import com.android.server.ServiceThread; 204import com.android.server.SystemConfig; 205import com.android.server.Watchdog; 206import com.android.server.pm.Settings.DatabaseVersion; 207import com.android.server.storage.DeviceStorageMonitorInternal; 208 209import org.xmlpull.v1.XmlPullParser; 210import org.xmlpull.v1.XmlSerializer; 211 212import java.io.BufferedInputStream; 213import java.io.BufferedOutputStream; 214import java.io.BufferedReader; 215import java.io.ByteArrayInputStream; 216import java.io.ByteArrayOutputStream; 217import java.io.File; 218import java.io.FileDescriptor; 219import java.io.FileNotFoundException; 220import java.io.FileOutputStream; 221import java.io.FileReader; 222import java.io.FilenameFilter; 223import java.io.IOException; 224import java.io.InputStream; 225import java.io.PrintWriter; 226import java.nio.charset.StandardCharsets; 227import java.security.NoSuchAlgorithmException; 228import java.security.PublicKey; 229import java.security.cert.CertificateEncodingException; 230import java.security.cert.CertificateException; 231import java.text.SimpleDateFormat; 232import java.util.ArrayList; 233import java.util.Arrays; 234import java.util.Collection; 235import java.util.Collections; 236import java.util.Comparator; 237import java.util.Date; 238import java.util.Iterator; 239import java.util.List; 240import java.util.Map; 241import java.util.Objects; 242import java.util.Set; 243import java.util.concurrent.atomic.AtomicBoolean; 244import java.util.concurrent.atomic.AtomicInteger; 245import java.util.concurrent.atomic.AtomicLong; 246 247/** 248 * Keep track of all those .apks everywhere. 249 * 250 * This is very central to the platform's security; please run the unit 251 * tests whenever making modifications here: 252 * 253mmm frameworks/base/tests/AndroidTests 254adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 255adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 256 * 257 * {@hide} 258 */ 259public class PackageManagerService extends IPackageManager.Stub { 260 static final String TAG = "PackageManager"; 261 static final boolean DEBUG_SETTINGS = false; 262 static final boolean DEBUG_PREFERRED = false; 263 static final boolean DEBUG_UPGRADE = false; 264 private static final boolean DEBUG_BACKUP = true; 265 private static final boolean DEBUG_INSTALL = false; 266 private static final boolean DEBUG_REMOVE = false; 267 private static final boolean DEBUG_BROADCASTS = false; 268 private static final boolean DEBUG_SHOW_INFO = false; 269 private static final boolean DEBUG_PACKAGE_INFO = false; 270 private static final boolean DEBUG_INTENT_MATCHING = false; 271 private static final boolean DEBUG_PACKAGE_SCANNING = false; 272 private static final boolean DEBUG_VERIFY = false; 273 private static final boolean DEBUG_DEXOPT = false; 274 private static final boolean DEBUG_ABI_SELECTION = false; 275 276 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 277 278 private static final int RADIO_UID = Process.PHONE_UID; 279 private static final int LOG_UID = Process.LOG_UID; 280 private static final int NFC_UID = Process.NFC_UID; 281 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 282 private static final int SHELL_UID = Process.SHELL_UID; 283 284 // Cap the size of permission trees that 3rd party apps can define 285 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 286 287 // Suffix used during package installation when copying/moving 288 // package apks to install directory. 289 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 290 291 static final int SCAN_NO_DEX = 1<<1; 292 static final int SCAN_FORCE_DEX = 1<<2; 293 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 294 static final int SCAN_NEW_INSTALL = 1<<4; 295 static final int SCAN_NO_PATHS = 1<<5; 296 static final int SCAN_UPDATE_TIME = 1<<6; 297 static final int SCAN_DEFER_DEX = 1<<7; 298 static final int SCAN_BOOTING = 1<<8; 299 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 300 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 301 static final int SCAN_REPLACING = 1<<11; 302 static final int SCAN_REQUIRE_KNOWN = 1<<12; 303 304 static final int REMOVE_CHATTY = 1<<16; 305 306 /** 307 * Timeout (in milliseconds) after which the watchdog should declare that 308 * our handler thread is wedged. The usual default for such things is one 309 * minute but we sometimes do very lengthy I/O operations on this thread, 310 * such as installing multi-gigabyte applications, so ours needs to be longer. 311 */ 312 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 313 314 /** 315 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 316 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 317 * settings entry if available, otherwise we use the hardcoded default. If it's been 318 * more than this long since the last fstrim, we force one during the boot sequence. 319 * 320 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 321 * one gets run at the next available charging+idle time. This final mandatory 322 * no-fstrim check kicks in only of the other scheduling criteria is never met. 323 */ 324 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 325 326 /** 327 * Whether verification is enabled by default. 328 */ 329 private static final boolean DEFAULT_VERIFY_ENABLE = true; 330 331 /** 332 * The default maximum time to wait for the verification agent to return in 333 * milliseconds. 334 */ 335 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 336 337 /** 338 * The default response for package verification timeout. 339 * 340 * This can be either PackageManager.VERIFICATION_ALLOW or 341 * PackageManager.VERIFICATION_REJECT. 342 */ 343 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 344 345 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 346 347 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 348 DEFAULT_CONTAINER_PACKAGE, 349 "com.android.defcontainer.DefaultContainerService"); 350 351 private static final String KILL_APP_REASON_GIDS_CHANGED = 352 "permission grant or revoke changed gids"; 353 354 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 355 "permissions revoked"; 356 357 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 358 359 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 360 361 /** Permission grant: not grant the permission. */ 362 private static final int GRANT_DENIED = 1; 363 364 /** Permission grant: grant the permission as an install permission. */ 365 private static final int GRANT_INSTALL = 2; 366 367 /** Permission grant: grant the permission as a runtime one. */ 368 private static final int GRANT_RUNTIME = 3; 369 370 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 371 private static final int GRANT_UPGRADE = 4; 372 373 final ServiceThread mHandlerThread; 374 375 final PackageHandler mHandler; 376 377 /** 378 * Messages for {@link #mHandler} that need to wait for system ready before 379 * being dispatched. 380 */ 381 private ArrayList<Message> mPostSystemReadyMessages; 382 383 final int mSdkVersion = Build.VERSION.SDK_INT; 384 385 final Context mContext; 386 final boolean mFactoryTest; 387 final boolean mOnlyCore; 388 final boolean mLazyDexOpt; 389 final long mDexOptLRUThresholdInMills; 390 final DisplayMetrics mMetrics; 391 final int mDefParseFlags; 392 final String[] mSeparateProcesses; 393 final boolean mIsUpgrade; 394 395 // This is where all application persistent data goes. 396 final File mAppDataDir; 397 398 // This is where all application persistent data goes for secondary users. 399 final File mUserAppDataDir; 400 401 /** The location for ASEC container files on internal storage. */ 402 final String mAsecInternalPath; 403 404 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 405 // LOCK HELD. Can be called with mInstallLock held. 406 final Installer mInstaller; 407 408 /** Directory where installed third-party apps stored */ 409 final File mAppInstallDir; 410 411 /** 412 * Directory to which applications installed internally have their 413 * 32 bit native libraries copied. 414 */ 415 private File mAppLib32InstallDir; 416 417 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 418 // apps. 419 final File mDrmAppPrivateInstallDir; 420 421 // ---------------------------------------------------------------- 422 423 // Lock for state used when installing and doing other long running 424 // operations. Methods that must be called with this lock held have 425 // the suffix "LI". 426 final Object mInstallLock = new Object(); 427 428 // ---------------------------------------------------------------- 429 430 // Keys are String (package name), values are Package. This also serves 431 // as the lock for the global state. Methods that must be called with 432 // this lock held have the prefix "LP". 433 final ArrayMap<String, PackageParser.Package> mPackages = 434 new ArrayMap<String, PackageParser.Package>(); 435 436 // Tracks available target package names -> overlay package paths. 437 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 438 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 439 440 final Settings mSettings; 441 boolean mRestoredSettings; 442 443 // System configuration read by SystemConfig. 444 final int[] mGlobalGids; 445 final SparseArray<ArraySet<String>> mSystemPermissions; 446 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 447 448 // If mac_permissions.xml was found for seinfo labeling. 449 boolean mFoundPolicyFile; 450 451 // If a recursive restorecon of /data/data/<pkg> is needed. 452 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 453 454 public static final class SharedLibraryEntry { 455 public final String path; 456 public final String apk; 457 458 SharedLibraryEntry(String _path, String _apk) { 459 path = _path; 460 apk = _apk; 461 } 462 } 463 464 // Currently known shared libraries. 465 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 466 new ArrayMap<String, SharedLibraryEntry>(); 467 468 // All available activities, for your resolving pleasure. 469 final ActivityIntentResolver mActivities = 470 new ActivityIntentResolver(); 471 472 // All available receivers, for your resolving pleasure. 473 final ActivityIntentResolver mReceivers = 474 new ActivityIntentResolver(); 475 476 // All available services, for your resolving pleasure. 477 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 478 479 // All available providers, for your resolving pleasure. 480 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 481 482 // Mapping from provider base names (first directory in content URI codePath) 483 // to the provider information. 484 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 485 new ArrayMap<String, PackageParser.Provider>(); 486 487 // Mapping from instrumentation class names to info about them. 488 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 489 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 490 491 // Mapping from permission names to info about them. 492 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 493 new ArrayMap<String, PackageParser.PermissionGroup>(); 494 495 // Packages whose data we have transfered into another package, thus 496 // should no longer exist. 497 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 498 499 // Broadcast actions that are only available to the system. 500 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 501 502 /** List of packages waiting for verification. */ 503 final SparseArray<PackageVerificationState> mPendingVerification 504 = new SparseArray<PackageVerificationState>(); 505 506 /** Set of packages associated with each app op permission. */ 507 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 508 509 final PackageInstallerService mInstallerService; 510 511 private final PackageDexOptimizer mPackageDexOptimizer; 512 513 private AtomicInteger mNextMoveId = new AtomicInteger(); 514 private final MoveCallbacks mMoveCallbacks; 515 516 // Cache of users who need badging. 517 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 518 519 /** Token for keys in mPendingVerification. */ 520 private int mPendingVerificationToken = 0; 521 522 volatile boolean mSystemReady; 523 volatile boolean mSafeMode; 524 volatile boolean mHasSystemUidErrors; 525 526 ApplicationInfo mAndroidApplication; 527 final ActivityInfo mResolveActivity = new ActivityInfo(); 528 final ResolveInfo mResolveInfo = new ResolveInfo(); 529 ComponentName mResolveComponentName; 530 PackageParser.Package mPlatformPackage; 531 ComponentName mCustomResolverComponentName; 532 533 boolean mResolverReplaced = false; 534 535 private final ComponentName mIntentFilterVerifierComponent; 536 private int mIntentFilterVerificationToken = 0; 537 538 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 539 = new SparseArray<IntentFilterVerificationState>(); 540 541 private interface IntentFilterVerifier<T extends IntentFilter> { 542 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 543 T filter, String packageName); 544 void startVerifications(int userId); 545 void receiveVerificationResponse(int verificationId); 546 } 547 548 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 549 private Context mContext; 550 private ComponentName mIntentFilterVerifierComponent; 551 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 552 553 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 554 mContext = context; 555 mIntentFilterVerifierComponent = verifierComponent; 556 } 557 558 private String getDefaultScheme() { 559 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 560 return IntentFilter.SCHEME_HTTP; 561 } 562 563 @Override 564 public void startVerifications(int userId) { 565 // Launch verifications requests 566 int count = mCurrentIntentFilterVerifications.size(); 567 for (int n=0; n<count; n++) { 568 int verificationId = mCurrentIntentFilterVerifications.get(n); 569 final IntentFilterVerificationState ivs = 570 mIntentFilterVerificationStates.get(verificationId); 571 572 String packageName = ivs.getPackageName(); 573 574 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 575 final int filterCount = filters.size(); 576 ArraySet<String> domainsSet = new ArraySet<>(); 577 for (int m=0; m<filterCount; m++) { 578 PackageParser.ActivityIntentInfo filter = filters.get(m); 579 domainsSet.addAll(filter.getHostsList()); 580 } 581 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 582 synchronized (mPackages) { 583 if (mSettings.createIntentFilterVerificationIfNeededLPw( 584 packageName, domainsList) != null) { 585 scheduleWriteSettingsLocked(); 586 } 587 } 588 sendVerificationRequest(userId, verificationId, ivs); 589 } 590 mCurrentIntentFilterVerifications.clear(); 591 } 592 593 private void sendVerificationRequest(int userId, int verificationId, 594 IntentFilterVerificationState ivs) { 595 596 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 599 verificationId); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 602 getDefaultScheme()); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 605 ivs.getHostsString()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 608 ivs.getPackageName()); 609 verificationIntent.setComponent(mIntentFilterVerifierComponent); 610 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 611 612 UserHandle user = new UserHandle(userId); 613 mContext.sendBroadcastAsUser(verificationIntent, user); 614 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 615 } 616 617 public void receiveVerificationResponse(int verificationId) { 618 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 619 620 final boolean verified = ivs.isVerified(); 621 622 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 623 final int count = filters.size(); 624 for (int n=0; n<count; n++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(n); 626 filter.setVerified(verified); 627 628 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 629 + verified + " and hosts:" + ivs.getHostsString()); 630 } 631 632 mIntentFilterVerificationStates.remove(verificationId); 633 634 final String packageName = ivs.getPackageName(); 635 IntentFilterVerificationInfo ivi = null; 636 637 synchronized (mPackages) { 638 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 639 } 640 if (ivi == null) { 641 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 642 + verificationId + " packageName:" + packageName); 643 return; 644 } 645 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 646 + verificationId); 647 648 synchronized (mPackages) { 649 if (verified) { 650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 651 } else { 652 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 653 } 654 scheduleWriteSettingsLocked(); 655 656 final int userId = ivs.getUserId(); 657 if (userId != UserHandle.USER_ALL) { 658 final int userStatus = 659 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 660 661 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 662 boolean needUpdate = false; 663 664 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 665 // already been set by the User thru the Disambiguation dialog 666 switch (userStatus) { 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 } else { 671 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 672 } 673 needUpdate = true; 674 break; 675 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 needUpdate = true; 680 } 681 break; 682 683 default: 684 // Nothing to do 685 } 686 687 if (needUpdate) { 688 mSettings.updateIntentFilterVerificationStatusLPw( 689 packageName, updatedStatus, userId); 690 scheduleWritePackageRestrictionsLocked(userId); 691 } 692 } 693 } 694 } 695 696 @Override 697 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 698 ActivityIntentInfo filter, String packageName) { 699 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 700 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 701 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 702 return false; 703 } 704 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 705 if (ivs == null) { 706 ivs = createDomainVerificationState(verifierId, userId, verificationId, 707 packageName); 708 } 709 if (!hasValidDomains(filter)) { 710 return false; 711 } 712 ivs.addFilter(filter); 713 return true; 714 } 715 716 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 717 int userId, int verificationId, String packageName) { 718 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 719 verifierId, userId, packageName); 720 ivs.setPendingState(); 721 synchronized (mPackages) { 722 mIntentFilterVerificationStates.append(verificationId, ivs); 723 mCurrentIntentFilterVerifications.add(verificationId); 724 } 725 return ivs; 726 } 727 } 728 729 private static boolean hasValidDomains(ActivityIntentInfo filter) { 730 return hasValidDomains(filter, true); 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 734 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 735 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 736 if (!hasHTTPorHTTPS) { 737 if (logging) { 738 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 739 } 740 return false; 741 } 742 return true; 743 } 744 745 private IntentFilterVerifier mIntentFilterVerifier; 746 747 // Set of pending broadcasts for aggregating enable/disable of components. 748 static class PendingPackageBroadcasts { 749 // for each user id, a map of <package name -> components within that package> 750 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 751 752 public PendingPackageBroadcasts() { 753 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 754 } 755 756 public ArrayList<String> get(int userId, String packageName) { 757 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 758 return packages.get(packageName); 759 } 760 761 public void put(int userId, String packageName, ArrayList<String> components) { 762 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 763 packages.put(packageName, components); 764 } 765 766 public void remove(int userId, String packageName) { 767 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 768 if (packages != null) { 769 packages.remove(packageName); 770 } 771 } 772 773 public void remove(int userId) { 774 mUidMap.remove(userId); 775 } 776 777 public int userIdCount() { 778 return mUidMap.size(); 779 } 780 781 public int userIdAt(int n) { 782 return mUidMap.keyAt(n); 783 } 784 785 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 786 return mUidMap.get(userId); 787 } 788 789 public int size() { 790 // total number of pending broadcast entries across all userIds 791 int num = 0; 792 for (int i = 0; i< mUidMap.size(); i++) { 793 num += mUidMap.valueAt(i).size(); 794 } 795 return num; 796 } 797 798 public void clear() { 799 mUidMap.clear(); 800 } 801 802 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 803 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 804 if (map == null) { 805 map = new ArrayMap<String, ArrayList<String>>(); 806 mUidMap.put(userId, map); 807 } 808 return map; 809 } 810 } 811 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 812 813 // Service Connection to remote media container service to copy 814 // package uri's from external media onto secure containers 815 // or internal storage. 816 private IMediaContainerService mContainerService = null; 817 818 static final int SEND_PENDING_BROADCAST = 1; 819 static final int MCS_BOUND = 3; 820 static final int END_COPY = 4; 821 static final int INIT_COPY = 5; 822 static final int MCS_UNBIND = 6; 823 static final int START_CLEANING_PACKAGE = 7; 824 static final int FIND_INSTALL_LOC = 8; 825 static final int POST_INSTALL = 9; 826 static final int MCS_RECONNECT = 10; 827 static final int MCS_GIVE_UP = 11; 828 static final int UPDATED_MEDIA_STATUS = 12; 829 static final int WRITE_SETTINGS = 13; 830 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 831 static final int PACKAGE_VERIFIED = 15; 832 static final int CHECK_PENDING_VERIFICATION = 16; 833 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 834 static final int INTENT_FILTER_VERIFIED = 18; 835 836 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 837 838 // Delay time in millisecs 839 static final int BROADCAST_DELAY = 10 * 1000; 840 841 static UserManagerService sUserManager; 842 843 // Stores a list of users whose package restrictions file needs to be updated 844 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 845 846 final private DefaultContainerConnection mDefContainerConn = 847 new DefaultContainerConnection(); 848 class DefaultContainerConnection implements ServiceConnection { 849 public void onServiceConnected(ComponentName name, IBinder service) { 850 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 851 IMediaContainerService imcs = 852 IMediaContainerService.Stub.asInterface(service); 853 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 854 } 855 856 public void onServiceDisconnected(ComponentName name) { 857 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 858 } 859 }; 860 861 // Recordkeeping of restore-after-install operations that are currently in flight 862 // between the Package Manager and the Backup Manager 863 class PostInstallData { 864 public InstallArgs args; 865 public PackageInstalledInfo res; 866 867 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 868 args = _a; 869 res = _r; 870 } 871 }; 872 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 873 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 874 875 // backup/restore of preferred activity state 876 private static final String TAG_PREFERRED_BACKUP = "pa"; 877 878 private final String mRequiredVerifierPackage; 879 880 private final PackageUsage mPackageUsage = new PackageUsage(); 881 882 private class PackageUsage { 883 private static final int WRITE_INTERVAL 884 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 885 886 private final Object mFileLock = new Object(); 887 private final AtomicLong mLastWritten = new AtomicLong(0); 888 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 889 890 private boolean mIsHistoricalPackageUsageAvailable = true; 891 892 boolean isHistoricalPackageUsageAvailable() { 893 return mIsHistoricalPackageUsageAvailable; 894 } 895 896 void write(boolean force) { 897 if (force) { 898 writeInternal(); 899 return; 900 } 901 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 902 && !DEBUG_DEXOPT) { 903 return; 904 } 905 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 906 new Thread("PackageUsage_DiskWriter") { 907 @Override 908 public void run() { 909 try { 910 writeInternal(); 911 } finally { 912 mBackgroundWriteRunning.set(false); 913 } 914 } 915 }.start(); 916 } 917 } 918 919 private void writeInternal() { 920 synchronized (mPackages) { 921 synchronized (mFileLock) { 922 AtomicFile file = getFile(); 923 FileOutputStream f = null; 924 try { 925 f = file.startWrite(); 926 BufferedOutputStream out = new BufferedOutputStream(f); 927 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 928 StringBuilder sb = new StringBuilder(); 929 for (PackageParser.Package pkg : mPackages.values()) { 930 if (pkg.mLastPackageUsageTimeInMills == 0) { 931 continue; 932 } 933 sb.setLength(0); 934 sb.append(pkg.packageName); 935 sb.append(' '); 936 sb.append((long)pkg.mLastPackageUsageTimeInMills); 937 sb.append('\n'); 938 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 939 } 940 out.flush(); 941 file.finishWrite(f); 942 } catch (IOException e) { 943 if (f != null) { 944 file.failWrite(f); 945 } 946 Log.e(TAG, "Failed to write package usage times", e); 947 } 948 } 949 } 950 mLastWritten.set(SystemClock.elapsedRealtime()); 951 } 952 953 void readLP() { 954 synchronized (mFileLock) { 955 AtomicFile file = getFile(); 956 BufferedInputStream in = null; 957 try { 958 in = new BufferedInputStream(file.openRead()); 959 StringBuffer sb = new StringBuffer(); 960 while (true) { 961 String packageName = readToken(in, sb, ' '); 962 if (packageName == null) { 963 break; 964 } 965 String timeInMillisString = readToken(in, sb, '\n'); 966 if (timeInMillisString == null) { 967 throw new IOException("Failed to find last usage time for package " 968 + packageName); 969 } 970 PackageParser.Package pkg = mPackages.get(packageName); 971 if (pkg == null) { 972 continue; 973 } 974 long timeInMillis; 975 try { 976 timeInMillis = Long.parseLong(timeInMillisString.toString()); 977 } catch (NumberFormatException e) { 978 throw new IOException("Failed to parse " + timeInMillisString 979 + " as a long.", e); 980 } 981 pkg.mLastPackageUsageTimeInMills = timeInMillis; 982 } 983 } catch (FileNotFoundException expected) { 984 mIsHistoricalPackageUsageAvailable = false; 985 } catch (IOException e) { 986 Log.w(TAG, "Failed to read package usage times", e); 987 } finally { 988 IoUtils.closeQuietly(in); 989 } 990 } 991 mLastWritten.set(SystemClock.elapsedRealtime()); 992 } 993 994 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 995 throws IOException { 996 sb.setLength(0); 997 while (true) { 998 int ch = in.read(); 999 if (ch == -1) { 1000 if (sb.length() == 0) { 1001 return null; 1002 } 1003 throw new IOException("Unexpected EOF"); 1004 } 1005 if (ch == endOfToken) { 1006 return sb.toString(); 1007 } 1008 sb.append((char)ch); 1009 } 1010 } 1011 1012 private AtomicFile getFile() { 1013 File dataDir = Environment.getDataDirectory(); 1014 File systemDir = new File(dataDir, "system"); 1015 File fname = new File(systemDir, "package-usage.list"); 1016 return new AtomicFile(fname); 1017 } 1018 } 1019 1020 class PackageHandler extends Handler { 1021 private boolean mBound = false; 1022 final ArrayList<HandlerParams> mPendingInstalls = 1023 new ArrayList<HandlerParams>(); 1024 1025 private boolean connectToService() { 1026 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1027 " DefaultContainerService"); 1028 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1029 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1030 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1031 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1033 mBound = true; 1034 return true; 1035 } 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 return false; 1038 } 1039 1040 private void disconnectService() { 1041 mContainerService = null; 1042 mBound = false; 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1044 mContext.unbindService(mDefContainerConn); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 } 1047 1048 PackageHandler(Looper looper) { 1049 super(looper); 1050 } 1051 1052 public void handleMessage(Message msg) { 1053 try { 1054 doHandleMessage(msg); 1055 } finally { 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 } 1059 1060 void doHandleMessage(Message msg) { 1061 switch (msg.what) { 1062 case INIT_COPY: { 1063 HandlerParams params = (HandlerParams) msg.obj; 1064 int idx = mPendingInstalls.size(); 1065 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1066 // If a bind was already initiated we dont really 1067 // need to do anything. The pending install 1068 // will be processed later on. 1069 if (!mBound) { 1070 // If this is the only one pending we might 1071 // have to bind to the service again. 1072 if (!connectToService()) { 1073 Slog.e(TAG, "Failed to bind to media container service"); 1074 params.serviceError(); 1075 return; 1076 } else { 1077 // Once we bind to the service, the first 1078 // pending request will be processed. 1079 mPendingInstalls.add(idx, params); 1080 } 1081 } else { 1082 mPendingInstalls.add(idx, params); 1083 // Already bound to the service. Just make 1084 // sure we trigger off processing the first request. 1085 if (idx == 0) { 1086 mHandler.sendEmptyMessage(MCS_BOUND); 1087 } 1088 } 1089 break; 1090 } 1091 case MCS_BOUND: { 1092 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1093 if (msg.obj != null) { 1094 mContainerService = (IMediaContainerService) msg.obj; 1095 } 1096 if (mContainerService == null) { 1097 // Something seriously wrong. Bail out 1098 Slog.e(TAG, "Cannot bind to media container service"); 1099 for (HandlerParams params : mPendingInstalls) { 1100 // Indicate service bind error 1101 params.serviceError(); 1102 } 1103 mPendingInstalls.clear(); 1104 } else if (mPendingInstalls.size() > 0) { 1105 HandlerParams params = mPendingInstalls.get(0); 1106 if (params != null) { 1107 if (params.startCopy()) { 1108 // We are done... look for more work or to 1109 // go idle. 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, 1111 "Checking for more work or unbind..."); 1112 // Delete pending install 1113 if (mPendingInstalls.size() > 0) { 1114 mPendingInstalls.remove(0); 1115 } 1116 if (mPendingInstalls.size() == 0) { 1117 if (mBound) { 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Posting delayed MCS_UNBIND"); 1120 removeMessages(MCS_UNBIND); 1121 Message ubmsg = obtainMessage(MCS_UNBIND); 1122 // Unbind after a little delay, to avoid 1123 // continual thrashing. 1124 sendMessageDelayed(ubmsg, 10000); 1125 } 1126 } else { 1127 // There are more pending requests in queue. 1128 // Just post MCS_BOUND message to trigger processing 1129 // of next pending install. 1130 if (DEBUG_SD_INSTALL) Log.i(TAG, 1131 "Posting MCS_BOUND for next work"); 1132 mHandler.sendEmptyMessage(MCS_BOUND); 1133 } 1134 } 1135 } 1136 } else { 1137 // Should never happen ideally. 1138 Slog.w(TAG, "Empty queue"); 1139 } 1140 break; 1141 } 1142 case MCS_RECONNECT: { 1143 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1144 if (mPendingInstalls.size() > 0) { 1145 if (mBound) { 1146 disconnectService(); 1147 } 1148 if (!connectToService()) { 1149 Slog.e(TAG, "Failed to bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_UNBIND: { 1160 // If there is no actual work left, then time to unbind. 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1162 1163 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1164 if (mBound) { 1165 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1166 1167 disconnectService(); 1168 } 1169 } else if (mPendingInstalls.size() > 0) { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 1176 break; 1177 } 1178 case MCS_GIVE_UP: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1180 mPendingInstalls.remove(0); 1181 break; 1182 } 1183 case SEND_PENDING_BROADCAST: { 1184 String packages[]; 1185 ArrayList<String> components[]; 1186 int size = 0; 1187 int uids[]; 1188 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1189 synchronized (mPackages) { 1190 if (mPendingBroadcasts == null) { 1191 return; 1192 } 1193 size = mPendingBroadcasts.size(); 1194 if (size <= 0) { 1195 // Nothing to be done. Just return 1196 return; 1197 } 1198 packages = new String[size]; 1199 components = new ArrayList[size]; 1200 uids = new int[size]; 1201 int i = 0; // filling out the above arrays 1202 1203 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1204 int packageUserId = mPendingBroadcasts.userIdAt(n); 1205 Iterator<Map.Entry<String, ArrayList<String>>> it 1206 = mPendingBroadcasts.packagesForUserId(packageUserId) 1207 .entrySet().iterator(); 1208 while (it.hasNext() && i < size) { 1209 Map.Entry<String, ArrayList<String>> ent = it.next(); 1210 packages[i] = ent.getKey(); 1211 components[i] = ent.getValue(); 1212 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1213 uids[i] = (ps != null) 1214 ? UserHandle.getUid(packageUserId, ps.appId) 1215 : -1; 1216 i++; 1217 } 1218 } 1219 size = i; 1220 mPendingBroadcasts.clear(); 1221 } 1222 // Send broadcasts 1223 for (int i = 0; i < size; i++) { 1224 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 break; 1228 } 1229 case START_CLEANING_PACKAGE: { 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 final String packageName = (String)msg.obj; 1232 final int userId = msg.arg1; 1233 final boolean andCode = msg.arg2 != 0; 1234 synchronized (mPackages) { 1235 if (userId == UserHandle.USER_ALL) { 1236 int[] users = sUserManager.getUserIds(); 1237 for (int user : users) { 1238 mSettings.addPackageToCleanLPw( 1239 new PackageCleanItem(user, packageName, andCode)); 1240 } 1241 } else { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(userId, packageName, andCode)); 1244 } 1245 } 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 startCleaningPackages(); 1248 } break; 1249 case POST_INSTALL: { 1250 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1251 PostInstallData data = mRunningInstalls.get(msg.arg1); 1252 mRunningInstalls.delete(msg.arg1); 1253 boolean deleteOld = false; 1254 1255 if (data != null) { 1256 InstallArgs args = data.args; 1257 PackageInstalledInfo res = data.res; 1258 1259 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1260 res.removedInfo.sendBroadcast(false, true, false); 1261 Bundle extras = new Bundle(1); 1262 extras.putInt(Intent.EXTRA_UID, res.uid); 1263 1264 // Now that we successfully installed the package, grant runtime 1265 // permissions if requested before broadcasting the install. 1266 if ((args.installFlags 1267 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1268 grantRequestedRuntimePermissions(res.pkg, 1269 args.user.getIdentifier()); 1270 } 1271 1272 // Determine the set of users who are adding this 1273 // package for the first time vs. those who are seeing 1274 // an update. 1275 int[] firstUsers; 1276 int[] updateUsers = new int[0]; 1277 if (res.origUsers == null || res.origUsers.length == 0) { 1278 firstUsers = res.newUsers; 1279 } else { 1280 firstUsers = new int[0]; 1281 for (int i=0; i<res.newUsers.length; i++) { 1282 int user = res.newUsers[i]; 1283 boolean isNew = true; 1284 for (int j=0; j<res.origUsers.length; j++) { 1285 if (res.origUsers[j] == user) { 1286 isNew = false; 1287 break; 1288 } 1289 } 1290 if (isNew) { 1291 int[] newFirst = new int[firstUsers.length+1]; 1292 System.arraycopy(firstUsers, 0, newFirst, 0, 1293 firstUsers.length); 1294 newFirst[firstUsers.length] = user; 1295 firstUsers = newFirst; 1296 } else { 1297 int[] newUpdate = new int[updateUsers.length+1]; 1298 System.arraycopy(updateUsers, 0, newUpdate, 0, 1299 updateUsers.length); 1300 newUpdate[updateUsers.length] = user; 1301 updateUsers = newUpdate; 1302 } 1303 } 1304 } 1305 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1306 res.pkg.applicationInfo.packageName, 1307 extras, null, null, firstUsers); 1308 final boolean update = res.removedInfo.removedPackage != null; 1309 if (update) { 1310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1311 } 1312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1313 res.pkg.applicationInfo.packageName, 1314 extras, null, null, updateUsers); 1315 if (update) { 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1320 null, null, 1321 res.pkg.applicationInfo.packageName, null, updateUsers); 1322 1323 // treat asec-hosted packages like removable media on upgrade 1324 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1325 if (DEBUG_INSTALL) { 1326 Slog.i(TAG, "upgrading pkg " + res.pkg 1327 + " is ASEC-hosted -> AVAILABLE"); 1328 } 1329 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1330 ArrayList<String> pkgList = new ArrayList<String>(1); 1331 pkgList.add(res.pkg.applicationInfo.packageName); 1332 sendResourcesChangedBroadcast(true, true, 1333 pkgList,uidArray, null); 1334 } 1335 } 1336 if (res.removedInfo.args != null) { 1337 // Remove the replaced package's older resources safely now 1338 deleteOld = true; 1339 } 1340 1341 // Log current value of "unknown sources" setting 1342 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1343 getUnknownSourcesSettings()); 1344 } 1345 // Force a gc to clear up things 1346 Runtime.getRuntime().gc(); 1347 // We delete after a gc for applications on sdcard. 1348 if (deleteOld) { 1349 synchronized (mInstallLock) { 1350 res.removedInfo.args.doPostDeleteLI(true); 1351 } 1352 } 1353 if (args.observer != null) { 1354 try { 1355 Bundle extras = extrasForInstallResult(res); 1356 args.observer.onPackageInstalled(res.name, res.returnCode, 1357 res.returnMsg, extras); 1358 } catch (RemoteException e) { 1359 Slog.i(TAG, "Observer no longer exists."); 1360 } 1361 } 1362 } else { 1363 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1364 } 1365 } break; 1366 case UPDATED_MEDIA_STATUS: { 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1368 boolean reportStatus = msg.arg1 == 1; 1369 boolean doGc = msg.arg2 == 1; 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1371 if (doGc) { 1372 // Force a gc to clear up stale containers. 1373 Runtime.getRuntime().gc(); 1374 } 1375 if (msg.obj != null) { 1376 @SuppressWarnings("unchecked") 1377 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1379 // Unload containers 1380 unloadAllContainers(args); 1381 } 1382 if (reportStatus) { 1383 try { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1385 PackageHelper.getMountService().finishMediaUpdate(); 1386 } catch (RemoteException e) { 1387 Log.e(TAG, "MountService not running?"); 1388 } 1389 } 1390 } break; 1391 case WRITE_SETTINGS: { 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1393 synchronized (mPackages) { 1394 removeMessages(WRITE_SETTINGS); 1395 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1396 mSettings.writeLPr(); 1397 mDirtyUsers.clear(); 1398 } 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } break; 1401 case WRITE_PACKAGE_RESTRICTIONS: { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1403 synchronized (mPackages) { 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 for (int userId : mDirtyUsers) { 1406 mSettings.writePackageRestrictionsLPr(userId); 1407 } 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case CHECK_PENDING_VERIFICATION: { 1413 final int verificationId = msg.arg1; 1414 final PackageVerificationState state = mPendingVerification.get(verificationId); 1415 1416 if ((state != null) && !state.timeoutExtended()) { 1417 final InstallArgs args = state.getInstallArgs(); 1418 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1419 1420 Slog.i(TAG, "Verification timed out for " + originUri); 1421 mPendingVerification.remove(verificationId); 1422 1423 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1424 1425 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1426 Slog.i(TAG, "Continuing with installation of " + originUri); 1427 state.setVerifierResponse(Binder.getCallingUid(), 1428 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1429 broadcastPackageVerified(verificationId, originUri, 1430 PackageManager.VERIFICATION_ALLOW, 1431 state.getInstallArgs().getUser()); 1432 try { 1433 ret = args.copyApk(mContainerService, true); 1434 } catch (RemoteException e) { 1435 Slog.e(TAG, "Could not contact the ContainerService"); 1436 } 1437 } else { 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_REJECT, 1440 state.getInstallArgs().getUser()); 1441 } 1442 1443 processPendingInstall(args, ret); 1444 mHandler.sendEmptyMessage(MCS_UNBIND); 1445 } 1446 break; 1447 } 1448 case PACKAGE_VERIFIED: { 1449 final int verificationId = msg.arg1; 1450 1451 final PackageVerificationState state = mPendingVerification.get(verificationId); 1452 if (state == null) { 1453 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1454 break; 1455 } 1456 1457 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1458 1459 state.setVerifierResponse(response.callerUid, response.code); 1460 1461 if (state.isVerificationComplete()) { 1462 mPendingVerification.remove(verificationId); 1463 1464 final InstallArgs args = state.getInstallArgs(); 1465 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1466 1467 int ret; 1468 if (state.isInstallAllowed()) { 1469 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1470 broadcastPackageVerified(verificationId, originUri, 1471 response.code, state.getInstallArgs().getUser()); 1472 try { 1473 ret = args.copyApk(mContainerService, true); 1474 } catch (RemoteException e) { 1475 Slog.e(TAG, "Could not contact the ContainerService"); 1476 } 1477 } else { 1478 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1479 } 1480 1481 processPendingInstall(args, ret); 1482 1483 mHandler.sendEmptyMessage(MCS_UNBIND); 1484 } 1485 1486 break; 1487 } 1488 case START_INTENT_FILTER_VERIFICATIONS: { 1489 int userId = msg.arg1; 1490 int verifierUid = msg.arg2; 1491 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1492 1493 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1494 break; 1495 } 1496 case INTENT_FILTER_VERIFIED: { 1497 final int verificationId = msg.arg1; 1498 1499 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1500 verificationId); 1501 if (state == null) { 1502 Slog.w(TAG, "Invalid IntentFilter verification token " 1503 + verificationId + " received"); 1504 break; 1505 } 1506 1507 final int userId = state.getUserId(); 1508 1509 Slog.d(TAG, "Processing IntentFilter verification with token:" 1510 + verificationId + " and userId:" + userId); 1511 1512 final IntentFilterVerificationResponse response = 1513 (IntentFilterVerificationResponse) msg.obj; 1514 1515 state.setVerifierResponse(response.callerUid, response.code); 1516 1517 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1518 + " and userId:" + userId 1519 + " is settings verifier response with response code:" 1520 + response.code); 1521 1522 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1523 Slog.d(TAG, "Domains failing verification: " 1524 + response.getFailedDomainsString()); 1525 } 1526 1527 if (state.isVerificationComplete()) { 1528 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1529 } else { 1530 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1531 + " was not said to be complete"); 1532 } 1533 1534 break; 1535 } 1536 } 1537 } 1538 } 1539 1540 private StorageEventListener mStorageListener = new StorageEventListener() { 1541 @Override 1542 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1543 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1544 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1545 // TODO: ensure that private directories exist for all active users 1546 // TODO: remove user data whose serial number doesn't match 1547 loadPrivatePackages(vol); 1548 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1549 unloadPrivatePackages(vol); 1550 } 1551 } 1552 1553 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1554 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1555 updateExternalMediaStatus(true, false); 1556 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1557 updateExternalMediaStatus(false, false); 1558 } 1559 } 1560 } 1561 }; 1562 1563 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1564 if (userId >= UserHandle.USER_OWNER) { 1565 grantRequestedRuntimePermissionsForUser(pkg, userId); 1566 } else if (userId == UserHandle.USER_ALL) { 1567 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1568 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1569 } 1570 } 1571 } 1572 1573 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1574 SettingBase sb = (SettingBase) pkg.mExtras; 1575 if (sb == null) { 1576 return; 1577 } 1578 1579 PermissionsState permissionsState = sb.getPermissionsState(); 1580 1581 for (String permission : pkg.requestedPermissions) { 1582 BasePermission bp = mSettings.mPermissions.get(permission); 1583 if (bp != null && bp.isRuntime()) { 1584 permissionsState.grantRuntimePermission(bp, userId); 1585 } 1586 } 1587 } 1588 1589 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1590 Bundle extras = null; 1591 switch (res.returnCode) { 1592 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1593 extras = new Bundle(); 1594 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1595 res.origPermission); 1596 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1597 res.origPackage); 1598 break; 1599 } 1600 } 1601 return extras; 1602 } 1603 1604 void scheduleWriteSettingsLocked() { 1605 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1606 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1607 } 1608 } 1609 1610 void scheduleWritePackageRestrictionsLocked(int userId) { 1611 if (!sUserManager.exists(userId)) return; 1612 mDirtyUsers.add(userId); 1613 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1614 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1615 } 1616 } 1617 1618 public static PackageManagerService main(Context context, Installer installer, 1619 boolean factoryTest, boolean onlyCore) { 1620 PackageManagerService m = new PackageManagerService(context, installer, 1621 factoryTest, onlyCore); 1622 ServiceManager.addService("package", m); 1623 return m; 1624 } 1625 1626 static String[] splitString(String str, char sep) { 1627 int count = 1; 1628 int i = 0; 1629 while ((i=str.indexOf(sep, i)) >= 0) { 1630 count++; 1631 i++; 1632 } 1633 1634 String[] res = new String[count]; 1635 i=0; 1636 count = 0; 1637 int lastI=0; 1638 while ((i=str.indexOf(sep, i)) >= 0) { 1639 res[count] = str.substring(lastI, i); 1640 count++; 1641 i++; 1642 lastI = i; 1643 } 1644 res[count] = str.substring(lastI, str.length()); 1645 return res; 1646 } 1647 1648 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1649 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1650 Context.DISPLAY_SERVICE); 1651 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1652 } 1653 1654 public PackageManagerService(Context context, Installer installer, 1655 boolean factoryTest, boolean onlyCore) { 1656 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1657 SystemClock.uptimeMillis()); 1658 1659 if (mSdkVersion <= 0) { 1660 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1661 } 1662 1663 mContext = context; 1664 mFactoryTest = factoryTest; 1665 mOnlyCore = onlyCore; 1666 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1667 mMetrics = new DisplayMetrics(); 1668 mSettings = new Settings(mPackages); 1669 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1670 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1671 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1674 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1675 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1676 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1677 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 1682 // TODO: add a property to control this? 1683 long dexOptLRUThresholdInMinutes; 1684 if (mLazyDexOpt) { 1685 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1686 } else { 1687 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1688 } 1689 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1690 1691 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1692 if (separateProcesses != null && separateProcesses.length() > 0) { 1693 if ("*".equals(separateProcesses)) { 1694 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1695 mSeparateProcesses = null; 1696 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1697 } else { 1698 mDefParseFlags = 0; 1699 mSeparateProcesses = separateProcesses.split(","); 1700 Slog.w(TAG, "Running with debug.separate_processes: " 1701 + separateProcesses); 1702 } 1703 } else { 1704 mDefParseFlags = 0; 1705 mSeparateProcesses = null; 1706 } 1707 1708 mInstaller = installer; 1709 mPackageDexOptimizer = new PackageDexOptimizer(this); 1710 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1711 1712 getDefaultDisplayMetrics(context, mMetrics); 1713 1714 SystemConfig systemConfig = SystemConfig.getInstance(); 1715 mGlobalGids = systemConfig.getGlobalGids(); 1716 mSystemPermissions = systemConfig.getSystemPermissions(); 1717 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1718 1719 synchronized (mInstallLock) { 1720 // writer 1721 synchronized (mPackages) { 1722 mHandlerThread = new ServiceThread(TAG, 1723 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1724 mHandlerThread.start(); 1725 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1726 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1727 1728 File dataDir = Environment.getDataDirectory(); 1729 mAppDataDir = new File(dataDir, "data"); 1730 mAppInstallDir = new File(dataDir, "app"); 1731 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1732 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1733 mUserAppDataDir = new File(dataDir, "user"); 1734 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1735 1736 sUserManager = new UserManagerService(context, this, 1737 mInstallLock, mPackages); 1738 1739 // Propagate permission configuration in to package manager. 1740 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1741 = systemConfig.getPermissions(); 1742 for (int i=0; i<permConfig.size(); i++) { 1743 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1744 BasePermission bp = mSettings.mPermissions.get(perm.name); 1745 if (bp == null) { 1746 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1747 mSettings.mPermissions.put(perm.name, bp); 1748 } 1749 if (perm.gids != null) { 1750 bp.setGids(perm.gids, perm.perUser); 1751 } 1752 } 1753 1754 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1755 for (int i=0; i<libConfig.size(); i++) { 1756 mSharedLibraries.put(libConfig.keyAt(i), 1757 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1758 } 1759 1760 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1761 1762 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1763 mSdkVersion, mOnlyCore); 1764 1765 String customResolverActivity = Resources.getSystem().getString( 1766 R.string.config_customResolverActivity); 1767 if (TextUtils.isEmpty(customResolverActivity)) { 1768 customResolverActivity = null; 1769 } else { 1770 mCustomResolverComponentName = ComponentName.unflattenFromString( 1771 customResolverActivity); 1772 } 1773 1774 long startTime = SystemClock.uptimeMillis(); 1775 1776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1777 startTime); 1778 1779 // Set flag to monitor and not change apk file paths when 1780 // scanning install directories. 1781 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1782 1783 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1784 1785 /** 1786 * Add everything in the in the boot class path to the 1787 * list of process files because dexopt will have been run 1788 * if necessary during zygote startup. 1789 */ 1790 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1791 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1792 1793 if (bootClassPath != null) { 1794 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1795 for (String element : bootClassPathElements) { 1796 alreadyDexOpted.add(element); 1797 } 1798 } else { 1799 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1800 } 1801 1802 if (systemServerClassPath != null) { 1803 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1804 for (String element : systemServerClassPathElements) { 1805 alreadyDexOpted.add(element); 1806 } 1807 } else { 1808 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1809 } 1810 1811 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1812 final String[] dexCodeInstructionSets = 1813 getDexCodeInstructionSets( 1814 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1815 1816 /** 1817 * Ensure all external libraries have had dexopt run on them. 1818 */ 1819 if (mSharedLibraries.size() > 0) { 1820 // NOTE: For now, we're compiling these system "shared libraries" 1821 // (and framework jars) into all available architectures. It's possible 1822 // to compile them only when we come across an app that uses them (there's 1823 // already logic for that in scanPackageLI) but that adds some complexity. 1824 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1825 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1826 final String lib = libEntry.path; 1827 if (lib == null) { 1828 continue; 1829 } 1830 1831 try { 1832 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1833 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1834 alreadyDexOpted.add(lib); 1835 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1836 } 1837 } catch (FileNotFoundException e) { 1838 Slog.w(TAG, "Library not found: " + lib); 1839 } catch (IOException e) { 1840 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1841 + e.getMessage()); 1842 } 1843 } 1844 } 1845 } 1846 1847 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1848 1849 // Gross hack for now: we know this file doesn't contain any 1850 // code, so don't dexopt it to avoid the resulting log spew. 1851 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1852 1853 // Gross hack for now: we know this file is only part of 1854 // the boot class path for art, so don't dexopt it to 1855 // avoid the resulting log spew. 1856 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1857 1858 /** 1859 * And there are a number of commands implemented in Java, which 1860 * we currently need to do the dexopt on so that they can be 1861 * run from a non-root shell. 1862 */ 1863 String[] frameworkFiles = frameworkDir.list(); 1864 if (frameworkFiles != null) { 1865 // TODO: We could compile these only for the most preferred ABI. We should 1866 // first double check that the dex files for these commands are not referenced 1867 // by other system apps. 1868 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1869 for (int i=0; i<frameworkFiles.length; i++) { 1870 File libPath = new File(frameworkDir, frameworkFiles[i]); 1871 String path = libPath.getPath(); 1872 // Skip the file if we already did it. 1873 if (alreadyDexOpted.contains(path)) { 1874 continue; 1875 } 1876 // Skip the file if it is not a type we want to dexopt. 1877 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1878 continue; 1879 } 1880 try { 1881 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1882 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1883 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1884 } 1885 } catch (FileNotFoundException e) { 1886 Slog.w(TAG, "Jar not found: " + path); 1887 } catch (IOException e) { 1888 Slog.w(TAG, "Exception reading jar: " + path, e); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Collect vendor overlay packages. 1895 // (Do this before scanning any apps.) 1896 // For security and version matching reason, only consider 1897 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1898 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1899 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1900 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1901 1902 // Find base frameworks (resource packages without code). 1903 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1904 | PackageParser.PARSE_IS_SYSTEM_DIR 1905 | PackageParser.PARSE_IS_PRIVILEGED, 1906 scanFlags | SCAN_NO_DEX, 0); 1907 1908 // Collected privileged system packages. 1909 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1910 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1911 | PackageParser.PARSE_IS_SYSTEM_DIR 1912 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1913 1914 // Collect ordinary system packages. 1915 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1916 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1918 1919 // Collect all vendor packages. 1920 File vendorAppDir = new File("/vendor/app"); 1921 try { 1922 vendorAppDir = vendorAppDir.getCanonicalFile(); 1923 } catch (IOException e) { 1924 // failed to look up canonical path, continue with original one 1925 } 1926 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1927 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1928 1929 // Collect all OEM packages. 1930 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1931 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1935 mInstaller.moveFiles(); 1936 1937 // Prune any system packages that no longer exist. 1938 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1939 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1940 if (!mOnlyCore) { 1941 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1942 while (psit.hasNext()) { 1943 PackageSetting ps = psit.next(); 1944 1945 /* 1946 * If this is not a system app, it can't be a 1947 * disable system app. 1948 */ 1949 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1950 continue; 1951 } 1952 1953 /* 1954 * If the package is scanned, it's not erased. 1955 */ 1956 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1957 if (scannedPkg != null) { 1958 /* 1959 * If the system app is both scanned and in the 1960 * disabled packages list, then it must have been 1961 * added via OTA. Remove it from the currently 1962 * scanned package so the previously user-installed 1963 * application can be scanned. 1964 */ 1965 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1966 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1967 + ps.name + "; removing system app. Last known codePath=" 1968 + ps.codePathString + ", installStatus=" + ps.installStatus 1969 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1970 + scannedPkg.mVersionCode); 1971 removePackageLI(ps, true); 1972 expectingBetter.put(ps.name, ps.codePath); 1973 } 1974 1975 continue; 1976 } 1977 1978 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1979 psit.remove(); 1980 logCriticalInfo(Log.WARN, "System package " + ps.name 1981 + " no longer exists; wiping its data"); 1982 removeDataDirsLI(null, ps.name); 1983 } else { 1984 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1985 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1986 possiblyDeletedUpdatedSystemApps.add(ps.name); 1987 } 1988 } 1989 } 1990 } 1991 1992 //look for any incomplete package installations 1993 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1994 //clean up list 1995 for(int i = 0; i < deletePkgsList.size(); i++) { 1996 //clean up here 1997 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1998 } 1999 //delete tmp files 2000 deleteTempPackageFiles(); 2001 2002 // Remove any shared userIDs that have no associated packages 2003 mSettings.pruneSharedUsersLPw(); 2004 2005 if (!mOnlyCore) { 2006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2007 SystemClock.uptimeMillis()); 2008 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2009 2010 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2011 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2012 2013 /** 2014 * Remove disable package settings for any updated system 2015 * apps that were removed via an OTA. If they're not a 2016 * previously-updated app, remove them completely. 2017 * Otherwise, just revoke their system-level permissions. 2018 */ 2019 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2020 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2021 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2022 2023 String msg; 2024 if (deletedPkg == null) { 2025 msg = "Updated system package " + deletedAppName 2026 + " no longer exists; wiping its data"; 2027 removeDataDirsLI(null, deletedAppName); 2028 } else { 2029 msg = "Updated system app + " + deletedAppName 2030 + " no longer present; removing system privileges for " 2031 + deletedAppName; 2032 2033 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2034 2035 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2036 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2037 } 2038 logCriticalInfo(Log.WARN, msg); 2039 } 2040 2041 /** 2042 * Make sure all system apps that we expected to appear on 2043 * the userdata partition actually showed up. If they never 2044 * appeared, crawl back and revive the system version. 2045 */ 2046 for (int i = 0; i < expectingBetter.size(); i++) { 2047 final String packageName = expectingBetter.keyAt(i); 2048 if (!mPackages.containsKey(packageName)) { 2049 final File scanFile = expectingBetter.valueAt(i); 2050 2051 logCriticalInfo(Log.WARN, "Expected better " + packageName 2052 + " but never showed up; reverting to system"); 2053 2054 final int reparseFlags; 2055 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2056 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2057 | PackageParser.PARSE_IS_SYSTEM_DIR 2058 | PackageParser.PARSE_IS_PRIVILEGED; 2059 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2060 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR; 2062 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2063 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR; 2065 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2066 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR; 2068 } else { 2069 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2070 continue; 2071 } 2072 2073 mSettings.enableSystemPackageLPw(packageName); 2074 2075 try { 2076 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2077 } catch (PackageManagerException e) { 2078 Slog.e(TAG, "Failed to parse original system package: " 2079 + e.getMessage()); 2080 } 2081 } 2082 } 2083 } 2084 2085 // Now that we know all of the shared libraries, update all clients to have 2086 // the correct library paths. 2087 updateAllSharedLibrariesLPw(); 2088 2089 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2090 // NOTE: We ignore potential failures here during a system scan (like 2091 // the rest of the commands above) because there's precious little we 2092 // can do about it. A settings error is reported, though. 2093 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2094 false /* force dexopt */, false /* defer dexopt */); 2095 } 2096 2097 // Now that we know all the packages we are keeping, 2098 // read and update their last usage times. 2099 mPackageUsage.readLP(); 2100 2101 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2102 SystemClock.uptimeMillis()); 2103 Slog.i(TAG, "Time to scan packages: " 2104 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2105 + " seconds"); 2106 2107 // If the platform SDK has changed since the last time we booted, 2108 // we need to re-grant app permission to catch any new ones that 2109 // appear. This is really a hack, and means that apps can in some 2110 // cases get permissions that the user didn't initially explicitly 2111 // allow... it would be nice to have some better way to handle 2112 // this situation. 2113 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2114 != mSdkVersion; 2115 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2116 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2117 + "; regranting permissions for internal storage"); 2118 mSettings.mInternalSdkPlatform = mSdkVersion; 2119 2120 // For now runtime permissions are toggled via a system property. 2121 if (!RUNTIME_PERMISSIONS_ENABLED) { 2122 // Remove the runtime permissions state if the feature 2123 // was disabled by flipping the system property. 2124 mSettings.deleteRuntimePermissionsFiles(); 2125 } 2126 2127 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2128 | (regrantPermissions 2129 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2130 : 0)); 2131 2132 // If this is the first boot, and it is a normal boot, then 2133 // we need to initialize the default preferred apps. 2134 if (!mRestoredSettings && !onlyCore) { 2135 mSettings.readDefaultPreferredAppsLPw(this, 0); 2136 } 2137 2138 // If this is first boot after an OTA, and a normal boot, then 2139 // we need to clear code cache directories. 2140 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2141 if (mIsUpgrade && !onlyCore) { 2142 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2143 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2144 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2145 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2146 } 2147 mSettings.mFingerprint = Build.FINGERPRINT; 2148 } 2149 2150 // All the changes are done during package scanning. 2151 mSettings.updateInternalDatabaseVersion(); 2152 2153 // can downgrade to reader 2154 mSettings.writeLPr(); 2155 2156 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2157 SystemClock.uptimeMillis()); 2158 2159 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2160 2161 mInstallerService = new PackageInstallerService(context, this); 2162 2163 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2164 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2165 mIntentFilterVerifierComponent); 2166 2167 primeDomainVerificationsLPw(false); 2168 2169 } // synchronized (mPackages) 2170 } // synchronized (mInstallLock) 2171 2172 // Now after opening every single application zip, make sure they 2173 // are all flushed. Not really needed, but keeps things nice and 2174 // tidy. 2175 Runtime.getRuntime().gc(); 2176 } 2177 2178 @Override 2179 public boolean isFirstBoot() { 2180 return !mRestoredSettings; 2181 } 2182 2183 @Override 2184 public boolean isOnlyCoreApps() { 2185 return mOnlyCore; 2186 } 2187 2188 @Override 2189 public boolean isUpgrade() { 2190 return mIsUpgrade; 2191 } 2192 2193 private String getRequiredVerifierLPr() { 2194 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2195 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2196 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2197 2198 String requiredVerifier = null; 2199 2200 final int N = receivers.size(); 2201 for (int i = 0; i < N; i++) { 2202 final ResolveInfo info = receivers.get(i); 2203 2204 if (info.activityInfo == null) { 2205 continue; 2206 } 2207 2208 final String packageName = info.activityInfo.packageName; 2209 2210 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2211 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2212 continue; 2213 } 2214 2215 if (requiredVerifier != null) { 2216 throw new RuntimeException("There can be only one required verifier"); 2217 } 2218 2219 requiredVerifier = packageName; 2220 } 2221 2222 return requiredVerifier; 2223 } 2224 2225 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2226 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2227 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2228 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2229 2230 ComponentName verifierComponentName = null; 2231 2232 int priority = -1000; 2233 final int N = receivers.size(); 2234 for (int i = 0; i < N; i++) { 2235 final ResolveInfo info = receivers.get(i); 2236 2237 if (info.activityInfo == null) { 2238 continue; 2239 } 2240 2241 final String packageName = info.activityInfo.packageName; 2242 2243 final PackageSetting ps = mSettings.mPackages.get(packageName); 2244 if (ps == null) { 2245 continue; 2246 } 2247 2248 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2249 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2250 continue; 2251 } 2252 2253 // Select the IntentFilterVerifier with the highest priority 2254 if (priority < info.priority) { 2255 priority = info.priority; 2256 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2257 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2258 " with priority: " + info.priority); 2259 } 2260 } 2261 2262 return verifierComponentName; 2263 } 2264 2265 private void primeDomainVerificationsLPw(boolean logging) { 2266 Slog.d(TAG, "Start priming domain verification"); 2267 boolean updated = false; 2268 ArrayList<String> allHosts = new ArrayList<>(); 2269 for (PackageParser.Package pkg : mPackages.values()) { 2270 final String packageName = pkg.packageName; 2271 if (!hasDomainURLs(pkg)) { 2272 if (logging) { 2273 Slog.d(TAG, "No priming domain verifications for " + 2274 "package with no domain URLs: " + packageName); 2275 } 2276 continue; 2277 } 2278 if (!pkg.isSystemApp()) { 2279 if (logging) { 2280 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2281 packageName); 2282 } 2283 continue; 2284 } 2285 for (PackageParser.Activity a : pkg.activities) { 2286 for (ActivityIntentInfo filter : a.intents) { 2287 if (hasValidDomains(filter, false)) { 2288 allHosts.addAll(filter.getHostsList()); 2289 } 2290 } 2291 } 2292 if (allHosts.size() == 0) { 2293 allHosts.add("*"); 2294 } 2295 IntentFilterVerificationInfo ivi = 2296 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2297 if (ivi != null) { 2298 // We will always log this 2299 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2300 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2301 updated = true; 2302 } 2303 else { 2304 if (logging) { 2305 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2306 } 2307 } 2308 allHosts.clear(); 2309 } 2310 if (updated) { 2311 scheduleWriteSettingsLocked(); 2312 } 2313 Slog.d(TAG, "End priming domain verification"); 2314 } 2315 2316 @Override 2317 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2318 throws RemoteException { 2319 try { 2320 return super.onTransact(code, data, reply, flags); 2321 } catch (RuntimeException e) { 2322 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2323 Slog.wtf(TAG, "Package Manager Crash", e); 2324 } 2325 throw e; 2326 } 2327 } 2328 2329 void cleanupInstallFailedPackage(PackageSetting ps) { 2330 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2331 2332 removeDataDirsLI(ps.volumeUuid, ps.name); 2333 if (ps.codePath != null) { 2334 if (ps.codePath.isDirectory()) { 2335 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2336 } else { 2337 ps.codePath.delete(); 2338 } 2339 } 2340 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2341 if (ps.resourcePath.isDirectory()) { 2342 FileUtils.deleteContents(ps.resourcePath); 2343 } 2344 ps.resourcePath.delete(); 2345 } 2346 mSettings.removePackageLPw(ps.name); 2347 } 2348 2349 static int[] appendInts(int[] cur, int[] add) { 2350 if (add == null) return cur; 2351 if (cur == null) return add; 2352 final int N = add.length; 2353 for (int i=0; i<N; i++) { 2354 cur = appendInt(cur, add[i]); 2355 } 2356 return cur; 2357 } 2358 2359 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2360 if (!sUserManager.exists(userId)) return null; 2361 final PackageSetting ps = (PackageSetting) p.mExtras; 2362 if (ps == null) { 2363 return null; 2364 } 2365 2366 final PermissionsState permissionsState = ps.getPermissionsState(); 2367 2368 final int[] gids = permissionsState.computeGids(userId); 2369 final Set<String> permissions = permissionsState.getPermissions(userId); 2370 final PackageUserState state = ps.readUserState(userId); 2371 2372 return PackageParser.generatePackageInfo(p, gids, flags, 2373 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2374 } 2375 2376 @Override 2377 public boolean isPackageAvailable(String packageName, int userId) { 2378 if (!sUserManager.exists(userId)) return false; 2379 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2380 synchronized (mPackages) { 2381 PackageParser.Package p = mPackages.get(packageName); 2382 if (p != null) { 2383 final PackageSetting ps = (PackageSetting) p.mExtras; 2384 if (ps != null) { 2385 final PackageUserState state = ps.readUserState(userId); 2386 if (state != null) { 2387 return PackageParser.isAvailable(state); 2388 } 2389 } 2390 } 2391 } 2392 return false; 2393 } 2394 2395 @Override 2396 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2397 if (!sUserManager.exists(userId)) return null; 2398 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2399 // reader 2400 synchronized (mPackages) { 2401 PackageParser.Package p = mPackages.get(packageName); 2402 if (DEBUG_PACKAGE_INFO) 2403 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2404 if (p != null) { 2405 return generatePackageInfo(p, flags, userId); 2406 } 2407 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2408 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2409 } 2410 } 2411 return null; 2412 } 2413 2414 @Override 2415 public String[] currentToCanonicalPackageNames(String[] names) { 2416 String[] out = new String[names.length]; 2417 // reader 2418 synchronized (mPackages) { 2419 for (int i=names.length-1; i>=0; i--) { 2420 PackageSetting ps = mSettings.mPackages.get(names[i]); 2421 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2422 } 2423 } 2424 return out; 2425 } 2426 2427 @Override 2428 public String[] canonicalToCurrentPackageNames(String[] names) { 2429 String[] out = new String[names.length]; 2430 // reader 2431 synchronized (mPackages) { 2432 for (int i=names.length-1; i>=0; i--) { 2433 String cur = mSettings.mRenamedPackages.get(names[i]); 2434 out[i] = cur != null ? cur : names[i]; 2435 } 2436 } 2437 return out; 2438 } 2439 2440 @Override 2441 public int getPackageUid(String packageName, int userId) { 2442 if (!sUserManager.exists(userId)) return -1; 2443 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2444 2445 // reader 2446 synchronized (mPackages) { 2447 PackageParser.Package p = mPackages.get(packageName); 2448 if(p != null) { 2449 return UserHandle.getUid(userId, p.applicationInfo.uid); 2450 } 2451 PackageSetting ps = mSettings.mPackages.get(packageName); 2452 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2453 return -1; 2454 } 2455 p = ps.pkg; 2456 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2457 } 2458 } 2459 2460 @Override 2461 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2462 if (!sUserManager.exists(userId)) { 2463 return null; 2464 } 2465 2466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2467 "getPackageGids"); 2468 2469 // reader 2470 synchronized (mPackages) { 2471 PackageParser.Package p = mPackages.get(packageName); 2472 if (DEBUG_PACKAGE_INFO) { 2473 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2474 } 2475 if (p != null) { 2476 PackageSetting ps = (PackageSetting) p.mExtras; 2477 return ps.getPermissionsState().computeGids(userId); 2478 } 2479 } 2480 2481 return null; 2482 } 2483 2484 static PermissionInfo generatePermissionInfo( 2485 BasePermission bp, int flags) { 2486 if (bp.perm != null) { 2487 return PackageParser.generatePermissionInfo(bp.perm, flags); 2488 } 2489 PermissionInfo pi = new PermissionInfo(); 2490 pi.name = bp.name; 2491 pi.packageName = bp.sourcePackage; 2492 pi.nonLocalizedLabel = bp.name; 2493 pi.protectionLevel = bp.protectionLevel; 2494 return pi; 2495 } 2496 2497 @Override 2498 public PermissionInfo getPermissionInfo(String name, int flags) { 2499 // reader 2500 synchronized (mPackages) { 2501 final BasePermission p = mSettings.mPermissions.get(name); 2502 if (p != null) { 2503 return generatePermissionInfo(p, flags); 2504 } 2505 return null; 2506 } 2507 } 2508 2509 @Override 2510 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2511 // reader 2512 synchronized (mPackages) { 2513 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2514 for (BasePermission p : mSettings.mPermissions.values()) { 2515 if (group == null) { 2516 if (p.perm == null || p.perm.info.group == null) { 2517 out.add(generatePermissionInfo(p, flags)); 2518 } 2519 } else { 2520 if (p.perm != null && group.equals(p.perm.info.group)) { 2521 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2522 } 2523 } 2524 } 2525 2526 if (out.size() > 0) { 2527 return out; 2528 } 2529 return mPermissionGroups.containsKey(group) ? out : null; 2530 } 2531 } 2532 2533 @Override 2534 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2535 // reader 2536 synchronized (mPackages) { 2537 return PackageParser.generatePermissionGroupInfo( 2538 mPermissionGroups.get(name), flags); 2539 } 2540 } 2541 2542 @Override 2543 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2544 // reader 2545 synchronized (mPackages) { 2546 final int N = mPermissionGroups.size(); 2547 ArrayList<PermissionGroupInfo> out 2548 = new ArrayList<PermissionGroupInfo>(N); 2549 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2550 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2551 } 2552 return out; 2553 } 2554 } 2555 2556 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2557 int userId) { 2558 if (!sUserManager.exists(userId)) return null; 2559 PackageSetting ps = mSettings.mPackages.get(packageName); 2560 if (ps != null) { 2561 if (ps.pkg == null) { 2562 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2563 flags, userId); 2564 if (pInfo != null) { 2565 return pInfo.applicationInfo; 2566 } 2567 return null; 2568 } 2569 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2570 ps.readUserState(userId), userId); 2571 } 2572 return null; 2573 } 2574 2575 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2576 int userId) { 2577 if (!sUserManager.exists(userId)) return null; 2578 PackageSetting ps = mSettings.mPackages.get(packageName); 2579 if (ps != null) { 2580 PackageParser.Package pkg = ps.pkg; 2581 if (pkg == null) { 2582 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2583 return null; 2584 } 2585 // Only data remains, so we aren't worried about code paths 2586 pkg = new PackageParser.Package(packageName); 2587 pkg.applicationInfo.packageName = packageName; 2588 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2589 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2590 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2591 packageName, userId).getAbsolutePath(); 2592 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2593 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2594 } 2595 return generatePackageInfo(pkg, flags, userId); 2596 } 2597 return null; 2598 } 2599 2600 @Override 2601 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2602 if (!sUserManager.exists(userId)) return null; 2603 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2604 // writer 2605 synchronized (mPackages) { 2606 PackageParser.Package p = mPackages.get(packageName); 2607 if (DEBUG_PACKAGE_INFO) Log.v( 2608 TAG, "getApplicationInfo " + packageName 2609 + ": " + p); 2610 if (p != null) { 2611 PackageSetting ps = mSettings.mPackages.get(packageName); 2612 if (ps == null) return null; 2613 // Note: isEnabledLP() does not apply here - always return info 2614 return PackageParser.generateApplicationInfo( 2615 p, flags, ps.readUserState(userId), userId); 2616 } 2617 if ("android".equals(packageName)||"system".equals(packageName)) { 2618 return mAndroidApplication; 2619 } 2620 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2621 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2622 } 2623 } 2624 return null; 2625 } 2626 2627 @Override 2628 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2629 final IPackageDataObserver observer) { 2630 mContext.enforceCallingOrSelfPermission( 2631 android.Manifest.permission.CLEAR_APP_CACHE, null); 2632 // Queue up an async operation since clearing cache may take a little while. 2633 mHandler.post(new Runnable() { 2634 public void run() { 2635 mHandler.removeCallbacks(this); 2636 int retCode = -1; 2637 synchronized (mInstallLock) { 2638 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2639 if (retCode < 0) { 2640 Slog.w(TAG, "Couldn't clear application caches"); 2641 } 2642 } 2643 if (observer != null) { 2644 try { 2645 observer.onRemoveCompleted(null, (retCode >= 0)); 2646 } catch (RemoteException e) { 2647 Slog.w(TAG, "RemoveException when invoking call back"); 2648 } 2649 } 2650 } 2651 }); 2652 } 2653 2654 @Override 2655 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2656 final IntentSender pi) { 2657 mContext.enforceCallingOrSelfPermission( 2658 android.Manifest.permission.CLEAR_APP_CACHE, null); 2659 // Queue up an async operation since clearing cache may take a little while. 2660 mHandler.post(new Runnable() { 2661 public void run() { 2662 mHandler.removeCallbacks(this); 2663 int retCode = -1; 2664 synchronized (mInstallLock) { 2665 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2666 if (retCode < 0) { 2667 Slog.w(TAG, "Couldn't clear application caches"); 2668 } 2669 } 2670 if(pi != null) { 2671 try { 2672 // Callback via pending intent 2673 int code = (retCode >= 0) ? 1 : 0; 2674 pi.sendIntent(null, code, null, 2675 null, null); 2676 } catch (SendIntentException e1) { 2677 Slog.i(TAG, "Failed to send pending intent"); 2678 } 2679 } 2680 } 2681 }); 2682 } 2683 2684 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2685 synchronized (mInstallLock) { 2686 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2687 throw new IOException("Failed to free enough space"); 2688 } 2689 } 2690 } 2691 2692 @Override 2693 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2694 if (!sUserManager.exists(userId)) return null; 2695 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2696 synchronized (mPackages) { 2697 PackageParser.Activity a = mActivities.mActivities.get(component); 2698 2699 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2700 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2701 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2702 if (ps == null) return null; 2703 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2704 userId); 2705 } 2706 if (mResolveComponentName.equals(component)) { 2707 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2708 new PackageUserState(), userId); 2709 } 2710 } 2711 return null; 2712 } 2713 2714 @Override 2715 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2716 String resolvedType) { 2717 synchronized (mPackages) { 2718 PackageParser.Activity a = mActivities.mActivities.get(component); 2719 if (a == null) { 2720 return false; 2721 } 2722 for (int i=0; i<a.intents.size(); i++) { 2723 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2724 intent.getData(), intent.getCategories(), TAG) >= 0) { 2725 return true; 2726 } 2727 } 2728 return false; 2729 } 2730 } 2731 2732 @Override 2733 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2734 if (!sUserManager.exists(userId)) return null; 2735 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2736 synchronized (mPackages) { 2737 PackageParser.Activity a = mReceivers.mActivities.get(component); 2738 if (DEBUG_PACKAGE_INFO) Log.v( 2739 TAG, "getReceiverInfo " + component + ": " + a); 2740 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2741 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2742 if (ps == null) return null; 2743 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2744 userId); 2745 } 2746 } 2747 return null; 2748 } 2749 2750 @Override 2751 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2752 if (!sUserManager.exists(userId)) return null; 2753 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2754 synchronized (mPackages) { 2755 PackageParser.Service s = mServices.mServices.get(component); 2756 if (DEBUG_PACKAGE_INFO) Log.v( 2757 TAG, "getServiceInfo " + component + ": " + s); 2758 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2759 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2760 if (ps == null) return null; 2761 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2762 userId); 2763 } 2764 } 2765 return null; 2766 } 2767 2768 @Override 2769 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2770 if (!sUserManager.exists(userId)) return null; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2772 synchronized (mPackages) { 2773 PackageParser.Provider p = mProviders.mProviders.get(component); 2774 if (DEBUG_PACKAGE_INFO) Log.v( 2775 TAG, "getProviderInfo " + component + ": " + p); 2776 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2777 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2778 if (ps == null) return null; 2779 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2780 userId); 2781 } 2782 } 2783 return null; 2784 } 2785 2786 @Override 2787 public String[] getSystemSharedLibraryNames() { 2788 Set<String> libSet; 2789 synchronized (mPackages) { 2790 libSet = mSharedLibraries.keySet(); 2791 int size = libSet.size(); 2792 if (size > 0) { 2793 String[] libs = new String[size]; 2794 libSet.toArray(libs); 2795 return libs; 2796 } 2797 } 2798 return null; 2799 } 2800 2801 /** 2802 * @hide 2803 */ 2804 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2805 synchronized (mPackages) { 2806 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2807 if (lib != null && lib.apk != null) { 2808 return mPackages.get(lib.apk); 2809 } 2810 } 2811 return null; 2812 } 2813 2814 @Override 2815 public FeatureInfo[] getSystemAvailableFeatures() { 2816 Collection<FeatureInfo> featSet; 2817 synchronized (mPackages) { 2818 featSet = mAvailableFeatures.values(); 2819 int size = featSet.size(); 2820 if (size > 0) { 2821 FeatureInfo[] features = new FeatureInfo[size+1]; 2822 featSet.toArray(features); 2823 FeatureInfo fi = new FeatureInfo(); 2824 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2825 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2826 features[size] = fi; 2827 return features; 2828 } 2829 } 2830 return null; 2831 } 2832 2833 @Override 2834 public boolean hasSystemFeature(String name) { 2835 synchronized (mPackages) { 2836 return mAvailableFeatures.containsKey(name); 2837 } 2838 } 2839 2840 private void checkValidCaller(int uid, int userId) { 2841 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2842 return; 2843 2844 throw new SecurityException("Caller uid=" + uid 2845 + " is not privileged to communicate with user=" + userId); 2846 } 2847 2848 @Override 2849 public int checkPermission(String permName, String pkgName, int userId) { 2850 if (!sUserManager.exists(userId)) { 2851 return PackageManager.PERMISSION_DENIED; 2852 } 2853 2854 synchronized (mPackages) { 2855 final PackageParser.Package p = mPackages.get(pkgName); 2856 if (p != null && p.mExtras != null) { 2857 final PackageSetting ps = (PackageSetting) p.mExtras; 2858 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2859 return PackageManager.PERMISSION_GRANTED; 2860 } 2861 } 2862 } 2863 2864 return PackageManager.PERMISSION_DENIED; 2865 } 2866 2867 @Override 2868 public int checkUidPermission(String permName, int uid) { 2869 final int userId = UserHandle.getUserId(uid); 2870 2871 if (!sUserManager.exists(userId)) { 2872 return PackageManager.PERMISSION_DENIED; 2873 } 2874 2875 synchronized (mPackages) { 2876 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2877 if (obj != null) { 2878 final SettingBase ps = (SettingBase) obj; 2879 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2880 return PackageManager.PERMISSION_GRANTED; 2881 } 2882 } else { 2883 ArraySet<String> perms = mSystemPermissions.get(uid); 2884 if (perms != null && perms.contains(permName)) { 2885 return PackageManager.PERMISSION_GRANTED; 2886 } 2887 } 2888 } 2889 2890 return PackageManager.PERMISSION_DENIED; 2891 } 2892 2893 /** 2894 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2895 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2896 * @param checkShell TODO(yamasani): 2897 * @param message the message to log on security exception 2898 */ 2899 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2900 boolean checkShell, String message) { 2901 if (userId < 0) { 2902 throw new IllegalArgumentException("Invalid userId " + userId); 2903 } 2904 if (checkShell) { 2905 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2906 } 2907 if (userId == UserHandle.getUserId(callingUid)) return; 2908 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2909 if (requireFullPermission) { 2910 mContext.enforceCallingOrSelfPermission( 2911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2912 } else { 2913 try { 2914 mContext.enforceCallingOrSelfPermission( 2915 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2916 } catch (SecurityException se) { 2917 mContext.enforceCallingOrSelfPermission( 2918 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2919 } 2920 } 2921 } 2922 } 2923 2924 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2925 if (callingUid == Process.SHELL_UID) { 2926 if (userHandle >= 0 2927 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2928 throw new SecurityException("Shell does not have permission to access user " 2929 + userHandle); 2930 } else if (userHandle < 0) { 2931 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2932 + Debug.getCallers(3)); 2933 } 2934 } 2935 } 2936 2937 private BasePermission findPermissionTreeLP(String permName) { 2938 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2939 if (permName.startsWith(bp.name) && 2940 permName.length() > bp.name.length() && 2941 permName.charAt(bp.name.length()) == '.') { 2942 return bp; 2943 } 2944 } 2945 return null; 2946 } 2947 2948 private BasePermission checkPermissionTreeLP(String permName) { 2949 if (permName != null) { 2950 BasePermission bp = findPermissionTreeLP(permName); 2951 if (bp != null) { 2952 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2953 return bp; 2954 } 2955 throw new SecurityException("Calling uid " 2956 + Binder.getCallingUid() 2957 + " is not allowed to add to permission tree " 2958 + bp.name + " owned by uid " + bp.uid); 2959 } 2960 } 2961 throw new SecurityException("No permission tree found for " + permName); 2962 } 2963 2964 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2965 if (s1 == null) { 2966 return s2 == null; 2967 } 2968 if (s2 == null) { 2969 return false; 2970 } 2971 if (s1.getClass() != s2.getClass()) { 2972 return false; 2973 } 2974 return s1.equals(s2); 2975 } 2976 2977 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2978 if (pi1.icon != pi2.icon) return false; 2979 if (pi1.logo != pi2.logo) return false; 2980 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2981 if (!compareStrings(pi1.name, pi2.name)) return false; 2982 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2983 // We'll take care of setting this one. 2984 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2985 // These are not currently stored in settings. 2986 //if (!compareStrings(pi1.group, pi2.group)) return false; 2987 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2988 //if (pi1.labelRes != pi2.labelRes) return false; 2989 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2990 return true; 2991 } 2992 2993 int permissionInfoFootprint(PermissionInfo info) { 2994 int size = info.name.length(); 2995 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2996 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2997 return size; 2998 } 2999 3000 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3001 int size = 0; 3002 for (BasePermission perm : mSettings.mPermissions.values()) { 3003 if (perm.uid == tree.uid) { 3004 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3005 } 3006 } 3007 return size; 3008 } 3009 3010 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3011 // We calculate the max size of permissions defined by this uid and throw 3012 // if that plus the size of 'info' would exceed our stated maximum. 3013 if (tree.uid != Process.SYSTEM_UID) { 3014 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3015 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3016 throw new SecurityException("Permission tree size cap exceeded"); 3017 } 3018 } 3019 } 3020 3021 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3022 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3023 throw new SecurityException("Label must be specified in permission"); 3024 } 3025 BasePermission tree = checkPermissionTreeLP(info.name); 3026 BasePermission bp = mSettings.mPermissions.get(info.name); 3027 boolean added = bp == null; 3028 boolean changed = true; 3029 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3030 if (added) { 3031 enforcePermissionCapLocked(info, tree); 3032 bp = new BasePermission(info.name, tree.sourcePackage, 3033 BasePermission.TYPE_DYNAMIC); 3034 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3035 throw new SecurityException( 3036 "Not allowed to modify non-dynamic permission " 3037 + info.name); 3038 } else { 3039 if (bp.protectionLevel == fixedLevel 3040 && bp.perm.owner.equals(tree.perm.owner) 3041 && bp.uid == tree.uid 3042 && comparePermissionInfos(bp.perm.info, info)) { 3043 changed = false; 3044 } 3045 } 3046 bp.protectionLevel = fixedLevel; 3047 info = new PermissionInfo(info); 3048 info.protectionLevel = fixedLevel; 3049 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3050 bp.perm.info.packageName = tree.perm.info.packageName; 3051 bp.uid = tree.uid; 3052 if (added) { 3053 mSettings.mPermissions.put(info.name, bp); 3054 } 3055 if (changed) { 3056 if (!async) { 3057 mSettings.writeLPr(); 3058 } else { 3059 scheduleWriteSettingsLocked(); 3060 } 3061 } 3062 return added; 3063 } 3064 3065 @Override 3066 public boolean addPermission(PermissionInfo info) { 3067 synchronized (mPackages) { 3068 return addPermissionLocked(info, false); 3069 } 3070 } 3071 3072 @Override 3073 public boolean addPermissionAsync(PermissionInfo info) { 3074 synchronized (mPackages) { 3075 return addPermissionLocked(info, true); 3076 } 3077 } 3078 3079 @Override 3080 public void removePermission(String name) { 3081 synchronized (mPackages) { 3082 checkPermissionTreeLP(name); 3083 BasePermission bp = mSettings.mPermissions.get(name); 3084 if (bp != null) { 3085 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3086 throw new SecurityException( 3087 "Not allowed to modify non-dynamic permission " 3088 + name); 3089 } 3090 mSettings.mPermissions.remove(name); 3091 mSettings.writeLPr(); 3092 } 3093 } 3094 } 3095 3096 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3097 BasePermission bp) { 3098 int index = pkg.requestedPermissions.indexOf(bp.name); 3099 if (index == -1) { 3100 throw new SecurityException("Package " + pkg.packageName 3101 + " has not requested permission " + bp.name); 3102 } 3103 if (!bp.isRuntime()) { 3104 throw new SecurityException("Permission " + bp.name 3105 + " is not a changeable permission type"); 3106 } 3107 } 3108 3109 @Override 3110 public boolean grantPermission(String packageName, String name, int userId) { 3111 if (!RUNTIME_PERMISSIONS_ENABLED) { 3112 return false; 3113 } 3114 3115 if (!sUserManager.exists(userId)) { 3116 return false; 3117 } 3118 3119 mContext.enforceCallingOrSelfPermission( 3120 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3121 "grantPermission"); 3122 3123 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3124 "grantPermission"); 3125 3126 boolean gidsChanged = false; 3127 final SettingBase sb; 3128 3129 synchronized (mPackages) { 3130 final PackageParser.Package pkg = mPackages.get(packageName); 3131 if (pkg == null) { 3132 throw new IllegalArgumentException("Unknown package: " + packageName); 3133 } 3134 3135 final BasePermission bp = mSettings.mPermissions.get(name); 3136 if (bp == null) { 3137 throw new IllegalArgumentException("Unknown permission: " + name); 3138 } 3139 3140 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3141 3142 sb = (SettingBase) pkg.mExtras; 3143 if (sb == null) { 3144 throw new IllegalArgumentException("Unknown package: " + packageName); 3145 } 3146 3147 final PermissionsState permissionsState = sb.getPermissionsState(); 3148 3149 final int result = permissionsState.grantRuntimePermission(bp, userId); 3150 switch (result) { 3151 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3152 return false; 3153 } 3154 3155 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3156 gidsChanged = true; 3157 } break; 3158 } 3159 3160 // Not critical if that is lost - app has to request again. 3161 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3162 } 3163 3164 if (gidsChanged) { 3165 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3166 } 3167 3168 return true; 3169 } 3170 3171 @Override 3172 public boolean revokePermission(String packageName, String name, int userId) { 3173 if (!RUNTIME_PERMISSIONS_ENABLED) { 3174 return false; 3175 } 3176 3177 if (!sUserManager.exists(userId)) { 3178 return false; 3179 } 3180 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3183 "revokePermission"); 3184 3185 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3186 "revokePermission"); 3187 3188 final SettingBase sb; 3189 3190 synchronized (mPackages) { 3191 final PackageParser.Package pkg = mPackages.get(packageName); 3192 if (pkg == null) { 3193 throw new IllegalArgumentException("Unknown package: " + packageName); 3194 } 3195 3196 final BasePermission bp = mSettings.mPermissions.get(name); 3197 if (bp == null) { 3198 throw new IllegalArgumentException("Unknown permission: " + name); 3199 } 3200 3201 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3202 3203 sb = (SettingBase) pkg.mExtras; 3204 if (sb == null) { 3205 throw new IllegalArgumentException("Unknown package: " + packageName); 3206 } 3207 3208 final PermissionsState permissionsState = sb.getPermissionsState(); 3209 3210 if (permissionsState.revokeRuntimePermission(bp, userId) == 3211 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3212 return false; 3213 } 3214 3215 // Critical, after this call all should never have the permission. 3216 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3217 } 3218 3219 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3220 3221 return true; 3222 } 3223 3224 @Override 3225 public boolean isProtectedBroadcast(String actionName) { 3226 synchronized (mPackages) { 3227 return mProtectedBroadcasts.contains(actionName); 3228 } 3229 } 3230 3231 @Override 3232 public int checkSignatures(String pkg1, String pkg2) { 3233 synchronized (mPackages) { 3234 final PackageParser.Package p1 = mPackages.get(pkg1); 3235 final PackageParser.Package p2 = mPackages.get(pkg2); 3236 if (p1 == null || p1.mExtras == null 3237 || p2 == null || p2.mExtras == null) { 3238 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3239 } 3240 return compareSignatures(p1.mSignatures, p2.mSignatures); 3241 } 3242 } 3243 3244 @Override 3245 public int checkUidSignatures(int uid1, int uid2) { 3246 // Map to base uids. 3247 uid1 = UserHandle.getAppId(uid1); 3248 uid2 = UserHandle.getAppId(uid2); 3249 // reader 3250 synchronized (mPackages) { 3251 Signature[] s1; 3252 Signature[] s2; 3253 Object obj = mSettings.getUserIdLPr(uid1); 3254 if (obj != null) { 3255 if (obj instanceof SharedUserSetting) { 3256 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3257 } else if (obj instanceof PackageSetting) { 3258 s1 = ((PackageSetting)obj).signatures.mSignatures; 3259 } else { 3260 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3261 } 3262 } else { 3263 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3264 } 3265 obj = mSettings.getUserIdLPr(uid2); 3266 if (obj != null) { 3267 if (obj instanceof SharedUserSetting) { 3268 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3269 } else if (obj instanceof PackageSetting) { 3270 s2 = ((PackageSetting)obj).signatures.mSignatures; 3271 } else { 3272 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3273 } 3274 } else { 3275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3276 } 3277 return compareSignatures(s1, s2); 3278 } 3279 } 3280 3281 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3282 final long identity = Binder.clearCallingIdentity(); 3283 try { 3284 if (sb instanceof SharedUserSetting) { 3285 SharedUserSetting sus = (SharedUserSetting) sb; 3286 final int packageCount = sus.packages.size(); 3287 for (int i = 0; i < packageCount; i++) { 3288 PackageSetting susPs = sus.packages.valueAt(i); 3289 if (userId == UserHandle.USER_ALL) { 3290 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3291 } else { 3292 final int uid = UserHandle.getUid(userId, susPs.appId); 3293 killUid(uid, reason); 3294 } 3295 } 3296 } else if (sb instanceof PackageSetting) { 3297 PackageSetting ps = (PackageSetting) sb; 3298 if (userId == UserHandle.USER_ALL) { 3299 killApplication(ps.pkg.packageName, ps.appId, reason); 3300 } else { 3301 final int uid = UserHandle.getUid(userId, ps.appId); 3302 killUid(uid, reason); 3303 } 3304 } 3305 } finally { 3306 Binder.restoreCallingIdentity(identity); 3307 } 3308 } 3309 3310 private static void killUid(int uid, String reason) { 3311 IActivityManager am = ActivityManagerNative.getDefault(); 3312 if (am != null) { 3313 try { 3314 am.killUid(uid, reason); 3315 } catch (RemoteException e) { 3316 /* ignore - same process */ 3317 } 3318 } 3319 } 3320 3321 /** 3322 * Compares two sets of signatures. Returns: 3323 * <br /> 3324 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3325 * <br /> 3326 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3327 * <br /> 3328 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3329 * <br /> 3330 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3331 * <br /> 3332 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3333 */ 3334 static int compareSignatures(Signature[] s1, Signature[] s2) { 3335 if (s1 == null) { 3336 return s2 == null 3337 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3338 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3339 } 3340 3341 if (s2 == null) { 3342 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3343 } 3344 3345 if (s1.length != s2.length) { 3346 return PackageManager.SIGNATURE_NO_MATCH; 3347 } 3348 3349 // Since both signature sets are of size 1, we can compare without HashSets. 3350 if (s1.length == 1) { 3351 return s1[0].equals(s2[0]) ? 3352 PackageManager.SIGNATURE_MATCH : 3353 PackageManager.SIGNATURE_NO_MATCH; 3354 } 3355 3356 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3357 for (Signature sig : s1) { 3358 set1.add(sig); 3359 } 3360 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3361 for (Signature sig : s2) { 3362 set2.add(sig); 3363 } 3364 // Make sure s2 contains all signatures in s1. 3365 if (set1.equals(set2)) { 3366 return PackageManager.SIGNATURE_MATCH; 3367 } 3368 return PackageManager.SIGNATURE_NO_MATCH; 3369 } 3370 3371 /** 3372 * If the database version for this type of package (internal storage or 3373 * external storage) is less than the version where package signatures 3374 * were updated, return true. 3375 */ 3376 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3377 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3378 DatabaseVersion.SIGNATURE_END_ENTITY)) 3379 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3380 DatabaseVersion.SIGNATURE_END_ENTITY)); 3381 } 3382 3383 /** 3384 * Used for backward compatibility to make sure any packages with 3385 * certificate chains get upgraded to the new style. {@code existingSigs} 3386 * will be in the old format (since they were stored on disk from before the 3387 * system upgrade) and {@code scannedSigs} will be in the newer format. 3388 */ 3389 private int compareSignaturesCompat(PackageSignatures existingSigs, 3390 PackageParser.Package scannedPkg) { 3391 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3392 return PackageManager.SIGNATURE_NO_MATCH; 3393 } 3394 3395 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3396 for (Signature sig : existingSigs.mSignatures) { 3397 existingSet.add(sig); 3398 } 3399 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3400 for (Signature sig : scannedPkg.mSignatures) { 3401 try { 3402 Signature[] chainSignatures = sig.getChainSignatures(); 3403 for (Signature chainSig : chainSignatures) { 3404 scannedCompatSet.add(chainSig); 3405 } 3406 } catch (CertificateEncodingException e) { 3407 scannedCompatSet.add(sig); 3408 } 3409 } 3410 /* 3411 * Make sure the expanded scanned set contains all signatures in the 3412 * existing one. 3413 */ 3414 if (scannedCompatSet.equals(existingSet)) { 3415 // Migrate the old signatures to the new scheme. 3416 existingSigs.assignSignatures(scannedPkg.mSignatures); 3417 // The new KeySets will be re-added later in the scanning process. 3418 synchronized (mPackages) { 3419 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3420 } 3421 return PackageManager.SIGNATURE_MATCH; 3422 } 3423 return PackageManager.SIGNATURE_NO_MATCH; 3424 } 3425 3426 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3427 if (isExternal(scannedPkg)) { 3428 return mSettings.isExternalDatabaseVersionOlderThan( 3429 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3430 } else { 3431 return mSettings.isInternalDatabaseVersionOlderThan( 3432 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3433 } 3434 } 3435 3436 private int compareSignaturesRecover(PackageSignatures existingSigs, 3437 PackageParser.Package scannedPkg) { 3438 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3439 return PackageManager.SIGNATURE_NO_MATCH; 3440 } 3441 3442 String msg = null; 3443 try { 3444 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3445 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3446 + scannedPkg.packageName); 3447 return PackageManager.SIGNATURE_MATCH; 3448 } 3449 } catch (CertificateException e) { 3450 msg = e.getMessage(); 3451 } 3452 3453 logCriticalInfo(Log.INFO, 3454 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3455 return PackageManager.SIGNATURE_NO_MATCH; 3456 } 3457 3458 @Override 3459 public String[] getPackagesForUid(int uid) { 3460 uid = UserHandle.getAppId(uid); 3461 // reader 3462 synchronized (mPackages) { 3463 Object obj = mSettings.getUserIdLPr(uid); 3464 if (obj instanceof SharedUserSetting) { 3465 final SharedUserSetting sus = (SharedUserSetting) obj; 3466 final int N = sus.packages.size(); 3467 final String[] res = new String[N]; 3468 final Iterator<PackageSetting> it = sus.packages.iterator(); 3469 int i = 0; 3470 while (it.hasNext()) { 3471 res[i++] = it.next().name; 3472 } 3473 return res; 3474 } else if (obj instanceof PackageSetting) { 3475 final PackageSetting ps = (PackageSetting) obj; 3476 return new String[] { ps.name }; 3477 } 3478 } 3479 return null; 3480 } 3481 3482 @Override 3483 public String getNameForUid(int uid) { 3484 // reader 3485 synchronized (mPackages) { 3486 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3487 if (obj instanceof SharedUserSetting) { 3488 final SharedUserSetting sus = (SharedUserSetting) obj; 3489 return sus.name + ":" + sus.userId; 3490 } else if (obj instanceof PackageSetting) { 3491 final PackageSetting ps = (PackageSetting) obj; 3492 return ps.name; 3493 } 3494 } 3495 return null; 3496 } 3497 3498 @Override 3499 public int getUidForSharedUser(String sharedUserName) { 3500 if(sharedUserName == null) { 3501 return -1; 3502 } 3503 // reader 3504 synchronized (mPackages) { 3505 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3506 if (suid == null) { 3507 return -1; 3508 } 3509 return suid.userId; 3510 } 3511 } 3512 3513 @Override 3514 public int getFlagsForUid(int uid) { 3515 synchronized (mPackages) { 3516 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3517 if (obj instanceof SharedUserSetting) { 3518 final SharedUserSetting sus = (SharedUserSetting) obj; 3519 return sus.pkgFlags; 3520 } else if (obj instanceof PackageSetting) { 3521 final PackageSetting ps = (PackageSetting) obj; 3522 return ps.pkgFlags; 3523 } 3524 } 3525 return 0; 3526 } 3527 3528 @Override 3529 public int getPrivateFlagsForUid(int uid) { 3530 synchronized (mPackages) { 3531 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3532 if (obj instanceof SharedUserSetting) { 3533 final SharedUserSetting sus = (SharedUserSetting) obj; 3534 return sus.pkgPrivateFlags; 3535 } else if (obj instanceof PackageSetting) { 3536 final PackageSetting ps = (PackageSetting) obj; 3537 return ps.pkgPrivateFlags; 3538 } 3539 } 3540 return 0; 3541 } 3542 3543 @Override 3544 public boolean isUidPrivileged(int uid) { 3545 uid = UserHandle.getAppId(uid); 3546 // reader 3547 synchronized (mPackages) { 3548 Object obj = mSettings.getUserIdLPr(uid); 3549 if (obj instanceof SharedUserSetting) { 3550 final SharedUserSetting sus = (SharedUserSetting) obj; 3551 final Iterator<PackageSetting> it = sus.packages.iterator(); 3552 while (it.hasNext()) { 3553 if (it.next().isPrivileged()) { 3554 return true; 3555 } 3556 } 3557 } else if (obj instanceof PackageSetting) { 3558 final PackageSetting ps = (PackageSetting) obj; 3559 return ps.isPrivileged(); 3560 } 3561 } 3562 return false; 3563 } 3564 3565 @Override 3566 public String[] getAppOpPermissionPackages(String permissionName) { 3567 synchronized (mPackages) { 3568 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3569 if (pkgs == null) { 3570 return null; 3571 } 3572 return pkgs.toArray(new String[pkgs.size()]); 3573 } 3574 } 3575 3576 @Override 3577 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3578 int flags, int userId) { 3579 if (!sUserManager.exists(userId)) return null; 3580 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3581 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3582 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3583 } 3584 3585 @Override 3586 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3587 IntentFilter filter, int match, ComponentName activity) { 3588 final int userId = UserHandle.getCallingUserId(); 3589 if (DEBUG_PREFERRED) { 3590 Log.v(TAG, "setLastChosenActivity intent=" + intent 3591 + " resolvedType=" + resolvedType 3592 + " flags=" + flags 3593 + " filter=" + filter 3594 + " match=" + match 3595 + " activity=" + activity); 3596 filter.dump(new PrintStreamPrinter(System.out), " "); 3597 } 3598 intent.setComponent(null); 3599 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3600 // Find any earlier preferred or last chosen entries and nuke them 3601 findPreferredActivity(intent, resolvedType, 3602 flags, query, 0, false, true, false, userId); 3603 // Add the new activity as the last chosen for this filter 3604 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3605 "Setting last chosen"); 3606 } 3607 3608 @Override 3609 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3610 final int userId = UserHandle.getCallingUserId(); 3611 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3612 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3613 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3614 false, false, false, userId); 3615 } 3616 3617 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3618 int flags, List<ResolveInfo> query, int userId) { 3619 if (query != null) { 3620 final int N = query.size(); 3621 if (N == 1) { 3622 return query.get(0); 3623 } else if (N > 1) { 3624 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3625 // If there is more than one activity with the same priority, 3626 // then let the user decide between them. 3627 ResolveInfo r0 = query.get(0); 3628 ResolveInfo r1 = query.get(1); 3629 if (DEBUG_INTENT_MATCHING || debug) { 3630 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3631 + r1.activityInfo.name + "=" + r1.priority); 3632 } 3633 // If the first activity has a higher priority, or a different 3634 // default, then it is always desireable to pick it. 3635 if (r0.priority != r1.priority 3636 || r0.preferredOrder != r1.preferredOrder 3637 || r0.isDefault != r1.isDefault) { 3638 return query.get(0); 3639 } 3640 // If we have saved a preference for a preferred activity for 3641 // this Intent, use that. 3642 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3643 flags, query, r0.priority, true, false, debug, userId); 3644 if (ri != null) { 3645 return ri; 3646 } 3647 if (userId != 0) { 3648 ri = new ResolveInfo(mResolveInfo); 3649 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3650 ri.activityInfo.applicationInfo = new ApplicationInfo( 3651 ri.activityInfo.applicationInfo); 3652 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3653 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3654 return ri; 3655 } 3656 return mResolveInfo; 3657 } 3658 } 3659 return null; 3660 } 3661 3662 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3663 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3664 final int N = query.size(); 3665 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3666 .get(userId); 3667 // Get the list of persistent preferred activities that handle the intent 3668 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3669 List<PersistentPreferredActivity> pprefs = ppir != null 3670 ? ppir.queryIntent(intent, resolvedType, 3671 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3672 : null; 3673 if (pprefs != null && pprefs.size() > 0) { 3674 final int M = pprefs.size(); 3675 for (int i=0; i<M; i++) { 3676 final PersistentPreferredActivity ppa = pprefs.get(i); 3677 if (DEBUG_PREFERRED || debug) { 3678 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3679 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3680 + "\n component=" + ppa.mComponent); 3681 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3682 } 3683 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3684 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3685 if (DEBUG_PREFERRED || debug) { 3686 Slog.v(TAG, "Found persistent preferred activity:"); 3687 if (ai != null) { 3688 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3689 } else { 3690 Slog.v(TAG, " null"); 3691 } 3692 } 3693 if (ai == null) { 3694 // This previously registered persistent preferred activity 3695 // component is no longer known. Ignore it and do NOT remove it. 3696 continue; 3697 } 3698 for (int j=0; j<N; j++) { 3699 final ResolveInfo ri = query.get(j); 3700 if (!ri.activityInfo.applicationInfo.packageName 3701 .equals(ai.applicationInfo.packageName)) { 3702 continue; 3703 } 3704 if (!ri.activityInfo.name.equals(ai.name)) { 3705 continue; 3706 } 3707 // Found a persistent preference that can handle the intent. 3708 if (DEBUG_PREFERRED || debug) { 3709 Slog.v(TAG, "Returning persistent preferred activity: " + 3710 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3711 } 3712 return ri; 3713 } 3714 } 3715 } 3716 return null; 3717 } 3718 3719 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3720 List<ResolveInfo> query, int priority, boolean always, 3721 boolean removeMatches, boolean debug, int userId) { 3722 if (!sUserManager.exists(userId)) return null; 3723 // writer 3724 synchronized (mPackages) { 3725 if (intent.getSelector() != null) { 3726 intent = intent.getSelector(); 3727 } 3728 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3729 3730 // Try to find a matching persistent preferred activity. 3731 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3732 debug, userId); 3733 3734 // If a persistent preferred activity matched, use it. 3735 if (pri != null) { 3736 return pri; 3737 } 3738 3739 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3740 // Get the list of preferred activities that handle the intent 3741 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3742 List<PreferredActivity> prefs = pir != null 3743 ? pir.queryIntent(intent, resolvedType, 3744 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3745 : null; 3746 if (prefs != null && prefs.size() > 0) { 3747 boolean changed = false; 3748 try { 3749 // First figure out how good the original match set is. 3750 // We will only allow preferred activities that came 3751 // from the same match quality. 3752 int match = 0; 3753 3754 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3755 3756 final int N = query.size(); 3757 for (int j=0; j<N; j++) { 3758 final ResolveInfo ri = query.get(j); 3759 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3760 + ": 0x" + Integer.toHexString(match)); 3761 if (ri.match > match) { 3762 match = ri.match; 3763 } 3764 } 3765 3766 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3767 + Integer.toHexString(match)); 3768 3769 match &= IntentFilter.MATCH_CATEGORY_MASK; 3770 final int M = prefs.size(); 3771 for (int i=0; i<M; i++) { 3772 final PreferredActivity pa = prefs.get(i); 3773 if (DEBUG_PREFERRED || debug) { 3774 Slog.v(TAG, "Checking PreferredActivity ds=" 3775 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3776 + "\n component=" + pa.mPref.mComponent); 3777 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3778 } 3779 if (pa.mPref.mMatch != match) { 3780 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3781 + Integer.toHexString(pa.mPref.mMatch)); 3782 continue; 3783 } 3784 // If it's not an "always" type preferred activity and that's what we're 3785 // looking for, skip it. 3786 if (always && !pa.mPref.mAlways) { 3787 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3788 continue; 3789 } 3790 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3791 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3792 if (DEBUG_PREFERRED || debug) { 3793 Slog.v(TAG, "Found preferred activity:"); 3794 if (ai != null) { 3795 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3796 } else { 3797 Slog.v(TAG, " null"); 3798 } 3799 } 3800 if (ai == null) { 3801 // This previously registered preferred activity 3802 // component is no longer known. Most likely an update 3803 // to the app was installed and in the new version this 3804 // component no longer exists. Clean it up by removing 3805 // it from the preferred activities list, and skip it. 3806 Slog.w(TAG, "Removing dangling preferred activity: " 3807 + pa.mPref.mComponent); 3808 pir.removeFilter(pa); 3809 changed = true; 3810 continue; 3811 } 3812 for (int j=0; j<N; j++) { 3813 final ResolveInfo ri = query.get(j); 3814 if (!ri.activityInfo.applicationInfo.packageName 3815 .equals(ai.applicationInfo.packageName)) { 3816 continue; 3817 } 3818 if (!ri.activityInfo.name.equals(ai.name)) { 3819 continue; 3820 } 3821 3822 if (removeMatches) { 3823 pir.removeFilter(pa); 3824 changed = true; 3825 if (DEBUG_PREFERRED) { 3826 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3827 } 3828 break; 3829 } 3830 3831 // Okay we found a previously set preferred or last chosen app. 3832 // If the result set is different from when this 3833 // was created, we need to clear it and re-ask the 3834 // user their preference, if we're looking for an "always" type entry. 3835 if (always && !pa.mPref.sameSet(query)) { 3836 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3837 + intent + " type " + resolvedType); 3838 if (DEBUG_PREFERRED) { 3839 Slog.v(TAG, "Removing preferred activity since set changed " 3840 + pa.mPref.mComponent); 3841 } 3842 pir.removeFilter(pa); 3843 // Re-add the filter as a "last chosen" entry (!always) 3844 PreferredActivity lastChosen = new PreferredActivity( 3845 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3846 pir.addFilter(lastChosen); 3847 changed = true; 3848 return null; 3849 } 3850 3851 // Yay! Either the set matched or we're looking for the last chosen 3852 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3853 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3854 return ri; 3855 } 3856 } 3857 } finally { 3858 if (changed) { 3859 if (DEBUG_PREFERRED) { 3860 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3861 } 3862 scheduleWritePackageRestrictionsLocked(userId); 3863 } 3864 } 3865 } 3866 } 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3868 return null; 3869 } 3870 3871 /* 3872 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3873 */ 3874 @Override 3875 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3876 int targetUserId) { 3877 mContext.enforceCallingOrSelfPermission( 3878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3879 List<CrossProfileIntentFilter> matches = 3880 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3881 if (matches != null) { 3882 int size = matches.size(); 3883 for (int i = 0; i < size; i++) { 3884 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3885 } 3886 } 3887 return false; 3888 } 3889 3890 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3891 String resolvedType, int userId) { 3892 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3893 if (resolver != null) { 3894 return resolver.queryIntent(intent, resolvedType, false, userId); 3895 } 3896 return null; 3897 } 3898 3899 @Override 3900 public List<ResolveInfo> queryIntentActivities(Intent intent, 3901 String resolvedType, int flags, int userId) { 3902 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3903 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3904 ComponentName comp = intent.getComponent(); 3905 if (comp == null) { 3906 if (intent.getSelector() != null) { 3907 intent = intent.getSelector(); 3908 comp = intent.getComponent(); 3909 } 3910 } 3911 3912 if (comp != null) { 3913 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3914 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3915 if (ai != null) { 3916 final ResolveInfo ri = new ResolveInfo(); 3917 ri.activityInfo = ai; 3918 list.add(ri); 3919 } 3920 return list; 3921 } 3922 3923 // reader 3924 synchronized (mPackages) { 3925 final String pkgName = intent.getPackage(); 3926 if (pkgName == null) { 3927 List<CrossProfileIntentFilter> matchingFilters = 3928 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3929 // Check for results that need to skip the current profile. 3930 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3931 resolvedType, flags, userId); 3932 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3933 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3934 result.add(resolveInfo); 3935 return filterIfNotPrimaryUser(result, userId); 3936 } 3937 3938 // Check for results in the current profile. 3939 List<ResolveInfo> result = mActivities.queryIntent( 3940 intent, resolvedType, flags, userId); 3941 3942 // Check for cross profile results. 3943 resolveInfo = queryCrossProfileIntents( 3944 matchingFilters, intent, resolvedType, flags, userId); 3945 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3946 result.add(resolveInfo); 3947 Collections.sort(result, mResolvePrioritySorter); 3948 } 3949 result = filterIfNotPrimaryUser(result, userId); 3950 if (result.size() > 1 && hasWebURI(intent)) { 3951 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3952 } 3953 return result; 3954 } 3955 final PackageParser.Package pkg = mPackages.get(pkgName); 3956 if (pkg != null) { 3957 return filterIfNotPrimaryUser( 3958 mActivities.queryIntentForPackage( 3959 intent, resolvedType, flags, pkg.activities, userId), 3960 userId); 3961 } 3962 return new ArrayList<ResolveInfo>(); 3963 } 3964 } 3965 3966 private boolean isUserEnabled(int userId) { 3967 long callingId = Binder.clearCallingIdentity(); 3968 try { 3969 UserInfo userInfo = sUserManager.getUserInfo(userId); 3970 return userInfo != null && userInfo.isEnabled(); 3971 } finally { 3972 Binder.restoreCallingIdentity(callingId); 3973 } 3974 } 3975 3976 /** 3977 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3978 * 3979 * @return filtered list 3980 */ 3981 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3982 if (userId == UserHandle.USER_OWNER) { 3983 return resolveInfos; 3984 } 3985 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3986 ResolveInfo info = resolveInfos.get(i); 3987 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3988 resolveInfos.remove(i); 3989 } 3990 } 3991 return resolveInfos; 3992 } 3993 3994 private static boolean hasWebURI(Intent intent) { 3995 if (intent.getData() == null) { 3996 return false; 3997 } 3998 final String scheme = intent.getScheme(); 3999 if (TextUtils.isEmpty(scheme)) { 4000 return false; 4001 } 4002 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4003 } 4004 4005 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4006 int flags, List<ResolveInfo> candidates) { 4007 if (DEBUG_PREFERRED) { 4008 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4009 candidates.size()); 4010 } 4011 4012 final int userId = UserHandle.getCallingUserId(); 4013 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4014 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4015 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4016 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4017 4018 synchronized (mPackages) { 4019 final int count = candidates.size(); 4020 // First, try to use the domain prefered App 4021 for (int n=0; n<count; n++) { 4022 ResolveInfo info = candidates.get(n); 4023 String packageName = info.activityInfo.packageName; 4024 PackageSetting ps = mSettings.mPackages.get(packageName); 4025 if (ps != null) { 4026 // Add to the special match all list (Browser use case) 4027 if (info.handleAllWebDataURI) { 4028 matchAllList.add(info); 4029 continue; 4030 } 4031 // Try to get the status from User settings first 4032 int status = getDomainVerificationStatusLPr(ps, userId); 4033 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4034 result.add(info); 4035 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4036 neverList.add(info); 4037 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4038 undefinedList.add(info); 4039 } 4040 } 4041 } 4042 // If there is nothing selected, add all candidates and remove the ones that the User 4043 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4044 // also remove any Browser Apps ones. 4045 // If there is still none after this pass, add all undefined one and Browser Apps and 4046 // let the User decide with the Disambiguation dialog if there are several ones. 4047 if (result.size() == 0) { 4048 result.addAll(candidates); 4049 } 4050 result.removeAll(neverList); 4051 result.removeAll(matchAllList); 4052 if (result.size() == 0) { 4053 result.addAll(undefinedList); 4054 if ((flags & MATCH_ALL) != 0) { 4055 result.addAll(matchAllList); 4056 } else { 4057 // Try to add the Default Browser if we can 4058 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4059 UserHandle.myUserId()); 4060 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4061 boolean defaultBrowserFound = false; 4062 final int browserCount = matchAllList.size(); 4063 for (int n=0; n<browserCount; n++) { 4064 ResolveInfo browser = matchAllList.get(n); 4065 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4066 result.add(browser); 4067 defaultBrowserFound = true; 4068 break; 4069 } 4070 } 4071 if (!defaultBrowserFound) { 4072 result.addAll(matchAllList); 4073 } 4074 } else { 4075 result.addAll(matchAllList); 4076 } 4077 } 4078 } 4079 } 4080 if (DEBUG_PREFERRED) { 4081 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4082 result.size()); 4083 } 4084 return result; 4085 } 4086 4087 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4088 int status = ps.getDomainVerificationStatusForUser(userId); 4089 // if none available, get the master status 4090 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4091 if (ps.getIntentFilterVerificationInfo() != null) { 4092 status = ps.getIntentFilterVerificationInfo().getStatus(); 4093 } 4094 } 4095 return status; 4096 } 4097 4098 private ResolveInfo querySkipCurrentProfileIntents( 4099 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4100 int flags, int sourceUserId) { 4101 if (matchingFilters != null) { 4102 int size = matchingFilters.size(); 4103 for (int i = 0; i < size; i ++) { 4104 CrossProfileIntentFilter filter = matchingFilters.get(i); 4105 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4106 // Checking if there are activities in the target user that can handle the 4107 // intent. 4108 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4109 flags, sourceUserId); 4110 if (resolveInfo != null) { 4111 return resolveInfo; 4112 } 4113 } 4114 } 4115 } 4116 return null; 4117 } 4118 4119 // Return matching ResolveInfo if any for skip current profile intent filters. 4120 private ResolveInfo queryCrossProfileIntents( 4121 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4122 int flags, int sourceUserId) { 4123 if (matchingFilters != null) { 4124 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4125 // match the same intent. For performance reasons, it is better not to 4126 // run queryIntent twice for the same userId 4127 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4128 int size = matchingFilters.size(); 4129 for (int i = 0; i < size; i++) { 4130 CrossProfileIntentFilter filter = matchingFilters.get(i); 4131 int targetUserId = filter.getTargetUserId(); 4132 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4133 && !alreadyTriedUserIds.get(targetUserId)) { 4134 // Checking if there are activities in the target user that can handle the 4135 // intent. 4136 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4137 flags, sourceUserId); 4138 if (resolveInfo != null) return resolveInfo; 4139 alreadyTriedUserIds.put(targetUserId, true); 4140 } 4141 } 4142 } 4143 return null; 4144 } 4145 4146 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4147 String resolvedType, int flags, int sourceUserId) { 4148 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4149 resolvedType, flags, filter.getTargetUserId()); 4150 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4151 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4152 } 4153 return null; 4154 } 4155 4156 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4157 int sourceUserId, int targetUserId) { 4158 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4159 String className; 4160 if (targetUserId == UserHandle.USER_OWNER) { 4161 className = FORWARD_INTENT_TO_USER_OWNER; 4162 } else { 4163 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4164 } 4165 ComponentName forwardingActivityComponentName = new ComponentName( 4166 mAndroidApplication.packageName, className); 4167 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4168 sourceUserId); 4169 if (targetUserId == UserHandle.USER_OWNER) { 4170 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4171 forwardingResolveInfo.noResourceId = true; 4172 } 4173 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4174 forwardingResolveInfo.priority = 0; 4175 forwardingResolveInfo.preferredOrder = 0; 4176 forwardingResolveInfo.match = 0; 4177 forwardingResolveInfo.isDefault = true; 4178 forwardingResolveInfo.filter = filter; 4179 forwardingResolveInfo.targetUserId = targetUserId; 4180 return forwardingResolveInfo; 4181 } 4182 4183 @Override 4184 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4185 Intent[] specifics, String[] specificTypes, Intent intent, 4186 String resolvedType, int flags, int userId) { 4187 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4188 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4189 false, "query intent activity options"); 4190 final String resultsAction = intent.getAction(); 4191 4192 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4193 | PackageManager.GET_RESOLVED_FILTER, userId); 4194 4195 if (DEBUG_INTENT_MATCHING) { 4196 Log.v(TAG, "Query " + intent + ": " + results); 4197 } 4198 4199 int specificsPos = 0; 4200 int N; 4201 4202 // todo: note that the algorithm used here is O(N^2). This 4203 // isn't a problem in our current environment, but if we start running 4204 // into situations where we have more than 5 or 10 matches then this 4205 // should probably be changed to something smarter... 4206 4207 // First we go through and resolve each of the specific items 4208 // that were supplied, taking care of removing any corresponding 4209 // duplicate items in the generic resolve list. 4210 if (specifics != null) { 4211 for (int i=0; i<specifics.length; i++) { 4212 final Intent sintent = specifics[i]; 4213 if (sintent == null) { 4214 continue; 4215 } 4216 4217 if (DEBUG_INTENT_MATCHING) { 4218 Log.v(TAG, "Specific #" + i + ": " + sintent); 4219 } 4220 4221 String action = sintent.getAction(); 4222 if (resultsAction != null && resultsAction.equals(action)) { 4223 // If this action was explicitly requested, then don't 4224 // remove things that have it. 4225 action = null; 4226 } 4227 4228 ResolveInfo ri = null; 4229 ActivityInfo ai = null; 4230 4231 ComponentName comp = sintent.getComponent(); 4232 if (comp == null) { 4233 ri = resolveIntent( 4234 sintent, 4235 specificTypes != null ? specificTypes[i] : null, 4236 flags, userId); 4237 if (ri == null) { 4238 continue; 4239 } 4240 if (ri == mResolveInfo) { 4241 // ACK! Must do something better with this. 4242 } 4243 ai = ri.activityInfo; 4244 comp = new ComponentName(ai.applicationInfo.packageName, 4245 ai.name); 4246 } else { 4247 ai = getActivityInfo(comp, flags, userId); 4248 if (ai == null) { 4249 continue; 4250 } 4251 } 4252 4253 // Look for any generic query activities that are duplicates 4254 // of this specific one, and remove them from the results. 4255 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4256 N = results.size(); 4257 int j; 4258 for (j=specificsPos; j<N; j++) { 4259 ResolveInfo sri = results.get(j); 4260 if ((sri.activityInfo.name.equals(comp.getClassName()) 4261 && sri.activityInfo.applicationInfo.packageName.equals( 4262 comp.getPackageName())) 4263 || (action != null && sri.filter.matchAction(action))) { 4264 results.remove(j); 4265 if (DEBUG_INTENT_MATCHING) Log.v( 4266 TAG, "Removing duplicate item from " + j 4267 + " due to specific " + specificsPos); 4268 if (ri == null) { 4269 ri = sri; 4270 } 4271 j--; 4272 N--; 4273 } 4274 } 4275 4276 // Add this specific item to its proper place. 4277 if (ri == null) { 4278 ri = new ResolveInfo(); 4279 ri.activityInfo = ai; 4280 } 4281 results.add(specificsPos, ri); 4282 ri.specificIndex = i; 4283 specificsPos++; 4284 } 4285 } 4286 4287 // Now we go through the remaining generic results and remove any 4288 // duplicate actions that are found here. 4289 N = results.size(); 4290 for (int i=specificsPos; i<N-1; i++) { 4291 final ResolveInfo rii = results.get(i); 4292 if (rii.filter == null) { 4293 continue; 4294 } 4295 4296 // Iterate over all of the actions of this result's intent 4297 // filter... typically this should be just one. 4298 final Iterator<String> it = rii.filter.actionsIterator(); 4299 if (it == null) { 4300 continue; 4301 } 4302 while (it.hasNext()) { 4303 final String action = it.next(); 4304 if (resultsAction != null && resultsAction.equals(action)) { 4305 // If this action was explicitly requested, then don't 4306 // remove things that have it. 4307 continue; 4308 } 4309 for (int j=i+1; j<N; j++) { 4310 final ResolveInfo rij = results.get(j); 4311 if (rij.filter != null && rij.filter.hasAction(action)) { 4312 results.remove(j); 4313 if (DEBUG_INTENT_MATCHING) Log.v( 4314 TAG, "Removing duplicate item from " + j 4315 + " due to action " + action + " at " + i); 4316 j--; 4317 N--; 4318 } 4319 } 4320 } 4321 4322 // If the caller didn't request filter information, drop it now 4323 // so we don't have to marshall/unmarshall it. 4324 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4325 rii.filter = null; 4326 } 4327 } 4328 4329 // Filter out the caller activity if so requested. 4330 if (caller != null) { 4331 N = results.size(); 4332 for (int i=0; i<N; i++) { 4333 ActivityInfo ainfo = results.get(i).activityInfo; 4334 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4335 && caller.getClassName().equals(ainfo.name)) { 4336 results.remove(i); 4337 break; 4338 } 4339 } 4340 } 4341 4342 // If the caller didn't request filter information, 4343 // drop them now so we don't have to 4344 // marshall/unmarshall it. 4345 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4346 N = results.size(); 4347 for (int i=0; i<N; i++) { 4348 results.get(i).filter = null; 4349 } 4350 } 4351 4352 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4353 return results; 4354 } 4355 4356 @Override 4357 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4358 int userId) { 4359 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4360 ComponentName comp = intent.getComponent(); 4361 if (comp == null) { 4362 if (intent.getSelector() != null) { 4363 intent = intent.getSelector(); 4364 comp = intent.getComponent(); 4365 } 4366 } 4367 if (comp != null) { 4368 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4369 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4370 if (ai != null) { 4371 ResolveInfo ri = new ResolveInfo(); 4372 ri.activityInfo = ai; 4373 list.add(ri); 4374 } 4375 return list; 4376 } 4377 4378 // reader 4379 synchronized (mPackages) { 4380 String pkgName = intent.getPackage(); 4381 if (pkgName == null) { 4382 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4383 } 4384 final PackageParser.Package pkg = mPackages.get(pkgName); 4385 if (pkg != null) { 4386 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4387 userId); 4388 } 4389 return null; 4390 } 4391 } 4392 4393 @Override 4394 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4395 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4396 if (!sUserManager.exists(userId)) return null; 4397 if (query != null) { 4398 if (query.size() >= 1) { 4399 // If there is more than one service with the same priority, 4400 // just arbitrarily pick the first one. 4401 return query.get(0); 4402 } 4403 } 4404 return null; 4405 } 4406 4407 @Override 4408 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4409 int userId) { 4410 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4411 ComponentName comp = intent.getComponent(); 4412 if (comp == null) { 4413 if (intent.getSelector() != null) { 4414 intent = intent.getSelector(); 4415 comp = intent.getComponent(); 4416 } 4417 } 4418 if (comp != null) { 4419 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4420 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4421 if (si != null) { 4422 final ResolveInfo ri = new ResolveInfo(); 4423 ri.serviceInfo = si; 4424 list.add(ri); 4425 } 4426 return list; 4427 } 4428 4429 // reader 4430 synchronized (mPackages) { 4431 String pkgName = intent.getPackage(); 4432 if (pkgName == null) { 4433 return mServices.queryIntent(intent, resolvedType, flags, userId); 4434 } 4435 final PackageParser.Package pkg = mPackages.get(pkgName); 4436 if (pkg != null) { 4437 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4438 userId); 4439 } 4440 return null; 4441 } 4442 } 4443 4444 @Override 4445 public List<ResolveInfo> queryIntentContentProviders( 4446 Intent intent, String resolvedType, int flags, int userId) { 4447 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4448 ComponentName comp = intent.getComponent(); 4449 if (comp == null) { 4450 if (intent.getSelector() != null) { 4451 intent = intent.getSelector(); 4452 comp = intent.getComponent(); 4453 } 4454 } 4455 if (comp != null) { 4456 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4457 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4458 if (pi != null) { 4459 final ResolveInfo ri = new ResolveInfo(); 4460 ri.providerInfo = pi; 4461 list.add(ri); 4462 } 4463 return list; 4464 } 4465 4466 // reader 4467 synchronized (mPackages) { 4468 String pkgName = intent.getPackage(); 4469 if (pkgName == null) { 4470 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4471 } 4472 final PackageParser.Package pkg = mPackages.get(pkgName); 4473 if (pkg != null) { 4474 return mProviders.queryIntentForPackage( 4475 intent, resolvedType, flags, pkg.providers, userId); 4476 } 4477 return null; 4478 } 4479 } 4480 4481 @Override 4482 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4483 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4484 4485 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4486 4487 // writer 4488 synchronized (mPackages) { 4489 ArrayList<PackageInfo> list; 4490 if (listUninstalled) { 4491 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4492 for (PackageSetting ps : mSettings.mPackages.values()) { 4493 PackageInfo pi; 4494 if (ps.pkg != null) { 4495 pi = generatePackageInfo(ps.pkg, flags, userId); 4496 } else { 4497 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4498 } 4499 if (pi != null) { 4500 list.add(pi); 4501 } 4502 } 4503 } else { 4504 list = new ArrayList<PackageInfo>(mPackages.size()); 4505 for (PackageParser.Package p : mPackages.values()) { 4506 PackageInfo pi = generatePackageInfo(p, flags, userId); 4507 if (pi != null) { 4508 list.add(pi); 4509 } 4510 } 4511 } 4512 4513 return new ParceledListSlice<PackageInfo>(list); 4514 } 4515 } 4516 4517 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4518 String[] permissions, boolean[] tmp, int flags, int userId) { 4519 int numMatch = 0; 4520 final PermissionsState permissionsState = ps.getPermissionsState(); 4521 for (int i=0; i<permissions.length; i++) { 4522 final String permission = permissions[i]; 4523 if (permissionsState.hasPermission(permission, userId)) { 4524 tmp[i] = true; 4525 numMatch++; 4526 } else { 4527 tmp[i] = false; 4528 } 4529 } 4530 if (numMatch == 0) { 4531 return; 4532 } 4533 PackageInfo pi; 4534 if (ps.pkg != null) { 4535 pi = generatePackageInfo(ps.pkg, flags, userId); 4536 } else { 4537 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4538 } 4539 // The above might return null in cases of uninstalled apps or install-state 4540 // skew across users/profiles. 4541 if (pi != null) { 4542 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4543 if (numMatch == permissions.length) { 4544 pi.requestedPermissions = permissions; 4545 } else { 4546 pi.requestedPermissions = new String[numMatch]; 4547 numMatch = 0; 4548 for (int i=0; i<permissions.length; i++) { 4549 if (tmp[i]) { 4550 pi.requestedPermissions[numMatch] = permissions[i]; 4551 numMatch++; 4552 } 4553 } 4554 } 4555 } 4556 list.add(pi); 4557 } 4558 } 4559 4560 @Override 4561 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4562 String[] permissions, int flags, int userId) { 4563 if (!sUserManager.exists(userId)) return null; 4564 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4565 4566 // writer 4567 synchronized (mPackages) { 4568 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4569 boolean[] tmpBools = new boolean[permissions.length]; 4570 if (listUninstalled) { 4571 for (PackageSetting ps : mSettings.mPackages.values()) { 4572 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4573 } 4574 } else { 4575 for (PackageParser.Package pkg : mPackages.values()) { 4576 PackageSetting ps = (PackageSetting)pkg.mExtras; 4577 if (ps != null) { 4578 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4579 userId); 4580 } 4581 } 4582 } 4583 4584 return new ParceledListSlice<PackageInfo>(list); 4585 } 4586 } 4587 4588 @Override 4589 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4590 if (!sUserManager.exists(userId)) return null; 4591 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4592 4593 // writer 4594 synchronized (mPackages) { 4595 ArrayList<ApplicationInfo> list; 4596 if (listUninstalled) { 4597 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4598 for (PackageSetting ps : mSettings.mPackages.values()) { 4599 ApplicationInfo ai; 4600 if (ps.pkg != null) { 4601 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4602 ps.readUserState(userId), userId); 4603 } else { 4604 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4605 } 4606 if (ai != null) { 4607 list.add(ai); 4608 } 4609 } 4610 } else { 4611 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4612 for (PackageParser.Package p : mPackages.values()) { 4613 if (p.mExtras != null) { 4614 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4615 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4616 if (ai != null) { 4617 list.add(ai); 4618 } 4619 } 4620 } 4621 } 4622 4623 return new ParceledListSlice<ApplicationInfo>(list); 4624 } 4625 } 4626 4627 public List<ApplicationInfo> getPersistentApplications(int flags) { 4628 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4629 4630 // reader 4631 synchronized (mPackages) { 4632 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4633 final int userId = UserHandle.getCallingUserId(); 4634 while (i.hasNext()) { 4635 final PackageParser.Package p = i.next(); 4636 if (p.applicationInfo != null 4637 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4638 && (!mSafeMode || isSystemApp(p))) { 4639 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4640 if (ps != null) { 4641 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4642 ps.readUserState(userId), userId); 4643 if (ai != null) { 4644 finalList.add(ai); 4645 } 4646 } 4647 } 4648 } 4649 } 4650 4651 return finalList; 4652 } 4653 4654 @Override 4655 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4656 if (!sUserManager.exists(userId)) return null; 4657 // reader 4658 synchronized (mPackages) { 4659 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4660 PackageSetting ps = provider != null 4661 ? mSettings.mPackages.get(provider.owner.packageName) 4662 : null; 4663 return ps != null 4664 && mSettings.isEnabledLPr(provider.info, flags, userId) 4665 && (!mSafeMode || (provider.info.applicationInfo.flags 4666 &ApplicationInfo.FLAG_SYSTEM) != 0) 4667 ? PackageParser.generateProviderInfo(provider, flags, 4668 ps.readUserState(userId), userId) 4669 : null; 4670 } 4671 } 4672 4673 /** 4674 * @deprecated 4675 */ 4676 @Deprecated 4677 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4678 // reader 4679 synchronized (mPackages) { 4680 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4681 .entrySet().iterator(); 4682 final int userId = UserHandle.getCallingUserId(); 4683 while (i.hasNext()) { 4684 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4685 PackageParser.Provider p = entry.getValue(); 4686 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4687 4688 if (ps != null && p.syncable 4689 && (!mSafeMode || (p.info.applicationInfo.flags 4690 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4691 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4692 ps.readUserState(userId), userId); 4693 if (info != null) { 4694 outNames.add(entry.getKey()); 4695 outInfo.add(info); 4696 } 4697 } 4698 } 4699 } 4700 } 4701 4702 @Override 4703 public List<ProviderInfo> queryContentProviders(String processName, 4704 int uid, int flags) { 4705 ArrayList<ProviderInfo> finalList = null; 4706 // reader 4707 synchronized (mPackages) { 4708 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4709 final int userId = processName != null ? 4710 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4711 while (i.hasNext()) { 4712 final PackageParser.Provider p = i.next(); 4713 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4714 if (ps != null && p.info.authority != null 4715 && (processName == null 4716 || (p.info.processName.equals(processName) 4717 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4718 && mSettings.isEnabledLPr(p.info, flags, userId) 4719 && (!mSafeMode 4720 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4721 if (finalList == null) { 4722 finalList = new ArrayList<ProviderInfo>(3); 4723 } 4724 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4725 ps.readUserState(userId), userId); 4726 if (info != null) { 4727 finalList.add(info); 4728 } 4729 } 4730 } 4731 } 4732 4733 if (finalList != null) { 4734 Collections.sort(finalList, mProviderInitOrderSorter); 4735 } 4736 4737 return finalList; 4738 } 4739 4740 @Override 4741 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4742 int flags) { 4743 // reader 4744 synchronized (mPackages) { 4745 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4746 return PackageParser.generateInstrumentationInfo(i, flags); 4747 } 4748 } 4749 4750 @Override 4751 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4752 int flags) { 4753 ArrayList<InstrumentationInfo> finalList = 4754 new ArrayList<InstrumentationInfo>(); 4755 4756 // reader 4757 synchronized (mPackages) { 4758 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4759 while (i.hasNext()) { 4760 final PackageParser.Instrumentation p = i.next(); 4761 if (targetPackage == null 4762 || targetPackage.equals(p.info.targetPackage)) { 4763 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4764 flags); 4765 if (ii != null) { 4766 finalList.add(ii); 4767 } 4768 } 4769 } 4770 } 4771 4772 return finalList; 4773 } 4774 4775 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4776 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4777 if (overlays == null) { 4778 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4779 return; 4780 } 4781 for (PackageParser.Package opkg : overlays.values()) { 4782 // Not much to do if idmap fails: we already logged the error 4783 // and we certainly don't want to abort installation of pkg simply 4784 // because an overlay didn't fit properly. For these reasons, 4785 // ignore the return value of createIdmapForPackagePairLI. 4786 createIdmapForPackagePairLI(pkg, opkg); 4787 } 4788 } 4789 4790 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4791 PackageParser.Package opkg) { 4792 if (!opkg.mTrustedOverlay) { 4793 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4794 opkg.baseCodePath + ": overlay not trusted"); 4795 return false; 4796 } 4797 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4798 if (overlaySet == null) { 4799 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4800 opkg.baseCodePath + " but target package has no known overlays"); 4801 return false; 4802 } 4803 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4804 // TODO: generate idmap for split APKs 4805 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4806 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4807 + opkg.baseCodePath); 4808 return false; 4809 } 4810 PackageParser.Package[] overlayArray = 4811 overlaySet.values().toArray(new PackageParser.Package[0]); 4812 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4813 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4814 return p1.mOverlayPriority - p2.mOverlayPriority; 4815 } 4816 }; 4817 Arrays.sort(overlayArray, cmp); 4818 4819 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4820 int i = 0; 4821 for (PackageParser.Package p : overlayArray) { 4822 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4823 } 4824 return true; 4825 } 4826 4827 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4828 final File[] files = dir.listFiles(); 4829 if (ArrayUtils.isEmpty(files)) { 4830 Log.d(TAG, "No files in app dir " + dir); 4831 return; 4832 } 4833 4834 if (DEBUG_PACKAGE_SCANNING) { 4835 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4836 + " flags=0x" + Integer.toHexString(parseFlags)); 4837 } 4838 4839 for (File file : files) { 4840 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4841 && !PackageInstallerService.isStageName(file.getName()); 4842 if (!isPackage) { 4843 // Ignore entries which are not packages 4844 continue; 4845 } 4846 try { 4847 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4848 scanFlags, currentTime, null); 4849 } catch (PackageManagerException e) { 4850 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4851 4852 // Delete invalid userdata apps 4853 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4854 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4855 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4856 if (file.isDirectory()) { 4857 mInstaller.rmPackageDir(file.getAbsolutePath()); 4858 } else { 4859 file.delete(); 4860 } 4861 } 4862 } 4863 } 4864 } 4865 4866 private static File getSettingsProblemFile() { 4867 File dataDir = Environment.getDataDirectory(); 4868 File systemDir = new File(dataDir, "system"); 4869 File fname = new File(systemDir, "uiderrors.txt"); 4870 return fname; 4871 } 4872 4873 static void reportSettingsProblem(int priority, String msg) { 4874 logCriticalInfo(priority, msg); 4875 } 4876 4877 static void logCriticalInfo(int priority, String msg) { 4878 Slog.println(priority, TAG, msg); 4879 EventLogTags.writePmCriticalInfo(msg); 4880 try { 4881 File fname = getSettingsProblemFile(); 4882 FileOutputStream out = new FileOutputStream(fname, true); 4883 PrintWriter pw = new FastPrintWriter(out); 4884 SimpleDateFormat formatter = new SimpleDateFormat(); 4885 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4886 pw.println(dateString + ": " + msg); 4887 pw.close(); 4888 FileUtils.setPermissions( 4889 fname.toString(), 4890 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4891 -1, -1); 4892 } catch (java.io.IOException e) { 4893 } 4894 } 4895 4896 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4897 PackageParser.Package pkg, File srcFile, int parseFlags) 4898 throws PackageManagerException { 4899 if (ps != null 4900 && ps.codePath.equals(srcFile) 4901 && ps.timeStamp == srcFile.lastModified() 4902 && !isCompatSignatureUpdateNeeded(pkg) 4903 && !isRecoverSignatureUpdateNeeded(pkg)) { 4904 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4905 if (ps.signatures.mSignatures != null 4906 && ps.signatures.mSignatures.length != 0 4907 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4908 // Optimization: reuse the existing cached certificates 4909 // if the package appears to be unchanged. 4910 pkg.mSignatures = ps.signatures.mSignatures; 4911 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4912 synchronized (mPackages) { 4913 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4914 } 4915 return; 4916 } 4917 4918 Slog.w(TAG, "PackageSetting for " + ps.name 4919 + " is missing signatures. Collecting certs again to recover them."); 4920 } else { 4921 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4922 } 4923 4924 try { 4925 pp.collectCertificates(pkg, parseFlags); 4926 pp.collectManifestDigest(pkg); 4927 } catch (PackageParserException e) { 4928 throw PackageManagerException.from(e); 4929 } 4930 } 4931 4932 /* 4933 * Scan a package and return the newly parsed package. 4934 * Returns null in case of errors and the error code is stored in mLastScanError 4935 */ 4936 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4937 long currentTime, UserHandle user) throws PackageManagerException { 4938 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4939 parseFlags |= mDefParseFlags; 4940 PackageParser pp = new PackageParser(); 4941 pp.setSeparateProcesses(mSeparateProcesses); 4942 pp.setOnlyCoreApps(mOnlyCore); 4943 pp.setDisplayMetrics(mMetrics); 4944 4945 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4946 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4947 } 4948 4949 final PackageParser.Package pkg; 4950 try { 4951 pkg = pp.parsePackage(scanFile, parseFlags); 4952 } catch (PackageParserException e) { 4953 throw PackageManagerException.from(e); 4954 } 4955 4956 PackageSetting ps = null; 4957 PackageSetting updatedPkg; 4958 // reader 4959 synchronized (mPackages) { 4960 // Look to see if we already know about this package. 4961 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4962 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4963 // This package has been renamed to its original name. Let's 4964 // use that. 4965 ps = mSettings.peekPackageLPr(oldName); 4966 } 4967 // If there was no original package, see one for the real package name. 4968 if (ps == null) { 4969 ps = mSettings.peekPackageLPr(pkg.packageName); 4970 } 4971 // Check to see if this package could be hiding/updating a system 4972 // package. Must look for it either under the original or real 4973 // package name depending on our state. 4974 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4975 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4976 } 4977 boolean updatedPkgBetter = false; 4978 // First check if this is a system package that may involve an update 4979 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4980 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4981 // it needs to drop FLAG_PRIVILEGED. 4982 if (locationIsPrivileged(scanFile)) { 4983 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4984 } else { 4985 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4986 } 4987 4988 if (ps != null && !ps.codePath.equals(scanFile)) { 4989 // The path has changed from what was last scanned... check the 4990 // version of the new path against what we have stored to determine 4991 // what to do. 4992 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4993 if (pkg.mVersionCode <= ps.versionCode) { 4994 // The system package has been updated and the code path does not match 4995 // Ignore entry. Skip it. 4996 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4997 + " ignored: updated version " + ps.versionCode 4998 + " better than this " + pkg.mVersionCode); 4999 if (!updatedPkg.codePath.equals(scanFile)) { 5000 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5001 + ps.name + " changing from " + updatedPkg.codePathString 5002 + " to " + scanFile); 5003 updatedPkg.codePath = scanFile; 5004 updatedPkg.codePathString = scanFile.toString(); 5005 updatedPkg.resourcePath = scanFile; 5006 updatedPkg.resourcePathString = scanFile.toString(); 5007 } 5008 updatedPkg.pkg = pkg; 5009 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5010 } else { 5011 // The current app on the system partition is better than 5012 // what we have updated to on the data partition; switch 5013 // back to the system partition version. 5014 // At this point, its safely assumed that package installation for 5015 // apps in system partition will go through. If not there won't be a working 5016 // version of the app 5017 // writer 5018 synchronized (mPackages) { 5019 // Just remove the loaded entries from package lists. 5020 mPackages.remove(ps.name); 5021 } 5022 5023 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5024 + " reverting from " + ps.codePathString 5025 + ": new version " + pkg.mVersionCode 5026 + " better than installed " + ps.versionCode); 5027 5028 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5029 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5030 getAppDexInstructionSets(ps)); 5031 synchronized (mInstallLock) { 5032 args.cleanUpResourcesLI(); 5033 } 5034 synchronized (mPackages) { 5035 mSettings.enableSystemPackageLPw(ps.name); 5036 } 5037 updatedPkgBetter = true; 5038 } 5039 } 5040 } 5041 5042 if (updatedPkg != null) { 5043 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5044 // initially 5045 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5046 5047 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5048 // flag set initially 5049 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5050 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5051 } 5052 } 5053 5054 // Verify certificates against what was last scanned 5055 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5056 5057 /* 5058 * A new system app appeared, but we already had a non-system one of the 5059 * same name installed earlier. 5060 */ 5061 boolean shouldHideSystemApp = false; 5062 if (updatedPkg == null && ps != null 5063 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5064 /* 5065 * Check to make sure the signatures match first. If they don't, 5066 * wipe the installed application and its data. 5067 */ 5068 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5069 != PackageManager.SIGNATURE_MATCH) { 5070 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5071 + " signatures don't match existing userdata copy; removing"); 5072 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5073 ps = null; 5074 } else { 5075 /* 5076 * If the newly-added system app is an older version than the 5077 * already installed version, hide it. It will be scanned later 5078 * and re-added like an update. 5079 */ 5080 if (pkg.mVersionCode <= ps.versionCode) { 5081 shouldHideSystemApp = true; 5082 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5083 + " but new version " + pkg.mVersionCode + " better than installed " 5084 + ps.versionCode + "; hiding system"); 5085 } else { 5086 /* 5087 * The newly found system app is a newer version that the 5088 * one previously installed. Simply remove the 5089 * already-installed application and replace it with our own 5090 * while keeping the application data. 5091 */ 5092 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5093 + " reverting from " + ps.codePathString + ": new version " 5094 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5095 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5096 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5097 getAppDexInstructionSets(ps)); 5098 synchronized (mInstallLock) { 5099 args.cleanUpResourcesLI(); 5100 } 5101 } 5102 } 5103 } 5104 5105 // The apk is forward locked (not public) if its code and resources 5106 // are kept in different files. (except for app in either system or 5107 // vendor path). 5108 // TODO grab this value from PackageSettings 5109 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5110 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5111 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5112 } 5113 } 5114 5115 // TODO: extend to support forward-locked splits 5116 String resourcePath = null; 5117 String baseResourcePath = null; 5118 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5119 if (ps != null && ps.resourcePathString != null) { 5120 resourcePath = ps.resourcePathString; 5121 baseResourcePath = ps.resourcePathString; 5122 } else { 5123 // Should not happen at all. Just log an error. 5124 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5125 } 5126 } else { 5127 resourcePath = pkg.codePath; 5128 baseResourcePath = pkg.baseCodePath; 5129 } 5130 5131 // Set application objects path explicitly. 5132 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5133 pkg.applicationInfo.setCodePath(pkg.codePath); 5134 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5135 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5136 pkg.applicationInfo.setResourcePath(resourcePath); 5137 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5138 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5139 5140 // Note that we invoke the following method only if we are about to unpack an application 5141 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5142 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5143 5144 /* 5145 * If the system app should be overridden by a previously installed 5146 * data, hide the system app now and let the /data/app scan pick it up 5147 * again. 5148 */ 5149 if (shouldHideSystemApp) { 5150 synchronized (mPackages) { 5151 /* 5152 * We have to grant systems permissions before we hide, because 5153 * grantPermissions will assume the package update is trying to 5154 * expand its permissions. 5155 */ 5156 grantPermissionsLPw(pkg, true, pkg.packageName); 5157 mSettings.disableSystemPackageLPw(pkg.packageName); 5158 } 5159 } 5160 5161 return scannedPkg; 5162 } 5163 5164 private static String fixProcessName(String defProcessName, 5165 String processName, int uid) { 5166 if (processName == null) { 5167 return defProcessName; 5168 } 5169 return processName; 5170 } 5171 5172 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5173 throws PackageManagerException { 5174 if (pkgSetting.signatures.mSignatures != null) { 5175 // Already existing package. Make sure signatures match 5176 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5177 == PackageManager.SIGNATURE_MATCH; 5178 if (!match) { 5179 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5180 == PackageManager.SIGNATURE_MATCH; 5181 } 5182 if (!match) { 5183 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5184 == PackageManager.SIGNATURE_MATCH; 5185 } 5186 if (!match) { 5187 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5188 + pkg.packageName + " signatures do not match the " 5189 + "previously installed version; ignoring!"); 5190 } 5191 } 5192 5193 // Check for shared user signatures 5194 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5195 // Already existing package. Make sure signatures match 5196 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5197 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5198 if (!match) { 5199 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5200 == PackageManager.SIGNATURE_MATCH; 5201 } 5202 if (!match) { 5203 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5204 == PackageManager.SIGNATURE_MATCH; 5205 } 5206 if (!match) { 5207 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5208 "Package " + pkg.packageName 5209 + " has no signatures that match those in shared user " 5210 + pkgSetting.sharedUser.name + "; ignoring!"); 5211 } 5212 } 5213 } 5214 5215 /** 5216 * Enforces that only the system UID or root's UID can call a method exposed 5217 * via Binder. 5218 * 5219 * @param message used as message if SecurityException is thrown 5220 * @throws SecurityException if the caller is not system or root 5221 */ 5222 private static final void enforceSystemOrRoot(String message) { 5223 final int uid = Binder.getCallingUid(); 5224 if (uid != Process.SYSTEM_UID && uid != 0) { 5225 throw new SecurityException(message); 5226 } 5227 } 5228 5229 @Override 5230 public void performBootDexOpt() { 5231 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5232 5233 // Before everything else, see whether we need to fstrim. 5234 try { 5235 IMountService ms = PackageHelper.getMountService(); 5236 if (ms != null) { 5237 final boolean isUpgrade = isUpgrade(); 5238 boolean doTrim = isUpgrade; 5239 if (doTrim) { 5240 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5241 } else { 5242 final long interval = android.provider.Settings.Global.getLong( 5243 mContext.getContentResolver(), 5244 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5245 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5246 if (interval > 0) { 5247 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5248 if (timeSinceLast > interval) { 5249 doTrim = true; 5250 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5251 + "; running immediately"); 5252 } 5253 } 5254 } 5255 if (doTrim) { 5256 if (!isFirstBoot()) { 5257 try { 5258 ActivityManagerNative.getDefault().showBootMessage( 5259 mContext.getResources().getString( 5260 R.string.android_upgrading_fstrim), true); 5261 } catch (RemoteException e) { 5262 } 5263 } 5264 ms.runMaintenance(); 5265 } 5266 } else { 5267 Slog.e(TAG, "Mount service unavailable!"); 5268 } 5269 } catch (RemoteException e) { 5270 // Can't happen; MountService is local 5271 } 5272 5273 final ArraySet<PackageParser.Package> pkgs; 5274 synchronized (mPackages) { 5275 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5276 } 5277 5278 if (pkgs != null) { 5279 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5280 // in case the device runs out of space. 5281 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5282 // Give priority to core apps. 5283 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5284 PackageParser.Package pkg = it.next(); 5285 if (pkg.coreApp) { 5286 if (DEBUG_DEXOPT) { 5287 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5288 } 5289 sortedPkgs.add(pkg); 5290 it.remove(); 5291 } 5292 } 5293 // Give priority to system apps that listen for pre boot complete. 5294 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5295 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5296 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5297 PackageParser.Package pkg = it.next(); 5298 if (pkgNames.contains(pkg.packageName)) { 5299 if (DEBUG_DEXOPT) { 5300 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5301 } 5302 sortedPkgs.add(pkg); 5303 it.remove(); 5304 } 5305 } 5306 // Give priority to system apps. 5307 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5308 PackageParser.Package pkg = it.next(); 5309 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5310 if (DEBUG_DEXOPT) { 5311 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5312 } 5313 sortedPkgs.add(pkg); 5314 it.remove(); 5315 } 5316 } 5317 // Give priority to updated system apps. 5318 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5319 PackageParser.Package pkg = it.next(); 5320 if (pkg.isUpdatedSystemApp()) { 5321 if (DEBUG_DEXOPT) { 5322 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5323 } 5324 sortedPkgs.add(pkg); 5325 it.remove(); 5326 } 5327 } 5328 // Give priority to apps that listen for boot complete. 5329 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5330 pkgNames = getPackageNamesForIntent(intent); 5331 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5332 PackageParser.Package pkg = it.next(); 5333 if (pkgNames.contains(pkg.packageName)) { 5334 if (DEBUG_DEXOPT) { 5335 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5336 } 5337 sortedPkgs.add(pkg); 5338 it.remove(); 5339 } 5340 } 5341 // Filter out packages that aren't recently used. 5342 filterRecentlyUsedApps(pkgs); 5343 // Add all remaining apps. 5344 for (PackageParser.Package pkg : pkgs) { 5345 if (DEBUG_DEXOPT) { 5346 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5347 } 5348 sortedPkgs.add(pkg); 5349 } 5350 5351 // If we want to be lazy, filter everything that wasn't recently used. 5352 if (mLazyDexOpt) { 5353 filterRecentlyUsedApps(sortedPkgs); 5354 } 5355 5356 int i = 0; 5357 int total = sortedPkgs.size(); 5358 File dataDir = Environment.getDataDirectory(); 5359 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5360 if (lowThreshold == 0) { 5361 throw new IllegalStateException("Invalid low memory threshold"); 5362 } 5363 for (PackageParser.Package pkg : sortedPkgs) { 5364 long usableSpace = dataDir.getUsableSpace(); 5365 if (usableSpace < lowThreshold) { 5366 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5367 break; 5368 } 5369 performBootDexOpt(pkg, ++i, total); 5370 } 5371 } 5372 } 5373 5374 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5375 // Filter out packages that aren't recently used. 5376 // 5377 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5378 // should do a full dexopt. 5379 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5380 int total = pkgs.size(); 5381 int skipped = 0; 5382 long now = System.currentTimeMillis(); 5383 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5384 PackageParser.Package pkg = i.next(); 5385 long then = pkg.mLastPackageUsageTimeInMills; 5386 if (then + mDexOptLRUThresholdInMills < now) { 5387 if (DEBUG_DEXOPT) { 5388 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5389 ((then == 0) ? "never" : new Date(then))); 5390 } 5391 i.remove(); 5392 skipped++; 5393 } 5394 } 5395 if (DEBUG_DEXOPT) { 5396 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5397 } 5398 } 5399 } 5400 5401 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5402 List<ResolveInfo> ris = null; 5403 try { 5404 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5405 intent, null, 0, UserHandle.USER_OWNER); 5406 } catch (RemoteException e) { 5407 } 5408 ArraySet<String> pkgNames = new ArraySet<String>(); 5409 if (ris != null) { 5410 for (ResolveInfo ri : ris) { 5411 pkgNames.add(ri.activityInfo.packageName); 5412 } 5413 } 5414 return pkgNames; 5415 } 5416 5417 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5418 if (DEBUG_DEXOPT) { 5419 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5420 } 5421 if (!isFirstBoot()) { 5422 try { 5423 ActivityManagerNative.getDefault().showBootMessage( 5424 mContext.getResources().getString(R.string.android_upgrading_apk, 5425 curr, total), true); 5426 } catch (RemoteException e) { 5427 } 5428 } 5429 PackageParser.Package p = pkg; 5430 synchronized (mInstallLock) { 5431 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5432 false /* force dex */, false /* defer */, true /* include dependencies */); 5433 } 5434 } 5435 5436 @Override 5437 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5438 return performDexOpt(packageName, instructionSet, false); 5439 } 5440 5441 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5442 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5443 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5444 if (!dexopt && !updateUsage) { 5445 // We aren't going to dexopt or update usage, so bail early. 5446 return false; 5447 } 5448 PackageParser.Package p; 5449 final String targetInstructionSet; 5450 synchronized (mPackages) { 5451 p = mPackages.get(packageName); 5452 if (p == null) { 5453 return false; 5454 } 5455 if (updateUsage) { 5456 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5457 } 5458 mPackageUsage.write(false); 5459 if (!dexopt) { 5460 // We aren't going to dexopt, so bail early. 5461 return false; 5462 } 5463 5464 targetInstructionSet = instructionSet != null ? instructionSet : 5465 getPrimaryInstructionSet(p.applicationInfo); 5466 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5467 return false; 5468 } 5469 } 5470 5471 synchronized (mInstallLock) { 5472 final String[] instructionSets = new String[] { targetInstructionSet }; 5473 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5474 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5475 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5476 } 5477 } 5478 5479 public ArraySet<String> getPackagesThatNeedDexOpt() { 5480 ArraySet<String> pkgs = null; 5481 synchronized (mPackages) { 5482 for (PackageParser.Package p : mPackages.values()) { 5483 if (DEBUG_DEXOPT) { 5484 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5485 } 5486 if (!p.mDexOptPerformed.isEmpty()) { 5487 continue; 5488 } 5489 if (pkgs == null) { 5490 pkgs = new ArraySet<String>(); 5491 } 5492 pkgs.add(p.packageName); 5493 } 5494 } 5495 return pkgs; 5496 } 5497 5498 public void shutdown() { 5499 mPackageUsage.write(true); 5500 } 5501 5502 @Override 5503 public void forceDexOpt(String packageName) { 5504 enforceSystemOrRoot("forceDexOpt"); 5505 5506 PackageParser.Package pkg; 5507 synchronized (mPackages) { 5508 pkg = mPackages.get(packageName); 5509 if (pkg == null) { 5510 throw new IllegalArgumentException("Missing package: " + packageName); 5511 } 5512 } 5513 5514 synchronized (mInstallLock) { 5515 final String[] instructionSets = new String[] { 5516 getPrimaryInstructionSet(pkg.applicationInfo) }; 5517 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5518 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5519 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5520 throw new IllegalStateException("Failed to dexopt: " + res); 5521 } 5522 } 5523 } 5524 5525 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5526 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5527 Slog.w(TAG, "Unable to update from " + oldPkg.name 5528 + " to " + newPkg.packageName 5529 + ": old package not in system partition"); 5530 return false; 5531 } else if (mPackages.get(oldPkg.name) != null) { 5532 Slog.w(TAG, "Unable to update from " + oldPkg.name 5533 + " to " + newPkg.packageName 5534 + ": old package still exists"); 5535 return false; 5536 } 5537 return true; 5538 } 5539 5540 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5541 int[] users = sUserManager.getUserIds(); 5542 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5543 if (res < 0) { 5544 return res; 5545 } 5546 for (int user : users) { 5547 if (user != 0) { 5548 res = mInstaller.createUserData(volumeUuid, packageName, 5549 UserHandle.getUid(user, uid), user, seinfo); 5550 if (res < 0) { 5551 return res; 5552 } 5553 } 5554 } 5555 return res; 5556 } 5557 5558 private int removeDataDirsLI(String volumeUuid, String packageName) { 5559 int[] users = sUserManager.getUserIds(); 5560 int res = 0; 5561 for (int user : users) { 5562 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5563 if (resInner < 0) { 5564 res = resInner; 5565 } 5566 } 5567 5568 return res; 5569 } 5570 5571 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5572 int[] users = sUserManager.getUserIds(); 5573 int res = 0; 5574 for (int user : users) { 5575 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5576 if (resInner < 0) { 5577 res = resInner; 5578 } 5579 } 5580 return res; 5581 } 5582 5583 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5584 PackageParser.Package changingLib) { 5585 if (file.path != null) { 5586 usesLibraryFiles.add(file.path); 5587 return; 5588 } 5589 PackageParser.Package p = mPackages.get(file.apk); 5590 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5591 // If we are doing this while in the middle of updating a library apk, 5592 // then we need to make sure to use that new apk for determining the 5593 // dependencies here. (We haven't yet finished committing the new apk 5594 // to the package manager state.) 5595 if (p == null || p.packageName.equals(changingLib.packageName)) { 5596 p = changingLib; 5597 } 5598 } 5599 if (p != null) { 5600 usesLibraryFiles.addAll(p.getAllCodePaths()); 5601 } 5602 } 5603 5604 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5605 PackageParser.Package changingLib) throws PackageManagerException { 5606 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5607 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5608 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5609 for (int i=0; i<N; i++) { 5610 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5611 if (file == null) { 5612 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5613 "Package " + pkg.packageName + " requires unavailable shared library " 5614 + pkg.usesLibraries.get(i) + "; failing!"); 5615 } 5616 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5617 } 5618 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5619 for (int i=0; i<N; i++) { 5620 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5621 if (file == null) { 5622 Slog.w(TAG, "Package " + pkg.packageName 5623 + " desires unavailable shared library " 5624 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5625 } else { 5626 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5627 } 5628 } 5629 N = usesLibraryFiles.size(); 5630 if (N > 0) { 5631 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5632 } else { 5633 pkg.usesLibraryFiles = null; 5634 } 5635 } 5636 } 5637 5638 private static boolean hasString(List<String> list, List<String> which) { 5639 if (list == null) { 5640 return false; 5641 } 5642 for (int i=list.size()-1; i>=0; i--) { 5643 for (int j=which.size()-1; j>=0; j--) { 5644 if (which.get(j).equals(list.get(i))) { 5645 return true; 5646 } 5647 } 5648 } 5649 return false; 5650 } 5651 5652 private void updateAllSharedLibrariesLPw() { 5653 for (PackageParser.Package pkg : mPackages.values()) { 5654 try { 5655 updateSharedLibrariesLPw(pkg, null); 5656 } catch (PackageManagerException e) { 5657 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5658 } 5659 } 5660 } 5661 5662 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5663 PackageParser.Package changingPkg) { 5664 ArrayList<PackageParser.Package> res = null; 5665 for (PackageParser.Package pkg : mPackages.values()) { 5666 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5667 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5668 if (res == null) { 5669 res = new ArrayList<PackageParser.Package>(); 5670 } 5671 res.add(pkg); 5672 try { 5673 updateSharedLibrariesLPw(pkg, changingPkg); 5674 } catch (PackageManagerException e) { 5675 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5676 } 5677 } 5678 } 5679 return res; 5680 } 5681 5682 /** 5683 * Derive the value of the {@code cpuAbiOverride} based on the provided 5684 * value and an optional stored value from the package settings. 5685 */ 5686 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5687 String cpuAbiOverride = null; 5688 5689 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5690 cpuAbiOverride = null; 5691 } else if (abiOverride != null) { 5692 cpuAbiOverride = abiOverride; 5693 } else if (settings != null) { 5694 cpuAbiOverride = settings.cpuAbiOverrideString; 5695 } 5696 5697 return cpuAbiOverride; 5698 } 5699 5700 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5701 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5702 boolean success = false; 5703 try { 5704 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5705 currentTime, user); 5706 success = true; 5707 return res; 5708 } finally { 5709 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5710 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5711 } 5712 } 5713 } 5714 5715 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5716 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5717 final File scanFile = new File(pkg.codePath); 5718 if (pkg.applicationInfo.getCodePath() == null || 5719 pkg.applicationInfo.getResourcePath() == null) { 5720 // Bail out. The resource and code paths haven't been set. 5721 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5722 "Code and resource paths haven't been set correctly"); 5723 } 5724 5725 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5726 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5727 } else { 5728 // Only allow system apps to be flagged as core apps. 5729 pkg.coreApp = false; 5730 } 5731 5732 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5733 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5734 } 5735 5736 if (mCustomResolverComponentName != null && 5737 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5738 setUpCustomResolverActivity(pkg); 5739 } 5740 5741 if (pkg.packageName.equals("android")) { 5742 synchronized (mPackages) { 5743 if (mAndroidApplication != null) { 5744 Slog.w(TAG, "*************************************************"); 5745 Slog.w(TAG, "Core android package being redefined. Skipping."); 5746 Slog.w(TAG, " file=" + scanFile); 5747 Slog.w(TAG, "*************************************************"); 5748 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5749 "Core android package being redefined. Skipping."); 5750 } 5751 5752 // Set up information for our fall-back user intent resolution activity. 5753 mPlatformPackage = pkg; 5754 pkg.mVersionCode = mSdkVersion; 5755 mAndroidApplication = pkg.applicationInfo; 5756 5757 if (!mResolverReplaced) { 5758 mResolveActivity.applicationInfo = mAndroidApplication; 5759 mResolveActivity.name = ResolverActivity.class.getName(); 5760 mResolveActivity.packageName = mAndroidApplication.packageName; 5761 mResolveActivity.processName = "system:ui"; 5762 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5763 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5764 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5765 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5766 mResolveActivity.exported = true; 5767 mResolveActivity.enabled = true; 5768 mResolveInfo.activityInfo = mResolveActivity; 5769 mResolveInfo.priority = 0; 5770 mResolveInfo.preferredOrder = 0; 5771 mResolveInfo.match = 0; 5772 mResolveComponentName = new ComponentName( 5773 mAndroidApplication.packageName, mResolveActivity.name); 5774 } 5775 } 5776 } 5777 5778 if (DEBUG_PACKAGE_SCANNING) { 5779 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5780 Log.d(TAG, "Scanning package " + pkg.packageName); 5781 } 5782 5783 if (mPackages.containsKey(pkg.packageName) 5784 || mSharedLibraries.containsKey(pkg.packageName)) { 5785 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5786 "Application package " + pkg.packageName 5787 + " already installed. Skipping duplicate."); 5788 } 5789 5790 // If we're only installing presumed-existing packages, require that the 5791 // scanned APK is both already known and at the path previously established 5792 // for it. Previously unknown packages we pick up normally, but if we have an 5793 // a priori expectation about this package's install presence, enforce it. 5794 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5795 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5796 if (known != null) { 5797 if (DEBUG_PACKAGE_SCANNING) { 5798 Log.d(TAG, "Examining " + pkg.codePath 5799 + " and requiring known paths " + known.codePathString 5800 + " & " + known.resourcePathString); 5801 } 5802 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5803 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5804 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5805 "Application package " + pkg.packageName 5806 + " found at " + pkg.applicationInfo.getCodePath() 5807 + " but expected at " + known.codePathString + "; ignoring."); 5808 } 5809 } 5810 } 5811 5812 // Initialize package source and resource directories 5813 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5814 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5815 5816 SharedUserSetting suid = null; 5817 PackageSetting pkgSetting = null; 5818 5819 if (!isSystemApp(pkg)) { 5820 // Only system apps can use these features. 5821 pkg.mOriginalPackages = null; 5822 pkg.mRealPackage = null; 5823 pkg.mAdoptPermissions = null; 5824 } 5825 5826 // writer 5827 synchronized (mPackages) { 5828 if (pkg.mSharedUserId != null) { 5829 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5830 if (suid == null) { 5831 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5832 "Creating application package " + pkg.packageName 5833 + " for shared user failed"); 5834 } 5835 if (DEBUG_PACKAGE_SCANNING) { 5836 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5837 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5838 + "): packages=" + suid.packages); 5839 } 5840 } 5841 5842 // Check if we are renaming from an original package name. 5843 PackageSetting origPackage = null; 5844 String realName = null; 5845 if (pkg.mOriginalPackages != null) { 5846 // This package may need to be renamed to a previously 5847 // installed name. Let's check on that... 5848 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5849 if (pkg.mOriginalPackages.contains(renamed)) { 5850 // This package had originally been installed as the 5851 // original name, and we have already taken care of 5852 // transitioning to the new one. Just update the new 5853 // one to continue using the old name. 5854 realName = pkg.mRealPackage; 5855 if (!pkg.packageName.equals(renamed)) { 5856 // Callers into this function may have already taken 5857 // care of renaming the package; only do it here if 5858 // it is not already done. 5859 pkg.setPackageName(renamed); 5860 } 5861 5862 } else { 5863 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5864 if ((origPackage = mSettings.peekPackageLPr( 5865 pkg.mOriginalPackages.get(i))) != null) { 5866 // We do have the package already installed under its 5867 // original name... should we use it? 5868 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5869 // New package is not compatible with original. 5870 origPackage = null; 5871 continue; 5872 } else if (origPackage.sharedUser != null) { 5873 // Make sure uid is compatible between packages. 5874 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5875 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5876 + " to " + pkg.packageName + ": old uid " 5877 + origPackage.sharedUser.name 5878 + " differs from " + pkg.mSharedUserId); 5879 origPackage = null; 5880 continue; 5881 } 5882 } else { 5883 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5884 + pkg.packageName + " to old name " + origPackage.name); 5885 } 5886 break; 5887 } 5888 } 5889 } 5890 } 5891 5892 if (mTransferedPackages.contains(pkg.packageName)) { 5893 Slog.w(TAG, "Package " + pkg.packageName 5894 + " was transferred to another, but its .apk remains"); 5895 } 5896 5897 // Just create the setting, don't add it yet. For already existing packages 5898 // the PkgSetting exists already and doesn't have to be created. 5899 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5900 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5901 pkg.applicationInfo.primaryCpuAbi, 5902 pkg.applicationInfo.secondaryCpuAbi, 5903 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5904 user, false); 5905 if (pkgSetting == null) { 5906 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5907 "Creating application package " + pkg.packageName + " failed"); 5908 } 5909 5910 if (pkgSetting.origPackage != null) { 5911 // If we are first transitioning from an original package, 5912 // fix up the new package's name now. We need to do this after 5913 // looking up the package under its new name, so getPackageLP 5914 // can take care of fiddling things correctly. 5915 pkg.setPackageName(origPackage.name); 5916 5917 // File a report about this. 5918 String msg = "New package " + pkgSetting.realName 5919 + " renamed to replace old package " + pkgSetting.name; 5920 reportSettingsProblem(Log.WARN, msg); 5921 5922 // Make a note of it. 5923 mTransferedPackages.add(origPackage.name); 5924 5925 // No longer need to retain this. 5926 pkgSetting.origPackage = null; 5927 } 5928 5929 if (realName != null) { 5930 // Make a note of it. 5931 mTransferedPackages.add(pkg.packageName); 5932 } 5933 5934 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5935 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5936 } 5937 5938 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5939 // Check all shared libraries and map to their actual file path. 5940 // We only do this here for apps not on a system dir, because those 5941 // are the only ones that can fail an install due to this. We 5942 // will take care of the system apps by updating all of their 5943 // library paths after the scan is done. 5944 updateSharedLibrariesLPw(pkg, null); 5945 } 5946 5947 if (mFoundPolicyFile) { 5948 SELinuxMMAC.assignSeinfoValue(pkg); 5949 } 5950 5951 pkg.applicationInfo.uid = pkgSetting.appId; 5952 pkg.mExtras = pkgSetting; 5953 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5954 try { 5955 verifySignaturesLP(pkgSetting, pkg); 5956 // We just determined the app is signed correctly, so bring 5957 // over the latest parsed certs. 5958 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5959 } catch (PackageManagerException e) { 5960 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5961 throw e; 5962 } 5963 // The signature has changed, but this package is in the system 5964 // image... let's recover! 5965 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5966 // However... if this package is part of a shared user, but it 5967 // doesn't match the signature of the shared user, let's fail. 5968 // What this means is that you can't change the signatures 5969 // associated with an overall shared user, which doesn't seem all 5970 // that unreasonable. 5971 if (pkgSetting.sharedUser != null) { 5972 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5973 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5974 throw new PackageManagerException( 5975 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5976 "Signature mismatch for shared user : " 5977 + pkgSetting.sharedUser); 5978 } 5979 } 5980 // File a report about this. 5981 String msg = "System package " + pkg.packageName 5982 + " signature changed; retaining data."; 5983 reportSettingsProblem(Log.WARN, msg); 5984 } 5985 } else { 5986 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5987 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5988 + pkg.packageName + " upgrade keys do not match the " 5989 + "previously installed version"); 5990 } else { 5991 // We just determined the app is signed correctly, so bring 5992 // over the latest parsed certs. 5993 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5994 } 5995 } 5996 // Verify that this new package doesn't have any content providers 5997 // that conflict with existing packages. Only do this if the 5998 // package isn't already installed, since we don't want to break 5999 // things that are installed. 6000 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6001 final int N = pkg.providers.size(); 6002 int i; 6003 for (i=0; i<N; i++) { 6004 PackageParser.Provider p = pkg.providers.get(i); 6005 if (p.info.authority != null) { 6006 String names[] = p.info.authority.split(";"); 6007 for (int j = 0; j < names.length; j++) { 6008 if (mProvidersByAuthority.containsKey(names[j])) { 6009 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6010 final String otherPackageName = 6011 ((other != null && other.getComponentName() != null) ? 6012 other.getComponentName().getPackageName() : "?"); 6013 throw new PackageManagerException( 6014 INSTALL_FAILED_CONFLICTING_PROVIDER, 6015 "Can't install because provider name " + names[j] 6016 + " (in package " + pkg.applicationInfo.packageName 6017 + ") is already used by " + otherPackageName); 6018 } 6019 } 6020 } 6021 } 6022 } 6023 6024 if (pkg.mAdoptPermissions != null) { 6025 // This package wants to adopt ownership of permissions from 6026 // another package. 6027 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6028 final String origName = pkg.mAdoptPermissions.get(i); 6029 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6030 if (orig != null) { 6031 if (verifyPackageUpdateLPr(orig, pkg)) { 6032 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6033 + pkg.packageName); 6034 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6035 } 6036 } 6037 } 6038 } 6039 } 6040 6041 final String pkgName = pkg.packageName; 6042 6043 final long scanFileTime = scanFile.lastModified(); 6044 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6045 pkg.applicationInfo.processName = fixProcessName( 6046 pkg.applicationInfo.packageName, 6047 pkg.applicationInfo.processName, 6048 pkg.applicationInfo.uid); 6049 6050 File dataPath; 6051 if (mPlatformPackage == pkg) { 6052 // The system package is special. 6053 dataPath = new File(Environment.getDataDirectory(), "system"); 6054 6055 pkg.applicationInfo.dataDir = dataPath.getPath(); 6056 6057 } else { 6058 // This is a normal package, need to make its data directory. 6059 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6060 UserHandle.USER_OWNER); 6061 6062 boolean uidError = false; 6063 if (dataPath.exists()) { 6064 int currentUid = 0; 6065 try { 6066 StructStat stat = Os.stat(dataPath.getPath()); 6067 currentUid = stat.st_uid; 6068 } catch (ErrnoException e) { 6069 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6070 } 6071 6072 // If we have mismatched owners for the data path, we have a problem. 6073 if (currentUid != pkg.applicationInfo.uid) { 6074 boolean recovered = false; 6075 if (currentUid == 0) { 6076 // The directory somehow became owned by root. Wow. 6077 // This is probably because the system was stopped while 6078 // installd was in the middle of messing with its libs 6079 // directory. Ask installd to fix that. 6080 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6081 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6082 if (ret >= 0) { 6083 recovered = true; 6084 String msg = "Package " + pkg.packageName 6085 + " unexpectedly changed to uid 0; recovered to " + 6086 + pkg.applicationInfo.uid; 6087 reportSettingsProblem(Log.WARN, msg); 6088 } 6089 } 6090 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6091 || (scanFlags&SCAN_BOOTING) != 0)) { 6092 // If this is a system app, we can at least delete its 6093 // current data so the application will still work. 6094 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6095 if (ret >= 0) { 6096 // TODO: Kill the processes first 6097 // Old data gone! 6098 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6099 ? "System package " : "Third party package "; 6100 String msg = prefix + pkg.packageName 6101 + " has changed from uid: " 6102 + currentUid + " to " 6103 + pkg.applicationInfo.uid + "; old data erased"; 6104 reportSettingsProblem(Log.WARN, msg); 6105 recovered = true; 6106 6107 // And now re-install the app. 6108 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6109 pkg.applicationInfo.seinfo); 6110 if (ret == -1) { 6111 // Ack should not happen! 6112 msg = prefix + pkg.packageName 6113 + " could not have data directory re-created after delete."; 6114 reportSettingsProblem(Log.WARN, msg); 6115 throw new PackageManagerException( 6116 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6117 } 6118 } 6119 if (!recovered) { 6120 mHasSystemUidErrors = true; 6121 } 6122 } else if (!recovered) { 6123 // If we allow this install to proceed, we will be broken. 6124 // Abort, abort! 6125 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6126 "scanPackageLI"); 6127 } 6128 if (!recovered) { 6129 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6130 + pkg.applicationInfo.uid + "/fs_" 6131 + currentUid; 6132 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6133 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6134 String msg = "Package " + pkg.packageName 6135 + " has mismatched uid: " 6136 + currentUid + " on disk, " 6137 + pkg.applicationInfo.uid + " in settings"; 6138 // writer 6139 synchronized (mPackages) { 6140 mSettings.mReadMessages.append(msg); 6141 mSettings.mReadMessages.append('\n'); 6142 uidError = true; 6143 if (!pkgSetting.uidError) { 6144 reportSettingsProblem(Log.ERROR, msg); 6145 } 6146 } 6147 } 6148 } 6149 pkg.applicationInfo.dataDir = dataPath.getPath(); 6150 if (mShouldRestoreconData) { 6151 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6152 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6153 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6154 } 6155 } else { 6156 if (DEBUG_PACKAGE_SCANNING) { 6157 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6158 Log.v(TAG, "Want this data dir: " + dataPath); 6159 } 6160 //invoke installer to do the actual installation 6161 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6162 pkg.applicationInfo.seinfo); 6163 if (ret < 0) { 6164 // Error from installer 6165 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6166 "Unable to create data dirs [errorCode=" + ret + "]"); 6167 } 6168 6169 if (dataPath.exists()) { 6170 pkg.applicationInfo.dataDir = dataPath.getPath(); 6171 } else { 6172 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6173 pkg.applicationInfo.dataDir = null; 6174 } 6175 } 6176 6177 pkgSetting.uidError = uidError; 6178 } 6179 6180 final String path = scanFile.getPath(); 6181 final String codePath = pkg.applicationInfo.getCodePath(); 6182 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6183 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6184 setBundledAppAbisAndRoots(pkg, pkgSetting); 6185 6186 // If we haven't found any native libraries for the app, check if it has 6187 // renderscript code. We'll need to force the app to 32 bit if it has 6188 // renderscript bitcode. 6189 if (pkg.applicationInfo.primaryCpuAbi == null 6190 && pkg.applicationInfo.secondaryCpuAbi == null 6191 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6192 NativeLibraryHelper.Handle handle = null; 6193 try { 6194 handle = NativeLibraryHelper.Handle.create(scanFile); 6195 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6196 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6197 } 6198 } catch (IOException ioe) { 6199 Slog.w(TAG, "Error scanning system app : " + ioe); 6200 } finally { 6201 IoUtils.closeQuietly(handle); 6202 } 6203 } 6204 6205 setNativeLibraryPaths(pkg); 6206 } else { 6207 // TODO: We can probably be smarter about this stuff. For installed apps, 6208 // we can calculate this information at install time once and for all. For 6209 // system apps, we can probably assume that this information doesn't change 6210 // after the first boot scan. As things stand, we do lots of unnecessary work. 6211 6212 // Give ourselves some initial paths; we'll come back for another 6213 // pass once we've determined ABI below. 6214 setNativeLibraryPaths(pkg); 6215 6216 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6217 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6218 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6219 6220 NativeLibraryHelper.Handle handle = null; 6221 try { 6222 handle = NativeLibraryHelper.Handle.create(scanFile); 6223 // TODO(multiArch): This can be null for apps that didn't go through the 6224 // usual installation process. We can calculate it again, like we 6225 // do during install time. 6226 // 6227 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6228 // unnecessary. 6229 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6230 6231 // Null out the abis so that they can be recalculated. 6232 pkg.applicationInfo.primaryCpuAbi = null; 6233 pkg.applicationInfo.secondaryCpuAbi = null; 6234 if (isMultiArch(pkg.applicationInfo)) { 6235 // Warn if we've set an abiOverride for multi-lib packages.. 6236 // By definition, we need to copy both 32 and 64 bit libraries for 6237 // such packages. 6238 if (pkg.cpuAbiOverride != null 6239 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6240 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6241 } 6242 6243 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6244 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6245 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6246 if (isAsec) { 6247 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6248 } else { 6249 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6250 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6251 useIsaSpecificSubdirs); 6252 } 6253 } 6254 6255 maybeThrowExceptionForMultiArchCopy( 6256 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6257 6258 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6259 if (isAsec) { 6260 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6261 } else { 6262 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6263 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6264 useIsaSpecificSubdirs); 6265 } 6266 } 6267 6268 maybeThrowExceptionForMultiArchCopy( 6269 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6270 6271 if (abi64 >= 0) { 6272 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6273 } 6274 6275 if (abi32 >= 0) { 6276 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6277 if (abi64 >= 0) { 6278 pkg.applicationInfo.secondaryCpuAbi = abi; 6279 } else { 6280 pkg.applicationInfo.primaryCpuAbi = abi; 6281 } 6282 } 6283 } else { 6284 String[] abiList = (cpuAbiOverride != null) ? 6285 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6286 6287 // Enable gross and lame hacks for apps that are built with old 6288 // SDK tools. We must scan their APKs for renderscript bitcode and 6289 // not launch them if it's present. Don't bother checking on devices 6290 // that don't have 64 bit support. 6291 boolean needsRenderScriptOverride = false; 6292 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6293 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6294 abiList = Build.SUPPORTED_32_BIT_ABIS; 6295 needsRenderScriptOverride = true; 6296 } 6297 6298 final int copyRet; 6299 if (isAsec) { 6300 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6301 } else { 6302 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6303 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6304 } 6305 6306 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6307 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6308 "Error unpackaging native libs for app, errorCode=" + copyRet); 6309 } 6310 6311 if (copyRet >= 0) { 6312 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6313 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6314 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6315 } else if (needsRenderScriptOverride) { 6316 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6317 } 6318 } 6319 } catch (IOException ioe) { 6320 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6321 } finally { 6322 IoUtils.closeQuietly(handle); 6323 } 6324 6325 // Now that we've calculated the ABIs and determined if it's an internal app, 6326 // we will go ahead and populate the nativeLibraryPath. 6327 setNativeLibraryPaths(pkg); 6328 6329 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6330 final int[] userIds = sUserManager.getUserIds(); 6331 synchronized (mInstallLock) { 6332 // Create a native library symlink only if we have native libraries 6333 // and if the native libraries are 32 bit libraries. We do not provide 6334 // this symlink for 64 bit libraries. 6335 if (pkg.applicationInfo.primaryCpuAbi != null && 6336 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6337 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6338 for (int userId : userIds) { 6339 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6340 nativeLibPath, userId) < 0) { 6341 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6342 "Failed linking native library dir (user=" + userId + ")"); 6343 } 6344 } 6345 } 6346 } 6347 } 6348 6349 // This is a special case for the "system" package, where the ABI is 6350 // dictated by the zygote configuration (and init.rc). We should keep track 6351 // of this ABI so that we can deal with "normal" applications that run under 6352 // the same UID correctly. 6353 if (mPlatformPackage == pkg) { 6354 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6355 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6356 } 6357 6358 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6359 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6360 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6361 // Copy the derived override back to the parsed package, so that we can 6362 // update the package settings accordingly. 6363 pkg.cpuAbiOverride = cpuAbiOverride; 6364 6365 if (DEBUG_ABI_SELECTION) { 6366 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6367 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6368 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6369 } 6370 6371 // Push the derived path down into PackageSettings so we know what to 6372 // clean up at uninstall time. 6373 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6374 6375 if (DEBUG_ABI_SELECTION) { 6376 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6377 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6378 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6379 } 6380 6381 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6382 // We don't do this here during boot because we can do it all 6383 // at once after scanning all existing packages. 6384 // 6385 // We also do this *before* we perform dexopt on this package, so that 6386 // we can avoid redundant dexopts, and also to make sure we've got the 6387 // code and package path correct. 6388 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6389 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6390 } 6391 6392 if ((scanFlags & SCAN_NO_DEX) == 0) { 6393 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6394 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6395 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6396 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6397 } 6398 } 6399 if (mFactoryTest && pkg.requestedPermissions.contains( 6400 android.Manifest.permission.FACTORY_TEST)) { 6401 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6402 } 6403 6404 ArrayList<PackageParser.Package> clientLibPkgs = null; 6405 6406 // writer 6407 synchronized (mPackages) { 6408 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6409 // Only system apps can add new shared libraries. 6410 if (pkg.libraryNames != null) { 6411 for (int i=0; i<pkg.libraryNames.size(); i++) { 6412 String name = pkg.libraryNames.get(i); 6413 boolean allowed = false; 6414 if (pkg.isUpdatedSystemApp()) { 6415 // New library entries can only be added through the 6416 // system image. This is important to get rid of a lot 6417 // of nasty edge cases: for example if we allowed a non- 6418 // system update of the app to add a library, then uninstalling 6419 // the update would make the library go away, and assumptions 6420 // we made such as through app install filtering would now 6421 // have allowed apps on the device which aren't compatible 6422 // with it. Better to just have the restriction here, be 6423 // conservative, and create many fewer cases that can negatively 6424 // impact the user experience. 6425 final PackageSetting sysPs = mSettings 6426 .getDisabledSystemPkgLPr(pkg.packageName); 6427 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6428 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6429 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6430 allowed = true; 6431 allowed = true; 6432 break; 6433 } 6434 } 6435 } 6436 } else { 6437 allowed = true; 6438 } 6439 if (allowed) { 6440 if (!mSharedLibraries.containsKey(name)) { 6441 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6442 } else if (!name.equals(pkg.packageName)) { 6443 Slog.w(TAG, "Package " + pkg.packageName + " library " 6444 + name + " already exists; skipping"); 6445 } 6446 } else { 6447 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6448 + name + " that is not declared on system image; skipping"); 6449 } 6450 } 6451 if ((scanFlags&SCAN_BOOTING) == 0) { 6452 // If we are not booting, we need to update any applications 6453 // that are clients of our shared library. If we are booting, 6454 // this will all be done once the scan is complete. 6455 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6456 } 6457 } 6458 } 6459 } 6460 6461 // We also need to dexopt any apps that are dependent on this library. Note that 6462 // if these fail, we should abort the install since installing the library will 6463 // result in some apps being broken. 6464 if (clientLibPkgs != null) { 6465 if ((scanFlags & SCAN_NO_DEX) == 0) { 6466 for (int i = 0; i < clientLibPkgs.size(); i++) { 6467 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6468 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6469 null /* instruction sets */, forceDex, 6470 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6471 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6472 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6473 "scanPackageLI failed to dexopt clientLibPkgs"); 6474 } 6475 } 6476 } 6477 } 6478 6479 // Request the ActivityManager to kill the process(only for existing packages) 6480 // so that we do not end up in a confused state while the user is still using the older 6481 // version of the application while the new one gets installed. 6482 if ((scanFlags & SCAN_REPLACING) != 0) { 6483 killApplication(pkg.applicationInfo.packageName, 6484 pkg.applicationInfo.uid, "update pkg"); 6485 } 6486 6487 // Also need to kill any apps that are dependent on the library. 6488 if (clientLibPkgs != null) { 6489 for (int i=0; i<clientLibPkgs.size(); i++) { 6490 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6491 killApplication(clientPkg.applicationInfo.packageName, 6492 clientPkg.applicationInfo.uid, "update lib"); 6493 } 6494 } 6495 6496 // writer 6497 synchronized (mPackages) { 6498 // We don't expect installation to fail beyond this point 6499 6500 // Add the new setting to mSettings 6501 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6502 // Add the new setting to mPackages 6503 mPackages.put(pkg.applicationInfo.packageName, pkg); 6504 // Make sure we don't accidentally delete its data. 6505 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6506 while (iter.hasNext()) { 6507 PackageCleanItem item = iter.next(); 6508 if (pkgName.equals(item.packageName)) { 6509 iter.remove(); 6510 } 6511 } 6512 6513 // Take care of first install / last update times. 6514 if (currentTime != 0) { 6515 if (pkgSetting.firstInstallTime == 0) { 6516 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6517 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6518 pkgSetting.lastUpdateTime = currentTime; 6519 } 6520 } else if (pkgSetting.firstInstallTime == 0) { 6521 // We need *something*. Take time time stamp of the file. 6522 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6523 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6524 if (scanFileTime != pkgSetting.timeStamp) { 6525 // A package on the system image has changed; consider this 6526 // to be an update. 6527 pkgSetting.lastUpdateTime = scanFileTime; 6528 } 6529 } 6530 6531 // Add the package's KeySets to the global KeySetManagerService 6532 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6533 try { 6534 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6535 if (pkg.mKeySetMapping != null) { 6536 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6537 if (pkg.mUpgradeKeySets != null) { 6538 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6539 } 6540 } 6541 } catch (NullPointerException e) { 6542 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6543 } catch (IllegalArgumentException e) { 6544 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6545 } 6546 6547 int N = pkg.providers.size(); 6548 StringBuilder r = null; 6549 int i; 6550 for (i=0; i<N; i++) { 6551 PackageParser.Provider p = pkg.providers.get(i); 6552 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6553 p.info.processName, pkg.applicationInfo.uid); 6554 mProviders.addProvider(p); 6555 p.syncable = p.info.isSyncable; 6556 if (p.info.authority != null) { 6557 String names[] = p.info.authority.split(";"); 6558 p.info.authority = null; 6559 for (int j = 0; j < names.length; j++) { 6560 if (j == 1 && p.syncable) { 6561 // We only want the first authority for a provider to possibly be 6562 // syncable, so if we already added this provider using a different 6563 // authority clear the syncable flag. We copy the provider before 6564 // changing it because the mProviders object contains a reference 6565 // to a provider that we don't want to change. 6566 // Only do this for the second authority since the resulting provider 6567 // object can be the same for all future authorities for this provider. 6568 p = new PackageParser.Provider(p); 6569 p.syncable = false; 6570 } 6571 if (!mProvidersByAuthority.containsKey(names[j])) { 6572 mProvidersByAuthority.put(names[j], p); 6573 if (p.info.authority == null) { 6574 p.info.authority = names[j]; 6575 } else { 6576 p.info.authority = p.info.authority + ";" + names[j]; 6577 } 6578 if (DEBUG_PACKAGE_SCANNING) { 6579 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6580 Log.d(TAG, "Registered content provider: " + names[j] 6581 + ", className = " + p.info.name + ", isSyncable = " 6582 + p.info.isSyncable); 6583 } 6584 } else { 6585 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6586 Slog.w(TAG, "Skipping provider name " + names[j] + 6587 " (in package " + pkg.applicationInfo.packageName + 6588 "): name already used by " 6589 + ((other != null && other.getComponentName() != null) 6590 ? other.getComponentName().getPackageName() : "?")); 6591 } 6592 } 6593 } 6594 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6595 if (r == null) { 6596 r = new StringBuilder(256); 6597 } else { 6598 r.append(' '); 6599 } 6600 r.append(p.info.name); 6601 } 6602 } 6603 if (r != null) { 6604 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6605 } 6606 6607 N = pkg.services.size(); 6608 r = null; 6609 for (i=0; i<N; i++) { 6610 PackageParser.Service s = pkg.services.get(i); 6611 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6612 s.info.processName, pkg.applicationInfo.uid); 6613 mServices.addService(s); 6614 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6615 if (r == null) { 6616 r = new StringBuilder(256); 6617 } else { 6618 r.append(' '); 6619 } 6620 r.append(s.info.name); 6621 } 6622 } 6623 if (r != null) { 6624 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6625 } 6626 6627 N = pkg.receivers.size(); 6628 r = null; 6629 for (i=0; i<N; i++) { 6630 PackageParser.Activity a = pkg.receivers.get(i); 6631 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6632 a.info.processName, pkg.applicationInfo.uid); 6633 mReceivers.addActivity(a, "receiver"); 6634 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6635 if (r == null) { 6636 r = new StringBuilder(256); 6637 } else { 6638 r.append(' '); 6639 } 6640 r.append(a.info.name); 6641 } 6642 } 6643 if (r != null) { 6644 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6645 } 6646 6647 N = pkg.activities.size(); 6648 r = null; 6649 for (i=0; i<N; i++) { 6650 PackageParser.Activity a = pkg.activities.get(i); 6651 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6652 a.info.processName, pkg.applicationInfo.uid); 6653 mActivities.addActivity(a, "activity"); 6654 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6655 if (r == null) { 6656 r = new StringBuilder(256); 6657 } else { 6658 r.append(' '); 6659 } 6660 r.append(a.info.name); 6661 } 6662 } 6663 if (r != null) { 6664 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6665 } 6666 6667 N = pkg.permissionGroups.size(); 6668 r = null; 6669 for (i=0; i<N; i++) { 6670 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6671 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6672 if (cur == null) { 6673 mPermissionGroups.put(pg.info.name, pg); 6674 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6675 if (r == null) { 6676 r = new StringBuilder(256); 6677 } else { 6678 r.append(' '); 6679 } 6680 r.append(pg.info.name); 6681 } 6682 } else { 6683 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6684 + pg.info.packageName + " ignored: original from " 6685 + cur.info.packageName); 6686 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6687 if (r == null) { 6688 r = new StringBuilder(256); 6689 } else { 6690 r.append(' '); 6691 } 6692 r.append("DUP:"); 6693 r.append(pg.info.name); 6694 } 6695 } 6696 } 6697 if (r != null) { 6698 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6699 } 6700 6701 N = pkg.permissions.size(); 6702 r = null; 6703 for (i=0; i<N; i++) { 6704 PackageParser.Permission p = pkg.permissions.get(i); 6705 6706 // Now that permission groups have a special meaning, we ignore permission 6707 // groups for legacy apps to prevent unexpected behavior. In particular, 6708 // permissions for one app being granted to someone just becuase they happen 6709 // to be in a group defined by another app (before this had no implications). 6710 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6711 p.group = mPermissionGroups.get(p.info.group); 6712 // Warn for a permission in an unknown group. 6713 if (p.info.group != null && p.group == null) { 6714 Slog.w(TAG, "Permission " + p.info.name + " from package " 6715 + p.info.packageName + " in an unknown group " + p.info.group); 6716 } 6717 } 6718 6719 ArrayMap<String, BasePermission> permissionMap = 6720 p.tree ? mSettings.mPermissionTrees 6721 : mSettings.mPermissions; 6722 BasePermission bp = permissionMap.get(p.info.name); 6723 6724 // Allow system apps to redefine non-system permissions 6725 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6726 final boolean currentOwnerIsSystem = (bp.perm != null 6727 && isSystemApp(bp.perm.owner)); 6728 if (isSystemApp(p.owner)) { 6729 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6730 // It's a built-in permission and no owner, take ownership now 6731 bp.packageSetting = pkgSetting; 6732 bp.perm = p; 6733 bp.uid = pkg.applicationInfo.uid; 6734 bp.sourcePackage = p.info.packageName; 6735 } else if (!currentOwnerIsSystem) { 6736 String msg = "New decl " + p.owner + " of permission " 6737 + p.info.name + " is system; overriding " + bp.sourcePackage; 6738 reportSettingsProblem(Log.WARN, msg); 6739 bp = null; 6740 } 6741 } 6742 } 6743 6744 if (bp == null) { 6745 bp = new BasePermission(p.info.name, p.info.packageName, 6746 BasePermission.TYPE_NORMAL); 6747 permissionMap.put(p.info.name, bp); 6748 } 6749 6750 if (bp.perm == null) { 6751 if (bp.sourcePackage == null 6752 || bp.sourcePackage.equals(p.info.packageName)) { 6753 BasePermission tree = findPermissionTreeLP(p.info.name); 6754 if (tree == null 6755 || tree.sourcePackage.equals(p.info.packageName)) { 6756 bp.packageSetting = pkgSetting; 6757 bp.perm = p; 6758 bp.uid = pkg.applicationInfo.uid; 6759 bp.sourcePackage = p.info.packageName; 6760 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6761 if (r == null) { 6762 r = new StringBuilder(256); 6763 } else { 6764 r.append(' '); 6765 } 6766 r.append(p.info.name); 6767 } 6768 } else { 6769 Slog.w(TAG, "Permission " + p.info.name + " from package " 6770 + p.info.packageName + " ignored: base tree " 6771 + tree.name + " is from package " 6772 + tree.sourcePackage); 6773 } 6774 } else { 6775 Slog.w(TAG, "Permission " + p.info.name + " from package " 6776 + p.info.packageName + " ignored: original from " 6777 + bp.sourcePackage); 6778 } 6779 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6780 if (r == null) { 6781 r = new StringBuilder(256); 6782 } else { 6783 r.append(' '); 6784 } 6785 r.append("DUP:"); 6786 r.append(p.info.name); 6787 } 6788 if (bp.perm == p) { 6789 bp.protectionLevel = p.info.protectionLevel; 6790 } 6791 } 6792 6793 if (r != null) { 6794 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6795 } 6796 6797 N = pkg.instrumentation.size(); 6798 r = null; 6799 for (i=0; i<N; i++) { 6800 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6801 a.info.packageName = pkg.applicationInfo.packageName; 6802 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6803 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6804 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6805 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6806 a.info.dataDir = pkg.applicationInfo.dataDir; 6807 6808 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6809 // need other information about the application, like the ABI and what not ? 6810 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6811 mInstrumentation.put(a.getComponentName(), a); 6812 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6813 if (r == null) { 6814 r = new StringBuilder(256); 6815 } else { 6816 r.append(' '); 6817 } 6818 r.append(a.info.name); 6819 } 6820 } 6821 if (r != null) { 6822 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6823 } 6824 6825 if (pkg.protectedBroadcasts != null) { 6826 N = pkg.protectedBroadcasts.size(); 6827 for (i=0; i<N; i++) { 6828 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6829 } 6830 } 6831 6832 pkgSetting.setTimeStamp(scanFileTime); 6833 6834 // Create idmap files for pairs of (packages, overlay packages). 6835 // Note: "android", ie framework-res.apk, is handled by native layers. 6836 if (pkg.mOverlayTarget != null) { 6837 // This is an overlay package. 6838 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6839 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6840 mOverlays.put(pkg.mOverlayTarget, 6841 new ArrayMap<String, PackageParser.Package>()); 6842 } 6843 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6844 map.put(pkg.packageName, pkg); 6845 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6846 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6847 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6848 "scanPackageLI failed to createIdmap"); 6849 } 6850 } 6851 } else if (mOverlays.containsKey(pkg.packageName) && 6852 !pkg.packageName.equals("android")) { 6853 // This is a regular package, with one or more known overlay packages. 6854 createIdmapsForPackageLI(pkg); 6855 } 6856 } 6857 6858 return pkg; 6859 } 6860 6861 /** 6862 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6863 * i.e, so that all packages can be run inside a single process if required. 6864 * 6865 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6866 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6867 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6868 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6869 * updating a package that belongs to a shared user. 6870 * 6871 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6872 * adds unnecessary complexity. 6873 */ 6874 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6875 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6876 String requiredInstructionSet = null; 6877 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6878 requiredInstructionSet = VMRuntime.getInstructionSet( 6879 scannedPackage.applicationInfo.primaryCpuAbi); 6880 } 6881 6882 PackageSetting requirer = null; 6883 for (PackageSetting ps : packagesForUser) { 6884 // If packagesForUser contains scannedPackage, we skip it. This will happen 6885 // when scannedPackage is an update of an existing package. Without this check, 6886 // we will never be able to change the ABI of any package belonging to a shared 6887 // user, even if it's compatible with other packages. 6888 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6889 if (ps.primaryCpuAbiString == null) { 6890 continue; 6891 } 6892 6893 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6894 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6895 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6896 // this but there's not much we can do. 6897 String errorMessage = "Instruction set mismatch, " 6898 + ((requirer == null) ? "[caller]" : requirer) 6899 + " requires " + requiredInstructionSet + " whereas " + ps 6900 + " requires " + instructionSet; 6901 Slog.w(TAG, errorMessage); 6902 } 6903 6904 if (requiredInstructionSet == null) { 6905 requiredInstructionSet = instructionSet; 6906 requirer = ps; 6907 } 6908 } 6909 } 6910 6911 if (requiredInstructionSet != null) { 6912 String adjustedAbi; 6913 if (requirer != null) { 6914 // requirer != null implies that either scannedPackage was null or that scannedPackage 6915 // did not require an ABI, in which case we have to adjust scannedPackage to match 6916 // the ABI of the set (which is the same as requirer's ABI) 6917 adjustedAbi = requirer.primaryCpuAbiString; 6918 if (scannedPackage != null) { 6919 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6920 } 6921 } else { 6922 // requirer == null implies that we're updating all ABIs in the set to 6923 // match scannedPackage. 6924 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6925 } 6926 6927 for (PackageSetting ps : packagesForUser) { 6928 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6929 if (ps.primaryCpuAbiString != null) { 6930 continue; 6931 } 6932 6933 ps.primaryCpuAbiString = adjustedAbi; 6934 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6935 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6936 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6937 6938 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6939 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6940 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6941 ps.primaryCpuAbiString = null; 6942 ps.pkg.applicationInfo.primaryCpuAbi = null; 6943 return; 6944 } else { 6945 mInstaller.rmdex(ps.codePathString, 6946 getDexCodeInstructionSet(getPreferredInstructionSet())); 6947 } 6948 } 6949 } 6950 } 6951 } 6952 } 6953 6954 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6955 synchronized (mPackages) { 6956 mResolverReplaced = true; 6957 // Set up information for custom user intent resolution activity. 6958 mResolveActivity.applicationInfo = pkg.applicationInfo; 6959 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6960 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6961 mResolveActivity.processName = pkg.applicationInfo.packageName; 6962 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6963 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6964 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6965 mResolveActivity.theme = 0; 6966 mResolveActivity.exported = true; 6967 mResolveActivity.enabled = true; 6968 mResolveInfo.activityInfo = mResolveActivity; 6969 mResolveInfo.priority = 0; 6970 mResolveInfo.preferredOrder = 0; 6971 mResolveInfo.match = 0; 6972 mResolveComponentName = mCustomResolverComponentName; 6973 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6974 mResolveComponentName); 6975 } 6976 } 6977 6978 private static String calculateBundledApkRoot(final String codePathString) { 6979 final File codePath = new File(codePathString); 6980 final File codeRoot; 6981 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6982 codeRoot = Environment.getRootDirectory(); 6983 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6984 codeRoot = Environment.getOemDirectory(); 6985 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6986 codeRoot = Environment.getVendorDirectory(); 6987 } else { 6988 // Unrecognized code path; take its top real segment as the apk root: 6989 // e.g. /something/app/blah.apk => /something 6990 try { 6991 File f = codePath.getCanonicalFile(); 6992 File parent = f.getParentFile(); // non-null because codePath is a file 6993 File tmp; 6994 while ((tmp = parent.getParentFile()) != null) { 6995 f = parent; 6996 parent = tmp; 6997 } 6998 codeRoot = f; 6999 Slog.w(TAG, "Unrecognized code path " 7000 + codePath + " - using " + codeRoot); 7001 } catch (IOException e) { 7002 // Can't canonicalize the code path -- shenanigans? 7003 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7004 return Environment.getRootDirectory().getPath(); 7005 } 7006 } 7007 return codeRoot.getPath(); 7008 } 7009 7010 /** 7011 * Derive and set the location of native libraries for the given package, 7012 * which varies depending on where and how the package was installed. 7013 */ 7014 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7015 final ApplicationInfo info = pkg.applicationInfo; 7016 final String codePath = pkg.codePath; 7017 final File codeFile = new File(codePath); 7018 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7019 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7020 7021 info.nativeLibraryRootDir = null; 7022 info.nativeLibraryRootRequiresIsa = false; 7023 info.nativeLibraryDir = null; 7024 info.secondaryNativeLibraryDir = null; 7025 7026 if (isApkFile(codeFile)) { 7027 // Monolithic install 7028 if (bundledApp) { 7029 // If "/system/lib64/apkname" exists, assume that is the per-package 7030 // native library directory to use; otherwise use "/system/lib/apkname". 7031 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7032 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7033 getPrimaryInstructionSet(info)); 7034 7035 // This is a bundled system app so choose the path based on the ABI. 7036 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7037 // is just the default path. 7038 final String apkName = deriveCodePathName(codePath); 7039 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7040 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7041 apkName).getAbsolutePath(); 7042 7043 if (info.secondaryCpuAbi != null) { 7044 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7045 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7046 secondaryLibDir, apkName).getAbsolutePath(); 7047 } 7048 } else if (asecApp) { 7049 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7050 .getAbsolutePath(); 7051 } else { 7052 final String apkName = deriveCodePathName(codePath); 7053 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7054 .getAbsolutePath(); 7055 } 7056 7057 info.nativeLibraryRootRequiresIsa = false; 7058 info.nativeLibraryDir = info.nativeLibraryRootDir; 7059 } else { 7060 // Cluster install 7061 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7062 info.nativeLibraryRootRequiresIsa = true; 7063 7064 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7065 getPrimaryInstructionSet(info)).getAbsolutePath(); 7066 7067 if (info.secondaryCpuAbi != null) { 7068 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7069 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7070 } 7071 } 7072 } 7073 7074 /** 7075 * Calculate the abis and roots for a bundled app. These can uniquely 7076 * be determined from the contents of the system partition, i.e whether 7077 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7078 * of this information, and instead assume that the system was built 7079 * sensibly. 7080 */ 7081 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7082 PackageSetting pkgSetting) { 7083 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7084 7085 // If "/system/lib64/apkname" exists, assume that is the per-package 7086 // native library directory to use; otherwise use "/system/lib/apkname". 7087 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7088 setBundledAppAbi(pkg, apkRoot, apkName); 7089 // pkgSetting might be null during rescan following uninstall of updates 7090 // to a bundled app, so accommodate that possibility. The settings in 7091 // that case will be established later from the parsed package. 7092 // 7093 // If the settings aren't null, sync them up with what we've just derived. 7094 // note that apkRoot isn't stored in the package settings. 7095 if (pkgSetting != null) { 7096 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7097 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7098 } 7099 } 7100 7101 /** 7102 * Deduces the ABI of a bundled app and sets the relevant fields on the 7103 * parsed pkg object. 7104 * 7105 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7106 * under which system libraries are installed. 7107 * @param apkName the name of the installed package. 7108 */ 7109 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7110 final File codeFile = new File(pkg.codePath); 7111 7112 final boolean has64BitLibs; 7113 final boolean has32BitLibs; 7114 if (isApkFile(codeFile)) { 7115 // Monolithic install 7116 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7117 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7118 } else { 7119 // Cluster install 7120 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7121 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7122 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7123 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7124 has64BitLibs = (new File(rootDir, isa)).exists(); 7125 } else { 7126 has64BitLibs = false; 7127 } 7128 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7129 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7130 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7131 has32BitLibs = (new File(rootDir, isa)).exists(); 7132 } else { 7133 has32BitLibs = false; 7134 } 7135 } 7136 7137 if (has64BitLibs && !has32BitLibs) { 7138 // The package has 64 bit libs, but not 32 bit libs. Its primary 7139 // ABI should be 64 bit. We can safely assume here that the bundled 7140 // native libraries correspond to the most preferred ABI in the list. 7141 7142 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7143 pkg.applicationInfo.secondaryCpuAbi = null; 7144 } else if (has32BitLibs && !has64BitLibs) { 7145 // The package has 32 bit libs but not 64 bit libs. Its primary 7146 // ABI should be 32 bit. 7147 7148 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7149 pkg.applicationInfo.secondaryCpuAbi = null; 7150 } else if (has32BitLibs && has64BitLibs) { 7151 // The application has both 64 and 32 bit bundled libraries. We check 7152 // here that the app declares multiArch support, and warn if it doesn't. 7153 // 7154 // We will be lenient here and record both ABIs. The primary will be the 7155 // ABI that's higher on the list, i.e, a device that's configured to prefer 7156 // 64 bit apps will see a 64 bit primary ABI, 7157 7158 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7159 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7160 } 7161 7162 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7163 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7164 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7165 } else { 7166 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7167 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7168 } 7169 } else { 7170 pkg.applicationInfo.primaryCpuAbi = null; 7171 pkg.applicationInfo.secondaryCpuAbi = null; 7172 } 7173 } 7174 7175 private void killApplication(String pkgName, int appId, String reason) { 7176 // Request the ActivityManager to kill the process(only for existing packages) 7177 // so that we do not end up in a confused state while the user is still using the older 7178 // version of the application while the new one gets installed. 7179 IActivityManager am = ActivityManagerNative.getDefault(); 7180 if (am != null) { 7181 try { 7182 am.killApplicationWithAppId(pkgName, appId, reason); 7183 } catch (RemoteException e) { 7184 } 7185 } 7186 } 7187 7188 void removePackageLI(PackageSetting ps, boolean chatty) { 7189 if (DEBUG_INSTALL) { 7190 if (chatty) 7191 Log.d(TAG, "Removing package " + ps.name); 7192 } 7193 7194 // writer 7195 synchronized (mPackages) { 7196 mPackages.remove(ps.name); 7197 final PackageParser.Package pkg = ps.pkg; 7198 if (pkg != null) { 7199 cleanPackageDataStructuresLILPw(pkg, chatty); 7200 } 7201 } 7202 } 7203 7204 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7205 if (DEBUG_INSTALL) { 7206 if (chatty) 7207 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7208 } 7209 7210 // writer 7211 synchronized (mPackages) { 7212 mPackages.remove(pkg.applicationInfo.packageName); 7213 cleanPackageDataStructuresLILPw(pkg, chatty); 7214 } 7215 } 7216 7217 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7218 int N = pkg.providers.size(); 7219 StringBuilder r = null; 7220 int i; 7221 for (i=0; i<N; i++) { 7222 PackageParser.Provider p = pkg.providers.get(i); 7223 mProviders.removeProvider(p); 7224 if (p.info.authority == null) { 7225 7226 /* There was another ContentProvider with this authority when 7227 * this app was installed so this authority is null, 7228 * Ignore it as we don't have to unregister the provider. 7229 */ 7230 continue; 7231 } 7232 String names[] = p.info.authority.split(";"); 7233 for (int j = 0; j < names.length; j++) { 7234 if (mProvidersByAuthority.get(names[j]) == p) { 7235 mProvidersByAuthority.remove(names[j]); 7236 if (DEBUG_REMOVE) { 7237 if (chatty) 7238 Log.d(TAG, "Unregistered content provider: " + names[j] 7239 + ", className = " + p.info.name + ", isSyncable = " 7240 + p.info.isSyncable); 7241 } 7242 } 7243 } 7244 if (DEBUG_REMOVE && chatty) { 7245 if (r == null) { 7246 r = new StringBuilder(256); 7247 } else { 7248 r.append(' '); 7249 } 7250 r.append(p.info.name); 7251 } 7252 } 7253 if (r != null) { 7254 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7255 } 7256 7257 N = pkg.services.size(); 7258 r = null; 7259 for (i=0; i<N; i++) { 7260 PackageParser.Service s = pkg.services.get(i); 7261 mServices.removeService(s); 7262 if (chatty) { 7263 if (r == null) { 7264 r = new StringBuilder(256); 7265 } else { 7266 r.append(' '); 7267 } 7268 r.append(s.info.name); 7269 } 7270 } 7271 if (r != null) { 7272 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7273 } 7274 7275 N = pkg.receivers.size(); 7276 r = null; 7277 for (i=0; i<N; i++) { 7278 PackageParser.Activity a = pkg.receivers.get(i); 7279 mReceivers.removeActivity(a, "receiver"); 7280 if (DEBUG_REMOVE && chatty) { 7281 if (r == null) { 7282 r = new StringBuilder(256); 7283 } else { 7284 r.append(' '); 7285 } 7286 r.append(a.info.name); 7287 } 7288 } 7289 if (r != null) { 7290 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7291 } 7292 7293 N = pkg.activities.size(); 7294 r = null; 7295 for (i=0; i<N; i++) { 7296 PackageParser.Activity a = pkg.activities.get(i); 7297 mActivities.removeActivity(a, "activity"); 7298 if (DEBUG_REMOVE && chatty) { 7299 if (r == null) { 7300 r = new StringBuilder(256); 7301 } else { 7302 r.append(' '); 7303 } 7304 r.append(a.info.name); 7305 } 7306 } 7307 if (r != null) { 7308 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7309 } 7310 7311 N = pkg.permissions.size(); 7312 r = null; 7313 for (i=0; i<N; i++) { 7314 PackageParser.Permission p = pkg.permissions.get(i); 7315 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7316 if (bp == null) { 7317 bp = mSettings.mPermissionTrees.get(p.info.name); 7318 } 7319 if (bp != null && bp.perm == p) { 7320 bp.perm = null; 7321 if (DEBUG_REMOVE && chatty) { 7322 if (r == null) { 7323 r = new StringBuilder(256); 7324 } else { 7325 r.append(' '); 7326 } 7327 r.append(p.info.name); 7328 } 7329 } 7330 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7331 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7332 if (appOpPerms != null) { 7333 appOpPerms.remove(pkg.packageName); 7334 } 7335 } 7336 } 7337 if (r != null) { 7338 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7339 } 7340 7341 N = pkg.requestedPermissions.size(); 7342 r = null; 7343 for (i=0; i<N; i++) { 7344 String perm = pkg.requestedPermissions.get(i); 7345 BasePermission bp = mSettings.mPermissions.get(perm); 7346 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7347 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7348 if (appOpPerms != null) { 7349 appOpPerms.remove(pkg.packageName); 7350 if (appOpPerms.isEmpty()) { 7351 mAppOpPermissionPackages.remove(perm); 7352 } 7353 } 7354 } 7355 } 7356 if (r != null) { 7357 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7358 } 7359 7360 N = pkg.instrumentation.size(); 7361 r = null; 7362 for (i=0; i<N; i++) { 7363 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7364 mInstrumentation.remove(a.getComponentName()); 7365 if (DEBUG_REMOVE && chatty) { 7366 if (r == null) { 7367 r = new StringBuilder(256); 7368 } else { 7369 r.append(' '); 7370 } 7371 r.append(a.info.name); 7372 } 7373 } 7374 if (r != null) { 7375 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7376 } 7377 7378 r = null; 7379 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7380 // Only system apps can hold shared libraries. 7381 if (pkg.libraryNames != null) { 7382 for (i=0; i<pkg.libraryNames.size(); i++) { 7383 String name = pkg.libraryNames.get(i); 7384 SharedLibraryEntry cur = mSharedLibraries.get(name); 7385 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7386 mSharedLibraries.remove(name); 7387 if (DEBUG_REMOVE && chatty) { 7388 if (r == null) { 7389 r = new StringBuilder(256); 7390 } else { 7391 r.append(' '); 7392 } 7393 r.append(name); 7394 } 7395 } 7396 } 7397 } 7398 } 7399 if (r != null) { 7400 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7401 } 7402 } 7403 7404 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7405 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7406 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7407 return true; 7408 } 7409 } 7410 return false; 7411 } 7412 7413 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7414 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7415 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7416 7417 private void updatePermissionsLPw(String changingPkg, 7418 PackageParser.Package pkgInfo, int flags) { 7419 // Make sure there are no dangling permission trees. 7420 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7421 while (it.hasNext()) { 7422 final BasePermission bp = it.next(); 7423 if (bp.packageSetting == null) { 7424 // We may not yet have parsed the package, so just see if 7425 // we still know about its settings. 7426 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7427 } 7428 if (bp.packageSetting == null) { 7429 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7430 + " from package " + bp.sourcePackage); 7431 it.remove(); 7432 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7433 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7434 Slog.i(TAG, "Removing old permission tree: " + bp.name 7435 + " from package " + bp.sourcePackage); 7436 flags |= UPDATE_PERMISSIONS_ALL; 7437 it.remove(); 7438 } 7439 } 7440 } 7441 7442 // Make sure all dynamic permissions have been assigned to a package, 7443 // and make sure there are no dangling permissions. 7444 it = mSettings.mPermissions.values().iterator(); 7445 while (it.hasNext()) { 7446 final BasePermission bp = it.next(); 7447 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7448 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7449 + bp.name + " pkg=" + bp.sourcePackage 7450 + " info=" + bp.pendingInfo); 7451 if (bp.packageSetting == null && bp.pendingInfo != null) { 7452 final BasePermission tree = findPermissionTreeLP(bp.name); 7453 if (tree != null && tree.perm != null) { 7454 bp.packageSetting = tree.packageSetting; 7455 bp.perm = new PackageParser.Permission(tree.perm.owner, 7456 new PermissionInfo(bp.pendingInfo)); 7457 bp.perm.info.packageName = tree.perm.info.packageName; 7458 bp.perm.info.name = bp.name; 7459 bp.uid = tree.uid; 7460 } 7461 } 7462 } 7463 if (bp.packageSetting == null) { 7464 // We may not yet have parsed the package, so just see if 7465 // we still know about its settings. 7466 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7467 } 7468 if (bp.packageSetting == null) { 7469 Slog.w(TAG, "Removing dangling permission: " + bp.name 7470 + " from package " + bp.sourcePackage); 7471 it.remove(); 7472 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7473 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7474 Slog.i(TAG, "Removing old permission: " + bp.name 7475 + " from package " + bp.sourcePackage); 7476 flags |= UPDATE_PERMISSIONS_ALL; 7477 it.remove(); 7478 } 7479 } 7480 } 7481 7482 // Now update the permissions for all packages, in particular 7483 // replace the granted permissions of the system packages. 7484 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7485 for (PackageParser.Package pkg : mPackages.values()) { 7486 if (pkg != pkgInfo) { 7487 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7488 changingPkg); 7489 } 7490 } 7491 } 7492 7493 if (pkgInfo != null) { 7494 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7495 } 7496 } 7497 7498 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7499 String packageOfInterest) { 7500 // IMPORTANT: There are two types of permissions: install and runtime. 7501 // Install time permissions are granted when the app is installed to 7502 // all device users and users added in the future. Runtime permissions 7503 // are granted at runtime explicitly to specific users. Normal and signature 7504 // protected permissions are install time permissions. Dangerous permissions 7505 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7506 // otherwise they are runtime permissions. This function does not manage 7507 // runtime permissions except for the case an app targeting Lollipop MR1 7508 // being upgraded to target a newer SDK, in which case dangerous permissions 7509 // are transformed from install time to runtime ones. 7510 7511 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7512 if (ps == null) { 7513 return; 7514 } 7515 7516 PermissionsState permissionsState = ps.getPermissionsState(); 7517 PermissionsState origPermissions = permissionsState; 7518 7519 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7520 7521 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7522 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7523 7524 boolean changedInstallPermission = false; 7525 7526 if (replace) { 7527 ps.installPermissionsFixed = false; 7528 if (!ps.isSharedUser()) { 7529 origPermissions = new PermissionsState(permissionsState); 7530 permissionsState.reset(); 7531 } 7532 } 7533 7534 permissionsState.setGlobalGids(mGlobalGids); 7535 7536 final int N = pkg.requestedPermissions.size(); 7537 for (int i=0; i<N; i++) { 7538 final String name = pkg.requestedPermissions.get(i); 7539 final BasePermission bp = mSettings.mPermissions.get(name); 7540 7541 if (DEBUG_INSTALL) { 7542 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7543 } 7544 7545 if (bp == null || bp.packageSetting == null) { 7546 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7547 Slog.w(TAG, "Unknown permission " + name 7548 + " in package " + pkg.packageName); 7549 } 7550 continue; 7551 } 7552 7553 final String perm = bp.name; 7554 boolean allowedSig = false; 7555 int grant = GRANT_DENIED; 7556 7557 // Keep track of app op permissions. 7558 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7559 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7560 if (pkgs == null) { 7561 pkgs = new ArraySet<>(); 7562 mAppOpPermissionPackages.put(bp.name, pkgs); 7563 } 7564 pkgs.add(pkg.packageName); 7565 } 7566 7567 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7568 switch (level) { 7569 case PermissionInfo.PROTECTION_NORMAL: { 7570 // For all apps normal permissions are install time ones. 7571 grant = GRANT_INSTALL; 7572 } break; 7573 7574 case PermissionInfo.PROTECTION_DANGEROUS: { 7575 if (!RUNTIME_PERMISSIONS_ENABLED 7576 || pkg.applicationInfo.targetSdkVersion 7577 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7578 // For legacy apps dangerous permissions are install time ones. 7579 grant = GRANT_INSTALL; 7580 } else if (ps.isSystem()) { 7581 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7582 if (origPermissions.hasInstallPermission(bp.name)) { 7583 // If a system app had an install permission, then the app was 7584 // upgraded and we grant the permissions as runtime to all users. 7585 grant = GRANT_UPGRADE; 7586 upgradeUserIds = currentUserIds; 7587 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7588 // If users changed since the last permissions update for a 7589 // system app, we grant the permission as runtime to the new users. 7590 grant = GRANT_UPGRADE; 7591 upgradeUserIds = currentUserIds; 7592 for (int userId : updatedUserIds) { 7593 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7594 } 7595 } else { 7596 // Otherwise, we grant the permission as runtime if the app 7597 // already had it, i.e. we preserve runtime permissions. 7598 grant = GRANT_RUNTIME; 7599 } 7600 } else if (origPermissions.hasInstallPermission(bp.name)) { 7601 // For legacy apps that became modern, install becomes runtime. 7602 grant = GRANT_UPGRADE; 7603 upgradeUserIds = currentUserIds; 7604 } else if (replace) { 7605 // For upgraded modern apps keep runtime permissions unchanged. 7606 grant = GRANT_RUNTIME; 7607 } 7608 } break; 7609 7610 case PermissionInfo.PROTECTION_SIGNATURE: { 7611 // For all apps signature permissions are install time ones. 7612 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7613 if (allowedSig) { 7614 grant = GRANT_INSTALL; 7615 } 7616 } break; 7617 } 7618 7619 if (DEBUG_INSTALL) { 7620 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7621 } 7622 7623 if (grant != GRANT_DENIED) { 7624 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7625 // If this is an existing, non-system package, then 7626 // we can't add any new permissions to it. 7627 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7628 // Except... if this is a permission that was added 7629 // to the platform (note: need to only do this when 7630 // updating the platform). 7631 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7632 grant = GRANT_DENIED; 7633 } 7634 } 7635 } 7636 7637 switch (grant) { 7638 case GRANT_INSTALL: { 7639 // Grant an install permission. 7640 if (permissionsState.grantInstallPermission(bp) != 7641 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7642 changedInstallPermission = true; 7643 } 7644 } break; 7645 7646 case GRANT_RUNTIME: { 7647 // Grant previously granted runtime permissions. 7648 for (int userId : UserManagerService.getInstance().getUserIds()) { 7649 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7650 if (permissionsState.grantRuntimePermission(bp, userId) == 7651 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7652 // If we cannot put the permission as it was, we have to write. 7653 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7654 changedRuntimePermissionUserIds, userId); 7655 } 7656 } 7657 } 7658 } break; 7659 7660 case GRANT_UPGRADE: { 7661 // Grant runtime permissions for a previously held install permission. 7662 permissionsState.revokeInstallPermission(bp); 7663 for (int userId : upgradeUserIds) { 7664 if (permissionsState.grantRuntimePermission(bp, userId) != 7665 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7666 // If we granted the permission, we have to write. 7667 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7668 changedRuntimePermissionUserIds, userId); 7669 } 7670 } 7671 } break; 7672 7673 default: { 7674 if (packageOfInterest == null 7675 || packageOfInterest.equals(pkg.packageName)) { 7676 Slog.w(TAG, "Not granting permission " + perm 7677 + " to package " + pkg.packageName 7678 + " because it was previously installed without"); 7679 } 7680 } break; 7681 } 7682 } else { 7683 if (permissionsState.revokeInstallPermission(bp) != 7684 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7685 changedInstallPermission = true; 7686 Slog.i(TAG, "Un-granting permission " + perm 7687 + " from package " + pkg.packageName 7688 + " (protectionLevel=" + bp.protectionLevel 7689 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7690 + ")"); 7691 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7692 // Don't print warning for app op permissions, since it is fine for them 7693 // not to be granted, there is a UI for the user to decide. 7694 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7695 Slog.w(TAG, "Not granting permission " + perm 7696 + " to package " + pkg.packageName 7697 + " (protectionLevel=" + bp.protectionLevel 7698 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7699 + ")"); 7700 } 7701 } 7702 } 7703 } 7704 7705 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7706 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7707 // This is the first that we have heard about this package, so the 7708 // permissions we have now selected are fixed until explicitly 7709 // changed. 7710 ps.installPermissionsFixed = true; 7711 } 7712 7713 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7714 7715 // Persist the runtime permissions state for users with changes. 7716 if (RUNTIME_PERMISSIONS_ENABLED) { 7717 for (int userId : changedRuntimePermissionUserIds) { 7718 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7719 } 7720 } 7721 } 7722 7723 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7724 boolean allowed = false; 7725 final int NP = PackageParser.NEW_PERMISSIONS.length; 7726 for (int ip=0; ip<NP; ip++) { 7727 final PackageParser.NewPermissionInfo npi 7728 = PackageParser.NEW_PERMISSIONS[ip]; 7729 if (npi.name.equals(perm) 7730 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7731 allowed = true; 7732 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7733 + pkg.packageName); 7734 break; 7735 } 7736 } 7737 return allowed; 7738 } 7739 7740 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7741 BasePermission bp, PermissionsState origPermissions) { 7742 boolean allowed; 7743 allowed = (compareSignatures( 7744 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7745 == PackageManager.SIGNATURE_MATCH) 7746 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7747 == PackageManager.SIGNATURE_MATCH); 7748 if (!allowed && (bp.protectionLevel 7749 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7750 if (isSystemApp(pkg)) { 7751 // For updated system applications, a system permission 7752 // is granted only if it had been defined by the original application. 7753 if (pkg.isUpdatedSystemApp()) { 7754 final PackageSetting sysPs = mSettings 7755 .getDisabledSystemPkgLPr(pkg.packageName); 7756 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7757 // If the original was granted this permission, we take 7758 // that grant decision as read and propagate it to the 7759 // update. 7760 if (sysPs.isPrivileged()) { 7761 allowed = true; 7762 } 7763 } else { 7764 // The system apk may have been updated with an older 7765 // version of the one on the data partition, but which 7766 // granted a new system permission that it didn't have 7767 // before. In this case we do want to allow the app to 7768 // now get the new permission if the ancestral apk is 7769 // privileged to get it. 7770 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7771 for (int j=0; 7772 j<sysPs.pkg.requestedPermissions.size(); j++) { 7773 if (perm.equals( 7774 sysPs.pkg.requestedPermissions.get(j))) { 7775 allowed = true; 7776 break; 7777 } 7778 } 7779 } 7780 } 7781 } else { 7782 allowed = isPrivilegedApp(pkg); 7783 } 7784 } 7785 } 7786 if (!allowed && (bp.protectionLevel 7787 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7788 // For development permissions, a development permission 7789 // is granted only if it was already granted. 7790 allowed = origPermissions.hasInstallPermission(perm); 7791 } 7792 return allowed; 7793 } 7794 7795 final class ActivityIntentResolver 7796 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7797 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7798 boolean defaultOnly, int userId) { 7799 if (!sUserManager.exists(userId)) return null; 7800 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7801 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7802 } 7803 7804 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7805 int userId) { 7806 if (!sUserManager.exists(userId)) return null; 7807 mFlags = flags; 7808 return super.queryIntent(intent, resolvedType, 7809 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7810 } 7811 7812 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7813 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7814 if (!sUserManager.exists(userId)) return null; 7815 if (packageActivities == null) { 7816 return null; 7817 } 7818 mFlags = flags; 7819 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7820 final int N = packageActivities.size(); 7821 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7822 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7823 7824 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7825 for (int i = 0; i < N; ++i) { 7826 intentFilters = packageActivities.get(i).intents; 7827 if (intentFilters != null && intentFilters.size() > 0) { 7828 PackageParser.ActivityIntentInfo[] array = 7829 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7830 intentFilters.toArray(array); 7831 listCut.add(array); 7832 } 7833 } 7834 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7835 } 7836 7837 public final void addActivity(PackageParser.Activity a, String type) { 7838 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7839 mActivities.put(a.getComponentName(), a); 7840 if (DEBUG_SHOW_INFO) 7841 Log.v( 7842 TAG, " " + type + " " + 7843 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7844 if (DEBUG_SHOW_INFO) 7845 Log.v(TAG, " Class=" + a.info.name); 7846 final int NI = a.intents.size(); 7847 for (int j=0; j<NI; j++) { 7848 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7849 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7850 intent.setPriority(0); 7851 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7852 + a.className + " with priority > 0, forcing to 0"); 7853 } 7854 if (DEBUG_SHOW_INFO) { 7855 Log.v(TAG, " IntentFilter:"); 7856 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7857 } 7858 if (!intent.debugCheck()) { 7859 Log.w(TAG, "==> For Activity " + a.info.name); 7860 } 7861 addFilter(intent); 7862 } 7863 } 7864 7865 public final void removeActivity(PackageParser.Activity a, String type) { 7866 mActivities.remove(a.getComponentName()); 7867 if (DEBUG_SHOW_INFO) { 7868 Log.v(TAG, " " + type + " " 7869 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7870 : a.info.name) + ":"); 7871 Log.v(TAG, " Class=" + a.info.name); 7872 } 7873 final int NI = a.intents.size(); 7874 for (int j=0; j<NI; j++) { 7875 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7876 if (DEBUG_SHOW_INFO) { 7877 Log.v(TAG, " IntentFilter:"); 7878 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7879 } 7880 removeFilter(intent); 7881 } 7882 } 7883 7884 @Override 7885 protected boolean allowFilterResult( 7886 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7887 ActivityInfo filterAi = filter.activity.info; 7888 for (int i=dest.size()-1; i>=0; i--) { 7889 ActivityInfo destAi = dest.get(i).activityInfo; 7890 if (destAi.name == filterAi.name 7891 && destAi.packageName == filterAi.packageName) { 7892 return false; 7893 } 7894 } 7895 return true; 7896 } 7897 7898 @Override 7899 protected ActivityIntentInfo[] newArray(int size) { 7900 return new ActivityIntentInfo[size]; 7901 } 7902 7903 @Override 7904 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7905 if (!sUserManager.exists(userId)) return true; 7906 PackageParser.Package p = filter.activity.owner; 7907 if (p != null) { 7908 PackageSetting ps = (PackageSetting)p.mExtras; 7909 if (ps != null) { 7910 // System apps are never considered stopped for purposes of 7911 // filtering, because there may be no way for the user to 7912 // actually re-launch them. 7913 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7914 && ps.getStopped(userId); 7915 } 7916 } 7917 return false; 7918 } 7919 7920 @Override 7921 protected boolean isPackageForFilter(String packageName, 7922 PackageParser.ActivityIntentInfo info) { 7923 return packageName.equals(info.activity.owner.packageName); 7924 } 7925 7926 @Override 7927 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7928 int match, int userId) { 7929 if (!sUserManager.exists(userId)) return null; 7930 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7931 return null; 7932 } 7933 final PackageParser.Activity activity = info.activity; 7934 if (mSafeMode && (activity.info.applicationInfo.flags 7935 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7936 return null; 7937 } 7938 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7939 if (ps == null) { 7940 return null; 7941 } 7942 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7943 ps.readUserState(userId), userId); 7944 if (ai == null) { 7945 return null; 7946 } 7947 final ResolveInfo res = new ResolveInfo(); 7948 res.activityInfo = ai; 7949 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7950 res.filter = info; 7951 } 7952 if (info != null) { 7953 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7954 } 7955 res.priority = info.getPriority(); 7956 res.preferredOrder = activity.owner.mPreferredOrder; 7957 //System.out.println("Result: " + res.activityInfo.className + 7958 // " = " + res.priority); 7959 res.match = match; 7960 res.isDefault = info.hasDefault; 7961 res.labelRes = info.labelRes; 7962 res.nonLocalizedLabel = info.nonLocalizedLabel; 7963 if (userNeedsBadging(userId)) { 7964 res.noResourceId = true; 7965 } else { 7966 res.icon = info.icon; 7967 } 7968 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7969 return res; 7970 } 7971 7972 @Override 7973 protected void sortResults(List<ResolveInfo> results) { 7974 Collections.sort(results, mResolvePrioritySorter); 7975 } 7976 7977 @Override 7978 protected void dumpFilter(PrintWriter out, String prefix, 7979 PackageParser.ActivityIntentInfo filter) { 7980 out.print(prefix); out.print( 7981 Integer.toHexString(System.identityHashCode(filter.activity))); 7982 out.print(' '); 7983 filter.activity.printComponentShortName(out); 7984 out.print(" filter "); 7985 out.println(Integer.toHexString(System.identityHashCode(filter))); 7986 } 7987 7988 @Override 7989 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7990 return filter.activity; 7991 } 7992 7993 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7994 PackageParser.Activity activity = (PackageParser.Activity)label; 7995 out.print(prefix); out.print( 7996 Integer.toHexString(System.identityHashCode(activity))); 7997 out.print(' '); 7998 activity.printComponentShortName(out); 7999 if (count > 1) { 8000 out.print(" ("); out.print(count); out.print(" filters)"); 8001 } 8002 out.println(); 8003 } 8004 8005// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8006// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8007// final List<ResolveInfo> retList = Lists.newArrayList(); 8008// while (i.hasNext()) { 8009// final ResolveInfo resolveInfo = i.next(); 8010// if (isEnabledLP(resolveInfo.activityInfo)) { 8011// retList.add(resolveInfo); 8012// } 8013// } 8014// return retList; 8015// } 8016 8017 // Keys are String (activity class name), values are Activity. 8018 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8019 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8020 private int mFlags; 8021 } 8022 8023 private final class ServiceIntentResolver 8024 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8026 boolean defaultOnly, int userId) { 8027 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8028 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8029 } 8030 8031 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8032 int userId) { 8033 if (!sUserManager.exists(userId)) return null; 8034 mFlags = flags; 8035 return super.queryIntent(intent, resolvedType, 8036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8037 } 8038 8039 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8040 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8041 if (!sUserManager.exists(userId)) return null; 8042 if (packageServices == null) { 8043 return null; 8044 } 8045 mFlags = flags; 8046 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8047 final int N = packageServices.size(); 8048 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8049 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8050 8051 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8052 for (int i = 0; i < N; ++i) { 8053 intentFilters = packageServices.get(i).intents; 8054 if (intentFilters != null && intentFilters.size() > 0) { 8055 PackageParser.ServiceIntentInfo[] array = 8056 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8057 intentFilters.toArray(array); 8058 listCut.add(array); 8059 } 8060 } 8061 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8062 } 8063 8064 public final void addService(PackageParser.Service s) { 8065 mServices.put(s.getComponentName(), s); 8066 if (DEBUG_SHOW_INFO) { 8067 Log.v(TAG, " " 8068 + (s.info.nonLocalizedLabel != null 8069 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8070 Log.v(TAG, " Class=" + s.info.name); 8071 } 8072 final int NI = s.intents.size(); 8073 int j; 8074 for (j=0; j<NI; j++) { 8075 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8076 if (DEBUG_SHOW_INFO) { 8077 Log.v(TAG, " IntentFilter:"); 8078 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8079 } 8080 if (!intent.debugCheck()) { 8081 Log.w(TAG, "==> For Service " + s.info.name); 8082 } 8083 addFilter(intent); 8084 } 8085 } 8086 8087 public final void removeService(PackageParser.Service s) { 8088 mServices.remove(s.getComponentName()); 8089 if (DEBUG_SHOW_INFO) { 8090 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8091 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8092 Log.v(TAG, " Class=" + s.info.name); 8093 } 8094 final int NI = s.intents.size(); 8095 int j; 8096 for (j=0; j<NI; j++) { 8097 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8098 if (DEBUG_SHOW_INFO) { 8099 Log.v(TAG, " IntentFilter:"); 8100 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8101 } 8102 removeFilter(intent); 8103 } 8104 } 8105 8106 @Override 8107 protected boolean allowFilterResult( 8108 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8109 ServiceInfo filterSi = filter.service.info; 8110 for (int i=dest.size()-1; i>=0; i--) { 8111 ServiceInfo destAi = dest.get(i).serviceInfo; 8112 if (destAi.name == filterSi.name 8113 && destAi.packageName == filterSi.packageName) { 8114 return false; 8115 } 8116 } 8117 return true; 8118 } 8119 8120 @Override 8121 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8122 return new PackageParser.ServiceIntentInfo[size]; 8123 } 8124 8125 @Override 8126 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8127 if (!sUserManager.exists(userId)) return true; 8128 PackageParser.Package p = filter.service.owner; 8129 if (p != null) { 8130 PackageSetting ps = (PackageSetting)p.mExtras; 8131 if (ps != null) { 8132 // System apps are never considered stopped for purposes of 8133 // filtering, because there may be no way for the user to 8134 // actually re-launch them. 8135 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8136 && ps.getStopped(userId); 8137 } 8138 } 8139 return false; 8140 } 8141 8142 @Override 8143 protected boolean isPackageForFilter(String packageName, 8144 PackageParser.ServiceIntentInfo info) { 8145 return packageName.equals(info.service.owner.packageName); 8146 } 8147 8148 @Override 8149 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8150 int match, int userId) { 8151 if (!sUserManager.exists(userId)) return null; 8152 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8153 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8154 return null; 8155 } 8156 final PackageParser.Service service = info.service; 8157 if (mSafeMode && (service.info.applicationInfo.flags 8158 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8159 return null; 8160 } 8161 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8162 if (ps == null) { 8163 return null; 8164 } 8165 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8166 ps.readUserState(userId), userId); 8167 if (si == null) { 8168 return null; 8169 } 8170 final ResolveInfo res = new ResolveInfo(); 8171 res.serviceInfo = si; 8172 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8173 res.filter = filter; 8174 } 8175 res.priority = info.getPriority(); 8176 res.preferredOrder = service.owner.mPreferredOrder; 8177 res.match = match; 8178 res.isDefault = info.hasDefault; 8179 res.labelRes = info.labelRes; 8180 res.nonLocalizedLabel = info.nonLocalizedLabel; 8181 res.icon = info.icon; 8182 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8183 return res; 8184 } 8185 8186 @Override 8187 protected void sortResults(List<ResolveInfo> results) { 8188 Collections.sort(results, mResolvePrioritySorter); 8189 } 8190 8191 @Override 8192 protected void dumpFilter(PrintWriter out, String prefix, 8193 PackageParser.ServiceIntentInfo filter) { 8194 out.print(prefix); out.print( 8195 Integer.toHexString(System.identityHashCode(filter.service))); 8196 out.print(' '); 8197 filter.service.printComponentShortName(out); 8198 out.print(" filter "); 8199 out.println(Integer.toHexString(System.identityHashCode(filter))); 8200 } 8201 8202 @Override 8203 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8204 return filter.service; 8205 } 8206 8207 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8208 PackageParser.Service service = (PackageParser.Service)label; 8209 out.print(prefix); out.print( 8210 Integer.toHexString(System.identityHashCode(service))); 8211 out.print(' '); 8212 service.printComponentShortName(out); 8213 if (count > 1) { 8214 out.print(" ("); out.print(count); out.print(" filters)"); 8215 } 8216 out.println(); 8217 } 8218 8219// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8220// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8221// final List<ResolveInfo> retList = Lists.newArrayList(); 8222// while (i.hasNext()) { 8223// final ResolveInfo resolveInfo = (ResolveInfo) i; 8224// if (isEnabledLP(resolveInfo.serviceInfo)) { 8225// retList.add(resolveInfo); 8226// } 8227// } 8228// return retList; 8229// } 8230 8231 // Keys are String (activity class name), values are Activity. 8232 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8233 = new ArrayMap<ComponentName, PackageParser.Service>(); 8234 private int mFlags; 8235 }; 8236 8237 private final class ProviderIntentResolver 8238 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8239 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8240 boolean defaultOnly, int userId) { 8241 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8242 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8243 } 8244 8245 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8246 int userId) { 8247 if (!sUserManager.exists(userId)) 8248 return null; 8249 mFlags = flags; 8250 return super.queryIntent(intent, resolvedType, 8251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8252 } 8253 8254 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8255 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8256 if (!sUserManager.exists(userId)) 8257 return null; 8258 if (packageProviders == null) { 8259 return null; 8260 } 8261 mFlags = flags; 8262 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8263 final int N = packageProviders.size(); 8264 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8265 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8266 8267 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8268 for (int i = 0; i < N; ++i) { 8269 intentFilters = packageProviders.get(i).intents; 8270 if (intentFilters != null && intentFilters.size() > 0) { 8271 PackageParser.ProviderIntentInfo[] array = 8272 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8273 intentFilters.toArray(array); 8274 listCut.add(array); 8275 } 8276 } 8277 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8278 } 8279 8280 public final void addProvider(PackageParser.Provider p) { 8281 if (mProviders.containsKey(p.getComponentName())) { 8282 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8283 return; 8284 } 8285 8286 mProviders.put(p.getComponentName(), p); 8287 if (DEBUG_SHOW_INFO) { 8288 Log.v(TAG, " " 8289 + (p.info.nonLocalizedLabel != null 8290 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8291 Log.v(TAG, " Class=" + p.info.name); 8292 } 8293 final int NI = p.intents.size(); 8294 int j; 8295 for (j = 0; j < NI; j++) { 8296 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8297 if (DEBUG_SHOW_INFO) { 8298 Log.v(TAG, " IntentFilter:"); 8299 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8300 } 8301 if (!intent.debugCheck()) { 8302 Log.w(TAG, "==> For Provider " + p.info.name); 8303 } 8304 addFilter(intent); 8305 } 8306 } 8307 8308 public final void removeProvider(PackageParser.Provider p) { 8309 mProviders.remove(p.getComponentName()); 8310 if (DEBUG_SHOW_INFO) { 8311 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8312 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8313 Log.v(TAG, " Class=" + p.info.name); 8314 } 8315 final int NI = p.intents.size(); 8316 int j; 8317 for (j = 0; j < NI; j++) { 8318 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8319 if (DEBUG_SHOW_INFO) { 8320 Log.v(TAG, " IntentFilter:"); 8321 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8322 } 8323 removeFilter(intent); 8324 } 8325 } 8326 8327 @Override 8328 protected boolean allowFilterResult( 8329 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8330 ProviderInfo filterPi = filter.provider.info; 8331 for (int i = dest.size() - 1; i >= 0; i--) { 8332 ProviderInfo destPi = dest.get(i).providerInfo; 8333 if (destPi.name == filterPi.name 8334 && destPi.packageName == filterPi.packageName) { 8335 return false; 8336 } 8337 } 8338 return true; 8339 } 8340 8341 @Override 8342 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8343 return new PackageParser.ProviderIntentInfo[size]; 8344 } 8345 8346 @Override 8347 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8348 if (!sUserManager.exists(userId)) 8349 return true; 8350 PackageParser.Package p = filter.provider.owner; 8351 if (p != null) { 8352 PackageSetting ps = (PackageSetting) p.mExtras; 8353 if (ps != null) { 8354 // System apps are never considered stopped for purposes of 8355 // filtering, because there may be no way for the user to 8356 // actually re-launch them. 8357 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8358 && ps.getStopped(userId); 8359 } 8360 } 8361 return false; 8362 } 8363 8364 @Override 8365 protected boolean isPackageForFilter(String packageName, 8366 PackageParser.ProviderIntentInfo info) { 8367 return packageName.equals(info.provider.owner.packageName); 8368 } 8369 8370 @Override 8371 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8372 int match, int userId) { 8373 if (!sUserManager.exists(userId)) 8374 return null; 8375 final PackageParser.ProviderIntentInfo info = filter; 8376 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8377 return null; 8378 } 8379 final PackageParser.Provider provider = info.provider; 8380 if (mSafeMode && (provider.info.applicationInfo.flags 8381 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8382 return null; 8383 } 8384 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8385 if (ps == null) { 8386 return null; 8387 } 8388 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8389 ps.readUserState(userId), userId); 8390 if (pi == null) { 8391 return null; 8392 } 8393 final ResolveInfo res = new ResolveInfo(); 8394 res.providerInfo = pi; 8395 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8396 res.filter = filter; 8397 } 8398 res.priority = info.getPriority(); 8399 res.preferredOrder = provider.owner.mPreferredOrder; 8400 res.match = match; 8401 res.isDefault = info.hasDefault; 8402 res.labelRes = info.labelRes; 8403 res.nonLocalizedLabel = info.nonLocalizedLabel; 8404 res.icon = info.icon; 8405 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8406 return res; 8407 } 8408 8409 @Override 8410 protected void sortResults(List<ResolveInfo> results) { 8411 Collections.sort(results, mResolvePrioritySorter); 8412 } 8413 8414 @Override 8415 protected void dumpFilter(PrintWriter out, String prefix, 8416 PackageParser.ProviderIntentInfo filter) { 8417 out.print(prefix); 8418 out.print( 8419 Integer.toHexString(System.identityHashCode(filter.provider))); 8420 out.print(' '); 8421 filter.provider.printComponentShortName(out); 8422 out.print(" filter "); 8423 out.println(Integer.toHexString(System.identityHashCode(filter))); 8424 } 8425 8426 @Override 8427 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8428 return filter.provider; 8429 } 8430 8431 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8432 PackageParser.Provider provider = (PackageParser.Provider)label; 8433 out.print(prefix); out.print( 8434 Integer.toHexString(System.identityHashCode(provider))); 8435 out.print(' '); 8436 provider.printComponentShortName(out); 8437 if (count > 1) { 8438 out.print(" ("); out.print(count); out.print(" filters)"); 8439 } 8440 out.println(); 8441 } 8442 8443 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8444 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8445 private int mFlags; 8446 }; 8447 8448 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8449 new Comparator<ResolveInfo>() { 8450 public int compare(ResolveInfo r1, ResolveInfo r2) { 8451 int v1 = r1.priority; 8452 int v2 = r2.priority; 8453 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8454 if (v1 != v2) { 8455 return (v1 > v2) ? -1 : 1; 8456 } 8457 v1 = r1.preferredOrder; 8458 v2 = r2.preferredOrder; 8459 if (v1 != v2) { 8460 return (v1 > v2) ? -1 : 1; 8461 } 8462 if (r1.isDefault != r2.isDefault) { 8463 return r1.isDefault ? -1 : 1; 8464 } 8465 v1 = r1.match; 8466 v2 = r2.match; 8467 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8468 if (v1 != v2) { 8469 return (v1 > v2) ? -1 : 1; 8470 } 8471 if (r1.system != r2.system) { 8472 return r1.system ? -1 : 1; 8473 } 8474 return 0; 8475 } 8476 }; 8477 8478 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8479 new Comparator<ProviderInfo>() { 8480 public int compare(ProviderInfo p1, ProviderInfo p2) { 8481 final int v1 = p1.initOrder; 8482 final int v2 = p2.initOrder; 8483 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8484 } 8485 }; 8486 8487 static final void sendPackageBroadcast(String action, String pkg, 8488 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8489 int[] userIds) { 8490 IActivityManager am = ActivityManagerNative.getDefault(); 8491 if (am != null) { 8492 try { 8493 if (userIds == null) { 8494 userIds = am.getRunningUserIds(); 8495 } 8496 for (int id : userIds) { 8497 final Intent intent = new Intent(action, 8498 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8499 if (extras != null) { 8500 intent.putExtras(extras); 8501 } 8502 if (targetPkg != null) { 8503 intent.setPackage(targetPkg); 8504 } 8505 // Modify the UID when posting to other users 8506 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8507 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8508 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8509 intent.putExtra(Intent.EXTRA_UID, uid); 8510 } 8511 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8512 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8513 if (DEBUG_BROADCASTS) { 8514 RuntimeException here = new RuntimeException("here"); 8515 here.fillInStackTrace(); 8516 Slog.d(TAG, "Sending to user " + id + ": " 8517 + intent.toShortString(false, true, false, false) 8518 + " " + intent.getExtras(), here); 8519 } 8520 am.broadcastIntent(null, intent, null, finishedReceiver, 8521 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8522 finishedReceiver != null, false, id); 8523 } 8524 } catch (RemoteException ex) { 8525 } 8526 } 8527 } 8528 8529 /** 8530 * Check if the external storage media is available. This is true if there 8531 * is a mounted external storage medium or if the external storage is 8532 * emulated. 8533 */ 8534 private boolean isExternalMediaAvailable() { 8535 return mMediaMounted || Environment.isExternalStorageEmulated(); 8536 } 8537 8538 @Override 8539 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8540 // writer 8541 synchronized (mPackages) { 8542 if (!isExternalMediaAvailable()) { 8543 // If the external storage is no longer mounted at this point, 8544 // the caller may not have been able to delete all of this 8545 // packages files and can not delete any more. Bail. 8546 return null; 8547 } 8548 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8549 if (lastPackage != null) { 8550 pkgs.remove(lastPackage); 8551 } 8552 if (pkgs.size() > 0) { 8553 return pkgs.get(0); 8554 } 8555 } 8556 return null; 8557 } 8558 8559 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8560 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8561 userId, andCode ? 1 : 0, packageName); 8562 if (mSystemReady) { 8563 msg.sendToTarget(); 8564 } else { 8565 if (mPostSystemReadyMessages == null) { 8566 mPostSystemReadyMessages = new ArrayList<>(); 8567 } 8568 mPostSystemReadyMessages.add(msg); 8569 } 8570 } 8571 8572 void startCleaningPackages() { 8573 // reader 8574 synchronized (mPackages) { 8575 if (!isExternalMediaAvailable()) { 8576 return; 8577 } 8578 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8579 return; 8580 } 8581 } 8582 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8583 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8584 IActivityManager am = ActivityManagerNative.getDefault(); 8585 if (am != null) { 8586 try { 8587 am.startService(null, intent, null, UserHandle.USER_OWNER); 8588 } catch (RemoteException e) { 8589 } 8590 } 8591 } 8592 8593 @Override 8594 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8595 int installFlags, String installerPackageName, VerificationParams verificationParams, 8596 String packageAbiOverride) { 8597 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8598 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8599 } 8600 8601 @Override 8602 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8603 int installFlags, String installerPackageName, VerificationParams verificationParams, 8604 String packageAbiOverride, int userId) { 8605 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8606 8607 final int callingUid = Binder.getCallingUid(); 8608 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8609 8610 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8611 try { 8612 if (observer != null) { 8613 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8614 } 8615 } catch (RemoteException re) { 8616 } 8617 return; 8618 } 8619 8620 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8621 installFlags |= PackageManager.INSTALL_FROM_ADB; 8622 8623 } else { 8624 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8625 // about installerPackageName. 8626 8627 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8628 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8629 } 8630 8631 UserHandle user; 8632 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8633 user = UserHandle.ALL; 8634 } else { 8635 user = new UserHandle(userId); 8636 } 8637 8638 // Only system components can circumvent runtime permissions when installing. 8639 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8640 && mContext.checkCallingOrSelfPermission(Manifest.permission 8641 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8642 throw new SecurityException("You need the " 8643 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8644 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8645 } 8646 8647 verificationParams.setInstallerUid(callingUid); 8648 8649 final File originFile = new File(originPath); 8650 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8651 8652 final Message msg = mHandler.obtainMessage(INIT_COPY); 8653 msg.obj = new InstallParams(origin, observer, installFlags, 8654 installerPackageName, null, verificationParams, user, packageAbiOverride); 8655 mHandler.sendMessage(msg); 8656 } 8657 8658 void installStage(String packageName, File stagedDir, String stagedCid, 8659 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8660 String installerPackageName, int installerUid, UserHandle user) { 8661 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8662 params.referrerUri, installerUid, null); 8663 8664 final OriginInfo origin; 8665 if (stagedDir != null) { 8666 origin = OriginInfo.fromStagedFile(stagedDir); 8667 } else { 8668 origin = OriginInfo.fromStagedContainer(stagedCid); 8669 } 8670 8671 final Message msg = mHandler.obtainMessage(INIT_COPY); 8672 msg.obj = new InstallParams(origin, observer, params.installFlags, 8673 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8674 mHandler.sendMessage(msg); 8675 } 8676 8677 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8678 Bundle extras = new Bundle(1); 8679 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8680 8681 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8682 packageName, extras, null, null, new int[] {userId}); 8683 try { 8684 IActivityManager am = ActivityManagerNative.getDefault(); 8685 final boolean isSystem = 8686 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8687 if (isSystem && am.isUserRunning(userId, false)) { 8688 // The just-installed/enabled app is bundled on the system, so presumed 8689 // to be able to run automatically without needing an explicit launch. 8690 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8691 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8692 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8693 .setPackage(packageName); 8694 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8695 android.app.AppOpsManager.OP_NONE, false, false, userId); 8696 } 8697 } catch (RemoteException e) { 8698 // shouldn't happen 8699 Slog.w(TAG, "Unable to bootstrap installed package", e); 8700 } 8701 } 8702 8703 @Override 8704 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8705 int userId) { 8706 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8707 PackageSetting pkgSetting; 8708 final int uid = Binder.getCallingUid(); 8709 enforceCrossUserPermission(uid, userId, true, true, 8710 "setApplicationHiddenSetting for user " + userId); 8711 8712 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8713 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8714 return false; 8715 } 8716 8717 long callingId = Binder.clearCallingIdentity(); 8718 try { 8719 boolean sendAdded = false; 8720 boolean sendRemoved = false; 8721 // writer 8722 synchronized (mPackages) { 8723 pkgSetting = mSettings.mPackages.get(packageName); 8724 if (pkgSetting == null) { 8725 return false; 8726 } 8727 if (pkgSetting.getHidden(userId) != hidden) { 8728 pkgSetting.setHidden(hidden, userId); 8729 mSettings.writePackageRestrictionsLPr(userId); 8730 if (hidden) { 8731 sendRemoved = true; 8732 } else { 8733 sendAdded = true; 8734 } 8735 } 8736 } 8737 if (sendAdded) { 8738 sendPackageAddedForUser(packageName, pkgSetting, userId); 8739 return true; 8740 } 8741 if (sendRemoved) { 8742 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8743 "hiding pkg"); 8744 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8745 } 8746 } finally { 8747 Binder.restoreCallingIdentity(callingId); 8748 } 8749 return false; 8750 } 8751 8752 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8753 int userId) { 8754 final PackageRemovedInfo info = new PackageRemovedInfo(); 8755 info.removedPackage = packageName; 8756 info.removedUsers = new int[] {userId}; 8757 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8758 info.sendBroadcast(false, false, false); 8759 } 8760 8761 /** 8762 * Returns true if application is not found or there was an error. Otherwise it returns 8763 * the hidden state of the package for the given user. 8764 */ 8765 @Override 8766 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8768 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8769 false, "getApplicationHidden for user " + userId); 8770 PackageSetting pkgSetting; 8771 long callingId = Binder.clearCallingIdentity(); 8772 try { 8773 // writer 8774 synchronized (mPackages) { 8775 pkgSetting = mSettings.mPackages.get(packageName); 8776 if (pkgSetting == null) { 8777 return true; 8778 } 8779 return pkgSetting.getHidden(userId); 8780 } 8781 } finally { 8782 Binder.restoreCallingIdentity(callingId); 8783 } 8784 } 8785 8786 /** 8787 * @hide 8788 */ 8789 @Override 8790 public int installExistingPackageAsUser(String packageName, int userId) { 8791 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8792 null); 8793 PackageSetting pkgSetting; 8794 final int uid = Binder.getCallingUid(); 8795 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8796 + userId); 8797 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8798 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8799 } 8800 8801 long callingId = Binder.clearCallingIdentity(); 8802 try { 8803 boolean sendAdded = false; 8804 8805 // writer 8806 synchronized (mPackages) { 8807 pkgSetting = mSettings.mPackages.get(packageName); 8808 if (pkgSetting == null) { 8809 return PackageManager.INSTALL_FAILED_INVALID_URI; 8810 } 8811 if (!pkgSetting.getInstalled(userId)) { 8812 pkgSetting.setInstalled(true, userId); 8813 pkgSetting.setHidden(false, userId); 8814 mSettings.writePackageRestrictionsLPr(userId); 8815 sendAdded = true; 8816 } 8817 } 8818 8819 if (sendAdded) { 8820 sendPackageAddedForUser(packageName, pkgSetting, userId); 8821 } 8822 } finally { 8823 Binder.restoreCallingIdentity(callingId); 8824 } 8825 8826 return PackageManager.INSTALL_SUCCEEDED; 8827 } 8828 8829 boolean isUserRestricted(int userId, String restrictionKey) { 8830 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8831 if (restrictions.getBoolean(restrictionKey, false)) { 8832 Log.w(TAG, "User is restricted: " + restrictionKey); 8833 return true; 8834 } 8835 return false; 8836 } 8837 8838 @Override 8839 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8840 mContext.enforceCallingOrSelfPermission( 8841 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8842 "Only package verification agents can verify applications"); 8843 8844 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8845 final PackageVerificationResponse response = new PackageVerificationResponse( 8846 verificationCode, Binder.getCallingUid()); 8847 msg.arg1 = id; 8848 msg.obj = response; 8849 mHandler.sendMessage(msg); 8850 } 8851 8852 @Override 8853 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8854 long millisecondsToDelay) { 8855 mContext.enforceCallingOrSelfPermission( 8856 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8857 "Only package verification agents can extend verification timeouts"); 8858 8859 final PackageVerificationState state = mPendingVerification.get(id); 8860 final PackageVerificationResponse response = new PackageVerificationResponse( 8861 verificationCodeAtTimeout, Binder.getCallingUid()); 8862 8863 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8864 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8865 } 8866 if (millisecondsToDelay < 0) { 8867 millisecondsToDelay = 0; 8868 } 8869 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8870 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8871 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8872 } 8873 8874 if ((state != null) && !state.timeoutExtended()) { 8875 state.extendTimeout(); 8876 8877 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8878 msg.arg1 = id; 8879 msg.obj = response; 8880 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8881 } 8882 } 8883 8884 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8885 int verificationCode, UserHandle user) { 8886 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8887 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8888 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8889 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8890 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8891 8892 mContext.sendBroadcastAsUser(intent, user, 8893 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8894 } 8895 8896 private ComponentName matchComponentForVerifier(String packageName, 8897 List<ResolveInfo> receivers) { 8898 ActivityInfo targetReceiver = null; 8899 8900 final int NR = receivers.size(); 8901 for (int i = 0; i < NR; i++) { 8902 final ResolveInfo info = receivers.get(i); 8903 if (info.activityInfo == null) { 8904 continue; 8905 } 8906 8907 if (packageName.equals(info.activityInfo.packageName)) { 8908 targetReceiver = info.activityInfo; 8909 break; 8910 } 8911 } 8912 8913 if (targetReceiver == null) { 8914 return null; 8915 } 8916 8917 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8918 } 8919 8920 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8921 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8922 if (pkgInfo.verifiers.length == 0) { 8923 return null; 8924 } 8925 8926 final int N = pkgInfo.verifiers.length; 8927 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8928 for (int i = 0; i < N; i++) { 8929 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8930 8931 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8932 receivers); 8933 if (comp == null) { 8934 continue; 8935 } 8936 8937 final int verifierUid = getUidForVerifier(verifierInfo); 8938 if (verifierUid == -1) { 8939 continue; 8940 } 8941 8942 if (DEBUG_VERIFY) { 8943 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8944 + " with the correct signature"); 8945 } 8946 sufficientVerifiers.add(comp); 8947 verificationState.addSufficientVerifier(verifierUid); 8948 } 8949 8950 return sufficientVerifiers; 8951 } 8952 8953 private int getUidForVerifier(VerifierInfo verifierInfo) { 8954 synchronized (mPackages) { 8955 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8956 if (pkg == null) { 8957 return -1; 8958 } else if (pkg.mSignatures.length != 1) { 8959 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8960 + " has more than one signature; ignoring"); 8961 return -1; 8962 } 8963 8964 /* 8965 * If the public key of the package's signature does not match 8966 * our expected public key, then this is a different package and 8967 * we should skip. 8968 */ 8969 8970 final byte[] expectedPublicKey; 8971 try { 8972 final Signature verifierSig = pkg.mSignatures[0]; 8973 final PublicKey publicKey = verifierSig.getPublicKey(); 8974 expectedPublicKey = publicKey.getEncoded(); 8975 } catch (CertificateException e) { 8976 return -1; 8977 } 8978 8979 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8980 8981 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8982 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8983 + " does not have the expected public key; ignoring"); 8984 return -1; 8985 } 8986 8987 return pkg.applicationInfo.uid; 8988 } 8989 } 8990 8991 @Override 8992 public void finishPackageInstall(int token) { 8993 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8994 8995 if (DEBUG_INSTALL) { 8996 Slog.v(TAG, "BM finishing package install for " + token); 8997 } 8998 8999 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9000 mHandler.sendMessage(msg); 9001 } 9002 9003 /** 9004 * Get the verification agent timeout. 9005 * 9006 * @return verification timeout in milliseconds 9007 */ 9008 private long getVerificationTimeout() { 9009 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9010 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9011 DEFAULT_VERIFICATION_TIMEOUT); 9012 } 9013 9014 /** 9015 * Get the default verification agent response code. 9016 * 9017 * @return default verification response code 9018 */ 9019 private int getDefaultVerificationResponse() { 9020 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9021 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9022 DEFAULT_VERIFICATION_RESPONSE); 9023 } 9024 9025 /** 9026 * Check whether or not package verification has been enabled. 9027 * 9028 * @return true if verification should be performed 9029 */ 9030 private boolean isVerificationEnabled(int userId, int installFlags) { 9031 if (!DEFAULT_VERIFY_ENABLE) { 9032 return false; 9033 } 9034 9035 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9036 9037 // Check if installing from ADB 9038 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9039 // Do not run verification in a test harness environment 9040 if (ActivityManager.isRunningInTestHarness()) { 9041 return false; 9042 } 9043 if (ensureVerifyAppsEnabled) { 9044 return true; 9045 } 9046 // Check if the developer does not want package verification for ADB installs 9047 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9048 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9049 return false; 9050 } 9051 } 9052 9053 if (ensureVerifyAppsEnabled) { 9054 return true; 9055 } 9056 9057 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9058 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9059 } 9060 9061 @Override 9062 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9063 throws RemoteException { 9064 mContext.enforceCallingOrSelfPermission( 9065 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9066 "Only intentfilter verification agents can verify applications"); 9067 9068 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9069 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9070 Binder.getCallingUid(), verificationCode, failedDomains); 9071 msg.arg1 = id; 9072 msg.obj = response; 9073 mHandler.sendMessage(msg); 9074 } 9075 9076 @Override 9077 public int getIntentVerificationStatus(String packageName, int userId) { 9078 synchronized (mPackages) { 9079 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9080 } 9081 } 9082 9083 @Override 9084 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9085 boolean result = false; 9086 synchronized (mPackages) { 9087 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9088 } 9089 scheduleWritePackageRestrictionsLocked(userId); 9090 return result; 9091 } 9092 9093 @Override 9094 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9095 synchronized (mPackages) { 9096 return mSettings.getIntentFilterVerificationsLPr(packageName); 9097 } 9098 } 9099 9100 @Override 9101 public List<IntentFilter> getAllIntentFilters(String packageName) { 9102 if (TextUtils.isEmpty(packageName)) { 9103 return Collections.<IntentFilter>emptyList(); 9104 } 9105 synchronized (mPackages) { 9106 PackageParser.Package pkg = mPackages.get(packageName); 9107 if (pkg == null || pkg.activities == null) { 9108 return Collections.<IntentFilter>emptyList(); 9109 } 9110 final int count = pkg.activities.size(); 9111 ArrayList<IntentFilter> result = new ArrayList<>(); 9112 for (int n=0; n<count; n++) { 9113 PackageParser.Activity activity = pkg.activities.get(n); 9114 if (activity.intents != null || activity.intents.size() > 0) { 9115 result.addAll(activity.intents); 9116 } 9117 } 9118 return result; 9119 } 9120 } 9121 9122 @Override 9123 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9124 synchronized (mPackages) { 9125 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9126 } 9127 } 9128 9129 @Override 9130 public String getDefaultBrowserPackageName(int userId) { 9131 synchronized (mPackages) { 9132 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9133 } 9134 } 9135 9136 /** 9137 * Get the "allow unknown sources" setting. 9138 * 9139 * @return the current "allow unknown sources" setting 9140 */ 9141 private int getUnknownSourcesSettings() { 9142 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9143 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9144 -1); 9145 } 9146 9147 @Override 9148 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9149 final int uid = Binder.getCallingUid(); 9150 // writer 9151 synchronized (mPackages) { 9152 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9153 if (targetPackageSetting == null) { 9154 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9155 } 9156 9157 PackageSetting installerPackageSetting; 9158 if (installerPackageName != null) { 9159 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9160 if (installerPackageSetting == null) { 9161 throw new IllegalArgumentException("Unknown installer package: " 9162 + installerPackageName); 9163 } 9164 } else { 9165 installerPackageSetting = null; 9166 } 9167 9168 Signature[] callerSignature; 9169 Object obj = mSettings.getUserIdLPr(uid); 9170 if (obj != null) { 9171 if (obj instanceof SharedUserSetting) { 9172 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9173 } else if (obj instanceof PackageSetting) { 9174 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9175 } else { 9176 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9177 } 9178 } else { 9179 throw new SecurityException("Unknown calling uid " + uid); 9180 } 9181 9182 // Verify: can't set installerPackageName to a package that is 9183 // not signed with the same cert as the caller. 9184 if (installerPackageSetting != null) { 9185 if (compareSignatures(callerSignature, 9186 installerPackageSetting.signatures.mSignatures) 9187 != PackageManager.SIGNATURE_MATCH) { 9188 throw new SecurityException( 9189 "Caller does not have same cert as new installer package " 9190 + installerPackageName); 9191 } 9192 } 9193 9194 // Verify: if target already has an installer package, it must 9195 // be signed with the same cert as the caller. 9196 if (targetPackageSetting.installerPackageName != null) { 9197 PackageSetting setting = mSettings.mPackages.get( 9198 targetPackageSetting.installerPackageName); 9199 // If the currently set package isn't valid, then it's always 9200 // okay to change it. 9201 if (setting != null) { 9202 if (compareSignatures(callerSignature, 9203 setting.signatures.mSignatures) 9204 != PackageManager.SIGNATURE_MATCH) { 9205 throw new SecurityException( 9206 "Caller does not have same cert as old installer package " 9207 + targetPackageSetting.installerPackageName); 9208 } 9209 } 9210 } 9211 9212 // Okay! 9213 targetPackageSetting.installerPackageName = installerPackageName; 9214 scheduleWriteSettingsLocked(); 9215 } 9216 } 9217 9218 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9219 // Queue up an async operation since the package installation may take a little while. 9220 mHandler.post(new Runnable() { 9221 public void run() { 9222 mHandler.removeCallbacks(this); 9223 // Result object to be returned 9224 PackageInstalledInfo res = new PackageInstalledInfo(); 9225 res.returnCode = currentStatus; 9226 res.uid = -1; 9227 res.pkg = null; 9228 res.removedInfo = new PackageRemovedInfo(); 9229 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9230 args.doPreInstall(res.returnCode); 9231 synchronized (mInstallLock) { 9232 installPackageLI(args, res); 9233 } 9234 args.doPostInstall(res.returnCode, res.uid); 9235 } 9236 9237 // A restore should be performed at this point if (a) the install 9238 // succeeded, (b) the operation is not an update, and (c) the new 9239 // package has not opted out of backup participation. 9240 final boolean update = res.removedInfo.removedPackage != null; 9241 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9242 boolean doRestore = !update 9243 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9244 9245 // Set up the post-install work request bookkeeping. This will be used 9246 // and cleaned up by the post-install event handling regardless of whether 9247 // there's a restore pass performed. Token values are >= 1. 9248 int token; 9249 if (mNextInstallToken < 0) mNextInstallToken = 1; 9250 token = mNextInstallToken++; 9251 9252 PostInstallData data = new PostInstallData(args, res); 9253 mRunningInstalls.put(token, data); 9254 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9255 9256 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9257 // Pass responsibility to the Backup Manager. It will perform a 9258 // restore if appropriate, then pass responsibility back to the 9259 // Package Manager to run the post-install observer callbacks 9260 // and broadcasts. 9261 IBackupManager bm = IBackupManager.Stub.asInterface( 9262 ServiceManager.getService(Context.BACKUP_SERVICE)); 9263 if (bm != null) { 9264 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9265 + " to BM for possible restore"); 9266 try { 9267 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9268 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9269 } else { 9270 doRestore = false; 9271 } 9272 } catch (RemoteException e) { 9273 // can't happen; the backup manager is local 9274 } catch (Exception e) { 9275 Slog.e(TAG, "Exception trying to enqueue restore", e); 9276 doRestore = false; 9277 } 9278 } else { 9279 Slog.e(TAG, "Backup Manager not found!"); 9280 doRestore = false; 9281 } 9282 } 9283 9284 if (!doRestore) { 9285 // No restore possible, or the Backup Manager was mysteriously not 9286 // available -- just fire the post-install work request directly. 9287 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9288 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9289 mHandler.sendMessage(msg); 9290 } 9291 } 9292 }); 9293 } 9294 9295 private abstract class HandlerParams { 9296 private static final int MAX_RETRIES = 4; 9297 9298 /** 9299 * Number of times startCopy() has been attempted and had a non-fatal 9300 * error. 9301 */ 9302 private int mRetries = 0; 9303 9304 /** User handle for the user requesting the information or installation. */ 9305 private final UserHandle mUser; 9306 9307 HandlerParams(UserHandle user) { 9308 mUser = user; 9309 } 9310 9311 UserHandle getUser() { 9312 return mUser; 9313 } 9314 9315 final boolean startCopy() { 9316 boolean res; 9317 try { 9318 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9319 9320 if (++mRetries > MAX_RETRIES) { 9321 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9322 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9323 handleServiceError(); 9324 return false; 9325 } else { 9326 handleStartCopy(); 9327 res = true; 9328 } 9329 } catch (RemoteException e) { 9330 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9331 mHandler.sendEmptyMessage(MCS_RECONNECT); 9332 res = false; 9333 } 9334 handleReturnCode(); 9335 return res; 9336 } 9337 9338 final void serviceError() { 9339 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9340 handleServiceError(); 9341 handleReturnCode(); 9342 } 9343 9344 abstract void handleStartCopy() throws RemoteException; 9345 abstract void handleServiceError(); 9346 abstract void handleReturnCode(); 9347 } 9348 9349 class MeasureParams extends HandlerParams { 9350 private final PackageStats mStats; 9351 private boolean mSuccess; 9352 9353 private final IPackageStatsObserver mObserver; 9354 9355 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9356 super(new UserHandle(stats.userHandle)); 9357 mObserver = observer; 9358 mStats = stats; 9359 } 9360 9361 @Override 9362 public String toString() { 9363 return "MeasureParams{" 9364 + Integer.toHexString(System.identityHashCode(this)) 9365 + " " + mStats.packageName + "}"; 9366 } 9367 9368 @Override 9369 void handleStartCopy() throws RemoteException { 9370 synchronized (mInstallLock) { 9371 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9372 } 9373 9374 if (mSuccess) { 9375 final boolean mounted; 9376 if (Environment.isExternalStorageEmulated()) { 9377 mounted = true; 9378 } else { 9379 final String status = Environment.getExternalStorageState(); 9380 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9381 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9382 } 9383 9384 if (mounted) { 9385 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9386 9387 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9388 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9389 9390 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9391 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9392 9393 // Always subtract cache size, since it's a subdirectory 9394 mStats.externalDataSize -= mStats.externalCacheSize; 9395 9396 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9397 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9398 9399 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9400 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9401 } 9402 } 9403 } 9404 9405 @Override 9406 void handleReturnCode() { 9407 if (mObserver != null) { 9408 try { 9409 mObserver.onGetStatsCompleted(mStats, mSuccess); 9410 } catch (RemoteException e) { 9411 Slog.i(TAG, "Observer no longer exists."); 9412 } 9413 } 9414 } 9415 9416 @Override 9417 void handleServiceError() { 9418 Slog.e(TAG, "Could not measure application " + mStats.packageName 9419 + " external storage"); 9420 } 9421 } 9422 9423 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9424 throws RemoteException { 9425 long result = 0; 9426 for (File path : paths) { 9427 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9428 } 9429 return result; 9430 } 9431 9432 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9433 for (File path : paths) { 9434 try { 9435 mcs.clearDirectory(path.getAbsolutePath()); 9436 } catch (RemoteException e) { 9437 } 9438 } 9439 } 9440 9441 static class OriginInfo { 9442 /** 9443 * Location where install is coming from, before it has been 9444 * copied/renamed into place. This could be a single monolithic APK 9445 * file, or a cluster directory. This location may be untrusted. 9446 */ 9447 final File file; 9448 final String cid; 9449 9450 /** 9451 * Flag indicating that {@link #file} or {@link #cid} has already been 9452 * staged, meaning downstream users don't need to defensively copy the 9453 * contents. 9454 */ 9455 final boolean staged; 9456 9457 /** 9458 * Flag indicating that {@link #file} or {@link #cid} is an already 9459 * installed app that is being moved. 9460 */ 9461 final boolean existing; 9462 9463 final String resolvedPath; 9464 final File resolvedFile; 9465 9466 static OriginInfo fromNothing() { 9467 return new OriginInfo(null, null, false, false); 9468 } 9469 9470 static OriginInfo fromUntrustedFile(File file) { 9471 return new OriginInfo(file, null, false, false); 9472 } 9473 9474 static OriginInfo fromExistingFile(File file) { 9475 return new OriginInfo(file, null, false, true); 9476 } 9477 9478 static OriginInfo fromStagedFile(File file) { 9479 return new OriginInfo(file, null, true, false); 9480 } 9481 9482 static OriginInfo fromStagedContainer(String cid) { 9483 return new OriginInfo(null, cid, true, false); 9484 } 9485 9486 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9487 this.file = file; 9488 this.cid = cid; 9489 this.staged = staged; 9490 this.existing = existing; 9491 9492 if (cid != null) { 9493 resolvedPath = PackageHelper.getSdDir(cid); 9494 resolvedFile = new File(resolvedPath); 9495 } else if (file != null) { 9496 resolvedPath = file.getAbsolutePath(); 9497 resolvedFile = file; 9498 } else { 9499 resolvedPath = null; 9500 resolvedFile = null; 9501 } 9502 } 9503 } 9504 9505 class InstallParams extends HandlerParams { 9506 final OriginInfo origin; 9507 final IPackageInstallObserver2 observer; 9508 int installFlags; 9509 final String installerPackageName; 9510 final String volumeUuid; 9511 final VerificationParams verificationParams; 9512 private InstallArgs mArgs; 9513 private int mRet; 9514 final String packageAbiOverride; 9515 9516 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9517 String installerPackageName, String volumeUuid, 9518 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9519 super(user); 9520 this.origin = origin; 9521 this.observer = observer; 9522 this.installFlags = installFlags; 9523 this.installerPackageName = installerPackageName; 9524 this.volumeUuid = volumeUuid; 9525 this.verificationParams = verificationParams; 9526 this.packageAbiOverride = packageAbiOverride; 9527 } 9528 9529 @Override 9530 public String toString() { 9531 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9532 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9533 } 9534 9535 public ManifestDigest getManifestDigest() { 9536 if (verificationParams == null) { 9537 return null; 9538 } 9539 return verificationParams.getManifestDigest(); 9540 } 9541 9542 private int installLocationPolicy(PackageInfoLite pkgLite) { 9543 String packageName = pkgLite.packageName; 9544 int installLocation = pkgLite.installLocation; 9545 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9546 // reader 9547 synchronized (mPackages) { 9548 PackageParser.Package pkg = mPackages.get(packageName); 9549 if (pkg != null) { 9550 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9551 // Check for downgrading. 9552 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9553 try { 9554 checkDowngrade(pkg, pkgLite); 9555 } catch (PackageManagerException e) { 9556 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9557 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9558 } 9559 } 9560 // Check for updated system application. 9561 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9562 if (onSd) { 9563 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9564 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9565 } 9566 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9567 } else { 9568 if (onSd) { 9569 // Install flag overrides everything. 9570 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9571 } 9572 // If current upgrade specifies particular preference 9573 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9574 // Application explicitly specified internal. 9575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9576 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9577 // App explictly prefers external. Let policy decide 9578 } else { 9579 // Prefer previous location 9580 if (isExternal(pkg)) { 9581 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9582 } 9583 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9584 } 9585 } 9586 } else { 9587 // Invalid install. Return error code 9588 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9589 } 9590 } 9591 } 9592 // All the special cases have been taken care of. 9593 // Return result based on recommended install location. 9594 if (onSd) { 9595 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9596 } 9597 return pkgLite.recommendedInstallLocation; 9598 } 9599 9600 /* 9601 * Invoke remote method to get package information and install 9602 * location values. Override install location based on default 9603 * policy if needed and then create install arguments based 9604 * on the install location. 9605 */ 9606 public void handleStartCopy() throws RemoteException { 9607 int ret = PackageManager.INSTALL_SUCCEEDED; 9608 9609 // If we're already staged, we've firmly committed to an install location 9610 if (origin.staged) { 9611 if (origin.file != null) { 9612 installFlags |= PackageManager.INSTALL_INTERNAL; 9613 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9614 } else if (origin.cid != null) { 9615 installFlags |= PackageManager.INSTALL_EXTERNAL; 9616 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9617 } else { 9618 throw new IllegalStateException("Invalid stage location"); 9619 } 9620 } 9621 9622 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9623 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9624 9625 PackageInfoLite pkgLite = null; 9626 9627 if (onInt && onSd) { 9628 // Check if both bits are set. 9629 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9630 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9631 } else { 9632 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9633 packageAbiOverride); 9634 9635 /* 9636 * If we have too little free space, try to free cache 9637 * before giving up. 9638 */ 9639 if (!origin.staged && pkgLite.recommendedInstallLocation 9640 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9641 // TODO: focus freeing disk space on the target device 9642 final StorageManager storage = StorageManager.from(mContext); 9643 final long lowThreshold = storage.getStorageLowBytes( 9644 Environment.getDataDirectory()); 9645 9646 final long sizeBytes = mContainerService.calculateInstalledSize( 9647 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9648 9649 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9650 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9651 installFlags, packageAbiOverride); 9652 } 9653 9654 /* 9655 * The cache free must have deleted the file we 9656 * downloaded to install. 9657 * 9658 * TODO: fix the "freeCache" call to not delete 9659 * the file we care about. 9660 */ 9661 if (pkgLite.recommendedInstallLocation 9662 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9663 pkgLite.recommendedInstallLocation 9664 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9665 } 9666 } 9667 } 9668 9669 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9670 int loc = pkgLite.recommendedInstallLocation; 9671 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9672 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9673 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9674 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9675 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9676 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9677 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9678 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9679 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9680 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9681 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9682 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9683 } else { 9684 // Override with defaults if needed. 9685 loc = installLocationPolicy(pkgLite); 9686 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9687 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9688 } else if (!onSd && !onInt) { 9689 // Override install location with flags 9690 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9691 // Set the flag to install on external media. 9692 installFlags |= PackageManager.INSTALL_EXTERNAL; 9693 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9694 } else { 9695 // Make sure the flag for installing on external 9696 // media is unset 9697 installFlags |= PackageManager.INSTALL_INTERNAL; 9698 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9699 } 9700 } 9701 } 9702 } 9703 9704 final InstallArgs args = createInstallArgs(this); 9705 mArgs = args; 9706 9707 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9708 /* 9709 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9710 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9711 */ 9712 int userIdentifier = getUser().getIdentifier(); 9713 if (userIdentifier == UserHandle.USER_ALL 9714 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9715 userIdentifier = UserHandle.USER_OWNER; 9716 } 9717 9718 /* 9719 * Determine if we have any installed package verifiers. If we 9720 * do, then we'll defer to them to verify the packages. 9721 */ 9722 final int requiredUid = mRequiredVerifierPackage == null ? -1 9723 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9724 if (!origin.existing && requiredUid != -1 9725 && isVerificationEnabled(userIdentifier, installFlags)) { 9726 final Intent verification = new Intent( 9727 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9728 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9729 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9730 PACKAGE_MIME_TYPE); 9731 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9732 9733 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9734 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9735 0 /* TODO: Which userId? */); 9736 9737 if (DEBUG_VERIFY) { 9738 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9739 + verification.toString() + " with " + pkgLite.verifiers.length 9740 + " optional verifiers"); 9741 } 9742 9743 final int verificationId = mPendingVerificationToken++; 9744 9745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9746 9747 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9748 installerPackageName); 9749 9750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9751 installFlags); 9752 9753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9754 pkgLite.packageName); 9755 9756 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9757 pkgLite.versionCode); 9758 9759 if (verificationParams != null) { 9760 if (verificationParams.getVerificationURI() != null) { 9761 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9762 verificationParams.getVerificationURI()); 9763 } 9764 if (verificationParams.getOriginatingURI() != null) { 9765 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9766 verificationParams.getOriginatingURI()); 9767 } 9768 if (verificationParams.getReferrer() != null) { 9769 verification.putExtra(Intent.EXTRA_REFERRER, 9770 verificationParams.getReferrer()); 9771 } 9772 if (verificationParams.getOriginatingUid() >= 0) { 9773 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9774 verificationParams.getOriginatingUid()); 9775 } 9776 if (verificationParams.getInstallerUid() >= 0) { 9777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9778 verificationParams.getInstallerUid()); 9779 } 9780 } 9781 9782 final PackageVerificationState verificationState = new PackageVerificationState( 9783 requiredUid, args); 9784 9785 mPendingVerification.append(verificationId, verificationState); 9786 9787 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9788 receivers, verificationState); 9789 9790 /* 9791 * If any sufficient verifiers were listed in the package 9792 * manifest, attempt to ask them. 9793 */ 9794 if (sufficientVerifiers != null) { 9795 final int N = sufficientVerifiers.size(); 9796 if (N == 0) { 9797 Slog.i(TAG, "Additional verifiers required, but none installed."); 9798 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9799 } else { 9800 for (int i = 0; i < N; i++) { 9801 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9802 9803 final Intent sufficientIntent = new Intent(verification); 9804 sufficientIntent.setComponent(verifierComponent); 9805 9806 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9807 } 9808 } 9809 } 9810 9811 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9812 mRequiredVerifierPackage, receivers); 9813 if (ret == PackageManager.INSTALL_SUCCEEDED 9814 && mRequiredVerifierPackage != null) { 9815 /* 9816 * Send the intent to the required verification agent, 9817 * but only start the verification timeout after the 9818 * target BroadcastReceivers have run. 9819 */ 9820 verification.setComponent(requiredVerifierComponent); 9821 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9822 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9823 new BroadcastReceiver() { 9824 @Override 9825 public void onReceive(Context context, Intent intent) { 9826 final Message msg = mHandler 9827 .obtainMessage(CHECK_PENDING_VERIFICATION); 9828 msg.arg1 = verificationId; 9829 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9830 } 9831 }, null, 0, null, null); 9832 9833 /* 9834 * We don't want the copy to proceed until verification 9835 * succeeds, so null out this field. 9836 */ 9837 mArgs = null; 9838 } 9839 } else { 9840 /* 9841 * No package verification is enabled, so immediately start 9842 * the remote call to initiate copy using temporary file. 9843 */ 9844 ret = args.copyApk(mContainerService, true); 9845 } 9846 } 9847 9848 mRet = ret; 9849 } 9850 9851 @Override 9852 void handleReturnCode() { 9853 // If mArgs is null, then MCS couldn't be reached. When it 9854 // reconnects, it will try again to install. At that point, this 9855 // will succeed. 9856 if (mArgs != null) { 9857 processPendingInstall(mArgs, mRet); 9858 } 9859 } 9860 9861 @Override 9862 void handleServiceError() { 9863 mArgs = createInstallArgs(this); 9864 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9865 } 9866 9867 public boolean isForwardLocked() { 9868 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9869 } 9870 } 9871 9872 /** 9873 * Used during creation of InstallArgs 9874 * 9875 * @param installFlags package installation flags 9876 * @return true if should be installed on external storage 9877 */ 9878 private static boolean installOnExternalAsec(int installFlags) { 9879 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9880 return false; 9881 } 9882 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9883 return true; 9884 } 9885 return false; 9886 } 9887 9888 /** 9889 * Used during creation of InstallArgs 9890 * 9891 * @param installFlags package installation flags 9892 * @return true if should be installed as forward locked 9893 */ 9894 private static boolean installForwardLocked(int installFlags) { 9895 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9896 } 9897 9898 private InstallArgs createInstallArgs(InstallParams params) { 9899 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9900 return new AsecInstallArgs(params); 9901 } else { 9902 return new FileInstallArgs(params); 9903 } 9904 } 9905 9906 /** 9907 * Create args that describe an existing installed package. Typically used 9908 * when cleaning up old installs, or used as a move source. 9909 */ 9910 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9911 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9912 final boolean isInAsec; 9913 if (installOnExternalAsec(installFlags)) { 9914 /* Apps on SD card are always in ASEC containers. */ 9915 isInAsec = true; 9916 } else if (installForwardLocked(installFlags) 9917 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9918 /* 9919 * Forward-locked apps are only in ASEC containers if they're the 9920 * new style 9921 */ 9922 isInAsec = true; 9923 } else { 9924 isInAsec = false; 9925 } 9926 9927 if (isInAsec) { 9928 return new AsecInstallArgs(codePath, instructionSets, 9929 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9930 } else { 9931 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9932 instructionSets); 9933 } 9934 } 9935 9936 static abstract class InstallArgs { 9937 /** @see InstallParams#origin */ 9938 final OriginInfo origin; 9939 9940 final IPackageInstallObserver2 observer; 9941 // Always refers to PackageManager flags only 9942 final int installFlags; 9943 final String installerPackageName; 9944 final String volumeUuid; 9945 final ManifestDigest manifestDigest; 9946 final UserHandle user; 9947 final String abiOverride; 9948 9949 // The list of instruction sets supported by this app. This is currently 9950 // only used during the rmdex() phase to clean up resources. We can get rid of this 9951 // if we move dex files under the common app path. 9952 /* nullable */ String[] instructionSets; 9953 9954 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9955 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9956 UserHandle user, String[] instructionSets, String abiOverride) { 9957 this.origin = origin; 9958 this.installFlags = installFlags; 9959 this.observer = observer; 9960 this.installerPackageName = installerPackageName; 9961 this.volumeUuid = volumeUuid; 9962 this.manifestDigest = manifestDigest; 9963 this.user = user; 9964 this.instructionSets = instructionSets; 9965 this.abiOverride = abiOverride; 9966 } 9967 9968 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9969 abstract int doPreInstall(int status); 9970 9971 /** 9972 * Rename package into final resting place. All paths on the given 9973 * scanned package should be updated to reflect the rename. 9974 */ 9975 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9976 abstract int doPostInstall(int status, int uid); 9977 9978 /** @see PackageSettingBase#codePathString */ 9979 abstract String getCodePath(); 9980 /** @see PackageSettingBase#resourcePathString */ 9981 abstract String getResourcePath(); 9982 abstract String getLegacyNativeLibraryPath(); 9983 9984 // Need installer lock especially for dex file removal. 9985 abstract void cleanUpResourcesLI(); 9986 abstract boolean doPostDeleteLI(boolean delete); 9987 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9988 9989 /** 9990 * Called before the source arguments are copied. This is used mostly 9991 * for MoveParams when it needs to read the source file to put it in the 9992 * destination. 9993 */ 9994 int doPreCopy() { 9995 return PackageManager.INSTALL_SUCCEEDED; 9996 } 9997 9998 /** 9999 * Called after the source arguments are copied. This is used mostly for 10000 * MoveParams when it needs to read the source file to put it in the 10001 * destination. 10002 * 10003 * @return 10004 */ 10005 int doPostCopy(int uid) { 10006 return PackageManager.INSTALL_SUCCEEDED; 10007 } 10008 10009 protected boolean isFwdLocked() { 10010 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10011 } 10012 10013 protected boolean isExternalAsec() { 10014 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10015 } 10016 10017 UserHandle getUser() { 10018 return user; 10019 } 10020 } 10021 10022 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10023 if (!allCodePaths.isEmpty()) { 10024 if (instructionSets == null) { 10025 throw new IllegalStateException("instructionSet == null"); 10026 } 10027 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10028 for (String codePath : allCodePaths) { 10029 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10030 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10031 if (retCode < 0) { 10032 Slog.w(TAG, "Couldn't remove dex file for package: " 10033 + " at location " + codePath + ", retcode=" + retCode); 10034 // we don't consider this to be a failure of the core package deletion 10035 } 10036 } 10037 } 10038 } 10039 } 10040 10041 /** 10042 * Logic to handle installation of non-ASEC applications, including copying 10043 * and renaming logic. 10044 */ 10045 class FileInstallArgs extends InstallArgs { 10046 private File codeFile; 10047 private File resourceFile; 10048 private File legacyNativeLibraryPath; 10049 10050 // Example topology: 10051 // /data/app/com.example/base.apk 10052 // /data/app/com.example/split_foo.apk 10053 // /data/app/com.example/lib/arm/libfoo.so 10054 // /data/app/com.example/lib/arm64/libfoo.so 10055 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10056 10057 /** New install */ 10058 FileInstallArgs(InstallParams params) { 10059 super(params.origin, params.observer, params.installFlags, 10060 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10061 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10062 if (isFwdLocked()) { 10063 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10064 } 10065 } 10066 10067 /** Existing install */ 10068 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10069 String[] instructionSets) { 10070 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10071 this.codeFile = (codePath != null) ? new File(codePath) : null; 10072 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10073 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10074 new File(legacyNativeLibraryPath) : null; 10075 } 10076 10077 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10078 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10079 isFwdLocked(), abiOverride); 10080 10081 final StorageManager storage = StorageManager.from(mContext); 10082 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10083 } 10084 10085 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10086 if (origin.staged) { 10087 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10088 codeFile = origin.file; 10089 resourceFile = origin.file; 10090 return PackageManager.INSTALL_SUCCEEDED; 10091 } 10092 10093 try { 10094 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10095 codeFile = tempDir; 10096 resourceFile = tempDir; 10097 } catch (IOException e) { 10098 Slog.w(TAG, "Failed to create copy file: " + e); 10099 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10100 } 10101 10102 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10103 @Override 10104 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10105 if (!FileUtils.isValidExtFilename(name)) { 10106 throw new IllegalArgumentException("Invalid filename: " + name); 10107 } 10108 try { 10109 final File file = new File(codeFile, name); 10110 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10111 O_RDWR | O_CREAT, 0644); 10112 Os.chmod(file.getAbsolutePath(), 0644); 10113 return new ParcelFileDescriptor(fd); 10114 } catch (ErrnoException e) { 10115 throw new RemoteException("Failed to open: " + e.getMessage()); 10116 } 10117 } 10118 }; 10119 10120 int ret = PackageManager.INSTALL_SUCCEEDED; 10121 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10122 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10123 Slog.e(TAG, "Failed to copy package"); 10124 return ret; 10125 } 10126 10127 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10128 NativeLibraryHelper.Handle handle = null; 10129 try { 10130 handle = NativeLibraryHelper.Handle.create(codeFile); 10131 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10132 abiOverride); 10133 } catch (IOException e) { 10134 Slog.e(TAG, "Copying native libraries failed", e); 10135 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10136 } finally { 10137 IoUtils.closeQuietly(handle); 10138 } 10139 10140 return ret; 10141 } 10142 10143 int doPreInstall(int status) { 10144 if (status != PackageManager.INSTALL_SUCCEEDED) { 10145 cleanUp(); 10146 } 10147 return status; 10148 } 10149 10150 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10151 if (status != PackageManager.INSTALL_SUCCEEDED) { 10152 cleanUp(); 10153 return false; 10154 } else { 10155 final File targetDir = codeFile.getParentFile(); 10156 final File beforeCodeFile = codeFile; 10157 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10158 10159 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10160 try { 10161 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10162 } catch (ErrnoException e) { 10163 Slog.d(TAG, "Failed to rename", e); 10164 return false; 10165 } 10166 10167 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10168 Slog.d(TAG, "Failed to restorecon"); 10169 return false; 10170 } 10171 10172 // Reflect the rename internally 10173 codeFile = afterCodeFile; 10174 resourceFile = afterCodeFile; 10175 10176 // Reflect the rename in scanned details 10177 pkg.codePath = afterCodeFile.getAbsolutePath(); 10178 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10179 pkg.baseCodePath); 10180 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10181 pkg.splitCodePaths); 10182 10183 // Reflect the rename in app info 10184 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10185 pkg.applicationInfo.setCodePath(pkg.codePath); 10186 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10187 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10188 pkg.applicationInfo.setResourcePath(pkg.codePath); 10189 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10190 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10191 10192 return true; 10193 } 10194 } 10195 10196 int doPostInstall(int status, int uid) { 10197 if (status != PackageManager.INSTALL_SUCCEEDED) { 10198 cleanUp(); 10199 } 10200 return status; 10201 } 10202 10203 @Override 10204 String getCodePath() { 10205 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10206 } 10207 10208 @Override 10209 String getResourcePath() { 10210 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10211 } 10212 10213 @Override 10214 String getLegacyNativeLibraryPath() { 10215 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10216 } 10217 10218 private boolean cleanUp() { 10219 if (codeFile == null || !codeFile.exists()) { 10220 return false; 10221 } 10222 10223 if (codeFile.isDirectory()) { 10224 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10225 } else { 10226 codeFile.delete(); 10227 } 10228 10229 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10230 resourceFile.delete(); 10231 } 10232 10233 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10234 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10235 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10236 } 10237 legacyNativeLibraryPath.delete(); 10238 } 10239 10240 return true; 10241 } 10242 10243 void cleanUpResourcesLI() { 10244 // Try enumerating all code paths before deleting 10245 List<String> allCodePaths = Collections.EMPTY_LIST; 10246 if (codeFile != null && codeFile.exists()) { 10247 try { 10248 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10249 allCodePaths = pkg.getAllCodePaths(); 10250 } catch (PackageParserException e) { 10251 // Ignored; we tried our best 10252 } 10253 } 10254 10255 cleanUp(); 10256 removeDexFiles(allCodePaths, instructionSets); 10257 } 10258 10259 boolean doPostDeleteLI(boolean delete) { 10260 // XXX err, shouldn't we respect the delete flag? 10261 cleanUpResourcesLI(); 10262 return true; 10263 } 10264 } 10265 10266 private boolean isAsecExternal(String cid) { 10267 final String asecPath = PackageHelper.getSdFilesystem(cid); 10268 return !asecPath.startsWith(mAsecInternalPath); 10269 } 10270 10271 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10272 PackageManagerException { 10273 if (copyRet < 0) { 10274 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10275 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10276 throw new PackageManagerException(copyRet, message); 10277 } 10278 } 10279 } 10280 10281 /** 10282 * Extract the MountService "container ID" from the full code path of an 10283 * .apk. 10284 */ 10285 static String cidFromCodePath(String fullCodePath) { 10286 int eidx = fullCodePath.lastIndexOf("/"); 10287 String subStr1 = fullCodePath.substring(0, eidx); 10288 int sidx = subStr1.lastIndexOf("/"); 10289 return subStr1.substring(sidx+1, eidx); 10290 } 10291 10292 /** 10293 * Logic to handle installation of ASEC applications, including copying and 10294 * renaming logic. 10295 */ 10296 class AsecInstallArgs extends InstallArgs { 10297 static final String RES_FILE_NAME = "pkg.apk"; 10298 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10299 10300 String cid; 10301 String packagePath; 10302 String resourcePath; 10303 String legacyNativeLibraryDir; 10304 10305 /** New install */ 10306 AsecInstallArgs(InstallParams params) { 10307 super(params.origin, params.observer, params.installFlags, 10308 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10309 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10310 } 10311 10312 /** Existing install */ 10313 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10314 boolean isExternal, boolean isForwardLocked) { 10315 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10316 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10317 instructionSets, null); 10318 // Hackily pretend we're still looking at a full code path 10319 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10320 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10321 } 10322 10323 // Extract cid from fullCodePath 10324 int eidx = fullCodePath.lastIndexOf("/"); 10325 String subStr1 = fullCodePath.substring(0, eidx); 10326 int sidx = subStr1.lastIndexOf("/"); 10327 cid = subStr1.substring(sidx+1, eidx); 10328 setMountPath(subStr1); 10329 } 10330 10331 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10332 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10333 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10334 instructionSets, null); 10335 this.cid = cid; 10336 setMountPath(PackageHelper.getSdDir(cid)); 10337 } 10338 10339 void createCopyFile() { 10340 cid = mInstallerService.allocateExternalStageCidLegacy(); 10341 } 10342 10343 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10344 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10345 abiOverride); 10346 10347 final File target; 10348 if (isExternalAsec()) { 10349 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10350 } else { 10351 target = Environment.getDataDirectory(); 10352 } 10353 10354 final StorageManager storage = StorageManager.from(mContext); 10355 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10356 } 10357 10358 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10359 if (origin.staged) { 10360 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10361 cid = origin.cid; 10362 setMountPath(PackageHelper.getSdDir(cid)); 10363 return PackageManager.INSTALL_SUCCEEDED; 10364 } 10365 10366 if (temp) { 10367 createCopyFile(); 10368 } else { 10369 /* 10370 * Pre-emptively destroy the container since it's destroyed if 10371 * copying fails due to it existing anyway. 10372 */ 10373 PackageHelper.destroySdDir(cid); 10374 } 10375 10376 final String newMountPath = imcs.copyPackageToContainer( 10377 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10378 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10379 10380 if (newMountPath != null) { 10381 setMountPath(newMountPath); 10382 return PackageManager.INSTALL_SUCCEEDED; 10383 } else { 10384 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10385 } 10386 } 10387 10388 @Override 10389 String getCodePath() { 10390 return packagePath; 10391 } 10392 10393 @Override 10394 String getResourcePath() { 10395 return resourcePath; 10396 } 10397 10398 @Override 10399 String getLegacyNativeLibraryPath() { 10400 return legacyNativeLibraryDir; 10401 } 10402 10403 int doPreInstall(int status) { 10404 if (status != PackageManager.INSTALL_SUCCEEDED) { 10405 // Destroy container 10406 PackageHelper.destroySdDir(cid); 10407 } else { 10408 boolean mounted = PackageHelper.isContainerMounted(cid); 10409 if (!mounted) { 10410 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10411 Process.SYSTEM_UID); 10412 if (newMountPath != null) { 10413 setMountPath(newMountPath); 10414 } else { 10415 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10416 } 10417 } 10418 } 10419 return status; 10420 } 10421 10422 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10423 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10424 String newMountPath = null; 10425 if (PackageHelper.isContainerMounted(cid)) { 10426 // Unmount the container 10427 if (!PackageHelper.unMountSdDir(cid)) { 10428 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10429 return false; 10430 } 10431 } 10432 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10433 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10434 " which might be stale. Will try to clean up."); 10435 // Clean up the stale container and proceed to recreate. 10436 if (!PackageHelper.destroySdDir(newCacheId)) { 10437 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10438 return false; 10439 } 10440 // Successfully cleaned up stale container. Try to rename again. 10441 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10442 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10443 + " inspite of cleaning it up."); 10444 return false; 10445 } 10446 } 10447 if (!PackageHelper.isContainerMounted(newCacheId)) { 10448 Slog.w(TAG, "Mounting container " + newCacheId); 10449 newMountPath = PackageHelper.mountSdDir(newCacheId, 10450 getEncryptKey(), Process.SYSTEM_UID); 10451 } else { 10452 newMountPath = PackageHelper.getSdDir(newCacheId); 10453 } 10454 if (newMountPath == null) { 10455 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10456 return false; 10457 } 10458 Log.i(TAG, "Succesfully renamed " + cid + 10459 " to " + newCacheId + 10460 " at new path: " + newMountPath); 10461 cid = newCacheId; 10462 10463 final File beforeCodeFile = new File(packagePath); 10464 setMountPath(newMountPath); 10465 final File afterCodeFile = new File(packagePath); 10466 10467 // Reflect the rename in scanned details 10468 pkg.codePath = afterCodeFile.getAbsolutePath(); 10469 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10470 pkg.baseCodePath); 10471 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10472 pkg.splitCodePaths); 10473 10474 // Reflect the rename in app info 10475 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10476 pkg.applicationInfo.setCodePath(pkg.codePath); 10477 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10478 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10479 pkg.applicationInfo.setResourcePath(pkg.codePath); 10480 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10481 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10482 10483 return true; 10484 } 10485 10486 private void setMountPath(String mountPath) { 10487 final File mountFile = new File(mountPath); 10488 10489 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10490 if (monolithicFile.exists()) { 10491 packagePath = monolithicFile.getAbsolutePath(); 10492 if (isFwdLocked()) { 10493 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10494 } else { 10495 resourcePath = packagePath; 10496 } 10497 } else { 10498 packagePath = mountFile.getAbsolutePath(); 10499 resourcePath = packagePath; 10500 } 10501 10502 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10503 } 10504 10505 int doPostInstall(int status, int uid) { 10506 if (status != PackageManager.INSTALL_SUCCEEDED) { 10507 cleanUp(); 10508 } else { 10509 final int groupOwner; 10510 final String protectedFile; 10511 if (isFwdLocked()) { 10512 groupOwner = UserHandle.getSharedAppGid(uid); 10513 protectedFile = RES_FILE_NAME; 10514 } else { 10515 groupOwner = -1; 10516 protectedFile = null; 10517 } 10518 10519 if (uid < Process.FIRST_APPLICATION_UID 10520 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10521 Slog.e(TAG, "Failed to finalize " + cid); 10522 PackageHelper.destroySdDir(cid); 10523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10524 } 10525 10526 boolean mounted = PackageHelper.isContainerMounted(cid); 10527 if (!mounted) { 10528 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10529 } 10530 } 10531 return status; 10532 } 10533 10534 private void cleanUp() { 10535 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10536 10537 // Destroy secure container 10538 PackageHelper.destroySdDir(cid); 10539 } 10540 10541 private List<String> getAllCodePaths() { 10542 final File codeFile = new File(getCodePath()); 10543 if (codeFile != null && codeFile.exists()) { 10544 try { 10545 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10546 return pkg.getAllCodePaths(); 10547 } catch (PackageParserException e) { 10548 // Ignored; we tried our best 10549 } 10550 } 10551 return Collections.EMPTY_LIST; 10552 } 10553 10554 void cleanUpResourcesLI() { 10555 // Enumerate all code paths before deleting 10556 cleanUpResourcesLI(getAllCodePaths()); 10557 } 10558 10559 private void cleanUpResourcesLI(List<String> allCodePaths) { 10560 cleanUp(); 10561 removeDexFiles(allCodePaths, instructionSets); 10562 } 10563 10564 10565 10566 String getPackageName() { 10567 return getAsecPackageName(cid); 10568 } 10569 10570 boolean doPostDeleteLI(boolean delete) { 10571 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10572 final List<String> allCodePaths = getAllCodePaths(); 10573 boolean mounted = PackageHelper.isContainerMounted(cid); 10574 if (mounted) { 10575 // Unmount first 10576 if (PackageHelper.unMountSdDir(cid)) { 10577 mounted = false; 10578 } 10579 } 10580 if (!mounted && delete) { 10581 cleanUpResourcesLI(allCodePaths); 10582 } 10583 return !mounted; 10584 } 10585 10586 @Override 10587 int doPreCopy() { 10588 if (isFwdLocked()) { 10589 if (!PackageHelper.fixSdPermissions(cid, 10590 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10591 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10592 } 10593 } 10594 10595 return PackageManager.INSTALL_SUCCEEDED; 10596 } 10597 10598 @Override 10599 int doPostCopy(int uid) { 10600 if (isFwdLocked()) { 10601 if (uid < Process.FIRST_APPLICATION_UID 10602 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10603 RES_FILE_NAME)) { 10604 Slog.e(TAG, "Failed to finalize " + cid); 10605 PackageHelper.destroySdDir(cid); 10606 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10607 } 10608 } 10609 10610 return PackageManager.INSTALL_SUCCEEDED; 10611 } 10612 } 10613 10614 static String getAsecPackageName(String packageCid) { 10615 int idx = packageCid.lastIndexOf("-"); 10616 if (idx == -1) { 10617 return packageCid; 10618 } 10619 return packageCid.substring(0, idx); 10620 } 10621 10622 // Utility method used to create code paths based on package name and available index. 10623 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10624 String idxStr = ""; 10625 int idx = 1; 10626 // Fall back to default value of idx=1 if prefix is not 10627 // part of oldCodePath 10628 if (oldCodePath != null) { 10629 String subStr = oldCodePath; 10630 // Drop the suffix right away 10631 if (suffix != null && subStr.endsWith(suffix)) { 10632 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10633 } 10634 // If oldCodePath already contains prefix find out the 10635 // ending index to either increment or decrement. 10636 int sidx = subStr.lastIndexOf(prefix); 10637 if (sidx != -1) { 10638 subStr = subStr.substring(sidx + prefix.length()); 10639 if (subStr != null) { 10640 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10641 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10642 } 10643 try { 10644 idx = Integer.parseInt(subStr); 10645 if (idx <= 1) { 10646 idx++; 10647 } else { 10648 idx--; 10649 } 10650 } catch(NumberFormatException e) { 10651 } 10652 } 10653 } 10654 } 10655 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10656 return prefix + idxStr; 10657 } 10658 10659 private File getNextCodePath(File targetDir, String packageName) { 10660 int suffix = 1; 10661 File result; 10662 do { 10663 result = new File(targetDir, packageName + "-" + suffix); 10664 suffix++; 10665 } while (result.exists()); 10666 return result; 10667 } 10668 10669 // Utility method that returns the relative package path with respect 10670 // to the installation directory. Like say for /data/data/com.test-1.apk 10671 // string com.test-1 is returned. 10672 static String deriveCodePathName(String codePath) { 10673 if (codePath == null) { 10674 return null; 10675 } 10676 final File codeFile = new File(codePath); 10677 final String name = codeFile.getName(); 10678 if (codeFile.isDirectory()) { 10679 return name; 10680 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10681 final int lastDot = name.lastIndexOf('.'); 10682 return name.substring(0, lastDot); 10683 } else { 10684 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10685 return null; 10686 } 10687 } 10688 10689 class PackageInstalledInfo { 10690 String name; 10691 int uid; 10692 // The set of users that originally had this package installed. 10693 int[] origUsers; 10694 // The set of users that now have this package installed. 10695 int[] newUsers; 10696 PackageParser.Package pkg; 10697 int returnCode; 10698 String returnMsg; 10699 PackageRemovedInfo removedInfo; 10700 10701 public void setError(int code, String msg) { 10702 returnCode = code; 10703 returnMsg = msg; 10704 Slog.w(TAG, msg); 10705 } 10706 10707 public void setError(String msg, PackageParserException e) { 10708 returnCode = e.error; 10709 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10710 Slog.w(TAG, msg, e); 10711 } 10712 10713 public void setError(String msg, PackageManagerException e) { 10714 returnCode = e.error; 10715 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10716 Slog.w(TAG, msg, e); 10717 } 10718 10719 // In some error cases we want to convey more info back to the observer 10720 String origPackage; 10721 String origPermission; 10722 } 10723 10724 /* 10725 * Install a non-existing package. 10726 */ 10727 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10728 UserHandle user, String installerPackageName, String volumeUuid, 10729 PackageInstalledInfo res) { 10730 // Remember this for later, in case we need to rollback this install 10731 String pkgName = pkg.packageName; 10732 10733 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10734 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10735 UserHandle.USER_OWNER).exists(); 10736 synchronized(mPackages) { 10737 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10738 // A package with the same name is already installed, though 10739 // it has been renamed to an older name. The package we 10740 // are trying to install should be installed as an update to 10741 // the existing one, but that has not been requested, so bail. 10742 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10743 + " without first uninstalling package running as " 10744 + mSettings.mRenamedPackages.get(pkgName)); 10745 return; 10746 } 10747 if (mPackages.containsKey(pkgName)) { 10748 // Don't allow installation over an existing package with the same name. 10749 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10750 + " without first uninstalling."); 10751 return; 10752 } 10753 } 10754 10755 try { 10756 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10757 System.currentTimeMillis(), user); 10758 10759 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10760 // delete the partially installed application. the data directory will have to be 10761 // restored if it was already existing 10762 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10763 // remove package from internal structures. Note that we want deletePackageX to 10764 // delete the package data and cache directories that it created in 10765 // scanPackageLocked, unless those directories existed before we even tried to 10766 // install. 10767 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10768 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10769 res.removedInfo, true); 10770 } 10771 10772 } catch (PackageManagerException e) { 10773 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10774 } 10775 } 10776 10777 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10778 // Upgrade keysets are being used. Determine if new package has a superset of the 10779 // required keys. 10780 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10781 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10782 for (int i = 0; i < upgradeKeySets.length; i++) { 10783 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10784 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10785 return true; 10786 } 10787 } 10788 return false; 10789 } 10790 10791 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10792 UserHandle user, String installerPackageName, String volumeUuid, 10793 PackageInstalledInfo res) { 10794 PackageParser.Package oldPackage; 10795 String pkgName = pkg.packageName; 10796 int[] allUsers; 10797 boolean[] perUserInstalled; 10798 10799 // First find the old package info and check signatures 10800 synchronized(mPackages) { 10801 oldPackage = mPackages.get(pkgName); 10802 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10803 PackageSetting ps = mSettings.mPackages.get(pkgName); 10804 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10805 // default to original signature matching 10806 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10807 != PackageManager.SIGNATURE_MATCH) { 10808 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10809 "New package has a different signature: " + pkgName); 10810 return; 10811 } 10812 } else { 10813 if(!checkUpgradeKeySetLP(ps, pkg)) { 10814 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10815 "New package not signed by keys specified by upgrade-keysets: " 10816 + pkgName); 10817 return; 10818 } 10819 } 10820 10821 // In case of rollback, remember per-user/profile install state 10822 allUsers = sUserManager.getUserIds(); 10823 perUserInstalled = new boolean[allUsers.length]; 10824 for (int i = 0; i < allUsers.length; i++) { 10825 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10826 } 10827 } 10828 10829 boolean sysPkg = (isSystemApp(oldPackage)); 10830 if (sysPkg) { 10831 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10832 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10833 } else { 10834 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10835 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10836 } 10837 } 10838 10839 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10840 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10841 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10842 String volumeUuid, PackageInstalledInfo res) { 10843 String pkgName = deletedPackage.packageName; 10844 boolean deletedPkg = true; 10845 boolean updatedSettings = false; 10846 10847 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10848 + deletedPackage); 10849 long origUpdateTime; 10850 if (pkg.mExtras != null) { 10851 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10852 } else { 10853 origUpdateTime = 0; 10854 } 10855 10856 // First delete the existing package while retaining the data directory 10857 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10858 res.removedInfo, true)) { 10859 // If the existing package wasn't successfully deleted 10860 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10861 deletedPkg = false; 10862 } else { 10863 // Successfully deleted the old package; proceed with replace. 10864 10865 // If deleted package lived in a container, give users a chance to 10866 // relinquish resources before killing. 10867 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10868 if (DEBUG_INSTALL) { 10869 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10870 } 10871 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10872 final ArrayList<String> pkgList = new ArrayList<String>(1); 10873 pkgList.add(deletedPackage.applicationInfo.packageName); 10874 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10875 } 10876 10877 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10878 try { 10879 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10880 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10881 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10882 perUserInstalled, res, user); 10883 updatedSettings = true; 10884 } catch (PackageManagerException e) { 10885 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10886 } 10887 } 10888 10889 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10890 // remove package from internal structures. Note that we want deletePackageX to 10891 // delete the package data and cache directories that it created in 10892 // scanPackageLocked, unless those directories existed before we even tried to 10893 // install. 10894 if(updatedSettings) { 10895 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10896 deletePackageLI( 10897 pkgName, null, true, allUsers, perUserInstalled, 10898 PackageManager.DELETE_KEEP_DATA, 10899 res.removedInfo, true); 10900 } 10901 // Since we failed to install the new package we need to restore the old 10902 // package that we deleted. 10903 if (deletedPkg) { 10904 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10905 File restoreFile = new File(deletedPackage.codePath); 10906 // Parse old package 10907 boolean oldExternal = isExternal(deletedPackage); 10908 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10909 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10910 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10911 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10912 try { 10913 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10914 } catch (PackageManagerException e) { 10915 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10916 + e.getMessage()); 10917 return; 10918 } 10919 // Restore of old package succeeded. Update permissions. 10920 // writer 10921 synchronized (mPackages) { 10922 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10923 UPDATE_PERMISSIONS_ALL); 10924 // can downgrade to reader 10925 mSettings.writeLPr(); 10926 } 10927 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10928 } 10929 } 10930 } 10931 10932 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10933 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10934 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10935 String volumeUuid, PackageInstalledInfo res) { 10936 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10937 + ", old=" + deletedPackage); 10938 boolean disabledSystem = false; 10939 boolean updatedSettings = false; 10940 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10941 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10942 != 0) { 10943 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10944 } 10945 String packageName = deletedPackage.packageName; 10946 if (packageName == null) { 10947 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10948 "Attempt to delete null packageName."); 10949 return; 10950 } 10951 PackageParser.Package oldPkg; 10952 PackageSetting oldPkgSetting; 10953 // reader 10954 synchronized (mPackages) { 10955 oldPkg = mPackages.get(packageName); 10956 oldPkgSetting = mSettings.mPackages.get(packageName); 10957 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10958 (oldPkgSetting == null)) { 10959 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10960 "Couldn't find package:" + packageName + " information"); 10961 return; 10962 } 10963 } 10964 10965 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10966 10967 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10968 res.removedInfo.removedPackage = packageName; 10969 // Remove existing system package 10970 removePackageLI(oldPkgSetting, true); 10971 // writer 10972 synchronized (mPackages) { 10973 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10974 if (!disabledSystem && deletedPackage != null) { 10975 // We didn't need to disable the .apk as a current system package, 10976 // which means we are replacing another update that is already 10977 // installed. We need to make sure to delete the older one's .apk. 10978 res.removedInfo.args = createInstallArgsForExisting(0, 10979 deletedPackage.applicationInfo.getCodePath(), 10980 deletedPackage.applicationInfo.getResourcePath(), 10981 deletedPackage.applicationInfo.nativeLibraryRootDir, 10982 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10983 } else { 10984 res.removedInfo.args = null; 10985 } 10986 } 10987 10988 // Successfully disabled the old package. Now proceed with re-installation 10989 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 10990 10991 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10992 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10993 10994 PackageParser.Package newPackage = null; 10995 try { 10996 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10997 if (newPackage.mExtras != null) { 10998 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10999 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11000 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11001 11002 // is the update attempting to change shared user? that isn't going to work... 11003 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11004 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11005 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11006 + " to " + newPkgSetting.sharedUser); 11007 updatedSettings = true; 11008 } 11009 } 11010 11011 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11012 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11013 perUserInstalled, res, user); 11014 updatedSettings = true; 11015 } 11016 11017 } catch (PackageManagerException e) { 11018 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11019 } 11020 11021 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11022 // Re installation failed. Restore old information 11023 // Remove new pkg information 11024 if (newPackage != null) { 11025 removeInstalledPackageLI(newPackage, true); 11026 } 11027 // Add back the old system package 11028 try { 11029 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11030 } catch (PackageManagerException e) { 11031 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11032 } 11033 // Restore the old system information in Settings 11034 synchronized (mPackages) { 11035 if (disabledSystem) { 11036 mSettings.enableSystemPackageLPw(packageName); 11037 } 11038 if (updatedSettings) { 11039 mSettings.setInstallerPackageName(packageName, 11040 oldPkgSetting.installerPackageName); 11041 } 11042 mSettings.writeLPr(); 11043 } 11044 } 11045 } 11046 11047 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11048 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11049 UserHandle user) { 11050 String pkgName = newPackage.packageName; 11051 synchronized (mPackages) { 11052 //write settings. the installStatus will be incomplete at this stage. 11053 //note that the new package setting would have already been 11054 //added to mPackages. It hasn't been persisted yet. 11055 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11056 mSettings.writeLPr(); 11057 } 11058 11059 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11060 11061 synchronized (mPackages) { 11062 updatePermissionsLPw(newPackage.packageName, newPackage, 11063 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11064 ? UPDATE_PERMISSIONS_ALL : 0)); 11065 // For system-bundled packages, we assume that installing an upgraded version 11066 // of the package implies that the user actually wants to run that new code, 11067 // so we enable the package. 11068 PackageSetting ps = mSettings.mPackages.get(pkgName); 11069 if (ps != null) { 11070 if (isSystemApp(newPackage)) { 11071 // NB: implicit assumption that system package upgrades apply to all users 11072 if (DEBUG_INSTALL) { 11073 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11074 } 11075 if (res.origUsers != null) { 11076 for (int userHandle : res.origUsers) { 11077 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11078 userHandle, installerPackageName); 11079 } 11080 } 11081 // Also convey the prior install/uninstall state 11082 if (allUsers != null && perUserInstalled != null) { 11083 for (int i = 0; i < allUsers.length; i++) { 11084 if (DEBUG_INSTALL) { 11085 Slog.d(TAG, " user " + allUsers[i] 11086 + " => " + perUserInstalled[i]); 11087 } 11088 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11089 } 11090 // these install state changes will be persisted in the 11091 // upcoming call to mSettings.writeLPr(). 11092 } 11093 } 11094 // It's implied that when a user requests installation, they want the app to be 11095 // installed and enabled. 11096 int userId = user.getIdentifier(); 11097 if (userId != UserHandle.USER_ALL) { 11098 ps.setInstalled(true, userId); 11099 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11100 } 11101 } 11102 res.name = pkgName; 11103 res.uid = newPackage.applicationInfo.uid; 11104 res.pkg = newPackage; 11105 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11106 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11107 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11108 //to update install status 11109 mSettings.writeLPr(); 11110 } 11111 } 11112 11113 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11114 final int installFlags = args.installFlags; 11115 final String installerPackageName = args.installerPackageName; 11116 final String volumeUuid = args.volumeUuid; 11117 final File tmpPackageFile = new File(args.getCodePath()); 11118 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11119 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11120 || (args.volumeUuid != null)); 11121 boolean replace = false; 11122 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11123 // Result object to be returned 11124 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11125 11126 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11127 // Retrieve PackageSettings and parse package 11128 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11129 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11130 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11131 PackageParser pp = new PackageParser(); 11132 pp.setSeparateProcesses(mSeparateProcesses); 11133 pp.setDisplayMetrics(mMetrics); 11134 11135 final PackageParser.Package pkg; 11136 try { 11137 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11138 } catch (PackageParserException e) { 11139 res.setError("Failed parse during installPackageLI", e); 11140 return; 11141 } 11142 11143 // Mark that we have an install time CPU ABI override. 11144 pkg.cpuAbiOverride = args.abiOverride; 11145 11146 String pkgName = res.name = pkg.packageName; 11147 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11148 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11149 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11150 return; 11151 } 11152 } 11153 11154 try { 11155 pp.collectCertificates(pkg, parseFlags); 11156 pp.collectManifestDigest(pkg); 11157 } catch (PackageParserException e) { 11158 res.setError("Failed collect during installPackageLI", e); 11159 return; 11160 } 11161 11162 /* If the installer passed in a manifest digest, compare it now. */ 11163 if (args.manifestDigest != null) { 11164 if (DEBUG_INSTALL) { 11165 final String parsedManifest = pkg.manifestDigest == null ? "null" 11166 : pkg.manifestDigest.toString(); 11167 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11168 + parsedManifest); 11169 } 11170 11171 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11172 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11173 return; 11174 } 11175 } else if (DEBUG_INSTALL) { 11176 final String parsedManifest = pkg.manifestDigest == null 11177 ? "null" : pkg.manifestDigest.toString(); 11178 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11179 } 11180 11181 // Get rid of all references to package scan path via parser. 11182 pp = null; 11183 String oldCodePath = null; 11184 boolean systemApp = false; 11185 synchronized (mPackages) { 11186 // Check if installing already existing package 11187 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11188 String oldName = mSettings.mRenamedPackages.get(pkgName); 11189 if (pkg.mOriginalPackages != null 11190 && pkg.mOriginalPackages.contains(oldName) 11191 && mPackages.containsKey(oldName)) { 11192 // This package is derived from an original package, 11193 // and this device has been updating from that original 11194 // name. We must continue using the original name, so 11195 // rename the new package here. 11196 pkg.setPackageName(oldName); 11197 pkgName = pkg.packageName; 11198 replace = true; 11199 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11200 + oldName + " pkgName=" + pkgName); 11201 } else if (mPackages.containsKey(pkgName)) { 11202 // This package, under its official name, already exists 11203 // on the device; we should replace it. 11204 replace = true; 11205 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11206 } 11207 } 11208 11209 PackageSetting ps = mSettings.mPackages.get(pkgName); 11210 if (ps != null) { 11211 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11212 11213 // Quick sanity check that we're signed correctly if updating; 11214 // we'll check this again later when scanning, but we want to 11215 // bail early here before tripping over redefined permissions. 11216 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11217 try { 11218 verifySignaturesLP(ps, pkg); 11219 } catch (PackageManagerException e) { 11220 res.setError(e.error, e.getMessage()); 11221 return; 11222 } 11223 } else { 11224 if (!checkUpgradeKeySetLP(ps, pkg)) { 11225 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11226 + pkg.packageName + " upgrade keys do not match the " 11227 + "previously installed version"); 11228 return; 11229 } 11230 } 11231 11232 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11233 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11234 systemApp = (ps.pkg.applicationInfo.flags & 11235 ApplicationInfo.FLAG_SYSTEM) != 0; 11236 } 11237 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11238 } 11239 11240 // Check whether the newly-scanned package wants to define an already-defined perm 11241 int N = pkg.permissions.size(); 11242 for (int i = N-1; i >= 0; i--) { 11243 PackageParser.Permission perm = pkg.permissions.get(i); 11244 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11245 if (bp != null) { 11246 // If the defining package is signed with our cert, it's okay. This 11247 // also includes the "updating the same package" case, of course. 11248 // "updating same package" could also involve key-rotation. 11249 final boolean sigsOk; 11250 if (!bp.sourcePackage.equals(pkg.packageName) 11251 || !(bp.packageSetting instanceof PackageSetting) 11252 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11253 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11254 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11255 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11256 } else { 11257 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11258 } 11259 if (!sigsOk) { 11260 // If the owning package is the system itself, we log but allow 11261 // install to proceed; we fail the install on all other permission 11262 // redefinitions. 11263 if (!bp.sourcePackage.equals("android")) { 11264 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11265 + pkg.packageName + " attempting to redeclare permission " 11266 + perm.info.name + " already owned by " + bp.sourcePackage); 11267 res.origPermission = perm.info.name; 11268 res.origPackage = bp.sourcePackage; 11269 return; 11270 } else { 11271 Slog.w(TAG, "Package " + pkg.packageName 11272 + " attempting to redeclare system permission " 11273 + perm.info.name + "; ignoring new declaration"); 11274 pkg.permissions.remove(i); 11275 } 11276 } 11277 } 11278 } 11279 11280 } 11281 11282 if (systemApp && onExternal) { 11283 // Disable updates to system apps on sdcard 11284 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11285 "Cannot install updates to system apps on sdcard"); 11286 return; 11287 } 11288 11289 // If app directory is not writable, dexopt will be called after the rename 11290 if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11291 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11292 scanFlags |= SCAN_NO_DEX; 11293 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11294 int result = mPackageDexOptimizer 11295 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11296 false /* defer */, false /* inclDependencies */); 11297 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11298 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11299 return; 11300 } 11301 } 11302 11303 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11304 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11305 return; 11306 } 11307 11308 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11309 11310 if (replace) { 11311 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11312 installerPackageName, volumeUuid, res); 11313 } else { 11314 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11315 args.user, installerPackageName, volumeUuid, res); 11316 } 11317 synchronized (mPackages) { 11318 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11319 if (ps != null) { 11320 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11321 } 11322 } 11323 } 11324 11325 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11326 if (mIntentFilterVerifierComponent == null) { 11327 Slog.d(TAG, "No IntentFilter verification will not be done as " 11328 + "there is no IntentFilterVerifier available!"); 11329 return; 11330 } 11331 11332 final int verifierUid = getPackageUid( 11333 mIntentFilterVerifierComponent.getPackageName(), 11334 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11335 11336 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11337 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11338 msg.obj = pkg; 11339 msg.arg1 = userId; 11340 msg.arg2 = verifierUid; 11341 11342 mHandler.sendMessage(msg); 11343 } 11344 11345 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11346 PackageParser.Package pkg) { 11347 int size = pkg.activities.size(); 11348 if (size == 0) { 11349 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11350 return; 11351 } 11352 11353 final boolean hasDomainURLs = hasDomainURLs(pkg); 11354 if (!hasDomainURLs) { 11355 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11356 return; 11357 } 11358 11359 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11360 + " Activities needs verification ..."); 11361 11362 final int verificationId = mIntentFilterVerificationToken++; 11363 int count = 0; 11364 final String packageName = pkg.packageName; 11365 ArrayList<String> allHosts = new ArrayList<>(); 11366 11367 synchronized (mPackages) { 11368 for (PackageParser.Activity a : pkg.activities) { 11369 for (ActivityIntentInfo filter : a.intents) { 11370 boolean needsFilterVerification = filter.needsVerification(); 11371 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11372 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11373 mIntentFilterVerifier.addOneIntentFilterVerification( 11374 verifierUid, userId, verificationId, filter, packageName); 11375 count++; 11376 } else if (!needsFilterVerification) { 11377 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11378 if (hasValidDomains(filter)) { 11379 ArrayList<String> hosts = filter.getHostsList(); 11380 if (hosts.size() > 0) { 11381 allHosts.addAll(hosts); 11382 } else { 11383 if (allHosts.isEmpty()) { 11384 allHosts.add("*"); 11385 } 11386 } 11387 } 11388 } else { 11389 Slog.d(TAG, "Verification already done for IntentFilter:" 11390 + filter.toString()); 11391 } 11392 } 11393 } 11394 } 11395 11396 if (count > 0) { 11397 mIntentFilterVerifier.startVerifications(userId); 11398 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11399 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11400 } else { 11401 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11402 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11403 packageName, allHosts) != null) { 11404 scheduleWriteSettingsLocked(); 11405 } 11406 } 11407 } 11408 11409 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11410 final ComponentName cn = filter.activity.getComponentName(); 11411 final String packageName = cn.getPackageName(); 11412 11413 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11414 packageName); 11415 if (ivi == null) { 11416 return true; 11417 } 11418 int status = ivi.getStatus(); 11419 switch (status) { 11420 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11421 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11422 return true; 11423 11424 default: 11425 // Nothing to do 11426 return false; 11427 } 11428 } 11429 11430 private static boolean isMultiArch(PackageSetting ps) { 11431 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11432 } 11433 11434 private static boolean isMultiArch(ApplicationInfo info) { 11435 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11436 } 11437 11438 private static boolean isExternal(PackageParser.Package pkg) { 11439 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11440 } 11441 11442 private static boolean isExternal(PackageSetting ps) { 11443 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11444 } 11445 11446 private static boolean isExternal(ApplicationInfo info) { 11447 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11448 } 11449 11450 private static boolean isSystemApp(PackageParser.Package pkg) { 11451 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11452 } 11453 11454 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11455 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11456 } 11457 11458 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11459 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11460 } 11461 11462 private static boolean isSystemApp(PackageSetting ps) { 11463 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11464 } 11465 11466 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11467 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11468 } 11469 11470 private int packageFlagsToInstallFlags(PackageSetting ps) { 11471 int installFlags = 0; 11472 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11473 // This existing package was an external ASEC install when we have 11474 // the external flag without a UUID 11475 installFlags |= PackageManager.INSTALL_EXTERNAL; 11476 } 11477 if (ps.isForwardLocked()) { 11478 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11479 } 11480 return installFlags; 11481 } 11482 11483 private void deleteTempPackageFiles() { 11484 final FilenameFilter filter = new FilenameFilter() { 11485 public boolean accept(File dir, String name) { 11486 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11487 } 11488 }; 11489 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11490 file.delete(); 11491 } 11492 } 11493 11494 @Override 11495 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11496 int flags) { 11497 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11498 flags); 11499 } 11500 11501 @Override 11502 public void deletePackage(final String packageName, 11503 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11504 mContext.enforceCallingOrSelfPermission( 11505 android.Manifest.permission.DELETE_PACKAGES, null); 11506 final int uid = Binder.getCallingUid(); 11507 if (UserHandle.getUserId(uid) != userId) { 11508 mContext.enforceCallingPermission( 11509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11510 "deletePackage for user " + userId); 11511 } 11512 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11513 try { 11514 observer.onPackageDeleted(packageName, 11515 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11516 } catch (RemoteException re) { 11517 } 11518 return; 11519 } 11520 11521 boolean uninstallBlocked = false; 11522 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11523 int[] users = sUserManager.getUserIds(); 11524 for (int i = 0; i < users.length; ++i) { 11525 if (getBlockUninstallForUser(packageName, users[i])) { 11526 uninstallBlocked = true; 11527 break; 11528 } 11529 } 11530 } else { 11531 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11532 } 11533 if (uninstallBlocked) { 11534 try { 11535 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11536 null); 11537 } catch (RemoteException re) { 11538 } 11539 return; 11540 } 11541 11542 if (DEBUG_REMOVE) { 11543 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11544 } 11545 // Queue up an async operation since the package deletion may take a little while. 11546 mHandler.post(new Runnable() { 11547 public void run() { 11548 mHandler.removeCallbacks(this); 11549 final int returnCode = deletePackageX(packageName, userId, flags); 11550 if (observer != null) { 11551 try { 11552 observer.onPackageDeleted(packageName, returnCode, null); 11553 } catch (RemoteException e) { 11554 Log.i(TAG, "Observer no longer exists."); 11555 } //end catch 11556 } //end if 11557 } //end run 11558 }); 11559 } 11560 11561 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11562 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11563 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11564 try { 11565 if (dpm != null) { 11566 if (dpm.isDeviceOwner(packageName)) { 11567 return true; 11568 } 11569 int[] users; 11570 if (userId == UserHandle.USER_ALL) { 11571 users = sUserManager.getUserIds(); 11572 } else { 11573 users = new int[]{userId}; 11574 } 11575 for (int i = 0; i < users.length; ++i) { 11576 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11577 return true; 11578 } 11579 } 11580 } 11581 } catch (RemoteException e) { 11582 } 11583 return false; 11584 } 11585 11586 /** 11587 * This method is an internal method that could be get invoked either 11588 * to delete an installed package or to clean up a failed installation. 11589 * After deleting an installed package, a broadcast is sent to notify any 11590 * listeners that the package has been installed. For cleaning up a failed 11591 * installation, the broadcast is not necessary since the package's 11592 * installation wouldn't have sent the initial broadcast either 11593 * The key steps in deleting a package are 11594 * deleting the package information in internal structures like mPackages, 11595 * deleting the packages base directories through installd 11596 * updating mSettings to reflect current status 11597 * persisting settings for later use 11598 * sending a broadcast if necessary 11599 */ 11600 private int deletePackageX(String packageName, int userId, int flags) { 11601 final PackageRemovedInfo info = new PackageRemovedInfo(); 11602 final boolean res; 11603 11604 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11605 ? UserHandle.ALL : new UserHandle(userId); 11606 11607 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11608 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11609 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11610 } 11611 11612 boolean removedForAllUsers = false; 11613 boolean systemUpdate = false; 11614 11615 // for the uninstall-updates case and restricted profiles, remember the per- 11616 // userhandle installed state 11617 int[] allUsers; 11618 boolean[] perUserInstalled; 11619 synchronized (mPackages) { 11620 PackageSetting ps = mSettings.mPackages.get(packageName); 11621 allUsers = sUserManager.getUserIds(); 11622 perUserInstalled = new boolean[allUsers.length]; 11623 for (int i = 0; i < allUsers.length; i++) { 11624 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11625 } 11626 } 11627 11628 synchronized (mInstallLock) { 11629 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11630 res = deletePackageLI(packageName, removeForUser, 11631 true, allUsers, perUserInstalled, 11632 flags | REMOVE_CHATTY, info, true); 11633 systemUpdate = info.isRemovedPackageSystemUpdate; 11634 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11635 removedForAllUsers = true; 11636 } 11637 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11638 + " removedForAllUsers=" + removedForAllUsers); 11639 } 11640 11641 if (res) { 11642 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11643 11644 // If the removed package was a system update, the old system package 11645 // was re-enabled; we need to broadcast this information 11646 if (systemUpdate) { 11647 Bundle extras = new Bundle(1); 11648 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11649 ? info.removedAppId : info.uid); 11650 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11651 11652 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11653 extras, null, null, null); 11654 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11655 extras, null, null, null); 11656 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11657 null, packageName, null, null); 11658 } 11659 } 11660 // Force a gc here. 11661 Runtime.getRuntime().gc(); 11662 // Delete the resources here after sending the broadcast to let 11663 // other processes clean up before deleting resources. 11664 if (info.args != null) { 11665 synchronized (mInstallLock) { 11666 info.args.doPostDeleteLI(true); 11667 } 11668 } 11669 11670 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11671 } 11672 11673 static class PackageRemovedInfo { 11674 String removedPackage; 11675 int uid = -1; 11676 int removedAppId = -1; 11677 int[] removedUsers = null; 11678 boolean isRemovedPackageSystemUpdate = false; 11679 // Clean up resources deleted packages. 11680 InstallArgs args = null; 11681 11682 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11683 Bundle extras = new Bundle(1); 11684 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11685 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11686 if (replacing) { 11687 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11688 } 11689 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11690 if (removedPackage != null) { 11691 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11692 extras, null, null, removedUsers); 11693 if (fullRemove && !replacing) { 11694 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11695 extras, null, null, removedUsers); 11696 } 11697 } 11698 if (removedAppId >= 0) { 11699 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11700 removedUsers); 11701 } 11702 } 11703 } 11704 11705 /* 11706 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11707 * flag is not set, the data directory is removed as well. 11708 * make sure this flag is set for partially installed apps. If not its meaningless to 11709 * delete a partially installed application. 11710 */ 11711 private void removePackageDataLI(PackageSetting ps, 11712 int[] allUserHandles, boolean[] perUserInstalled, 11713 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11714 String packageName = ps.name; 11715 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11716 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11717 // Retrieve object to delete permissions for shared user later on 11718 final PackageSetting deletedPs; 11719 // reader 11720 synchronized (mPackages) { 11721 deletedPs = mSettings.mPackages.get(packageName); 11722 if (outInfo != null) { 11723 outInfo.removedPackage = packageName; 11724 outInfo.removedUsers = deletedPs != null 11725 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11726 : null; 11727 } 11728 } 11729 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11730 removeDataDirsLI(ps.volumeUuid, packageName); 11731 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11732 } 11733 // writer 11734 synchronized (mPackages) { 11735 if (deletedPs != null) { 11736 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11737 if (outInfo != null) { 11738 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11739 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11740 } 11741 updatePermissionsLPw(deletedPs.name, null, 0); 11742 if (deletedPs.sharedUser != null) { 11743 // Remove permissions associated with package. Since runtime 11744 // permissions are per user we have to kill the removed package 11745 // or packages running under the shared user of the removed 11746 // package if revoking the permissions requested only by the removed 11747 // package is successful and this causes a change in gids. 11748 for (int userId : UserManagerService.getInstance().getUserIds()) { 11749 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11750 userId); 11751 if (userIdToKill == UserHandle.USER_ALL 11752 || userIdToKill >= UserHandle.USER_OWNER) { 11753 // If gids changed for this user, kill all affected packages. 11754 mHandler.post(new Runnable() { 11755 @Override 11756 public void run() { 11757 // This has to happen with no lock held. 11758 killSettingPackagesForUser(deletedPs, userIdToKill, 11759 KILL_APP_REASON_GIDS_CHANGED); 11760 } 11761 }); 11762 break; 11763 } 11764 } 11765 } 11766 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11767 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11768 } 11769 // make sure to preserve per-user disabled state if this removal was just 11770 // a downgrade of a system app to the factory package 11771 if (allUserHandles != null && perUserInstalled != null) { 11772 if (DEBUG_REMOVE) { 11773 Slog.d(TAG, "Propagating install state across downgrade"); 11774 } 11775 for (int i = 0; i < allUserHandles.length; i++) { 11776 if (DEBUG_REMOVE) { 11777 Slog.d(TAG, " user " + allUserHandles[i] 11778 + " => " + perUserInstalled[i]); 11779 } 11780 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11781 } 11782 } 11783 } 11784 // can downgrade to reader 11785 if (writeSettings) { 11786 // Save settings now 11787 mSettings.writeLPr(); 11788 } 11789 } 11790 if (outInfo != null) { 11791 // A user ID was deleted here. Go through all users and remove it 11792 // from KeyStore. 11793 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11794 } 11795 } 11796 11797 static boolean locationIsPrivileged(File path) { 11798 try { 11799 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11800 .getCanonicalPath(); 11801 return path.getCanonicalPath().startsWith(privilegedAppDir); 11802 } catch (IOException e) { 11803 Slog.e(TAG, "Unable to access code path " + path); 11804 } 11805 return false; 11806 } 11807 11808 /* 11809 * Tries to delete system package. 11810 */ 11811 private boolean deleteSystemPackageLI(PackageSetting newPs, 11812 int[] allUserHandles, boolean[] perUserInstalled, 11813 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11814 final boolean applyUserRestrictions 11815 = (allUserHandles != null) && (perUserInstalled != null); 11816 PackageSetting disabledPs = null; 11817 // Confirm if the system package has been updated 11818 // An updated system app can be deleted. This will also have to restore 11819 // the system pkg from system partition 11820 // reader 11821 synchronized (mPackages) { 11822 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11823 } 11824 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11825 + " disabledPs=" + disabledPs); 11826 if (disabledPs == null) { 11827 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11828 return false; 11829 } else if (DEBUG_REMOVE) { 11830 Slog.d(TAG, "Deleting system pkg from data partition"); 11831 } 11832 if (DEBUG_REMOVE) { 11833 if (applyUserRestrictions) { 11834 Slog.d(TAG, "Remembering install states:"); 11835 for (int i = 0; i < allUserHandles.length; i++) { 11836 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11837 } 11838 } 11839 } 11840 // Delete the updated package 11841 outInfo.isRemovedPackageSystemUpdate = true; 11842 if (disabledPs.versionCode < newPs.versionCode) { 11843 // Delete data for downgrades 11844 flags &= ~PackageManager.DELETE_KEEP_DATA; 11845 } else { 11846 // Preserve data by setting flag 11847 flags |= PackageManager.DELETE_KEEP_DATA; 11848 } 11849 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11850 allUserHandles, perUserInstalled, outInfo, writeSettings); 11851 if (!ret) { 11852 return false; 11853 } 11854 // writer 11855 synchronized (mPackages) { 11856 // Reinstate the old system package 11857 mSettings.enableSystemPackageLPw(newPs.name); 11858 // Remove any native libraries from the upgraded package. 11859 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11860 } 11861 // Install the system package 11862 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11863 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11864 if (locationIsPrivileged(disabledPs.codePath)) { 11865 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11866 } 11867 11868 final PackageParser.Package newPkg; 11869 try { 11870 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11871 } catch (PackageManagerException e) { 11872 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11873 return false; 11874 } 11875 11876 // writer 11877 synchronized (mPackages) { 11878 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11879 updatePermissionsLPw(newPkg.packageName, newPkg, 11880 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11881 if (applyUserRestrictions) { 11882 if (DEBUG_REMOVE) { 11883 Slog.d(TAG, "Propagating install state across reinstall"); 11884 } 11885 for (int i = 0; i < allUserHandles.length; i++) { 11886 if (DEBUG_REMOVE) { 11887 Slog.d(TAG, " user " + allUserHandles[i] 11888 + " => " + perUserInstalled[i]); 11889 } 11890 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11891 } 11892 // Regardless of writeSettings we need to ensure that this restriction 11893 // state propagation is persisted 11894 mSettings.writeAllUsersPackageRestrictionsLPr(); 11895 } 11896 // can downgrade to reader here 11897 if (writeSettings) { 11898 mSettings.writeLPr(); 11899 } 11900 } 11901 return true; 11902 } 11903 11904 private boolean deleteInstalledPackageLI(PackageSetting ps, 11905 boolean deleteCodeAndResources, int flags, 11906 int[] allUserHandles, boolean[] perUserInstalled, 11907 PackageRemovedInfo outInfo, boolean writeSettings) { 11908 if (outInfo != null) { 11909 outInfo.uid = ps.appId; 11910 } 11911 11912 // Delete package data from internal structures and also remove data if flag is set 11913 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11914 11915 // Delete application code and resources 11916 if (deleteCodeAndResources && (outInfo != null)) { 11917 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11918 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11919 getAppDexInstructionSets(ps)); 11920 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11921 } 11922 return true; 11923 } 11924 11925 @Override 11926 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11927 int userId) { 11928 mContext.enforceCallingOrSelfPermission( 11929 android.Manifest.permission.DELETE_PACKAGES, null); 11930 synchronized (mPackages) { 11931 PackageSetting ps = mSettings.mPackages.get(packageName); 11932 if (ps == null) { 11933 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11934 return false; 11935 } 11936 if (!ps.getInstalled(userId)) { 11937 // Can't block uninstall for an app that is not installed or enabled. 11938 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11939 return false; 11940 } 11941 ps.setBlockUninstall(blockUninstall, userId); 11942 mSettings.writePackageRestrictionsLPr(userId); 11943 } 11944 return true; 11945 } 11946 11947 @Override 11948 public boolean getBlockUninstallForUser(String packageName, int userId) { 11949 synchronized (mPackages) { 11950 PackageSetting ps = mSettings.mPackages.get(packageName); 11951 if (ps == null) { 11952 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11953 return false; 11954 } 11955 return ps.getBlockUninstall(userId); 11956 } 11957 } 11958 11959 /* 11960 * This method handles package deletion in general 11961 */ 11962 private boolean deletePackageLI(String packageName, UserHandle user, 11963 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11964 int flags, PackageRemovedInfo outInfo, 11965 boolean writeSettings) { 11966 if (packageName == null) { 11967 Slog.w(TAG, "Attempt to delete null packageName."); 11968 return false; 11969 } 11970 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11971 PackageSetting ps; 11972 boolean dataOnly = false; 11973 int removeUser = -1; 11974 int appId = -1; 11975 synchronized (mPackages) { 11976 ps = mSettings.mPackages.get(packageName); 11977 if (ps == null) { 11978 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11979 return false; 11980 } 11981 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11982 && user.getIdentifier() != UserHandle.USER_ALL) { 11983 // The caller is asking that the package only be deleted for a single 11984 // user. To do this, we just mark its uninstalled state and delete 11985 // its data. If this is a system app, we only allow this to happen if 11986 // they have set the special DELETE_SYSTEM_APP which requests different 11987 // semantics than normal for uninstalling system apps. 11988 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11989 ps.setUserState(user.getIdentifier(), 11990 COMPONENT_ENABLED_STATE_DEFAULT, 11991 false, //installed 11992 true, //stopped 11993 true, //notLaunched 11994 false, //hidden 11995 null, null, null, 11996 false, // blockUninstall 11997 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11998 if (!isSystemApp(ps)) { 11999 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12000 // Other user still have this package installed, so all 12001 // we need to do is clear this user's data and save that 12002 // it is uninstalled. 12003 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12004 removeUser = user.getIdentifier(); 12005 appId = ps.appId; 12006 scheduleWritePackageRestrictionsLocked(removeUser); 12007 } else { 12008 // We need to set it back to 'installed' so the uninstall 12009 // broadcasts will be sent correctly. 12010 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12011 ps.setInstalled(true, user.getIdentifier()); 12012 } 12013 } else { 12014 // This is a system app, so we assume that the 12015 // other users still have this package installed, so all 12016 // we need to do is clear this user's data and save that 12017 // it is uninstalled. 12018 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12019 removeUser = user.getIdentifier(); 12020 appId = ps.appId; 12021 scheduleWritePackageRestrictionsLocked(removeUser); 12022 } 12023 } 12024 } 12025 12026 if (removeUser >= 0) { 12027 // From above, we determined that we are deleting this only 12028 // for a single user. Continue the work here. 12029 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12030 if (outInfo != null) { 12031 outInfo.removedPackage = packageName; 12032 outInfo.removedAppId = appId; 12033 outInfo.removedUsers = new int[] {removeUser}; 12034 } 12035 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12036 removeKeystoreDataIfNeeded(removeUser, appId); 12037 schedulePackageCleaning(packageName, removeUser, false); 12038 synchronized (mPackages) { 12039 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12040 scheduleWritePackageRestrictionsLocked(removeUser); 12041 } 12042 } 12043 return true; 12044 } 12045 12046 if (dataOnly) { 12047 // Delete application data first 12048 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12049 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12050 return true; 12051 } 12052 12053 boolean ret = false; 12054 if (isSystemApp(ps)) { 12055 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12056 // When an updated system application is deleted we delete the existing resources as well and 12057 // fall back to existing code in system partition 12058 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12059 flags, outInfo, writeSettings); 12060 } else { 12061 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12062 // Kill application pre-emptively especially for apps on sd. 12063 killApplication(packageName, ps.appId, "uninstall pkg"); 12064 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12065 allUserHandles, perUserInstalled, 12066 outInfo, writeSettings); 12067 } 12068 12069 return ret; 12070 } 12071 12072 private final class ClearStorageConnection implements ServiceConnection { 12073 IMediaContainerService mContainerService; 12074 12075 @Override 12076 public void onServiceConnected(ComponentName name, IBinder service) { 12077 synchronized (this) { 12078 mContainerService = IMediaContainerService.Stub.asInterface(service); 12079 notifyAll(); 12080 } 12081 } 12082 12083 @Override 12084 public void onServiceDisconnected(ComponentName name) { 12085 } 12086 } 12087 12088 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12089 final boolean mounted; 12090 if (Environment.isExternalStorageEmulated()) { 12091 mounted = true; 12092 } else { 12093 final String status = Environment.getExternalStorageState(); 12094 12095 mounted = status.equals(Environment.MEDIA_MOUNTED) 12096 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12097 } 12098 12099 if (!mounted) { 12100 return; 12101 } 12102 12103 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12104 int[] users; 12105 if (userId == UserHandle.USER_ALL) { 12106 users = sUserManager.getUserIds(); 12107 } else { 12108 users = new int[] { userId }; 12109 } 12110 final ClearStorageConnection conn = new ClearStorageConnection(); 12111 if (mContext.bindServiceAsUser( 12112 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12113 try { 12114 for (int curUser : users) { 12115 long timeout = SystemClock.uptimeMillis() + 5000; 12116 synchronized (conn) { 12117 long now = SystemClock.uptimeMillis(); 12118 while (conn.mContainerService == null && now < timeout) { 12119 try { 12120 conn.wait(timeout - now); 12121 } catch (InterruptedException e) { 12122 } 12123 } 12124 } 12125 if (conn.mContainerService == null) { 12126 return; 12127 } 12128 12129 final UserEnvironment userEnv = new UserEnvironment(curUser); 12130 clearDirectory(conn.mContainerService, 12131 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12132 if (allData) { 12133 clearDirectory(conn.mContainerService, 12134 userEnv.buildExternalStorageAppDataDirs(packageName)); 12135 clearDirectory(conn.mContainerService, 12136 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12137 } 12138 } 12139 } finally { 12140 mContext.unbindService(conn); 12141 } 12142 } 12143 } 12144 12145 @Override 12146 public void clearApplicationUserData(final String packageName, 12147 final IPackageDataObserver observer, final int userId) { 12148 mContext.enforceCallingOrSelfPermission( 12149 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12150 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12151 // Queue up an async operation since the package deletion may take a little while. 12152 mHandler.post(new Runnable() { 12153 public void run() { 12154 mHandler.removeCallbacks(this); 12155 final boolean succeeded; 12156 synchronized (mInstallLock) { 12157 succeeded = clearApplicationUserDataLI(packageName, userId); 12158 } 12159 clearExternalStorageDataSync(packageName, userId, true); 12160 if (succeeded) { 12161 // invoke DeviceStorageMonitor's update method to clear any notifications 12162 DeviceStorageMonitorInternal 12163 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12164 if (dsm != null) { 12165 dsm.checkMemory(); 12166 } 12167 } 12168 if(observer != null) { 12169 try { 12170 observer.onRemoveCompleted(packageName, succeeded); 12171 } catch (RemoteException e) { 12172 Log.i(TAG, "Observer no longer exists."); 12173 } 12174 } //end if observer 12175 } //end run 12176 }); 12177 } 12178 12179 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12180 if (packageName == null) { 12181 Slog.w(TAG, "Attempt to delete null packageName."); 12182 return false; 12183 } 12184 12185 // Try finding details about the requested package 12186 PackageParser.Package pkg; 12187 synchronized (mPackages) { 12188 pkg = mPackages.get(packageName); 12189 if (pkg == null) { 12190 final PackageSetting ps = mSettings.mPackages.get(packageName); 12191 if (ps != null) { 12192 pkg = ps.pkg; 12193 } 12194 } 12195 } 12196 12197 if (pkg == null) { 12198 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12199 } 12200 12201 // Always delete data directories for package, even if we found no other 12202 // record of app. This helps users recover from UID mismatches without 12203 // resorting to a full data wipe. 12204 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12205 if (retCode < 0) { 12206 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12207 return false; 12208 } 12209 12210 if (pkg == null) { 12211 return false; 12212 } 12213 12214 if (pkg != null && pkg.applicationInfo != null) { 12215 final int appId = pkg.applicationInfo.uid; 12216 removeKeystoreDataIfNeeded(userId, appId); 12217 } 12218 12219 // Create a native library symlink only if we have native libraries 12220 // and if the native libraries are 32 bit libraries. We do not provide 12221 // this symlink for 64 bit libraries. 12222 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12223 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12224 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12225 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12226 nativeLibPath, userId) < 0) { 12227 Slog.w(TAG, "Failed linking native library dir"); 12228 return false; 12229 } 12230 } 12231 12232 return true; 12233 } 12234 12235 /** 12236 * Remove entries from the keystore daemon. Will only remove it if the 12237 * {@code appId} is valid. 12238 */ 12239 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12240 if (appId < 0) { 12241 return; 12242 } 12243 12244 final KeyStore keyStore = KeyStore.getInstance(); 12245 if (keyStore != null) { 12246 if (userId == UserHandle.USER_ALL) { 12247 for (final int individual : sUserManager.getUserIds()) { 12248 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12249 } 12250 } else { 12251 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12252 } 12253 } else { 12254 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12255 } 12256 } 12257 12258 @Override 12259 public void deleteApplicationCacheFiles(final String packageName, 12260 final IPackageDataObserver observer) { 12261 mContext.enforceCallingOrSelfPermission( 12262 android.Manifest.permission.DELETE_CACHE_FILES, null); 12263 // Queue up an async operation since the package deletion may take a little while. 12264 final int userId = UserHandle.getCallingUserId(); 12265 mHandler.post(new Runnable() { 12266 public void run() { 12267 mHandler.removeCallbacks(this); 12268 final boolean succeded; 12269 synchronized (mInstallLock) { 12270 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12271 } 12272 clearExternalStorageDataSync(packageName, userId, false); 12273 if(observer != null) { 12274 try { 12275 observer.onRemoveCompleted(packageName, succeded); 12276 } catch (RemoteException e) { 12277 Log.i(TAG, "Observer no longer exists."); 12278 } 12279 } //end if observer 12280 } //end run 12281 }); 12282 } 12283 12284 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12285 if (packageName == null) { 12286 Slog.w(TAG, "Attempt to delete null packageName."); 12287 return false; 12288 } 12289 PackageParser.Package p; 12290 synchronized (mPackages) { 12291 p = mPackages.get(packageName); 12292 } 12293 if (p == null) { 12294 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12295 return false; 12296 } 12297 final ApplicationInfo applicationInfo = p.applicationInfo; 12298 if (applicationInfo == null) { 12299 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12300 return false; 12301 } 12302 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12303 if (retCode < 0) { 12304 Slog.w(TAG, "Couldn't remove cache files for package: " 12305 + packageName + " u" + userId); 12306 return false; 12307 } 12308 return true; 12309 } 12310 12311 @Override 12312 public void getPackageSizeInfo(final String packageName, int userHandle, 12313 final IPackageStatsObserver observer) { 12314 mContext.enforceCallingOrSelfPermission( 12315 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12316 if (packageName == null) { 12317 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12318 } 12319 12320 PackageStats stats = new PackageStats(packageName, userHandle); 12321 12322 /* 12323 * Queue up an async operation since the package measurement may take a 12324 * little while. 12325 */ 12326 Message msg = mHandler.obtainMessage(INIT_COPY); 12327 msg.obj = new MeasureParams(stats, observer); 12328 mHandler.sendMessage(msg); 12329 } 12330 12331 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12332 PackageStats pStats) { 12333 if (packageName == null) { 12334 Slog.w(TAG, "Attempt to get size of null packageName."); 12335 return false; 12336 } 12337 PackageParser.Package p; 12338 boolean dataOnly = false; 12339 String libDirRoot = null; 12340 String asecPath = null; 12341 PackageSetting ps = null; 12342 synchronized (mPackages) { 12343 p = mPackages.get(packageName); 12344 ps = mSettings.mPackages.get(packageName); 12345 if(p == null) { 12346 dataOnly = true; 12347 if((ps == null) || (ps.pkg == null)) { 12348 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12349 return false; 12350 } 12351 p = ps.pkg; 12352 } 12353 if (ps != null) { 12354 libDirRoot = ps.legacyNativeLibraryPathString; 12355 } 12356 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12357 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12358 if (secureContainerId != null) { 12359 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12360 } 12361 } 12362 } 12363 String publicSrcDir = null; 12364 if(!dataOnly) { 12365 final ApplicationInfo applicationInfo = p.applicationInfo; 12366 if (applicationInfo == null) { 12367 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12368 return false; 12369 } 12370 if (p.isForwardLocked()) { 12371 publicSrcDir = applicationInfo.getBaseResourcePath(); 12372 } 12373 } 12374 // TODO: extend to measure size of split APKs 12375 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12376 // not just the first level. 12377 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12378 // just the primary. 12379 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12380 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12381 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12382 if (res < 0) { 12383 return false; 12384 } 12385 12386 // Fix-up for forward-locked applications in ASEC containers. 12387 if (!isExternal(p)) { 12388 pStats.codeSize += pStats.externalCodeSize; 12389 pStats.externalCodeSize = 0L; 12390 } 12391 12392 return true; 12393 } 12394 12395 12396 @Override 12397 public void addPackageToPreferred(String packageName) { 12398 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12399 } 12400 12401 @Override 12402 public void removePackageFromPreferred(String packageName) { 12403 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12404 } 12405 12406 @Override 12407 public List<PackageInfo> getPreferredPackages(int flags) { 12408 return new ArrayList<PackageInfo>(); 12409 } 12410 12411 private int getUidTargetSdkVersionLockedLPr(int uid) { 12412 Object obj = mSettings.getUserIdLPr(uid); 12413 if (obj instanceof SharedUserSetting) { 12414 final SharedUserSetting sus = (SharedUserSetting) obj; 12415 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12416 final Iterator<PackageSetting> it = sus.packages.iterator(); 12417 while (it.hasNext()) { 12418 final PackageSetting ps = it.next(); 12419 if (ps.pkg != null) { 12420 int v = ps.pkg.applicationInfo.targetSdkVersion; 12421 if (v < vers) vers = v; 12422 } 12423 } 12424 return vers; 12425 } else if (obj instanceof PackageSetting) { 12426 final PackageSetting ps = (PackageSetting) obj; 12427 if (ps.pkg != null) { 12428 return ps.pkg.applicationInfo.targetSdkVersion; 12429 } 12430 } 12431 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12432 } 12433 12434 @Override 12435 public void addPreferredActivity(IntentFilter filter, int match, 12436 ComponentName[] set, ComponentName activity, int userId) { 12437 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12438 "Adding preferred"); 12439 } 12440 12441 private void addPreferredActivityInternal(IntentFilter filter, int match, 12442 ComponentName[] set, ComponentName activity, boolean always, int userId, 12443 String opname) { 12444 // writer 12445 int callingUid = Binder.getCallingUid(); 12446 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12447 if (filter.countActions() == 0) { 12448 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12449 return; 12450 } 12451 synchronized (mPackages) { 12452 if (mContext.checkCallingOrSelfPermission( 12453 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12454 != PackageManager.PERMISSION_GRANTED) { 12455 if (getUidTargetSdkVersionLockedLPr(callingUid) 12456 < Build.VERSION_CODES.FROYO) { 12457 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12458 + callingUid); 12459 return; 12460 } 12461 mContext.enforceCallingOrSelfPermission( 12462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12463 } 12464 12465 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12466 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12467 + userId + ":"); 12468 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12469 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12470 scheduleWritePackageRestrictionsLocked(userId); 12471 } 12472 } 12473 12474 @Override 12475 public void replacePreferredActivity(IntentFilter filter, int match, 12476 ComponentName[] set, ComponentName activity, int userId) { 12477 if (filter.countActions() != 1) { 12478 throw new IllegalArgumentException( 12479 "replacePreferredActivity expects filter to have only 1 action."); 12480 } 12481 if (filter.countDataAuthorities() != 0 12482 || filter.countDataPaths() != 0 12483 || filter.countDataSchemes() > 1 12484 || filter.countDataTypes() != 0) { 12485 throw new IllegalArgumentException( 12486 "replacePreferredActivity expects filter to have no data authorities, " + 12487 "paths, or types; and at most one scheme."); 12488 } 12489 12490 final int callingUid = Binder.getCallingUid(); 12491 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12492 synchronized (mPackages) { 12493 if (mContext.checkCallingOrSelfPermission( 12494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12495 != PackageManager.PERMISSION_GRANTED) { 12496 if (getUidTargetSdkVersionLockedLPr(callingUid) 12497 < Build.VERSION_CODES.FROYO) { 12498 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12499 + Binder.getCallingUid()); 12500 return; 12501 } 12502 mContext.enforceCallingOrSelfPermission( 12503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12504 } 12505 12506 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12507 if (pir != null) { 12508 // Get all of the existing entries that exactly match this filter. 12509 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12510 if (existing != null && existing.size() == 1) { 12511 PreferredActivity cur = existing.get(0); 12512 if (DEBUG_PREFERRED) { 12513 Slog.i(TAG, "Checking replace of preferred:"); 12514 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12515 if (!cur.mPref.mAlways) { 12516 Slog.i(TAG, " -- CUR; not mAlways!"); 12517 } else { 12518 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12519 Slog.i(TAG, " -- CUR: mSet=" 12520 + Arrays.toString(cur.mPref.mSetComponents)); 12521 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12522 Slog.i(TAG, " -- NEW: mMatch=" 12523 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12524 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12525 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12526 } 12527 } 12528 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12529 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12530 && cur.mPref.sameSet(set)) { 12531 // Setting the preferred activity to what it happens to be already 12532 if (DEBUG_PREFERRED) { 12533 Slog.i(TAG, "Replacing with same preferred activity " 12534 + cur.mPref.mShortComponent + " for user " 12535 + userId + ":"); 12536 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12537 } 12538 return; 12539 } 12540 } 12541 12542 if (existing != null) { 12543 if (DEBUG_PREFERRED) { 12544 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12546 } 12547 for (int i = 0; i < existing.size(); i++) { 12548 PreferredActivity pa = existing.get(i); 12549 if (DEBUG_PREFERRED) { 12550 Slog.i(TAG, "Removing existing preferred activity " 12551 + pa.mPref.mComponent + ":"); 12552 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12553 } 12554 pir.removeFilter(pa); 12555 } 12556 } 12557 } 12558 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12559 "Replacing preferred"); 12560 } 12561 } 12562 12563 @Override 12564 public void clearPackagePreferredActivities(String packageName) { 12565 final int uid = Binder.getCallingUid(); 12566 // writer 12567 synchronized (mPackages) { 12568 PackageParser.Package pkg = mPackages.get(packageName); 12569 if (pkg == null || pkg.applicationInfo.uid != uid) { 12570 if (mContext.checkCallingOrSelfPermission( 12571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12572 != PackageManager.PERMISSION_GRANTED) { 12573 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12574 < Build.VERSION_CODES.FROYO) { 12575 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12576 + Binder.getCallingUid()); 12577 return; 12578 } 12579 mContext.enforceCallingOrSelfPermission( 12580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12581 } 12582 } 12583 12584 int user = UserHandle.getCallingUserId(); 12585 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12586 scheduleWritePackageRestrictionsLocked(user); 12587 } 12588 } 12589 } 12590 12591 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12592 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12593 ArrayList<PreferredActivity> removed = null; 12594 boolean changed = false; 12595 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12596 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12597 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12598 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12599 continue; 12600 } 12601 Iterator<PreferredActivity> it = pir.filterIterator(); 12602 while (it.hasNext()) { 12603 PreferredActivity pa = it.next(); 12604 // Mark entry for removal only if it matches the package name 12605 // and the entry is of type "always". 12606 if (packageName == null || 12607 (pa.mPref.mComponent.getPackageName().equals(packageName) 12608 && pa.mPref.mAlways)) { 12609 if (removed == null) { 12610 removed = new ArrayList<PreferredActivity>(); 12611 } 12612 removed.add(pa); 12613 } 12614 } 12615 if (removed != null) { 12616 for (int j=0; j<removed.size(); j++) { 12617 PreferredActivity pa = removed.get(j); 12618 pir.removeFilter(pa); 12619 } 12620 changed = true; 12621 } 12622 } 12623 return changed; 12624 } 12625 12626 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12627 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12628 if (userId == UserHandle.USER_ALL) { 12629 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12630 for (int oneUserId : sUserManager.getUserIds()) { 12631 scheduleWritePackageRestrictionsLocked(oneUserId); 12632 } 12633 } else { 12634 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12635 scheduleWritePackageRestrictionsLocked(userId); 12636 } 12637 } 12638 12639 @Override 12640 public void resetPreferredActivities(int userId) { 12641 /* TODO: Actually use userId. Why is it being passed in? */ 12642 mContext.enforceCallingOrSelfPermission( 12643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12644 // writer 12645 synchronized (mPackages) { 12646 int user = UserHandle.getCallingUserId(); 12647 clearPackagePreferredActivitiesLPw(null, user); 12648 mSettings.readDefaultPreferredAppsLPw(this, user); 12649 scheduleWritePackageRestrictionsLocked(user); 12650 } 12651 } 12652 12653 @Override 12654 public int getPreferredActivities(List<IntentFilter> outFilters, 12655 List<ComponentName> outActivities, String packageName) { 12656 12657 int num = 0; 12658 final int userId = UserHandle.getCallingUserId(); 12659 // reader 12660 synchronized (mPackages) { 12661 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12662 if (pir != null) { 12663 final Iterator<PreferredActivity> it = pir.filterIterator(); 12664 while (it.hasNext()) { 12665 final PreferredActivity pa = it.next(); 12666 if (packageName == null 12667 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12668 && pa.mPref.mAlways)) { 12669 if (outFilters != null) { 12670 outFilters.add(new IntentFilter(pa)); 12671 } 12672 if (outActivities != null) { 12673 outActivities.add(pa.mPref.mComponent); 12674 } 12675 } 12676 } 12677 } 12678 } 12679 12680 return num; 12681 } 12682 12683 @Override 12684 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12685 int userId) { 12686 int callingUid = Binder.getCallingUid(); 12687 if (callingUid != Process.SYSTEM_UID) { 12688 throw new SecurityException( 12689 "addPersistentPreferredActivity can only be run by the system"); 12690 } 12691 if (filter.countActions() == 0) { 12692 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12693 return; 12694 } 12695 synchronized (mPackages) { 12696 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12697 " :"); 12698 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12699 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12700 new PersistentPreferredActivity(filter, activity)); 12701 scheduleWritePackageRestrictionsLocked(userId); 12702 } 12703 } 12704 12705 @Override 12706 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12707 int callingUid = Binder.getCallingUid(); 12708 if (callingUid != Process.SYSTEM_UID) { 12709 throw new SecurityException( 12710 "clearPackagePersistentPreferredActivities can only be run by the system"); 12711 } 12712 ArrayList<PersistentPreferredActivity> removed = null; 12713 boolean changed = false; 12714 synchronized (mPackages) { 12715 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12716 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12717 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12718 .valueAt(i); 12719 if (userId != thisUserId) { 12720 continue; 12721 } 12722 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12723 while (it.hasNext()) { 12724 PersistentPreferredActivity ppa = it.next(); 12725 // Mark entry for removal only if it matches the package name. 12726 if (ppa.mComponent.getPackageName().equals(packageName)) { 12727 if (removed == null) { 12728 removed = new ArrayList<PersistentPreferredActivity>(); 12729 } 12730 removed.add(ppa); 12731 } 12732 } 12733 if (removed != null) { 12734 for (int j=0; j<removed.size(); j++) { 12735 PersistentPreferredActivity ppa = removed.get(j); 12736 ppir.removeFilter(ppa); 12737 } 12738 changed = true; 12739 } 12740 } 12741 12742 if (changed) { 12743 scheduleWritePackageRestrictionsLocked(userId); 12744 } 12745 } 12746 } 12747 12748 /** 12749 * Non-Binder method, support for the backup/restore mechanism: write the 12750 * full set of preferred activities in its canonical XML format. Returns true 12751 * on success; false otherwise. 12752 */ 12753 @Override 12754 public byte[] getPreferredActivityBackup(int userId) { 12755 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12756 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12757 } 12758 12759 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12760 try { 12761 final XmlSerializer serializer = new FastXmlSerializer(); 12762 serializer.setOutput(dataStream, "utf-8"); 12763 serializer.startDocument(null, true); 12764 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12765 12766 synchronized (mPackages) { 12767 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12768 } 12769 12770 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12771 serializer.endDocument(); 12772 serializer.flush(); 12773 } catch (Exception e) { 12774 if (DEBUG_BACKUP) { 12775 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12776 } 12777 return null; 12778 } 12779 12780 return dataStream.toByteArray(); 12781 } 12782 12783 @Override 12784 public void restorePreferredActivities(byte[] backup, int userId) { 12785 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12786 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12787 } 12788 12789 try { 12790 final XmlPullParser parser = Xml.newPullParser(); 12791 parser.setInput(new ByteArrayInputStream(backup), null); 12792 12793 int type; 12794 while ((type = parser.next()) != XmlPullParser.START_TAG 12795 && type != XmlPullParser.END_DOCUMENT) { 12796 } 12797 if (type != XmlPullParser.START_TAG) { 12798 // oops didn't find a start tag?! 12799 if (DEBUG_BACKUP) { 12800 Slog.e(TAG, "Didn't find start tag during restore"); 12801 } 12802 return; 12803 } 12804 12805 // this is supposed to be TAG_PREFERRED_BACKUP 12806 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12807 if (DEBUG_BACKUP) { 12808 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12809 } 12810 return; 12811 } 12812 12813 // skip interfering stuff, then we're aligned with the backing implementation 12814 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12815 synchronized (mPackages) { 12816 mSettings.readPreferredActivitiesLPw(parser, userId); 12817 } 12818 } catch (Exception e) { 12819 if (DEBUG_BACKUP) { 12820 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12821 } 12822 } 12823 } 12824 12825 @Override 12826 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12827 int sourceUserId, int targetUserId, int flags) { 12828 mContext.enforceCallingOrSelfPermission( 12829 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12830 int callingUid = Binder.getCallingUid(); 12831 enforceOwnerRights(ownerPackage, callingUid); 12832 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12833 if (intentFilter.countActions() == 0) { 12834 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12835 return; 12836 } 12837 synchronized (mPackages) { 12838 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12839 ownerPackage, targetUserId, flags); 12840 CrossProfileIntentResolver resolver = 12841 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12842 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12843 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12844 if (existing != null) { 12845 int size = existing.size(); 12846 for (int i = 0; i < size; i++) { 12847 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12848 return; 12849 } 12850 } 12851 } 12852 resolver.addFilter(newFilter); 12853 scheduleWritePackageRestrictionsLocked(sourceUserId); 12854 } 12855 } 12856 12857 @Override 12858 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12859 mContext.enforceCallingOrSelfPermission( 12860 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12861 int callingUid = Binder.getCallingUid(); 12862 enforceOwnerRights(ownerPackage, callingUid); 12863 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12864 synchronized (mPackages) { 12865 CrossProfileIntentResolver resolver = 12866 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12867 ArraySet<CrossProfileIntentFilter> set = 12868 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12869 for (CrossProfileIntentFilter filter : set) { 12870 if (filter.getOwnerPackage().equals(ownerPackage)) { 12871 resolver.removeFilter(filter); 12872 } 12873 } 12874 scheduleWritePackageRestrictionsLocked(sourceUserId); 12875 } 12876 } 12877 12878 // Enforcing that callingUid is owning pkg on userId 12879 private void enforceOwnerRights(String pkg, int callingUid) { 12880 // The system owns everything. 12881 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12882 return; 12883 } 12884 int callingUserId = UserHandle.getUserId(callingUid); 12885 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12886 if (pi == null) { 12887 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12888 + callingUserId); 12889 } 12890 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12891 throw new SecurityException("Calling uid " + callingUid 12892 + " does not own package " + pkg); 12893 } 12894 } 12895 12896 @Override 12897 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12898 Intent intent = new Intent(Intent.ACTION_MAIN); 12899 intent.addCategory(Intent.CATEGORY_HOME); 12900 12901 final int callingUserId = UserHandle.getCallingUserId(); 12902 List<ResolveInfo> list = queryIntentActivities(intent, null, 12903 PackageManager.GET_META_DATA, callingUserId); 12904 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12905 true, false, false, callingUserId); 12906 12907 allHomeCandidates.clear(); 12908 if (list != null) { 12909 for (ResolveInfo ri : list) { 12910 allHomeCandidates.add(ri); 12911 } 12912 } 12913 return (preferred == null || preferred.activityInfo == null) 12914 ? null 12915 : new ComponentName(preferred.activityInfo.packageName, 12916 preferred.activityInfo.name); 12917 } 12918 12919 @Override 12920 public void setApplicationEnabledSetting(String appPackageName, 12921 int newState, int flags, int userId, String callingPackage) { 12922 if (!sUserManager.exists(userId)) return; 12923 if (callingPackage == null) { 12924 callingPackage = Integer.toString(Binder.getCallingUid()); 12925 } 12926 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12927 } 12928 12929 @Override 12930 public void setComponentEnabledSetting(ComponentName componentName, 12931 int newState, int flags, int userId) { 12932 if (!sUserManager.exists(userId)) return; 12933 setEnabledSetting(componentName.getPackageName(), 12934 componentName.getClassName(), newState, flags, userId, null); 12935 } 12936 12937 private void setEnabledSetting(final String packageName, String className, int newState, 12938 final int flags, int userId, String callingPackage) { 12939 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12940 || newState == COMPONENT_ENABLED_STATE_ENABLED 12941 || newState == COMPONENT_ENABLED_STATE_DISABLED 12942 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12943 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12944 throw new IllegalArgumentException("Invalid new component state: " 12945 + newState); 12946 } 12947 PackageSetting pkgSetting; 12948 final int uid = Binder.getCallingUid(); 12949 final int permission = mContext.checkCallingOrSelfPermission( 12950 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12951 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12952 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12953 boolean sendNow = false; 12954 boolean isApp = (className == null); 12955 String componentName = isApp ? packageName : className; 12956 int packageUid = -1; 12957 ArrayList<String> components; 12958 12959 // writer 12960 synchronized (mPackages) { 12961 pkgSetting = mSettings.mPackages.get(packageName); 12962 if (pkgSetting == null) { 12963 if (className == null) { 12964 throw new IllegalArgumentException( 12965 "Unknown package: " + packageName); 12966 } 12967 throw new IllegalArgumentException( 12968 "Unknown component: " + packageName 12969 + "/" + className); 12970 } 12971 // Allow root and verify that userId is not being specified by a different user 12972 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12973 throw new SecurityException( 12974 "Permission Denial: attempt to change component state from pid=" 12975 + Binder.getCallingPid() 12976 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12977 } 12978 if (className == null) { 12979 // We're dealing with an application/package level state change 12980 if (pkgSetting.getEnabled(userId) == newState) { 12981 // Nothing to do 12982 return; 12983 } 12984 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12985 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12986 // Don't care about who enables an app. 12987 callingPackage = null; 12988 } 12989 pkgSetting.setEnabled(newState, userId, callingPackage); 12990 // pkgSetting.pkg.mSetEnabled = newState; 12991 } else { 12992 // We're dealing with a component level state change 12993 // First, verify that this is a valid class name. 12994 PackageParser.Package pkg = pkgSetting.pkg; 12995 if (pkg == null || !pkg.hasComponentClassName(className)) { 12996 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12997 throw new IllegalArgumentException("Component class " + className 12998 + " does not exist in " + packageName); 12999 } else { 13000 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13001 + className + " does not exist in " + packageName); 13002 } 13003 } 13004 switch (newState) { 13005 case COMPONENT_ENABLED_STATE_ENABLED: 13006 if (!pkgSetting.enableComponentLPw(className, userId)) { 13007 return; 13008 } 13009 break; 13010 case COMPONENT_ENABLED_STATE_DISABLED: 13011 if (!pkgSetting.disableComponentLPw(className, userId)) { 13012 return; 13013 } 13014 break; 13015 case COMPONENT_ENABLED_STATE_DEFAULT: 13016 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13017 return; 13018 } 13019 break; 13020 default: 13021 Slog.e(TAG, "Invalid new component state: " + newState); 13022 return; 13023 } 13024 } 13025 scheduleWritePackageRestrictionsLocked(userId); 13026 components = mPendingBroadcasts.get(userId, packageName); 13027 final boolean newPackage = components == null; 13028 if (newPackage) { 13029 components = new ArrayList<String>(); 13030 } 13031 if (!components.contains(componentName)) { 13032 components.add(componentName); 13033 } 13034 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13035 sendNow = true; 13036 // Purge entry from pending broadcast list if another one exists already 13037 // since we are sending one right away. 13038 mPendingBroadcasts.remove(userId, packageName); 13039 } else { 13040 if (newPackage) { 13041 mPendingBroadcasts.put(userId, packageName, components); 13042 } 13043 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13044 // Schedule a message 13045 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13046 } 13047 } 13048 } 13049 13050 long callingId = Binder.clearCallingIdentity(); 13051 try { 13052 if (sendNow) { 13053 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13054 sendPackageChangedBroadcast(packageName, 13055 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13056 } 13057 } finally { 13058 Binder.restoreCallingIdentity(callingId); 13059 } 13060 } 13061 13062 private void sendPackageChangedBroadcast(String packageName, 13063 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13064 if (DEBUG_INSTALL) 13065 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13066 + componentNames); 13067 Bundle extras = new Bundle(4); 13068 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13069 String nameList[] = new String[componentNames.size()]; 13070 componentNames.toArray(nameList); 13071 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13072 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13073 extras.putInt(Intent.EXTRA_UID, packageUid); 13074 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13075 new int[] {UserHandle.getUserId(packageUid)}); 13076 } 13077 13078 @Override 13079 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13080 if (!sUserManager.exists(userId)) return; 13081 final int uid = Binder.getCallingUid(); 13082 final int permission = mContext.checkCallingOrSelfPermission( 13083 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13084 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13085 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13086 // writer 13087 synchronized (mPackages) { 13088 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13089 uid, userId)) { 13090 scheduleWritePackageRestrictionsLocked(userId); 13091 } 13092 } 13093 } 13094 13095 @Override 13096 public String getInstallerPackageName(String packageName) { 13097 // reader 13098 synchronized (mPackages) { 13099 return mSettings.getInstallerPackageNameLPr(packageName); 13100 } 13101 } 13102 13103 @Override 13104 public int getApplicationEnabledSetting(String packageName, int userId) { 13105 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13106 int uid = Binder.getCallingUid(); 13107 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13108 // reader 13109 synchronized (mPackages) { 13110 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13111 } 13112 } 13113 13114 @Override 13115 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13116 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13117 int uid = Binder.getCallingUid(); 13118 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13119 // reader 13120 synchronized (mPackages) { 13121 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13122 } 13123 } 13124 13125 @Override 13126 public void enterSafeMode() { 13127 enforceSystemOrRoot("Only the system can request entering safe mode"); 13128 13129 if (!mSystemReady) { 13130 mSafeMode = true; 13131 } 13132 } 13133 13134 @Override 13135 public void systemReady() { 13136 mSystemReady = true; 13137 13138 // Read the compatibilty setting when the system is ready. 13139 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13140 mContext.getContentResolver(), 13141 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13142 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13143 if (DEBUG_SETTINGS) { 13144 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13145 } 13146 13147 synchronized (mPackages) { 13148 // Verify that all of the preferred activity components actually 13149 // exist. It is possible for applications to be updated and at 13150 // that point remove a previously declared activity component that 13151 // had been set as a preferred activity. We try to clean this up 13152 // the next time we encounter that preferred activity, but it is 13153 // possible for the user flow to never be able to return to that 13154 // situation so here we do a sanity check to make sure we haven't 13155 // left any junk around. 13156 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13157 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13158 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13159 removed.clear(); 13160 for (PreferredActivity pa : pir.filterSet()) { 13161 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13162 removed.add(pa); 13163 } 13164 } 13165 if (removed.size() > 0) { 13166 for (int r=0; r<removed.size(); r++) { 13167 PreferredActivity pa = removed.get(r); 13168 Slog.w(TAG, "Removing dangling preferred activity: " 13169 + pa.mPref.mComponent); 13170 pir.removeFilter(pa); 13171 } 13172 mSettings.writePackageRestrictionsLPr( 13173 mSettings.mPreferredActivities.keyAt(i)); 13174 } 13175 } 13176 } 13177 sUserManager.systemReady(); 13178 13179 // Kick off any messages waiting for system ready 13180 if (mPostSystemReadyMessages != null) { 13181 for (Message msg : mPostSystemReadyMessages) { 13182 msg.sendToTarget(); 13183 } 13184 mPostSystemReadyMessages = null; 13185 } 13186 13187 // Watch for external volumes that come and go over time 13188 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13189 storage.registerListener(mStorageListener); 13190 13191 mInstallerService.systemReady(); 13192 } 13193 13194 @Override 13195 public boolean isSafeMode() { 13196 return mSafeMode; 13197 } 13198 13199 @Override 13200 public boolean hasSystemUidErrors() { 13201 return mHasSystemUidErrors; 13202 } 13203 13204 static String arrayToString(int[] array) { 13205 StringBuffer buf = new StringBuffer(128); 13206 buf.append('['); 13207 if (array != null) { 13208 for (int i=0; i<array.length; i++) { 13209 if (i > 0) buf.append(", "); 13210 buf.append(array[i]); 13211 } 13212 } 13213 buf.append(']'); 13214 return buf.toString(); 13215 } 13216 13217 static class DumpState { 13218 public static final int DUMP_LIBS = 1 << 0; 13219 public static final int DUMP_FEATURES = 1 << 1; 13220 public static final int DUMP_RESOLVERS = 1 << 2; 13221 public static final int DUMP_PERMISSIONS = 1 << 3; 13222 public static final int DUMP_PACKAGES = 1 << 4; 13223 public static final int DUMP_SHARED_USERS = 1 << 5; 13224 public static final int DUMP_MESSAGES = 1 << 6; 13225 public static final int DUMP_PROVIDERS = 1 << 7; 13226 public static final int DUMP_VERIFIERS = 1 << 8; 13227 public static final int DUMP_PREFERRED = 1 << 9; 13228 public static final int DUMP_PREFERRED_XML = 1 << 10; 13229 public static final int DUMP_KEYSETS = 1 << 11; 13230 public static final int DUMP_VERSION = 1 << 12; 13231 public static final int DUMP_INSTALLS = 1 << 13; 13232 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13233 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13234 13235 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13236 13237 private int mTypes; 13238 13239 private int mOptions; 13240 13241 private boolean mTitlePrinted; 13242 13243 private SharedUserSetting mSharedUser; 13244 13245 public boolean isDumping(int type) { 13246 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13247 return true; 13248 } 13249 13250 return (mTypes & type) != 0; 13251 } 13252 13253 public void setDump(int type) { 13254 mTypes |= type; 13255 } 13256 13257 public boolean isOptionEnabled(int option) { 13258 return (mOptions & option) != 0; 13259 } 13260 13261 public void setOptionEnabled(int option) { 13262 mOptions |= option; 13263 } 13264 13265 public boolean onTitlePrinted() { 13266 final boolean printed = mTitlePrinted; 13267 mTitlePrinted = true; 13268 return printed; 13269 } 13270 13271 public boolean getTitlePrinted() { 13272 return mTitlePrinted; 13273 } 13274 13275 public void setTitlePrinted(boolean enabled) { 13276 mTitlePrinted = enabled; 13277 } 13278 13279 public SharedUserSetting getSharedUser() { 13280 return mSharedUser; 13281 } 13282 13283 public void setSharedUser(SharedUserSetting user) { 13284 mSharedUser = user; 13285 } 13286 } 13287 13288 @Override 13289 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13290 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13291 != PackageManager.PERMISSION_GRANTED) { 13292 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13293 + Binder.getCallingPid() 13294 + ", uid=" + Binder.getCallingUid() 13295 + " without permission " 13296 + android.Manifest.permission.DUMP); 13297 return; 13298 } 13299 13300 DumpState dumpState = new DumpState(); 13301 boolean fullPreferred = false; 13302 boolean checkin = false; 13303 13304 String packageName = null; 13305 13306 int opti = 0; 13307 while (opti < args.length) { 13308 String opt = args[opti]; 13309 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13310 break; 13311 } 13312 opti++; 13313 13314 if ("-a".equals(opt)) { 13315 // Right now we only know how to print all. 13316 } else if ("-h".equals(opt)) { 13317 pw.println("Package manager dump options:"); 13318 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13319 pw.println(" --checkin: dump for a checkin"); 13320 pw.println(" -f: print details of intent filters"); 13321 pw.println(" -h: print this help"); 13322 pw.println(" cmd may be one of:"); 13323 pw.println(" l[ibraries]: list known shared libraries"); 13324 pw.println(" f[ibraries]: list device features"); 13325 pw.println(" k[eysets]: print known keysets"); 13326 pw.println(" r[esolvers]: dump intent resolvers"); 13327 pw.println(" perm[issions]: dump permissions"); 13328 pw.println(" pref[erred]: print preferred package settings"); 13329 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13330 pw.println(" prov[iders]: dump content providers"); 13331 pw.println(" p[ackages]: dump installed packages"); 13332 pw.println(" s[hared-users]: dump shared user IDs"); 13333 pw.println(" m[essages]: print collected runtime messages"); 13334 pw.println(" v[erifiers]: print package verifier info"); 13335 pw.println(" version: print database version info"); 13336 pw.println(" write: write current settings now"); 13337 pw.println(" <package.name>: info about given package"); 13338 pw.println(" installs: details about install sessions"); 13339 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13340 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13341 return; 13342 } else if ("--checkin".equals(opt)) { 13343 checkin = true; 13344 } else if ("-f".equals(opt)) { 13345 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13346 } else { 13347 pw.println("Unknown argument: " + opt + "; use -h for help"); 13348 } 13349 } 13350 13351 // Is the caller requesting to dump a particular piece of data? 13352 if (opti < args.length) { 13353 String cmd = args[opti]; 13354 opti++; 13355 // Is this a package name? 13356 if ("android".equals(cmd) || cmd.contains(".")) { 13357 packageName = cmd; 13358 // When dumping a single package, we always dump all of its 13359 // filter information since the amount of data will be reasonable. 13360 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13361 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13362 dumpState.setDump(DumpState.DUMP_LIBS); 13363 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13364 dumpState.setDump(DumpState.DUMP_FEATURES); 13365 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13366 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13367 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13368 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13369 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13370 dumpState.setDump(DumpState.DUMP_PREFERRED); 13371 } else if ("preferred-xml".equals(cmd)) { 13372 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13373 if (opti < args.length && "--full".equals(args[opti])) { 13374 fullPreferred = true; 13375 opti++; 13376 } 13377 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13378 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13379 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13380 dumpState.setDump(DumpState.DUMP_PACKAGES); 13381 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13382 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13383 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13384 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13385 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13386 dumpState.setDump(DumpState.DUMP_MESSAGES); 13387 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13388 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13389 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13390 || "intent-filter-verifiers".equals(cmd)) { 13391 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13392 } else if ("version".equals(cmd)) { 13393 dumpState.setDump(DumpState.DUMP_VERSION); 13394 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13395 dumpState.setDump(DumpState.DUMP_KEYSETS); 13396 } else if ("installs".equals(cmd)) { 13397 dumpState.setDump(DumpState.DUMP_INSTALLS); 13398 } else if ("write".equals(cmd)) { 13399 synchronized (mPackages) { 13400 mSettings.writeLPr(); 13401 pw.println("Settings written."); 13402 return; 13403 } 13404 } 13405 } 13406 13407 if (checkin) { 13408 pw.println("vers,1"); 13409 } 13410 13411 // reader 13412 synchronized (mPackages) { 13413 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13414 if (!checkin) { 13415 if (dumpState.onTitlePrinted()) 13416 pw.println(); 13417 pw.println("Database versions:"); 13418 pw.print(" SDK Version:"); 13419 pw.print(" internal="); 13420 pw.print(mSettings.mInternalSdkPlatform); 13421 pw.print(" external="); 13422 pw.println(mSettings.mExternalSdkPlatform); 13423 pw.print(" DB Version:"); 13424 pw.print(" internal="); 13425 pw.print(mSettings.mInternalDatabaseVersion); 13426 pw.print(" external="); 13427 pw.println(mSettings.mExternalDatabaseVersion); 13428 } 13429 } 13430 13431 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13432 if (!checkin) { 13433 if (dumpState.onTitlePrinted()) 13434 pw.println(); 13435 pw.println("Verifiers:"); 13436 pw.print(" Required: "); 13437 pw.print(mRequiredVerifierPackage); 13438 pw.print(" (uid="); 13439 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13440 pw.println(")"); 13441 } else if (mRequiredVerifierPackage != null) { 13442 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13443 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13444 } 13445 } 13446 13447 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13448 packageName == null) { 13449 if (mIntentFilterVerifierComponent != null) { 13450 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13451 if (!checkin) { 13452 if (dumpState.onTitlePrinted()) 13453 pw.println(); 13454 pw.println("Intent Filter Verifier:"); 13455 pw.print(" Using: "); 13456 pw.print(verifierPackageName); 13457 pw.print(" (uid="); 13458 pw.print(getPackageUid(verifierPackageName, 0)); 13459 pw.println(")"); 13460 } else if (verifierPackageName != null) { 13461 pw.print("ifv,"); pw.print(verifierPackageName); 13462 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13463 } 13464 } else { 13465 pw.println(); 13466 pw.println("No Intent Filter Verifier available!"); 13467 } 13468 } 13469 13470 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13471 boolean printedHeader = false; 13472 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13473 while (it.hasNext()) { 13474 String name = it.next(); 13475 SharedLibraryEntry ent = mSharedLibraries.get(name); 13476 if (!checkin) { 13477 if (!printedHeader) { 13478 if (dumpState.onTitlePrinted()) 13479 pw.println(); 13480 pw.println("Libraries:"); 13481 printedHeader = true; 13482 } 13483 pw.print(" "); 13484 } else { 13485 pw.print("lib,"); 13486 } 13487 pw.print(name); 13488 if (!checkin) { 13489 pw.print(" -> "); 13490 } 13491 if (ent.path != null) { 13492 if (!checkin) { 13493 pw.print("(jar) "); 13494 pw.print(ent.path); 13495 } else { 13496 pw.print(",jar,"); 13497 pw.print(ent.path); 13498 } 13499 } else { 13500 if (!checkin) { 13501 pw.print("(apk) "); 13502 pw.print(ent.apk); 13503 } else { 13504 pw.print(",apk,"); 13505 pw.print(ent.apk); 13506 } 13507 } 13508 pw.println(); 13509 } 13510 } 13511 13512 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13513 if (dumpState.onTitlePrinted()) 13514 pw.println(); 13515 if (!checkin) { 13516 pw.println("Features:"); 13517 } 13518 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13519 while (it.hasNext()) { 13520 String name = it.next(); 13521 if (!checkin) { 13522 pw.print(" "); 13523 } else { 13524 pw.print("feat,"); 13525 } 13526 pw.println(name); 13527 } 13528 } 13529 13530 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13531 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13532 : "Activity Resolver Table:", " ", packageName, 13533 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13534 dumpState.setTitlePrinted(true); 13535 } 13536 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13537 : "Receiver Resolver Table:", " ", packageName, 13538 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13539 dumpState.setTitlePrinted(true); 13540 } 13541 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13542 : "Service Resolver Table:", " ", packageName, 13543 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13544 dumpState.setTitlePrinted(true); 13545 } 13546 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13547 : "Provider Resolver Table:", " ", packageName, 13548 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13549 dumpState.setTitlePrinted(true); 13550 } 13551 } 13552 13553 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13554 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13555 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13556 int user = mSettings.mPreferredActivities.keyAt(i); 13557 if (pir.dump(pw, 13558 dumpState.getTitlePrinted() 13559 ? "\nPreferred Activities User " + user + ":" 13560 : "Preferred Activities User " + user + ":", " ", 13561 packageName, true, false)) { 13562 dumpState.setTitlePrinted(true); 13563 } 13564 } 13565 } 13566 13567 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13568 pw.flush(); 13569 FileOutputStream fout = new FileOutputStream(fd); 13570 BufferedOutputStream str = new BufferedOutputStream(fout); 13571 XmlSerializer serializer = new FastXmlSerializer(); 13572 try { 13573 serializer.setOutput(str, "utf-8"); 13574 serializer.startDocument(null, true); 13575 serializer.setFeature( 13576 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13577 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13578 serializer.endDocument(); 13579 serializer.flush(); 13580 } catch (IllegalArgumentException e) { 13581 pw.println("Failed writing: " + e); 13582 } catch (IllegalStateException e) { 13583 pw.println("Failed writing: " + e); 13584 } catch (IOException e) { 13585 pw.println("Failed writing: " + e); 13586 } 13587 } 13588 13589 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13590 pw.println(); 13591 int count = mSettings.mPackages.size(); 13592 if (count == 0) { 13593 pw.println("No domain preferred apps!"); 13594 pw.println(); 13595 } else { 13596 final String prefix = " "; 13597 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13598 if (allPackageSettings.size() == 0) { 13599 pw.println("No domain preferred apps!"); 13600 pw.println(); 13601 } else { 13602 pw.println("Domain preferred apps status:"); 13603 pw.println(); 13604 count = 0; 13605 for (PackageSetting ps : allPackageSettings) { 13606 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13607 if (ivi == null || ivi.getPackageName() == null) continue; 13608 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13609 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13610 pw.println(prefix + "Status: " + ivi.getStatusString()); 13611 pw.println(); 13612 count++; 13613 } 13614 if (count == 0) { 13615 pw.println(prefix + "No domain preferred app status!"); 13616 pw.println(); 13617 } 13618 for (int userId : sUserManager.getUserIds()) { 13619 pw.println("Domain preferred apps for User " + userId + ":"); 13620 pw.println(); 13621 count = 0; 13622 for (PackageSetting ps : allPackageSettings) { 13623 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13624 if (ivi == null || ivi.getPackageName() == null) { 13625 continue; 13626 } 13627 final int status = ps.getDomainVerificationStatusForUser(userId); 13628 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13629 continue; 13630 } 13631 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13632 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13633 String statusStr = IntentFilterVerificationInfo. 13634 getStatusStringFromValue(status); 13635 pw.println(prefix + "Status: " + statusStr); 13636 pw.println(); 13637 count++; 13638 } 13639 if (count == 0) { 13640 pw.println(prefix + "No domain preferred apps!"); 13641 pw.println(); 13642 } 13643 } 13644 } 13645 } 13646 } 13647 13648 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13649 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13650 if (packageName == null) { 13651 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13652 if (iperm == 0) { 13653 if (dumpState.onTitlePrinted()) 13654 pw.println(); 13655 pw.println("AppOp Permissions:"); 13656 } 13657 pw.print(" AppOp Permission "); 13658 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13659 pw.println(":"); 13660 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13661 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13662 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13663 } 13664 } 13665 } 13666 } 13667 13668 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13669 boolean printedSomething = false; 13670 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13671 if (packageName != null && !packageName.equals(p.info.packageName)) { 13672 continue; 13673 } 13674 if (!printedSomething) { 13675 if (dumpState.onTitlePrinted()) 13676 pw.println(); 13677 pw.println("Registered ContentProviders:"); 13678 printedSomething = true; 13679 } 13680 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13681 pw.print(" "); pw.println(p.toString()); 13682 } 13683 printedSomething = false; 13684 for (Map.Entry<String, PackageParser.Provider> entry : 13685 mProvidersByAuthority.entrySet()) { 13686 PackageParser.Provider p = entry.getValue(); 13687 if (packageName != null && !packageName.equals(p.info.packageName)) { 13688 continue; 13689 } 13690 if (!printedSomething) { 13691 if (dumpState.onTitlePrinted()) 13692 pw.println(); 13693 pw.println("ContentProvider Authorities:"); 13694 printedSomething = true; 13695 } 13696 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13697 pw.print(" "); pw.println(p.toString()); 13698 if (p.info != null && p.info.applicationInfo != null) { 13699 final String appInfo = p.info.applicationInfo.toString(); 13700 pw.print(" applicationInfo="); pw.println(appInfo); 13701 } 13702 } 13703 } 13704 13705 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13706 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13707 } 13708 13709 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13710 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13711 } 13712 13713 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13714 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13715 } 13716 13717 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13718 // XXX should handle packageName != null by dumping only install data that 13719 // the given package is involved with. 13720 if (dumpState.onTitlePrinted()) pw.println(); 13721 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13722 } 13723 13724 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13725 if (dumpState.onTitlePrinted()) pw.println(); 13726 mSettings.dumpReadMessagesLPr(pw, dumpState); 13727 13728 pw.println(); 13729 pw.println("Package warning messages:"); 13730 BufferedReader in = null; 13731 String line = null; 13732 try { 13733 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13734 while ((line = in.readLine()) != null) { 13735 if (line.contains("ignored: updated version")) continue; 13736 pw.println(line); 13737 } 13738 } catch (IOException ignored) { 13739 } finally { 13740 IoUtils.closeQuietly(in); 13741 } 13742 } 13743 13744 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13745 BufferedReader in = null; 13746 String line = null; 13747 try { 13748 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13749 while ((line = in.readLine()) != null) { 13750 if (line.contains("ignored: updated version")) continue; 13751 pw.print("msg,"); 13752 pw.println(line); 13753 } 13754 } catch (IOException ignored) { 13755 } finally { 13756 IoUtils.closeQuietly(in); 13757 } 13758 } 13759 } 13760 } 13761 13762 // ------- apps on sdcard specific code ------- 13763 static final boolean DEBUG_SD_INSTALL = false; 13764 13765 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13766 13767 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13768 13769 private boolean mMediaMounted = false; 13770 13771 static String getEncryptKey() { 13772 try { 13773 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13774 SD_ENCRYPTION_KEYSTORE_NAME); 13775 if (sdEncKey == null) { 13776 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13777 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13778 if (sdEncKey == null) { 13779 Slog.e(TAG, "Failed to create encryption keys"); 13780 return null; 13781 } 13782 } 13783 return sdEncKey; 13784 } catch (NoSuchAlgorithmException nsae) { 13785 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13786 return null; 13787 } catch (IOException ioe) { 13788 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13789 return null; 13790 } 13791 } 13792 13793 /* 13794 * Update media status on PackageManager. 13795 */ 13796 @Override 13797 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13798 int callingUid = Binder.getCallingUid(); 13799 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13800 throw new SecurityException("Media status can only be updated by the system"); 13801 } 13802 // reader; this apparently protects mMediaMounted, but should probably 13803 // be a different lock in that case. 13804 synchronized (mPackages) { 13805 Log.i(TAG, "Updating external media status from " 13806 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13807 + (mediaStatus ? "mounted" : "unmounted")); 13808 if (DEBUG_SD_INSTALL) 13809 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13810 + ", mMediaMounted=" + mMediaMounted); 13811 if (mediaStatus == mMediaMounted) { 13812 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13813 : 0, -1); 13814 mHandler.sendMessage(msg); 13815 return; 13816 } 13817 mMediaMounted = mediaStatus; 13818 } 13819 // Queue up an async operation since the package installation may take a 13820 // little while. 13821 mHandler.post(new Runnable() { 13822 public void run() { 13823 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13824 } 13825 }); 13826 } 13827 13828 /** 13829 * Called by MountService when the initial ASECs to scan are available. 13830 * Should block until all the ASEC containers are finished being scanned. 13831 */ 13832 public void scanAvailableAsecs() { 13833 updateExternalMediaStatusInner(true, false, false); 13834 if (mShouldRestoreconData) { 13835 SELinuxMMAC.setRestoreconDone(); 13836 mShouldRestoreconData = false; 13837 } 13838 } 13839 13840 /* 13841 * Collect information of applications on external media, map them against 13842 * existing containers and update information based on current mount status. 13843 * Please note that we always have to report status if reportStatus has been 13844 * set to true especially when unloading packages. 13845 */ 13846 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13847 boolean externalStorage) { 13848 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13849 int[] uidArr = EmptyArray.INT; 13850 13851 final String[] list = PackageHelper.getSecureContainerList(); 13852 if (ArrayUtils.isEmpty(list)) { 13853 Log.i(TAG, "No secure containers found"); 13854 } else { 13855 // Process list of secure containers and categorize them 13856 // as active or stale based on their package internal state. 13857 13858 // reader 13859 synchronized (mPackages) { 13860 for (String cid : list) { 13861 // Leave stages untouched for now; installer service owns them 13862 if (PackageInstallerService.isStageName(cid)) continue; 13863 13864 if (DEBUG_SD_INSTALL) 13865 Log.i(TAG, "Processing container " + cid); 13866 String pkgName = getAsecPackageName(cid); 13867 if (pkgName == null) { 13868 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13869 continue; 13870 } 13871 if (DEBUG_SD_INSTALL) 13872 Log.i(TAG, "Looking for pkg : " + pkgName); 13873 13874 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13875 if (ps == null) { 13876 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13877 continue; 13878 } 13879 13880 /* 13881 * Skip packages that are not external if we're unmounting 13882 * external storage. 13883 */ 13884 if (externalStorage && !isMounted && !isExternal(ps)) { 13885 continue; 13886 } 13887 13888 final AsecInstallArgs args = new AsecInstallArgs(cid, 13889 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13890 // The package status is changed only if the code path 13891 // matches between settings and the container id. 13892 if (ps.codePathString != null 13893 && ps.codePathString.startsWith(args.getCodePath())) { 13894 if (DEBUG_SD_INSTALL) { 13895 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13896 + " at code path: " + ps.codePathString); 13897 } 13898 13899 // We do have a valid package installed on sdcard 13900 processCids.put(args, ps.codePathString); 13901 final int uid = ps.appId; 13902 if (uid != -1) { 13903 uidArr = ArrayUtils.appendInt(uidArr, uid); 13904 } 13905 } else { 13906 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13907 + ps.codePathString); 13908 } 13909 } 13910 } 13911 13912 Arrays.sort(uidArr); 13913 } 13914 13915 // Process packages with valid entries. 13916 if (isMounted) { 13917 if (DEBUG_SD_INSTALL) 13918 Log.i(TAG, "Loading packages"); 13919 loadMediaPackages(processCids, uidArr); 13920 startCleaningPackages(); 13921 mInstallerService.onSecureContainersAvailable(); 13922 } else { 13923 if (DEBUG_SD_INSTALL) 13924 Log.i(TAG, "Unloading packages"); 13925 unloadMediaPackages(processCids, uidArr, reportStatus); 13926 } 13927 } 13928 13929 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13930 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13931 final int size = infos.size(); 13932 final String[] packageNames = new String[size]; 13933 final int[] packageUids = new int[size]; 13934 for (int i = 0; i < size; i++) { 13935 final ApplicationInfo info = infos.get(i); 13936 packageNames[i] = info.packageName; 13937 packageUids[i] = info.uid; 13938 } 13939 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13940 finishedReceiver); 13941 } 13942 13943 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13944 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13945 sendResourcesChangedBroadcast(mediaStatus, replacing, 13946 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13947 } 13948 13949 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13950 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13951 int size = pkgList.length; 13952 if (size > 0) { 13953 // Send broadcasts here 13954 Bundle extras = new Bundle(); 13955 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13956 if (uidArr != null) { 13957 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13958 } 13959 if (replacing) { 13960 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13961 } 13962 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13963 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13964 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13965 } 13966 } 13967 13968 /* 13969 * Look at potentially valid container ids from processCids If package 13970 * information doesn't match the one on record or package scanning fails, 13971 * the cid is added to list of removeCids. We currently don't delete stale 13972 * containers. 13973 */ 13974 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13975 ArrayList<String> pkgList = new ArrayList<String>(); 13976 Set<AsecInstallArgs> keys = processCids.keySet(); 13977 13978 for (AsecInstallArgs args : keys) { 13979 String codePath = processCids.get(args); 13980 if (DEBUG_SD_INSTALL) 13981 Log.i(TAG, "Loading container : " + args.cid); 13982 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13983 try { 13984 // Make sure there are no container errors first. 13985 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13986 Slog.e(TAG, "Failed to mount cid : " + args.cid 13987 + " when installing from sdcard"); 13988 continue; 13989 } 13990 // Check code path here. 13991 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13992 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13993 + " does not match one in settings " + codePath); 13994 continue; 13995 } 13996 // Parse package 13997 int parseFlags = mDefParseFlags; 13998 if (args.isExternalAsec()) { 13999 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14000 } 14001 if (args.isFwdLocked()) { 14002 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14003 } 14004 14005 synchronized (mInstallLock) { 14006 PackageParser.Package pkg = null; 14007 try { 14008 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14009 } catch (PackageManagerException e) { 14010 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14011 } 14012 // Scan the package 14013 if (pkg != null) { 14014 /* 14015 * TODO why is the lock being held? doPostInstall is 14016 * called in other places without the lock. This needs 14017 * to be straightened out. 14018 */ 14019 // writer 14020 synchronized (mPackages) { 14021 retCode = PackageManager.INSTALL_SUCCEEDED; 14022 pkgList.add(pkg.packageName); 14023 // Post process args 14024 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14025 pkg.applicationInfo.uid); 14026 } 14027 } else { 14028 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14029 } 14030 } 14031 14032 } finally { 14033 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14034 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14035 } 14036 } 14037 } 14038 // writer 14039 synchronized (mPackages) { 14040 // If the platform SDK has changed since the last time we booted, 14041 // we need to re-grant app permission to catch any new ones that 14042 // appear. This is really a hack, and means that apps can in some 14043 // cases get permissions that the user didn't initially explicitly 14044 // allow... it would be nice to have some better way to handle 14045 // this situation. 14046 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14047 if (regrantPermissions) 14048 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14049 + mSdkVersion + "; regranting permissions for external storage"); 14050 mSettings.mExternalSdkPlatform = mSdkVersion; 14051 14052 // Make sure group IDs have been assigned, and any permission 14053 // changes in other apps are accounted for 14054 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14055 | (regrantPermissions 14056 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14057 : 0)); 14058 14059 mSettings.updateExternalDatabaseVersion(); 14060 14061 // can downgrade to reader 14062 // Persist settings 14063 mSettings.writeLPr(); 14064 } 14065 // Send a broadcast to let everyone know we are done processing 14066 if (pkgList.size() > 0) { 14067 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14068 } 14069 } 14070 14071 /* 14072 * Utility method to unload a list of specified containers 14073 */ 14074 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14075 // Just unmount all valid containers. 14076 for (AsecInstallArgs arg : cidArgs) { 14077 synchronized (mInstallLock) { 14078 arg.doPostDeleteLI(false); 14079 } 14080 } 14081 } 14082 14083 /* 14084 * Unload packages mounted on external media. This involves deleting package 14085 * data from internal structures, sending broadcasts about diabled packages, 14086 * gc'ing to free up references, unmounting all secure containers 14087 * corresponding to packages on external media, and posting a 14088 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14089 * that we always have to post this message if status has been requested no 14090 * matter what. 14091 */ 14092 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14093 final boolean reportStatus) { 14094 if (DEBUG_SD_INSTALL) 14095 Log.i(TAG, "unloading media packages"); 14096 ArrayList<String> pkgList = new ArrayList<String>(); 14097 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14098 final Set<AsecInstallArgs> keys = processCids.keySet(); 14099 for (AsecInstallArgs args : keys) { 14100 String pkgName = args.getPackageName(); 14101 if (DEBUG_SD_INSTALL) 14102 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14103 // Delete package internally 14104 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14105 synchronized (mInstallLock) { 14106 boolean res = deletePackageLI(pkgName, null, false, null, null, 14107 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14108 if (res) { 14109 pkgList.add(pkgName); 14110 } else { 14111 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14112 failedList.add(args); 14113 } 14114 } 14115 } 14116 14117 // reader 14118 synchronized (mPackages) { 14119 // We didn't update the settings after removing each package; 14120 // write them now for all packages. 14121 mSettings.writeLPr(); 14122 } 14123 14124 // We have to absolutely send UPDATED_MEDIA_STATUS only 14125 // after confirming that all the receivers processed the ordered 14126 // broadcast when packages get disabled, force a gc to clean things up. 14127 // and unload all the containers. 14128 if (pkgList.size() > 0) { 14129 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14130 new IIntentReceiver.Stub() { 14131 public void performReceive(Intent intent, int resultCode, String data, 14132 Bundle extras, boolean ordered, boolean sticky, 14133 int sendingUser) throws RemoteException { 14134 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14135 reportStatus ? 1 : 0, 1, keys); 14136 mHandler.sendMessage(msg); 14137 } 14138 }); 14139 } else { 14140 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14141 keys); 14142 mHandler.sendMessage(msg); 14143 } 14144 } 14145 14146 private void loadPrivatePackages(VolumeInfo vol) { 14147 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14148 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14149 synchronized (mPackages) { 14150 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14151 for (PackageSetting ps : packages) { 14152 synchronized (mInstallLock) { 14153 final PackageParser.Package pkg; 14154 try { 14155 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14156 loaded.add(pkg.applicationInfo); 14157 } catch (PackageManagerException e) { 14158 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14159 } 14160 } 14161 } 14162 14163 // TODO: regrant any permissions that changed based since original install 14164 14165 mSettings.writeLPr(); 14166 } 14167 14168 Slog.d(TAG, "Loaded packages " + loaded); 14169 sendResourcesChangedBroadcast(true, false, loaded, null); 14170 } 14171 14172 private void unloadPrivatePackages(VolumeInfo vol) { 14173 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14174 synchronized (mPackages) { 14175 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14176 for (PackageSetting ps : packages) { 14177 if (ps.pkg == null) continue; 14178 synchronized (mInstallLock) { 14179 final ApplicationInfo info = ps.pkg.applicationInfo; 14180 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14181 if (deletePackageLI(ps.name, null, false, null, null, 14182 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14183 unloaded.add(info); 14184 } else { 14185 Slog.w(TAG, "Failed to unload " + ps.codePath); 14186 } 14187 } 14188 } 14189 14190 mSettings.writeLPr(); 14191 } 14192 14193 Slog.d(TAG, "Unloaded packages " + unloaded); 14194 sendResourcesChangedBroadcast(false, false, unloaded, null); 14195 } 14196 14197 @Override 14198 public int movePackage(final String packageName, final String volumeUuid) { 14199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14200 14201 final int moveId = mNextMoveId.getAndIncrement(); 14202 try { 14203 movePackageInternal(packageName, volumeUuid, moveId); 14204 } catch (PackageManagerException e) { 14205 Slog.d(TAG, "Failed to move " + packageName, e); 14206 mMoveCallbacks.notifyStatusChanged(moveId, null, 14207 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14208 } 14209 return moveId; 14210 } 14211 14212 private void movePackageInternal(final String packageName, final String volumeUuid, 14213 final int moveId) throws PackageManagerException { 14214 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14215 final PackageManager pm = mContext.getPackageManager(); 14216 14217 final boolean currentAsec; 14218 final String currentVolumeUuid; 14219 final File codeFile; 14220 final String installerPackageName; 14221 final String packageAbiOverride; 14222 final int appId; 14223 final String seinfo; 14224 final String moveTitle; 14225 14226 // reader 14227 synchronized (mPackages) { 14228 final PackageParser.Package pkg = mPackages.get(packageName); 14229 final PackageSetting ps = mSettings.mPackages.get(packageName); 14230 if (pkg == null || ps == null) { 14231 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14232 } 14233 14234 if (pkg.applicationInfo.isSystemApp()) { 14235 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14236 "Cannot move system application"); 14237 } else if (pkg.mOperationPending) { 14238 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14239 "Attempt to move package which has pending operations"); 14240 } 14241 14242 // TODO: yell if already in desired location 14243 14244 pkg.mOperationPending = true; 14245 14246 currentAsec = pkg.applicationInfo.isForwardLocked() 14247 || pkg.applicationInfo.isExternalAsec(); 14248 currentVolumeUuid = ps.volumeUuid; 14249 codeFile = new File(pkg.codePath); 14250 installerPackageName = ps.installerPackageName; 14251 packageAbiOverride = ps.cpuAbiOverrideString; 14252 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14253 seinfo = pkg.applicationInfo.seinfo; 14254 moveTitle = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14255 } 14256 14257 int installFlags; 14258 final boolean moveData; 14259 14260 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14261 installFlags = INSTALL_INTERNAL; 14262 moveData = !currentAsec; 14263 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14264 installFlags = INSTALL_EXTERNAL; 14265 moveData = false; 14266 } else { 14267 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14268 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14269 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14270 || !volume.isMountedWritable()) { 14271 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14272 "Move location not mounted private volume"); 14273 } 14274 14275 Preconditions.checkState(!currentAsec); 14276 14277 installFlags = INSTALL_INTERNAL; 14278 moveData = true; 14279 } 14280 14281 Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid); 14282 mMoveCallbacks.notifyStatusChanged(moveId, moveTitle, 10); 14283 14284 if (moveData) { 14285 synchronized (mInstallLock) { 14286 // TODO: split this into separate copy and delete operations 14287 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14288 seinfo) != 0) { 14289 synchronized (mPackages) { 14290 final PackageParser.Package pkg = mPackages.get(packageName); 14291 if (pkg != null) { 14292 pkg.mOperationPending = false; 14293 } 14294 } 14295 14296 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14297 "Failed to move private data"); 14298 } 14299 } 14300 } 14301 14302 mMoveCallbacks.notifyStatusChanged(moveId, moveTitle, 50); 14303 14304 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14305 @Override 14306 public void onUserActionRequired(Intent intent) throws RemoteException { 14307 throw new IllegalStateException(); 14308 } 14309 14310 @Override 14311 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14312 Bundle extras) throws RemoteException { 14313 Slog.d(TAG, "Install result for move: " 14314 + PackageManager.installStatusToString(returnCode, msg)); 14315 14316 // We usually have a new package now after the install, but if 14317 // we failed we need to clear the pending flag on the original 14318 // package object. 14319 synchronized (mPackages) { 14320 final PackageParser.Package pkg = mPackages.get(packageName); 14321 if (pkg != null) { 14322 pkg.mOperationPending = false; 14323 } 14324 } 14325 14326 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14327 switch (status) { 14328 case PackageInstaller.STATUS_SUCCESS: 14329 mMoveCallbacks.notifyStatusChanged(moveId, moveTitle, 14330 PackageManager.MOVE_SUCCEEDED); 14331 break; 14332 case PackageInstaller.STATUS_FAILURE_STORAGE: 14333 mMoveCallbacks.notifyStatusChanged(moveId, moveTitle, 14334 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14335 break; 14336 default: 14337 mMoveCallbacks.notifyStatusChanged(moveId, moveTitle, 14338 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14339 break; 14340 } 14341 } 14342 }; 14343 14344 // Treat a move like reinstalling an existing app, which ensures that we 14345 // process everythign uniformly, like unpacking native libraries. 14346 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14347 14348 final Message msg = mHandler.obtainMessage(INIT_COPY); 14349 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14350 msg.obj = new InstallParams(origin, installObserver, installFlags, 14351 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14352 mHandler.sendMessage(msg); 14353 } 14354 14355 @Override 14356 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14357 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14358 14359 final int realMoveId = mNextMoveId.getAndIncrement(); 14360 final String realTitle = null; 14361 14362 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14363 @Override 14364 public void onStatusChanged(int moveId, String title, int status, long estMillis) { 14365 mMoveCallbacks.notifyStatusChanged(realMoveId, realTitle, status, estMillis); 14366 } 14367 }; 14368 14369 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14370 storage.setPrimaryStorageUuid(volumeUuid, callback); 14371 return realMoveId; 14372 } 14373 14374 @Override 14375 public int getMoveStatus(int moveId) { 14376 mContext.enforceCallingOrSelfPermission( 14377 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14378 return mMoveCallbacks.mLastStatus.get(moveId); 14379 } 14380 14381 @Override 14382 public void registerMoveCallback(IPackageMoveObserver callback) { 14383 mContext.enforceCallingOrSelfPermission( 14384 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14385 mMoveCallbacks.register(callback); 14386 } 14387 14388 @Override 14389 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14390 mContext.enforceCallingOrSelfPermission( 14391 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14392 mMoveCallbacks.unregister(callback); 14393 } 14394 14395 @Override 14396 public boolean setInstallLocation(int loc) { 14397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14398 null); 14399 if (getInstallLocation() == loc) { 14400 return true; 14401 } 14402 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14403 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14404 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14405 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14406 return true; 14407 } 14408 return false; 14409 } 14410 14411 @Override 14412 public int getInstallLocation() { 14413 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14414 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14415 PackageHelper.APP_INSTALL_AUTO); 14416 } 14417 14418 /** Called by UserManagerService */ 14419 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14420 mDirtyUsers.remove(userHandle); 14421 mSettings.removeUserLPw(userHandle); 14422 mPendingBroadcasts.remove(userHandle); 14423 if (mInstaller != null) { 14424 // Technically, we shouldn't be doing this with the package lock 14425 // held. However, this is very rare, and there is already so much 14426 // other disk I/O going on, that we'll let it slide for now. 14427 final StorageManager storage = StorageManager.from(mContext); 14428 final List<VolumeInfo> vols = storage.getVolumes(); 14429 for (VolumeInfo vol : vols) { 14430 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14431 final String volumeUuid = vol.getFsUuid(); 14432 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14433 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14434 } 14435 } 14436 } 14437 mUserNeedsBadging.delete(userHandle); 14438 removeUnusedPackagesLILPw(userManager, userHandle); 14439 } 14440 14441 /** 14442 * We're removing userHandle and would like to remove any downloaded packages 14443 * that are no longer in use by any other user. 14444 * @param userHandle the user being removed 14445 */ 14446 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14447 final boolean DEBUG_CLEAN_APKS = false; 14448 int [] users = userManager.getUserIdsLPr(); 14449 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14450 while (psit.hasNext()) { 14451 PackageSetting ps = psit.next(); 14452 if (ps.pkg == null) { 14453 continue; 14454 } 14455 final String packageName = ps.pkg.packageName; 14456 // Skip over if system app 14457 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14458 continue; 14459 } 14460 if (DEBUG_CLEAN_APKS) { 14461 Slog.i(TAG, "Checking package " + packageName); 14462 } 14463 boolean keep = false; 14464 for (int i = 0; i < users.length; i++) { 14465 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14466 keep = true; 14467 if (DEBUG_CLEAN_APKS) { 14468 Slog.i(TAG, " Keeping package " + packageName + " for user " 14469 + users[i]); 14470 } 14471 break; 14472 } 14473 } 14474 if (!keep) { 14475 if (DEBUG_CLEAN_APKS) { 14476 Slog.i(TAG, " Removing package " + packageName); 14477 } 14478 mHandler.post(new Runnable() { 14479 public void run() { 14480 deletePackageX(packageName, userHandle, 0); 14481 } //end run 14482 }); 14483 } 14484 } 14485 } 14486 14487 /** Called by UserManagerService */ 14488 void createNewUserLILPw(int userHandle, File path) { 14489 if (mInstaller != null) { 14490 mInstaller.createUserConfig(userHandle); 14491 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14492 } 14493 } 14494 14495 void newUserCreatedLILPw(int userHandle) { 14496 // Adding a user requires updating runtime permissions for system apps. 14497 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14498 } 14499 14500 @Override 14501 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14502 mContext.enforceCallingOrSelfPermission( 14503 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14504 "Only package verification agents can read the verifier device identity"); 14505 14506 synchronized (mPackages) { 14507 return mSettings.getVerifierDeviceIdentityLPw(); 14508 } 14509 } 14510 14511 @Override 14512 public void setPermissionEnforced(String permission, boolean enforced) { 14513 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14514 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14515 synchronized (mPackages) { 14516 if (mSettings.mReadExternalStorageEnforced == null 14517 || mSettings.mReadExternalStorageEnforced != enforced) { 14518 mSettings.mReadExternalStorageEnforced = enforced; 14519 mSettings.writeLPr(); 14520 } 14521 } 14522 // kill any non-foreground processes so we restart them and 14523 // grant/revoke the GID. 14524 final IActivityManager am = ActivityManagerNative.getDefault(); 14525 if (am != null) { 14526 final long token = Binder.clearCallingIdentity(); 14527 try { 14528 am.killProcessesBelowForeground("setPermissionEnforcement"); 14529 } catch (RemoteException e) { 14530 } finally { 14531 Binder.restoreCallingIdentity(token); 14532 } 14533 } 14534 } else { 14535 throw new IllegalArgumentException("No selective enforcement for " + permission); 14536 } 14537 } 14538 14539 @Override 14540 @Deprecated 14541 public boolean isPermissionEnforced(String permission) { 14542 return true; 14543 } 14544 14545 @Override 14546 public boolean isStorageLow() { 14547 final long token = Binder.clearCallingIdentity(); 14548 try { 14549 final DeviceStorageMonitorInternal 14550 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14551 if (dsm != null) { 14552 return dsm.isMemoryLow(); 14553 } else { 14554 return false; 14555 } 14556 } finally { 14557 Binder.restoreCallingIdentity(token); 14558 } 14559 } 14560 14561 @Override 14562 public IPackageInstaller getPackageInstaller() { 14563 return mInstallerService; 14564 } 14565 14566 private boolean userNeedsBadging(int userId) { 14567 int index = mUserNeedsBadging.indexOfKey(userId); 14568 if (index < 0) { 14569 final UserInfo userInfo; 14570 final long token = Binder.clearCallingIdentity(); 14571 try { 14572 userInfo = sUserManager.getUserInfo(userId); 14573 } finally { 14574 Binder.restoreCallingIdentity(token); 14575 } 14576 final boolean b; 14577 if (userInfo != null && userInfo.isManagedProfile()) { 14578 b = true; 14579 } else { 14580 b = false; 14581 } 14582 mUserNeedsBadging.put(userId, b); 14583 return b; 14584 } 14585 return mUserNeedsBadging.valueAt(index); 14586 } 14587 14588 @Override 14589 public KeySet getKeySetByAlias(String packageName, String alias) { 14590 if (packageName == null || alias == null) { 14591 return null; 14592 } 14593 synchronized(mPackages) { 14594 final PackageParser.Package pkg = mPackages.get(packageName); 14595 if (pkg == null) { 14596 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14597 throw new IllegalArgumentException("Unknown package: " + packageName); 14598 } 14599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14600 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14601 } 14602 } 14603 14604 @Override 14605 public KeySet getSigningKeySet(String packageName) { 14606 if (packageName == null) { 14607 return null; 14608 } 14609 synchronized(mPackages) { 14610 final PackageParser.Package pkg = mPackages.get(packageName); 14611 if (pkg == null) { 14612 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14613 throw new IllegalArgumentException("Unknown package: " + packageName); 14614 } 14615 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14616 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14617 throw new SecurityException("May not access signing KeySet of other apps."); 14618 } 14619 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14620 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14621 } 14622 } 14623 14624 @Override 14625 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14626 if (packageName == null || ks == null) { 14627 return false; 14628 } 14629 synchronized(mPackages) { 14630 final PackageParser.Package pkg = mPackages.get(packageName); 14631 if (pkg == null) { 14632 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14633 throw new IllegalArgumentException("Unknown package: " + packageName); 14634 } 14635 IBinder ksh = ks.getToken(); 14636 if (ksh instanceof KeySetHandle) { 14637 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14638 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14639 } 14640 return false; 14641 } 14642 } 14643 14644 @Override 14645 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14646 if (packageName == null || ks == null) { 14647 return false; 14648 } 14649 synchronized(mPackages) { 14650 final PackageParser.Package pkg = mPackages.get(packageName); 14651 if (pkg == null) { 14652 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14653 throw new IllegalArgumentException("Unknown package: " + packageName); 14654 } 14655 IBinder ksh = ks.getToken(); 14656 if (ksh instanceof KeySetHandle) { 14657 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14658 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14659 } 14660 return false; 14661 } 14662 } 14663 14664 public void getUsageStatsIfNoPackageUsageInfo() { 14665 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14666 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14667 if (usm == null) { 14668 throw new IllegalStateException("UsageStatsManager must be initialized"); 14669 } 14670 long now = System.currentTimeMillis(); 14671 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14672 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14673 String packageName = entry.getKey(); 14674 PackageParser.Package pkg = mPackages.get(packageName); 14675 if (pkg == null) { 14676 continue; 14677 } 14678 UsageStats usage = entry.getValue(); 14679 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14680 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14681 } 14682 } 14683 } 14684 14685 /** 14686 * Check and throw if the given before/after packages would be considered a 14687 * downgrade. 14688 */ 14689 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14690 throws PackageManagerException { 14691 if (after.versionCode < before.mVersionCode) { 14692 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14693 "Update version code " + after.versionCode + " is older than current " 14694 + before.mVersionCode); 14695 } else if (after.versionCode == before.mVersionCode) { 14696 if (after.baseRevisionCode < before.baseRevisionCode) { 14697 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14698 "Update base revision code " + after.baseRevisionCode 14699 + " is older than current " + before.baseRevisionCode); 14700 } 14701 14702 if (!ArrayUtils.isEmpty(after.splitNames)) { 14703 for (int i = 0; i < after.splitNames.length; i++) { 14704 final String splitName = after.splitNames[i]; 14705 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14706 if (j != -1) { 14707 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14708 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14709 "Update split " + splitName + " revision code " 14710 + after.splitRevisionCodes[i] + " is older than current " 14711 + before.splitRevisionCodes[j]); 14712 } 14713 } 14714 } 14715 } 14716 } 14717 } 14718 14719 private static class MoveCallbacks extends Handler { 14720 private static final int MSG_STATUS_CHANGED = 2; 14721 14722 private final RemoteCallbackList<IPackageMoveObserver> 14723 mCallbacks = new RemoteCallbackList<>(); 14724 14725 private final SparseIntArray mLastStatus = new SparseIntArray(); 14726 14727 public MoveCallbacks(Looper looper) { 14728 super(looper); 14729 } 14730 14731 public void register(IPackageMoveObserver callback) { 14732 mCallbacks.register(callback); 14733 } 14734 14735 public void unregister(IPackageMoveObserver callback) { 14736 mCallbacks.unregister(callback); 14737 } 14738 14739 @Override 14740 public void handleMessage(Message msg) { 14741 final SomeArgs args = (SomeArgs) msg.obj; 14742 final int n = mCallbacks.beginBroadcast(); 14743 for (int i = 0; i < n; i++) { 14744 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14745 try { 14746 invokeCallback(callback, msg.what, args); 14747 } catch (RemoteException ignored) { 14748 } 14749 } 14750 mCallbacks.finishBroadcast(); 14751 args.recycle(); 14752 } 14753 14754 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14755 throws RemoteException { 14756 switch (what) { 14757 case MSG_STATUS_CHANGED: { 14758 callback.onStatusChanged(args.argi1, (String) args.arg2, args.argi3, 14759 (long) args.arg4); 14760 break; 14761 } 14762 } 14763 } 14764 14765 private void notifyStatusChanged(int moveId, String moveTitle, int status) { 14766 notifyStatusChanged(moveId, moveTitle, status, -1); 14767 } 14768 14769 private void notifyStatusChanged(int moveId, String moveTitle, int status, long estMillis) { 14770 Slog.v(TAG, "Move " + moveId + " status " + status); 14771 14772 final SomeArgs args = SomeArgs.obtain(); 14773 args.argi1 = moveId; 14774 args.arg2 = moveTitle; 14775 args.argi3 = status; 14776 args.arg4 = estMillis; 14777 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14778 14779 synchronized (mLastStatus) { 14780 mLastStatus.put(moveId, status); 14781 } 14782 } 14783 } 14784} 14785