PackageManagerService.java revision c6d1c345f41cf817bf2c07c97b97107d94296064
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_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 58import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 60import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 61 62import android.util.ArrayMap; 63 64import com.android.internal.R; 65import com.android.internal.app.IMediaContainerService; 66import com.android.internal.app.ResolverActivity; 67import com.android.internal.content.NativeLibraryHelper; 68import com.android.internal.content.PackageHelper; 69import com.android.internal.os.IParcelFileDescriptorFactory; 70import com.android.internal.util.ArrayUtils; 71import com.android.internal.util.FastPrintWriter; 72import com.android.internal.util.FastXmlSerializer; 73import com.android.internal.util.IndentingPrintWriter; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.AppGlobals; 88import android.app.IActivityManager; 89import android.app.admin.IDevicePolicyManager; 90import android.app.backup.IBackupManager; 91import android.app.usage.UsageStats; 92import android.app.usage.UsageStatsManager; 93import android.content.BroadcastReceiver; 94import android.content.ComponentName; 95import android.content.Context; 96import android.content.IIntentReceiver; 97import android.content.Intent; 98import android.content.IntentFilter; 99import android.content.IntentSender; 100import android.content.IntentSender.SendIntentException; 101import android.content.ServiceConnection; 102import android.content.pm.ActivityInfo; 103import android.content.pm.ApplicationInfo; 104import android.content.pm.FeatureInfo; 105import android.content.pm.IPackageDataObserver; 106import android.content.pm.IPackageDeleteObserver; 107import android.content.pm.IPackageDeleteObserver2; 108import android.content.pm.IPackageInstallObserver2; 109import android.content.pm.IPackageInstaller; 110import android.content.pm.IPackageManager; 111import android.content.pm.IPackageMoveObserver; 112import android.content.pm.IPackageStatsObserver; 113import android.content.pm.InstrumentationInfo; 114import android.content.pm.KeySet; 115import android.content.pm.ManifestDigest; 116import android.content.pm.PackageCleanItem; 117import android.content.pm.PackageInfo; 118import android.content.pm.PackageInfoLite; 119import android.content.pm.PackageInstaller; 120import android.content.pm.PackageManager; 121import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 122import android.content.pm.PackageParser.ActivityIntentInfo; 123import android.content.pm.PackageParser.PackageLite; 124import android.content.pm.PackageParser.PackageParserException; 125import android.content.pm.PackageParser; 126import android.content.pm.PackageStats; 127import android.content.pm.PackageUserState; 128import android.content.pm.ParceledListSlice; 129import android.content.pm.PermissionGroupInfo; 130import android.content.pm.PermissionInfo; 131import android.content.pm.ProviderInfo; 132import android.content.pm.ResolveInfo; 133import android.content.pm.ServiceInfo; 134import android.content.pm.Signature; 135import android.content.pm.UserInfo; 136import android.content.pm.VerificationParams; 137import android.content.pm.VerifierDeviceIdentity; 138import android.content.pm.VerifierInfo; 139import android.content.res.Resources; 140import android.hardware.display.DisplayManager; 141import android.net.Uri; 142import android.os.Binder; 143import android.os.Build; 144import android.os.Bundle; 145import android.os.Environment; 146import android.os.Environment.UserEnvironment; 147import android.os.storage.IMountService; 148import android.os.storage.StorageManager; 149import android.os.Debug; 150import android.os.FileUtils; 151import android.os.Handler; 152import android.os.IBinder; 153import android.os.Looper; 154import android.os.Message; 155import android.os.Parcel; 156import android.os.ParcelFileDescriptor; 157import android.os.Process; 158import android.os.RemoteException; 159import android.os.SELinux; 160import android.os.ServiceManager; 161import android.os.SystemClock; 162import android.os.SystemProperties; 163import android.os.UserHandle; 164import android.os.UserManager; 165import android.security.KeyStore; 166import android.security.SystemKeyStore; 167import android.system.ErrnoException; 168import android.system.Os; 169import android.system.StructStat; 170import android.text.TextUtils; 171import android.text.format.DateUtils; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.view.Display; 184 185import java.io.BufferedInputStream; 186import java.io.BufferedOutputStream; 187import java.io.BufferedReader; 188import java.io.File; 189import java.io.FileDescriptor; 190import java.io.FileNotFoundException; 191import java.io.FileOutputStream; 192import java.io.FileReader; 193import java.io.FilenameFilter; 194import java.io.IOException; 195import java.io.InputStream; 196import java.io.PrintWriter; 197import java.nio.charset.StandardCharsets; 198import java.security.NoSuchAlgorithmException; 199import java.security.PublicKey; 200import java.security.cert.CertificateEncodingException; 201import java.security.cert.CertificateException; 202import java.text.SimpleDateFormat; 203import java.util.ArrayList; 204import java.util.Arrays; 205import java.util.Collection; 206import java.util.Collections; 207import java.util.Comparator; 208import java.util.Date; 209import java.util.Iterator; 210import java.util.List; 211import java.util.Map; 212import java.util.Objects; 213import java.util.Set; 214import java.util.concurrent.atomic.AtomicBoolean; 215import java.util.concurrent.atomic.AtomicLong; 216 217import dalvik.system.DexFile; 218import dalvik.system.VMRuntime; 219 220import libcore.io.IoUtils; 221import libcore.util.EmptyArray; 222 223/** 224 * Keep track of all those .apks everywhere. 225 * 226 * This is very central to the platform's security; please run the unit 227 * tests whenever making modifications here: 228 * 229mmm frameworks/base/tests/AndroidTests 230adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 231adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 232 * 233 * {@hide} 234 */ 235public class PackageManagerService extends IPackageManager.Stub { 236 static final String TAG = "PackageManager"; 237 static final boolean DEBUG_SETTINGS = false; 238 static final boolean DEBUG_PREFERRED = false; 239 static final boolean DEBUG_UPGRADE = false; 240 private static final boolean DEBUG_INSTALL = false; 241 private static final boolean DEBUG_REMOVE = false; 242 private static final boolean DEBUG_BROADCASTS = false; 243 private static final boolean DEBUG_SHOW_INFO = false; 244 private static final boolean DEBUG_PACKAGE_INFO = false; 245 private static final boolean DEBUG_INTENT_MATCHING = false; 246 private static final boolean DEBUG_PACKAGE_SCANNING = false; 247 private static final boolean DEBUG_VERIFY = false; 248 private static final boolean DEBUG_DEXOPT = false; 249 private static final boolean DEBUG_ABI_SELECTION = false; 250 251 private static final boolean RUNTIME_PERMISSIONS_ENABLED = 252 SystemProperties.getInt("ro.runtime.premissions.enabled", 0) == 1; 253 254 private static final int RADIO_UID = Process.PHONE_UID; 255 private static final int LOG_UID = Process.LOG_UID; 256 private static final int NFC_UID = Process.NFC_UID; 257 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 258 private static final int SHELL_UID = Process.SHELL_UID; 259 260 // Cap the size of permission trees that 3rd party apps can define 261 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 262 263 // Suffix used during package installation when copying/moving 264 // package apks to install directory. 265 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 266 267 static final int SCAN_NO_DEX = 1<<1; 268 static final int SCAN_FORCE_DEX = 1<<2; 269 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 270 static final int SCAN_NEW_INSTALL = 1<<4; 271 static final int SCAN_NO_PATHS = 1<<5; 272 static final int SCAN_UPDATE_TIME = 1<<6; 273 static final int SCAN_DEFER_DEX = 1<<7; 274 static final int SCAN_BOOTING = 1<<8; 275 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 276 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 277 static final int SCAN_REPLACING = 1<<11; 278 279 static final int REMOVE_CHATTY = 1<<16; 280 281 /** 282 * Timeout (in milliseconds) after which the watchdog should declare that 283 * our handler thread is wedged. The usual default for such things is one 284 * minute but we sometimes do very lengthy I/O operations on this thread, 285 * such as installing multi-gigabyte applications, so ours needs to be longer. 286 */ 287 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 288 289 /** 290 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 291 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 292 * settings entry if available, otherwise we use the hardcoded default. If it's been 293 * more than this long since the last fstrim, we force one during the boot sequence. 294 * 295 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 296 * one gets run at the next available charging+idle time. This final mandatory 297 * no-fstrim check kicks in only of the other scheduling criteria is never met. 298 */ 299 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 300 301 /** 302 * Whether verification is enabled by default. 303 */ 304 private static final boolean DEFAULT_VERIFY_ENABLE = true; 305 306 /** 307 * The default maximum time to wait for the verification agent to return in 308 * milliseconds. 309 */ 310 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 311 312 /** 313 * The default response for package verification timeout. 314 * 315 * This can be either PackageManager.VERIFICATION_ALLOW or 316 * PackageManager.VERIFICATION_REJECT. 317 */ 318 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 319 320 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 321 322 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 323 DEFAULT_CONTAINER_PACKAGE, 324 "com.android.defcontainer.DefaultContainerService"); 325 326 private static final String KILL_APP_REASON_GIDS_CHANGED = 327 "permission grant or revoke changed gids"; 328 329 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 330 "permissions revoked"; 331 332 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 333 334 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 335 336 /** Permission grant: not grant the permission. */ 337 private static final int GRANT_DENIED = 1; 338 339 /** Permission grant: grant the permission as an install permission. */ 340 private static final int GRANT_INSTALL = 2; 341 342 /** Permission grant: grant the permission as a runtime permission. */ 343 private static final int GRANT_RUNTIME = 3; 344 345 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 346 private static final int GRANT_UPGRADE = 4; 347 348 final ServiceThread mHandlerThread; 349 350 final PackageHandler mHandler; 351 352 /** 353 * Messages for {@link #mHandler} that need to wait for system ready before 354 * being dispatched. 355 */ 356 private ArrayList<Message> mPostSystemReadyMessages; 357 358 final int mSdkVersion = Build.VERSION.SDK_INT; 359 360 final Context mContext; 361 final boolean mFactoryTest; 362 final boolean mOnlyCore; 363 final boolean mLazyDexOpt; 364 final long mDexOptLRUThresholdInMills; 365 final DisplayMetrics mMetrics; 366 final int mDefParseFlags; 367 final String[] mSeparateProcesses; 368 final boolean mIsUpgrade; 369 370 // This is where all application persistent data goes. 371 final File mAppDataDir; 372 373 // This is where all application persistent data goes for secondary users. 374 final File mUserAppDataDir; 375 376 /** The location for ASEC container files on internal storage. */ 377 final String mAsecInternalPath; 378 379 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 380 // LOCK HELD. Can be called with mInstallLock held. 381 final Installer mInstaller; 382 383 /** Directory where installed third-party apps stored */ 384 final File mAppInstallDir; 385 386 /** 387 * Directory to which applications installed internally have their 388 * 32 bit native libraries copied. 389 */ 390 private File mAppLib32InstallDir; 391 392 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 393 // apps. 394 final File mDrmAppPrivateInstallDir; 395 396 // ---------------------------------------------------------------- 397 398 // Lock for state used when installing and doing other long running 399 // operations. Methods that must be called with this lock held have 400 // the suffix "LI". 401 final Object mInstallLock = new Object(); 402 403 // ---------------------------------------------------------------- 404 405 // Keys are String (package name), values are Package. This also serves 406 // as the lock for the global state. Methods that must be called with 407 // this lock held have the prefix "LP". 408 final ArrayMap<String, PackageParser.Package> mPackages = 409 new ArrayMap<String, PackageParser.Package>(); 410 411 // Tracks available target package names -> overlay package paths. 412 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 413 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 414 415 final Settings mSettings; 416 boolean mRestoredSettings; 417 418 // System configuration read by SystemConfig. 419 final int[] mGlobalGids; 420 final SparseArray<ArraySet<String>> mSystemPermissions; 421 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 422 423 // If mac_permissions.xml was found for seinfo labeling. 424 boolean mFoundPolicyFile; 425 426 // If a recursive restorecon of /data/data/<pkg> is needed. 427 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 428 429 public static final class SharedLibraryEntry { 430 public final String path; 431 public final String apk; 432 433 SharedLibraryEntry(String _path, String _apk) { 434 path = _path; 435 apk = _apk; 436 } 437 } 438 439 // Currently known shared libraries. 440 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 441 new ArrayMap<String, SharedLibraryEntry>(); 442 443 // All available activities, for your resolving pleasure. 444 final ActivityIntentResolver mActivities = 445 new ActivityIntentResolver(); 446 447 // All available receivers, for your resolving pleasure. 448 final ActivityIntentResolver mReceivers = 449 new ActivityIntentResolver(); 450 451 // All available services, for your resolving pleasure. 452 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 453 454 // All available providers, for your resolving pleasure. 455 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 456 457 // Mapping from provider base names (first directory in content URI codePath) 458 // to the provider information. 459 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 460 new ArrayMap<String, PackageParser.Provider>(); 461 462 // Mapping from instrumentation class names to info about them. 463 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 464 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 465 466 // Mapping from permission names to info about them. 467 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 468 new ArrayMap<String, PackageParser.PermissionGroup>(); 469 470 // Packages whose data we have transfered into another package, thus 471 // should no longer exist. 472 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 473 474 // Broadcast actions that are only available to the system. 475 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 476 477 /** List of packages waiting for verification. */ 478 final SparseArray<PackageVerificationState> mPendingVerification 479 = new SparseArray<PackageVerificationState>(); 480 481 /** Set of packages associated with each app op permission. */ 482 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 483 484 final PackageInstallerService mInstallerService; 485 486 private final PackageDexOptimizer mPackageDexOptimizer; 487 // Cache of users who need badging. 488 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 489 490 /** Token for keys in mPendingVerification. */ 491 private int mPendingVerificationToken = 0; 492 493 volatile boolean mSystemReady; 494 volatile boolean mSafeMode; 495 volatile boolean mHasSystemUidErrors; 496 497 ApplicationInfo mAndroidApplication; 498 final ActivityInfo mResolveActivity = new ActivityInfo(); 499 final ResolveInfo mResolveInfo = new ResolveInfo(); 500 ComponentName mResolveComponentName; 501 PackageParser.Package mPlatformPackage; 502 ComponentName mCustomResolverComponentName; 503 504 boolean mResolverReplaced = false; 505 506 // Set of pending broadcasts for aggregating enable/disable of components. 507 static class PendingPackageBroadcasts { 508 // for each user id, a map of <package name -> components within that package> 509 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 510 511 public PendingPackageBroadcasts() { 512 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 513 } 514 515 public ArrayList<String> get(int userId, String packageName) { 516 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 517 return packages.get(packageName); 518 } 519 520 public void put(int userId, String packageName, ArrayList<String> components) { 521 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 522 packages.put(packageName, components); 523 } 524 525 public void remove(int userId, String packageName) { 526 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 527 if (packages != null) { 528 packages.remove(packageName); 529 } 530 } 531 532 public void remove(int userId) { 533 mUidMap.remove(userId); 534 } 535 536 public int userIdCount() { 537 return mUidMap.size(); 538 } 539 540 public int userIdAt(int n) { 541 return mUidMap.keyAt(n); 542 } 543 544 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 545 return mUidMap.get(userId); 546 } 547 548 public int size() { 549 // total number of pending broadcast entries across all userIds 550 int num = 0; 551 for (int i = 0; i< mUidMap.size(); i++) { 552 num += mUidMap.valueAt(i).size(); 553 } 554 return num; 555 } 556 557 public void clear() { 558 mUidMap.clear(); 559 } 560 561 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 562 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 563 if (map == null) { 564 map = new ArrayMap<String, ArrayList<String>>(); 565 mUidMap.put(userId, map); 566 } 567 return map; 568 } 569 } 570 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 571 572 // Service Connection to remote media container service to copy 573 // package uri's from external media onto secure containers 574 // or internal storage. 575 private IMediaContainerService mContainerService = null; 576 577 static final int SEND_PENDING_BROADCAST = 1; 578 static final int MCS_BOUND = 3; 579 static final int END_COPY = 4; 580 static final int INIT_COPY = 5; 581 static final int MCS_UNBIND = 6; 582 static final int START_CLEANING_PACKAGE = 7; 583 static final int FIND_INSTALL_LOC = 8; 584 static final int POST_INSTALL = 9; 585 static final int MCS_RECONNECT = 10; 586 static final int MCS_GIVE_UP = 11; 587 static final int UPDATED_MEDIA_STATUS = 12; 588 static final int WRITE_SETTINGS = 13; 589 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 590 static final int PACKAGE_VERIFIED = 15; 591 static final int CHECK_PENDING_VERIFICATION = 16; 592 593 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 594 595 // Delay time in millisecs 596 static final int BROADCAST_DELAY = 10 * 1000; 597 598 static UserManagerService sUserManager; 599 600 // Stores a list of users whose package restrictions file needs to be updated 601 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 602 603 final private DefaultContainerConnection mDefContainerConn = 604 new DefaultContainerConnection(); 605 class DefaultContainerConnection implements ServiceConnection { 606 public void onServiceConnected(ComponentName name, IBinder service) { 607 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 608 IMediaContainerService imcs = 609 IMediaContainerService.Stub.asInterface(service); 610 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 611 } 612 613 public void onServiceDisconnected(ComponentName name) { 614 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 615 } 616 }; 617 618 // Recordkeeping of restore-after-install operations that are currently in flight 619 // between the Package Manager and the Backup Manager 620 class PostInstallData { 621 public InstallArgs args; 622 public PackageInstalledInfo res; 623 624 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 625 args = _a; 626 res = _r; 627 } 628 }; 629 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 630 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 631 632 private final String mRequiredVerifierPackage; 633 634 private final PackageUsage mPackageUsage = new PackageUsage(); 635 636 private class PackageUsage { 637 private static final int WRITE_INTERVAL 638 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 639 640 private final Object mFileLock = new Object(); 641 private final AtomicLong mLastWritten = new AtomicLong(0); 642 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 643 644 private boolean mIsHistoricalPackageUsageAvailable = true; 645 646 boolean isHistoricalPackageUsageAvailable() { 647 return mIsHistoricalPackageUsageAvailable; 648 } 649 650 void write(boolean force) { 651 if (force) { 652 writeInternal(); 653 return; 654 } 655 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 656 && !DEBUG_DEXOPT) { 657 return; 658 } 659 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 660 new Thread("PackageUsage_DiskWriter") { 661 @Override 662 public void run() { 663 try { 664 writeInternal(); 665 } finally { 666 mBackgroundWriteRunning.set(false); 667 } 668 } 669 }.start(); 670 } 671 } 672 673 private void writeInternal() { 674 synchronized (mPackages) { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 FileOutputStream f = null; 678 try { 679 f = file.startWrite(); 680 BufferedOutputStream out = new BufferedOutputStream(f); 681 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 682 StringBuilder sb = new StringBuilder(); 683 for (PackageParser.Package pkg : mPackages.values()) { 684 if (pkg.mLastPackageUsageTimeInMills == 0) { 685 continue; 686 } 687 sb.setLength(0); 688 sb.append(pkg.packageName); 689 sb.append(' '); 690 sb.append((long)pkg.mLastPackageUsageTimeInMills); 691 sb.append('\n'); 692 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 693 } 694 out.flush(); 695 file.finishWrite(f); 696 } catch (IOException e) { 697 if (f != null) { 698 file.failWrite(f); 699 } 700 Log.e(TAG, "Failed to write package usage times", e); 701 } 702 } 703 } 704 mLastWritten.set(SystemClock.elapsedRealtime()); 705 } 706 707 void readLP() { 708 synchronized (mFileLock) { 709 AtomicFile file = getFile(); 710 BufferedInputStream in = null; 711 try { 712 in = new BufferedInputStream(file.openRead()); 713 StringBuffer sb = new StringBuffer(); 714 while (true) { 715 String packageName = readToken(in, sb, ' '); 716 if (packageName == null) { 717 break; 718 } 719 String timeInMillisString = readToken(in, sb, '\n'); 720 if (timeInMillisString == null) { 721 throw new IOException("Failed to find last usage time for package " 722 + packageName); 723 } 724 PackageParser.Package pkg = mPackages.get(packageName); 725 if (pkg == null) { 726 continue; 727 } 728 long timeInMillis; 729 try { 730 timeInMillis = Long.parseLong(timeInMillisString.toString()); 731 } catch (NumberFormatException e) { 732 throw new IOException("Failed to parse " + timeInMillisString 733 + " as a long.", e); 734 } 735 pkg.mLastPackageUsageTimeInMills = timeInMillis; 736 } 737 } catch (FileNotFoundException expected) { 738 mIsHistoricalPackageUsageAvailable = false; 739 } catch (IOException e) { 740 Log.w(TAG, "Failed to read package usage times", e); 741 } finally { 742 IoUtils.closeQuietly(in); 743 } 744 } 745 mLastWritten.set(SystemClock.elapsedRealtime()); 746 } 747 748 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 749 throws IOException { 750 sb.setLength(0); 751 while (true) { 752 int ch = in.read(); 753 if (ch == -1) { 754 if (sb.length() == 0) { 755 return null; 756 } 757 throw new IOException("Unexpected EOF"); 758 } 759 if (ch == endOfToken) { 760 return sb.toString(); 761 } 762 sb.append((char)ch); 763 } 764 } 765 766 private AtomicFile getFile() { 767 File dataDir = Environment.getDataDirectory(); 768 File systemDir = new File(dataDir, "system"); 769 File fname = new File(systemDir, "package-usage.list"); 770 return new AtomicFile(fname); 771 } 772 } 773 774 class PackageHandler extends Handler { 775 private boolean mBound = false; 776 final ArrayList<HandlerParams> mPendingInstalls = 777 new ArrayList<HandlerParams>(); 778 779 private boolean connectToService() { 780 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 781 " DefaultContainerService"); 782 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 783 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 784 if (mContext.bindServiceAsUser(service, mDefContainerConn, 785 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 786 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 787 mBound = true; 788 return true; 789 } 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 return false; 792 } 793 794 private void disconnectService() { 795 mContainerService = null; 796 mBound = false; 797 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 798 mContext.unbindService(mDefContainerConn); 799 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 800 } 801 802 PackageHandler(Looper looper) { 803 super(looper); 804 } 805 806 public void handleMessage(Message msg) { 807 try { 808 doHandleMessage(msg); 809 } finally { 810 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 811 } 812 } 813 814 void doHandleMessage(Message msg) { 815 switch (msg.what) { 816 case INIT_COPY: { 817 HandlerParams params = (HandlerParams) msg.obj; 818 int idx = mPendingInstalls.size(); 819 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 820 // If a bind was already initiated we dont really 821 // need to do anything. The pending install 822 // will be processed later on. 823 if (!mBound) { 824 // If this is the only one pending we might 825 // have to bind to the service again. 826 if (!connectToService()) { 827 Slog.e(TAG, "Failed to bind to media container service"); 828 params.serviceError(); 829 return; 830 } else { 831 // Once we bind to the service, the first 832 // pending request will be processed. 833 mPendingInstalls.add(idx, params); 834 } 835 } else { 836 mPendingInstalls.add(idx, params); 837 // Already bound to the service. Just make 838 // sure we trigger off processing the first request. 839 if (idx == 0) { 840 mHandler.sendEmptyMessage(MCS_BOUND); 841 } 842 } 843 break; 844 } 845 case MCS_BOUND: { 846 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 847 if (msg.obj != null) { 848 mContainerService = (IMediaContainerService) msg.obj; 849 } 850 if (mContainerService == null) { 851 // Something seriously wrong. Bail out 852 Slog.e(TAG, "Cannot bind to media container service"); 853 for (HandlerParams params : mPendingInstalls) { 854 // Indicate service bind error 855 params.serviceError(); 856 } 857 mPendingInstalls.clear(); 858 } else if (mPendingInstalls.size() > 0) { 859 HandlerParams params = mPendingInstalls.get(0); 860 if (params != null) { 861 if (params.startCopy()) { 862 // We are done... look for more work or to 863 // go idle. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Checking for more work or unbind..."); 866 // Delete pending install 867 if (mPendingInstalls.size() > 0) { 868 mPendingInstalls.remove(0); 869 } 870 if (mPendingInstalls.size() == 0) { 871 if (mBound) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, 873 "Posting delayed MCS_UNBIND"); 874 removeMessages(MCS_UNBIND); 875 Message ubmsg = obtainMessage(MCS_UNBIND); 876 // Unbind after a little delay, to avoid 877 // continual thrashing. 878 sendMessageDelayed(ubmsg, 10000); 879 } 880 } else { 881 // There are more pending requests in queue. 882 // Just post MCS_BOUND message to trigger processing 883 // of next pending install. 884 if (DEBUG_SD_INSTALL) Log.i(TAG, 885 "Posting MCS_BOUND for next work"); 886 mHandler.sendEmptyMessage(MCS_BOUND); 887 } 888 } 889 } 890 } else { 891 // Should never happen ideally. 892 Slog.w(TAG, "Empty queue"); 893 } 894 break; 895 } 896 case MCS_RECONNECT: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 898 if (mPendingInstalls.size() > 0) { 899 if (mBound) { 900 disconnectService(); 901 } 902 if (!connectToService()) { 903 Slog.e(TAG, "Failed to bind to media container service"); 904 for (HandlerParams params : mPendingInstalls) { 905 // Indicate service bind error 906 params.serviceError(); 907 } 908 mPendingInstalls.clear(); 909 } 910 } 911 break; 912 } 913 case MCS_UNBIND: { 914 // If there is no actual work left, then time to unbind. 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 916 917 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 918 if (mBound) { 919 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 920 921 disconnectService(); 922 } 923 } else if (mPendingInstalls.size() > 0) { 924 // There are more pending requests in queue. 925 // Just post MCS_BOUND message to trigger processing 926 // of next pending install. 927 mHandler.sendEmptyMessage(MCS_BOUND); 928 } 929 930 break; 931 } 932 case MCS_GIVE_UP: { 933 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 934 mPendingInstalls.remove(0); 935 break; 936 } 937 case SEND_PENDING_BROADCAST: { 938 String packages[]; 939 ArrayList<String> components[]; 940 int size = 0; 941 int uids[]; 942 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 943 synchronized (mPackages) { 944 if (mPendingBroadcasts == null) { 945 return; 946 } 947 size = mPendingBroadcasts.size(); 948 if (size <= 0) { 949 // Nothing to be done. Just return 950 return; 951 } 952 packages = new String[size]; 953 components = new ArrayList[size]; 954 uids = new int[size]; 955 int i = 0; // filling out the above arrays 956 957 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 958 int packageUserId = mPendingBroadcasts.userIdAt(n); 959 Iterator<Map.Entry<String, ArrayList<String>>> it 960 = mPendingBroadcasts.packagesForUserId(packageUserId) 961 .entrySet().iterator(); 962 while (it.hasNext() && i < size) { 963 Map.Entry<String, ArrayList<String>> ent = it.next(); 964 packages[i] = ent.getKey(); 965 components[i] = ent.getValue(); 966 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 967 uids[i] = (ps != null) 968 ? UserHandle.getUid(packageUserId, ps.appId) 969 : -1; 970 i++; 971 } 972 } 973 size = i; 974 mPendingBroadcasts.clear(); 975 } 976 // Send broadcasts 977 for (int i = 0; i < size; i++) { 978 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 break; 982 } 983 case START_CLEANING_PACKAGE: { 984 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 985 final String packageName = (String)msg.obj; 986 final int userId = msg.arg1; 987 final boolean andCode = msg.arg2 != 0; 988 synchronized (mPackages) { 989 if (userId == UserHandle.USER_ALL) { 990 int[] users = sUserManager.getUserIds(); 991 for (int user : users) { 992 mSettings.addPackageToCleanLPw( 993 new PackageCleanItem(user, packageName, andCode)); 994 } 995 } else { 996 mSettings.addPackageToCleanLPw( 997 new PackageCleanItem(userId, packageName, andCode)); 998 } 999 } 1000 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1001 startCleaningPackages(); 1002 } break; 1003 case POST_INSTALL: { 1004 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1005 PostInstallData data = mRunningInstalls.get(msg.arg1); 1006 mRunningInstalls.delete(msg.arg1); 1007 boolean deleteOld = false; 1008 1009 if (data != null) { 1010 InstallArgs args = data.args; 1011 PackageInstalledInfo res = data.res; 1012 1013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1014 res.removedInfo.sendBroadcast(false, true, false); 1015 Bundle extras = new Bundle(1); 1016 extras.putInt(Intent.EXTRA_UID, res.uid); 1017 // Determine the set of users who are adding this 1018 // package for the first time vs. those who are seeing 1019 // an update. 1020 int[] firstUsers; 1021 int[] updateUsers = new int[0]; 1022 if (res.origUsers == null || res.origUsers.length == 0) { 1023 firstUsers = res.newUsers; 1024 } else { 1025 firstUsers = new int[0]; 1026 for (int i=0; i<res.newUsers.length; i++) { 1027 int user = res.newUsers[i]; 1028 boolean isNew = true; 1029 for (int j=0; j<res.origUsers.length; j++) { 1030 if (res.origUsers[j] == user) { 1031 isNew = false; 1032 break; 1033 } 1034 } 1035 if (isNew) { 1036 int[] newFirst = new int[firstUsers.length+1]; 1037 System.arraycopy(firstUsers, 0, newFirst, 0, 1038 firstUsers.length); 1039 newFirst[firstUsers.length] = user; 1040 firstUsers = newFirst; 1041 } else { 1042 int[] newUpdate = new int[updateUsers.length+1]; 1043 System.arraycopy(updateUsers, 0, newUpdate, 0, 1044 updateUsers.length); 1045 newUpdate[updateUsers.length] = user; 1046 updateUsers = newUpdate; 1047 } 1048 } 1049 } 1050 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1051 res.pkg.applicationInfo.packageName, 1052 extras, null, null, firstUsers); 1053 final boolean update = res.removedInfo.removedPackage != null; 1054 if (update) { 1055 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1056 } 1057 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1058 res.pkg.applicationInfo.packageName, 1059 extras, null, null, updateUsers); 1060 if (update) { 1061 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1062 res.pkg.applicationInfo.packageName, 1063 extras, null, null, updateUsers); 1064 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1065 null, null, 1066 res.pkg.applicationInfo.packageName, null, updateUsers); 1067 1068 // treat asec-hosted packages like removable media on upgrade 1069 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1070 if (DEBUG_INSTALL) { 1071 Slog.i(TAG, "upgrading pkg " + res.pkg 1072 + " is ASEC-hosted -> AVAILABLE"); 1073 } 1074 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1075 ArrayList<String> pkgList = new ArrayList<String>(1); 1076 pkgList.add(res.pkg.applicationInfo.packageName); 1077 sendResourcesChangedBroadcast(true, true, 1078 pkgList,uidArray, null); 1079 } 1080 } 1081 if (res.removedInfo.args != null) { 1082 // Remove the replaced package's older resources safely now 1083 deleteOld = true; 1084 } 1085 1086 // Log current value of "unknown sources" setting 1087 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1088 getUnknownSourcesSettings()); 1089 } 1090 // Force a gc to clear up things 1091 Runtime.getRuntime().gc(); 1092 // We delete after a gc for applications on sdcard. 1093 if (deleteOld) { 1094 synchronized (mInstallLock) { 1095 res.removedInfo.args.doPostDeleteLI(true); 1096 } 1097 } 1098 if (args.observer != null) { 1099 try { 1100 Bundle extras = extrasForInstallResult(res); 1101 args.observer.onPackageInstalled(res.name, res.returnCode, 1102 res.returnMsg, extras); 1103 } catch (RemoteException e) { 1104 Slog.i(TAG, "Observer no longer exists."); 1105 } 1106 } 1107 } else { 1108 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1109 } 1110 } break; 1111 case UPDATED_MEDIA_STATUS: { 1112 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1113 boolean reportStatus = msg.arg1 == 1; 1114 boolean doGc = msg.arg2 == 1; 1115 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1116 if (doGc) { 1117 // Force a gc to clear up stale containers. 1118 Runtime.getRuntime().gc(); 1119 } 1120 if (msg.obj != null) { 1121 @SuppressWarnings("unchecked") 1122 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1123 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1124 // Unload containers 1125 unloadAllContainers(args); 1126 } 1127 if (reportStatus) { 1128 try { 1129 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1130 PackageHelper.getMountService().finishMediaUpdate(); 1131 } catch (RemoteException e) { 1132 Log.e(TAG, "MountService not running?"); 1133 } 1134 } 1135 } break; 1136 case WRITE_SETTINGS: { 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1138 synchronized (mPackages) { 1139 removeMessages(WRITE_SETTINGS); 1140 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1141 mSettings.writeLPr(); 1142 mDirtyUsers.clear(); 1143 } 1144 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1145 } break; 1146 case WRITE_PACKAGE_RESTRICTIONS: { 1147 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1148 synchronized (mPackages) { 1149 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1150 for (int userId : mDirtyUsers) { 1151 mSettings.writePackageRestrictionsLPr(userId); 1152 } 1153 mDirtyUsers.clear(); 1154 } 1155 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1156 } break; 1157 case CHECK_PENDING_VERIFICATION: { 1158 final int verificationId = msg.arg1; 1159 final PackageVerificationState state = mPendingVerification.get(verificationId); 1160 1161 if ((state != null) && !state.timeoutExtended()) { 1162 final InstallArgs args = state.getInstallArgs(); 1163 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1164 1165 Slog.i(TAG, "Verification timed out for " + originUri); 1166 mPendingVerification.remove(verificationId); 1167 1168 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1169 1170 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1171 Slog.i(TAG, "Continuing with installation of " + originUri); 1172 state.setVerifierResponse(Binder.getCallingUid(), 1173 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1174 broadcastPackageVerified(verificationId, originUri, 1175 PackageManager.VERIFICATION_ALLOW, 1176 state.getInstallArgs().getUser()); 1177 try { 1178 ret = args.copyApk(mContainerService, true); 1179 } catch (RemoteException e) { 1180 Slog.e(TAG, "Could not contact the ContainerService"); 1181 } 1182 } else { 1183 broadcastPackageVerified(verificationId, originUri, 1184 PackageManager.VERIFICATION_REJECT, 1185 state.getInstallArgs().getUser()); 1186 } 1187 1188 processPendingInstall(args, ret); 1189 mHandler.sendEmptyMessage(MCS_UNBIND); 1190 } 1191 break; 1192 } 1193 case PACKAGE_VERIFIED: { 1194 final int verificationId = msg.arg1; 1195 1196 final PackageVerificationState state = mPendingVerification.get(verificationId); 1197 if (state == null) { 1198 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1199 break; 1200 } 1201 1202 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1203 1204 state.setVerifierResponse(response.callerUid, response.code); 1205 1206 if (state.isVerificationComplete()) { 1207 mPendingVerification.remove(verificationId); 1208 1209 final InstallArgs args = state.getInstallArgs(); 1210 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1211 1212 int ret; 1213 if (state.isInstallAllowed()) { 1214 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1215 broadcastPackageVerified(verificationId, originUri, 1216 response.code, state.getInstallArgs().getUser()); 1217 try { 1218 ret = args.copyApk(mContainerService, true); 1219 } catch (RemoteException e) { 1220 Slog.e(TAG, "Could not contact the ContainerService"); 1221 } 1222 } else { 1223 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1224 } 1225 1226 processPendingInstall(args, ret); 1227 1228 mHandler.sendEmptyMessage(MCS_UNBIND); 1229 } 1230 1231 break; 1232 } 1233 } 1234 } 1235 } 1236 1237 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1238 Bundle extras = null; 1239 switch (res.returnCode) { 1240 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1241 extras = new Bundle(); 1242 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1243 res.origPermission); 1244 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1245 res.origPackage); 1246 break; 1247 } 1248 } 1249 return extras; 1250 } 1251 1252 void scheduleWriteSettingsLocked() { 1253 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1254 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1255 } 1256 } 1257 1258 void scheduleWritePackageRestrictionsLocked(int userId) { 1259 if (!sUserManager.exists(userId)) return; 1260 mDirtyUsers.add(userId); 1261 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1262 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1263 } 1264 } 1265 1266 public static PackageManagerService main(Context context, Installer installer, 1267 boolean factoryTest, boolean onlyCore) { 1268 PackageManagerService m = new PackageManagerService(context, installer, 1269 factoryTest, onlyCore); 1270 ServiceManager.addService("package", m); 1271 return m; 1272 } 1273 1274 static String[] splitString(String str, char sep) { 1275 int count = 1; 1276 int i = 0; 1277 while ((i=str.indexOf(sep, i)) >= 0) { 1278 count++; 1279 i++; 1280 } 1281 1282 String[] res = new String[count]; 1283 i=0; 1284 count = 0; 1285 int lastI=0; 1286 while ((i=str.indexOf(sep, i)) >= 0) { 1287 res[count] = str.substring(lastI, i); 1288 count++; 1289 i++; 1290 lastI = i; 1291 } 1292 res[count] = str.substring(lastI, str.length()); 1293 return res; 1294 } 1295 1296 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1297 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1298 Context.DISPLAY_SERVICE); 1299 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1300 } 1301 1302 public PackageManagerService(Context context, Installer installer, 1303 boolean factoryTest, boolean onlyCore) { 1304 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1305 SystemClock.uptimeMillis()); 1306 1307 if (mSdkVersion <= 0) { 1308 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1309 } 1310 1311 mContext = context; 1312 mFactoryTest = factoryTest; 1313 mOnlyCore = onlyCore; 1314 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1315 mMetrics = new DisplayMetrics(); 1316 mSettings = new Settings(mContext, mPackages); 1317 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1318 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1319 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1320 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1321 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1322 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1323 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1324 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1325 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1326 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1327 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1328 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1329 1330 // TODO: add a property to control this? 1331 long dexOptLRUThresholdInMinutes; 1332 if (mLazyDexOpt) { 1333 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1334 } else { 1335 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1336 } 1337 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1338 1339 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1340 if (separateProcesses != null && separateProcesses.length() > 0) { 1341 if ("*".equals(separateProcesses)) { 1342 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1343 mSeparateProcesses = null; 1344 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1345 } else { 1346 mDefParseFlags = 0; 1347 mSeparateProcesses = separateProcesses.split(","); 1348 Slog.w(TAG, "Running with debug.separate_processes: " 1349 + separateProcesses); 1350 } 1351 } else { 1352 mDefParseFlags = 0; 1353 mSeparateProcesses = null; 1354 } 1355 1356 mInstaller = installer; 1357 mPackageDexOptimizer = new PackageDexOptimizer(this); 1358 1359 getDefaultDisplayMetrics(context, mMetrics); 1360 1361 SystemConfig systemConfig = SystemConfig.getInstance(); 1362 mGlobalGids = systemConfig.getGlobalGids(); 1363 mSystemPermissions = systemConfig.getSystemPermissions(); 1364 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1365 1366 synchronized (mInstallLock) { 1367 // writer 1368 synchronized (mPackages) { 1369 mHandlerThread = new ServiceThread(TAG, 1370 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1371 mHandlerThread.start(); 1372 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1373 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1374 1375 File dataDir = Environment.getDataDirectory(); 1376 mAppDataDir = new File(dataDir, "data"); 1377 mAppInstallDir = new File(dataDir, "app"); 1378 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1379 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1380 mUserAppDataDir = new File(dataDir, "user"); 1381 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1382 1383 sUserManager = new UserManagerService(context, this, 1384 mInstallLock, mPackages); 1385 1386 // Propagate permission configuration in to package manager. 1387 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1388 = systemConfig.getPermissions(); 1389 for (int i=0; i<permConfig.size(); i++) { 1390 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1391 BasePermission bp = mSettings.mPermissions.get(perm.name); 1392 if (bp == null) { 1393 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1394 mSettings.mPermissions.put(perm.name, bp); 1395 } 1396 if (perm.gids != null) { 1397 bp.gids = appendInts(bp.gids, perm.gids); 1398 } 1399 } 1400 1401 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1402 for (int i=0; i<libConfig.size(); i++) { 1403 mSharedLibraries.put(libConfig.keyAt(i), 1404 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1405 } 1406 1407 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1408 1409 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1410 mSdkVersion, mOnlyCore); 1411 1412 String customResolverActivity = Resources.getSystem().getString( 1413 R.string.config_customResolverActivity); 1414 if (TextUtils.isEmpty(customResolverActivity)) { 1415 customResolverActivity = null; 1416 } else { 1417 mCustomResolverComponentName = ComponentName.unflattenFromString( 1418 customResolverActivity); 1419 } 1420 1421 long startTime = SystemClock.uptimeMillis(); 1422 1423 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1424 startTime); 1425 1426 // Set flag to monitor and not change apk file paths when 1427 // scanning install directories. 1428 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1429 1430 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1431 1432 /** 1433 * Add everything in the in the boot class path to the 1434 * list of process files because dexopt will have been run 1435 * if necessary during zygote startup. 1436 */ 1437 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1438 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1439 1440 if (bootClassPath != null) { 1441 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1442 for (String element : bootClassPathElements) { 1443 alreadyDexOpted.add(element); 1444 } 1445 } else { 1446 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1447 } 1448 1449 if (systemServerClassPath != null) { 1450 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1451 for (String element : systemServerClassPathElements) { 1452 alreadyDexOpted.add(element); 1453 } 1454 } else { 1455 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1456 } 1457 1458 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1459 final String[] dexCodeInstructionSets = 1460 getDexCodeInstructionSets( 1461 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1462 1463 /** 1464 * Ensure all external libraries have had dexopt run on them. 1465 */ 1466 if (mSharedLibraries.size() > 0) { 1467 // NOTE: For now, we're compiling these system "shared libraries" 1468 // (and framework jars) into all available architectures. It's possible 1469 // to compile them only when we come across an app that uses them (there's 1470 // already logic for that in scanPackageLI) but that adds some complexity. 1471 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1472 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1473 final String lib = libEntry.path; 1474 if (lib == null) { 1475 continue; 1476 } 1477 1478 try { 1479 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1480 dexCodeInstructionSet, 1481 false); 1482 if (dexoptRequired != DexFile.UP_TO_DATE) { 1483 alreadyDexOpted.add(lib); 1484 1485 // The list of "shared libraries" we have at this point is 1486 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1487 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1488 } else { 1489 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1490 } 1491 } 1492 } catch (FileNotFoundException e) { 1493 Slog.w(TAG, "Library not found: " + lib); 1494 } catch (IOException e) { 1495 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1496 + e.getMessage()); 1497 } 1498 } 1499 } 1500 } 1501 1502 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1503 1504 // Gross hack for now: we know this file doesn't contain any 1505 // code, so don't dexopt it to avoid the resulting log spew. 1506 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1507 1508 // Gross hack for now: we know this file is only part of 1509 // the boot class path for art, so don't dexopt it to 1510 // avoid the resulting log spew. 1511 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1512 1513 /** 1514 * And there are a number of commands implemented in Java, which 1515 * we currently need to do the dexopt on so that they can be 1516 * run from a non-root shell. 1517 */ 1518 String[] frameworkFiles = frameworkDir.list(); 1519 if (frameworkFiles != null) { 1520 // TODO: We could compile these only for the most preferred ABI. We should 1521 // first double check that the dex files for these commands are not referenced 1522 // by other system apps. 1523 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1524 for (int i=0; i<frameworkFiles.length; i++) { 1525 File libPath = new File(frameworkDir, frameworkFiles[i]); 1526 String path = libPath.getPath(); 1527 // Skip the file if we already did it. 1528 if (alreadyDexOpted.contains(path)) { 1529 continue; 1530 } 1531 // Skip the file if it is not a type we want to dexopt. 1532 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1533 continue; 1534 } 1535 try { 1536 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1537 dexCodeInstructionSet, 1538 false); 1539 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1540 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1541 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1542 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1543 } 1544 } catch (FileNotFoundException e) { 1545 Slog.w(TAG, "Jar not found: " + path); 1546 } catch (IOException e) { 1547 Slog.w(TAG, "Exception reading jar: " + path, e); 1548 } 1549 } 1550 } 1551 } 1552 1553 // Collect vendor overlay packages. 1554 // (Do this before scanning any apps.) 1555 // For security and version matching reason, only consider 1556 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1557 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1558 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1559 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1560 1561 // Find base frameworks (resource packages without code). 1562 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR 1564 | PackageParser.PARSE_IS_PRIVILEGED, 1565 scanFlags | SCAN_NO_DEX, 0); 1566 1567 // Collected privileged system packages. 1568 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1569 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1570 | PackageParser.PARSE_IS_SYSTEM_DIR 1571 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1572 1573 // Collect ordinary system packages. 1574 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1575 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1576 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1577 1578 // Collect all vendor packages. 1579 File vendorAppDir = new File("/vendor/app"); 1580 try { 1581 vendorAppDir = vendorAppDir.getCanonicalFile(); 1582 } catch (IOException e) { 1583 // failed to look up canonical path, continue with original one 1584 } 1585 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1586 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1587 1588 // Collect all OEM packages. 1589 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1590 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1591 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1592 1593 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1594 mInstaller.moveFiles(); 1595 1596 // Prune any system packages that no longer exist. 1597 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1598 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1599 if (!mOnlyCore) { 1600 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1601 while (psit.hasNext()) { 1602 PackageSetting ps = psit.next(); 1603 1604 /* 1605 * If this is not a system app, it can't be a 1606 * disable system app. 1607 */ 1608 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1609 continue; 1610 } 1611 1612 /* 1613 * If the package is scanned, it's not erased. 1614 */ 1615 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1616 if (scannedPkg != null) { 1617 /* 1618 * If the system app is both scanned and in the 1619 * disabled packages list, then it must have been 1620 * added via OTA. Remove it from the currently 1621 * scanned package so the previously user-installed 1622 * application can be scanned. 1623 */ 1624 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1625 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1626 + ps.name + "; removing system app. Last known codePath=" 1627 + ps.codePathString + ", installStatus=" + ps.installStatus 1628 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1629 + scannedPkg.mVersionCode); 1630 removePackageLI(ps, true); 1631 expectingBetter.put(ps.name, ps.codePath); 1632 } 1633 1634 continue; 1635 } 1636 1637 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1638 psit.remove(); 1639 logCriticalInfo(Log.WARN, "System package " + ps.name 1640 + " no longer exists; wiping its data"); 1641 removeDataDirsLI(ps.name); 1642 } else { 1643 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1644 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1645 possiblyDeletedUpdatedSystemApps.add(ps.name); 1646 } 1647 } 1648 } 1649 } 1650 1651 //look for any incomplete package installations 1652 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1653 //clean up list 1654 for(int i = 0; i < deletePkgsList.size(); i++) { 1655 //clean up here 1656 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1657 } 1658 //delete tmp files 1659 deleteTempPackageFiles(); 1660 1661 // Remove any shared userIDs that have no associated packages 1662 mSettings.pruneSharedUsersLPw(); 1663 1664 if (!mOnlyCore) { 1665 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1666 SystemClock.uptimeMillis()); 1667 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1668 1669 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1670 scanFlags, 0); 1671 1672 /** 1673 * Remove disable package settings for any updated system 1674 * apps that were removed via an OTA. If they're not a 1675 * previously-updated app, remove them completely. 1676 * Otherwise, just revoke their system-level permissions. 1677 */ 1678 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1679 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1680 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1681 1682 String msg; 1683 if (deletedPkg == null) { 1684 msg = "Updated system package " + deletedAppName 1685 + " no longer exists; wiping its data"; 1686 removeDataDirsLI(deletedAppName); 1687 } else { 1688 msg = "Updated system app + " + deletedAppName 1689 + " no longer present; removing system privileges for " 1690 + deletedAppName; 1691 1692 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1693 1694 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1695 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1696 } 1697 logCriticalInfo(Log.WARN, msg); 1698 } 1699 1700 /** 1701 * Make sure all system apps that we expected to appear on 1702 * the userdata partition actually showed up. If they never 1703 * appeared, crawl back and revive the system version. 1704 */ 1705 for (int i = 0; i < expectingBetter.size(); i++) { 1706 final String packageName = expectingBetter.keyAt(i); 1707 if (!mPackages.containsKey(packageName)) { 1708 final File scanFile = expectingBetter.valueAt(i); 1709 1710 logCriticalInfo(Log.WARN, "Expected better " + packageName 1711 + " but never showed up; reverting to system"); 1712 1713 final int reparseFlags; 1714 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1715 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1716 | PackageParser.PARSE_IS_SYSTEM_DIR 1717 | PackageParser.PARSE_IS_PRIVILEGED; 1718 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1719 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1720 | PackageParser.PARSE_IS_SYSTEM_DIR; 1721 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1722 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1723 | PackageParser.PARSE_IS_SYSTEM_DIR; 1724 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1725 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1726 | PackageParser.PARSE_IS_SYSTEM_DIR; 1727 } else { 1728 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1729 continue; 1730 } 1731 1732 mSettings.enableSystemPackageLPw(packageName); 1733 1734 try { 1735 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1736 } catch (PackageManagerException e) { 1737 Slog.e(TAG, "Failed to parse original system package: " 1738 + e.getMessage()); 1739 } 1740 } 1741 } 1742 } 1743 1744 // Now that we know all of the shared libraries, update all clients to have 1745 // the correct library paths. 1746 updateAllSharedLibrariesLPw(); 1747 1748 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1749 // NOTE: We ignore potential failures here during a system scan (like 1750 // the rest of the commands above) because there's precious little we 1751 // can do about it. A settings error is reported, though. 1752 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1753 false /* force dexopt */, false /* defer dexopt */); 1754 } 1755 1756 // Now that we know all the packages we are keeping, 1757 // read and update their last usage times. 1758 mPackageUsage.readLP(); 1759 1760 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1761 SystemClock.uptimeMillis()); 1762 Slog.i(TAG, "Time to scan packages: " 1763 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1764 + " seconds"); 1765 1766 // If the platform SDK has changed since the last time we booted, 1767 // we need to re-grant app permission to catch any new ones that 1768 // appear. This is really a hack, and means that apps can in some 1769 // cases get permissions that the user didn't initially explicitly 1770 // allow... it would be nice to have some better way to handle 1771 // this situation. 1772 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1773 != mSdkVersion; 1774 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1775 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1776 + "; regranting permissions for internal storage"); 1777 mSettings.mInternalSdkPlatform = mSdkVersion; 1778 1779 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1780 | (regrantPermissions 1781 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1782 : 0)); 1783 1784 // If this is the first boot, and it is a normal boot, then 1785 // we need to initialize the default preferred apps. 1786 if (!mRestoredSettings && !onlyCore) { 1787 mSettings.readDefaultPreferredAppsLPw(this, 0); 1788 } 1789 1790 // If this is first boot after an OTA, and a normal boot, then 1791 // we need to clear code cache directories. 1792 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1793 if (mIsUpgrade && !onlyCore) { 1794 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1795 for (String pkgName : mSettings.mPackages.keySet()) { 1796 deleteCodeCacheDirsLI(pkgName); 1797 } 1798 mSettings.mFingerprint = Build.FINGERPRINT; 1799 } 1800 1801 // All the changes are done during package scanning. 1802 mSettings.updateInternalDatabaseVersion(); 1803 1804 // can downgrade to reader 1805 mSettings.writeLPr(); 1806 1807 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1808 SystemClock.uptimeMillis()); 1809 1810 1811 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1812 } // synchronized (mPackages) 1813 } // synchronized (mInstallLock) 1814 1815 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1816 1817 // Now after opening every single application zip, make sure they 1818 // are all flushed. Not really needed, but keeps things nice and 1819 // tidy. 1820 Runtime.getRuntime().gc(); 1821 } 1822 1823 @Override 1824 public boolean isFirstBoot() { 1825 return !mRestoredSettings; 1826 } 1827 1828 @Override 1829 public boolean isOnlyCoreApps() { 1830 return mOnlyCore; 1831 } 1832 1833 @Override 1834 public boolean isUpgrade() { 1835 return mIsUpgrade; 1836 } 1837 1838 private String getRequiredVerifierLPr() { 1839 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1840 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1841 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1842 1843 String requiredVerifier = null; 1844 1845 final int N = receivers.size(); 1846 for (int i = 0; i < N; i++) { 1847 final ResolveInfo info = receivers.get(i); 1848 1849 if (info.activityInfo == null) { 1850 continue; 1851 } 1852 1853 final String packageName = info.activityInfo.packageName; 1854 1855 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 1856 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 1857 continue; 1858 } 1859 1860 if (requiredVerifier != null) { 1861 throw new RuntimeException("There can be only one required verifier"); 1862 } 1863 1864 requiredVerifier = packageName; 1865 } 1866 1867 return requiredVerifier; 1868 } 1869 1870 @Override 1871 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1872 throws RemoteException { 1873 try { 1874 return super.onTransact(code, data, reply, flags); 1875 } catch (RuntimeException e) { 1876 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1877 Slog.wtf(TAG, "Package Manager Crash", e); 1878 } 1879 throw e; 1880 } 1881 } 1882 1883 void cleanupInstallFailedPackage(PackageSetting ps) { 1884 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1885 1886 removeDataDirsLI(ps.name); 1887 if (ps.codePath != null) { 1888 if (ps.codePath.isDirectory()) { 1889 FileUtils.deleteContents(ps.codePath); 1890 } 1891 ps.codePath.delete(); 1892 } 1893 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1894 if (ps.resourcePath.isDirectory()) { 1895 FileUtils.deleteContents(ps.resourcePath); 1896 } 1897 ps.resourcePath.delete(); 1898 } 1899 mSettings.removePackageLPw(ps.name); 1900 } 1901 1902 static int[] appendInts(int[] cur, int[] add) { 1903 if (add == null) return cur; 1904 if (cur == null) return add; 1905 final int N = add.length; 1906 for (int i=0; i<N; i++) { 1907 cur = appendInt(cur, add[i]); 1908 } 1909 return cur; 1910 } 1911 1912 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1913 if (!sUserManager.exists(userId)) return null; 1914 final PackageSetting ps = (PackageSetting) p.mExtras; 1915 if (ps == null) { 1916 return null; 1917 } 1918 1919 PermissionsState permissionsState = ps.getPermissionsState(); 1920 1921 final int[] gids = permissionsState.computeGids(userId); 1922 Set<String> permissions = permissionsState.getPermissions(userId); 1923 1924 final PackageUserState state = ps.readUserState(userId); 1925 return PackageParser.generatePackageInfo(p, gids, flags, 1926 ps.firstInstallTime, ps.lastUpdateTime, permissions, 1927 state, userId); 1928 } 1929 1930 @Override 1931 public boolean isPackageAvailable(String packageName, int userId) { 1932 if (!sUserManager.exists(userId)) return false; 1933 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1934 synchronized (mPackages) { 1935 PackageParser.Package p = mPackages.get(packageName); 1936 if (p != null) { 1937 final PackageSetting ps = (PackageSetting) p.mExtras; 1938 if (ps != null) { 1939 final PackageUserState state = ps.readUserState(userId); 1940 if (state != null) { 1941 return PackageParser.isAvailable(state); 1942 } 1943 } 1944 } 1945 } 1946 return false; 1947 } 1948 1949 @Override 1950 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1951 if (!sUserManager.exists(userId)) return null; 1952 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1953 // reader 1954 synchronized (mPackages) { 1955 PackageParser.Package p = mPackages.get(packageName); 1956 if (DEBUG_PACKAGE_INFO) 1957 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1958 if (p != null) { 1959 return generatePackageInfo(p, flags, userId); 1960 } 1961 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1962 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1963 } 1964 } 1965 return null; 1966 } 1967 1968 @Override 1969 public String[] currentToCanonicalPackageNames(String[] names) { 1970 String[] out = new String[names.length]; 1971 // reader 1972 synchronized (mPackages) { 1973 for (int i=names.length-1; i>=0; i--) { 1974 PackageSetting ps = mSettings.mPackages.get(names[i]); 1975 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1976 } 1977 } 1978 return out; 1979 } 1980 1981 @Override 1982 public String[] canonicalToCurrentPackageNames(String[] names) { 1983 String[] out = new String[names.length]; 1984 // reader 1985 synchronized (mPackages) { 1986 for (int i=names.length-1; i>=0; i--) { 1987 String cur = mSettings.mRenamedPackages.get(names[i]); 1988 out[i] = cur != null ? cur : names[i]; 1989 } 1990 } 1991 return out; 1992 } 1993 1994 @Override 1995 public int getPackageUid(String packageName, int userId) { 1996 if (!sUserManager.exists(userId)) return -1; 1997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1998 1999 // reader 2000 synchronized (mPackages) { 2001 PackageParser.Package p = mPackages.get(packageName); 2002 if(p != null) { 2003 return UserHandle.getUid(userId, p.applicationInfo.uid); 2004 } 2005 PackageSetting ps = mSettings.mPackages.get(packageName); 2006 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2007 return -1; 2008 } 2009 p = ps.pkg; 2010 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2011 } 2012 } 2013 2014 @Override 2015 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2016 if (!sUserManager.exists(userId)) { 2017 return null; 2018 } 2019 2020 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2021 "getPackageGids"); 2022 2023 // reader 2024 synchronized (mPackages) { 2025 PackageParser.Package p = mPackages.get(packageName); 2026 if (DEBUG_PACKAGE_INFO) { 2027 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2028 } 2029 if (p != null) { 2030 PackageSetting ps = (PackageSetting) p.mExtras; 2031 return ps.getPermissionsState().computeGids(userId); 2032 } 2033 } 2034 2035 return null; 2036 } 2037 2038 static PermissionInfo generatePermissionInfo( 2039 BasePermission bp, int flags) { 2040 if (bp.perm != null) { 2041 return PackageParser.generatePermissionInfo(bp.perm, flags); 2042 } 2043 PermissionInfo pi = new PermissionInfo(); 2044 pi.name = bp.name; 2045 pi.packageName = bp.sourcePackage; 2046 pi.nonLocalizedLabel = bp.name; 2047 pi.protectionLevel = bp.protectionLevel; 2048 return pi; 2049 } 2050 2051 @Override 2052 public PermissionInfo getPermissionInfo(String name, int flags) { 2053 // reader 2054 synchronized (mPackages) { 2055 final BasePermission p = mSettings.mPermissions.get(name); 2056 if (p != null) { 2057 return generatePermissionInfo(p, flags); 2058 } 2059 return null; 2060 } 2061 } 2062 2063 @Override 2064 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2065 // reader 2066 synchronized (mPackages) { 2067 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2068 for (BasePermission p : mSettings.mPermissions.values()) { 2069 if (group == null) { 2070 if (p.perm == null || p.perm.info.group == null) { 2071 out.add(generatePermissionInfo(p, flags)); 2072 } 2073 } else { 2074 if (p.perm != null && group.equals(p.perm.info.group)) { 2075 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2076 } 2077 } 2078 } 2079 2080 if (out.size() > 0) { 2081 return out; 2082 } 2083 return mPermissionGroups.containsKey(group) ? out : null; 2084 } 2085 } 2086 2087 @Override 2088 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2089 // reader 2090 synchronized (mPackages) { 2091 return PackageParser.generatePermissionGroupInfo( 2092 mPermissionGroups.get(name), flags); 2093 } 2094 } 2095 2096 @Override 2097 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2098 // reader 2099 synchronized (mPackages) { 2100 final int N = mPermissionGroups.size(); 2101 ArrayList<PermissionGroupInfo> out 2102 = new ArrayList<PermissionGroupInfo>(N); 2103 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2104 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2105 } 2106 return out; 2107 } 2108 } 2109 2110 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2111 int userId) { 2112 if (!sUserManager.exists(userId)) return null; 2113 PackageSetting ps = mSettings.mPackages.get(packageName); 2114 if (ps != null) { 2115 if (ps.pkg == null) { 2116 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2117 flags, userId); 2118 if (pInfo != null) { 2119 return pInfo.applicationInfo; 2120 } 2121 return null; 2122 } 2123 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2124 ps.readUserState(userId), userId); 2125 } 2126 return null; 2127 } 2128 2129 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2130 int userId) { 2131 if (!sUserManager.exists(userId)) return null; 2132 PackageSetting ps = mSettings.mPackages.get(packageName); 2133 if (ps != null) { 2134 PackageParser.Package pkg = ps.pkg; 2135 if (pkg == null) { 2136 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2137 return null; 2138 } 2139 // Only data remains, so we aren't worried about code paths 2140 pkg = new PackageParser.Package(packageName); 2141 pkg.applicationInfo.packageName = packageName; 2142 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2143 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2144 pkg.applicationInfo.dataDir = 2145 getDataPathForPackage(packageName, 0).getPath(); 2146 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2147 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2148 } 2149 return generatePackageInfo(pkg, flags, userId); 2150 } 2151 return null; 2152 } 2153 2154 @Override 2155 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2156 if (!sUserManager.exists(userId)) return null; 2157 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2158 // writer 2159 synchronized (mPackages) { 2160 PackageParser.Package p = mPackages.get(packageName); 2161 if (DEBUG_PACKAGE_INFO) Log.v( 2162 TAG, "getApplicationInfo " + packageName 2163 + ": " + p); 2164 if (p != null) { 2165 PackageSetting ps = mSettings.mPackages.get(packageName); 2166 if (ps == null) return null; 2167 // Note: isEnabledLP() does not apply here - always return info 2168 return PackageParser.generateApplicationInfo( 2169 p, flags, ps.readUserState(userId), userId); 2170 } 2171 if ("android".equals(packageName)||"system".equals(packageName)) { 2172 return mAndroidApplication; 2173 } 2174 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2175 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2176 } 2177 } 2178 return null; 2179 } 2180 2181 2182 @Override 2183 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2184 mContext.enforceCallingOrSelfPermission( 2185 android.Manifest.permission.CLEAR_APP_CACHE, null); 2186 // Queue up an async operation since clearing cache may take a little while. 2187 mHandler.post(new Runnable() { 2188 public void run() { 2189 mHandler.removeCallbacks(this); 2190 int retCode = -1; 2191 synchronized (mInstallLock) { 2192 retCode = mInstaller.freeCache(freeStorageSize); 2193 if (retCode < 0) { 2194 Slog.w(TAG, "Couldn't clear application caches"); 2195 } 2196 } 2197 if (observer != null) { 2198 try { 2199 observer.onRemoveCompleted(null, (retCode >= 0)); 2200 } catch (RemoteException e) { 2201 Slog.w(TAG, "RemoveException when invoking call back"); 2202 } 2203 } 2204 } 2205 }); 2206 } 2207 2208 @Override 2209 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2210 mContext.enforceCallingOrSelfPermission( 2211 android.Manifest.permission.CLEAR_APP_CACHE, null); 2212 // Queue up an async operation since clearing cache may take a little while. 2213 mHandler.post(new Runnable() { 2214 public void run() { 2215 mHandler.removeCallbacks(this); 2216 int retCode = -1; 2217 synchronized (mInstallLock) { 2218 retCode = mInstaller.freeCache(freeStorageSize); 2219 if (retCode < 0) { 2220 Slog.w(TAG, "Couldn't clear application caches"); 2221 } 2222 } 2223 if(pi != null) { 2224 try { 2225 // Callback via pending intent 2226 int code = (retCode >= 0) ? 1 : 0; 2227 pi.sendIntent(null, code, null, 2228 null, null); 2229 } catch (SendIntentException e1) { 2230 Slog.i(TAG, "Failed to send pending intent"); 2231 } 2232 } 2233 } 2234 }); 2235 } 2236 2237 void freeStorage(long freeStorageSize) throws IOException { 2238 synchronized (mInstallLock) { 2239 if (mInstaller.freeCache(freeStorageSize) < 0) { 2240 throw new IOException("Failed to free enough space"); 2241 } 2242 } 2243 } 2244 2245 @Override 2246 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2247 if (!sUserManager.exists(userId)) return null; 2248 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2249 synchronized (mPackages) { 2250 PackageParser.Activity a = mActivities.mActivities.get(component); 2251 2252 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2253 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2254 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2255 if (ps == null) return null; 2256 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2257 userId); 2258 } 2259 if (mResolveComponentName.equals(component)) { 2260 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2261 new PackageUserState(), userId); 2262 } 2263 } 2264 return null; 2265 } 2266 2267 @Override 2268 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2269 String resolvedType) { 2270 synchronized (mPackages) { 2271 PackageParser.Activity a = mActivities.mActivities.get(component); 2272 if (a == null) { 2273 return false; 2274 } 2275 for (int i=0; i<a.intents.size(); i++) { 2276 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2277 intent.getData(), intent.getCategories(), TAG) >= 0) { 2278 return true; 2279 } 2280 } 2281 return false; 2282 } 2283 } 2284 2285 @Override 2286 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2287 if (!sUserManager.exists(userId)) return null; 2288 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2289 synchronized (mPackages) { 2290 PackageParser.Activity a = mReceivers.mActivities.get(component); 2291 if (DEBUG_PACKAGE_INFO) Log.v( 2292 TAG, "getReceiverInfo " + component + ": " + a); 2293 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2294 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2295 if (ps == null) return null; 2296 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2297 userId); 2298 } 2299 } 2300 return null; 2301 } 2302 2303 @Override 2304 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2305 if (!sUserManager.exists(userId)) return null; 2306 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2307 synchronized (mPackages) { 2308 PackageParser.Service s = mServices.mServices.get(component); 2309 if (DEBUG_PACKAGE_INFO) Log.v( 2310 TAG, "getServiceInfo " + component + ": " + s); 2311 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2312 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2313 if (ps == null) return null; 2314 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2315 userId); 2316 } 2317 } 2318 return null; 2319 } 2320 2321 @Override 2322 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2323 if (!sUserManager.exists(userId)) return null; 2324 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2325 synchronized (mPackages) { 2326 PackageParser.Provider p = mProviders.mProviders.get(component); 2327 if (DEBUG_PACKAGE_INFO) Log.v( 2328 TAG, "getProviderInfo " + component + ": " + p); 2329 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2330 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2331 if (ps == null) return null; 2332 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2333 userId); 2334 } 2335 } 2336 return null; 2337 } 2338 2339 @Override 2340 public String[] getSystemSharedLibraryNames() { 2341 Set<String> libSet; 2342 synchronized (mPackages) { 2343 libSet = mSharedLibraries.keySet(); 2344 int size = libSet.size(); 2345 if (size > 0) { 2346 String[] libs = new String[size]; 2347 libSet.toArray(libs); 2348 return libs; 2349 } 2350 } 2351 return null; 2352 } 2353 2354 /** 2355 * @hide 2356 */ 2357 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2358 synchronized (mPackages) { 2359 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2360 if (lib != null && lib.apk != null) { 2361 return mPackages.get(lib.apk); 2362 } 2363 } 2364 return null; 2365 } 2366 2367 @Override 2368 public FeatureInfo[] getSystemAvailableFeatures() { 2369 Collection<FeatureInfo> featSet; 2370 synchronized (mPackages) { 2371 featSet = mAvailableFeatures.values(); 2372 int size = featSet.size(); 2373 if (size > 0) { 2374 FeatureInfo[] features = new FeatureInfo[size+1]; 2375 featSet.toArray(features); 2376 FeatureInfo fi = new FeatureInfo(); 2377 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2378 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2379 features[size] = fi; 2380 return features; 2381 } 2382 } 2383 return null; 2384 } 2385 2386 @Override 2387 public boolean hasSystemFeature(String name) { 2388 synchronized (mPackages) { 2389 return mAvailableFeatures.containsKey(name); 2390 } 2391 } 2392 2393 private void checkValidCaller(int uid, int userId) { 2394 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2395 return; 2396 2397 throw new SecurityException("Caller uid=" + uid 2398 + " is not privileged to communicate with user=" + userId); 2399 } 2400 2401 @Override 2402 public int checkPermission(String permName, String pkgName, int userId) { 2403 if (!sUserManager.exists(userId)) { 2404 return PackageManager.PERMISSION_DENIED; 2405 } 2406 2407 synchronized (mPackages) { 2408 final PackageParser.Package p = mPackages.get(pkgName); 2409 if (p != null && p.mExtras != null) { 2410 final PackageSetting ps = (PackageSetting) p.mExtras; 2411 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2412 return PackageManager.PERMISSION_GRANTED; 2413 } 2414 } 2415 } 2416 2417 return PackageManager.PERMISSION_DENIED; 2418 } 2419 2420 @Override 2421 public int checkUidPermission(String permName, int uid) { 2422 final int userId = UserHandle.getUserId(uid); 2423 2424 if (!sUserManager.exists(userId)) { 2425 return PackageManager.PERMISSION_DENIED; 2426 } 2427 2428 synchronized (mPackages) { 2429 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2430 if (obj != null) { 2431 final SettingBase ps = (SettingBase) obj; 2432 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2433 return PackageManager.PERMISSION_GRANTED; 2434 } 2435 } else { 2436 ArraySet<String> perms = mSystemPermissions.get(uid); 2437 if (perms != null && perms.contains(permName)) { 2438 return PackageManager.PERMISSION_GRANTED; 2439 } 2440 } 2441 } 2442 2443 return PackageManager.PERMISSION_DENIED; 2444 } 2445 2446 /** 2447 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2448 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2449 * @param checkShell TODO(yamasani): 2450 * @param message the message to log on security exception 2451 */ 2452 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2453 boolean checkShell, String message) { 2454 if (userId < 0) { 2455 throw new IllegalArgumentException("Invalid userId " + userId); 2456 } 2457 if (checkShell) { 2458 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2459 } 2460 if (userId == UserHandle.getUserId(callingUid)) return; 2461 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2462 if (requireFullPermission) { 2463 mContext.enforceCallingOrSelfPermission( 2464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2465 } else { 2466 try { 2467 mContext.enforceCallingOrSelfPermission( 2468 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2469 } catch (SecurityException se) { 2470 mContext.enforceCallingOrSelfPermission( 2471 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2472 } 2473 } 2474 } 2475 } 2476 2477 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2478 if (callingUid == Process.SHELL_UID) { 2479 if (userHandle >= 0 2480 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2481 throw new SecurityException("Shell does not have permission to access user " 2482 + userHandle); 2483 } else if (userHandle < 0) { 2484 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2485 + Debug.getCallers(3)); 2486 } 2487 } 2488 } 2489 2490 private BasePermission findPermissionTreeLP(String permName) { 2491 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2492 if (permName.startsWith(bp.name) && 2493 permName.length() > bp.name.length() && 2494 permName.charAt(bp.name.length()) == '.') { 2495 return bp; 2496 } 2497 } 2498 return null; 2499 } 2500 2501 private BasePermission checkPermissionTreeLP(String permName) { 2502 if (permName != null) { 2503 BasePermission bp = findPermissionTreeLP(permName); 2504 if (bp != null) { 2505 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2506 return bp; 2507 } 2508 throw new SecurityException("Calling uid " 2509 + Binder.getCallingUid() 2510 + " is not allowed to add to permission tree " 2511 + bp.name + " owned by uid " + bp.uid); 2512 } 2513 } 2514 throw new SecurityException("No permission tree found for " + permName); 2515 } 2516 2517 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2518 if (s1 == null) { 2519 return s2 == null; 2520 } 2521 if (s2 == null) { 2522 return false; 2523 } 2524 if (s1.getClass() != s2.getClass()) { 2525 return false; 2526 } 2527 return s1.equals(s2); 2528 } 2529 2530 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2531 if (pi1.icon != pi2.icon) return false; 2532 if (pi1.logo != pi2.logo) return false; 2533 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2534 if (!compareStrings(pi1.name, pi2.name)) return false; 2535 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2536 // We'll take care of setting this one. 2537 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2538 // These are not currently stored in settings. 2539 //if (!compareStrings(pi1.group, pi2.group)) return false; 2540 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2541 //if (pi1.labelRes != pi2.labelRes) return false; 2542 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2543 return true; 2544 } 2545 2546 int permissionInfoFootprint(PermissionInfo info) { 2547 int size = info.name.length(); 2548 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2549 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2550 return size; 2551 } 2552 2553 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2554 int size = 0; 2555 for (BasePermission perm : mSettings.mPermissions.values()) { 2556 if (perm.uid == tree.uid) { 2557 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2558 } 2559 } 2560 return size; 2561 } 2562 2563 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2564 // We calculate the max size of permissions defined by this uid and throw 2565 // if that plus the size of 'info' would exceed our stated maximum. 2566 if (tree.uid != Process.SYSTEM_UID) { 2567 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2568 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2569 throw new SecurityException("Permission tree size cap exceeded"); 2570 } 2571 } 2572 } 2573 2574 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2575 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2576 throw new SecurityException("Label must be specified in permission"); 2577 } 2578 BasePermission tree = checkPermissionTreeLP(info.name); 2579 BasePermission bp = mSettings.mPermissions.get(info.name); 2580 boolean added = bp == null; 2581 boolean changed = true; 2582 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2583 if (added) { 2584 enforcePermissionCapLocked(info, tree); 2585 bp = new BasePermission(info.name, tree.sourcePackage, 2586 BasePermission.TYPE_DYNAMIC); 2587 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2588 throw new SecurityException( 2589 "Not allowed to modify non-dynamic permission " 2590 + info.name); 2591 } else { 2592 if (bp.protectionLevel == fixedLevel 2593 && bp.perm.owner.equals(tree.perm.owner) 2594 && bp.uid == tree.uid 2595 && comparePermissionInfos(bp.perm.info, info)) { 2596 changed = false; 2597 } 2598 } 2599 bp.protectionLevel = fixedLevel; 2600 info = new PermissionInfo(info); 2601 info.protectionLevel = fixedLevel; 2602 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2603 bp.perm.info.packageName = tree.perm.info.packageName; 2604 bp.uid = tree.uid; 2605 if (added) { 2606 mSettings.mPermissions.put(info.name, bp); 2607 } 2608 if (changed) { 2609 if (!async) { 2610 mSettings.writeLPr(); 2611 } else { 2612 scheduleWriteSettingsLocked(); 2613 } 2614 } 2615 return added; 2616 } 2617 2618 @Override 2619 public boolean addPermission(PermissionInfo info) { 2620 synchronized (mPackages) { 2621 return addPermissionLocked(info, false); 2622 } 2623 } 2624 2625 @Override 2626 public boolean addPermissionAsync(PermissionInfo info) { 2627 synchronized (mPackages) { 2628 return addPermissionLocked(info, true); 2629 } 2630 } 2631 2632 @Override 2633 public void removePermission(String name) { 2634 synchronized (mPackages) { 2635 checkPermissionTreeLP(name); 2636 BasePermission bp = mSettings.mPermissions.get(name); 2637 if (bp != null) { 2638 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2639 throw new SecurityException( 2640 "Not allowed to modify non-dynamic permission " 2641 + name); 2642 } 2643 mSettings.mPermissions.remove(name); 2644 mSettings.writeLPr(); 2645 } 2646 } 2647 } 2648 2649 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 2650 BasePermission bp) { 2651 int index = pkg.requestedPermissions.indexOf(bp.name); 2652 if (index == -1) { 2653 throw new SecurityException("Package " + pkg.packageName 2654 + " has not requested permission " + bp.name); 2655 } 2656 if (!bp.isRuntime()) { 2657 throw new SecurityException("Permission " + bp.name 2658 + " is not a changeable permission type"); 2659 } 2660 } 2661 2662 @Override 2663 public boolean grantPermission(String packageName, String name, int userId) { 2664 if (!sUserManager.exists(userId)) { 2665 return false; 2666 } 2667 2668 mContext.enforceCallingOrSelfPermission( 2669 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2670 "grantPermission"); 2671 2672 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2673 "grantPermission"); 2674 2675 synchronized (mPackages) { 2676 final PackageParser.Package pkg = mPackages.get(packageName); 2677 if (pkg == null) { 2678 throw new IllegalArgumentException("Unknown package: " + packageName); 2679 } 2680 2681 final BasePermission bp = mSettings.mPermissions.get(name); 2682 if (bp == null) { 2683 throw new IllegalArgumentException("Unknown permission: " + name); 2684 } 2685 2686 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2687 2688 final SettingBase sb = (SettingBase) pkg.mExtras; 2689 if (sb == null) { 2690 throw new IllegalArgumentException("Unknown package: " + packageName); 2691 } 2692 2693 final PermissionsState permissionsState = sb.getPermissionsState(); 2694 2695 final int result = permissionsState.grantRuntimePermission(bp, userId); 2696 switch (result) { 2697 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 2698 return false; 2699 } 2700 2701 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 2702 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 2703 } break; 2704 } 2705 2706 // Not critical if that is lost - app has to request again. 2707 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 2708 2709 return true; 2710 } 2711 } 2712 2713 @Override 2714 public boolean revokePermission(String packageName, String name, int userId) { 2715 if (!sUserManager.exists(userId)) { 2716 return false; 2717 } 2718 2719 mContext.enforceCallingOrSelfPermission( 2720 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2721 "revokePermission"); 2722 2723 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2724 "revokePermission"); 2725 2726 synchronized (mPackages) { 2727 final PackageParser.Package pkg = mPackages.get(packageName); 2728 if (pkg == null) { 2729 throw new IllegalArgumentException("Unknown package: " + packageName); 2730 } 2731 2732 final BasePermission bp = mSettings.mPermissions.get(name); 2733 if (bp == null) { 2734 throw new IllegalArgumentException("Unknown permission: " + name); 2735 } 2736 2737 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2738 2739 final SettingBase sb = (SettingBase) pkg.mExtras; 2740 if (sb == null) { 2741 throw new IllegalArgumentException("Unknown package: " + packageName); 2742 } 2743 2744 final PermissionsState permissionsState = sb.getPermissionsState(); 2745 2746 if (permissionsState.revokeRuntimePermission(bp, userId) == 2747 PermissionsState.PERMISSION_OPERATION_FAILURE) { 2748 return false; 2749 } 2750 2751 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 2752 2753 // Critical, after this call all should never have the permission. 2754 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 2755 2756 return true; 2757 } 2758 } 2759 2760 @Override 2761 public boolean isProtectedBroadcast(String actionName) { 2762 synchronized (mPackages) { 2763 return mProtectedBroadcasts.contains(actionName); 2764 } 2765 } 2766 2767 @Override 2768 public int checkSignatures(String pkg1, String pkg2) { 2769 synchronized (mPackages) { 2770 final PackageParser.Package p1 = mPackages.get(pkg1); 2771 final PackageParser.Package p2 = mPackages.get(pkg2); 2772 if (p1 == null || p1.mExtras == null 2773 || p2 == null || p2.mExtras == null) { 2774 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2775 } 2776 return compareSignatures(p1.mSignatures, p2.mSignatures); 2777 } 2778 } 2779 2780 @Override 2781 public int checkUidSignatures(int uid1, int uid2) { 2782 // Map to base uids. 2783 uid1 = UserHandle.getAppId(uid1); 2784 uid2 = UserHandle.getAppId(uid2); 2785 // reader 2786 synchronized (mPackages) { 2787 Signature[] s1; 2788 Signature[] s2; 2789 Object obj = mSettings.getUserIdLPr(uid1); 2790 if (obj != null) { 2791 if (obj instanceof SharedUserSetting) { 2792 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2793 } else if (obj instanceof PackageSetting) { 2794 s1 = ((PackageSetting)obj).signatures.mSignatures; 2795 } else { 2796 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2797 } 2798 } else { 2799 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2800 } 2801 obj = mSettings.getUserIdLPr(uid2); 2802 if (obj != null) { 2803 if (obj instanceof SharedUserSetting) { 2804 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2805 } else if (obj instanceof PackageSetting) { 2806 s2 = ((PackageSetting)obj).signatures.mSignatures; 2807 } else { 2808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2809 } 2810 } else { 2811 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2812 } 2813 return compareSignatures(s1, s2); 2814 } 2815 } 2816 2817 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 2818 final long identity = Binder.clearCallingIdentity(); 2819 try { 2820 if (sb instanceof SharedUserSetting) { 2821 SharedUserSetting sus = (SharedUserSetting) sb; 2822 final int packageCount = sus.packages.size(); 2823 for (int i = 0; i < packageCount; i++) { 2824 PackageSetting susPs = sus.packages.valueAt(i); 2825 if (userId == UserHandle.USER_ALL) { 2826 killApplication(susPs.pkg.packageName, susPs.appId, reason); 2827 } else { 2828 final int uid = UserHandle.getUid(userId, susPs.appId); 2829 killUid(uid, reason); 2830 } 2831 } 2832 } else if (sb instanceof PackageSetting) { 2833 PackageSetting ps = (PackageSetting) sb; 2834 if (userId == UserHandle.USER_ALL) { 2835 killApplication(ps.pkg.packageName, ps.appId, reason); 2836 } else { 2837 final int uid = UserHandle.getUid(userId, ps.appId); 2838 killUid(uid, reason); 2839 } 2840 } 2841 } finally { 2842 Binder.restoreCallingIdentity(identity); 2843 } 2844 } 2845 2846 private static void killUid(int uid, String reason) { 2847 IActivityManager am = ActivityManagerNative.getDefault(); 2848 if (am != null) { 2849 try { 2850 am.killUid(uid, reason); 2851 } catch (RemoteException e) { 2852 /* ignore - same process */ 2853 } 2854 } 2855 } 2856 2857 /** 2858 * Compares two sets of signatures. Returns: 2859 * <br /> 2860 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2861 * <br /> 2862 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2863 * <br /> 2864 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2865 * <br /> 2866 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2867 * <br /> 2868 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2869 */ 2870 static int compareSignatures(Signature[] s1, Signature[] s2) { 2871 if (s1 == null) { 2872 return s2 == null 2873 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2874 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2875 } 2876 2877 if (s2 == null) { 2878 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2879 } 2880 2881 if (s1.length != s2.length) { 2882 return PackageManager.SIGNATURE_NO_MATCH; 2883 } 2884 2885 // Since both signature sets are of size 1, we can compare without HashSets. 2886 if (s1.length == 1) { 2887 return s1[0].equals(s2[0]) ? 2888 PackageManager.SIGNATURE_MATCH : 2889 PackageManager.SIGNATURE_NO_MATCH; 2890 } 2891 2892 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2893 for (Signature sig : s1) { 2894 set1.add(sig); 2895 } 2896 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2897 for (Signature sig : s2) { 2898 set2.add(sig); 2899 } 2900 // Make sure s2 contains all signatures in s1. 2901 if (set1.equals(set2)) { 2902 return PackageManager.SIGNATURE_MATCH; 2903 } 2904 return PackageManager.SIGNATURE_NO_MATCH; 2905 } 2906 2907 /** 2908 * If the database version for this type of package (internal storage or 2909 * external storage) is less than the version where package signatures 2910 * were updated, return true. 2911 */ 2912 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2913 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2914 DatabaseVersion.SIGNATURE_END_ENTITY)) 2915 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2916 DatabaseVersion.SIGNATURE_END_ENTITY)); 2917 } 2918 2919 /** 2920 * Used for backward compatibility to make sure any packages with 2921 * certificate chains get upgraded to the new style. {@code existingSigs} 2922 * will be in the old format (since they were stored on disk from before the 2923 * system upgrade) and {@code scannedSigs} will be in the newer format. 2924 */ 2925 private int compareSignaturesCompat(PackageSignatures existingSigs, 2926 PackageParser.Package scannedPkg) { 2927 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2928 return PackageManager.SIGNATURE_NO_MATCH; 2929 } 2930 2931 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2932 for (Signature sig : existingSigs.mSignatures) { 2933 existingSet.add(sig); 2934 } 2935 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2936 for (Signature sig : scannedPkg.mSignatures) { 2937 try { 2938 Signature[] chainSignatures = sig.getChainSignatures(); 2939 for (Signature chainSig : chainSignatures) { 2940 scannedCompatSet.add(chainSig); 2941 } 2942 } catch (CertificateEncodingException e) { 2943 scannedCompatSet.add(sig); 2944 } 2945 } 2946 /* 2947 * Make sure the expanded scanned set contains all signatures in the 2948 * existing one. 2949 */ 2950 if (scannedCompatSet.equals(existingSet)) { 2951 // Migrate the old signatures to the new scheme. 2952 existingSigs.assignSignatures(scannedPkg.mSignatures); 2953 // The new KeySets will be re-added later in the scanning process. 2954 synchronized (mPackages) { 2955 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2956 } 2957 return PackageManager.SIGNATURE_MATCH; 2958 } 2959 return PackageManager.SIGNATURE_NO_MATCH; 2960 } 2961 2962 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2963 if (isExternal(scannedPkg)) { 2964 return mSettings.isExternalDatabaseVersionOlderThan( 2965 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2966 } else { 2967 return mSettings.isInternalDatabaseVersionOlderThan( 2968 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2969 } 2970 } 2971 2972 private int compareSignaturesRecover(PackageSignatures existingSigs, 2973 PackageParser.Package scannedPkg) { 2974 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2975 return PackageManager.SIGNATURE_NO_MATCH; 2976 } 2977 2978 String msg = null; 2979 try { 2980 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2981 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2982 + scannedPkg.packageName); 2983 return PackageManager.SIGNATURE_MATCH; 2984 } 2985 } catch (CertificateException e) { 2986 msg = e.getMessage(); 2987 } 2988 2989 logCriticalInfo(Log.INFO, 2990 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2991 return PackageManager.SIGNATURE_NO_MATCH; 2992 } 2993 2994 @Override 2995 public String[] getPackagesForUid(int uid) { 2996 uid = UserHandle.getAppId(uid); 2997 // reader 2998 synchronized (mPackages) { 2999 Object obj = mSettings.getUserIdLPr(uid); 3000 if (obj instanceof SharedUserSetting) { 3001 final SharedUserSetting sus = (SharedUserSetting) obj; 3002 final int N = sus.packages.size(); 3003 final String[] res = new String[N]; 3004 final Iterator<PackageSetting> it = sus.packages.iterator(); 3005 int i = 0; 3006 while (it.hasNext()) { 3007 res[i++] = it.next().name; 3008 } 3009 return res; 3010 } else if (obj instanceof PackageSetting) { 3011 final PackageSetting ps = (PackageSetting) obj; 3012 return new String[] { ps.name }; 3013 } 3014 } 3015 return null; 3016 } 3017 3018 @Override 3019 public String getNameForUid(int uid) { 3020 // reader 3021 synchronized (mPackages) { 3022 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3023 if (obj instanceof SharedUserSetting) { 3024 final SharedUserSetting sus = (SharedUserSetting) obj; 3025 return sus.name + ":" + sus.userId; 3026 } else if (obj instanceof PackageSetting) { 3027 final PackageSetting ps = (PackageSetting) obj; 3028 return ps.name; 3029 } 3030 } 3031 return null; 3032 } 3033 3034 @Override 3035 public int getUidForSharedUser(String sharedUserName) { 3036 if(sharedUserName == null) { 3037 return -1; 3038 } 3039 // reader 3040 synchronized (mPackages) { 3041 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3042 if (suid == null) { 3043 return -1; 3044 } 3045 return suid.userId; 3046 } 3047 } 3048 3049 @Override 3050 public int getFlagsForUid(int uid) { 3051 synchronized (mPackages) { 3052 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3053 if (obj instanceof SharedUserSetting) { 3054 final SharedUserSetting sus = (SharedUserSetting) obj; 3055 return sus.pkgFlags; 3056 } else if (obj instanceof PackageSetting) { 3057 final PackageSetting ps = (PackageSetting) obj; 3058 return ps.pkgFlags; 3059 } 3060 } 3061 return 0; 3062 } 3063 3064 @Override 3065 public int getPrivateFlagsForUid(int uid) { 3066 synchronized (mPackages) { 3067 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3068 if (obj instanceof SharedUserSetting) { 3069 final SharedUserSetting sus = (SharedUserSetting) obj; 3070 return sus.pkgPrivateFlags; 3071 } else if (obj instanceof PackageSetting) { 3072 final PackageSetting ps = (PackageSetting) obj; 3073 return ps.pkgPrivateFlags; 3074 } 3075 } 3076 return 0; 3077 } 3078 3079 @Override 3080 public boolean isUidPrivileged(int uid) { 3081 uid = UserHandle.getAppId(uid); 3082 // reader 3083 synchronized (mPackages) { 3084 Object obj = mSettings.getUserIdLPr(uid); 3085 if (obj instanceof SharedUserSetting) { 3086 final SharedUserSetting sus = (SharedUserSetting) obj; 3087 final Iterator<PackageSetting> it = sus.packages.iterator(); 3088 while (it.hasNext()) { 3089 if (it.next().isPrivileged()) { 3090 return true; 3091 } 3092 } 3093 } else if (obj instanceof PackageSetting) { 3094 final PackageSetting ps = (PackageSetting) obj; 3095 return ps.isPrivileged(); 3096 } 3097 } 3098 return false; 3099 } 3100 3101 @Override 3102 public String[] getAppOpPermissionPackages(String permissionName) { 3103 synchronized (mPackages) { 3104 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3105 if (pkgs == null) { 3106 return null; 3107 } 3108 return pkgs.toArray(new String[pkgs.size()]); 3109 } 3110 } 3111 3112 @Override 3113 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3114 int flags, int userId) { 3115 if (!sUserManager.exists(userId)) return null; 3116 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3117 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3118 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3119 } 3120 3121 @Override 3122 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3123 IntentFilter filter, int match, ComponentName activity) { 3124 final int userId = UserHandle.getCallingUserId(); 3125 if (DEBUG_PREFERRED) { 3126 Log.v(TAG, "setLastChosenActivity intent=" + intent 3127 + " resolvedType=" + resolvedType 3128 + " flags=" + flags 3129 + " filter=" + filter 3130 + " match=" + match 3131 + " activity=" + activity); 3132 filter.dump(new PrintStreamPrinter(System.out), " "); 3133 } 3134 intent.setComponent(null); 3135 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3136 // Find any earlier preferred or last chosen entries and nuke them 3137 findPreferredActivity(intent, resolvedType, 3138 flags, query, 0, false, true, false, userId); 3139 // Add the new activity as the last chosen for this filter 3140 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3141 "Setting last chosen"); 3142 } 3143 3144 @Override 3145 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3146 final int userId = UserHandle.getCallingUserId(); 3147 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3148 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3149 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3150 false, false, false, userId); 3151 } 3152 3153 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3154 int flags, List<ResolveInfo> query, int userId) { 3155 if (query != null) { 3156 final int N = query.size(); 3157 if (N == 1) { 3158 return query.get(0); 3159 } else if (N > 1) { 3160 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3161 // If there is more than one activity with the same priority, 3162 // then let the user decide between them. 3163 ResolveInfo r0 = query.get(0); 3164 ResolveInfo r1 = query.get(1); 3165 if (DEBUG_INTENT_MATCHING || debug) { 3166 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3167 + r1.activityInfo.name + "=" + r1.priority); 3168 } 3169 // If the first activity has a higher priority, or a different 3170 // default, then it is always desireable to pick it. 3171 if (r0.priority != r1.priority 3172 || r0.preferredOrder != r1.preferredOrder 3173 || r0.isDefault != r1.isDefault) { 3174 return query.get(0); 3175 } 3176 // If we have saved a preference for a preferred activity for 3177 // this Intent, use that. 3178 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3179 flags, query, r0.priority, true, false, debug, userId); 3180 if (ri != null) { 3181 return ri; 3182 } 3183 if (userId != 0) { 3184 ri = new ResolveInfo(mResolveInfo); 3185 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3186 ri.activityInfo.applicationInfo = new ApplicationInfo( 3187 ri.activityInfo.applicationInfo); 3188 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3189 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3190 return ri; 3191 } 3192 return mResolveInfo; 3193 } 3194 } 3195 return null; 3196 } 3197 3198 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3199 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3200 final int N = query.size(); 3201 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3202 .get(userId); 3203 // Get the list of persistent preferred activities that handle the intent 3204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3205 List<PersistentPreferredActivity> pprefs = ppir != null 3206 ? ppir.queryIntent(intent, resolvedType, 3207 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3208 : null; 3209 if (pprefs != null && pprefs.size() > 0) { 3210 final int M = pprefs.size(); 3211 for (int i=0; i<M; i++) { 3212 final PersistentPreferredActivity ppa = pprefs.get(i); 3213 if (DEBUG_PREFERRED || debug) { 3214 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3215 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3216 + "\n component=" + ppa.mComponent); 3217 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3218 } 3219 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3220 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3221 if (DEBUG_PREFERRED || debug) { 3222 Slog.v(TAG, "Found persistent preferred activity:"); 3223 if (ai != null) { 3224 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3225 } else { 3226 Slog.v(TAG, " null"); 3227 } 3228 } 3229 if (ai == null) { 3230 // This previously registered persistent preferred activity 3231 // component is no longer known. Ignore it and do NOT remove it. 3232 continue; 3233 } 3234 for (int j=0; j<N; j++) { 3235 final ResolveInfo ri = query.get(j); 3236 if (!ri.activityInfo.applicationInfo.packageName 3237 .equals(ai.applicationInfo.packageName)) { 3238 continue; 3239 } 3240 if (!ri.activityInfo.name.equals(ai.name)) { 3241 continue; 3242 } 3243 // Found a persistent preference that can handle the intent. 3244 if (DEBUG_PREFERRED || debug) { 3245 Slog.v(TAG, "Returning persistent preferred activity: " + 3246 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3247 } 3248 return ri; 3249 } 3250 } 3251 } 3252 return null; 3253 } 3254 3255 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3256 List<ResolveInfo> query, int priority, boolean always, 3257 boolean removeMatches, boolean debug, int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 // writer 3260 synchronized (mPackages) { 3261 if (intent.getSelector() != null) { 3262 intent = intent.getSelector(); 3263 } 3264 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3265 3266 // Try to find a matching persistent preferred activity. 3267 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3268 debug, userId); 3269 3270 // If a persistent preferred activity matched, use it. 3271 if (pri != null) { 3272 return pri; 3273 } 3274 3275 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3276 // Get the list of preferred activities that handle the intent 3277 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3278 List<PreferredActivity> prefs = pir != null 3279 ? pir.queryIntent(intent, resolvedType, 3280 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3281 : null; 3282 if (prefs != null && prefs.size() > 0) { 3283 boolean changed = false; 3284 try { 3285 // First figure out how good the original match set is. 3286 // We will only allow preferred activities that came 3287 // from the same match quality. 3288 int match = 0; 3289 3290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3291 3292 final int N = query.size(); 3293 for (int j=0; j<N; j++) { 3294 final ResolveInfo ri = query.get(j); 3295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3296 + ": 0x" + Integer.toHexString(match)); 3297 if (ri.match > match) { 3298 match = ri.match; 3299 } 3300 } 3301 3302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3303 + Integer.toHexString(match)); 3304 3305 match &= IntentFilter.MATCH_CATEGORY_MASK; 3306 final int M = prefs.size(); 3307 for (int i=0; i<M; i++) { 3308 final PreferredActivity pa = prefs.get(i); 3309 if (DEBUG_PREFERRED || debug) { 3310 Slog.v(TAG, "Checking PreferredActivity ds=" 3311 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3312 + "\n component=" + pa.mPref.mComponent); 3313 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3314 } 3315 if (pa.mPref.mMatch != match) { 3316 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3317 + Integer.toHexString(pa.mPref.mMatch)); 3318 continue; 3319 } 3320 // If it's not an "always" type preferred activity and that's what we're 3321 // looking for, skip it. 3322 if (always && !pa.mPref.mAlways) { 3323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3324 continue; 3325 } 3326 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3327 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3328 if (DEBUG_PREFERRED || debug) { 3329 Slog.v(TAG, "Found preferred activity:"); 3330 if (ai != null) { 3331 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3332 } else { 3333 Slog.v(TAG, " null"); 3334 } 3335 } 3336 if (ai == null) { 3337 // This previously registered preferred activity 3338 // component is no longer known. Most likely an update 3339 // to the app was installed and in the new version this 3340 // component no longer exists. Clean it up by removing 3341 // it from the preferred activities list, and skip it. 3342 Slog.w(TAG, "Removing dangling preferred activity: " 3343 + pa.mPref.mComponent); 3344 pir.removeFilter(pa); 3345 changed = true; 3346 continue; 3347 } 3348 for (int j=0; j<N; j++) { 3349 final ResolveInfo ri = query.get(j); 3350 if (!ri.activityInfo.applicationInfo.packageName 3351 .equals(ai.applicationInfo.packageName)) { 3352 continue; 3353 } 3354 if (!ri.activityInfo.name.equals(ai.name)) { 3355 continue; 3356 } 3357 3358 if (removeMatches) { 3359 pir.removeFilter(pa); 3360 changed = true; 3361 if (DEBUG_PREFERRED) { 3362 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3363 } 3364 break; 3365 } 3366 3367 // Okay we found a previously set preferred or last chosen app. 3368 // If the result set is different from when this 3369 // was created, we need to clear it and re-ask the 3370 // user their preference, if we're looking for an "always" type entry. 3371 if (always && !pa.mPref.sameSet(query)) { 3372 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3373 + intent + " type " + resolvedType); 3374 if (DEBUG_PREFERRED) { 3375 Slog.v(TAG, "Removing preferred activity since set changed " 3376 + pa.mPref.mComponent); 3377 } 3378 pir.removeFilter(pa); 3379 // Re-add the filter as a "last chosen" entry (!always) 3380 PreferredActivity lastChosen = new PreferredActivity( 3381 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3382 pir.addFilter(lastChosen); 3383 changed = true; 3384 return null; 3385 } 3386 3387 // Yay! Either the set matched or we're looking for the last chosen 3388 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3389 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3390 return ri; 3391 } 3392 } 3393 } finally { 3394 if (changed) { 3395 if (DEBUG_PREFERRED) { 3396 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3397 } 3398 scheduleWritePackageRestrictionsLocked(userId); 3399 } 3400 } 3401 } 3402 } 3403 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3404 return null; 3405 } 3406 3407 /* 3408 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3409 */ 3410 @Override 3411 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3412 int targetUserId) { 3413 mContext.enforceCallingOrSelfPermission( 3414 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3415 List<CrossProfileIntentFilter> matches = 3416 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3417 if (matches != null) { 3418 int size = matches.size(); 3419 for (int i = 0; i < size; i++) { 3420 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3421 } 3422 } 3423 return false; 3424 } 3425 3426 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3427 String resolvedType, int userId) { 3428 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3429 if (resolver != null) { 3430 return resolver.queryIntent(intent, resolvedType, false, userId); 3431 } 3432 return null; 3433 } 3434 3435 @Override 3436 public List<ResolveInfo> queryIntentActivities(Intent intent, 3437 String resolvedType, int flags, int userId) { 3438 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3439 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3440 ComponentName comp = intent.getComponent(); 3441 if (comp == null) { 3442 if (intent.getSelector() != null) { 3443 intent = intent.getSelector(); 3444 comp = intent.getComponent(); 3445 } 3446 } 3447 3448 if (comp != null) { 3449 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3450 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3451 if (ai != null) { 3452 final ResolveInfo ri = new ResolveInfo(); 3453 ri.activityInfo = ai; 3454 list.add(ri); 3455 } 3456 return list; 3457 } 3458 3459 // reader 3460 synchronized (mPackages) { 3461 final String pkgName = intent.getPackage(); 3462 if (pkgName == null) { 3463 List<CrossProfileIntentFilter> matchingFilters = 3464 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3465 // Check for results that need to skip the current profile. 3466 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3467 resolvedType, flags, userId); 3468 if (resolveInfo != null) { 3469 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3470 result.add(resolveInfo); 3471 return filterIfNotPrimaryUser(result, userId); 3472 } 3473 // Check for cross profile results. 3474 resolveInfo = queryCrossProfileIntents( 3475 matchingFilters, intent, resolvedType, flags, userId); 3476 3477 // Check for results in the current profile. 3478 List<ResolveInfo> result = mActivities.queryIntent( 3479 intent, resolvedType, flags, userId); 3480 if (resolveInfo != null) { 3481 result.add(resolveInfo); 3482 Collections.sort(result, mResolvePrioritySorter); 3483 } 3484 return filterIfNotPrimaryUser(result, userId); 3485 } 3486 final PackageParser.Package pkg = mPackages.get(pkgName); 3487 if (pkg != null) { 3488 return filterIfNotPrimaryUser( 3489 mActivities.queryIntentForPackage( 3490 intent, resolvedType, flags, pkg.activities, userId), 3491 userId); 3492 } 3493 return new ArrayList<ResolveInfo>(); 3494 } 3495 } 3496 3497 /** 3498 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3499 * 3500 * @return filtered list 3501 */ 3502 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3503 if (userId == UserHandle.USER_OWNER) { 3504 return resolveInfos; 3505 } 3506 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3507 ResolveInfo info = resolveInfos.get(i); 3508 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3509 resolveInfos.remove(i); 3510 } 3511 } 3512 return resolveInfos; 3513 } 3514 3515 3516 private ResolveInfo querySkipCurrentProfileIntents( 3517 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3518 int flags, int sourceUserId) { 3519 if (matchingFilters != null) { 3520 int size = matchingFilters.size(); 3521 for (int i = 0; i < size; i ++) { 3522 CrossProfileIntentFilter filter = matchingFilters.get(i); 3523 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3524 // Checking if there are activities in the target user that can handle the 3525 // intent. 3526 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3527 flags, sourceUserId); 3528 if (resolveInfo != null) { 3529 return resolveInfo; 3530 } 3531 } 3532 } 3533 } 3534 return null; 3535 } 3536 3537 // Return matching ResolveInfo if any for skip current profile intent filters. 3538 private ResolveInfo queryCrossProfileIntents( 3539 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3540 int flags, int sourceUserId) { 3541 if (matchingFilters != null) { 3542 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3543 // match the same intent. For performance reasons, it is better not to 3544 // run queryIntent twice for the same userId 3545 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3546 int size = matchingFilters.size(); 3547 for (int i = 0; i < size; i++) { 3548 CrossProfileIntentFilter filter = matchingFilters.get(i); 3549 int targetUserId = filter.getTargetUserId(); 3550 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3551 && !alreadyTriedUserIds.get(targetUserId)) { 3552 // Checking if there are activities in the target user that can handle the 3553 // intent. 3554 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3555 flags, sourceUserId); 3556 if (resolveInfo != null) return resolveInfo; 3557 alreadyTriedUserIds.put(targetUserId, true); 3558 } 3559 } 3560 } 3561 return null; 3562 } 3563 3564 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3565 String resolvedType, int flags, int sourceUserId) { 3566 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3567 resolvedType, flags, filter.getTargetUserId()); 3568 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3569 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3570 } 3571 return null; 3572 } 3573 3574 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3575 int sourceUserId, int targetUserId) { 3576 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3577 String className; 3578 if (targetUserId == UserHandle.USER_OWNER) { 3579 className = FORWARD_INTENT_TO_USER_OWNER; 3580 } else { 3581 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3582 } 3583 ComponentName forwardingActivityComponentName = new ComponentName( 3584 mAndroidApplication.packageName, className); 3585 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3586 sourceUserId); 3587 if (targetUserId == UserHandle.USER_OWNER) { 3588 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3589 forwardingResolveInfo.noResourceId = true; 3590 } 3591 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3592 forwardingResolveInfo.priority = 0; 3593 forwardingResolveInfo.preferredOrder = 0; 3594 forwardingResolveInfo.match = 0; 3595 forwardingResolveInfo.isDefault = true; 3596 forwardingResolveInfo.filter = filter; 3597 forwardingResolveInfo.targetUserId = targetUserId; 3598 return forwardingResolveInfo; 3599 } 3600 3601 @Override 3602 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3603 Intent[] specifics, String[] specificTypes, Intent intent, 3604 String resolvedType, int flags, int userId) { 3605 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3607 false, "query intent activity options"); 3608 final String resultsAction = intent.getAction(); 3609 3610 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3611 | PackageManager.GET_RESOLVED_FILTER, userId); 3612 3613 if (DEBUG_INTENT_MATCHING) { 3614 Log.v(TAG, "Query " + intent + ": " + results); 3615 } 3616 3617 int specificsPos = 0; 3618 int N; 3619 3620 // todo: note that the algorithm used here is O(N^2). This 3621 // isn't a problem in our current environment, but if we start running 3622 // into situations where we have more than 5 or 10 matches then this 3623 // should probably be changed to something smarter... 3624 3625 // First we go through and resolve each of the specific items 3626 // that were supplied, taking care of removing any corresponding 3627 // duplicate items in the generic resolve list. 3628 if (specifics != null) { 3629 for (int i=0; i<specifics.length; i++) { 3630 final Intent sintent = specifics[i]; 3631 if (sintent == null) { 3632 continue; 3633 } 3634 3635 if (DEBUG_INTENT_MATCHING) { 3636 Log.v(TAG, "Specific #" + i + ": " + sintent); 3637 } 3638 3639 String action = sintent.getAction(); 3640 if (resultsAction != null && resultsAction.equals(action)) { 3641 // If this action was explicitly requested, then don't 3642 // remove things that have it. 3643 action = null; 3644 } 3645 3646 ResolveInfo ri = null; 3647 ActivityInfo ai = null; 3648 3649 ComponentName comp = sintent.getComponent(); 3650 if (comp == null) { 3651 ri = resolveIntent( 3652 sintent, 3653 specificTypes != null ? specificTypes[i] : null, 3654 flags, userId); 3655 if (ri == null) { 3656 continue; 3657 } 3658 if (ri == mResolveInfo) { 3659 // ACK! Must do something better with this. 3660 } 3661 ai = ri.activityInfo; 3662 comp = new ComponentName(ai.applicationInfo.packageName, 3663 ai.name); 3664 } else { 3665 ai = getActivityInfo(comp, flags, userId); 3666 if (ai == null) { 3667 continue; 3668 } 3669 } 3670 3671 // Look for any generic query activities that are duplicates 3672 // of this specific one, and remove them from the results. 3673 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3674 N = results.size(); 3675 int j; 3676 for (j=specificsPos; j<N; j++) { 3677 ResolveInfo sri = results.get(j); 3678 if ((sri.activityInfo.name.equals(comp.getClassName()) 3679 && sri.activityInfo.applicationInfo.packageName.equals( 3680 comp.getPackageName())) 3681 || (action != null && sri.filter.matchAction(action))) { 3682 results.remove(j); 3683 if (DEBUG_INTENT_MATCHING) Log.v( 3684 TAG, "Removing duplicate item from " + j 3685 + " due to specific " + specificsPos); 3686 if (ri == null) { 3687 ri = sri; 3688 } 3689 j--; 3690 N--; 3691 } 3692 } 3693 3694 // Add this specific item to its proper place. 3695 if (ri == null) { 3696 ri = new ResolveInfo(); 3697 ri.activityInfo = ai; 3698 } 3699 results.add(specificsPos, ri); 3700 ri.specificIndex = i; 3701 specificsPos++; 3702 } 3703 } 3704 3705 // Now we go through the remaining generic results and remove any 3706 // duplicate actions that are found here. 3707 N = results.size(); 3708 for (int i=specificsPos; i<N-1; i++) { 3709 final ResolveInfo rii = results.get(i); 3710 if (rii.filter == null) { 3711 continue; 3712 } 3713 3714 // Iterate over all of the actions of this result's intent 3715 // filter... typically this should be just one. 3716 final Iterator<String> it = rii.filter.actionsIterator(); 3717 if (it == null) { 3718 continue; 3719 } 3720 while (it.hasNext()) { 3721 final String action = it.next(); 3722 if (resultsAction != null && resultsAction.equals(action)) { 3723 // If this action was explicitly requested, then don't 3724 // remove things that have it. 3725 continue; 3726 } 3727 for (int j=i+1; j<N; j++) { 3728 final ResolveInfo rij = results.get(j); 3729 if (rij.filter != null && rij.filter.hasAction(action)) { 3730 results.remove(j); 3731 if (DEBUG_INTENT_MATCHING) Log.v( 3732 TAG, "Removing duplicate item from " + j 3733 + " due to action " + action + " at " + i); 3734 j--; 3735 N--; 3736 } 3737 } 3738 } 3739 3740 // If the caller didn't request filter information, drop it now 3741 // so we don't have to marshall/unmarshall it. 3742 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3743 rii.filter = null; 3744 } 3745 } 3746 3747 // Filter out the caller activity if so requested. 3748 if (caller != null) { 3749 N = results.size(); 3750 for (int i=0; i<N; i++) { 3751 ActivityInfo ainfo = results.get(i).activityInfo; 3752 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3753 && caller.getClassName().equals(ainfo.name)) { 3754 results.remove(i); 3755 break; 3756 } 3757 } 3758 } 3759 3760 // If the caller didn't request filter information, 3761 // drop them now so we don't have to 3762 // marshall/unmarshall it. 3763 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3764 N = results.size(); 3765 for (int i=0; i<N; i++) { 3766 results.get(i).filter = null; 3767 } 3768 } 3769 3770 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3771 return results; 3772 } 3773 3774 @Override 3775 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3776 int userId) { 3777 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3778 ComponentName comp = intent.getComponent(); 3779 if (comp == null) { 3780 if (intent.getSelector() != null) { 3781 intent = intent.getSelector(); 3782 comp = intent.getComponent(); 3783 } 3784 } 3785 if (comp != null) { 3786 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3787 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3788 if (ai != null) { 3789 ResolveInfo ri = new ResolveInfo(); 3790 ri.activityInfo = ai; 3791 list.add(ri); 3792 } 3793 return list; 3794 } 3795 3796 // reader 3797 synchronized (mPackages) { 3798 String pkgName = intent.getPackage(); 3799 if (pkgName == null) { 3800 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3801 } 3802 final PackageParser.Package pkg = mPackages.get(pkgName); 3803 if (pkg != null) { 3804 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3805 userId); 3806 } 3807 return null; 3808 } 3809 } 3810 3811 @Override 3812 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3813 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3814 if (!sUserManager.exists(userId)) return null; 3815 if (query != null) { 3816 if (query.size() >= 1) { 3817 // If there is more than one service with the same priority, 3818 // just arbitrarily pick the first one. 3819 return query.get(0); 3820 } 3821 } 3822 return null; 3823 } 3824 3825 @Override 3826 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3827 int userId) { 3828 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3829 ComponentName comp = intent.getComponent(); 3830 if (comp == null) { 3831 if (intent.getSelector() != null) { 3832 intent = intent.getSelector(); 3833 comp = intent.getComponent(); 3834 } 3835 } 3836 if (comp != null) { 3837 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3838 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3839 if (si != null) { 3840 final ResolveInfo ri = new ResolveInfo(); 3841 ri.serviceInfo = si; 3842 list.add(ri); 3843 } 3844 return list; 3845 } 3846 3847 // reader 3848 synchronized (mPackages) { 3849 String pkgName = intent.getPackage(); 3850 if (pkgName == null) { 3851 return mServices.queryIntent(intent, resolvedType, flags, userId); 3852 } 3853 final PackageParser.Package pkg = mPackages.get(pkgName); 3854 if (pkg != null) { 3855 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3856 userId); 3857 } 3858 return null; 3859 } 3860 } 3861 3862 @Override 3863 public List<ResolveInfo> queryIntentContentProviders( 3864 Intent intent, String resolvedType, int flags, int userId) { 3865 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3866 ComponentName comp = intent.getComponent(); 3867 if (comp == null) { 3868 if (intent.getSelector() != null) { 3869 intent = intent.getSelector(); 3870 comp = intent.getComponent(); 3871 } 3872 } 3873 if (comp != null) { 3874 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3875 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3876 if (pi != null) { 3877 final ResolveInfo ri = new ResolveInfo(); 3878 ri.providerInfo = pi; 3879 list.add(ri); 3880 } 3881 return list; 3882 } 3883 3884 // reader 3885 synchronized (mPackages) { 3886 String pkgName = intent.getPackage(); 3887 if (pkgName == null) { 3888 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3889 } 3890 final PackageParser.Package pkg = mPackages.get(pkgName); 3891 if (pkg != null) { 3892 return mProviders.queryIntentForPackage( 3893 intent, resolvedType, flags, pkg.providers, userId); 3894 } 3895 return null; 3896 } 3897 } 3898 3899 @Override 3900 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3901 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3902 3903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3904 3905 // writer 3906 synchronized (mPackages) { 3907 ArrayList<PackageInfo> list; 3908 if (listUninstalled) { 3909 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3910 for (PackageSetting ps : mSettings.mPackages.values()) { 3911 PackageInfo pi; 3912 if (ps.pkg != null) { 3913 pi = generatePackageInfo(ps.pkg, flags, userId); 3914 } else { 3915 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3916 } 3917 if (pi != null) { 3918 list.add(pi); 3919 } 3920 } 3921 } else { 3922 list = new ArrayList<PackageInfo>(mPackages.size()); 3923 for (PackageParser.Package p : mPackages.values()) { 3924 PackageInfo pi = generatePackageInfo(p, flags, userId); 3925 if (pi != null) { 3926 list.add(pi); 3927 } 3928 } 3929 } 3930 3931 return new ParceledListSlice<PackageInfo>(list); 3932 } 3933 } 3934 3935 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3936 String[] permissions, boolean[] tmp, int flags, int userId) { 3937 int numMatch = 0; 3938 final PermissionsState permissionsState = ps.getPermissionsState(); 3939 for (int i=0; i<permissions.length; i++) { 3940 final String permission = permissions[i]; 3941 if (permissionsState.hasPermission(permission, userId)) { 3942 tmp[i] = true; 3943 numMatch++; 3944 } else { 3945 tmp[i] = false; 3946 } 3947 } 3948 if (numMatch == 0) { 3949 return; 3950 } 3951 PackageInfo pi; 3952 if (ps.pkg != null) { 3953 pi = generatePackageInfo(ps.pkg, flags, userId); 3954 } else { 3955 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3956 } 3957 // The above might return null in cases of uninstalled apps or install-state 3958 // skew across users/profiles. 3959 if (pi != null) { 3960 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3961 if (numMatch == permissions.length) { 3962 pi.requestedPermissions = permissions; 3963 } else { 3964 pi.requestedPermissions = new String[numMatch]; 3965 numMatch = 0; 3966 for (int i=0; i<permissions.length; i++) { 3967 if (tmp[i]) { 3968 pi.requestedPermissions[numMatch] = permissions[i]; 3969 numMatch++; 3970 } 3971 } 3972 } 3973 } 3974 list.add(pi); 3975 } 3976 } 3977 3978 @Override 3979 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3980 String[] permissions, int flags, int userId) { 3981 if (!sUserManager.exists(userId)) return null; 3982 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3983 3984 // writer 3985 synchronized (mPackages) { 3986 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3987 boolean[] tmpBools = new boolean[permissions.length]; 3988 if (listUninstalled) { 3989 for (PackageSetting ps : mSettings.mPackages.values()) { 3990 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3991 } 3992 } else { 3993 for (PackageParser.Package pkg : mPackages.values()) { 3994 PackageSetting ps = (PackageSetting)pkg.mExtras; 3995 if (ps != null) { 3996 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3997 userId); 3998 } 3999 } 4000 } 4001 4002 return new ParceledListSlice<PackageInfo>(list); 4003 } 4004 } 4005 4006 @Override 4007 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4008 if (!sUserManager.exists(userId)) return null; 4009 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4010 4011 // writer 4012 synchronized (mPackages) { 4013 ArrayList<ApplicationInfo> list; 4014 if (listUninstalled) { 4015 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4016 for (PackageSetting ps : mSettings.mPackages.values()) { 4017 ApplicationInfo ai; 4018 if (ps.pkg != null) { 4019 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4020 ps.readUserState(userId), userId); 4021 } else { 4022 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4023 } 4024 if (ai != null) { 4025 list.add(ai); 4026 } 4027 } 4028 } else { 4029 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4030 for (PackageParser.Package p : mPackages.values()) { 4031 if (p.mExtras != null) { 4032 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4033 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4034 if (ai != null) { 4035 list.add(ai); 4036 } 4037 } 4038 } 4039 } 4040 4041 return new ParceledListSlice<ApplicationInfo>(list); 4042 } 4043 } 4044 4045 public List<ApplicationInfo> getPersistentApplications(int flags) { 4046 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4047 4048 // reader 4049 synchronized (mPackages) { 4050 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4051 final int userId = UserHandle.getCallingUserId(); 4052 while (i.hasNext()) { 4053 final PackageParser.Package p = i.next(); 4054 if (p.applicationInfo != null 4055 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4056 && (!mSafeMode || isSystemApp(p))) { 4057 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4058 if (ps != null) { 4059 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4060 ps.readUserState(userId), userId); 4061 if (ai != null) { 4062 finalList.add(ai); 4063 } 4064 } 4065 } 4066 } 4067 } 4068 4069 return finalList; 4070 } 4071 4072 @Override 4073 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4074 if (!sUserManager.exists(userId)) return null; 4075 // reader 4076 synchronized (mPackages) { 4077 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4078 PackageSetting ps = provider != null 4079 ? mSettings.mPackages.get(provider.owner.packageName) 4080 : null; 4081 return ps != null 4082 && mSettings.isEnabledLPr(provider.info, flags, userId) 4083 && (!mSafeMode || (provider.info.applicationInfo.flags 4084 &ApplicationInfo.FLAG_SYSTEM) != 0) 4085 ? PackageParser.generateProviderInfo(provider, flags, 4086 ps.readUserState(userId), userId) 4087 : null; 4088 } 4089 } 4090 4091 /** 4092 * @deprecated 4093 */ 4094 @Deprecated 4095 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4096 // reader 4097 synchronized (mPackages) { 4098 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4099 .entrySet().iterator(); 4100 final int userId = UserHandle.getCallingUserId(); 4101 while (i.hasNext()) { 4102 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4103 PackageParser.Provider p = entry.getValue(); 4104 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4105 4106 if (ps != null && p.syncable 4107 && (!mSafeMode || (p.info.applicationInfo.flags 4108 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4109 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4110 ps.readUserState(userId), userId); 4111 if (info != null) { 4112 outNames.add(entry.getKey()); 4113 outInfo.add(info); 4114 } 4115 } 4116 } 4117 } 4118 } 4119 4120 @Override 4121 public List<ProviderInfo> queryContentProviders(String processName, 4122 int uid, int flags) { 4123 ArrayList<ProviderInfo> finalList = null; 4124 // reader 4125 synchronized (mPackages) { 4126 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4127 final int userId = processName != null ? 4128 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4129 while (i.hasNext()) { 4130 final PackageParser.Provider p = i.next(); 4131 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4132 if (ps != null && p.info.authority != null 4133 && (processName == null 4134 || (p.info.processName.equals(processName) 4135 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4136 && mSettings.isEnabledLPr(p.info, flags, userId) 4137 && (!mSafeMode 4138 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4139 if (finalList == null) { 4140 finalList = new ArrayList<ProviderInfo>(3); 4141 } 4142 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4143 ps.readUserState(userId), userId); 4144 if (info != null) { 4145 finalList.add(info); 4146 } 4147 } 4148 } 4149 } 4150 4151 if (finalList != null) { 4152 Collections.sort(finalList, mProviderInitOrderSorter); 4153 } 4154 4155 return finalList; 4156 } 4157 4158 @Override 4159 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4160 int flags) { 4161 // reader 4162 synchronized (mPackages) { 4163 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4164 return PackageParser.generateInstrumentationInfo(i, flags); 4165 } 4166 } 4167 4168 @Override 4169 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4170 int flags) { 4171 ArrayList<InstrumentationInfo> finalList = 4172 new ArrayList<InstrumentationInfo>(); 4173 4174 // reader 4175 synchronized (mPackages) { 4176 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4177 while (i.hasNext()) { 4178 final PackageParser.Instrumentation p = i.next(); 4179 if (targetPackage == null 4180 || targetPackage.equals(p.info.targetPackage)) { 4181 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4182 flags); 4183 if (ii != null) { 4184 finalList.add(ii); 4185 } 4186 } 4187 } 4188 } 4189 4190 return finalList; 4191 } 4192 4193 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4194 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4195 if (overlays == null) { 4196 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4197 return; 4198 } 4199 for (PackageParser.Package opkg : overlays.values()) { 4200 // Not much to do if idmap fails: we already logged the error 4201 // and we certainly don't want to abort installation of pkg simply 4202 // because an overlay didn't fit properly. For these reasons, 4203 // ignore the return value of createIdmapForPackagePairLI. 4204 createIdmapForPackagePairLI(pkg, opkg); 4205 } 4206 } 4207 4208 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4209 PackageParser.Package opkg) { 4210 if (!opkg.mTrustedOverlay) { 4211 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4212 opkg.baseCodePath + ": overlay not trusted"); 4213 return false; 4214 } 4215 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4216 if (overlaySet == null) { 4217 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4218 opkg.baseCodePath + " but target package has no known overlays"); 4219 return false; 4220 } 4221 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4222 // TODO: generate idmap for split APKs 4223 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4224 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4225 + opkg.baseCodePath); 4226 return false; 4227 } 4228 PackageParser.Package[] overlayArray = 4229 overlaySet.values().toArray(new PackageParser.Package[0]); 4230 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4231 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4232 return p1.mOverlayPriority - p2.mOverlayPriority; 4233 } 4234 }; 4235 Arrays.sort(overlayArray, cmp); 4236 4237 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4238 int i = 0; 4239 for (PackageParser.Package p : overlayArray) { 4240 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4241 } 4242 return true; 4243 } 4244 4245 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4246 final File[] files = dir.listFiles(); 4247 if (ArrayUtils.isEmpty(files)) { 4248 Log.d(TAG, "No files in app dir " + dir); 4249 return; 4250 } 4251 4252 if (DEBUG_PACKAGE_SCANNING) { 4253 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4254 + " flags=0x" + Integer.toHexString(parseFlags)); 4255 } 4256 4257 for (File file : files) { 4258 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4259 && !PackageInstallerService.isStageName(file.getName()); 4260 if (!isPackage) { 4261 // Ignore entries which are not packages 4262 continue; 4263 } 4264 try { 4265 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4266 scanFlags, currentTime, null); 4267 } catch (PackageManagerException e) { 4268 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4269 4270 // Delete invalid userdata apps 4271 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4272 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4273 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4274 if (file.isDirectory()) { 4275 FileUtils.deleteContents(file); 4276 } 4277 file.delete(); 4278 } 4279 } 4280 } 4281 } 4282 4283 private static File getSettingsProblemFile() { 4284 File dataDir = Environment.getDataDirectory(); 4285 File systemDir = new File(dataDir, "system"); 4286 File fname = new File(systemDir, "uiderrors.txt"); 4287 return fname; 4288 } 4289 4290 static void reportSettingsProblem(int priority, String msg) { 4291 logCriticalInfo(priority, msg); 4292 } 4293 4294 static void logCriticalInfo(int priority, String msg) { 4295 Slog.println(priority, TAG, msg); 4296 EventLogTags.writePmCriticalInfo(msg); 4297 try { 4298 File fname = getSettingsProblemFile(); 4299 FileOutputStream out = new FileOutputStream(fname, true); 4300 PrintWriter pw = new FastPrintWriter(out); 4301 SimpleDateFormat formatter = new SimpleDateFormat(); 4302 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4303 pw.println(dateString + ": " + msg); 4304 pw.close(); 4305 FileUtils.setPermissions( 4306 fname.toString(), 4307 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4308 -1, -1); 4309 } catch (java.io.IOException e) { 4310 } 4311 } 4312 4313 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4314 PackageParser.Package pkg, File srcFile, int parseFlags) 4315 throws PackageManagerException { 4316 if (ps != null 4317 && ps.codePath.equals(srcFile) 4318 && ps.timeStamp == srcFile.lastModified() 4319 && !isCompatSignatureUpdateNeeded(pkg) 4320 && !isRecoverSignatureUpdateNeeded(pkg)) { 4321 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4322 if (ps.signatures.mSignatures != null 4323 && ps.signatures.mSignatures.length != 0 4324 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4325 // Optimization: reuse the existing cached certificates 4326 // if the package appears to be unchanged. 4327 pkg.mSignatures = ps.signatures.mSignatures; 4328 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4329 synchronized (mPackages) { 4330 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4331 } 4332 return; 4333 } 4334 4335 Slog.w(TAG, "PackageSetting for " + ps.name 4336 + " is missing signatures. Collecting certs again to recover them."); 4337 } else { 4338 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4339 } 4340 4341 try { 4342 pp.collectCertificates(pkg, parseFlags); 4343 pp.collectManifestDigest(pkg); 4344 } catch (PackageParserException e) { 4345 throw PackageManagerException.from(e); 4346 } 4347 } 4348 4349 /* 4350 * Scan a package and return the newly parsed package. 4351 * Returns null in case of errors and the error code is stored in mLastScanError 4352 */ 4353 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4354 long currentTime, UserHandle user) throws PackageManagerException { 4355 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4356 parseFlags |= mDefParseFlags; 4357 PackageParser pp = new PackageParser(); 4358 pp.setSeparateProcesses(mSeparateProcesses); 4359 pp.setOnlyCoreApps(mOnlyCore); 4360 pp.setDisplayMetrics(mMetrics); 4361 4362 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4363 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4364 } 4365 4366 final PackageParser.Package pkg; 4367 try { 4368 pkg = pp.parsePackage(scanFile, parseFlags); 4369 } catch (PackageParserException e) { 4370 throw PackageManagerException.from(e); 4371 } 4372 4373 PackageSetting ps = null; 4374 PackageSetting updatedPkg; 4375 // reader 4376 synchronized (mPackages) { 4377 // Look to see if we already know about this package. 4378 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4379 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4380 // This package has been renamed to its original name. Let's 4381 // use that. 4382 ps = mSettings.peekPackageLPr(oldName); 4383 } 4384 // If there was no original package, see one for the real package name. 4385 if (ps == null) { 4386 ps = mSettings.peekPackageLPr(pkg.packageName); 4387 } 4388 // Check to see if this package could be hiding/updating a system 4389 // package. Must look for it either under the original or real 4390 // package name depending on our state. 4391 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4392 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4393 } 4394 boolean updatedPkgBetter = false; 4395 // First check if this is a system package that may involve an update 4396 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4397 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4398 // it needs to drop FLAG_PRIVILEGED. 4399 if (locationIsPrivileged(scanFile)) { 4400 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4401 } else { 4402 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4403 } 4404 4405 if (ps != null && !ps.codePath.equals(scanFile)) { 4406 // The path has changed from what was last scanned... check the 4407 // version of the new path against what we have stored to determine 4408 // what to do. 4409 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4410 if (pkg.mVersionCode <= ps.versionCode) { 4411 // The system package has been updated and the code path does not match 4412 // Ignore entry. Skip it. 4413 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4414 + " ignored: updated version " + ps.versionCode 4415 + " better than this " + pkg.mVersionCode); 4416 if (!updatedPkg.codePath.equals(scanFile)) { 4417 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4418 + ps.name + " changing from " + updatedPkg.codePathString 4419 + " to " + scanFile); 4420 updatedPkg.codePath = scanFile; 4421 updatedPkg.codePathString = scanFile.toString(); 4422 updatedPkg.resourcePath = scanFile; 4423 updatedPkg.resourcePathString = scanFile.toString(); 4424 } 4425 updatedPkg.pkg = pkg; 4426 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4427 } else { 4428 // The current app on the system partition is better than 4429 // what we have updated to on the data partition; switch 4430 // back to the system partition version. 4431 // At this point, its safely assumed that package installation for 4432 // apps in system partition will go through. If not there won't be a working 4433 // version of the app 4434 // writer 4435 synchronized (mPackages) { 4436 // Just remove the loaded entries from package lists. 4437 mPackages.remove(ps.name); 4438 } 4439 4440 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4441 + " reverting from " + ps.codePathString 4442 + ": new version " + pkg.mVersionCode 4443 + " better than installed " + ps.versionCode); 4444 4445 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4446 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4447 getAppDexInstructionSets(ps)); 4448 synchronized (mInstallLock) { 4449 args.cleanUpResourcesLI(); 4450 } 4451 synchronized (mPackages) { 4452 mSettings.enableSystemPackageLPw(ps.name); 4453 } 4454 updatedPkgBetter = true; 4455 } 4456 } 4457 } 4458 4459 if (updatedPkg != null) { 4460 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4461 // initially 4462 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4463 4464 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4465 // flag set initially 4466 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4467 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4468 } 4469 } 4470 4471 // Verify certificates against what was last scanned 4472 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4473 4474 /* 4475 * A new system app appeared, but we already had a non-system one of the 4476 * same name installed earlier. 4477 */ 4478 boolean shouldHideSystemApp = false; 4479 if (updatedPkg == null && ps != null 4480 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4481 /* 4482 * Check to make sure the signatures match first. If they don't, 4483 * wipe the installed application and its data. 4484 */ 4485 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4486 != PackageManager.SIGNATURE_MATCH) { 4487 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4488 + " signatures don't match existing userdata copy; removing"); 4489 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4490 ps = null; 4491 } else { 4492 /* 4493 * If the newly-added system app is an older version than the 4494 * already installed version, hide it. It will be scanned later 4495 * and re-added like an update. 4496 */ 4497 if (pkg.mVersionCode <= ps.versionCode) { 4498 shouldHideSystemApp = true; 4499 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4500 + " but new version " + pkg.mVersionCode + " better than installed " 4501 + ps.versionCode + "; hiding system"); 4502 } else { 4503 /* 4504 * The newly found system app is a newer version that the 4505 * one previously installed. Simply remove the 4506 * already-installed application and replace it with our own 4507 * while keeping the application data. 4508 */ 4509 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4510 + " reverting from " + ps.codePathString + ": new version " 4511 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4512 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4513 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4514 getAppDexInstructionSets(ps)); 4515 synchronized (mInstallLock) { 4516 args.cleanUpResourcesLI(); 4517 } 4518 } 4519 } 4520 } 4521 4522 // The apk is forward locked (not public) if its code and resources 4523 // are kept in different files. (except for app in either system or 4524 // vendor path). 4525 // TODO grab this value from PackageSettings 4526 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4527 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4528 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4529 } 4530 } 4531 4532 // TODO: extend to support forward-locked splits 4533 String resourcePath = null; 4534 String baseResourcePath = null; 4535 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4536 if (ps != null && ps.resourcePathString != null) { 4537 resourcePath = ps.resourcePathString; 4538 baseResourcePath = ps.resourcePathString; 4539 } else { 4540 // Should not happen at all. Just log an error. 4541 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4542 } 4543 } else { 4544 resourcePath = pkg.codePath; 4545 baseResourcePath = pkg.baseCodePath; 4546 } 4547 4548 // Set application objects path explicitly. 4549 pkg.applicationInfo.setCodePath(pkg.codePath); 4550 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4551 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4552 pkg.applicationInfo.setResourcePath(resourcePath); 4553 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4554 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4555 4556 // Note that we invoke the following method only if we are about to unpack an application 4557 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4558 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4559 4560 /* 4561 * If the system app should be overridden by a previously installed 4562 * data, hide the system app now and let the /data/app scan pick it up 4563 * again. 4564 */ 4565 if (shouldHideSystemApp) { 4566 synchronized (mPackages) { 4567 /* 4568 * We have to grant systems permissions before we hide, because 4569 * grantPermissions will assume the package update is trying to 4570 * expand its permissions. 4571 */ 4572 grantPermissionsLPw(pkg, true, pkg.packageName); 4573 mSettings.disableSystemPackageLPw(pkg.packageName); 4574 } 4575 } 4576 4577 return scannedPkg; 4578 } 4579 4580 private static String fixProcessName(String defProcessName, 4581 String processName, int uid) { 4582 if (processName == null) { 4583 return defProcessName; 4584 } 4585 return processName; 4586 } 4587 4588 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4589 throws PackageManagerException { 4590 if (pkgSetting.signatures.mSignatures != null) { 4591 // Already existing package. Make sure signatures match 4592 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4593 == PackageManager.SIGNATURE_MATCH; 4594 if (!match) { 4595 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4596 == PackageManager.SIGNATURE_MATCH; 4597 } 4598 if (!match) { 4599 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4600 == PackageManager.SIGNATURE_MATCH; 4601 } 4602 if (!match) { 4603 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4604 + pkg.packageName + " signatures do not match the " 4605 + "previously installed version; ignoring!"); 4606 } 4607 } 4608 4609 // Check for shared user signatures 4610 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4611 // Already existing package. Make sure signatures match 4612 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4613 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4614 if (!match) { 4615 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4616 == PackageManager.SIGNATURE_MATCH; 4617 } 4618 if (!match) { 4619 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4620 == PackageManager.SIGNATURE_MATCH; 4621 } 4622 if (!match) { 4623 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4624 "Package " + pkg.packageName 4625 + " has no signatures that match those in shared user " 4626 + pkgSetting.sharedUser.name + "; ignoring!"); 4627 } 4628 } 4629 } 4630 4631 /** 4632 * Enforces that only the system UID or root's UID can call a method exposed 4633 * via Binder. 4634 * 4635 * @param message used as message if SecurityException is thrown 4636 * @throws SecurityException if the caller is not system or root 4637 */ 4638 private static final void enforceSystemOrRoot(String message) { 4639 final int uid = Binder.getCallingUid(); 4640 if (uid != Process.SYSTEM_UID && uid != 0) { 4641 throw new SecurityException(message); 4642 } 4643 } 4644 4645 @Override 4646 public void performBootDexOpt() { 4647 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4648 4649 // Before everything else, see whether we need to fstrim. 4650 try { 4651 IMountService ms = PackageHelper.getMountService(); 4652 if (ms != null) { 4653 final boolean isUpgrade = isUpgrade(); 4654 boolean doTrim = isUpgrade; 4655 if (doTrim) { 4656 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4657 } else { 4658 final long interval = android.provider.Settings.Global.getLong( 4659 mContext.getContentResolver(), 4660 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4661 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4662 if (interval > 0) { 4663 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4664 if (timeSinceLast > interval) { 4665 doTrim = true; 4666 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4667 + "; running immediately"); 4668 } 4669 } 4670 } 4671 if (doTrim) { 4672 if (!isFirstBoot()) { 4673 try { 4674 ActivityManagerNative.getDefault().showBootMessage( 4675 mContext.getResources().getString( 4676 R.string.android_upgrading_fstrim), true); 4677 } catch (RemoteException e) { 4678 } 4679 } 4680 ms.runMaintenance(); 4681 } 4682 } else { 4683 Slog.e(TAG, "Mount service unavailable!"); 4684 } 4685 } catch (RemoteException e) { 4686 // Can't happen; MountService is local 4687 } 4688 4689 final ArraySet<PackageParser.Package> pkgs; 4690 synchronized (mPackages) { 4691 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4692 } 4693 4694 if (pkgs != null) { 4695 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4696 // in case the device runs out of space. 4697 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4698 // Give priority to core apps. 4699 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4700 PackageParser.Package pkg = it.next(); 4701 if (pkg.coreApp) { 4702 if (DEBUG_DEXOPT) { 4703 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4704 } 4705 sortedPkgs.add(pkg); 4706 it.remove(); 4707 } 4708 } 4709 // Give priority to system apps that listen for pre boot complete. 4710 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4711 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4712 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4713 PackageParser.Package pkg = it.next(); 4714 if (pkgNames.contains(pkg.packageName)) { 4715 if (DEBUG_DEXOPT) { 4716 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4717 } 4718 sortedPkgs.add(pkg); 4719 it.remove(); 4720 } 4721 } 4722 // Give priority to system apps. 4723 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4724 PackageParser.Package pkg = it.next(); 4725 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4726 if (DEBUG_DEXOPT) { 4727 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4728 } 4729 sortedPkgs.add(pkg); 4730 it.remove(); 4731 } 4732 } 4733 // Give priority to updated system apps. 4734 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4735 PackageParser.Package pkg = it.next(); 4736 if (isUpdatedSystemApp(pkg)) { 4737 if (DEBUG_DEXOPT) { 4738 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4739 } 4740 sortedPkgs.add(pkg); 4741 it.remove(); 4742 } 4743 } 4744 // Give priority to apps that listen for boot complete. 4745 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4746 pkgNames = getPackageNamesForIntent(intent); 4747 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4748 PackageParser.Package pkg = it.next(); 4749 if (pkgNames.contains(pkg.packageName)) { 4750 if (DEBUG_DEXOPT) { 4751 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4752 } 4753 sortedPkgs.add(pkg); 4754 it.remove(); 4755 } 4756 } 4757 // Filter out packages that aren't recently used. 4758 filterRecentlyUsedApps(pkgs); 4759 // Add all remaining apps. 4760 for (PackageParser.Package pkg : pkgs) { 4761 if (DEBUG_DEXOPT) { 4762 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4763 } 4764 sortedPkgs.add(pkg); 4765 } 4766 4767 // If we want to be lazy, filter everything that wasn't recently used. 4768 if (mLazyDexOpt) { 4769 filterRecentlyUsedApps(sortedPkgs); 4770 } 4771 4772 int i = 0; 4773 int total = sortedPkgs.size(); 4774 File dataDir = Environment.getDataDirectory(); 4775 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4776 if (lowThreshold == 0) { 4777 throw new IllegalStateException("Invalid low memory threshold"); 4778 } 4779 for (PackageParser.Package pkg : sortedPkgs) { 4780 long usableSpace = dataDir.getUsableSpace(); 4781 if (usableSpace < lowThreshold) { 4782 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4783 break; 4784 } 4785 performBootDexOpt(pkg, ++i, total); 4786 } 4787 } 4788 } 4789 4790 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4791 // Filter out packages that aren't recently used. 4792 // 4793 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4794 // should do a full dexopt. 4795 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4796 int total = pkgs.size(); 4797 int skipped = 0; 4798 long now = System.currentTimeMillis(); 4799 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4800 PackageParser.Package pkg = i.next(); 4801 long then = pkg.mLastPackageUsageTimeInMills; 4802 if (then + mDexOptLRUThresholdInMills < now) { 4803 if (DEBUG_DEXOPT) { 4804 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4805 ((then == 0) ? "never" : new Date(then))); 4806 } 4807 i.remove(); 4808 skipped++; 4809 } 4810 } 4811 if (DEBUG_DEXOPT) { 4812 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4813 } 4814 } 4815 } 4816 4817 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4818 List<ResolveInfo> ris = null; 4819 try { 4820 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4821 intent, null, 0, UserHandle.USER_OWNER); 4822 } catch (RemoteException e) { 4823 } 4824 ArraySet<String> pkgNames = new ArraySet<String>(); 4825 if (ris != null) { 4826 for (ResolveInfo ri : ris) { 4827 pkgNames.add(ri.activityInfo.packageName); 4828 } 4829 } 4830 return pkgNames; 4831 } 4832 4833 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4834 if (DEBUG_DEXOPT) { 4835 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4836 } 4837 if (!isFirstBoot()) { 4838 try { 4839 ActivityManagerNative.getDefault().showBootMessage( 4840 mContext.getResources().getString(R.string.android_upgrading_apk, 4841 curr, total), true); 4842 } catch (RemoteException e) { 4843 } 4844 } 4845 PackageParser.Package p = pkg; 4846 synchronized (mInstallLock) { 4847 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4848 false /* force dex */, false /* defer */, true /* include dependencies */); 4849 } 4850 } 4851 4852 @Override 4853 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4854 return performDexOpt(packageName, instructionSet, false); 4855 } 4856 4857 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4858 if (info.primaryCpuAbi == null) { 4859 return getPreferredInstructionSet(); 4860 } 4861 4862 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4863 } 4864 4865 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4866 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4867 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4868 if (!dexopt && !updateUsage) { 4869 // We aren't going to dexopt or update usage, so bail early. 4870 return false; 4871 } 4872 PackageParser.Package p; 4873 final String targetInstructionSet; 4874 synchronized (mPackages) { 4875 p = mPackages.get(packageName); 4876 if (p == null) { 4877 return false; 4878 } 4879 if (updateUsage) { 4880 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4881 } 4882 mPackageUsage.write(false); 4883 if (!dexopt) { 4884 // We aren't going to dexopt, so bail early. 4885 return false; 4886 } 4887 4888 targetInstructionSet = instructionSet != null ? instructionSet : 4889 getPrimaryInstructionSet(p.applicationInfo); 4890 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4891 return false; 4892 } 4893 } 4894 4895 synchronized (mInstallLock) { 4896 final String[] instructionSets = new String[] { targetInstructionSet }; 4897 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4898 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4899 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4900 } 4901 } 4902 4903 public ArraySet<String> getPackagesThatNeedDexOpt() { 4904 ArraySet<String> pkgs = null; 4905 synchronized (mPackages) { 4906 for (PackageParser.Package p : mPackages.values()) { 4907 if (DEBUG_DEXOPT) { 4908 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4909 } 4910 if (!p.mDexOptPerformed.isEmpty()) { 4911 continue; 4912 } 4913 if (pkgs == null) { 4914 pkgs = new ArraySet<String>(); 4915 } 4916 pkgs.add(p.packageName); 4917 } 4918 } 4919 return pkgs; 4920 } 4921 4922 public void shutdown() { 4923 mPackageUsage.write(true); 4924 } 4925 4926 @Override 4927 public void forceDexOpt(String packageName) { 4928 enforceSystemOrRoot("forceDexOpt"); 4929 4930 PackageParser.Package pkg; 4931 synchronized (mPackages) { 4932 pkg = mPackages.get(packageName); 4933 if (pkg == null) { 4934 throw new IllegalArgumentException("Missing package: " + packageName); 4935 } 4936 } 4937 4938 synchronized (mInstallLock) { 4939 final String[] instructionSets = new String[] { 4940 getPrimaryInstructionSet(pkg.applicationInfo) }; 4941 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4942 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4943 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4944 throw new IllegalStateException("Failed to dexopt: " + res); 4945 } 4946 } 4947 } 4948 4949 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4950 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4951 Slog.w(TAG, "Unable to update from " + oldPkg.name 4952 + " to " + newPkg.packageName 4953 + ": old package not in system partition"); 4954 return false; 4955 } else if (mPackages.get(oldPkg.name) != null) { 4956 Slog.w(TAG, "Unable to update from " + oldPkg.name 4957 + " to " + newPkg.packageName 4958 + ": old package still exists"); 4959 return false; 4960 } 4961 return true; 4962 } 4963 4964 private File getDataPathForPackage(String packageName, int userId) { 4965 /* 4966 * Until we fully support multiple users, return the directory we 4967 * previously would have. The PackageManagerTests will need to be 4968 * revised when this is changed back.. 4969 */ 4970 if (userId == 0) { 4971 return new File(mAppDataDir, packageName); 4972 } else { 4973 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4974 + File.separator + packageName); 4975 } 4976 } 4977 4978 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4979 int[] users = sUserManager.getUserIds(); 4980 int res = mInstaller.install(packageName, uid, uid, seinfo); 4981 if (res < 0) { 4982 return res; 4983 } 4984 for (int user : users) { 4985 if (user != 0) { 4986 res = mInstaller.createUserData(packageName, 4987 UserHandle.getUid(user, uid), user, seinfo); 4988 if (res < 0) { 4989 return res; 4990 } 4991 } 4992 } 4993 return res; 4994 } 4995 4996 private int removeDataDirsLI(String packageName) { 4997 int[] users = sUserManager.getUserIds(); 4998 int res = 0; 4999 for (int user : users) { 5000 int resInner = mInstaller.remove(packageName, user); 5001 if (resInner < 0) { 5002 res = resInner; 5003 } 5004 } 5005 5006 return res; 5007 } 5008 5009 private int deleteCodeCacheDirsLI(String packageName) { 5010 int[] users = sUserManager.getUserIds(); 5011 int res = 0; 5012 for (int user : users) { 5013 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5014 if (resInner < 0) { 5015 res = resInner; 5016 } 5017 } 5018 return res; 5019 } 5020 5021 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5022 PackageParser.Package changingLib) { 5023 if (file.path != null) { 5024 usesLibraryFiles.add(file.path); 5025 return; 5026 } 5027 PackageParser.Package p = mPackages.get(file.apk); 5028 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5029 // If we are doing this while in the middle of updating a library apk, 5030 // then we need to make sure to use that new apk for determining the 5031 // dependencies here. (We haven't yet finished committing the new apk 5032 // to the package manager state.) 5033 if (p == null || p.packageName.equals(changingLib.packageName)) { 5034 p = changingLib; 5035 } 5036 } 5037 if (p != null) { 5038 usesLibraryFiles.addAll(p.getAllCodePaths()); 5039 } 5040 } 5041 5042 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5043 PackageParser.Package changingLib) throws PackageManagerException { 5044 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5045 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5046 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5047 for (int i=0; i<N; i++) { 5048 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5049 if (file == null) { 5050 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5051 "Package " + pkg.packageName + " requires unavailable shared library " 5052 + pkg.usesLibraries.get(i) + "; failing!"); 5053 } 5054 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5055 } 5056 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5057 for (int i=0; i<N; i++) { 5058 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5059 if (file == null) { 5060 Slog.w(TAG, "Package " + pkg.packageName 5061 + " desires unavailable shared library " 5062 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5063 } else { 5064 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5065 } 5066 } 5067 N = usesLibraryFiles.size(); 5068 if (N > 0) { 5069 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5070 } else { 5071 pkg.usesLibraryFiles = null; 5072 } 5073 } 5074 } 5075 5076 private static boolean hasString(List<String> list, List<String> which) { 5077 if (list == null) { 5078 return false; 5079 } 5080 for (int i=list.size()-1; i>=0; i--) { 5081 for (int j=which.size()-1; j>=0; j--) { 5082 if (which.get(j).equals(list.get(i))) { 5083 return true; 5084 } 5085 } 5086 } 5087 return false; 5088 } 5089 5090 private void updateAllSharedLibrariesLPw() { 5091 for (PackageParser.Package pkg : mPackages.values()) { 5092 try { 5093 updateSharedLibrariesLPw(pkg, null); 5094 } catch (PackageManagerException e) { 5095 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5096 } 5097 } 5098 } 5099 5100 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5101 PackageParser.Package changingPkg) { 5102 ArrayList<PackageParser.Package> res = null; 5103 for (PackageParser.Package pkg : mPackages.values()) { 5104 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5105 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5106 if (res == null) { 5107 res = new ArrayList<PackageParser.Package>(); 5108 } 5109 res.add(pkg); 5110 try { 5111 updateSharedLibrariesLPw(pkg, changingPkg); 5112 } catch (PackageManagerException e) { 5113 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5114 } 5115 } 5116 } 5117 return res; 5118 } 5119 5120 /** 5121 * Derive the value of the {@code cpuAbiOverride} based on the provided 5122 * value and an optional stored value from the package settings. 5123 */ 5124 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5125 String cpuAbiOverride = null; 5126 5127 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5128 cpuAbiOverride = null; 5129 } else if (abiOverride != null) { 5130 cpuAbiOverride = abiOverride; 5131 } else if (settings != null) { 5132 cpuAbiOverride = settings.cpuAbiOverrideString; 5133 } 5134 5135 return cpuAbiOverride; 5136 } 5137 5138 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5139 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5140 boolean success = false; 5141 try { 5142 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5143 currentTime, user); 5144 success = true; 5145 return res; 5146 } finally { 5147 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5148 removeDataDirsLI(pkg.packageName); 5149 } 5150 } 5151 } 5152 5153 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5154 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5155 final File scanFile = new File(pkg.codePath); 5156 if (pkg.applicationInfo.getCodePath() == null || 5157 pkg.applicationInfo.getResourcePath() == null) { 5158 // Bail out. The resource and code paths haven't been set. 5159 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5160 "Code and resource paths haven't been set correctly"); 5161 } 5162 5163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5164 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5165 } else { 5166 // Only allow system apps to be flagged as core apps. 5167 pkg.coreApp = false; 5168 } 5169 5170 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5171 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5172 } 5173 5174 if (mCustomResolverComponentName != null && 5175 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5176 setUpCustomResolverActivity(pkg); 5177 } 5178 5179 if (pkg.packageName.equals("android")) { 5180 synchronized (mPackages) { 5181 if (mAndroidApplication != null) { 5182 Slog.w(TAG, "*************************************************"); 5183 Slog.w(TAG, "Core android package being redefined. Skipping."); 5184 Slog.w(TAG, " file=" + scanFile); 5185 Slog.w(TAG, "*************************************************"); 5186 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5187 "Core android package being redefined. Skipping."); 5188 } 5189 5190 // Set up information for our fall-back user intent resolution activity. 5191 mPlatformPackage = pkg; 5192 pkg.mVersionCode = mSdkVersion; 5193 mAndroidApplication = pkg.applicationInfo; 5194 5195 if (!mResolverReplaced) { 5196 mResolveActivity.applicationInfo = mAndroidApplication; 5197 mResolveActivity.name = ResolverActivity.class.getName(); 5198 mResolveActivity.packageName = mAndroidApplication.packageName; 5199 mResolveActivity.processName = "system:ui"; 5200 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5201 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5202 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5203 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5204 mResolveActivity.exported = true; 5205 mResolveActivity.enabled = true; 5206 mResolveInfo.activityInfo = mResolveActivity; 5207 mResolveInfo.priority = 0; 5208 mResolveInfo.preferredOrder = 0; 5209 mResolveInfo.match = 0; 5210 mResolveComponentName = new ComponentName( 5211 mAndroidApplication.packageName, mResolveActivity.name); 5212 } 5213 } 5214 } 5215 5216 if (DEBUG_PACKAGE_SCANNING) { 5217 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5218 Log.d(TAG, "Scanning package " + pkg.packageName); 5219 } 5220 5221 if (mPackages.containsKey(pkg.packageName) 5222 || mSharedLibraries.containsKey(pkg.packageName)) { 5223 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5224 "Application package " + pkg.packageName 5225 + " already installed. Skipping duplicate."); 5226 } 5227 5228 // Initialize package source and resource directories 5229 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5230 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5231 5232 SharedUserSetting suid = null; 5233 PackageSetting pkgSetting = null; 5234 5235 if (!isSystemApp(pkg)) { 5236 // Only system apps can use these features. 5237 pkg.mOriginalPackages = null; 5238 pkg.mRealPackage = null; 5239 pkg.mAdoptPermissions = null; 5240 } 5241 5242 // writer 5243 synchronized (mPackages) { 5244 if (pkg.mSharedUserId != null) { 5245 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5246 if (suid == null) { 5247 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5248 "Creating application package " + pkg.packageName 5249 + " for shared user failed"); 5250 } 5251 if (DEBUG_PACKAGE_SCANNING) { 5252 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5253 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5254 + "): packages=" + suid.packages); 5255 } 5256 } 5257 5258 // Check if we are renaming from an original package name. 5259 PackageSetting origPackage = null; 5260 String realName = null; 5261 if (pkg.mOriginalPackages != null) { 5262 // This package may need to be renamed to a previously 5263 // installed name. Let's check on that... 5264 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5265 if (pkg.mOriginalPackages.contains(renamed)) { 5266 // This package had originally been installed as the 5267 // original name, and we have already taken care of 5268 // transitioning to the new one. Just update the new 5269 // one to continue using the old name. 5270 realName = pkg.mRealPackage; 5271 if (!pkg.packageName.equals(renamed)) { 5272 // Callers into this function may have already taken 5273 // care of renaming the package; only do it here if 5274 // it is not already done. 5275 pkg.setPackageName(renamed); 5276 } 5277 5278 } else { 5279 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5280 if ((origPackage = mSettings.peekPackageLPr( 5281 pkg.mOriginalPackages.get(i))) != null) { 5282 // We do have the package already installed under its 5283 // original name... should we use it? 5284 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5285 // New package is not compatible with original. 5286 origPackage = null; 5287 continue; 5288 } else if (origPackage.sharedUser != null) { 5289 // Make sure uid is compatible between packages. 5290 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5291 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5292 + " to " + pkg.packageName + ": old uid " 5293 + origPackage.sharedUser.name 5294 + " differs from " + pkg.mSharedUserId); 5295 origPackage = null; 5296 continue; 5297 } 5298 } else { 5299 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5300 + pkg.packageName + " to old name " + origPackage.name); 5301 } 5302 break; 5303 } 5304 } 5305 } 5306 } 5307 5308 if (mTransferedPackages.contains(pkg.packageName)) { 5309 Slog.w(TAG, "Package " + pkg.packageName 5310 + " was transferred to another, but its .apk remains"); 5311 } 5312 5313 // Just create the setting, don't add it yet. For already existing packages 5314 // the PkgSetting exists already and doesn't have to be created. 5315 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5316 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5317 pkg.applicationInfo.primaryCpuAbi, 5318 pkg.applicationInfo.secondaryCpuAbi, 5319 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5320 user, false); 5321 if (pkgSetting == null) { 5322 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5323 "Creating application package " + pkg.packageName + " failed"); 5324 } 5325 5326 if (pkgSetting.origPackage != null) { 5327 // If we are first transitioning from an original package, 5328 // fix up the new package's name now. We need to do this after 5329 // looking up the package under its new name, so getPackageLP 5330 // can take care of fiddling things correctly. 5331 pkg.setPackageName(origPackage.name); 5332 5333 // File a report about this. 5334 String msg = "New package " + pkgSetting.realName 5335 + " renamed to replace old package " + pkgSetting.name; 5336 reportSettingsProblem(Log.WARN, msg); 5337 5338 // Make a note of it. 5339 mTransferedPackages.add(origPackage.name); 5340 5341 // No longer need to retain this. 5342 pkgSetting.origPackage = null; 5343 } 5344 5345 if (realName != null) { 5346 // Make a note of it. 5347 mTransferedPackages.add(pkg.packageName); 5348 } 5349 5350 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5351 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5352 } 5353 5354 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5355 // Check all shared libraries and map to their actual file path. 5356 // We only do this here for apps not on a system dir, because those 5357 // are the only ones that can fail an install due to this. We 5358 // will take care of the system apps by updating all of their 5359 // library paths after the scan is done. 5360 updateSharedLibrariesLPw(pkg, null); 5361 } 5362 5363 if (mFoundPolicyFile) { 5364 SELinuxMMAC.assignSeinfoValue(pkg); 5365 } 5366 5367 pkg.applicationInfo.uid = pkgSetting.appId; 5368 pkg.mExtras = pkgSetting; 5369 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5370 try { 5371 verifySignaturesLP(pkgSetting, pkg); 5372 // We just determined the app is signed correctly, so bring 5373 // over the latest parsed certs. 5374 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5375 } catch (PackageManagerException e) { 5376 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5377 throw e; 5378 } 5379 // The signature has changed, but this package is in the system 5380 // image... let's recover! 5381 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5382 // However... if this package is part of a shared user, but it 5383 // doesn't match the signature of the shared user, let's fail. 5384 // What this means is that you can't change the signatures 5385 // associated with an overall shared user, which doesn't seem all 5386 // that unreasonable. 5387 if (pkgSetting.sharedUser != null) { 5388 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5389 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5390 throw new PackageManagerException( 5391 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5392 "Signature mismatch for shared user : " 5393 + pkgSetting.sharedUser); 5394 } 5395 } 5396 // File a report about this. 5397 String msg = "System package " + pkg.packageName 5398 + " signature changed; retaining data."; 5399 reportSettingsProblem(Log.WARN, msg); 5400 } 5401 } else { 5402 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5403 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5404 + pkg.packageName + " upgrade keys do not match the " 5405 + "previously installed version"); 5406 } else { 5407 // We just determined the app is signed correctly, so bring 5408 // over the latest parsed certs. 5409 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5410 } 5411 } 5412 // Verify that this new package doesn't have any content providers 5413 // that conflict with existing packages. Only do this if the 5414 // package isn't already installed, since we don't want to break 5415 // things that are installed. 5416 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5417 final int N = pkg.providers.size(); 5418 int i; 5419 for (i=0; i<N; i++) { 5420 PackageParser.Provider p = pkg.providers.get(i); 5421 if (p.info.authority != null) { 5422 String names[] = p.info.authority.split(";"); 5423 for (int j = 0; j < names.length; j++) { 5424 if (mProvidersByAuthority.containsKey(names[j])) { 5425 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5426 final String otherPackageName = 5427 ((other != null && other.getComponentName() != null) ? 5428 other.getComponentName().getPackageName() : "?"); 5429 throw new PackageManagerException( 5430 INSTALL_FAILED_CONFLICTING_PROVIDER, 5431 "Can't install because provider name " + names[j] 5432 + " (in package " + pkg.applicationInfo.packageName 5433 + ") is already used by " + otherPackageName); 5434 } 5435 } 5436 } 5437 } 5438 } 5439 5440 if (pkg.mAdoptPermissions != null) { 5441 // This package wants to adopt ownership of permissions from 5442 // another package. 5443 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5444 final String origName = pkg.mAdoptPermissions.get(i); 5445 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5446 if (orig != null) { 5447 if (verifyPackageUpdateLPr(orig, pkg)) { 5448 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5449 + pkg.packageName); 5450 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5451 } 5452 } 5453 } 5454 } 5455 } 5456 5457 final String pkgName = pkg.packageName; 5458 5459 final long scanFileTime = scanFile.lastModified(); 5460 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5461 pkg.applicationInfo.processName = fixProcessName( 5462 pkg.applicationInfo.packageName, 5463 pkg.applicationInfo.processName, 5464 pkg.applicationInfo.uid); 5465 5466 File dataPath; 5467 if (mPlatformPackage == pkg) { 5468 // The system package is special. 5469 dataPath = new File(Environment.getDataDirectory(), "system"); 5470 5471 pkg.applicationInfo.dataDir = dataPath.getPath(); 5472 5473 } else { 5474 // This is a normal package, need to make its data directory. 5475 dataPath = getDataPathForPackage(pkg.packageName, 0); 5476 5477 boolean uidError = false; 5478 if (dataPath.exists()) { 5479 int currentUid = 0; 5480 try { 5481 StructStat stat = Os.stat(dataPath.getPath()); 5482 currentUid = stat.st_uid; 5483 } catch (ErrnoException e) { 5484 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5485 } 5486 5487 // If we have mismatched owners for the data path, we have a problem. 5488 if (currentUid != pkg.applicationInfo.uid) { 5489 boolean recovered = false; 5490 if (currentUid == 0) { 5491 // The directory somehow became owned by root. Wow. 5492 // This is probably because the system was stopped while 5493 // installd was in the middle of messing with its libs 5494 // directory. Ask installd to fix that. 5495 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5496 pkg.applicationInfo.uid); 5497 if (ret >= 0) { 5498 recovered = true; 5499 String msg = "Package " + pkg.packageName 5500 + " unexpectedly changed to uid 0; recovered to " + 5501 + pkg.applicationInfo.uid; 5502 reportSettingsProblem(Log.WARN, msg); 5503 } 5504 } 5505 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5506 || (scanFlags&SCAN_BOOTING) != 0)) { 5507 // If this is a system app, we can at least delete its 5508 // current data so the application will still work. 5509 int ret = removeDataDirsLI(pkgName); 5510 if (ret >= 0) { 5511 // TODO: Kill the processes first 5512 // Old data gone! 5513 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5514 ? "System package " : "Third party package "; 5515 String msg = prefix + pkg.packageName 5516 + " has changed from uid: " 5517 + currentUid + " to " 5518 + pkg.applicationInfo.uid + "; old data erased"; 5519 reportSettingsProblem(Log.WARN, msg); 5520 recovered = true; 5521 5522 // And now re-install the app. 5523 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5524 pkg.applicationInfo.seinfo); 5525 if (ret == -1) { 5526 // Ack should not happen! 5527 msg = prefix + pkg.packageName 5528 + " could not have data directory re-created after delete."; 5529 reportSettingsProblem(Log.WARN, msg); 5530 throw new PackageManagerException( 5531 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5532 } 5533 } 5534 if (!recovered) { 5535 mHasSystemUidErrors = true; 5536 } 5537 } else if (!recovered) { 5538 // If we allow this install to proceed, we will be broken. 5539 // Abort, abort! 5540 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5541 "scanPackageLI"); 5542 } 5543 if (!recovered) { 5544 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5545 + pkg.applicationInfo.uid + "/fs_" 5546 + currentUid; 5547 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5548 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5549 String msg = "Package " + pkg.packageName 5550 + " has mismatched uid: " 5551 + currentUid + " on disk, " 5552 + pkg.applicationInfo.uid + " in settings"; 5553 // writer 5554 synchronized (mPackages) { 5555 mSettings.mReadMessages.append(msg); 5556 mSettings.mReadMessages.append('\n'); 5557 uidError = true; 5558 if (!pkgSetting.uidError) { 5559 reportSettingsProblem(Log.ERROR, msg); 5560 } 5561 } 5562 } 5563 } 5564 pkg.applicationInfo.dataDir = dataPath.getPath(); 5565 if (mShouldRestoreconData) { 5566 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5567 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5568 pkg.applicationInfo.uid); 5569 } 5570 } else { 5571 if (DEBUG_PACKAGE_SCANNING) { 5572 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5573 Log.v(TAG, "Want this data dir: " + dataPath); 5574 } 5575 //invoke installer to do the actual installation 5576 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5577 pkg.applicationInfo.seinfo); 5578 if (ret < 0) { 5579 // Error from installer 5580 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5581 "Unable to create data dirs [errorCode=" + ret + "]"); 5582 } 5583 5584 if (dataPath.exists()) { 5585 pkg.applicationInfo.dataDir = dataPath.getPath(); 5586 } else { 5587 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5588 pkg.applicationInfo.dataDir = null; 5589 } 5590 } 5591 5592 pkgSetting.uidError = uidError; 5593 } 5594 5595 final String path = scanFile.getPath(); 5596 final String codePath = pkg.applicationInfo.getCodePath(); 5597 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5598 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5599 setBundledAppAbisAndRoots(pkg, pkgSetting); 5600 5601 // If we haven't found any native libraries for the app, check if it has 5602 // renderscript code. We'll need to force the app to 32 bit if it has 5603 // renderscript bitcode. 5604 if (pkg.applicationInfo.primaryCpuAbi == null 5605 && pkg.applicationInfo.secondaryCpuAbi == null 5606 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5607 NativeLibraryHelper.Handle handle = null; 5608 try { 5609 handle = NativeLibraryHelper.Handle.create(scanFile); 5610 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5611 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5612 } 5613 } catch (IOException ioe) { 5614 Slog.w(TAG, "Error scanning system app : " + ioe); 5615 } finally { 5616 IoUtils.closeQuietly(handle); 5617 } 5618 } 5619 5620 setNativeLibraryPaths(pkg); 5621 } else { 5622 // TODO: We can probably be smarter about this stuff. For installed apps, 5623 // we can calculate this information at install time once and for all. For 5624 // system apps, we can probably assume that this information doesn't change 5625 // after the first boot scan. As things stand, we do lots of unnecessary work. 5626 5627 // Give ourselves some initial paths; we'll come back for another 5628 // pass once we've determined ABI below. 5629 setNativeLibraryPaths(pkg); 5630 5631 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5632 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5633 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5634 5635 NativeLibraryHelper.Handle handle = null; 5636 try { 5637 handle = NativeLibraryHelper.Handle.create(scanFile); 5638 // TODO(multiArch): This can be null for apps that didn't go through the 5639 // usual installation process. We can calculate it again, like we 5640 // do during install time. 5641 // 5642 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5643 // unnecessary. 5644 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5645 5646 // Null out the abis so that they can be recalculated. 5647 pkg.applicationInfo.primaryCpuAbi = null; 5648 pkg.applicationInfo.secondaryCpuAbi = null; 5649 if (isMultiArch(pkg.applicationInfo)) { 5650 // Warn if we've set an abiOverride for multi-lib packages.. 5651 // By definition, we need to copy both 32 and 64 bit libraries for 5652 // such packages. 5653 if (pkg.cpuAbiOverride != null 5654 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5655 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5656 } 5657 5658 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5659 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5660 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5661 if (isAsec) { 5662 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5663 } else { 5664 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5665 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5666 useIsaSpecificSubdirs); 5667 } 5668 } 5669 5670 maybeThrowExceptionForMultiArchCopy( 5671 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5672 5673 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5674 if (isAsec) { 5675 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5676 } else { 5677 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5678 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5679 useIsaSpecificSubdirs); 5680 } 5681 } 5682 5683 maybeThrowExceptionForMultiArchCopy( 5684 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5685 5686 if (abi64 >= 0) { 5687 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5688 } 5689 5690 if (abi32 >= 0) { 5691 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5692 if (abi64 >= 0) { 5693 pkg.applicationInfo.secondaryCpuAbi = abi; 5694 } else { 5695 pkg.applicationInfo.primaryCpuAbi = abi; 5696 } 5697 } 5698 } else { 5699 String[] abiList = (cpuAbiOverride != null) ? 5700 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5701 5702 // Enable gross and lame hacks for apps that are built with old 5703 // SDK tools. We must scan their APKs for renderscript bitcode and 5704 // not launch them if it's present. Don't bother checking on devices 5705 // that don't have 64 bit support. 5706 boolean needsRenderScriptOverride = false; 5707 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5708 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5709 abiList = Build.SUPPORTED_32_BIT_ABIS; 5710 needsRenderScriptOverride = true; 5711 } 5712 5713 final int copyRet; 5714 if (isAsec) { 5715 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5716 } else { 5717 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5718 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5719 } 5720 5721 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5722 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5723 "Error unpackaging native libs for app, errorCode=" + copyRet); 5724 } 5725 5726 if (copyRet >= 0) { 5727 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5728 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5729 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5730 } else if (needsRenderScriptOverride) { 5731 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5732 } 5733 } 5734 } catch (IOException ioe) { 5735 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5736 } finally { 5737 IoUtils.closeQuietly(handle); 5738 } 5739 5740 // Now that we've calculated the ABIs and determined if it's an internal app, 5741 // we will go ahead and populate the nativeLibraryPath. 5742 setNativeLibraryPaths(pkg); 5743 5744 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5745 final int[] userIds = sUserManager.getUserIds(); 5746 synchronized (mInstallLock) { 5747 // Create a native library symlink only if we have native libraries 5748 // and if the native libraries are 32 bit libraries. We do not provide 5749 // this symlink for 64 bit libraries. 5750 if (pkg.applicationInfo.primaryCpuAbi != null && 5751 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5752 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5753 for (int userId : userIds) { 5754 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5755 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5756 "Failed linking native library dir (user=" + userId + ")"); 5757 } 5758 } 5759 } 5760 } 5761 } 5762 5763 // This is a special case for the "system" package, where the ABI is 5764 // dictated by the zygote configuration (and init.rc). We should keep track 5765 // of this ABI so that we can deal with "normal" applications that run under 5766 // the same UID correctly. 5767 if (mPlatformPackage == pkg) { 5768 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5769 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5770 } 5771 5772 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5773 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5774 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5775 // Copy the derived override back to the parsed package, so that we can 5776 // update the package settings accordingly. 5777 pkg.cpuAbiOverride = cpuAbiOverride; 5778 5779 if (DEBUG_ABI_SELECTION) { 5780 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5781 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5782 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5783 } 5784 5785 // Push the derived path down into PackageSettings so we know what to 5786 // clean up at uninstall time. 5787 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5788 5789 if (DEBUG_ABI_SELECTION) { 5790 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5791 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5792 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5793 } 5794 5795 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5796 // We don't do this here during boot because we can do it all 5797 // at once after scanning all existing packages. 5798 // 5799 // We also do this *before* we perform dexopt on this package, so that 5800 // we can avoid redundant dexopts, and also to make sure we've got the 5801 // code and package path correct. 5802 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5803 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5804 } 5805 5806 if ((scanFlags & SCAN_NO_DEX) == 0) { 5807 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5808 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5809 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5810 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5811 } 5812 } 5813 5814 if (mFactoryTest && pkg.requestedPermissions.contains( 5815 android.Manifest.permission.FACTORY_TEST)) { 5816 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5817 } 5818 5819 ArrayList<PackageParser.Package> clientLibPkgs = null; 5820 5821 // writer 5822 synchronized (mPackages) { 5823 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5824 // Only system apps can add new shared libraries. 5825 if (pkg.libraryNames != null) { 5826 for (int i=0; i<pkg.libraryNames.size(); i++) { 5827 String name = pkg.libraryNames.get(i); 5828 boolean allowed = false; 5829 if (isUpdatedSystemApp(pkg)) { 5830 // New library entries can only be added through the 5831 // system image. This is important to get rid of a lot 5832 // of nasty edge cases: for example if we allowed a non- 5833 // system update of the app to add a library, then uninstalling 5834 // the update would make the library go away, and assumptions 5835 // we made such as through app install filtering would now 5836 // have allowed apps on the device which aren't compatible 5837 // with it. Better to just have the restriction here, be 5838 // conservative, and create many fewer cases that can negatively 5839 // impact the user experience. 5840 final PackageSetting sysPs = mSettings 5841 .getDisabledSystemPkgLPr(pkg.packageName); 5842 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5843 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5844 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5845 allowed = true; 5846 allowed = true; 5847 break; 5848 } 5849 } 5850 } 5851 } else { 5852 allowed = true; 5853 } 5854 if (allowed) { 5855 if (!mSharedLibraries.containsKey(name)) { 5856 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5857 } else if (!name.equals(pkg.packageName)) { 5858 Slog.w(TAG, "Package " + pkg.packageName + " library " 5859 + name + " already exists; skipping"); 5860 } 5861 } else { 5862 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5863 + name + " that is not declared on system image; skipping"); 5864 } 5865 } 5866 if ((scanFlags&SCAN_BOOTING) == 0) { 5867 // If we are not booting, we need to update any applications 5868 // that are clients of our shared library. If we are booting, 5869 // this will all be done once the scan is complete. 5870 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5871 } 5872 } 5873 } 5874 } 5875 5876 // We also need to dexopt any apps that are dependent on this library. Note that 5877 // if these fail, we should abort the install since installing the library will 5878 // result in some apps being broken. 5879 if (clientLibPkgs != null) { 5880 if ((scanFlags & SCAN_NO_DEX) == 0) { 5881 for (int i = 0; i < clientLibPkgs.size(); i++) { 5882 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5883 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5884 null /* instruction sets */, forceDex, 5885 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5886 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5887 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5888 "scanPackageLI failed to dexopt clientLibPkgs"); 5889 } 5890 } 5891 } 5892 } 5893 5894 // Request the ActivityManager to kill the process(only for existing packages) 5895 // so that we do not end up in a confused state while the user is still using the older 5896 // version of the application while the new one gets installed. 5897 if ((scanFlags & SCAN_REPLACING) != 0) { 5898 killApplication(pkg.applicationInfo.packageName, 5899 pkg.applicationInfo.uid, "update pkg"); 5900 } 5901 5902 // Also need to kill any apps that are dependent on the library. 5903 if (clientLibPkgs != null) { 5904 for (int i=0; i<clientLibPkgs.size(); i++) { 5905 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5906 killApplication(clientPkg.applicationInfo.packageName, 5907 clientPkg.applicationInfo.uid, "update lib"); 5908 } 5909 } 5910 5911 // writer 5912 synchronized (mPackages) { 5913 // We don't expect installation to fail beyond this point 5914 5915 // Add the new setting to mSettings 5916 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5917 // Add the new setting to mPackages 5918 mPackages.put(pkg.applicationInfo.packageName, pkg); 5919 // Make sure we don't accidentally delete its data. 5920 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5921 while (iter.hasNext()) { 5922 PackageCleanItem item = iter.next(); 5923 if (pkgName.equals(item.packageName)) { 5924 iter.remove(); 5925 } 5926 } 5927 5928 // Take care of first install / last update times. 5929 if (currentTime != 0) { 5930 if (pkgSetting.firstInstallTime == 0) { 5931 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5932 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5933 pkgSetting.lastUpdateTime = currentTime; 5934 } 5935 } else if (pkgSetting.firstInstallTime == 0) { 5936 // We need *something*. Take time time stamp of the file. 5937 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5938 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5939 if (scanFileTime != pkgSetting.timeStamp) { 5940 // A package on the system image has changed; consider this 5941 // to be an update. 5942 pkgSetting.lastUpdateTime = scanFileTime; 5943 } 5944 } 5945 5946 // Add the package's KeySets to the global KeySetManagerService 5947 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5948 try { 5949 // Old KeySetData no longer valid. 5950 ksms.removeAppKeySetDataLPw(pkg.packageName); 5951 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5952 if (pkg.mKeySetMapping != null) { 5953 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5954 pkg.mKeySetMapping.entrySet()) { 5955 if (entry.getValue() != null) { 5956 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5957 entry.getValue(), entry.getKey()); 5958 } 5959 } 5960 if (pkg.mUpgradeKeySets != null) { 5961 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5962 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5963 } 5964 } 5965 } 5966 } catch (NullPointerException e) { 5967 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5968 } catch (IllegalArgumentException e) { 5969 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5970 } 5971 5972 int N = pkg.providers.size(); 5973 StringBuilder r = null; 5974 int i; 5975 for (i=0; i<N; i++) { 5976 PackageParser.Provider p = pkg.providers.get(i); 5977 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5978 p.info.processName, pkg.applicationInfo.uid); 5979 mProviders.addProvider(p); 5980 p.syncable = p.info.isSyncable; 5981 if (p.info.authority != null) { 5982 String names[] = p.info.authority.split(";"); 5983 p.info.authority = null; 5984 for (int j = 0; j < names.length; j++) { 5985 if (j == 1 && p.syncable) { 5986 // We only want the first authority for a provider to possibly be 5987 // syncable, so if we already added this provider using a different 5988 // authority clear the syncable flag. We copy the provider before 5989 // changing it because the mProviders object contains a reference 5990 // to a provider that we don't want to change. 5991 // Only do this for the second authority since the resulting provider 5992 // object can be the same for all future authorities for this provider. 5993 p = new PackageParser.Provider(p); 5994 p.syncable = false; 5995 } 5996 if (!mProvidersByAuthority.containsKey(names[j])) { 5997 mProvidersByAuthority.put(names[j], p); 5998 if (p.info.authority == null) { 5999 p.info.authority = names[j]; 6000 } else { 6001 p.info.authority = p.info.authority + ";" + names[j]; 6002 } 6003 if (DEBUG_PACKAGE_SCANNING) { 6004 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6005 Log.d(TAG, "Registered content provider: " + names[j] 6006 + ", className = " + p.info.name + ", isSyncable = " 6007 + p.info.isSyncable); 6008 } 6009 } else { 6010 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6011 Slog.w(TAG, "Skipping provider name " + names[j] + 6012 " (in package " + pkg.applicationInfo.packageName + 6013 "): name already used by " 6014 + ((other != null && other.getComponentName() != null) 6015 ? other.getComponentName().getPackageName() : "?")); 6016 } 6017 } 6018 } 6019 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6020 if (r == null) { 6021 r = new StringBuilder(256); 6022 } else { 6023 r.append(' '); 6024 } 6025 r.append(p.info.name); 6026 } 6027 } 6028 if (r != null) { 6029 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6030 } 6031 6032 N = pkg.services.size(); 6033 r = null; 6034 for (i=0; i<N; i++) { 6035 PackageParser.Service s = pkg.services.get(i); 6036 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6037 s.info.processName, pkg.applicationInfo.uid); 6038 mServices.addService(s); 6039 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6040 if (r == null) { 6041 r = new StringBuilder(256); 6042 } else { 6043 r.append(' '); 6044 } 6045 r.append(s.info.name); 6046 } 6047 } 6048 if (r != null) { 6049 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6050 } 6051 6052 N = pkg.receivers.size(); 6053 r = null; 6054 for (i=0; i<N; i++) { 6055 PackageParser.Activity a = pkg.receivers.get(i); 6056 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6057 a.info.processName, pkg.applicationInfo.uid); 6058 mReceivers.addActivity(a, "receiver"); 6059 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6060 if (r == null) { 6061 r = new StringBuilder(256); 6062 } else { 6063 r.append(' '); 6064 } 6065 r.append(a.info.name); 6066 } 6067 } 6068 if (r != null) { 6069 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6070 } 6071 6072 N = pkg.activities.size(); 6073 r = null; 6074 for (i=0; i<N; i++) { 6075 PackageParser.Activity a = pkg.activities.get(i); 6076 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6077 a.info.processName, pkg.applicationInfo.uid); 6078 mActivities.addActivity(a, "activity"); 6079 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6080 if (r == null) { 6081 r = new StringBuilder(256); 6082 } else { 6083 r.append(' '); 6084 } 6085 r.append(a.info.name); 6086 } 6087 } 6088 if (r != null) { 6089 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6090 } 6091 6092 N = pkg.permissionGroups.size(); 6093 r = null; 6094 for (i=0; i<N; i++) { 6095 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6096 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6097 if (cur == null) { 6098 mPermissionGroups.put(pg.info.name, pg); 6099 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6100 if (r == null) { 6101 r = new StringBuilder(256); 6102 } else { 6103 r.append(' '); 6104 } 6105 r.append(pg.info.name); 6106 } 6107 } else { 6108 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6109 + pg.info.packageName + " ignored: original from " 6110 + cur.info.packageName); 6111 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6112 if (r == null) { 6113 r = new StringBuilder(256); 6114 } else { 6115 r.append(' '); 6116 } 6117 r.append("DUP:"); 6118 r.append(pg.info.name); 6119 } 6120 } 6121 } 6122 if (r != null) { 6123 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6124 } 6125 6126 N = pkg.permissions.size(); 6127 r = null; 6128 for (i=0; i<N; i++) { 6129 PackageParser.Permission p = pkg.permissions.get(i); 6130 ArrayMap<String, BasePermission> permissionMap = 6131 p.tree ? mSettings.mPermissionTrees 6132 : mSettings.mPermissions; 6133 p.group = mPermissionGroups.get(p.info.group); 6134 if (p.info.group == null || p.group != null) { 6135 BasePermission bp = permissionMap.get(p.info.name); 6136 6137 // Allow system apps to redefine non-system permissions 6138 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6139 final boolean currentOwnerIsSystem = (bp.perm != null 6140 && isSystemApp(bp.perm.owner)); 6141 if (isSystemApp(p.owner)) { 6142 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6143 // It's a built-in permission and no owner, take ownership now 6144 bp.packageSetting = pkgSetting; 6145 bp.perm = p; 6146 bp.uid = pkg.applicationInfo.uid; 6147 bp.sourcePackage = p.info.packageName; 6148 } else if (!currentOwnerIsSystem) { 6149 String msg = "New decl " + p.owner + " of permission " 6150 + p.info.name + " is system; overriding " + bp.sourcePackage; 6151 reportSettingsProblem(Log.WARN, msg); 6152 bp = null; 6153 } 6154 } 6155 } 6156 6157 if (bp == null) { 6158 bp = new BasePermission(p.info.name, p.info.packageName, 6159 BasePermission.TYPE_NORMAL); 6160 permissionMap.put(p.info.name, bp); 6161 } 6162 6163 if (bp.perm == null) { 6164 if (bp.sourcePackage == null 6165 || bp.sourcePackage.equals(p.info.packageName)) { 6166 BasePermission tree = findPermissionTreeLP(p.info.name); 6167 if (tree == null 6168 || tree.sourcePackage.equals(p.info.packageName)) { 6169 bp.packageSetting = pkgSetting; 6170 bp.perm = p; 6171 bp.uid = pkg.applicationInfo.uid; 6172 bp.sourcePackage = p.info.packageName; 6173 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6174 if (r == null) { 6175 r = new StringBuilder(256); 6176 } else { 6177 r.append(' '); 6178 } 6179 r.append(p.info.name); 6180 } 6181 } else { 6182 Slog.w(TAG, "Permission " + p.info.name + " from package " 6183 + p.info.packageName + " ignored: base tree " 6184 + tree.name + " is from package " 6185 + tree.sourcePackage); 6186 } 6187 } else { 6188 Slog.w(TAG, "Permission " + p.info.name + " from package " 6189 + p.info.packageName + " ignored: original from " 6190 + bp.sourcePackage); 6191 } 6192 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6193 if (r == null) { 6194 r = new StringBuilder(256); 6195 } else { 6196 r.append(' '); 6197 } 6198 r.append("DUP:"); 6199 r.append(p.info.name); 6200 } 6201 if (bp.perm == p) { 6202 bp.protectionLevel = p.info.protectionLevel; 6203 } 6204 } else { 6205 Slog.w(TAG, "Permission " + p.info.name + " from package " 6206 + p.info.packageName + " ignored: no group " 6207 + p.group); 6208 } 6209 } 6210 if (r != null) { 6211 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6212 } 6213 6214 N = pkg.instrumentation.size(); 6215 r = null; 6216 for (i=0; i<N; i++) { 6217 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6218 a.info.packageName = pkg.applicationInfo.packageName; 6219 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6220 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6221 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6222 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6223 a.info.dataDir = pkg.applicationInfo.dataDir; 6224 6225 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6226 // need other information about the application, like the ABI and what not ? 6227 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6228 mInstrumentation.put(a.getComponentName(), a); 6229 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6230 if (r == null) { 6231 r = new StringBuilder(256); 6232 } else { 6233 r.append(' '); 6234 } 6235 r.append(a.info.name); 6236 } 6237 } 6238 if (r != null) { 6239 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6240 } 6241 6242 if (pkg.protectedBroadcasts != null) { 6243 N = pkg.protectedBroadcasts.size(); 6244 for (i=0; i<N; i++) { 6245 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6246 } 6247 } 6248 6249 pkgSetting.setTimeStamp(scanFileTime); 6250 6251 // Create idmap files for pairs of (packages, overlay packages). 6252 // Note: "android", ie framework-res.apk, is handled by native layers. 6253 if (pkg.mOverlayTarget != null) { 6254 // This is an overlay package. 6255 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6256 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6257 mOverlays.put(pkg.mOverlayTarget, 6258 new ArrayMap<String, PackageParser.Package>()); 6259 } 6260 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6261 map.put(pkg.packageName, pkg); 6262 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6263 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6264 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6265 "scanPackageLI failed to createIdmap"); 6266 } 6267 } 6268 } else if (mOverlays.containsKey(pkg.packageName) && 6269 !pkg.packageName.equals("android")) { 6270 // This is a regular package, with one or more known overlay packages. 6271 createIdmapsForPackageLI(pkg); 6272 } 6273 } 6274 6275 return pkg; 6276 } 6277 6278 /** 6279 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6280 * i.e, so that all packages can be run inside a single process if required. 6281 * 6282 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6283 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6284 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6285 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6286 * updating a package that belongs to a shared user. 6287 * 6288 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6289 * adds unnecessary complexity. 6290 */ 6291 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6292 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6293 String requiredInstructionSet = null; 6294 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6295 requiredInstructionSet = VMRuntime.getInstructionSet( 6296 scannedPackage.applicationInfo.primaryCpuAbi); 6297 } 6298 6299 PackageSetting requirer = null; 6300 for (PackageSetting ps : packagesForUser) { 6301 // If packagesForUser contains scannedPackage, we skip it. This will happen 6302 // when scannedPackage is an update of an existing package. Without this check, 6303 // we will never be able to change the ABI of any package belonging to a shared 6304 // user, even if it's compatible with other packages. 6305 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6306 if (ps.primaryCpuAbiString == null) { 6307 continue; 6308 } 6309 6310 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6311 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6312 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6313 // this but there's not much we can do. 6314 String errorMessage = "Instruction set mismatch, " 6315 + ((requirer == null) ? "[caller]" : requirer) 6316 + " requires " + requiredInstructionSet + " whereas " + ps 6317 + " requires " + instructionSet; 6318 Slog.w(TAG, errorMessage); 6319 } 6320 6321 if (requiredInstructionSet == null) { 6322 requiredInstructionSet = instructionSet; 6323 requirer = ps; 6324 } 6325 } 6326 } 6327 6328 if (requiredInstructionSet != null) { 6329 String adjustedAbi; 6330 if (requirer != null) { 6331 // requirer != null implies that either scannedPackage was null or that scannedPackage 6332 // did not require an ABI, in which case we have to adjust scannedPackage to match 6333 // the ABI of the set (which is the same as requirer's ABI) 6334 adjustedAbi = requirer.primaryCpuAbiString; 6335 if (scannedPackage != null) { 6336 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6337 } 6338 } else { 6339 // requirer == null implies that we're updating all ABIs in the set to 6340 // match scannedPackage. 6341 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6342 } 6343 6344 for (PackageSetting ps : packagesForUser) { 6345 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6346 if (ps.primaryCpuAbiString != null) { 6347 continue; 6348 } 6349 6350 ps.primaryCpuAbiString = adjustedAbi; 6351 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6352 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6353 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6354 6355 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6356 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6357 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6358 ps.primaryCpuAbiString = null; 6359 ps.pkg.applicationInfo.primaryCpuAbi = null; 6360 return; 6361 } else { 6362 mInstaller.rmdex(ps.codePathString, 6363 getDexCodeInstructionSet(getPreferredInstructionSet())); 6364 } 6365 } 6366 } 6367 } 6368 } 6369 } 6370 6371 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6372 synchronized (mPackages) { 6373 mResolverReplaced = true; 6374 // Set up information for custom user intent resolution activity. 6375 mResolveActivity.applicationInfo = pkg.applicationInfo; 6376 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6377 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6378 mResolveActivity.processName = pkg.applicationInfo.packageName; 6379 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6380 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6381 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6382 mResolveActivity.theme = 0; 6383 mResolveActivity.exported = true; 6384 mResolveActivity.enabled = true; 6385 mResolveInfo.activityInfo = mResolveActivity; 6386 mResolveInfo.priority = 0; 6387 mResolveInfo.preferredOrder = 0; 6388 mResolveInfo.match = 0; 6389 mResolveComponentName = mCustomResolverComponentName; 6390 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6391 mResolveComponentName); 6392 } 6393 } 6394 6395 private static String calculateBundledApkRoot(final String codePathString) { 6396 final File codePath = new File(codePathString); 6397 final File codeRoot; 6398 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6399 codeRoot = Environment.getRootDirectory(); 6400 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6401 codeRoot = Environment.getOemDirectory(); 6402 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6403 codeRoot = Environment.getVendorDirectory(); 6404 } else { 6405 // Unrecognized code path; take its top real segment as the apk root: 6406 // e.g. /something/app/blah.apk => /something 6407 try { 6408 File f = codePath.getCanonicalFile(); 6409 File parent = f.getParentFile(); // non-null because codePath is a file 6410 File tmp; 6411 while ((tmp = parent.getParentFile()) != null) { 6412 f = parent; 6413 parent = tmp; 6414 } 6415 codeRoot = f; 6416 Slog.w(TAG, "Unrecognized code path " 6417 + codePath + " - using " + codeRoot); 6418 } catch (IOException e) { 6419 // Can't canonicalize the code path -- shenanigans? 6420 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6421 return Environment.getRootDirectory().getPath(); 6422 } 6423 } 6424 return codeRoot.getPath(); 6425 } 6426 6427 /** 6428 * Derive and set the location of native libraries for the given package, 6429 * which varies depending on where and how the package was installed. 6430 */ 6431 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6432 final ApplicationInfo info = pkg.applicationInfo; 6433 final String codePath = pkg.codePath; 6434 final File codeFile = new File(codePath); 6435 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6436 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6437 6438 info.nativeLibraryRootDir = null; 6439 info.nativeLibraryRootRequiresIsa = false; 6440 info.nativeLibraryDir = null; 6441 info.secondaryNativeLibraryDir = null; 6442 6443 if (isApkFile(codeFile)) { 6444 // Monolithic install 6445 if (bundledApp) { 6446 // If "/system/lib64/apkname" exists, assume that is the per-package 6447 // native library directory to use; otherwise use "/system/lib/apkname". 6448 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6449 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6450 getPrimaryInstructionSet(info)); 6451 6452 // This is a bundled system app so choose the path based on the ABI. 6453 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6454 // is just the default path. 6455 final String apkName = deriveCodePathName(codePath); 6456 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6457 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6458 apkName).getAbsolutePath(); 6459 6460 if (info.secondaryCpuAbi != null) { 6461 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6462 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6463 secondaryLibDir, apkName).getAbsolutePath(); 6464 } 6465 } else if (asecApp) { 6466 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6467 .getAbsolutePath(); 6468 } else { 6469 final String apkName = deriveCodePathName(codePath); 6470 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6471 .getAbsolutePath(); 6472 } 6473 6474 info.nativeLibraryRootRequiresIsa = false; 6475 info.nativeLibraryDir = info.nativeLibraryRootDir; 6476 } else { 6477 // Cluster install 6478 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6479 info.nativeLibraryRootRequiresIsa = true; 6480 6481 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6482 getPrimaryInstructionSet(info)).getAbsolutePath(); 6483 6484 if (info.secondaryCpuAbi != null) { 6485 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6486 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6487 } 6488 } 6489 } 6490 6491 /** 6492 * Calculate the abis and roots for a bundled app. These can uniquely 6493 * be determined from the contents of the system partition, i.e whether 6494 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6495 * of this information, and instead assume that the system was built 6496 * sensibly. 6497 */ 6498 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6499 PackageSetting pkgSetting) { 6500 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6501 6502 // If "/system/lib64/apkname" exists, assume that is the per-package 6503 // native library directory to use; otherwise use "/system/lib/apkname". 6504 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6505 setBundledAppAbi(pkg, apkRoot, apkName); 6506 // pkgSetting might be null during rescan following uninstall of updates 6507 // to a bundled app, so accommodate that possibility. The settings in 6508 // that case will be established later from the parsed package. 6509 // 6510 // If the settings aren't null, sync them up with what we've just derived. 6511 // note that apkRoot isn't stored in the package settings. 6512 if (pkgSetting != null) { 6513 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6514 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6515 } 6516 } 6517 6518 /** 6519 * Deduces the ABI of a bundled app and sets the relevant fields on the 6520 * parsed pkg object. 6521 * 6522 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6523 * under which system libraries are installed. 6524 * @param apkName the name of the installed package. 6525 */ 6526 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6527 final File codeFile = new File(pkg.codePath); 6528 6529 final boolean has64BitLibs; 6530 final boolean has32BitLibs; 6531 if (isApkFile(codeFile)) { 6532 // Monolithic install 6533 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6534 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6535 } else { 6536 // Cluster install 6537 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6538 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6539 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6540 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6541 has64BitLibs = (new File(rootDir, isa)).exists(); 6542 } else { 6543 has64BitLibs = false; 6544 } 6545 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6546 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6547 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6548 has32BitLibs = (new File(rootDir, isa)).exists(); 6549 } else { 6550 has32BitLibs = false; 6551 } 6552 } 6553 6554 if (has64BitLibs && !has32BitLibs) { 6555 // The package has 64 bit libs, but not 32 bit libs. Its primary 6556 // ABI should be 64 bit. We can safely assume here that the bundled 6557 // native libraries correspond to the most preferred ABI in the list. 6558 6559 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6560 pkg.applicationInfo.secondaryCpuAbi = null; 6561 } else if (has32BitLibs && !has64BitLibs) { 6562 // The package has 32 bit libs but not 64 bit libs. Its primary 6563 // ABI should be 32 bit. 6564 6565 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6566 pkg.applicationInfo.secondaryCpuAbi = null; 6567 } else if (has32BitLibs && has64BitLibs) { 6568 // The application has both 64 and 32 bit bundled libraries. We check 6569 // here that the app declares multiArch support, and warn if it doesn't. 6570 // 6571 // We will be lenient here and record both ABIs. The primary will be the 6572 // ABI that's higher on the list, i.e, a device that's configured to prefer 6573 // 64 bit apps will see a 64 bit primary ABI, 6574 6575 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6576 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6577 } 6578 6579 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6580 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6581 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6582 } else { 6583 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6584 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6585 } 6586 } else { 6587 pkg.applicationInfo.primaryCpuAbi = null; 6588 pkg.applicationInfo.secondaryCpuAbi = null; 6589 } 6590 } 6591 6592 private void killApplication(String pkgName, int appId, String reason) { 6593 // Request the ActivityManager to kill the process(only for existing packages) 6594 // so that we do not end up in a confused state while the user is still using the older 6595 // version of the application while the new one gets installed. 6596 IActivityManager am = ActivityManagerNative.getDefault(); 6597 if (am != null) { 6598 try { 6599 am.killApplicationWithAppId(pkgName, appId, reason); 6600 } catch (RemoteException e) { 6601 } 6602 } 6603 } 6604 6605 void removePackageLI(PackageSetting ps, boolean chatty) { 6606 if (DEBUG_INSTALL) { 6607 if (chatty) 6608 Log.d(TAG, "Removing package " + ps.name); 6609 } 6610 6611 // writer 6612 synchronized (mPackages) { 6613 mPackages.remove(ps.name); 6614 final PackageParser.Package pkg = ps.pkg; 6615 if (pkg != null) { 6616 cleanPackageDataStructuresLILPw(pkg, chatty); 6617 } 6618 } 6619 } 6620 6621 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6622 if (DEBUG_INSTALL) { 6623 if (chatty) 6624 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6625 } 6626 6627 // writer 6628 synchronized (mPackages) { 6629 mPackages.remove(pkg.applicationInfo.packageName); 6630 cleanPackageDataStructuresLILPw(pkg, chatty); 6631 } 6632 } 6633 6634 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6635 int N = pkg.providers.size(); 6636 StringBuilder r = null; 6637 int i; 6638 for (i=0; i<N; i++) { 6639 PackageParser.Provider p = pkg.providers.get(i); 6640 mProviders.removeProvider(p); 6641 if (p.info.authority == null) { 6642 6643 /* There was another ContentProvider with this authority when 6644 * this app was installed so this authority is null, 6645 * Ignore it as we don't have to unregister the provider. 6646 */ 6647 continue; 6648 } 6649 String names[] = p.info.authority.split(";"); 6650 for (int j = 0; j < names.length; j++) { 6651 if (mProvidersByAuthority.get(names[j]) == p) { 6652 mProvidersByAuthority.remove(names[j]); 6653 if (DEBUG_REMOVE) { 6654 if (chatty) 6655 Log.d(TAG, "Unregistered content provider: " + names[j] 6656 + ", className = " + p.info.name + ", isSyncable = " 6657 + p.info.isSyncable); 6658 } 6659 } 6660 } 6661 if (DEBUG_REMOVE && chatty) { 6662 if (r == null) { 6663 r = new StringBuilder(256); 6664 } else { 6665 r.append(' '); 6666 } 6667 r.append(p.info.name); 6668 } 6669 } 6670 if (r != null) { 6671 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6672 } 6673 6674 N = pkg.services.size(); 6675 r = null; 6676 for (i=0; i<N; i++) { 6677 PackageParser.Service s = pkg.services.get(i); 6678 mServices.removeService(s); 6679 if (chatty) { 6680 if (r == null) { 6681 r = new StringBuilder(256); 6682 } else { 6683 r.append(' '); 6684 } 6685 r.append(s.info.name); 6686 } 6687 } 6688 if (r != null) { 6689 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6690 } 6691 6692 N = pkg.receivers.size(); 6693 r = null; 6694 for (i=0; i<N; i++) { 6695 PackageParser.Activity a = pkg.receivers.get(i); 6696 mReceivers.removeActivity(a, "receiver"); 6697 if (DEBUG_REMOVE && chatty) { 6698 if (r == null) { 6699 r = new StringBuilder(256); 6700 } else { 6701 r.append(' '); 6702 } 6703 r.append(a.info.name); 6704 } 6705 } 6706 if (r != null) { 6707 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6708 } 6709 6710 N = pkg.activities.size(); 6711 r = null; 6712 for (i=0; i<N; i++) { 6713 PackageParser.Activity a = pkg.activities.get(i); 6714 mActivities.removeActivity(a, "activity"); 6715 if (DEBUG_REMOVE && chatty) { 6716 if (r == null) { 6717 r = new StringBuilder(256); 6718 } else { 6719 r.append(' '); 6720 } 6721 r.append(a.info.name); 6722 } 6723 } 6724 if (r != null) { 6725 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6726 } 6727 6728 N = pkg.permissions.size(); 6729 r = null; 6730 for (i=0; i<N; i++) { 6731 PackageParser.Permission p = pkg.permissions.get(i); 6732 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6733 if (bp == null) { 6734 bp = mSettings.mPermissionTrees.get(p.info.name); 6735 } 6736 if (bp != null && bp.perm == p) { 6737 bp.perm = null; 6738 if (DEBUG_REMOVE && chatty) { 6739 if (r == null) { 6740 r = new StringBuilder(256); 6741 } else { 6742 r.append(' '); 6743 } 6744 r.append(p.info.name); 6745 } 6746 } 6747 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6748 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6749 if (appOpPerms != null) { 6750 appOpPerms.remove(pkg.packageName); 6751 } 6752 } 6753 } 6754 if (r != null) { 6755 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6756 } 6757 6758 N = pkg.requestedPermissions.size(); 6759 r = null; 6760 for (i=0; i<N; i++) { 6761 String perm = pkg.requestedPermissions.get(i); 6762 BasePermission bp = mSettings.mPermissions.get(perm); 6763 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6764 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6765 if (appOpPerms != null) { 6766 appOpPerms.remove(pkg.packageName); 6767 if (appOpPerms.isEmpty()) { 6768 mAppOpPermissionPackages.remove(perm); 6769 } 6770 } 6771 } 6772 } 6773 if (r != null) { 6774 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6775 } 6776 6777 N = pkg.instrumentation.size(); 6778 r = null; 6779 for (i=0; i<N; i++) { 6780 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6781 mInstrumentation.remove(a.getComponentName()); 6782 if (DEBUG_REMOVE && chatty) { 6783 if (r == null) { 6784 r = new StringBuilder(256); 6785 } else { 6786 r.append(' '); 6787 } 6788 r.append(a.info.name); 6789 } 6790 } 6791 if (r != null) { 6792 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6793 } 6794 6795 r = null; 6796 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6797 // Only system apps can hold shared libraries. 6798 if (pkg.libraryNames != null) { 6799 for (i=0; i<pkg.libraryNames.size(); i++) { 6800 String name = pkg.libraryNames.get(i); 6801 SharedLibraryEntry cur = mSharedLibraries.get(name); 6802 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6803 mSharedLibraries.remove(name); 6804 if (DEBUG_REMOVE && chatty) { 6805 if (r == null) { 6806 r = new StringBuilder(256); 6807 } else { 6808 r.append(' '); 6809 } 6810 r.append(name); 6811 } 6812 } 6813 } 6814 } 6815 } 6816 if (r != null) { 6817 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6818 } 6819 } 6820 6821 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6822 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6823 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6824 return true; 6825 } 6826 } 6827 return false; 6828 } 6829 6830 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6831 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6832 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6833 6834 private void updatePermissionsLPw(String changingPkg, 6835 PackageParser.Package pkgInfo, int flags) { 6836 // Make sure there are no dangling permission trees. 6837 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6838 while (it.hasNext()) { 6839 final BasePermission bp = it.next(); 6840 if (bp.packageSetting == null) { 6841 // We may not yet have parsed the package, so just see if 6842 // we still know about its settings. 6843 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6844 } 6845 if (bp.packageSetting == null) { 6846 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6847 + " from package " + bp.sourcePackage); 6848 it.remove(); 6849 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6850 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6851 Slog.i(TAG, "Removing old permission tree: " + bp.name 6852 + " from package " + bp.sourcePackage); 6853 flags |= UPDATE_PERMISSIONS_ALL; 6854 it.remove(); 6855 } 6856 } 6857 } 6858 6859 // Make sure all dynamic permissions have been assigned to a package, 6860 // and make sure there are no dangling permissions. 6861 it = mSettings.mPermissions.values().iterator(); 6862 while (it.hasNext()) { 6863 final BasePermission bp = it.next(); 6864 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6865 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6866 + bp.name + " pkg=" + bp.sourcePackage 6867 + " info=" + bp.pendingInfo); 6868 if (bp.packageSetting == null && bp.pendingInfo != null) { 6869 final BasePermission tree = findPermissionTreeLP(bp.name); 6870 if (tree != null && tree.perm != null) { 6871 bp.packageSetting = tree.packageSetting; 6872 bp.perm = new PackageParser.Permission(tree.perm.owner, 6873 new PermissionInfo(bp.pendingInfo)); 6874 bp.perm.info.packageName = tree.perm.info.packageName; 6875 bp.perm.info.name = bp.name; 6876 bp.uid = tree.uid; 6877 } 6878 } 6879 } 6880 if (bp.packageSetting == null) { 6881 // We may not yet have parsed the package, so just see if 6882 // we still know about its settings. 6883 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6884 } 6885 if (bp.packageSetting == null) { 6886 Slog.w(TAG, "Removing dangling permission: " + bp.name 6887 + " from package " + bp.sourcePackage); 6888 it.remove(); 6889 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6890 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6891 Slog.i(TAG, "Removing old permission: " + bp.name 6892 + " from package " + bp.sourcePackage); 6893 flags |= UPDATE_PERMISSIONS_ALL; 6894 it.remove(); 6895 } 6896 } 6897 } 6898 6899 // Now update the permissions for all packages, in particular 6900 // replace the granted permissions of the system packages. 6901 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6902 for (PackageParser.Package pkg : mPackages.values()) { 6903 if (pkg != pkgInfo) { 6904 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6905 changingPkg); 6906 } 6907 } 6908 } 6909 6910 if (pkgInfo != null) { 6911 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6912 } 6913 } 6914 6915 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6916 String packageOfInterest) { 6917 // IMPORTANT: There are two types of permissions: install and runtime. 6918 // Install time permissions are granted when the app is installed to 6919 // all device users and users added in the future. Runtime permissions 6920 // are granted at runtime explicitly to specific users. Normal and signature 6921 // protected permissions are install time permissions. Dangerous permissions 6922 // are install permissions if the app's target SDK is Lollipop MR1 or older, 6923 // otherwise they are runtime permissions. This function does not manage 6924 // runtime permissions except for the case an app targeting Lollipop MR1 6925 // being upgraded to target a newer SDK, in which case dangerous permissions 6926 // are transformed from install time to runtime ones. 6927 6928 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6929 if (ps == null) { 6930 return; 6931 } 6932 6933 PermissionsState permissionsState = ps.getPermissionsState(); 6934 PermissionsState origPermissions = permissionsState; 6935 6936 boolean changedPermission = false; 6937 6938 if (replace) { 6939 ps.permissionsFixed = false; 6940 origPermissions = new PermissionsState(permissionsState); 6941 permissionsState.reset(); 6942 } 6943 6944 permissionsState.setGlobalGids(mGlobalGids); 6945 6946 final int N = pkg.requestedPermissions.size(); 6947 for (int i=0; i<N; i++) { 6948 final String name = pkg.requestedPermissions.get(i); 6949 final BasePermission bp = mSettings.mPermissions.get(name); 6950 6951 if (DEBUG_INSTALL) { 6952 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6953 } 6954 6955 if (bp == null || bp.packageSetting == null) { 6956 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6957 Slog.w(TAG, "Unknown permission " + name 6958 + " in package " + pkg.packageName); 6959 } 6960 continue; 6961 } 6962 6963 final String perm = bp.name; 6964 boolean allowedSig = false; 6965 int grant = GRANT_DENIED; 6966 6967 // Keep track of app op permissions. 6968 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6969 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6970 if (pkgs == null) { 6971 pkgs = new ArraySet<>(); 6972 mAppOpPermissionPackages.put(bp.name, pkgs); 6973 } 6974 pkgs.add(pkg.packageName); 6975 } 6976 6977 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6978 switch (level) { 6979 case PermissionInfo.PROTECTION_NORMAL: { 6980 // For all apps normal permissions are install time ones. 6981 grant = GRANT_INSTALL; 6982 } break; 6983 6984 case PermissionInfo.PROTECTION_DANGEROUS: { 6985 if (!RUNTIME_PERMISSIONS_ENABLED 6986 || pkg.applicationInfo.targetSdkVersion 6987 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 6988 // For legacy apps dangerous permissions are install time ones. 6989 grant = GRANT_INSTALL; 6990 } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6991 // For modern system apps dangerous permissions are install time ones. 6992 grant = GRANT_INSTALL; 6993 } else { 6994 if (origPermissions.hasInstallPermission(bp.name)) { 6995 // For legacy apps that became modern, install becomes runtime. 6996 grant = GRANT_UPGRADE; 6997 } else if (replace) { 6998 // For upgraded modern apps keep runtime permissions unchanged. 6999 grant = GRANT_RUNTIME; 7000 } 7001 } 7002 } break; 7003 7004 case PermissionInfo.PROTECTION_SIGNATURE: { 7005 // For all apps signature permissions are install time ones. 7006 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7007 if (allowedSig) { 7008 grant = GRANT_INSTALL; 7009 } 7010 } break; 7011 } 7012 7013 if (DEBUG_INSTALL) { 7014 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7015 } 7016 7017 if (grant != GRANT_DENIED) { 7018 if (!isSystemApp(ps) && ps.permissionsFixed) { 7019 // If this is an existing, non-system package, then 7020 // we can't add any new permissions to it. 7021 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7022 // Except... if this is a permission that was added 7023 // to the platform (note: need to only do this when 7024 // updating the platform). 7025 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7026 grant = GRANT_DENIED; 7027 } 7028 } 7029 } 7030 7031 switch (grant) { 7032 case GRANT_INSTALL: { 7033 // Grant an install permission. 7034 if (permissionsState.grantInstallPermission(bp) != 7035 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7036 changedPermission = true; 7037 } 7038 } break; 7039 7040 case GRANT_RUNTIME: { 7041 // Grant previously granted runtime permissions. 7042 for (int userId : UserManagerService.getInstance().getUserIds()) { 7043 // Make sure runtime permissions are loaded. 7044 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7045 if (permissionsState.grantRuntimePermission(bp, userId) != 7046 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7047 changedPermission = true; 7048 } 7049 } 7050 } 7051 } break; 7052 7053 case GRANT_UPGRADE: { 7054 // Grant runtime permissions for a previously held install permission. 7055 permissionsState.revokeInstallPermission(bp); 7056 for (int userId : UserManagerService.getInstance().getUserIds()) { 7057 // Make sure runtime permissions are loaded. 7058 if (permissionsState.grantRuntimePermission(bp, userId) != 7059 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7060 changedPermission = true; 7061 } 7062 } 7063 } break; 7064 7065 default: { 7066 if (packageOfInterest == null 7067 || packageOfInterest.equals(pkg.packageName)) { 7068 Slog.w(TAG, "Not granting permission " + perm 7069 + " to package " + pkg.packageName 7070 + " because it was previously installed without"); 7071 } 7072 } break; 7073 } 7074 } else { 7075 if (permissionsState.revokeInstallPermission(bp) != 7076 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7077 changedPermission = true; 7078 Slog.i(TAG, "Un-granting permission " + perm 7079 + " from package " + pkg.packageName 7080 + " (protectionLevel=" + bp.protectionLevel 7081 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7082 + ")"); 7083 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7084 // Don't print warning for app op permissions, since it is fine for them 7085 // not to be granted, there is a UI for the user to decide. 7086 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7087 Slog.w(TAG, "Not granting permission " + perm 7088 + " to package " + pkg.packageName 7089 + " (protectionLevel=" + bp.protectionLevel 7090 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7091 + ")"); 7092 } 7093 } 7094 } 7095 } 7096 7097 if ((changedPermission || replace) && !ps.permissionsFixed && 7098 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7099 // This is the first that we have heard about this package, so the 7100 // permissions we have now selected are fixed until explicitly 7101 // changed. 7102 ps.permissionsFixed = true; 7103 } 7104 } 7105 7106 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7107 boolean allowed = false; 7108 final int NP = PackageParser.NEW_PERMISSIONS.length; 7109 for (int ip=0; ip<NP; ip++) { 7110 final PackageParser.NewPermissionInfo npi 7111 = PackageParser.NEW_PERMISSIONS[ip]; 7112 if (npi.name.equals(perm) 7113 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7114 allowed = true; 7115 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7116 + pkg.packageName); 7117 break; 7118 } 7119 } 7120 return allowed; 7121 } 7122 7123 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7124 BasePermission bp, PermissionsState origPermissions) { 7125 boolean allowed; 7126 allowed = (compareSignatures( 7127 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7128 == PackageManager.SIGNATURE_MATCH) 7129 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7130 == PackageManager.SIGNATURE_MATCH); 7131 if (!allowed && (bp.protectionLevel 7132 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7133 if (isSystemApp(pkg)) { 7134 // For updated system applications, a system permission 7135 // is granted only if it had been defined by the original application. 7136 if (isUpdatedSystemApp(pkg)) { 7137 final PackageSetting sysPs = mSettings 7138 .getDisabledSystemPkgLPr(pkg.packageName); 7139 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7140 // If the original was granted this permission, we take 7141 // that grant decision as read and propagate it to the 7142 // update. 7143 if (sysPs.isPrivileged()) { 7144 allowed = true; 7145 } 7146 } else { 7147 // The system apk may have been updated with an older 7148 // version of the one on the data partition, but which 7149 // granted a new system permission that it didn't have 7150 // before. In this case we do want to allow the app to 7151 // now get the new permission if the ancestral apk is 7152 // privileged to get it. 7153 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7154 for (int j=0; 7155 j<sysPs.pkg.requestedPermissions.size(); j++) { 7156 if (perm.equals( 7157 sysPs.pkg.requestedPermissions.get(j))) { 7158 allowed = true; 7159 break; 7160 } 7161 } 7162 } 7163 } 7164 } else { 7165 allowed = isPrivilegedApp(pkg); 7166 } 7167 } 7168 } 7169 if (!allowed && (bp.protectionLevel 7170 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7171 // For development permissions, a development permission 7172 // is granted only if it was already granted. 7173 allowed = origPermissions.hasInstallPermission(perm); 7174 } 7175 return allowed; 7176 } 7177 7178 final class ActivityIntentResolver 7179 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7181 boolean defaultOnly, int userId) { 7182 if (!sUserManager.exists(userId)) return null; 7183 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7184 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7185 } 7186 7187 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7188 int userId) { 7189 if (!sUserManager.exists(userId)) return null; 7190 mFlags = flags; 7191 return super.queryIntent(intent, resolvedType, 7192 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7193 } 7194 7195 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7196 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7197 if (!sUserManager.exists(userId)) return null; 7198 if (packageActivities == null) { 7199 return null; 7200 } 7201 mFlags = flags; 7202 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7203 final int N = packageActivities.size(); 7204 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7205 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7206 7207 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7208 for (int i = 0; i < N; ++i) { 7209 intentFilters = packageActivities.get(i).intents; 7210 if (intentFilters != null && intentFilters.size() > 0) { 7211 PackageParser.ActivityIntentInfo[] array = 7212 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7213 intentFilters.toArray(array); 7214 listCut.add(array); 7215 } 7216 } 7217 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7218 } 7219 7220 public final void addActivity(PackageParser.Activity a, String type) { 7221 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7222 mActivities.put(a.getComponentName(), a); 7223 if (DEBUG_SHOW_INFO) 7224 Log.v( 7225 TAG, " " + type + " " + 7226 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7227 if (DEBUG_SHOW_INFO) 7228 Log.v(TAG, " Class=" + a.info.name); 7229 final int NI = a.intents.size(); 7230 for (int j=0; j<NI; j++) { 7231 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7232 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7233 intent.setPriority(0); 7234 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7235 + a.className + " with priority > 0, forcing to 0"); 7236 } 7237 if (DEBUG_SHOW_INFO) { 7238 Log.v(TAG, " IntentFilter:"); 7239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7240 } 7241 if (!intent.debugCheck()) { 7242 Log.w(TAG, "==> For Activity " + a.info.name); 7243 } 7244 addFilter(intent); 7245 } 7246 } 7247 7248 public final void removeActivity(PackageParser.Activity a, String type) { 7249 mActivities.remove(a.getComponentName()); 7250 if (DEBUG_SHOW_INFO) { 7251 Log.v(TAG, " " + type + " " 7252 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7253 : a.info.name) + ":"); 7254 Log.v(TAG, " Class=" + a.info.name); 7255 } 7256 final int NI = a.intents.size(); 7257 for (int j=0; j<NI; j++) { 7258 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7259 if (DEBUG_SHOW_INFO) { 7260 Log.v(TAG, " IntentFilter:"); 7261 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7262 } 7263 removeFilter(intent); 7264 } 7265 } 7266 7267 @Override 7268 protected boolean allowFilterResult( 7269 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7270 ActivityInfo filterAi = filter.activity.info; 7271 for (int i=dest.size()-1; i>=0; i--) { 7272 ActivityInfo destAi = dest.get(i).activityInfo; 7273 if (destAi.name == filterAi.name 7274 && destAi.packageName == filterAi.packageName) { 7275 return false; 7276 } 7277 } 7278 return true; 7279 } 7280 7281 @Override 7282 protected ActivityIntentInfo[] newArray(int size) { 7283 return new ActivityIntentInfo[size]; 7284 } 7285 7286 @Override 7287 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7288 if (!sUserManager.exists(userId)) return true; 7289 PackageParser.Package p = filter.activity.owner; 7290 if (p != null) { 7291 PackageSetting ps = (PackageSetting)p.mExtras; 7292 if (ps != null) { 7293 // System apps are never considered stopped for purposes of 7294 // filtering, because there may be no way for the user to 7295 // actually re-launch them. 7296 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7297 && ps.getStopped(userId); 7298 } 7299 } 7300 return false; 7301 } 7302 7303 @Override 7304 protected boolean isPackageForFilter(String packageName, 7305 PackageParser.ActivityIntentInfo info) { 7306 return packageName.equals(info.activity.owner.packageName); 7307 } 7308 7309 @Override 7310 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7311 int match, int userId) { 7312 if (!sUserManager.exists(userId)) return null; 7313 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7314 return null; 7315 } 7316 final PackageParser.Activity activity = info.activity; 7317 if (mSafeMode && (activity.info.applicationInfo.flags 7318 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7319 return null; 7320 } 7321 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7322 if (ps == null) { 7323 return null; 7324 } 7325 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7326 ps.readUserState(userId), userId); 7327 if (ai == null) { 7328 return null; 7329 } 7330 final ResolveInfo res = new ResolveInfo(); 7331 res.activityInfo = ai; 7332 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7333 res.filter = info; 7334 } 7335 res.priority = info.getPriority(); 7336 res.preferredOrder = activity.owner.mPreferredOrder; 7337 //System.out.println("Result: " + res.activityInfo.className + 7338 // " = " + res.priority); 7339 res.match = match; 7340 res.isDefault = info.hasDefault; 7341 res.labelRes = info.labelRes; 7342 res.nonLocalizedLabel = info.nonLocalizedLabel; 7343 if (userNeedsBadging(userId)) { 7344 res.noResourceId = true; 7345 } else { 7346 res.icon = info.icon; 7347 } 7348 res.system = isSystemApp(res.activityInfo.applicationInfo); 7349 return res; 7350 } 7351 7352 @Override 7353 protected void sortResults(List<ResolveInfo> results) { 7354 Collections.sort(results, mResolvePrioritySorter); 7355 } 7356 7357 @Override 7358 protected void dumpFilter(PrintWriter out, String prefix, 7359 PackageParser.ActivityIntentInfo filter) { 7360 out.print(prefix); out.print( 7361 Integer.toHexString(System.identityHashCode(filter.activity))); 7362 out.print(' '); 7363 filter.activity.printComponentShortName(out); 7364 out.print(" filter "); 7365 out.println(Integer.toHexString(System.identityHashCode(filter))); 7366 } 7367 7368 @Override 7369 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7370 return filter.activity; 7371 } 7372 7373 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7374 PackageParser.Activity activity = (PackageParser.Activity)label; 7375 out.print(prefix); out.print( 7376 Integer.toHexString(System.identityHashCode(activity))); 7377 out.print(' '); 7378 activity.printComponentShortName(out); 7379 if (count > 1) { 7380 out.print(" ("); out.print(count); out.print(" filters)"); 7381 } 7382 out.println(); 7383 } 7384 7385// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7386// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7387// final List<ResolveInfo> retList = Lists.newArrayList(); 7388// while (i.hasNext()) { 7389// final ResolveInfo resolveInfo = i.next(); 7390// if (isEnabledLP(resolveInfo.activityInfo)) { 7391// retList.add(resolveInfo); 7392// } 7393// } 7394// return retList; 7395// } 7396 7397 // Keys are String (activity class name), values are Activity. 7398 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7399 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7400 private int mFlags; 7401 } 7402 7403 private final class ServiceIntentResolver 7404 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7405 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7406 boolean defaultOnly, int userId) { 7407 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7408 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7409 } 7410 7411 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7412 int userId) { 7413 if (!sUserManager.exists(userId)) return null; 7414 mFlags = flags; 7415 return super.queryIntent(intent, resolvedType, 7416 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7417 } 7418 7419 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7420 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7421 if (!sUserManager.exists(userId)) return null; 7422 if (packageServices == null) { 7423 return null; 7424 } 7425 mFlags = flags; 7426 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7427 final int N = packageServices.size(); 7428 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7429 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7430 7431 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7432 for (int i = 0; i < N; ++i) { 7433 intentFilters = packageServices.get(i).intents; 7434 if (intentFilters != null && intentFilters.size() > 0) { 7435 PackageParser.ServiceIntentInfo[] array = 7436 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7437 intentFilters.toArray(array); 7438 listCut.add(array); 7439 } 7440 } 7441 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7442 } 7443 7444 public final void addService(PackageParser.Service s) { 7445 mServices.put(s.getComponentName(), s); 7446 if (DEBUG_SHOW_INFO) { 7447 Log.v(TAG, " " 7448 + (s.info.nonLocalizedLabel != null 7449 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7450 Log.v(TAG, " Class=" + s.info.name); 7451 } 7452 final int NI = s.intents.size(); 7453 int j; 7454 for (j=0; j<NI; j++) { 7455 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7456 if (DEBUG_SHOW_INFO) { 7457 Log.v(TAG, " IntentFilter:"); 7458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7459 } 7460 if (!intent.debugCheck()) { 7461 Log.w(TAG, "==> For Service " + s.info.name); 7462 } 7463 addFilter(intent); 7464 } 7465 } 7466 7467 public final void removeService(PackageParser.Service s) { 7468 mServices.remove(s.getComponentName()); 7469 if (DEBUG_SHOW_INFO) { 7470 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7471 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7472 Log.v(TAG, " Class=" + s.info.name); 7473 } 7474 final int NI = s.intents.size(); 7475 int j; 7476 for (j=0; j<NI; j++) { 7477 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7478 if (DEBUG_SHOW_INFO) { 7479 Log.v(TAG, " IntentFilter:"); 7480 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7481 } 7482 removeFilter(intent); 7483 } 7484 } 7485 7486 @Override 7487 protected boolean allowFilterResult( 7488 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7489 ServiceInfo filterSi = filter.service.info; 7490 for (int i=dest.size()-1; i>=0; i--) { 7491 ServiceInfo destAi = dest.get(i).serviceInfo; 7492 if (destAi.name == filterSi.name 7493 && destAi.packageName == filterSi.packageName) { 7494 return false; 7495 } 7496 } 7497 return true; 7498 } 7499 7500 @Override 7501 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7502 return new PackageParser.ServiceIntentInfo[size]; 7503 } 7504 7505 @Override 7506 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7507 if (!sUserManager.exists(userId)) return true; 7508 PackageParser.Package p = filter.service.owner; 7509 if (p != null) { 7510 PackageSetting ps = (PackageSetting)p.mExtras; 7511 if (ps != null) { 7512 // System apps are never considered stopped for purposes of 7513 // filtering, because there may be no way for the user to 7514 // actually re-launch them. 7515 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7516 && ps.getStopped(userId); 7517 } 7518 } 7519 return false; 7520 } 7521 7522 @Override 7523 protected boolean isPackageForFilter(String packageName, 7524 PackageParser.ServiceIntentInfo info) { 7525 return packageName.equals(info.service.owner.packageName); 7526 } 7527 7528 @Override 7529 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7530 int match, int userId) { 7531 if (!sUserManager.exists(userId)) return null; 7532 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7533 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7534 return null; 7535 } 7536 final PackageParser.Service service = info.service; 7537 if (mSafeMode && (service.info.applicationInfo.flags 7538 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7539 return null; 7540 } 7541 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7542 if (ps == null) { 7543 return null; 7544 } 7545 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7546 ps.readUserState(userId), userId); 7547 if (si == null) { 7548 return null; 7549 } 7550 final ResolveInfo res = new ResolveInfo(); 7551 res.serviceInfo = si; 7552 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7553 res.filter = filter; 7554 } 7555 res.priority = info.getPriority(); 7556 res.preferredOrder = service.owner.mPreferredOrder; 7557 //System.out.println("Result: " + res.activityInfo.className + 7558 // " = " + res.priority); 7559 res.match = match; 7560 res.isDefault = info.hasDefault; 7561 res.labelRes = info.labelRes; 7562 res.nonLocalizedLabel = info.nonLocalizedLabel; 7563 res.icon = info.icon; 7564 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7565 return res; 7566 } 7567 7568 @Override 7569 protected void sortResults(List<ResolveInfo> results) { 7570 Collections.sort(results, mResolvePrioritySorter); 7571 } 7572 7573 @Override 7574 protected void dumpFilter(PrintWriter out, String prefix, 7575 PackageParser.ServiceIntentInfo filter) { 7576 out.print(prefix); out.print( 7577 Integer.toHexString(System.identityHashCode(filter.service))); 7578 out.print(' '); 7579 filter.service.printComponentShortName(out); 7580 out.print(" filter "); 7581 out.println(Integer.toHexString(System.identityHashCode(filter))); 7582 } 7583 7584 @Override 7585 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7586 return filter.service; 7587 } 7588 7589 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7590 PackageParser.Service service = (PackageParser.Service)label; 7591 out.print(prefix); out.print( 7592 Integer.toHexString(System.identityHashCode(service))); 7593 out.print(' '); 7594 service.printComponentShortName(out); 7595 if (count > 1) { 7596 out.print(" ("); out.print(count); out.print(" filters)"); 7597 } 7598 out.println(); 7599 } 7600 7601// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7602// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7603// final List<ResolveInfo> retList = Lists.newArrayList(); 7604// while (i.hasNext()) { 7605// final ResolveInfo resolveInfo = (ResolveInfo) i; 7606// if (isEnabledLP(resolveInfo.serviceInfo)) { 7607// retList.add(resolveInfo); 7608// } 7609// } 7610// return retList; 7611// } 7612 7613 // Keys are String (activity class name), values are Activity. 7614 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7615 = new ArrayMap<ComponentName, PackageParser.Service>(); 7616 private int mFlags; 7617 }; 7618 7619 private final class ProviderIntentResolver 7620 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7621 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7622 boolean defaultOnly, int userId) { 7623 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7624 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7625 } 7626 7627 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7628 int userId) { 7629 if (!sUserManager.exists(userId)) 7630 return null; 7631 mFlags = flags; 7632 return super.queryIntent(intent, resolvedType, 7633 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7634 } 7635 7636 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7637 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7638 if (!sUserManager.exists(userId)) 7639 return null; 7640 if (packageProviders == null) { 7641 return null; 7642 } 7643 mFlags = flags; 7644 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7645 final int N = packageProviders.size(); 7646 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7647 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7648 7649 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7650 for (int i = 0; i < N; ++i) { 7651 intentFilters = packageProviders.get(i).intents; 7652 if (intentFilters != null && intentFilters.size() > 0) { 7653 PackageParser.ProviderIntentInfo[] array = 7654 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7655 intentFilters.toArray(array); 7656 listCut.add(array); 7657 } 7658 } 7659 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7660 } 7661 7662 public final void addProvider(PackageParser.Provider p) { 7663 if (mProviders.containsKey(p.getComponentName())) { 7664 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7665 return; 7666 } 7667 7668 mProviders.put(p.getComponentName(), p); 7669 if (DEBUG_SHOW_INFO) { 7670 Log.v(TAG, " " 7671 + (p.info.nonLocalizedLabel != null 7672 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7673 Log.v(TAG, " Class=" + p.info.name); 7674 } 7675 final int NI = p.intents.size(); 7676 int j; 7677 for (j = 0; j < NI; j++) { 7678 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7679 if (DEBUG_SHOW_INFO) { 7680 Log.v(TAG, " IntentFilter:"); 7681 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7682 } 7683 if (!intent.debugCheck()) { 7684 Log.w(TAG, "==> For Provider " + p.info.name); 7685 } 7686 addFilter(intent); 7687 } 7688 } 7689 7690 public final void removeProvider(PackageParser.Provider p) { 7691 mProviders.remove(p.getComponentName()); 7692 if (DEBUG_SHOW_INFO) { 7693 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7694 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7695 Log.v(TAG, " Class=" + p.info.name); 7696 } 7697 final int NI = p.intents.size(); 7698 int j; 7699 for (j = 0; j < NI; j++) { 7700 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7701 if (DEBUG_SHOW_INFO) { 7702 Log.v(TAG, " IntentFilter:"); 7703 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7704 } 7705 removeFilter(intent); 7706 } 7707 } 7708 7709 @Override 7710 protected boolean allowFilterResult( 7711 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7712 ProviderInfo filterPi = filter.provider.info; 7713 for (int i = dest.size() - 1; i >= 0; i--) { 7714 ProviderInfo destPi = dest.get(i).providerInfo; 7715 if (destPi.name == filterPi.name 7716 && destPi.packageName == filterPi.packageName) { 7717 return false; 7718 } 7719 } 7720 return true; 7721 } 7722 7723 @Override 7724 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7725 return new PackageParser.ProviderIntentInfo[size]; 7726 } 7727 7728 @Override 7729 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7730 if (!sUserManager.exists(userId)) 7731 return true; 7732 PackageParser.Package p = filter.provider.owner; 7733 if (p != null) { 7734 PackageSetting ps = (PackageSetting) p.mExtras; 7735 if (ps != null) { 7736 // System apps are never considered stopped for purposes of 7737 // filtering, because there may be no way for the user to 7738 // actually re-launch them. 7739 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7740 && ps.getStopped(userId); 7741 } 7742 } 7743 return false; 7744 } 7745 7746 @Override 7747 protected boolean isPackageForFilter(String packageName, 7748 PackageParser.ProviderIntentInfo info) { 7749 return packageName.equals(info.provider.owner.packageName); 7750 } 7751 7752 @Override 7753 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7754 int match, int userId) { 7755 if (!sUserManager.exists(userId)) 7756 return null; 7757 final PackageParser.ProviderIntentInfo info = filter; 7758 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7759 return null; 7760 } 7761 final PackageParser.Provider provider = info.provider; 7762 if (mSafeMode && (provider.info.applicationInfo.flags 7763 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7764 return null; 7765 } 7766 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7767 if (ps == null) { 7768 return null; 7769 } 7770 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7771 ps.readUserState(userId), userId); 7772 if (pi == null) { 7773 return null; 7774 } 7775 final ResolveInfo res = new ResolveInfo(); 7776 res.providerInfo = pi; 7777 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7778 res.filter = filter; 7779 } 7780 res.priority = info.getPriority(); 7781 res.preferredOrder = provider.owner.mPreferredOrder; 7782 res.match = match; 7783 res.isDefault = info.hasDefault; 7784 res.labelRes = info.labelRes; 7785 res.nonLocalizedLabel = info.nonLocalizedLabel; 7786 res.icon = info.icon; 7787 res.system = isSystemApp(res.providerInfo.applicationInfo); 7788 return res; 7789 } 7790 7791 @Override 7792 protected void sortResults(List<ResolveInfo> results) { 7793 Collections.sort(results, mResolvePrioritySorter); 7794 } 7795 7796 @Override 7797 protected void dumpFilter(PrintWriter out, String prefix, 7798 PackageParser.ProviderIntentInfo filter) { 7799 out.print(prefix); 7800 out.print( 7801 Integer.toHexString(System.identityHashCode(filter.provider))); 7802 out.print(' '); 7803 filter.provider.printComponentShortName(out); 7804 out.print(" filter "); 7805 out.println(Integer.toHexString(System.identityHashCode(filter))); 7806 } 7807 7808 @Override 7809 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7810 return filter.provider; 7811 } 7812 7813 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7814 PackageParser.Provider provider = (PackageParser.Provider)label; 7815 out.print(prefix); out.print( 7816 Integer.toHexString(System.identityHashCode(provider))); 7817 out.print(' '); 7818 provider.printComponentShortName(out); 7819 if (count > 1) { 7820 out.print(" ("); out.print(count); out.print(" filters)"); 7821 } 7822 out.println(); 7823 } 7824 7825 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7826 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7827 private int mFlags; 7828 }; 7829 7830 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7831 new Comparator<ResolveInfo>() { 7832 public int compare(ResolveInfo r1, ResolveInfo r2) { 7833 int v1 = r1.priority; 7834 int v2 = r2.priority; 7835 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7836 if (v1 != v2) { 7837 return (v1 > v2) ? -1 : 1; 7838 } 7839 v1 = r1.preferredOrder; 7840 v2 = r2.preferredOrder; 7841 if (v1 != v2) { 7842 return (v1 > v2) ? -1 : 1; 7843 } 7844 if (r1.isDefault != r2.isDefault) { 7845 return r1.isDefault ? -1 : 1; 7846 } 7847 v1 = r1.match; 7848 v2 = r2.match; 7849 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7850 if (v1 != v2) { 7851 return (v1 > v2) ? -1 : 1; 7852 } 7853 if (r1.system != r2.system) { 7854 return r1.system ? -1 : 1; 7855 } 7856 return 0; 7857 } 7858 }; 7859 7860 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7861 new Comparator<ProviderInfo>() { 7862 public int compare(ProviderInfo p1, ProviderInfo p2) { 7863 final int v1 = p1.initOrder; 7864 final int v2 = p2.initOrder; 7865 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7866 } 7867 }; 7868 7869 static final void sendPackageBroadcast(String action, String pkg, 7870 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7871 int[] userIds) { 7872 IActivityManager am = ActivityManagerNative.getDefault(); 7873 if (am != null) { 7874 try { 7875 if (userIds == null) { 7876 userIds = am.getRunningUserIds(); 7877 } 7878 for (int id : userIds) { 7879 final Intent intent = new Intent(action, 7880 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7881 if (extras != null) { 7882 intent.putExtras(extras); 7883 } 7884 if (targetPkg != null) { 7885 intent.setPackage(targetPkg); 7886 } 7887 // Modify the UID when posting to other users 7888 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7889 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7890 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7891 intent.putExtra(Intent.EXTRA_UID, uid); 7892 } 7893 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7894 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7895 if (DEBUG_BROADCASTS) { 7896 RuntimeException here = new RuntimeException("here"); 7897 here.fillInStackTrace(); 7898 Slog.d(TAG, "Sending to user " + id + ": " 7899 + intent.toShortString(false, true, false, false) 7900 + " " + intent.getExtras(), here); 7901 } 7902 am.broadcastIntent(null, intent, null, finishedReceiver, 7903 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7904 finishedReceiver != null, false, id); 7905 } 7906 } catch (RemoteException ex) { 7907 } 7908 } 7909 } 7910 7911 /** 7912 * Check if the external storage media is available. This is true if there 7913 * is a mounted external storage medium or if the external storage is 7914 * emulated. 7915 */ 7916 private boolean isExternalMediaAvailable() { 7917 return mMediaMounted || Environment.isExternalStorageEmulated(); 7918 } 7919 7920 @Override 7921 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7922 // writer 7923 synchronized (mPackages) { 7924 if (!isExternalMediaAvailable()) { 7925 // If the external storage is no longer mounted at this point, 7926 // the caller may not have been able to delete all of this 7927 // packages files and can not delete any more. Bail. 7928 return null; 7929 } 7930 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7931 if (lastPackage != null) { 7932 pkgs.remove(lastPackage); 7933 } 7934 if (pkgs.size() > 0) { 7935 return pkgs.get(0); 7936 } 7937 } 7938 return null; 7939 } 7940 7941 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7942 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7943 userId, andCode ? 1 : 0, packageName); 7944 if (mSystemReady) { 7945 msg.sendToTarget(); 7946 } else { 7947 if (mPostSystemReadyMessages == null) { 7948 mPostSystemReadyMessages = new ArrayList<>(); 7949 } 7950 mPostSystemReadyMessages.add(msg); 7951 } 7952 } 7953 7954 void startCleaningPackages() { 7955 // reader 7956 synchronized (mPackages) { 7957 if (!isExternalMediaAvailable()) { 7958 return; 7959 } 7960 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7961 return; 7962 } 7963 } 7964 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7965 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7966 IActivityManager am = ActivityManagerNative.getDefault(); 7967 if (am != null) { 7968 try { 7969 am.startService(null, intent, null, UserHandle.USER_OWNER); 7970 } catch (RemoteException e) { 7971 } 7972 } 7973 } 7974 7975 @Override 7976 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7977 int installFlags, String installerPackageName, VerificationParams verificationParams, 7978 String packageAbiOverride) { 7979 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7980 packageAbiOverride, UserHandle.getCallingUserId()); 7981 } 7982 7983 @Override 7984 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7985 int installFlags, String installerPackageName, VerificationParams verificationParams, 7986 String packageAbiOverride, int userId) { 7987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7988 7989 final int callingUid = Binder.getCallingUid(); 7990 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7991 7992 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7993 try { 7994 if (observer != null) { 7995 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7996 } 7997 } catch (RemoteException re) { 7998 } 7999 return; 8000 } 8001 8002 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8003 installFlags |= PackageManager.INSTALL_FROM_ADB; 8004 8005 } else { 8006 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8007 // about installerPackageName. 8008 8009 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8010 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8011 } 8012 8013 UserHandle user; 8014 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8015 user = UserHandle.ALL; 8016 } else { 8017 user = new UserHandle(userId); 8018 } 8019 8020 verificationParams.setInstallerUid(callingUid); 8021 8022 final File originFile = new File(originPath); 8023 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8024 8025 final Message msg = mHandler.obtainMessage(INIT_COPY); 8026 msg.obj = new InstallParams(origin, observer, installFlags, 8027 installerPackageName, verificationParams, user, packageAbiOverride); 8028 mHandler.sendMessage(msg); 8029 } 8030 8031 void installStage(String packageName, File stagedDir, String stagedCid, 8032 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8033 String installerPackageName, int installerUid, UserHandle user) { 8034 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8035 params.referrerUri, installerUid, null); 8036 8037 final OriginInfo origin; 8038 if (stagedDir != null) { 8039 origin = OriginInfo.fromStagedFile(stagedDir); 8040 } else { 8041 origin = OriginInfo.fromStagedContainer(stagedCid); 8042 } 8043 8044 final Message msg = mHandler.obtainMessage(INIT_COPY); 8045 msg.obj = new InstallParams(origin, observer, params.installFlags, 8046 installerPackageName, verifParams, user, params.abiOverride); 8047 mHandler.sendMessage(msg); 8048 } 8049 8050 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8051 Bundle extras = new Bundle(1); 8052 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8053 8054 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8055 packageName, extras, null, null, new int[] {userId}); 8056 try { 8057 IActivityManager am = ActivityManagerNative.getDefault(); 8058 final boolean isSystem = 8059 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8060 if (isSystem && am.isUserRunning(userId, false)) { 8061 // The just-installed/enabled app is bundled on the system, so presumed 8062 // to be able to run automatically without needing an explicit launch. 8063 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8064 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8065 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8066 .setPackage(packageName); 8067 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8068 android.app.AppOpsManager.OP_NONE, false, false, userId); 8069 } 8070 } catch (RemoteException e) { 8071 // shouldn't happen 8072 Slog.w(TAG, "Unable to bootstrap installed package", e); 8073 } 8074 } 8075 8076 @Override 8077 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8078 int userId) { 8079 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8080 PackageSetting pkgSetting; 8081 final int uid = Binder.getCallingUid(); 8082 enforceCrossUserPermission(uid, userId, true, true, 8083 "setApplicationHiddenSetting for user " + userId); 8084 8085 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8086 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8087 return false; 8088 } 8089 8090 long callingId = Binder.clearCallingIdentity(); 8091 try { 8092 boolean sendAdded = false; 8093 boolean sendRemoved = false; 8094 // writer 8095 synchronized (mPackages) { 8096 pkgSetting = mSettings.mPackages.get(packageName); 8097 if (pkgSetting == null) { 8098 return false; 8099 } 8100 if (pkgSetting.getHidden(userId) != hidden) { 8101 pkgSetting.setHidden(hidden, userId); 8102 mSettings.writePackageRestrictionsLPr(userId); 8103 if (hidden) { 8104 sendRemoved = true; 8105 } else { 8106 sendAdded = true; 8107 } 8108 } 8109 } 8110 if (sendAdded) { 8111 sendPackageAddedForUser(packageName, pkgSetting, userId); 8112 return true; 8113 } 8114 if (sendRemoved) { 8115 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8116 "hiding pkg"); 8117 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8118 } 8119 } finally { 8120 Binder.restoreCallingIdentity(callingId); 8121 } 8122 return false; 8123 } 8124 8125 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8126 int userId) { 8127 final PackageRemovedInfo info = new PackageRemovedInfo(); 8128 info.removedPackage = packageName; 8129 info.removedUsers = new int[] {userId}; 8130 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8131 info.sendBroadcast(false, false, false); 8132 } 8133 8134 /** 8135 * Returns true if application is not found or there was an error. Otherwise it returns 8136 * the hidden state of the package for the given user. 8137 */ 8138 @Override 8139 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8141 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8142 false, "getApplicationHidden for user " + userId); 8143 PackageSetting pkgSetting; 8144 long callingId = Binder.clearCallingIdentity(); 8145 try { 8146 // writer 8147 synchronized (mPackages) { 8148 pkgSetting = mSettings.mPackages.get(packageName); 8149 if (pkgSetting == null) { 8150 return true; 8151 } 8152 return pkgSetting.getHidden(userId); 8153 } 8154 } finally { 8155 Binder.restoreCallingIdentity(callingId); 8156 } 8157 } 8158 8159 /** 8160 * @hide 8161 */ 8162 @Override 8163 public int installExistingPackageAsUser(String packageName, int userId) { 8164 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8165 null); 8166 PackageSetting pkgSetting; 8167 final int uid = Binder.getCallingUid(); 8168 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8169 + userId); 8170 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8171 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8172 } 8173 8174 long callingId = Binder.clearCallingIdentity(); 8175 try { 8176 boolean sendAdded = false; 8177 Bundle extras = new Bundle(1); 8178 8179 // writer 8180 synchronized (mPackages) { 8181 pkgSetting = mSettings.mPackages.get(packageName); 8182 if (pkgSetting == null) { 8183 return PackageManager.INSTALL_FAILED_INVALID_URI; 8184 } 8185 if (!pkgSetting.getInstalled(userId)) { 8186 pkgSetting.setInstalled(true, userId); 8187 pkgSetting.setHidden(false, userId); 8188 mSettings.writePackageRestrictionsLPr(userId); 8189 sendAdded = true; 8190 } 8191 } 8192 8193 if (sendAdded) { 8194 sendPackageAddedForUser(packageName, pkgSetting, userId); 8195 } 8196 } finally { 8197 Binder.restoreCallingIdentity(callingId); 8198 } 8199 8200 return PackageManager.INSTALL_SUCCEEDED; 8201 } 8202 8203 boolean isUserRestricted(int userId, String restrictionKey) { 8204 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8205 if (restrictions.getBoolean(restrictionKey, false)) { 8206 Log.w(TAG, "User is restricted: " + restrictionKey); 8207 return true; 8208 } 8209 return false; 8210 } 8211 8212 @Override 8213 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8214 mContext.enforceCallingOrSelfPermission( 8215 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8216 "Only package verification agents can verify applications"); 8217 8218 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8219 final PackageVerificationResponse response = new PackageVerificationResponse( 8220 verificationCode, Binder.getCallingUid()); 8221 msg.arg1 = id; 8222 msg.obj = response; 8223 mHandler.sendMessage(msg); 8224 } 8225 8226 @Override 8227 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8228 long millisecondsToDelay) { 8229 mContext.enforceCallingOrSelfPermission( 8230 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8231 "Only package verification agents can extend verification timeouts"); 8232 8233 final PackageVerificationState state = mPendingVerification.get(id); 8234 final PackageVerificationResponse response = new PackageVerificationResponse( 8235 verificationCodeAtTimeout, Binder.getCallingUid()); 8236 8237 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8238 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8239 } 8240 if (millisecondsToDelay < 0) { 8241 millisecondsToDelay = 0; 8242 } 8243 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8244 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8245 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8246 } 8247 8248 if ((state != null) && !state.timeoutExtended()) { 8249 state.extendTimeout(); 8250 8251 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8252 msg.arg1 = id; 8253 msg.obj = response; 8254 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8255 } 8256 } 8257 8258 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8259 int verificationCode, UserHandle user) { 8260 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8261 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8262 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8263 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8264 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8265 8266 mContext.sendBroadcastAsUser(intent, user, 8267 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8268 } 8269 8270 private ComponentName matchComponentForVerifier(String packageName, 8271 List<ResolveInfo> receivers) { 8272 ActivityInfo targetReceiver = null; 8273 8274 final int NR = receivers.size(); 8275 for (int i = 0; i < NR; i++) { 8276 final ResolveInfo info = receivers.get(i); 8277 if (info.activityInfo == null) { 8278 continue; 8279 } 8280 8281 if (packageName.equals(info.activityInfo.packageName)) { 8282 targetReceiver = info.activityInfo; 8283 break; 8284 } 8285 } 8286 8287 if (targetReceiver == null) { 8288 return null; 8289 } 8290 8291 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8292 } 8293 8294 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8295 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8296 if (pkgInfo.verifiers.length == 0) { 8297 return null; 8298 } 8299 8300 final int N = pkgInfo.verifiers.length; 8301 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8302 for (int i = 0; i < N; i++) { 8303 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8304 8305 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8306 receivers); 8307 if (comp == null) { 8308 continue; 8309 } 8310 8311 final int verifierUid = getUidForVerifier(verifierInfo); 8312 if (verifierUid == -1) { 8313 continue; 8314 } 8315 8316 if (DEBUG_VERIFY) { 8317 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8318 + " with the correct signature"); 8319 } 8320 sufficientVerifiers.add(comp); 8321 verificationState.addSufficientVerifier(verifierUid); 8322 } 8323 8324 return sufficientVerifiers; 8325 } 8326 8327 private int getUidForVerifier(VerifierInfo verifierInfo) { 8328 synchronized (mPackages) { 8329 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8330 if (pkg == null) { 8331 return -1; 8332 } else if (pkg.mSignatures.length != 1) { 8333 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8334 + " has more than one signature; ignoring"); 8335 return -1; 8336 } 8337 8338 /* 8339 * If the public key of the package's signature does not match 8340 * our expected public key, then this is a different package and 8341 * we should skip. 8342 */ 8343 8344 final byte[] expectedPublicKey; 8345 try { 8346 final Signature verifierSig = pkg.mSignatures[0]; 8347 final PublicKey publicKey = verifierSig.getPublicKey(); 8348 expectedPublicKey = publicKey.getEncoded(); 8349 } catch (CertificateException e) { 8350 return -1; 8351 } 8352 8353 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8354 8355 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8356 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8357 + " does not have the expected public key; ignoring"); 8358 return -1; 8359 } 8360 8361 return pkg.applicationInfo.uid; 8362 } 8363 } 8364 8365 @Override 8366 public void finishPackageInstall(int token) { 8367 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8368 8369 if (DEBUG_INSTALL) { 8370 Slog.v(TAG, "BM finishing package install for " + token); 8371 } 8372 8373 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8374 mHandler.sendMessage(msg); 8375 } 8376 8377 /** 8378 * Get the verification agent timeout. 8379 * 8380 * @return verification timeout in milliseconds 8381 */ 8382 private long getVerificationTimeout() { 8383 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8384 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8385 DEFAULT_VERIFICATION_TIMEOUT); 8386 } 8387 8388 /** 8389 * Get the default verification agent response code. 8390 * 8391 * @return default verification response code 8392 */ 8393 private int getDefaultVerificationResponse() { 8394 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8395 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8396 DEFAULT_VERIFICATION_RESPONSE); 8397 } 8398 8399 /** 8400 * Check whether or not package verification has been enabled. 8401 * 8402 * @return true if verification should be performed 8403 */ 8404 private boolean isVerificationEnabled(int userId, int installFlags) { 8405 if (!DEFAULT_VERIFY_ENABLE) { 8406 return false; 8407 } 8408 8409 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8410 8411 // Check if installing from ADB 8412 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8413 // Do not run verification in a test harness environment 8414 if (ActivityManager.isRunningInTestHarness()) { 8415 return false; 8416 } 8417 if (ensureVerifyAppsEnabled) { 8418 return true; 8419 } 8420 // Check if the developer does not want package verification for ADB installs 8421 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8422 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8423 return false; 8424 } 8425 } 8426 8427 if (ensureVerifyAppsEnabled) { 8428 return true; 8429 } 8430 8431 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8432 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8433 } 8434 8435 /** 8436 * Get the "allow unknown sources" setting. 8437 * 8438 * @return the current "allow unknown sources" setting 8439 */ 8440 private int getUnknownSourcesSettings() { 8441 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8442 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8443 -1); 8444 } 8445 8446 @Override 8447 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8448 final int uid = Binder.getCallingUid(); 8449 // writer 8450 synchronized (mPackages) { 8451 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8452 if (targetPackageSetting == null) { 8453 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8454 } 8455 8456 PackageSetting installerPackageSetting; 8457 if (installerPackageName != null) { 8458 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8459 if (installerPackageSetting == null) { 8460 throw new IllegalArgumentException("Unknown installer package: " 8461 + installerPackageName); 8462 } 8463 } else { 8464 installerPackageSetting = null; 8465 } 8466 8467 Signature[] callerSignature; 8468 Object obj = mSettings.getUserIdLPr(uid); 8469 if (obj != null) { 8470 if (obj instanceof SharedUserSetting) { 8471 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8472 } else if (obj instanceof PackageSetting) { 8473 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8474 } else { 8475 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8476 } 8477 } else { 8478 throw new SecurityException("Unknown calling uid " + uid); 8479 } 8480 8481 // Verify: can't set installerPackageName to a package that is 8482 // not signed with the same cert as the caller. 8483 if (installerPackageSetting != null) { 8484 if (compareSignatures(callerSignature, 8485 installerPackageSetting.signatures.mSignatures) 8486 != PackageManager.SIGNATURE_MATCH) { 8487 throw new SecurityException( 8488 "Caller does not have same cert as new installer package " 8489 + installerPackageName); 8490 } 8491 } 8492 8493 // Verify: if target already has an installer package, it must 8494 // be signed with the same cert as the caller. 8495 if (targetPackageSetting.installerPackageName != null) { 8496 PackageSetting setting = mSettings.mPackages.get( 8497 targetPackageSetting.installerPackageName); 8498 // If the currently set package isn't valid, then it's always 8499 // okay to change it. 8500 if (setting != null) { 8501 if (compareSignatures(callerSignature, 8502 setting.signatures.mSignatures) 8503 != PackageManager.SIGNATURE_MATCH) { 8504 throw new SecurityException( 8505 "Caller does not have same cert as old installer package " 8506 + targetPackageSetting.installerPackageName); 8507 } 8508 } 8509 } 8510 8511 // Okay! 8512 targetPackageSetting.installerPackageName = installerPackageName; 8513 scheduleWriteSettingsLocked(); 8514 } 8515 } 8516 8517 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8518 // Queue up an async operation since the package installation may take a little while. 8519 mHandler.post(new Runnable() { 8520 public void run() { 8521 mHandler.removeCallbacks(this); 8522 // Result object to be returned 8523 PackageInstalledInfo res = new PackageInstalledInfo(); 8524 res.returnCode = currentStatus; 8525 res.uid = -1; 8526 res.pkg = null; 8527 res.removedInfo = new PackageRemovedInfo(); 8528 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8529 args.doPreInstall(res.returnCode); 8530 synchronized (mInstallLock) { 8531 installPackageLI(args, res); 8532 } 8533 args.doPostInstall(res.returnCode, res.uid); 8534 } 8535 8536 // A restore should be performed at this point if (a) the install 8537 // succeeded, (b) the operation is not an update, and (c) the new 8538 // package has not opted out of backup participation. 8539 final boolean update = res.removedInfo.removedPackage != null; 8540 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8541 boolean doRestore = !update 8542 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8543 8544 // Set up the post-install work request bookkeeping. This will be used 8545 // and cleaned up by the post-install event handling regardless of whether 8546 // there's a restore pass performed. Token values are >= 1. 8547 int token; 8548 if (mNextInstallToken < 0) mNextInstallToken = 1; 8549 token = mNextInstallToken++; 8550 8551 PostInstallData data = new PostInstallData(args, res); 8552 mRunningInstalls.put(token, data); 8553 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8554 8555 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8556 // Pass responsibility to the Backup Manager. It will perform a 8557 // restore if appropriate, then pass responsibility back to the 8558 // Package Manager to run the post-install observer callbacks 8559 // and broadcasts. 8560 IBackupManager bm = IBackupManager.Stub.asInterface( 8561 ServiceManager.getService(Context.BACKUP_SERVICE)); 8562 if (bm != null) { 8563 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8564 + " to BM for possible restore"); 8565 try { 8566 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8567 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8568 } else { 8569 doRestore = false; 8570 } 8571 } catch (RemoteException e) { 8572 // can't happen; the backup manager is local 8573 } catch (Exception e) { 8574 Slog.e(TAG, "Exception trying to enqueue restore", e); 8575 doRestore = false; 8576 } 8577 } else { 8578 Slog.e(TAG, "Backup Manager not found!"); 8579 doRestore = false; 8580 } 8581 } 8582 8583 if (!doRestore) { 8584 // No restore possible, or the Backup Manager was mysteriously not 8585 // available -- just fire the post-install work request directly. 8586 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8587 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8588 mHandler.sendMessage(msg); 8589 } 8590 } 8591 }); 8592 } 8593 8594 private abstract class HandlerParams { 8595 private static final int MAX_RETRIES = 4; 8596 8597 /** 8598 * Number of times startCopy() has been attempted and had a non-fatal 8599 * error. 8600 */ 8601 private int mRetries = 0; 8602 8603 /** User handle for the user requesting the information or installation. */ 8604 private final UserHandle mUser; 8605 8606 HandlerParams(UserHandle user) { 8607 mUser = user; 8608 } 8609 8610 UserHandle getUser() { 8611 return mUser; 8612 } 8613 8614 final boolean startCopy() { 8615 boolean res; 8616 try { 8617 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8618 8619 if (++mRetries > MAX_RETRIES) { 8620 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8621 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8622 handleServiceError(); 8623 return false; 8624 } else { 8625 handleStartCopy(); 8626 res = true; 8627 } 8628 } catch (RemoteException e) { 8629 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8630 mHandler.sendEmptyMessage(MCS_RECONNECT); 8631 res = false; 8632 } 8633 handleReturnCode(); 8634 return res; 8635 } 8636 8637 final void serviceError() { 8638 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8639 handleServiceError(); 8640 handleReturnCode(); 8641 } 8642 8643 abstract void handleStartCopy() throws RemoteException; 8644 abstract void handleServiceError(); 8645 abstract void handleReturnCode(); 8646 } 8647 8648 class MeasureParams extends HandlerParams { 8649 private final PackageStats mStats; 8650 private boolean mSuccess; 8651 8652 private final IPackageStatsObserver mObserver; 8653 8654 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8655 super(new UserHandle(stats.userHandle)); 8656 mObserver = observer; 8657 mStats = stats; 8658 } 8659 8660 @Override 8661 public String toString() { 8662 return "MeasureParams{" 8663 + Integer.toHexString(System.identityHashCode(this)) 8664 + " " + mStats.packageName + "}"; 8665 } 8666 8667 @Override 8668 void handleStartCopy() throws RemoteException { 8669 synchronized (mInstallLock) { 8670 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8671 } 8672 8673 if (mSuccess) { 8674 final boolean mounted; 8675 if (Environment.isExternalStorageEmulated()) { 8676 mounted = true; 8677 } else { 8678 final String status = Environment.getExternalStorageState(); 8679 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8680 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8681 } 8682 8683 if (mounted) { 8684 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8685 8686 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8687 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8688 8689 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8690 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8691 8692 // Always subtract cache size, since it's a subdirectory 8693 mStats.externalDataSize -= mStats.externalCacheSize; 8694 8695 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8696 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8697 8698 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8699 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8700 } 8701 } 8702 } 8703 8704 @Override 8705 void handleReturnCode() { 8706 if (mObserver != null) { 8707 try { 8708 mObserver.onGetStatsCompleted(mStats, mSuccess); 8709 } catch (RemoteException e) { 8710 Slog.i(TAG, "Observer no longer exists."); 8711 } 8712 } 8713 } 8714 8715 @Override 8716 void handleServiceError() { 8717 Slog.e(TAG, "Could not measure application " + mStats.packageName 8718 + " external storage"); 8719 } 8720 } 8721 8722 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8723 throws RemoteException { 8724 long result = 0; 8725 for (File path : paths) { 8726 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8727 } 8728 return result; 8729 } 8730 8731 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8732 for (File path : paths) { 8733 try { 8734 mcs.clearDirectory(path.getAbsolutePath()); 8735 } catch (RemoteException e) { 8736 } 8737 } 8738 } 8739 8740 static class OriginInfo { 8741 /** 8742 * Location where install is coming from, before it has been 8743 * copied/renamed into place. This could be a single monolithic APK 8744 * file, or a cluster directory. This location may be untrusted. 8745 */ 8746 final File file; 8747 final String cid; 8748 8749 /** 8750 * Flag indicating that {@link #file} or {@link #cid} has already been 8751 * staged, meaning downstream users don't need to defensively copy the 8752 * contents. 8753 */ 8754 final boolean staged; 8755 8756 /** 8757 * Flag indicating that {@link #file} or {@link #cid} is an already 8758 * installed app that is being moved. 8759 */ 8760 final boolean existing; 8761 8762 final String resolvedPath; 8763 final File resolvedFile; 8764 8765 static OriginInfo fromNothing() { 8766 return new OriginInfo(null, null, false, false); 8767 } 8768 8769 static OriginInfo fromUntrustedFile(File file) { 8770 return new OriginInfo(file, null, false, false); 8771 } 8772 8773 static OriginInfo fromExistingFile(File file) { 8774 return new OriginInfo(file, null, false, true); 8775 } 8776 8777 static OriginInfo fromStagedFile(File file) { 8778 return new OriginInfo(file, null, true, false); 8779 } 8780 8781 static OriginInfo fromStagedContainer(String cid) { 8782 return new OriginInfo(null, cid, true, false); 8783 } 8784 8785 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8786 this.file = file; 8787 this.cid = cid; 8788 this.staged = staged; 8789 this.existing = existing; 8790 8791 if (cid != null) { 8792 resolvedPath = PackageHelper.getSdDir(cid); 8793 resolvedFile = new File(resolvedPath); 8794 } else if (file != null) { 8795 resolvedPath = file.getAbsolutePath(); 8796 resolvedFile = file; 8797 } else { 8798 resolvedPath = null; 8799 resolvedFile = null; 8800 } 8801 } 8802 } 8803 8804 class InstallParams extends HandlerParams { 8805 final OriginInfo origin; 8806 final IPackageInstallObserver2 observer; 8807 int installFlags; 8808 final String installerPackageName; 8809 final VerificationParams verificationParams; 8810 private InstallArgs mArgs; 8811 private int mRet; 8812 final String packageAbiOverride; 8813 8814 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8815 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8816 String packageAbiOverride) { 8817 super(user); 8818 this.origin = origin; 8819 this.observer = observer; 8820 this.installFlags = installFlags; 8821 this.installerPackageName = installerPackageName; 8822 this.verificationParams = verificationParams; 8823 this.packageAbiOverride = packageAbiOverride; 8824 } 8825 8826 @Override 8827 public String toString() { 8828 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8829 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8830 } 8831 8832 public ManifestDigest getManifestDigest() { 8833 if (verificationParams == null) { 8834 return null; 8835 } 8836 return verificationParams.getManifestDigest(); 8837 } 8838 8839 private int installLocationPolicy(PackageInfoLite pkgLite) { 8840 String packageName = pkgLite.packageName; 8841 int installLocation = pkgLite.installLocation; 8842 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8843 // reader 8844 synchronized (mPackages) { 8845 PackageParser.Package pkg = mPackages.get(packageName); 8846 if (pkg != null) { 8847 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8848 // Check for downgrading. 8849 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8850 try { 8851 checkDowngrade(pkg, pkgLite); 8852 } catch (PackageManagerException e) { 8853 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8854 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8855 } 8856 } 8857 // Check for updated system application. 8858 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8859 if (onSd) { 8860 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8861 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8862 } 8863 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8864 } else { 8865 if (onSd) { 8866 // Install flag overrides everything. 8867 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8868 } 8869 // If current upgrade specifies particular preference 8870 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8871 // Application explicitly specified internal. 8872 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8873 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8874 // App explictly prefers external. Let policy decide 8875 } else { 8876 // Prefer previous location 8877 if (isExternal(pkg)) { 8878 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8879 } 8880 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8881 } 8882 } 8883 } else { 8884 // Invalid install. Return error code 8885 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8886 } 8887 } 8888 } 8889 // All the special cases have been taken care of. 8890 // Return result based on recommended install location. 8891 if (onSd) { 8892 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8893 } 8894 return pkgLite.recommendedInstallLocation; 8895 } 8896 8897 /* 8898 * Invoke remote method to get package information and install 8899 * location values. Override install location based on default 8900 * policy if needed and then create install arguments based 8901 * on the install location. 8902 */ 8903 public void handleStartCopy() throws RemoteException { 8904 int ret = PackageManager.INSTALL_SUCCEEDED; 8905 8906 // If we're already staged, we've firmly committed to an install location 8907 if (origin.staged) { 8908 if (origin.file != null) { 8909 installFlags |= PackageManager.INSTALL_INTERNAL; 8910 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8911 } else if (origin.cid != null) { 8912 installFlags |= PackageManager.INSTALL_EXTERNAL; 8913 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8914 } else { 8915 throw new IllegalStateException("Invalid stage location"); 8916 } 8917 } 8918 8919 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8920 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8921 8922 PackageInfoLite pkgLite = null; 8923 8924 if (onInt && onSd) { 8925 // Check if both bits are set. 8926 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8927 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8928 } else { 8929 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8930 packageAbiOverride); 8931 8932 /* 8933 * If we have too little free space, try to free cache 8934 * before giving up. 8935 */ 8936 if (!origin.staged && pkgLite.recommendedInstallLocation 8937 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8938 // TODO: focus freeing disk space on the target device 8939 final StorageManager storage = StorageManager.from(mContext); 8940 final long lowThreshold = storage.getStorageLowBytes( 8941 Environment.getDataDirectory()); 8942 8943 final long sizeBytes = mContainerService.calculateInstalledSize( 8944 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8945 8946 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8947 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8948 installFlags, packageAbiOverride); 8949 } 8950 8951 /* 8952 * The cache free must have deleted the file we 8953 * downloaded to install. 8954 * 8955 * TODO: fix the "freeCache" call to not delete 8956 * the file we care about. 8957 */ 8958 if (pkgLite.recommendedInstallLocation 8959 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8960 pkgLite.recommendedInstallLocation 8961 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8962 } 8963 } 8964 } 8965 8966 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8967 int loc = pkgLite.recommendedInstallLocation; 8968 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8969 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8970 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8971 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8972 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8973 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8974 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8975 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8976 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8977 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8978 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8979 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8980 } else { 8981 // Override with defaults if needed. 8982 loc = installLocationPolicy(pkgLite); 8983 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8984 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8985 } else if (!onSd && !onInt) { 8986 // Override install location with flags 8987 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8988 // Set the flag to install on external media. 8989 installFlags |= PackageManager.INSTALL_EXTERNAL; 8990 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8991 } else { 8992 // Make sure the flag for installing on external 8993 // media is unset 8994 installFlags |= PackageManager.INSTALL_INTERNAL; 8995 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8996 } 8997 } 8998 } 8999 } 9000 9001 final InstallArgs args = createInstallArgs(this); 9002 mArgs = args; 9003 9004 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9005 /* 9006 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9007 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9008 */ 9009 int userIdentifier = getUser().getIdentifier(); 9010 if (userIdentifier == UserHandle.USER_ALL 9011 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9012 userIdentifier = UserHandle.USER_OWNER; 9013 } 9014 9015 /* 9016 * Determine if we have any installed package verifiers. If we 9017 * do, then we'll defer to them to verify the packages. 9018 */ 9019 final int requiredUid = mRequiredVerifierPackage == null ? -1 9020 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9021 if (!origin.existing && requiredUid != -1 9022 && isVerificationEnabled(userIdentifier, installFlags)) { 9023 final Intent verification = new Intent( 9024 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9025 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9026 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9027 PACKAGE_MIME_TYPE); 9028 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9029 9030 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9031 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9032 0 /* TODO: Which userId? */); 9033 9034 if (DEBUG_VERIFY) { 9035 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9036 + verification.toString() + " with " + pkgLite.verifiers.length 9037 + " optional verifiers"); 9038 } 9039 9040 final int verificationId = mPendingVerificationToken++; 9041 9042 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9043 9044 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9045 installerPackageName); 9046 9047 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9048 installFlags); 9049 9050 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9051 pkgLite.packageName); 9052 9053 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9054 pkgLite.versionCode); 9055 9056 if (verificationParams != null) { 9057 if (verificationParams.getVerificationURI() != null) { 9058 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9059 verificationParams.getVerificationURI()); 9060 } 9061 if (verificationParams.getOriginatingURI() != null) { 9062 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9063 verificationParams.getOriginatingURI()); 9064 } 9065 if (verificationParams.getReferrer() != null) { 9066 verification.putExtra(Intent.EXTRA_REFERRER, 9067 verificationParams.getReferrer()); 9068 } 9069 if (verificationParams.getOriginatingUid() >= 0) { 9070 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9071 verificationParams.getOriginatingUid()); 9072 } 9073 if (verificationParams.getInstallerUid() >= 0) { 9074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9075 verificationParams.getInstallerUid()); 9076 } 9077 } 9078 9079 final PackageVerificationState verificationState = new PackageVerificationState( 9080 requiredUid, args); 9081 9082 mPendingVerification.append(verificationId, verificationState); 9083 9084 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9085 receivers, verificationState); 9086 9087 /* 9088 * If any sufficient verifiers were listed in the package 9089 * manifest, attempt to ask them. 9090 */ 9091 if (sufficientVerifiers != null) { 9092 final int N = sufficientVerifiers.size(); 9093 if (N == 0) { 9094 Slog.i(TAG, "Additional verifiers required, but none installed."); 9095 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9096 } else { 9097 for (int i = 0; i < N; i++) { 9098 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9099 9100 final Intent sufficientIntent = new Intent(verification); 9101 sufficientIntent.setComponent(verifierComponent); 9102 9103 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9104 } 9105 } 9106 } 9107 9108 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9109 mRequiredVerifierPackage, receivers); 9110 if (ret == PackageManager.INSTALL_SUCCEEDED 9111 && mRequiredVerifierPackage != null) { 9112 /* 9113 * Send the intent to the required verification agent, 9114 * but only start the verification timeout after the 9115 * target BroadcastReceivers have run. 9116 */ 9117 verification.setComponent(requiredVerifierComponent); 9118 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9119 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9120 new BroadcastReceiver() { 9121 @Override 9122 public void onReceive(Context context, Intent intent) { 9123 final Message msg = mHandler 9124 .obtainMessage(CHECK_PENDING_VERIFICATION); 9125 msg.arg1 = verificationId; 9126 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9127 } 9128 }, null, 0, null, null); 9129 9130 /* 9131 * We don't want the copy to proceed until verification 9132 * succeeds, so null out this field. 9133 */ 9134 mArgs = null; 9135 } 9136 } else { 9137 /* 9138 * No package verification is enabled, so immediately start 9139 * the remote call to initiate copy using temporary file. 9140 */ 9141 ret = args.copyApk(mContainerService, true); 9142 } 9143 } 9144 9145 mRet = ret; 9146 } 9147 9148 @Override 9149 void handleReturnCode() { 9150 // If mArgs is null, then MCS couldn't be reached. When it 9151 // reconnects, it will try again to install. At that point, this 9152 // will succeed. 9153 if (mArgs != null) { 9154 processPendingInstall(mArgs, mRet); 9155 } 9156 } 9157 9158 @Override 9159 void handleServiceError() { 9160 mArgs = createInstallArgs(this); 9161 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9162 } 9163 9164 public boolean isForwardLocked() { 9165 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9166 } 9167 } 9168 9169 /** 9170 * Used during creation of InstallArgs 9171 * 9172 * @param installFlags package installation flags 9173 * @return true if should be installed on external storage 9174 */ 9175 private static boolean installOnSd(int installFlags) { 9176 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9177 return false; 9178 } 9179 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9180 return true; 9181 } 9182 return false; 9183 } 9184 9185 /** 9186 * Used during creation of InstallArgs 9187 * 9188 * @param installFlags package installation flags 9189 * @return true if should be installed as forward locked 9190 */ 9191 private static boolean installForwardLocked(int installFlags) { 9192 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9193 } 9194 9195 private InstallArgs createInstallArgs(InstallParams params) { 9196 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9197 return new AsecInstallArgs(params); 9198 } else { 9199 return new FileInstallArgs(params); 9200 } 9201 } 9202 9203 /** 9204 * Create args that describe an existing installed package. Typically used 9205 * when cleaning up old installs, or used as a move source. 9206 */ 9207 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9208 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9209 final boolean isInAsec; 9210 if (installOnSd(installFlags)) { 9211 /* Apps on SD card are always in ASEC containers. */ 9212 isInAsec = true; 9213 } else if (installForwardLocked(installFlags) 9214 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9215 /* 9216 * Forward-locked apps are only in ASEC containers if they're the 9217 * new style 9218 */ 9219 isInAsec = true; 9220 } else { 9221 isInAsec = false; 9222 } 9223 9224 if (isInAsec) { 9225 return new AsecInstallArgs(codePath, instructionSets, 9226 installOnSd(installFlags), installForwardLocked(installFlags)); 9227 } else { 9228 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9229 instructionSets); 9230 } 9231 } 9232 9233 static abstract class InstallArgs { 9234 /** @see InstallParams#origin */ 9235 final OriginInfo origin; 9236 9237 final IPackageInstallObserver2 observer; 9238 // Always refers to PackageManager flags only 9239 final int installFlags; 9240 final String installerPackageName; 9241 final ManifestDigest manifestDigest; 9242 final UserHandle user; 9243 final String abiOverride; 9244 9245 // The list of instruction sets supported by this app. This is currently 9246 // only used during the rmdex() phase to clean up resources. We can get rid of this 9247 // if we move dex files under the common app path. 9248 /* nullable */ String[] instructionSets; 9249 9250 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9251 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9252 String[] instructionSets, String abiOverride) { 9253 this.origin = origin; 9254 this.installFlags = installFlags; 9255 this.observer = observer; 9256 this.installerPackageName = installerPackageName; 9257 this.manifestDigest = manifestDigest; 9258 this.user = user; 9259 this.instructionSets = instructionSets; 9260 this.abiOverride = abiOverride; 9261 } 9262 9263 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9264 abstract int doPreInstall(int status); 9265 9266 /** 9267 * Rename package into final resting place. All paths on the given 9268 * scanned package should be updated to reflect the rename. 9269 */ 9270 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9271 abstract int doPostInstall(int status, int uid); 9272 9273 /** @see PackageSettingBase#codePathString */ 9274 abstract String getCodePath(); 9275 /** @see PackageSettingBase#resourcePathString */ 9276 abstract String getResourcePath(); 9277 abstract String getLegacyNativeLibraryPath(); 9278 9279 // Need installer lock especially for dex file removal. 9280 abstract void cleanUpResourcesLI(); 9281 abstract boolean doPostDeleteLI(boolean delete); 9282 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9283 9284 /** 9285 * Called before the source arguments are copied. This is used mostly 9286 * for MoveParams when it needs to read the source file to put it in the 9287 * destination. 9288 */ 9289 int doPreCopy() { 9290 return PackageManager.INSTALL_SUCCEEDED; 9291 } 9292 9293 /** 9294 * Called after the source arguments are copied. This is used mostly for 9295 * MoveParams when it needs to read the source file to put it in the 9296 * destination. 9297 * 9298 * @return 9299 */ 9300 int doPostCopy(int uid) { 9301 return PackageManager.INSTALL_SUCCEEDED; 9302 } 9303 9304 protected boolean isFwdLocked() { 9305 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9306 } 9307 9308 protected boolean isExternal() { 9309 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9310 } 9311 9312 UserHandle getUser() { 9313 return user; 9314 } 9315 } 9316 9317 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9318 if (!allCodePaths.isEmpty()) { 9319 if (instructionSets == null) { 9320 throw new IllegalStateException("instructionSet == null"); 9321 } 9322 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9323 for (String codePath : allCodePaths) { 9324 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9325 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9326 if (retCode < 0) { 9327 Slog.w(TAG, "Couldn't remove dex file for package: " 9328 + " at location " + codePath + ", retcode=" + retCode); 9329 // we don't consider this to be a failure of the core package deletion 9330 } 9331 } 9332 } 9333 } 9334 } 9335 9336 /** 9337 * Logic to handle installation of non-ASEC applications, including copying 9338 * and renaming logic. 9339 */ 9340 class FileInstallArgs extends InstallArgs { 9341 private File codeFile; 9342 private File resourceFile; 9343 private File legacyNativeLibraryPath; 9344 9345 // Example topology: 9346 // /data/app/com.example/base.apk 9347 // /data/app/com.example/split_foo.apk 9348 // /data/app/com.example/lib/arm/libfoo.so 9349 // /data/app/com.example/lib/arm64/libfoo.so 9350 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9351 9352 /** New install */ 9353 FileInstallArgs(InstallParams params) { 9354 super(params.origin, params.observer, params.installFlags, 9355 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9356 null /* instruction sets */, params.packageAbiOverride); 9357 if (isFwdLocked()) { 9358 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9359 } 9360 } 9361 9362 /** Existing install */ 9363 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9364 String[] instructionSets) { 9365 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9366 this.codeFile = (codePath != null) ? new File(codePath) : null; 9367 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9368 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9369 new File(legacyNativeLibraryPath) : null; 9370 } 9371 9372 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9373 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9374 isFwdLocked(), abiOverride); 9375 9376 final StorageManager storage = StorageManager.from(mContext); 9377 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9378 } 9379 9380 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9381 if (origin.staged) { 9382 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9383 codeFile = origin.file; 9384 resourceFile = origin.file; 9385 return PackageManager.INSTALL_SUCCEEDED; 9386 } 9387 9388 try { 9389 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9390 codeFile = tempDir; 9391 resourceFile = tempDir; 9392 } catch (IOException e) { 9393 Slog.w(TAG, "Failed to create copy file: " + e); 9394 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9395 } 9396 9397 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9398 @Override 9399 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9400 if (!FileUtils.isValidExtFilename(name)) { 9401 throw new IllegalArgumentException("Invalid filename: " + name); 9402 } 9403 try { 9404 final File file = new File(codeFile, name); 9405 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9406 O_RDWR | O_CREAT, 0644); 9407 Os.chmod(file.getAbsolutePath(), 0644); 9408 return new ParcelFileDescriptor(fd); 9409 } catch (ErrnoException e) { 9410 throw new RemoteException("Failed to open: " + e.getMessage()); 9411 } 9412 } 9413 }; 9414 9415 int ret = PackageManager.INSTALL_SUCCEEDED; 9416 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9417 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9418 Slog.e(TAG, "Failed to copy package"); 9419 return ret; 9420 } 9421 9422 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9423 NativeLibraryHelper.Handle handle = null; 9424 try { 9425 handle = NativeLibraryHelper.Handle.create(codeFile); 9426 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9427 abiOverride); 9428 } catch (IOException e) { 9429 Slog.e(TAG, "Copying native libraries failed", e); 9430 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9431 } finally { 9432 IoUtils.closeQuietly(handle); 9433 } 9434 9435 return ret; 9436 } 9437 9438 int doPreInstall(int status) { 9439 if (status != PackageManager.INSTALL_SUCCEEDED) { 9440 cleanUp(); 9441 } 9442 return status; 9443 } 9444 9445 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9446 if (status != PackageManager.INSTALL_SUCCEEDED) { 9447 cleanUp(); 9448 return false; 9449 } else { 9450 final File beforeCodeFile = codeFile; 9451 final File afterCodeFile = getNextCodePath(pkg.packageName); 9452 9453 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9454 try { 9455 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9456 } catch (ErrnoException e) { 9457 Slog.d(TAG, "Failed to rename", e); 9458 return false; 9459 } 9460 9461 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9462 Slog.d(TAG, "Failed to restorecon"); 9463 return false; 9464 } 9465 9466 // Reflect the rename internally 9467 codeFile = afterCodeFile; 9468 resourceFile = afterCodeFile; 9469 9470 // Reflect the rename in scanned details 9471 pkg.codePath = afterCodeFile.getAbsolutePath(); 9472 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9473 pkg.baseCodePath); 9474 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9475 pkg.splitCodePaths); 9476 9477 // Reflect the rename in app info 9478 pkg.applicationInfo.setCodePath(pkg.codePath); 9479 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9480 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9481 pkg.applicationInfo.setResourcePath(pkg.codePath); 9482 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9483 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9484 9485 return true; 9486 } 9487 } 9488 9489 int doPostInstall(int status, int uid) { 9490 if (status != PackageManager.INSTALL_SUCCEEDED) { 9491 cleanUp(); 9492 } 9493 return status; 9494 } 9495 9496 @Override 9497 String getCodePath() { 9498 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9499 } 9500 9501 @Override 9502 String getResourcePath() { 9503 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9504 } 9505 9506 @Override 9507 String getLegacyNativeLibraryPath() { 9508 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9509 } 9510 9511 private boolean cleanUp() { 9512 if (codeFile == null || !codeFile.exists()) { 9513 return false; 9514 } 9515 9516 if (codeFile.isDirectory()) { 9517 FileUtils.deleteContents(codeFile); 9518 } 9519 codeFile.delete(); 9520 9521 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9522 resourceFile.delete(); 9523 } 9524 9525 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9526 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9527 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9528 } 9529 legacyNativeLibraryPath.delete(); 9530 } 9531 9532 return true; 9533 } 9534 9535 void cleanUpResourcesLI() { 9536 // Try enumerating all code paths before deleting 9537 List<String> allCodePaths = Collections.EMPTY_LIST; 9538 if (codeFile != null && codeFile.exists()) { 9539 try { 9540 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9541 allCodePaths = pkg.getAllCodePaths(); 9542 } catch (PackageParserException e) { 9543 // Ignored; we tried our best 9544 } 9545 } 9546 9547 cleanUp(); 9548 removeDexFiles(allCodePaths, instructionSets); 9549 } 9550 9551 boolean doPostDeleteLI(boolean delete) { 9552 // XXX err, shouldn't we respect the delete flag? 9553 cleanUpResourcesLI(); 9554 return true; 9555 } 9556 } 9557 9558 private boolean isAsecExternal(String cid) { 9559 final String asecPath = PackageHelper.getSdFilesystem(cid); 9560 return !asecPath.startsWith(mAsecInternalPath); 9561 } 9562 9563 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9564 PackageManagerException { 9565 if (copyRet < 0) { 9566 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9567 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9568 throw new PackageManagerException(copyRet, message); 9569 } 9570 } 9571 } 9572 9573 /** 9574 * Extract the MountService "container ID" from the full code path of an 9575 * .apk. 9576 */ 9577 static String cidFromCodePath(String fullCodePath) { 9578 int eidx = fullCodePath.lastIndexOf("/"); 9579 String subStr1 = fullCodePath.substring(0, eidx); 9580 int sidx = subStr1.lastIndexOf("/"); 9581 return subStr1.substring(sidx+1, eidx); 9582 } 9583 9584 /** 9585 * Logic to handle installation of ASEC applications, including copying and 9586 * renaming logic. 9587 */ 9588 class AsecInstallArgs extends InstallArgs { 9589 static final String RES_FILE_NAME = "pkg.apk"; 9590 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9591 9592 String cid; 9593 String packagePath; 9594 String resourcePath; 9595 String legacyNativeLibraryDir; 9596 9597 /** New install */ 9598 AsecInstallArgs(InstallParams params) { 9599 super(params.origin, params.observer, params.installFlags, 9600 params.installerPackageName, params.getManifestDigest(), 9601 params.getUser(), null /* instruction sets */, 9602 params.packageAbiOverride); 9603 } 9604 9605 /** Existing install */ 9606 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9607 boolean isExternal, boolean isForwardLocked) { 9608 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9609 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9610 instructionSets, null); 9611 // Hackily pretend we're still looking at a full code path 9612 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9613 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9614 } 9615 9616 // Extract cid from fullCodePath 9617 int eidx = fullCodePath.lastIndexOf("/"); 9618 String subStr1 = fullCodePath.substring(0, eidx); 9619 int sidx = subStr1.lastIndexOf("/"); 9620 cid = subStr1.substring(sidx+1, eidx); 9621 setMountPath(subStr1); 9622 } 9623 9624 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9625 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9626 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9627 instructionSets, null); 9628 this.cid = cid; 9629 setMountPath(PackageHelper.getSdDir(cid)); 9630 } 9631 9632 void createCopyFile() { 9633 cid = mInstallerService.allocateExternalStageCidLegacy(); 9634 } 9635 9636 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9637 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9638 abiOverride); 9639 9640 final File target; 9641 if (isExternal()) { 9642 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9643 } else { 9644 target = Environment.getDataDirectory(); 9645 } 9646 9647 final StorageManager storage = StorageManager.from(mContext); 9648 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9649 } 9650 9651 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9652 if (origin.staged) { 9653 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9654 cid = origin.cid; 9655 setMountPath(PackageHelper.getSdDir(cid)); 9656 return PackageManager.INSTALL_SUCCEEDED; 9657 } 9658 9659 if (temp) { 9660 createCopyFile(); 9661 } else { 9662 /* 9663 * Pre-emptively destroy the container since it's destroyed if 9664 * copying fails due to it existing anyway. 9665 */ 9666 PackageHelper.destroySdDir(cid); 9667 } 9668 9669 final String newMountPath = imcs.copyPackageToContainer( 9670 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9671 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9672 9673 if (newMountPath != null) { 9674 setMountPath(newMountPath); 9675 return PackageManager.INSTALL_SUCCEEDED; 9676 } else { 9677 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9678 } 9679 } 9680 9681 @Override 9682 String getCodePath() { 9683 return packagePath; 9684 } 9685 9686 @Override 9687 String getResourcePath() { 9688 return resourcePath; 9689 } 9690 9691 @Override 9692 String getLegacyNativeLibraryPath() { 9693 return legacyNativeLibraryDir; 9694 } 9695 9696 int doPreInstall(int status) { 9697 if (status != PackageManager.INSTALL_SUCCEEDED) { 9698 // Destroy container 9699 PackageHelper.destroySdDir(cid); 9700 } else { 9701 boolean mounted = PackageHelper.isContainerMounted(cid); 9702 if (!mounted) { 9703 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9704 Process.SYSTEM_UID); 9705 if (newMountPath != null) { 9706 setMountPath(newMountPath); 9707 } else { 9708 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9709 } 9710 } 9711 } 9712 return status; 9713 } 9714 9715 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9716 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9717 String newMountPath = null; 9718 if (PackageHelper.isContainerMounted(cid)) { 9719 // Unmount the container 9720 if (!PackageHelper.unMountSdDir(cid)) { 9721 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9722 return false; 9723 } 9724 } 9725 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9726 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9727 " which might be stale. Will try to clean up."); 9728 // Clean up the stale container and proceed to recreate. 9729 if (!PackageHelper.destroySdDir(newCacheId)) { 9730 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9731 return false; 9732 } 9733 // Successfully cleaned up stale container. Try to rename again. 9734 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9735 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9736 + " inspite of cleaning it up."); 9737 return false; 9738 } 9739 } 9740 if (!PackageHelper.isContainerMounted(newCacheId)) { 9741 Slog.w(TAG, "Mounting container " + newCacheId); 9742 newMountPath = PackageHelper.mountSdDir(newCacheId, 9743 getEncryptKey(), Process.SYSTEM_UID); 9744 } else { 9745 newMountPath = PackageHelper.getSdDir(newCacheId); 9746 } 9747 if (newMountPath == null) { 9748 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9749 return false; 9750 } 9751 Log.i(TAG, "Succesfully renamed " + cid + 9752 " to " + newCacheId + 9753 " at new path: " + newMountPath); 9754 cid = newCacheId; 9755 9756 final File beforeCodeFile = new File(packagePath); 9757 setMountPath(newMountPath); 9758 final File afterCodeFile = new File(packagePath); 9759 9760 // Reflect the rename in scanned details 9761 pkg.codePath = afterCodeFile.getAbsolutePath(); 9762 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9763 pkg.baseCodePath); 9764 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9765 pkg.splitCodePaths); 9766 9767 // Reflect the rename in app info 9768 pkg.applicationInfo.setCodePath(pkg.codePath); 9769 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9770 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9771 pkg.applicationInfo.setResourcePath(pkg.codePath); 9772 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9773 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9774 9775 return true; 9776 } 9777 9778 private void setMountPath(String mountPath) { 9779 final File mountFile = new File(mountPath); 9780 9781 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9782 if (monolithicFile.exists()) { 9783 packagePath = monolithicFile.getAbsolutePath(); 9784 if (isFwdLocked()) { 9785 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9786 } else { 9787 resourcePath = packagePath; 9788 } 9789 } else { 9790 packagePath = mountFile.getAbsolutePath(); 9791 resourcePath = packagePath; 9792 } 9793 9794 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9795 } 9796 9797 int doPostInstall(int status, int uid) { 9798 if (status != PackageManager.INSTALL_SUCCEEDED) { 9799 cleanUp(); 9800 } else { 9801 final int groupOwner; 9802 final String protectedFile; 9803 if (isFwdLocked()) { 9804 groupOwner = UserHandle.getSharedAppGid(uid); 9805 protectedFile = RES_FILE_NAME; 9806 } else { 9807 groupOwner = -1; 9808 protectedFile = null; 9809 } 9810 9811 if (uid < Process.FIRST_APPLICATION_UID 9812 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9813 Slog.e(TAG, "Failed to finalize " + cid); 9814 PackageHelper.destroySdDir(cid); 9815 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9816 } 9817 9818 boolean mounted = PackageHelper.isContainerMounted(cid); 9819 if (!mounted) { 9820 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9821 } 9822 } 9823 return status; 9824 } 9825 9826 private void cleanUp() { 9827 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9828 9829 // Destroy secure container 9830 PackageHelper.destroySdDir(cid); 9831 } 9832 9833 private List<String> getAllCodePaths() { 9834 final File codeFile = new File(getCodePath()); 9835 if (codeFile != null && codeFile.exists()) { 9836 try { 9837 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9838 return pkg.getAllCodePaths(); 9839 } catch (PackageParserException e) { 9840 // Ignored; we tried our best 9841 } 9842 } 9843 return Collections.EMPTY_LIST; 9844 } 9845 9846 void cleanUpResourcesLI() { 9847 // Enumerate all code paths before deleting 9848 cleanUpResourcesLI(getAllCodePaths()); 9849 } 9850 9851 private void cleanUpResourcesLI(List<String> allCodePaths) { 9852 cleanUp(); 9853 removeDexFiles(allCodePaths, instructionSets); 9854 } 9855 9856 9857 9858 String getPackageName() { 9859 return getAsecPackageName(cid); 9860 } 9861 9862 boolean doPostDeleteLI(boolean delete) { 9863 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9864 final List<String> allCodePaths = getAllCodePaths(); 9865 boolean mounted = PackageHelper.isContainerMounted(cid); 9866 if (mounted) { 9867 // Unmount first 9868 if (PackageHelper.unMountSdDir(cid)) { 9869 mounted = false; 9870 } 9871 } 9872 if (!mounted && delete) { 9873 cleanUpResourcesLI(allCodePaths); 9874 } 9875 return !mounted; 9876 } 9877 9878 @Override 9879 int doPreCopy() { 9880 if (isFwdLocked()) { 9881 if (!PackageHelper.fixSdPermissions(cid, 9882 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9883 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9884 } 9885 } 9886 9887 return PackageManager.INSTALL_SUCCEEDED; 9888 } 9889 9890 @Override 9891 int doPostCopy(int uid) { 9892 if (isFwdLocked()) { 9893 if (uid < Process.FIRST_APPLICATION_UID 9894 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9895 RES_FILE_NAME)) { 9896 Slog.e(TAG, "Failed to finalize " + cid); 9897 PackageHelper.destroySdDir(cid); 9898 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9899 } 9900 } 9901 9902 return PackageManager.INSTALL_SUCCEEDED; 9903 } 9904 } 9905 9906 static String getAsecPackageName(String packageCid) { 9907 int idx = packageCid.lastIndexOf("-"); 9908 if (idx == -1) { 9909 return packageCid; 9910 } 9911 return packageCid.substring(0, idx); 9912 } 9913 9914 // Utility method used to create code paths based on package name and available index. 9915 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9916 String idxStr = ""; 9917 int idx = 1; 9918 // Fall back to default value of idx=1 if prefix is not 9919 // part of oldCodePath 9920 if (oldCodePath != null) { 9921 String subStr = oldCodePath; 9922 // Drop the suffix right away 9923 if (suffix != null && subStr.endsWith(suffix)) { 9924 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9925 } 9926 // If oldCodePath already contains prefix find out the 9927 // ending index to either increment or decrement. 9928 int sidx = subStr.lastIndexOf(prefix); 9929 if (sidx != -1) { 9930 subStr = subStr.substring(sidx + prefix.length()); 9931 if (subStr != null) { 9932 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9933 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9934 } 9935 try { 9936 idx = Integer.parseInt(subStr); 9937 if (idx <= 1) { 9938 idx++; 9939 } else { 9940 idx--; 9941 } 9942 } catch(NumberFormatException e) { 9943 } 9944 } 9945 } 9946 } 9947 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9948 return prefix + idxStr; 9949 } 9950 9951 private File getNextCodePath(String packageName) { 9952 int suffix = 1; 9953 File result; 9954 do { 9955 result = new File(mAppInstallDir, packageName + "-" + suffix); 9956 suffix++; 9957 } while (result.exists()); 9958 return result; 9959 } 9960 9961 // Utility method used to ignore ADD/REMOVE events 9962 // by directory observer. 9963 private static boolean ignoreCodePath(String fullPathStr) { 9964 String apkName = deriveCodePathName(fullPathStr); 9965 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9966 if (idx != -1 && ((idx+1) < apkName.length())) { 9967 // Make sure the package ends with a numeral 9968 String version = apkName.substring(idx+1); 9969 try { 9970 Integer.parseInt(version); 9971 return true; 9972 } catch (NumberFormatException e) {} 9973 } 9974 return false; 9975 } 9976 9977 // Utility method that returns the relative package path with respect 9978 // to the installation directory. Like say for /data/data/com.test-1.apk 9979 // string com.test-1 is returned. 9980 static String deriveCodePathName(String codePath) { 9981 if (codePath == null) { 9982 return null; 9983 } 9984 final File codeFile = new File(codePath); 9985 final String name = codeFile.getName(); 9986 if (codeFile.isDirectory()) { 9987 return name; 9988 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9989 final int lastDot = name.lastIndexOf('.'); 9990 return name.substring(0, lastDot); 9991 } else { 9992 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9993 return null; 9994 } 9995 } 9996 9997 class PackageInstalledInfo { 9998 String name; 9999 int uid; 10000 // The set of users that originally had this package installed. 10001 int[] origUsers; 10002 // The set of users that now have this package installed. 10003 int[] newUsers; 10004 PackageParser.Package pkg; 10005 int returnCode; 10006 String returnMsg; 10007 PackageRemovedInfo removedInfo; 10008 10009 public void setError(int code, String msg) { 10010 returnCode = code; 10011 returnMsg = msg; 10012 Slog.w(TAG, msg); 10013 } 10014 10015 public void setError(String msg, PackageParserException e) { 10016 returnCode = e.error; 10017 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10018 Slog.w(TAG, msg, e); 10019 } 10020 10021 public void setError(String msg, PackageManagerException e) { 10022 returnCode = e.error; 10023 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10024 Slog.w(TAG, msg, e); 10025 } 10026 10027 // In some error cases we want to convey more info back to the observer 10028 String origPackage; 10029 String origPermission; 10030 } 10031 10032 /* 10033 * Install a non-existing package. 10034 */ 10035 private void installNewPackageLI(PackageParser.Package pkg, 10036 int parseFlags, int scanFlags, UserHandle user, 10037 String installerPackageName, PackageInstalledInfo res) { 10038 // Remember this for later, in case we need to rollback this install 10039 String pkgName = pkg.packageName; 10040 10041 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10042 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10043 synchronized(mPackages) { 10044 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10045 // A package with the same name is already installed, though 10046 // it has been renamed to an older name. The package we 10047 // are trying to install should be installed as an update to 10048 // the existing one, but that has not been requested, so bail. 10049 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10050 + " without first uninstalling package running as " 10051 + mSettings.mRenamedPackages.get(pkgName)); 10052 return; 10053 } 10054 if (mPackages.containsKey(pkgName)) { 10055 // Don't allow installation over an existing package with the same name. 10056 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10057 + " without first uninstalling."); 10058 return; 10059 } 10060 } 10061 10062 try { 10063 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10064 System.currentTimeMillis(), user); 10065 10066 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10067 // delete the partially installed application. the data directory will have to be 10068 // restored if it was already existing 10069 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10070 // remove package from internal structures. Note that we want deletePackageX to 10071 // delete the package data and cache directories that it created in 10072 // scanPackageLocked, unless those directories existed before we even tried to 10073 // install. 10074 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10075 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10076 res.removedInfo, true); 10077 } 10078 10079 } catch (PackageManagerException e) { 10080 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10081 } 10082 } 10083 10084 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10085 // Upgrade keysets are being used. Determine if new package has a superset of the 10086 // required keys. 10087 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10088 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10089 for (int i = 0; i < upgradeKeySets.length; i++) { 10090 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10091 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10092 return true; 10093 } 10094 } 10095 return false; 10096 } 10097 10098 private void replacePackageLI(PackageParser.Package pkg, 10099 int parseFlags, int scanFlags, UserHandle user, 10100 String installerPackageName, PackageInstalledInfo res) { 10101 PackageParser.Package oldPackage; 10102 String pkgName = pkg.packageName; 10103 int[] allUsers; 10104 boolean[] perUserInstalled; 10105 10106 // First find the old package info and check signatures 10107 synchronized(mPackages) { 10108 oldPackage = mPackages.get(pkgName); 10109 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10110 PackageSetting ps = mSettings.mPackages.get(pkgName); 10111 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10112 // default to original signature matching 10113 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10114 != PackageManager.SIGNATURE_MATCH) { 10115 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10116 "New package has a different signature: " + pkgName); 10117 return; 10118 } 10119 } else { 10120 if(!checkUpgradeKeySetLP(ps, pkg)) { 10121 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10122 "New package not signed by keys specified by upgrade-keysets: " 10123 + pkgName); 10124 return; 10125 } 10126 } 10127 10128 // In case of rollback, remember per-user/profile install state 10129 allUsers = sUserManager.getUserIds(); 10130 perUserInstalled = new boolean[allUsers.length]; 10131 for (int i = 0; i < allUsers.length; i++) { 10132 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10133 } 10134 } 10135 10136 boolean sysPkg = (isSystemApp(oldPackage)); 10137 if (sysPkg) { 10138 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10139 user, allUsers, perUserInstalled, installerPackageName, res); 10140 } else { 10141 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10142 user, allUsers, perUserInstalled, installerPackageName, res); 10143 } 10144 } 10145 10146 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10147 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10148 int[] allUsers, boolean[] perUserInstalled, 10149 String installerPackageName, PackageInstalledInfo res) { 10150 String pkgName = deletedPackage.packageName; 10151 boolean deletedPkg = true; 10152 boolean updatedSettings = false; 10153 10154 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10155 + deletedPackage); 10156 long origUpdateTime; 10157 if (pkg.mExtras != null) { 10158 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10159 } else { 10160 origUpdateTime = 0; 10161 } 10162 10163 // First delete the existing package while retaining the data directory 10164 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10165 res.removedInfo, true)) { 10166 // If the existing package wasn't successfully deleted 10167 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10168 deletedPkg = false; 10169 } else { 10170 // Successfully deleted the old package; proceed with replace. 10171 10172 // If deleted package lived in a container, give users a chance to 10173 // relinquish resources before killing. 10174 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10175 if (DEBUG_INSTALL) { 10176 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10177 } 10178 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10179 final ArrayList<String> pkgList = new ArrayList<String>(1); 10180 pkgList.add(deletedPackage.applicationInfo.packageName); 10181 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10182 } 10183 10184 deleteCodeCacheDirsLI(pkgName); 10185 try { 10186 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10187 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10188 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10189 user); 10190 updatedSettings = true; 10191 } catch (PackageManagerException e) { 10192 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10193 } 10194 } 10195 10196 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10197 // remove package from internal structures. Note that we want deletePackageX to 10198 // delete the package data and cache directories that it created in 10199 // scanPackageLocked, unless those directories existed before we even tried to 10200 // install. 10201 if(updatedSettings) { 10202 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10203 deletePackageLI( 10204 pkgName, null, true, allUsers, perUserInstalled, 10205 PackageManager.DELETE_KEEP_DATA, 10206 res.removedInfo, true); 10207 } 10208 // Since we failed to install the new package we need to restore the old 10209 // package that we deleted. 10210 if (deletedPkg) { 10211 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10212 File restoreFile = new File(deletedPackage.codePath); 10213 // Parse old package 10214 boolean oldOnSd = isExternal(deletedPackage); 10215 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10216 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10217 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10218 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10219 try { 10220 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10221 } catch (PackageManagerException e) { 10222 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10223 + e.getMessage()); 10224 return; 10225 } 10226 // Restore of old package succeeded. Update permissions. 10227 // writer 10228 synchronized (mPackages) { 10229 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10230 UPDATE_PERMISSIONS_ALL); 10231 // can downgrade to reader 10232 mSettings.writeLPr(); 10233 } 10234 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10235 } 10236 } 10237 } 10238 10239 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10240 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10241 int[] allUsers, boolean[] perUserInstalled, 10242 String installerPackageName, PackageInstalledInfo res) { 10243 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10244 + ", old=" + deletedPackage); 10245 boolean disabledSystem = false; 10246 boolean updatedSettings = false; 10247 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10248 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10249 != 0) { 10250 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10251 } 10252 String packageName = deletedPackage.packageName; 10253 if (packageName == null) { 10254 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10255 "Attempt to delete null packageName."); 10256 return; 10257 } 10258 PackageParser.Package oldPkg; 10259 PackageSetting oldPkgSetting; 10260 // reader 10261 synchronized (mPackages) { 10262 oldPkg = mPackages.get(packageName); 10263 oldPkgSetting = mSettings.mPackages.get(packageName); 10264 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10265 (oldPkgSetting == null)) { 10266 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10267 "Couldn't find package:" + packageName + " information"); 10268 return; 10269 } 10270 } 10271 10272 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10273 10274 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10275 res.removedInfo.removedPackage = packageName; 10276 // Remove existing system package 10277 removePackageLI(oldPkgSetting, true); 10278 // writer 10279 synchronized (mPackages) { 10280 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10281 if (!disabledSystem && deletedPackage != null) { 10282 // We didn't need to disable the .apk as a current system package, 10283 // which means we are replacing another update that is already 10284 // installed. We need to make sure to delete the older one's .apk. 10285 res.removedInfo.args = createInstallArgsForExisting(0, 10286 deletedPackage.applicationInfo.getCodePath(), 10287 deletedPackage.applicationInfo.getResourcePath(), 10288 deletedPackage.applicationInfo.nativeLibraryRootDir, 10289 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10290 } else { 10291 res.removedInfo.args = null; 10292 } 10293 } 10294 10295 // Successfully disabled the old package. Now proceed with re-installation 10296 deleteCodeCacheDirsLI(packageName); 10297 10298 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10299 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10300 10301 PackageParser.Package newPackage = null; 10302 try { 10303 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10304 if (newPackage.mExtras != null) { 10305 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10306 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10307 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10308 10309 // is the update attempting to change shared user? that isn't going to work... 10310 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10311 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10312 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10313 + " to " + newPkgSetting.sharedUser); 10314 updatedSettings = true; 10315 } 10316 } 10317 10318 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10319 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10320 user); 10321 updatedSettings = true; 10322 } 10323 10324 } catch (PackageManagerException e) { 10325 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10326 } 10327 10328 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10329 // Re installation failed. Restore old information 10330 // Remove new pkg information 10331 if (newPackage != null) { 10332 removeInstalledPackageLI(newPackage, true); 10333 } 10334 // Add back the old system package 10335 try { 10336 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10337 } catch (PackageManagerException e) { 10338 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10339 } 10340 // Restore the old system information in Settings 10341 synchronized (mPackages) { 10342 if (disabledSystem) { 10343 mSettings.enableSystemPackageLPw(packageName); 10344 } 10345 if (updatedSettings) { 10346 mSettings.setInstallerPackageName(packageName, 10347 oldPkgSetting.installerPackageName); 10348 } 10349 mSettings.writeLPr(); 10350 } 10351 } 10352 } 10353 10354 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10355 int[] allUsers, boolean[] perUserInstalled, 10356 PackageInstalledInfo res, UserHandle user) { 10357 String pkgName = newPackage.packageName; 10358 synchronized (mPackages) { 10359 //write settings. the installStatus will be incomplete at this stage. 10360 //note that the new package setting would have already been 10361 //added to mPackages. It hasn't been persisted yet. 10362 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10363 mSettings.writeLPr(); 10364 } 10365 10366 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10367 10368 synchronized (mPackages) { 10369 updatePermissionsLPw(newPackage.packageName, newPackage, 10370 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10371 ? UPDATE_PERMISSIONS_ALL : 0)); 10372 // For system-bundled packages, we assume that installing an upgraded version 10373 // of the package implies that the user actually wants to run that new code, 10374 // so we enable the package. 10375 PackageSetting ps = mSettings.mPackages.get(pkgName); 10376 if (ps != null) { 10377 if (isSystemApp(newPackage)) { 10378 // NB: implicit assumption that system package upgrades apply to all users 10379 if (DEBUG_INSTALL) { 10380 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10381 } 10382 if (res.origUsers != null) { 10383 for (int userHandle : res.origUsers) { 10384 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10385 userHandle, installerPackageName); 10386 } 10387 } 10388 // Also convey the prior install/uninstall state 10389 if (allUsers != null && perUserInstalled != null) { 10390 for (int i = 0; i < allUsers.length; i++) { 10391 if (DEBUG_INSTALL) { 10392 Slog.d(TAG, " user " + allUsers[i] 10393 + " => " + perUserInstalled[i]); 10394 } 10395 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10396 } 10397 // these install state changes will be persisted in the 10398 // upcoming call to mSettings.writeLPr(). 10399 } 10400 } 10401 // It's implied that when a user requests installation, they want the app to be 10402 // installed and enabled. 10403 int userId = user.getIdentifier(); 10404 if (userId != UserHandle.USER_ALL) { 10405 ps.setInstalled(true, userId); 10406 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10407 } 10408 } 10409 res.name = pkgName; 10410 res.uid = newPackage.applicationInfo.uid; 10411 res.pkg = newPackage; 10412 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10413 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10414 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10415 //to update install status 10416 mSettings.writeLPr(); 10417 } 10418 } 10419 10420 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10421 final int installFlags = args.installFlags; 10422 String installerPackageName = args.installerPackageName; 10423 File tmpPackageFile = new File(args.getCodePath()); 10424 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10425 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10426 boolean replace = false; 10427 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10428 // Result object to be returned 10429 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10430 10431 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10432 // Retrieve PackageSettings and parse package 10433 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10434 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10435 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10436 PackageParser pp = new PackageParser(); 10437 pp.setSeparateProcesses(mSeparateProcesses); 10438 pp.setDisplayMetrics(mMetrics); 10439 10440 final PackageParser.Package pkg; 10441 try { 10442 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10443 } catch (PackageParserException e) { 10444 res.setError("Failed parse during installPackageLI", e); 10445 return; 10446 } 10447 10448 // Mark that we have an install time CPU ABI override. 10449 pkg.cpuAbiOverride = args.abiOverride; 10450 10451 String pkgName = res.name = pkg.packageName; 10452 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10453 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10454 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10455 return; 10456 } 10457 } 10458 10459 try { 10460 pp.collectCertificates(pkg, parseFlags); 10461 pp.collectManifestDigest(pkg); 10462 } catch (PackageParserException e) { 10463 res.setError("Failed collect during installPackageLI", e); 10464 return; 10465 } 10466 10467 /* If the installer passed in a manifest digest, compare it now. */ 10468 if (args.manifestDigest != null) { 10469 if (DEBUG_INSTALL) { 10470 final String parsedManifest = pkg.manifestDigest == null ? "null" 10471 : pkg.manifestDigest.toString(); 10472 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10473 + parsedManifest); 10474 } 10475 10476 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10477 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10478 return; 10479 } 10480 } else if (DEBUG_INSTALL) { 10481 final String parsedManifest = pkg.manifestDigest == null 10482 ? "null" : pkg.manifestDigest.toString(); 10483 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10484 } 10485 10486 // Get rid of all references to package scan path via parser. 10487 pp = null; 10488 String oldCodePath = null; 10489 boolean systemApp = false; 10490 synchronized (mPackages) { 10491 // Check if installing already existing package 10492 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10493 String oldName = mSettings.mRenamedPackages.get(pkgName); 10494 if (pkg.mOriginalPackages != null 10495 && pkg.mOriginalPackages.contains(oldName) 10496 && mPackages.containsKey(oldName)) { 10497 // This package is derived from an original package, 10498 // and this device has been updating from that original 10499 // name. We must continue using the original name, so 10500 // rename the new package here. 10501 pkg.setPackageName(oldName); 10502 pkgName = pkg.packageName; 10503 replace = true; 10504 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10505 + oldName + " pkgName=" + pkgName); 10506 } else if (mPackages.containsKey(pkgName)) { 10507 // This package, under its official name, already exists 10508 // on the device; we should replace it. 10509 replace = true; 10510 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10511 } 10512 } 10513 10514 PackageSetting ps = mSettings.mPackages.get(pkgName); 10515 if (ps != null) { 10516 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10517 10518 // Quick sanity check that we're signed correctly if updating; 10519 // we'll check this again later when scanning, but we want to 10520 // bail early here before tripping over redefined permissions. 10521 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10522 try { 10523 verifySignaturesLP(ps, pkg); 10524 } catch (PackageManagerException e) { 10525 res.setError(e.error, e.getMessage()); 10526 return; 10527 } 10528 } else { 10529 if (!checkUpgradeKeySetLP(ps, pkg)) { 10530 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10531 + pkg.packageName + " upgrade keys do not match the " 10532 + "previously installed version"); 10533 return; 10534 } 10535 } 10536 10537 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10538 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10539 systemApp = (ps.pkg.applicationInfo.flags & 10540 ApplicationInfo.FLAG_SYSTEM) != 0; 10541 } 10542 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10543 } 10544 10545 // Check whether the newly-scanned package wants to define an already-defined perm 10546 int N = pkg.permissions.size(); 10547 for (int i = N-1; i >= 0; i--) { 10548 PackageParser.Permission perm = pkg.permissions.get(i); 10549 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10550 if (bp != null) { 10551 // If the defining package is signed with our cert, it's okay. This 10552 // also includes the "updating the same package" case, of course. 10553 // "updating same package" could also involve key-rotation. 10554 final boolean sigsOk; 10555 if (!bp.sourcePackage.equals(pkg.packageName) 10556 || !(bp.packageSetting instanceof PackageSetting) 10557 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10558 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10559 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10560 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10561 } else { 10562 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10563 } 10564 if (!sigsOk) { 10565 // If the owning package is the system itself, we log but allow 10566 // install to proceed; we fail the install on all other permission 10567 // redefinitions. 10568 if (!bp.sourcePackage.equals("android")) { 10569 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10570 + pkg.packageName + " attempting to redeclare permission " 10571 + perm.info.name + " already owned by " + bp.sourcePackage); 10572 res.origPermission = perm.info.name; 10573 res.origPackage = bp.sourcePackage; 10574 return; 10575 } else { 10576 Slog.w(TAG, "Package " + pkg.packageName 10577 + " attempting to redeclare system permission " 10578 + perm.info.name + "; ignoring new declaration"); 10579 pkg.permissions.remove(i); 10580 } 10581 } 10582 } 10583 } 10584 10585 } 10586 10587 if (systemApp && onSd) { 10588 // Disable updates to system apps on sdcard 10589 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10590 "Cannot install updates to system apps on sdcard"); 10591 return; 10592 } 10593 10594 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10595 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10596 return; 10597 } 10598 10599 if (replace) { 10600 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10601 installerPackageName, res); 10602 } else { 10603 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10604 args.user, installerPackageName, res); 10605 } 10606 synchronized (mPackages) { 10607 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10608 if (ps != null) { 10609 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10610 } 10611 } 10612 } 10613 10614 private static boolean isMultiArch(PackageSetting ps) { 10615 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10616 } 10617 10618 private static boolean isMultiArch(ApplicationInfo info) { 10619 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10620 } 10621 10622 private static boolean isExternal(PackageParser.Package pkg) { 10623 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10624 } 10625 10626 private static boolean isExternal(PackageSetting ps) { 10627 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10628 } 10629 10630 private static boolean isExternal(ApplicationInfo info) { 10631 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10632 } 10633 10634 private static boolean isSystemApp(PackageParser.Package pkg) { 10635 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10636 } 10637 10638 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10639 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10640 } 10641 10642 private static boolean isSystemApp(ApplicationInfo info) { 10643 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10644 } 10645 10646 private static boolean isSystemApp(PackageSetting ps) { 10647 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10648 } 10649 10650 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10651 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10652 } 10653 10654 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10655 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10656 } 10657 10658 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10659 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10660 } 10661 10662 private int packageFlagsToInstallFlags(PackageSetting ps) { 10663 int installFlags = 0; 10664 if (isExternal(ps)) { 10665 installFlags |= PackageManager.INSTALL_EXTERNAL; 10666 } 10667 if (ps.isForwardLocked()) { 10668 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10669 } 10670 return installFlags; 10671 } 10672 10673 private void deleteTempPackageFiles() { 10674 final FilenameFilter filter = new FilenameFilter() { 10675 public boolean accept(File dir, String name) { 10676 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10677 } 10678 }; 10679 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10680 file.delete(); 10681 } 10682 } 10683 10684 @Override 10685 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10686 int flags) { 10687 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10688 flags); 10689 } 10690 10691 @Override 10692 public void deletePackage(final String packageName, 10693 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10694 mContext.enforceCallingOrSelfPermission( 10695 android.Manifest.permission.DELETE_PACKAGES, null); 10696 final int uid = Binder.getCallingUid(); 10697 if (UserHandle.getUserId(uid) != userId) { 10698 mContext.enforceCallingPermission( 10699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10700 "deletePackage for user " + userId); 10701 } 10702 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10703 try { 10704 observer.onPackageDeleted(packageName, 10705 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10706 } catch (RemoteException re) { 10707 } 10708 return; 10709 } 10710 10711 boolean uninstallBlocked = false; 10712 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10713 int[] users = sUserManager.getUserIds(); 10714 for (int i = 0; i < users.length; ++i) { 10715 if (getBlockUninstallForUser(packageName, users[i])) { 10716 uninstallBlocked = true; 10717 break; 10718 } 10719 } 10720 } else { 10721 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10722 } 10723 if (uninstallBlocked) { 10724 try { 10725 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10726 null); 10727 } catch (RemoteException re) { 10728 } 10729 return; 10730 } 10731 10732 if (DEBUG_REMOVE) { 10733 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10734 } 10735 // Queue up an async operation since the package deletion may take a little while. 10736 mHandler.post(new Runnable() { 10737 public void run() { 10738 mHandler.removeCallbacks(this); 10739 final int returnCode = deletePackageX(packageName, userId, flags); 10740 if (observer != null) { 10741 try { 10742 observer.onPackageDeleted(packageName, returnCode, null); 10743 } catch (RemoteException e) { 10744 Log.i(TAG, "Observer no longer exists."); 10745 } //end catch 10746 } //end if 10747 } //end run 10748 }); 10749 } 10750 10751 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10752 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10753 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10754 try { 10755 if (dpm != null) { 10756 if (dpm.isDeviceOwner(packageName)) { 10757 return true; 10758 } 10759 int[] users; 10760 if (userId == UserHandle.USER_ALL) { 10761 users = sUserManager.getUserIds(); 10762 } else { 10763 users = new int[]{userId}; 10764 } 10765 for (int i = 0; i < users.length; ++i) { 10766 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10767 return true; 10768 } 10769 } 10770 } 10771 } catch (RemoteException e) { 10772 } 10773 return false; 10774 } 10775 10776 /** 10777 * This method is an internal method that could be get invoked either 10778 * to delete an installed package or to clean up a failed installation. 10779 * After deleting an installed package, a broadcast is sent to notify any 10780 * listeners that the package has been installed. For cleaning up a failed 10781 * installation, the broadcast is not necessary since the package's 10782 * installation wouldn't have sent the initial broadcast either 10783 * The key steps in deleting a package are 10784 * deleting the package information in internal structures like mPackages, 10785 * deleting the packages base directories through installd 10786 * updating mSettings to reflect current status 10787 * persisting settings for later use 10788 * sending a broadcast if necessary 10789 */ 10790 private int deletePackageX(String packageName, int userId, int flags) { 10791 final PackageRemovedInfo info = new PackageRemovedInfo(); 10792 final boolean res; 10793 10794 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10795 ? UserHandle.ALL : new UserHandle(userId); 10796 10797 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10798 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10799 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10800 } 10801 10802 boolean removedForAllUsers = false; 10803 boolean systemUpdate = false; 10804 10805 // for the uninstall-updates case and restricted profiles, remember the per- 10806 // userhandle installed state 10807 int[] allUsers; 10808 boolean[] perUserInstalled; 10809 synchronized (mPackages) { 10810 PackageSetting ps = mSettings.mPackages.get(packageName); 10811 allUsers = sUserManager.getUserIds(); 10812 perUserInstalled = new boolean[allUsers.length]; 10813 for (int i = 0; i < allUsers.length; i++) { 10814 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10815 } 10816 } 10817 10818 synchronized (mInstallLock) { 10819 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10820 res = deletePackageLI(packageName, removeForUser, 10821 true, allUsers, perUserInstalled, 10822 flags | REMOVE_CHATTY, info, true); 10823 systemUpdate = info.isRemovedPackageSystemUpdate; 10824 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10825 removedForAllUsers = true; 10826 } 10827 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10828 + " removedForAllUsers=" + removedForAllUsers); 10829 } 10830 10831 if (res) { 10832 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10833 10834 // If the removed package was a system update, the old system package 10835 // was re-enabled; we need to broadcast this information 10836 if (systemUpdate) { 10837 Bundle extras = new Bundle(1); 10838 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10839 ? info.removedAppId : info.uid); 10840 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10841 10842 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10843 extras, null, null, null); 10844 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10845 extras, null, null, null); 10846 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10847 null, packageName, null, null); 10848 } 10849 } 10850 // Force a gc here. 10851 Runtime.getRuntime().gc(); 10852 // Delete the resources here after sending the broadcast to let 10853 // other processes clean up before deleting resources. 10854 if (info.args != null) { 10855 synchronized (mInstallLock) { 10856 info.args.doPostDeleteLI(true); 10857 } 10858 } 10859 10860 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10861 } 10862 10863 static class PackageRemovedInfo { 10864 String removedPackage; 10865 int uid = -1; 10866 int removedAppId = -1; 10867 int[] removedUsers = null; 10868 boolean isRemovedPackageSystemUpdate = false; 10869 // Clean up resources deleted packages. 10870 InstallArgs args = null; 10871 10872 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10873 Bundle extras = new Bundle(1); 10874 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10875 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10876 if (replacing) { 10877 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10878 } 10879 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10880 if (removedPackage != null) { 10881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10882 extras, null, null, removedUsers); 10883 if (fullRemove && !replacing) { 10884 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10885 extras, null, null, removedUsers); 10886 } 10887 } 10888 if (removedAppId >= 0) { 10889 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10890 removedUsers); 10891 } 10892 } 10893 } 10894 10895 /* 10896 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10897 * flag is not set, the data directory is removed as well. 10898 * make sure this flag is set for partially installed apps. If not its meaningless to 10899 * delete a partially installed application. 10900 */ 10901 private void removePackageDataLI(PackageSetting ps, 10902 int[] allUserHandles, boolean[] perUserInstalled, 10903 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10904 String packageName = ps.name; 10905 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10906 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10907 // Retrieve object to delete permissions for shared user later on 10908 final PackageSetting deletedPs; 10909 // reader 10910 synchronized (mPackages) { 10911 deletedPs = mSettings.mPackages.get(packageName); 10912 if (outInfo != null) { 10913 outInfo.removedPackage = packageName; 10914 outInfo.removedUsers = deletedPs != null 10915 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10916 : null; 10917 } 10918 } 10919 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10920 removeDataDirsLI(packageName); 10921 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10922 } 10923 // writer 10924 synchronized (mPackages) { 10925 if (deletedPs != null) { 10926 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10927 if (outInfo != null) { 10928 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10929 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10930 } 10931 updatePermissionsLPw(deletedPs.name, null, 0); 10932 if (deletedPs.sharedUser != null) { 10933 // Remove permissions associated with package. Since runtime 10934 // permissions are per user we have to kill the removed package 10935 // or packages running under the shared user of the removed 10936 // package if revoking the permissions requested only by the removed 10937 // package is successful and this causes a change in gids. 10938 for (int userId : UserManagerService.getInstance().getUserIds()) { 10939 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 10940 userId); 10941 if (userIdToKill == userId) { 10942 // If gids changed for this user, kill all affected packages. 10943 killSettingPackagesForUser(deletedPs, userIdToKill, 10944 KILL_APP_REASON_GIDS_CHANGED); 10945 } else if (userIdToKill == UserHandle.USER_ALL) { 10946 // If gids changed for all users, kill them all - done. 10947 killSettingPackagesForUser(deletedPs, userIdToKill, 10948 KILL_APP_REASON_GIDS_CHANGED); 10949 break; 10950 } 10951 } 10952 } 10953 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10954 } 10955 // make sure to preserve per-user disabled state if this removal was just 10956 // a downgrade of a system app to the factory package 10957 if (allUserHandles != null && perUserInstalled != null) { 10958 if (DEBUG_REMOVE) { 10959 Slog.d(TAG, "Propagating install state across downgrade"); 10960 } 10961 for (int i = 0; i < allUserHandles.length; i++) { 10962 if (DEBUG_REMOVE) { 10963 Slog.d(TAG, " user " + allUserHandles[i] 10964 + " => " + perUserInstalled[i]); 10965 } 10966 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10967 } 10968 } 10969 } 10970 // can downgrade to reader 10971 if (writeSettings) { 10972 // Save settings now 10973 mSettings.writeLPr(); 10974 } 10975 } 10976 if (outInfo != null) { 10977 // A user ID was deleted here. Go through all users and remove it 10978 // from KeyStore. 10979 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10980 } 10981 } 10982 10983 static boolean locationIsPrivileged(File path) { 10984 try { 10985 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10986 .getCanonicalPath(); 10987 return path.getCanonicalPath().startsWith(privilegedAppDir); 10988 } catch (IOException e) { 10989 Slog.e(TAG, "Unable to access code path " + path); 10990 } 10991 return false; 10992 } 10993 10994 /* 10995 * Tries to delete system package. 10996 */ 10997 private boolean deleteSystemPackageLI(PackageSetting newPs, 10998 int[] allUserHandles, boolean[] perUserInstalled, 10999 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11000 final boolean applyUserRestrictions 11001 = (allUserHandles != null) && (perUserInstalled != null); 11002 PackageSetting disabledPs = null; 11003 // Confirm if the system package has been updated 11004 // An updated system app can be deleted. This will also have to restore 11005 // the system pkg from system partition 11006 // reader 11007 synchronized (mPackages) { 11008 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11009 } 11010 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11011 + " disabledPs=" + disabledPs); 11012 if (disabledPs == null) { 11013 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11014 return false; 11015 } else if (DEBUG_REMOVE) { 11016 Slog.d(TAG, "Deleting system pkg from data partition"); 11017 } 11018 if (DEBUG_REMOVE) { 11019 if (applyUserRestrictions) { 11020 Slog.d(TAG, "Remembering install states:"); 11021 for (int i = 0; i < allUserHandles.length; i++) { 11022 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11023 } 11024 } 11025 } 11026 // Delete the updated package 11027 outInfo.isRemovedPackageSystemUpdate = true; 11028 if (disabledPs.versionCode < newPs.versionCode) { 11029 // Delete data for downgrades 11030 flags &= ~PackageManager.DELETE_KEEP_DATA; 11031 } else { 11032 // Preserve data by setting flag 11033 flags |= PackageManager.DELETE_KEEP_DATA; 11034 } 11035 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11036 allUserHandles, perUserInstalled, outInfo, writeSettings); 11037 if (!ret) { 11038 return false; 11039 } 11040 // writer 11041 synchronized (mPackages) { 11042 // Reinstate the old system package 11043 mSettings.enableSystemPackageLPw(newPs.name); 11044 // Remove any native libraries from the upgraded package. 11045 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11046 } 11047 // Install the system package 11048 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11049 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11050 if (locationIsPrivileged(disabledPs.codePath)) { 11051 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11052 } 11053 11054 final PackageParser.Package newPkg; 11055 try { 11056 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11057 } catch (PackageManagerException e) { 11058 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11059 return false; 11060 } 11061 11062 // writer 11063 synchronized (mPackages) { 11064 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11065 updatePermissionsLPw(newPkg.packageName, newPkg, 11066 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11067 if (applyUserRestrictions) { 11068 if (DEBUG_REMOVE) { 11069 Slog.d(TAG, "Propagating install state across reinstall"); 11070 } 11071 for (int i = 0; i < allUserHandles.length; i++) { 11072 if (DEBUG_REMOVE) { 11073 Slog.d(TAG, " user " + allUserHandles[i] 11074 + " => " + perUserInstalled[i]); 11075 } 11076 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11077 } 11078 // Regardless of writeSettings we need to ensure that this restriction 11079 // state propagation is persisted 11080 mSettings.writeAllUsersPackageRestrictionsLPr(); 11081 } 11082 // can downgrade to reader here 11083 if (writeSettings) { 11084 mSettings.writeLPr(); 11085 } 11086 } 11087 return true; 11088 } 11089 11090 private boolean deleteInstalledPackageLI(PackageSetting ps, 11091 boolean deleteCodeAndResources, int flags, 11092 int[] allUserHandles, boolean[] perUserInstalled, 11093 PackageRemovedInfo outInfo, boolean writeSettings) { 11094 if (outInfo != null) { 11095 outInfo.uid = ps.appId; 11096 } 11097 11098 // Delete package data from internal structures and also remove data if flag is set 11099 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11100 11101 // Delete application code and resources 11102 if (deleteCodeAndResources && (outInfo != null)) { 11103 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11104 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11105 getAppDexInstructionSets(ps)); 11106 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11107 } 11108 return true; 11109 } 11110 11111 @Override 11112 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11113 int userId) { 11114 mContext.enforceCallingOrSelfPermission( 11115 android.Manifest.permission.DELETE_PACKAGES, null); 11116 synchronized (mPackages) { 11117 PackageSetting ps = mSettings.mPackages.get(packageName); 11118 if (ps == null) { 11119 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11120 return false; 11121 } 11122 if (!ps.getInstalled(userId)) { 11123 // Can't block uninstall for an app that is not installed or enabled. 11124 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11125 return false; 11126 } 11127 ps.setBlockUninstall(blockUninstall, userId); 11128 mSettings.writePackageRestrictionsLPr(userId); 11129 } 11130 return true; 11131 } 11132 11133 @Override 11134 public boolean getBlockUninstallForUser(String packageName, int userId) { 11135 synchronized (mPackages) { 11136 PackageSetting ps = mSettings.mPackages.get(packageName); 11137 if (ps == null) { 11138 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11139 return false; 11140 } 11141 return ps.getBlockUninstall(userId); 11142 } 11143 } 11144 11145 /* 11146 * This method handles package deletion in general 11147 */ 11148 private boolean deletePackageLI(String packageName, UserHandle user, 11149 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11150 int flags, PackageRemovedInfo outInfo, 11151 boolean writeSettings) { 11152 if (packageName == null) { 11153 Slog.w(TAG, "Attempt to delete null packageName."); 11154 return false; 11155 } 11156 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11157 PackageSetting ps; 11158 boolean dataOnly = false; 11159 int removeUser = -1; 11160 int appId = -1; 11161 synchronized (mPackages) { 11162 ps = mSettings.mPackages.get(packageName); 11163 if (ps == null) { 11164 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11165 return false; 11166 } 11167 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11168 && user.getIdentifier() != UserHandle.USER_ALL) { 11169 // The caller is asking that the package only be deleted for a single 11170 // user. To do this, we just mark its uninstalled state and delete 11171 // its data. If this is a system app, we only allow this to happen if 11172 // they have set the special DELETE_SYSTEM_APP which requests different 11173 // semantics than normal for uninstalling system apps. 11174 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11175 ps.setUserState(user.getIdentifier(), 11176 COMPONENT_ENABLED_STATE_DEFAULT, 11177 false, //installed 11178 true, //stopped 11179 true, //notLaunched 11180 false, //hidden 11181 null, null, null, 11182 false // blockUninstall 11183 ); 11184 if (!isSystemApp(ps)) { 11185 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11186 // Other user still have this package installed, so all 11187 // we need to do is clear this user's data and save that 11188 // it is uninstalled. 11189 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11190 removeUser = user.getIdentifier(); 11191 appId = ps.appId; 11192 mSettings.writePackageRestrictionsLPr(removeUser); 11193 } else { 11194 // We need to set it back to 'installed' so the uninstall 11195 // broadcasts will be sent correctly. 11196 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11197 ps.setInstalled(true, user.getIdentifier()); 11198 } 11199 } else { 11200 // This is a system app, so we assume that the 11201 // other users still have this package installed, so all 11202 // we need to do is clear this user's data and save that 11203 // it is uninstalled. 11204 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11205 removeUser = user.getIdentifier(); 11206 appId = ps.appId; 11207 mSettings.writePackageRestrictionsLPr(removeUser); 11208 } 11209 } 11210 } 11211 11212 if (removeUser >= 0) { 11213 // From above, we determined that we are deleting this only 11214 // for a single user. Continue the work here. 11215 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11216 if (outInfo != null) { 11217 outInfo.removedPackage = packageName; 11218 outInfo.removedAppId = appId; 11219 outInfo.removedUsers = new int[] {removeUser}; 11220 } 11221 mInstaller.clearUserData(packageName, removeUser); 11222 removeKeystoreDataIfNeeded(removeUser, appId); 11223 schedulePackageCleaning(packageName, removeUser, false); 11224 return true; 11225 } 11226 11227 if (dataOnly) { 11228 // Delete application data first 11229 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11230 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11231 return true; 11232 } 11233 11234 boolean ret = false; 11235 if (isSystemApp(ps)) { 11236 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11237 // When an updated system application is deleted we delete the existing resources as well and 11238 // fall back to existing code in system partition 11239 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11240 flags, outInfo, writeSettings); 11241 } else { 11242 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11243 // Kill application pre-emptively especially for apps on sd. 11244 killApplication(packageName, ps.appId, "uninstall pkg"); 11245 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11246 allUserHandles, perUserInstalled, 11247 outInfo, writeSettings); 11248 } 11249 11250 return ret; 11251 } 11252 11253 private final class ClearStorageConnection implements ServiceConnection { 11254 IMediaContainerService mContainerService; 11255 11256 @Override 11257 public void onServiceConnected(ComponentName name, IBinder service) { 11258 synchronized (this) { 11259 mContainerService = IMediaContainerService.Stub.asInterface(service); 11260 notifyAll(); 11261 } 11262 } 11263 11264 @Override 11265 public void onServiceDisconnected(ComponentName name) { 11266 } 11267 } 11268 11269 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11270 final boolean mounted; 11271 if (Environment.isExternalStorageEmulated()) { 11272 mounted = true; 11273 } else { 11274 final String status = Environment.getExternalStorageState(); 11275 11276 mounted = status.equals(Environment.MEDIA_MOUNTED) 11277 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11278 } 11279 11280 if (!mounted) { 11281 return; 11282 } 11283 11284 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11285 int[] users; 11286 if (userId == UserHandle.USER_ALL) { 11287 users = sUserManager.getUserIds(); 11288 } else { 11289 users = new int[] { userId }; 11290 } 11291 final ClearStorageConnection conn = new ClearStorageConnection(); 11292 if (mContext.bindServiceAsUser( 11293 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11294 try { 11295 for (int curUser : users) { 11296 long timeout = SystemClock.uptimeMillis() + 5000; 11297 synchronized (conn) { 11298 long now = SystemClock.uptimeMillis(); 11299 while (conn.mContainerService == null && now < timeout) { 11300 try { 11301 conn.wait(timeout - now); 11302 } catch (InterruptedException e) { 11303 } 11304 } 11305 } 11306 if (conn.mContainerService == null) { 11307 return; 11308 } 11309 11310 final UserEnvironment userEnv = new UserEnvironment(curUser); 11311 clearDirectory(conn.mContainerService, 11312 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11313 if (allData) { 11314 clearDirectory(conn.mContainerService, 11315 userEnv.buildExternalStorageAppDataDirs(packageName)); 11316 clearDirectory(conn.mContainerService, 11317 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11318 } 11319 } 11320 } finally { 11321 mContext.unbindService(conn); 11322 } 11323 } 11324 } 11325 11326 @Override 11327 public void clearApplicationUserData(final String packageName, 11328 final IPackageDataObserver observer, final int userId) { 11329 mContext.enforceCallingOrSelfPermission( 11330 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11331 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11332 // Queue up an async operation since the package deletion may take a little while. 11333 mHandler.post(new Runnable() { 11334 public void run() { 11335 mHandler.removeCallbacks(this); 11336 final boolean succeeded; 11337 synchronized (mInstallLock) { 11338 succeeded = clearApplicationUserDataLI(packageName, userId); 11339 } 11340 clearExternalStorageDataSync(packageName, userId, true); 11341 if (succeeded) { 11342 // invoke DeviceStorageMonitor's update method to clear any notifications 11343 DeviceStorageMonitorInternal 11344 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11345 if (dsm != null) { 11346 dsm.checkMemory(); 11347 } 11348 } 11349 if(observer != null) { 11350 try { 11351 observer.onRemoveCompleted(packageName, succeeded); 11352 } catch (RemoteException e) { 11353 Log.i(TAG, "Observer no longer exists."); 11354 } 11355 } //end if observer 11356 } //end run 11357 }); 11358 } 11359 11360 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11361 if (packageName == null) { 11362 Slog.w(TAG, "Attempt to delete null packageName."); 11363 return false; 11364 } 11365 11366 // Try finding details about the requested package 11367 PackageParser.Package pkg; 11368 synchronized (mPackages) { 11369 pkg = mPackages.get(packageName); 11370 if (pkg == null) { 11371 final PackageSetting ps = mSettings.mPackages.get(packageName); 11372 if (ps != null) { 11373 pkg = ps.pkg; 11374 } 11375 } 11376 } 11377 11378 if (pkg == null) { 11379 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11380 } 11381 11382 // Always delete data directories for package, even if we found no other 11383 // record of app. This helps users recover from UID mismatches without 11384 // resorting to a full data wipe. 11385 int retCode = mInstaller.clearUserData(packageName, userId); 11386 if (retCode < 0) { 11387 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11388 return false; 11389 } 11390 11391 if (pkg == null) { 11392 return false; 11393 } 11394 11395 if (pkg != null && pkg.applicationInfo != null) { 11396 final int appId = pkg.applicationInfo.uid; 11397 removeKeystoreDataIfNeeded(userId, appId); 11398 } 11399 11400 // Create a native library symlink only if we have native libraries 11401 // and if the native libraries are 32 bit libraries. We do not provide 11402 // this symlink for 64 bit libraries. 11403 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11404 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11405 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11406 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11407 Slog.w(TAG, "Failed linking native library dir"); 11408 return false; 11409 } 11410 } 11411 11412 return true; 11413 } 11414 11415 /** 11416 * Remove entries from the keystore daemon. Will only remove it if the 11417 * {@code appId} is valid. 11418 */ 11419 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11420 if (appId < 0) { 11421 return; 11422 } 11423 11424 final KeyStore keyStore = KeyStore.getInstance(); 11425 if (keyStore != null) { 11426 if (userId == UserHandle.USER_ALL) { 11427 for (final int individual : sUserManager.getUserIds()) { 11428 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11429 } 11430 } else { 11431 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11432 } 11433 } else { 11434 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11435 } 11436 } 11437 11438 @Override 11439 public void deleteApplicationCacheFiles(final String packageName, 11440 final IPackageDataObserver observer) { 11441 mContext.enforceCallingOrSelfPermission( 11442 android.Manifest.permission.DELETE_CACHE_FILES, null); 11443 // Queue up an async operation since the package deletion may take a little while. 11444 final int userId = UserHandle.getCallingUserId(); 11445 mHandler.post(new Runnable() { 11446 public void run() { 11447 mHandler.removeCallbacks(this); 11448 final boolean succeded; 11449 synchronized (mInstallLock) { 11450 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11451 } 11452 clearExternalStorageDataSync(packageName, userId, false); 11453 if(observer != null) { 11454 try { 11455 observer.onRemoveCompleted(packageName, succeded); 11456 } catch (RemoteException e) { 11457 Log.i(TAG, "Observer no longer exists."); 11458 } 11459 } //end if observer 11460 } //end run 11461 }); 11462 } 11463 11464 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11465 if (packageName == null) { 11466 Slog.w(TAG, "Attempt to delete null packageName."); 11467 return false; 11468 } 11469 PackageParser.Package p; 11470 synchronized (mPackages) { 11471 p = mPackages.get(packageName); 11472 } 11473 if (p == null) { 11474 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11475 return false; 11476 } 11477 final ApplicationInfo applicationInfo = p.applicationInfo; 11478 if (applicationInfo == null) { 11479 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11480 return false; 11481 } 11482 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11483 if (retCode < 0) { 11484 Slog.w(TAG, "Couldn't remove cache files for package: " 11485 + packageName + " u" + userId); 11486 return false; 11487 } 11488 return true; 11489 } 11490 11491 @Override 11492 public void getPackageSizeInfo(final String packageName, int userHandle, 11493 final IPackageStatsObserver observer) { 11494 mContext.enforceCallingOrSelfPermission( 11495 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11496 if (packageName == null) { 11497 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11498 } 11499 11500 PackageStats stats = new PackageStats(packageName, userHandle); 11501 11502 /* 11503 * Queue up an async operation since the package measurement may take a 11504 * little while. 11505 */ 11506 Message msg = mHandler.obtainMessage(INIT_COPY); 11507 msg.obj = new MeasureParams(stats, observer); 11508 mHandler.sendMessage(msg); 11509 } 11510 11511 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11512 PackageStats pStats) { 11513 if (packageName == null) { 11514 Slog.w(TAG, "Attempt to get size of null packageName."); 11515 return false; 11516 } 11517 PackageParser.Package p; 11518 boolean dataOnly = false; 11519 String libDirRoot = null; 11520 String asecPath = null; 11521 PackageSetting ps = null; 11522 synchronized (mPackages) { 11523 p = mPackages.get(packageName); 11524 ps = mSettings.mPackages.get(packageName); 11525 if(p == null) { 11526 dataOnly = true; 11527 if((ps == null) || (ps.pkg == null)) { 11528 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11529 return false; 11530 } 11531 p = ps.pkg; 11532 } 11533 if (ps != null) { 11534 libDirRoot = ps.legacyNativeLibraryPathString; 11535 } 11536 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11537 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11538 if (secureContainerId != null) { 11539 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11540 } 11541 } 11542 } 11543 String publicSrcDir = null; 11544 if(!dataOnly) { 11545 final ApplicationInfo applicationInfo = p.applicationInfo; 11546 if (applicationInfo == null) { 11547 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11548 return false; 11549 } 11550 if (p.isForwardLocked()) { 11551 publicSrcDir = applicationInfo.getBaseResourcePath(); 11552 } 11553 } 11554 // TODO: extend to measure size of split APKs 11555 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11556 // not just the first level. 11557 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11558 // just the primary. 11559 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11560 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11561 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11562 if (res < 0) { 11563 return false; 11564 } 11565 11566 // Fix-up for forward-locked applications in ASEC containers. 11567 if (!isExternal(p)) { 11568 pStats.codeSize += pStats.externalCodeSize; 11569 pStats.externalCodeSize = 0L; 11570 } 11571 11572 return true; 11573 } 11574 11575 11576 @Override 11577 public void addPackageToPreferred(String packageName) { 11578 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11579 } 11580 11581 @Override 11582 public void removePackageFromPreferred(String packageName) { 11583 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11584 } 11585 11586 @Override 11587 public List<PackageInfo> getPreferredPackages(int flags) { 11588 return new ArrayList<PackageInfo>(); 11589 } 11590 11591 private int getUidTargetSdkVersionLockedLPr(int uid) { 11592 Object obj = mSettings.getUserIdLPr(uid); 11593 if (obj instanceof SharedUserSetting) { 11594 final SharedUserSetting sus = (SharedUserSetting) obj; 11595 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11596 final Iterator<PackageSetting> it = sus.packages.iterator(); 11597 while (it.hasNext()) { 11598 final PackageSetting ps = it.next(); 11599 if (ps.pkg != null) { 11600 int v = ps.pkg.applicationInfo.targetSdkVersion; 11601 if (v < vers) vers = v; 11602 } 11603 } 11604 return vers; 11605 } else if (obj instanceof PackageSetting) { 11606 final PackageSetting ps = (PackageSetting) obj; 11607 if (ps.pkg != null) { 11608 return ps.pkg.applicationInfo.targetSdkVersion; 11609 } 11610 } 11611 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11612 } 11613 11614 @Override 11615 public void addPreferredActivity(IntentFilter filter, int match, 11616 ComponentName[] set, ComponentName activity, int userId) { 11617 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11618 "Adding preferred"); 11619 } 11620 11621 private void addPreferredActivityInternal(IntentFilter filter, int match, 11622 ComponentName[] set, ComponentName activity, boolean always, int userId, 11623 String opname) { 11624 // writer 11625 int callingUid = Binder.getCallingUid(); 11626 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11627 if (filter.countActions() == 0) { 11628 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11629 return; 11630 } 11631 synchronized (mPackages) { 11632 if (mContext.checkCallingOrSelfPermission( 11633 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11634 != PackageManager.PERMISSION_GRANTED) { 11635 if (getUidTargetSdkVersionLockedLPr(callingUid) 11636 < Build.VERSION_CODES.FROYO) { 11637 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11638 + callingUid); 11639 return; 11640 } 11641 mContext.enforceCallingOrSelfPermission( 11642 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11643 } 11644 11645 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11646 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11647 + userId + ":"); 11648 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11649 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11650 scheduleWritePackageRestrictionsLocked(userId); 11651 } 11652 } 11653 11654 @Override 11655 public void replacePreferredActivity(IntentFilter filter, int match, 11656 ComponentName[] set, ComponentName activity, int userId) { 11657 if (filter.countActions() != 1) { 11658 throw new IllegalArgumentException( 11659 "replacePreferredActivity expects filter to have only 1 action."); 11660 } 11661 if (filter.countDataAuthorities() != 0 11662 || filter.countDataPaths() != 0 11663 || filter.countDataSchemes() > 1 11664 || filter.countDataTypes() != 0) { 11665 throw new IllegalArgumentException( 11666 "replacePreferredActivity expects filter to have no data authorities, " + 11667 "paths, or types; and at most one scheme."); 11668 } 11669 11670 final int callingUid = Binder.getCallingUid(); 11671 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11672 synchronized (mPackages) { 11673 if (mContext.checkCallingOrSelfPermission( 11674 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11675 != PackageManager.PERMISSION_GRANTED) { 11676 if (getUidTargetSdkVersionLockedLPr(callingUid) 11677 < Build.VERSION_CODES.FROYO) { 11678 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11679 + Binder.getCallingUid()); 11680 return; 11681 } 11682 mContext.enforceCallingOrSelfPermission( 11683 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11684 } 11685 11686 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11687 if (pir != null) { 11688 // Get all of the existing entries that exactly match this filter. 11689 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11690 if (existing != null && existing.size() == 1) { 11691 PreferredActivity cur = existing.get(0); 11692 if (DEBUG_PREFERRED) { 11693 Slog.i(TAG, "Checking replace of preferred:"); 11694 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11695 if (!cur.mPref.mAlways) { 11696 Slog.i(TAG, " -- CUR; not mAlways!"); 11697 } else { 11698 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11699 Slog.i(TAG, " -- CUR: mSet=" 11700 + Arrays.toString(cur.mPref.mSetComponents)); 11701 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11702 Slog.i(TAG, " -- NEW: mMatch=" 11703 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11704 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11705 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11706 } 11707 } 11708 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11709 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11710 && cur.mPref.sameSet(set)) { 11711 // Setting the preferred activity to what it happens to be already 11712 if (DEBUG_PREFERRED) { 11713 Slog.i(TAG, "Replacing with same preferred activity " 11714 + cur.mPref.mShortComponent + " for user " 11715 + userId + ":"); 11716 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11717 } 11718 return; 11719 } 11720 } 11721 11722 if (existing != null) { 11723 if (DEBUG_PREFERRED) { 11724 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11725 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11726 } 11727 for (int i = 0; i < existing.size(); i++) { 11728 PreferredActivity pa = existing.get(i); 11729 if (DEBUG_PREFERRED) { 11730 Slog.i(TAG, "Removing existing preferred activity " 11731 + pa.mPref.mComponent + ":"); 11732 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11733 } 11734 pir.removeFilter(pa); 11735 } 11736 } 11737 } 11738 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11739 "Replacing preferred"); 11740 } 11741 } 11742 11743 @Override 11744 public void clearPackagePreferredActivities(String packageName) { 11745 final int uid = Binder.getCallingUid(); 11746 // writer 11747 synchronized (mPackages) { 11748 PackageParser.Package pkg = mPackages.get(packageName); 11749 if (pkg == null || pkg.applicationInfo.uid != uid) { 11750 if (mContext.checkCallingOrSelfPermission( 11751 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11752 != PackageManager.PERMISSION_GRANTED) { 11753 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11754 < Build.VERSION_CODES.FROYO) { 11755 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11756 + Binder.getCallingUid()); 11757 return; 11758 } 11759 mContext.enforceCallingOrSelfPermission( 11760 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11761 } 11762 } 11763 11764 int user = UserHandle.getCallingUserId(); 11765 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11766 scheduleWritePackageRestrictionsLocked(user); 11767 } 11768 } 11769 } 11770 11771 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11772 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11773 ArrayList<PreferredActivity> removed = null; 11774 boolean changed = false; 11775 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11776 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11777 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11778 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11779 continue; 11780 } 11781 Iterator<PreferredActivity> it = pir.filterIterator(); 11782 while (it.hasNext()) { 11783 PreferredActivity pa = it.next(); 11784 // Mark entry for removal only if it matches the package name 11785 // and the entry is of type "always". 11786 if (packageName == null || 11787 (pa.mPref.mComponent.getPackageName().equals(packageName) 11788 && pa.mPref.mAlways)) { 11789 if (removed == null) { 11790 removed = new ArrayList<PreferredActivity>(); 11791 } 11792 removed.add(pa); 11793 } 11794 } 11795 if (removed != null) { 11796 for (int j=0; j<removed.size(); j++) { 11797 PreferredActivity pa = removed.get(j); 11798 pir.removeFilter(pa); 11799 } 11800 changed = true; 11801 } 11802 } 11803 return changed; 11804 } 11805 11806 @Override 11807 public void resetPreferredActivities(int userId) { 11808 /* TODO: Actually use userId. Why is it being passed in? */ 11809 mContext.enforceCallingOrSelfPermission( 11810 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11811 // writer 11812 synchronized (mPackages) { 11813 int user = UserHandle.getCallingUserId(); 11814 clearPackagePreferredActivitiesLPw(null, user); 11815 mSettings.readDefaultPreferredAppsLPw(this, user); 11816 scheduleWritePackageRestrictionsLocked(user); 11817 } 11818 } 11819 11820 @Override 11821 public int getPreferredActivities(List<IntentFilter> outFilters, 11822 List<ComponentName> outActivities, String packageName) { 11823 11824 int num = 0; 11825 final int userId = UserHandle.getCallingUserId(); 11826 // reader 11827 synchronized (mPackages) { 11828 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11829 if (pir != null) { 11830 final Iterator<PreferredActivity> it = pir.filterIterator(); 11831 while (it.hasNext()) { 11832 final PreferredActivity pa = it.next(); 11833 if (packageName == null 11834 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11835 && pa.mPref.mAlways)) { 11836 if (outFilters != null) { 11837 outFilters.add(new IntentFilter(pa)); 11838 } 11839 if (outActivities != null) { 11840 outActivities.add(pa.mPref.mComponent); 11841 } 11842 } 11843 } 11844 } 11845 } 11846 11847 return num; 11848 } 11849 11850 @Override 11851 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11852 int userId) { 11853 int callingUid = Binder.getCallingUid(); 11854 if (callingUid != Process.SYSTEM_UID) { 11855 throw new SecurityException( 11856 "addPersistentPreferredActivity can only be run by the system"); 11857 } 11858 if (filter.countActions() == 0) { 11859 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11860 return; 11861 } 11862 synchronized (mPackages) { 11863 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11864 " :"); 11865 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11866 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11867 new PersistentPreferredActivity(filter, activity)); 11868 scheduleWritePackageRestrictionsLocked(userId); 11869 } 11870 } 11871 11872 @Override 11873 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11874 int callingUid = Binder.getCallingUid(); 11875 if (callingUid != Process.SYSTEM_UID) { 11876 throw new SecurityException( 11877 "clearPackagePersistentPreferredActivities can only be run by the system"); 11878 } 11879 ArrayList<PersistentPreferredActivity> removed = null; 11880 boolean changed = false; 11881 synchronized (mPackages) { 11882 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11883 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11884 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11885 .valueAt(i); 11886 if (userId != thisUserId) { 11887 continue; 11888 } 11889 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11890 while (it.hasNext()) { 11891 PersistentPreferredActivity ppa = it.next(); 11892 // Mark entry for removal only if it matches the package name. 11893 if (ppa.mComponent.getPackageName().equals(packageName)) { 11894 if (removed == null) { 11895 removed = new ArrayList<PersistentPreferredActivity>(); 11896 } 11897 removed.add(ppa); 11898 } 11899 } 11900 if (removed != null) { 11901 for (int j=0; j<removed.size(); j++) { 11902 PersistentPreferredActivity ppa = removed.get(j); 11903 ppir.removeFilter(ppa); 11904 } 11905 changed = true; 11906 } 11907 } 11908 11909 if (changed) { 11910 scheduleWritePackageRestrictionsLocked(userId); 11911 } 11912 } 11913 } 11914 11915 @Override 11916 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11917 int sourceUserId, int targetUserId, int flags) { 11918 mContext.enforceCallingOrSelfPermission( 11919 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11920 int callingUid = Binder.getCallingUid(); 11921 enforceOwnerRights(ownerPackage, callingUid); 11922 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11923 if (intentFilter.countActions() == 0) { 11924 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11925 return; 11926 } 11927 synchronized (mPackages) { 11928 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11929 ownerPackage, targetUserId, flags); 11930 CrossProfileIntentResolver resolver = 11931 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11932 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11933 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11934 if (existing != null) { 11935 int size = existing.size(); 11936 for (int i = 0; i < size; i++) { 11937 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11938 return; 11939 } 11940 } 11941 } 11942 resolver.addFilter(newFilter); 11943 scheduleWritePackageRestrictionsLocked(sourceUserId); 11944 } 11945 } 11946 11947 @Override 11948 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 11949 mContext.enforceCallingOrSelfPermission( 11950 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11951 int callingUid = Binder.getCallingUid(); 11952 enforceOwnerRights(ownerPackage, callingUid); 11953 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11954 synchronized (mPackages) { 11955 CrossProfileIntentResolver resolver = 11956 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11957 ArraySet<CrossProfileIntentFilter> set = 11958 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11959 for (CrossProfileIntentFilter filter : set) { 11960 if (filter.getOwnerPackage().equals(ownerPackage)) { 11961 resolver.removeFilter(filter); 11962 } 11963 } 11964 scheduleWritePackageRestrictionsLocked(sourceUserId); 11965 } 11966 } 11967 11968 // Enforcing that callingUid is owning pkg on userId 11969 private void enforceOwnerRights(String pkg, int callingUid) { 11970 // The system owns everything. 11971 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11972 return; 11973 } 11974 int callingUserId = UserHandle.getUserId(callingUid); 11975 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11976 if (pi == null) { 11977 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11978 + callingUserId); 11979 } 11980 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11981 throw new SecurityException("Calling uid " + callingUid 11982 + " does not own package " + pkg); 11983 } 11984 } 11985 11986 @Override 11987 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11988 Intent intent = new Intent(Intent.ACTION_MAIN); 11989 intent.addCategory(Intent.CATEGORY_HOME); 11990 11991 final int callingUserId = UserHandle.getCallingUserId(); 11992 List<ResolveInfo> list = queryIntentActivities(intent, null, 11993 PackageManager.GET_META_DATA, callingUserId); 11994 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11995 true, false, false, callingUserId); 11996 11997 allHomeCandidates.clear(); 11998 if (list != null) { 11999 for (ResolveInfo ri : list) { 12000 allHomeCandidates.add(ri); 12001 } 12002 } 12003 return (preferred == null || preferred.activityInfo == null) 12004 ? null 12005 : new ComponentName(preferred.activityInfo.packageName, 12006 preferred.activityInfo.name); 12007 } 12008 12009 @Override 12010 public void setApplicationEnabledSetting(String appPackageName, 12011 int newState, int flags, int userId, String callingPackage) { 12012 if (!sUserManager.exists(userId)) return; 12013 if (callingPackage == null) { 12014 callingPackage = Integer.toString(Binder.getCallingUid()); 12015 } 12016 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12017 } 12018 12019 @Override 12020 public void setComponentEnabledSetting(ComponentName componentName, 12021 int newState, int flags, int userId) { 12022 if (!sUserManager.exists(userId)) return; 12023 setEnabledSetting(componentName.getPackageName(), 12024 componentName.getClassName(), newState, flags, userId, null); 12025 } 12026 12027 private void setEnabledSetting(final String packageName, String className, int newState, 12028 final int flags, int userId, String callingPackage) { 12029 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12030 || newState == COMPONENT_ENABLED_STATE_ENABLED 12031 || newState == COMPONENT_ENABLED_STATE_DISABLED 12032 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12033 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12034 throw new IllegalArgumentException("Invalid new component state: " 12035 + newState); 12036 } 12037 PackageSetting pkgSetting; 12038 final int uid = Binder.getCallingUid(); 12039 final int permission = mContext.checkCallingOrSelfPermission( 12040 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12041 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12042 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12043 boolean sendNow = false; 12044 boolean isApp = (className == null); 12045 String componentName = isApp ? packageName : className; 12046 int packageUid = -1; 12047 ArrayList<String> components; 12048 12049 // writer 12050 synchronized (mPackages) { 12051 pkgSetting = mSettings.mPackages.get(packageName); 12052 if (pkgSetting == null) { 12053 if (className == null) { 12054 throw new IllegalArgumentException( 12055 "Unknown package: " + packageName); 12056 } 12057 throw new IllegalArgumentException( 12058 "Unknown component: " + packageName 12059 + "/" + className); 12060 } 12061 // Allow root and verify that userId is not being specified by a different user 12062 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12063 throw new SecurityException( 12064 "Permission Denial: attempt to change component state from pid=" 12065 + Binder.getCallingPid() 12066 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12067 } 12068 if (className == null) { 12069 // We're dealing with an application/package level state change 12070 if (pkgSetting.getEnabled(userId) == newState) { 12071 // Nothing to do 12072 return; 12073 } 12074 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12075 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12076 // Don't care about who enables an app. 12077 callingPackage = null; 12078 } 12079 pkgSetting.setEnabled(newState, userId, callingPackage); 12080 // pkgSetting.pkg.mSetEnabled = newState; 12081 } else { 12082 // We're dealing with a component level state change 12083 // First, verify that this is a valid class name. 12084 PackageParser.Package pkg = pkgSetting.pkg; 12085 if (pkg == null || !pkg.hasComponentClassName(className)) { 12086 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12087 throw new IllegalArgumentException("Component class " + className 12088 + " does not exist in " + packageName); 12089 } else { 12090 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12091 + className + " does not exist in " + packageName); 12092 } 12093 } 12094 switch (newState) { 12095 case COMPONENT_ENABLED_STATE_ENABLED: 12096 if (!pkgSetting.enableComponentLPw(className, userId)) { 12097 return; 12098 } 12099 break; 12100 case COMPONENT_ENABLED_STATE_DISABLED: 12101 if (!pkgSetting.disableComponentLPw(className, userId)) { 12102 return; 12103 } 12104 break; 12105 case COMPONENT_ENABLED_STATE_DEFAULT: 12106 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12107 return; 12108 } 12109 break; 12110 default: 12111 Slog.e(TAG, "Invalid new component state: " + newState); 12112 return; 12113 } 12114 } 12115 scheduleWritePackageRestrictionsLocked(userId); 12116 components = mPendingBroadcasts.get(userId, packageName); 12117 final boolean newPackage = components == null; 12118 if (newPackage) { 12119 components = new ArrayList<String>(); 12120 } 12121 if (!components.contains(componentName)) { 12122 components.add(componentName); 12123 } 12124 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12125 sendNow = true; 12126 // Purge entry from pending broadcast list if another one exists already 12127 // since we are sending one right away. 12128 mPendingBroadcasts.remove(userId, packageName); 12129 } else { 12130 if (newPackage) { 12131 mPendingBroadcasts.put(userId, packageName, components); 12132 } 12133 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12134 // Schedule a message 12135 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12136 } 12137 } 12138 } 12139 12140 long callingId = Binder.clearCallingIdentity(); 12141 try { 12142 if (sendNow) { 12143 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12144 sendPackageChangedBroadcast(packageName, 12145 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12146 } 12147 } finally { 12148 Binder.restoreCallingIdentity(callingId); 12149 } 12150 } 12151 12152 private void sendPackageChangedBroadcast(String packageName, 12153 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12154 if (DEBUG_INSTALL) 12155 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12156 + componentNames); 12157 Bundle extras = new Bundle(4); 12158 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12159 String nameList[] = new String[componentNames.size()]; 12160 componentNames.toArray(nameList); 12161 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12162 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12163 extras.putInt(Intent.EXTRA_UID, packageUid); 12164 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12165 new int[] {UserHandle.getUserId(packageUid)}); 12166 } 12167 12168 @Override 12169 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12170 if (!sUserManager.exists(userId)) return; 12171 final int uid = Binder.getCallingUid(); 12172 final int permission = mContext.checkCallingOrSelfPermission( 12173 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12174 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12175 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12176 // writer 12177 synchronized (mPackages) { 12178 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12179 uid, userId)) { 12180 scheduleWritePackageRestrictionsLocked(userId); 12181 } 12182 } 12183 } 12184 12185 @Override 12186 public String getInstallerPackageName(String packageName) { 12187 // reader 12188 synchronized (mPackages) { 12189 return mSettings.getInstallerPackageNameLPr(packageName); 12190 } 12191 } 12192 12193 @Override 12194 public int getApplicationEnabledSetting(String packageName, int userId) { 12195 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12196 int uid = Binder.getCallingUid(); 12197 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12198 // reader 12199 synchronized (mPackages) { 12200 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12201 } 12202 } 12203 12204 @Override 12205 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12206 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12207 int uid = Binder.getCallingUid(); 12208 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12209 // reader 12210 synchronized (mPackages) { 12211 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12212 } 12213 } 12214 12215 @Override 12216 public void enterSafeMode() { 12217 enforceSystemOrRoot("Only the system can request entering safe mode"); 12218 12219 if (!mSystemReady) { 12220 mSafeMode = true; 12221 } 12222 } 12223 12224 @Override 12225 public void systemReady() { 12226 mSystemReady = true; 12227 12228 // Read the compatibilty setting when the system is ready. 12229 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12230 mContext.getContentResolver(), 12231 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12232 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12233 if (DEBUG_SETTINGS) { 12234 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12235 } 12236 12237 synchronized (mPackages) { 12238 // Verify that all of the preferred activity components actually 12239 // exist. It is possible for applications to be updated and at 12240 // that point remove a previously declared activity component that 12241 // had been set as a preferred activity. We try to clean this up 12242 // the next time we encounter that preferred activity, but it is 12243 // possible for the user flow to never be able to return to that 12244 // situation so here we do a sanity check to make sure we haven't 12245 // left any junk around. 12246 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12247 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12248 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12249 removed.clear(); 12250 for (PreferredActivity pa : pir.filterSet()) { 12251 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12252 removed.add(pa); 12253 } 12254 } 12255 if (removed.size() > 0) { 12256 for (int r=0; r<removed.size(); r++) { 12257 PreferredActivity pa = removed.get(r); 12258 Slog.w(TAG, "Removing dangling preferred activity: " 12259 + pa.mPref.mComponent); 12260 pir.removeFilter(pa); 12261 } 12262 mSettings.writePackageRestrictionsLPr( 12263 mSettings.mPreferredActivities.keyAt(i)); 12264 } 12265 } 12266 } 12267 sUserManager.systemReady(); 12268 12269 // Kick off any messages waiting for system ready 12270 if (mPostSystemReadyMessages != null) { 12271 for (Message msg : mPostSystemReadyMessages) { 12272 msg.sendToTarget(); 12273 } 12274 mPostSystemReadyMessages = null; 12275 } 12276 } 12277 12278 @Override 12279 public boolean isSafeMode() { 12280 return mSafeMode; 12281 } 12282 12283 @Override 12284 public boolean hasSystemUidErrors() { 12285 return mHasSystemUidErrors; 12286 } 12287 12288 static String arrayToString(int[] array) { 12289 StringBuffer buf = new StringBuffer(128); 12290 buf.append('['); 12291 if (array != null) { 12292 for (int i=0; i<array.length; i++) { 12293 if (i > 0) buf.append(", "); 12294 buf.append(array[i]); 12295 } 12296 } 12297 buf.append(']'); 12298 return buf.toString(); 12299 } 12300 12301 static class DumpState { 12302 public static final int DUMP_LIBS = 1 << 0; 12303 public static final int DUMP_FEATURES = 1 << 1; 12304 public static final int DUMP_RESOLVERS = 1 << 2; 12305 public static final int DUMP_PERMISSIONS = 1 << 3; 12306 public static final int DUMP_PACKAGES = 1 << 4; 12307 public static final int DUMP_SHARED_USERS = 1 << 5; 12308 public static final int DUMP_MESSAGES = 1 << 6; 12309 public static final int DUMP_PROVIDERS = 1 << 7; 12310 public static final int DUMP_VERIFIERS = 1 << 8; 12311 public static final int DUMP_PREFERRED = 1 << 9; 12312 public static final int DUMP_PREFERRED_XML = 1 << 10; 12313 public static final int DUMP_KEYSETS = 1 << 11; 12314 public static final int DUMP_VERSION = 1 << 12; 12315 public static final int DUMP_INSTALLS = 1 << 13; 12316 12317 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12318 12319 private int mTypes; 12320 12321 private int mOptions; 12322 12323 private boolean mTitlePrinted; 12324 12325 private SharedUserSetting mSharedUser; 12326 12327 public boolean isDumping(int type) { 12328 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12329 return true; 12330 } 12331 12332 return (mTypes & type) != 0; 12333 } 12334 12335 public void setDump(int type) { 12336 mTypes |= type; 12337 } 12338 12339 public boolean isOptionEnabled(int option) { 12340 return (mOptions & option) != 0; 12341 } 12342 12343 public void setOptionEnabled(int option) { 12344 mOptions |= option; 12345 } 12346 12347 public boolean onTitlePrinted() { 12348 final boolean printed = mTitlePrinted; 12349 mTitlePrinted = true; 12350 return printed; 12351 } 12352 12353 public boolean getTitlePrinted() { 12354 return mTitlePrinted; 12355 } 12356 12357 public void setTitlePrinted(boolean enabled) { 12358 mTitlePrinted = enabled; 12359 } 12360 12361 public SharedUserSetting getSharedUser() { 12362 return mSharedUser; 12363 } 12364 12365 public void setSharedUser(SharedUserSetting user) { 12366 mSharedUser = user; 12367 } 12368 } 12369 12370 @Override 12371 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12372 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12373 != PackageManager.PERMISSION_GRANTED) { 12374 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12375 + Binder.getCallingPid() 12376 + ", uid=" + Binder.getCallingUid() 12377 + " without permission " 12378 + android.Manifest.permission.DUMP); 12379 return; 12380 } 12381 12382 DumpState dumpState = new DumpState(); 12383 boolean fullPreferred = false; 12384 boolean checkin = false; 12385 12386 String packageName = null; 12387 12388 int opti = 0; 12389 while (opti < args.length) { 12390 String opt = args[opti]; 12391 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12392 break; 12393 } 12394 opti++; 12395 12396 if ("-a".equals(opt)) { 12397 // Right now we only know how to print all. 12398 } else if ("-h".equals(opt)) { 12399 pw.println("Package manager dump options:"); 12400 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12401 pw.println(" --checkin: dump for a checkin"); 12402 pw.println(" -f: print details of intent filters"); 12403 pw.println(" -h: print this help"); 12404 pw.println(" cmd may be one of:"); 12405 pw.println(" l[ibraries]: list known shared libraries"); 12406 pw.println(" f[ibraries]: list device features"); 12407 pw.println(" k[eysets]: print known keysets"); 12408 pw.println(" r[esolvers]: dump intent resolvers"); 12409 pw.println(" perm[issions]: dump permissions"); 12410 pw.println(" pref[erred]: print preferred package settings"); 12411 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12412 pw.println(" prov[iders]: dump content providers"); 12413 pw.println(" p[ackages]: dump installed packages"); 12414 pw.println(" s[hared-users]: dump shared user IDs"); 12415 pw.println(" m[essages]: print collected runtime messages"); 12416 pw.println(" v[erifiers]: print package verifier info"); 12417 pw.println(" version: print database version info"); 12418 pw.println(" write: write current settings now"); 12419 pw.println(" <package.name>: info about given package"); 12420 pw.println(" installs: details about install sessions"); 12421 return; 12422 } else if ("--checkin".equals(opt)) { 12423 checkin = true; 12424 } else if ("-f".equals(opt)) { 12425 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12426 } else { 12427 pw.println("Unknown argument: " + opt + "; use -h for help"); 12428 } 12429 } 12430 12431 // Is the caller requesting to dump a particular piece of data? 12432 if (opti < args.length) { 12433 String cmd = args[opti]; 12434 opti++; 12435 // Is this a package name? 12436 if ("android".equals(cmd) || cmd.contains(".")) { 12437 packageName = cmd; 12438 // When dumping a single package, we always dump all of its 12439 // filter information since the amount of data will be reasonable. 12440 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12441 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12442 dumpState.setDump(DumpState.DUMP_LIBS); 12443 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12444 dumpState.setDump(DumpState.DUMP_FEATURES); 12445 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12446 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12447 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12448 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12449 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12450 dumpState.setDump(DumpState.DUMP_PREFERRED); 12451 } else if ("preferred-xml".equals(cmd)) { 12452 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12453 if (opti < args.length && "--full".equals(args[opti])) { 12454 fullPreferred = true; 12455 opti++; 12456 } 12457 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12458 dumpState.setDump(DumpState.DUMP_PACKAGES); 12459 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12460 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12461 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12462 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12463 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12464 dumpState.setDump(DumpState.DUMP_MESSAGES); 12465 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12466 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12467 } else if ("version".equals(cmd)) { 12468 dumpState.setDump(DumpState.DUMP_VERSION); 12469 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12470 dumpState.setDump(DumpState.DUMP_KEYSETS); 12471 } else if ("installs".equals(cmd)) { 12472 dumpState.setDump(DumpState.DUMP_INSTALLS); 12473 } else if ("write".equals(cmd)) { 12474 synchronized (mPackages) { 12475 mSettings.writeLPr(); 12476 pw.println("Settings written."); 12477 return; 12478 } 12479 } 12480 } 12481 12482 if (checkin) { 12483 pw.println("vers,1"); 12484 } 12485 12486 // reader 12487 synchronized (mPackages) { 12488 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12489 if (!checkin) { 12490 if (dumpState.onTitlePrinted()) 12491 pw.println(); 12492 pw.println("Database versions:"); 12493 pw.print(" SDK Version:"); 12494 pw.print(" internal="); 12495 pw.print(mSettings.mInternalSdkPlatform); 12496 pw.print(" external="); 12497 pw.println(mSettings.mExternalSdkPlatform); 12498 pw.print(" DB Version:"); 12499 pw.print(" internal="); 12500 pw.print(mSettings.mInternalDatabaseVersion); 12501 pw.print(" external="); 12502 pw.println(mSettings.mExternalDatabaseVersion); 12503 } 12504 } 12505 12506 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12507 if (!checkin) { 12508 if (dumpState.onTitlePrinted()) 12509 pw.println(); 12510 pw.println("Verifiers:"); 12511 pw.print(" Required: "); 12512 pw.print(mRequiredVerifierPackage); 12513 pw.print(" (uid="); 12514 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12515 pw.println(")"); 12516 } else if (mRequiredVerifierPackage != null) { 12517 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12518 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12519 } 12520 } 12521 12522 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12523 boolean printedHeader = false; 12524 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12525 while (it.hasNext()) { 12526 String name = it.next(); 12527 SharedLibraryEntry ent = mSharedLibraries.get(name); 12528 if (!checkin) { 12529 if (!printedHeader) { 12530 if (dumpState.onTitlePrinted()) 12531 pw.println(); 12532 pw.println("Libraries:"); 12533 printedHeader = true; 12534 } 12535 pw.print(" "); 12536 } else { 12537 pw.print("lib,"); 12538 } 12539 pw.print(name); 12540 if (!checkin) { 12541 pw.print(" -> "); 12542 } 12543 if (ent.path != null) { 12544 if (!checkin) { 12545 pw.print("(jar) "); 12546 pw.print(ent.path); 12547 } else { 12548 pw.print(",jar,"); 12549 pw.print(ent.path); 12550 } 12551 } else { 12552 if (!checkin) { 12553 pw.print("(apk) "); 12554 pw.print(ent.apk); 12555 } else { 12556 pw.print(",apk,"); 12557 pw.print(ent.apk); 12558 } 12559 } 12560 pw.println(); 12561 } 12562 } 12563 12564 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12565 if (dumpState.onTitlePrinted()) 12566 pw.println(); 12567 if (!checkin) { 12568 pw.println("Features:"); 12569 } 12570 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12571 while (it.hasNext()) { 12572 String name = it.next(); 12573 if (!checkin) { 12574 pw.print(" "); 12575 } else { 12576 pw.print("feat,"); 12577 } 12578 pw.println(name); 12579 } 12580 } 12581 12582 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12583 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12584 : "Activity Resolver Table:", " ", packageName, 12585 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12586 dumpState.setTitlePrinted(true); 12587 } 12588 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12589 : "Receiver Resolver Table:", " ", packageName, 12590 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12591 dumpState.setTitlePrinted(true); 12592 } 12593 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12594 : "Service Resolver Table:", " ", packageName, 12595 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12596 dumpState.setTitlePrinted(true); 12597 } 12598 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12599 : "Provider Resolver Table:", " ", packageName, 12600 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12601 dumpState.setTitlePrinted(true); 12602 } 12603 } 12604 12605 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12606 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12607 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12608 int user = mSettings.mPreferredActivities.keyAt(i); 12609 if (pir.dump(pw, 12610 dumpState.getTitlePrinted() 12611 ? "\nPreferred Activities User " + user + ":" 12612 : "Preferred Activities User " + user + ":", " ", 12613 packageName, true, false)) { 12614 dumpState.setTitlePrinted(true); 12615 } 12616 } 12617 } 12618 12619 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12620 pw.flush(); 12621 FileOutputStream fout = new FileOutputStream(fd); 12622 BufferedOutputStream str = new BufferedOutputStream(fout); 12623 XmlSerializer serializer = new FastXmlSerializer(); 12624 try { 12625 serializer.setOutput(str, "utf-8"); 12626 serializer.startDocument(null, true); 12627 serializer.setFeature( 12628 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12629 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12630 serializer.endDocument(); 12631 serializer.flush(); 12632 } catch (IllegalArgumentException e) { 12633 pw.println("Failed writing: " + e); 12634 } catch (IllegalStateException e) { 12635 pw.println("Failed writing: " + e); 12636 } catch (IOException e) { 12637 pw.println("Failed writing: " + e); 12638 } 12639 } 12640 12641 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12642 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12643 if (packageName == null) { 12644 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12645 if (iperm == 0) { 12646 if (dumpState.onTitlePrinted()) 12647 pw.println(); 12648 pw.println("AppOp Permissions:"); 12649 } 12650 pw.print(" AppOp Permission "); 12651 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12652 pw.println(":"); 12653 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12654 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12655 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12656 } 12657 } 12658 } 12659 } 12660 12661 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12662 boolean printedSomething = false; 12663 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12664 if (packageName != null && !packageName.equals(p.info.packageName)) { 12665 continue; 12666 } 12667 if (!printedSomething) { 12668 if (dumpState.onTitlePrinted()) 12669 pw.println(); 12670 pw.println("Registered ContentProviders:"); 12671 printedSomething = true; 12672 } 12673 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12674 pw.print(" "); pw.println(p.toString()); 12675 } 12676 printedSomething = false; 12677 for (Map.Entry<String, PackageParser.Provider> entry : 12678 mProvidersByAuthority.entrySet()) { 12679 PackageParser.Provider p = entry.getValue(); 12680 if (packageName != null && !packageName.equals(p.info.packageName)) { 12681 continue; 12682 } 12683 if (!printedSomething) { 12684 if (dumpState.onTitlePrinted()) 12685 pw.println(); 12686 pw.println("ContentProvider Authorities:"); 12687 printedSomething = true; 12688 } 12689 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12690 pw.print(" "); pw.println(p.toString()); 12691 if (p.info != null && p.info.applicationInfo != null) { 12692 final String appInfo = p.info.applicationInfo.toString(); 12693 pw.print(" applicationInfo="); pw.println(appInfo); 12694 } 12695 } 12696 } 12697 12698 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12699 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12700 } 12701 12702 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12703 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12704 } 12705 12706 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12707 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12708 } 12709 12710 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12711 // XXX should handle packageName != null by dumping only install data that 12712 // the given package is involved with. 12713 if (dumpState.onTitlePrinted()) pw.println(); 12714 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12715 } 12716 12717 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12718 if (dumpState.onTitlePrinted()) pw.println(); 12719 mSettings.dumpReadMessagesLPr(pw, dumpState); 12720 12721 pw.println(); 12722 pw.println("Package warning messages:"); 12723 BufferedReader in = null; 12724 String line = null; 12725 try { 12726 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12727 while ((line = in.readLine()) != null) { 12728 if (line.contains("ignored: updated version")) continue; 12729 pw.println(line); 12730 } 12731 } catch (IOException ignored) { 12732 } finally { 12733 IoUtils.closeQuietly(in); 12734 } 12735 } 12736 12737 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12738 BufferedReader in = null; 12739 String line = null; 12740 try { 12741 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12742 while ((line = in.readLine()) != null) { 12743 if (line.contains("ignored: updated version")) continue; 12744 pw.print("msg,"); 12745 pw.println(line); 12746 } 12747 } catch (IOException ignored) { 12748 } finally { 12749 IoUtils.closeQuietly(in); 12750 } 12751 } 12752 } 12753 } 12754 12755 // ------- apps on sdcard specific code ------- 12756 static final boolean DEBUG_SD_INSTALL = false; 12757 12758 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12759 12760 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12761 12762 private boolean mMediaMounted = false; 12763 12764 static String getEncryptKey() { 12765 try { 12766 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12767 SD_ENCRYPTION_KEYSTORE_NAME); 12768 if (sdEncKey == null) { 12769 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12770 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12771 if (sdEncKey == null) { 12772 Slog.e(TAG, "Failed to create encryption keys"); 12773 return null; 12774 } 12775 } 12776 return sdEncKey; 12777 } catch (NoSuchAlgorithmException nsae) { 12778 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12779 return null; 12780 } catch (IOException ioe) { 12781 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12782 return null; 12783 } 12784 } 12785 12786 /* 12787 * Update media status on PackageManager. 12788 */ 12789 @Override 12790 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12791 int callingUid = Binder.getCallingUid(); 12792 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12793 throw new SecurityException("Media status can only be updated by the system"); 12794 } 12795 // reader; this apparently protects mMediaMounted, but should probably 12796 // be a different lock in that case. 12797 synchronized (mPackages) { 12798 Log.i(TAG, "Updating external media status from " 12799 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12800 + (mediaStatus ? "mounted" : "unmounted")); 12801 if (DEBUG_SD_INSTALL) 12802 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12803 + ", mMediaMounted=" + mMediaMounted); 12804 if (mediaStatus == mMediaMounted) { 12805 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12806 : 0, -1); 12807 mHandler.sendMessage(msg); 12808 return; 12809 } 12810 mMediaMounted = mediaStatus; 12811 } 12812 // Queue up an async operation since the package installation may take a 12813 // little while. 12814 mHandler.post(new Runnable() { 12815 public void run() { 12816 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12817 } 12818 }); 12819 } 12820 12821 /** 12822 * Called by MountService when the initial ASECs to scan are available. 12823 * Should block until all the ASEC containers are finished being scanned. 12824 */ 12825 public void scanAvailableAsecs() { 12826 updateExternalMediaStatusInner(true, false, false); 12827 if (mShouldRestoreconData) { 12828 SELinuxMMAC.setRestoreconDone(); 12829 mShouldRestoreconData = false; 12830 } 12831 } 12832 12833 /* 12834 * Collect information of applications on external media, map them against 12835 * existing containers and update information based on current mount status. 12836 * Please note that we always have to report status if reportStatus has been 12837 * set to true especially when unloading packages. 12838 */ 12839 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12840 boolean externalStorage) { 12841 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12842 int[] uidArr = EmptyArray.INT; 12843 12844 final String[] list = PackageHelper.getSecureContainerList(); 12845 if (ArrayUtils.isEmpty(list)) { 12846 Log.i(TAG, "No secure containers found"); 12847 } else { 12848 // Process list of secure containers and categorize them 12849 // as active or stale based on their package internal state. 12850 12851 // reader 12852 synchronized (mPackages) { 12853 for (String cid : list) { 12854 // Leave stages untouched for now; installer service owns them 12855 if (PackageInstallerService.isStageName(cid)) continue; 12856 12857 if (DEBUG_SD_INSTALL) 12858 Log.i(TAG, "Processing container " + cid); 12859 String pkgName = getAsecPackageName(cid); 12860 if (pkgName == null) { 12861 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12862 continue; 12863 } 12864 if (DEBUG_SD_INSTALL) 12865 Log.i(TAG, "Looking for pkg : " + pkgName); 12866 12867 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12868 if (ps == null) { 12869 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12870 continue; 12871 } 12872 12873 /* 12874 * Skip packages that are not external if we're unmounting 12875 * external storage. 12876 */ 12877 if (externalStorage && !isMounted && !isExternal(ps)) { 12878 continue; 12879 } 12880 12881 final AsecInstallArgs args = new AsecInstallArgs(cid, 12882 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12883 // The package status is changed only if the code path 12884 // matches between settings and the container id. 12885 if (ps.codePathString != null 12886 && ps.codePathString.startsWith(args.getCodePath())) { 12887 if (DEBUG_SD_INSTALL) { 12888 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12889 + " at code path: " + ps.codePathString); 12890 } 12891 12892 // We do have a valid package installed on sdcard 12893 processCids.put(args, ps.codePathString); 12894 final int uid = ps.appId; 12895 if (uid != -1) { 12896 uidArr = ArrayUtils.appendInt(uidArr, uid); 12897 } 12898 } else { 12899 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12900 + ps.codePathString); 12901 } 12902 } 12903 } 12904 12905 Arrays.sort(uidArr); 12906 } 12907 12908 // Process packages with valid entries. 12909 if (isMounted) { 12910 if (DEBUG_SD_INSTALL) 12911 Log.i(TAG, "Loading packages"); 12912 loadMediaPackages(processCids, uidArr); 12913 startCleaningPackages(); 12914 mInstallerService.onSecureContainersAvailable(); 12915 } else { 12916 if (DEBUG_SD_INSTALL) 12917 Log.i(TAG, "Unloading packages"); 12918 unloadMediaPackages(processCids, uidArr, reportStatus); 12919 } 12920 } 12921 12922 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12923 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12924 int size = pkgList.size(); 12925 if (size > 0) { 12926 // Send broadcasts here 12927 Bundle extras = new Bundle(); 12928 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12929 .toArray(new String[size])); 12930 if (uidArr != null) { 12931 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12932 } 12933 if (replacing) { 12934 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12935 } 12936 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12937 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12938 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12939 } 12940 } 12941 12942 /* 12943 * Look at potentially valid container ids from processCids If package 12944 * information doesn't match the one on record or package scanning fails, 12945 * the cid is added to list of removeCids. We currently don't delete stale 12946 * containers. 12947 */ 12948 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12949 ArrayList<String> pkgList = new ArrayList<String>(); 12950 Set<AsecInstallArgs> keys = processCids.keySet(); 12951 12952 for (AsecInstallArgs args : keys) { 12953 String codePath = processCids.get(args); 12954 if (DEBUG_SD_INSTALL) 12955 Log.i(TAG, "Loading container : " + args.cid); 12956 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12957 try { 12958 // Make sure there are no container errors first. 12959 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12960 Slog.e(TAG, "Failed to mount cid : " + args.cid 12961 + " when installing from sdcard"); 12962 continue; 12963 } 12964 // Check code path here. 12965 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12966 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12967 + " does not match one in settings " + codePath); 12968 continue; 12969 } 12970 // Parse package 12971 int parseFlags = mDefParseFlags; 12972 if (args.isExternal()) { 12973 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12974 } 12975 if (args.isFwdLocked()) { 12976 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12977 } 12978 12979 synchronized (mInstallLock) { 12980 PackageParser.Package pkg = null; 12981 try { 12982 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12983 } catch (PackageManagerException e) { 12984 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12985 } 12986 // Scan the package 12987 if (pkg != null) { 12988 /* 12989 * TODO why is the lock being held? doPostInstall is 12990 * called in other places without the lock. This needs 12991 * to be straightened out. 12992 */ 12993 // writer 12994 synchronized (mPackages) { 12995 retCode = PackageManager.INSTALL_SUCCEEDED; 12996 pkgList.add(pkg.packageName); 12997 // Post process args 12998 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12999 pkg.applicationInfo.uid); 13000 } 13001 } else { 13002 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13003 } 13004 } 13005 13006 } finally { 13007 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13008 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13009 } 13010 } 13011 } 13012 // writer 13013 synchronized (mPackages) { 13014 // If the platform SDK has changed since the last time we booted, 13015 // we need to re-grant app permission to catch any new ones that 13016 // appear. This is really a hack, and means that apps can in some 13017 // cases get permissions that the user didn't initially explicitly 13018 // allow... it would be nice to have some better way to handle 13019 // this situation. 13020 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13021 if (regrantPermissions) 13022 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13023 + mSdkVersion + "; regranting permissions for external storage"); 13024 mSettings.mExternalSdkPlatform = mSdkVersion; 13025 13026 // Make sure group IDs have been assigned, and any permission 13027 // changes in other apps are accounted for 13028 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13029 | (regrantPermissions 13030 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13031 : 0)); 13032 13033 mSettings.updateExternalDatabaseVersion(); 13034 13035 // can downgrade to reader 13036 // Persist settings 13037 mSettings.writeLPr(); 13038 } 13039 // Send a broadcast to let everyone know we are done processing 13040 if (pkgList.size() > 0) { 13041 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13042 } 13043 } 13044 13045 /* 13046 * Utility method to unload a list of specified containers 13047 */ 13048 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13049 // Just unmount all valid containers. 13050 for (AsecInstallArgs arg : cidArgs) { 13051 synchronized (mInstallLock) { 13052 arg.doPostDeleteLI(false); 13053 } 13054 } 13055 } 13056 13057 /* 13058 * Unload packages mounted on external media. This involves deleting package 13059 * data from internal structures, sending broadcasts about diabled packages, 13060 * gc'ing to free up references, unmounting all secure containers 13061 * corresponding to packages on external media, and posting a 13062 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13063 * that we always have to post this message if status has been requested no 13064 * matter what. 13065 */ 13066 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13067 final boolean reportStatus) { 13068 if (DEBUG_SD_INSTALL) 13069 Log.i(TAG, "unloading media packages"); 13070 ArrayList<String> pkgList = new ArrayList<String>(); 13071 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13072 final Set<AsecInstallArgs> keys = processCids.keySet(); 13073 for (AsecInstallArgs args : keys) { 13074 String pkgName = args.getPackageName(); 13075 if (DEBUG_SD_INSTALL) 13076 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13077 // Delete package internally 13078 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13079 synchronized (mInstallLock) { 13080 boolean res = deletePackageLI(pkgName, null, false, null, null, 13081 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13082 if (res) { 13083 pkgList.add(pkgName); 13084 } else { 13085 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13086 failedList.add(args); 13087 } 13088 } 13089 } 13090 13091 // reader 13092 synchronized (mPackages) { 13093 // We didn't update the settings after removing each package; 13094 // write them now for all packages. 13095 mSettings.writeLPr(); 13096 } 13097 13098 // We have to absolutely send UPDATED_MEDIA_STATUS only 13099 // after confirming that all the receivers processed the ordered 13100 // broadcast when packages get disabled, force a gc to clean things up. 13101 // and unload all the containers. 13102 if (pkgList.size() > 0) { 13103 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13104 new IIntentReceiver.Stub() { 13105 public void performReceive(Intent intent, int resultCode, String data, 13106 Bundle extras, boolean ordered, boolean sticky, 13107 int sendingUser) throws RemoteException { 13108 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13109 reportStatus ? 1 : 0, 1, keys); 13110 mHandler.sendMessage(msg); 13111 } 13112 }); 13113 } else { 13114 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13115 keys); 13116 mHandler.sendMessage(msg); 13117 } 13118 } 13119 13120 /** Binder call */ 13121 @Override 13122 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13123 final int flags) { 13124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13125 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13126 int returnCode = PackageManager.MOVE_SUCCEEDED; 13127 int currInstallFlags = 0; 13128 int newInstallFlags = 0; 13129 13130 File codeFile = null; 13131 String installerPackageName = null; 13132 String packageAbiOverride = null; 13133 13134 // reader 13135 synchronized (mPackages) { 13136 final PackageParser.Package pkg = mPackages.get(packageName); 13137 final PackageSetting ps = mSettings.mPackages.get(packageName); 13138 if (pkg == null || ps == null) { 13139 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13140 } else { 13141 // Disable moving fwd locked apps and system packages 13142 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13143 Slog.w(TAG, "Cannot move system application"); 13144 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13145 } else if (pkg.mOperationPending) { 13146 Slog.w(TAG, "Attempt to move package which has pending operations"); 13147 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13148 } else { 13149 // Find install location first 13150 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13151 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13152 Slog.w(TAG, "Ambigous flags specified for move location."); 13153 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13154 } else { 13155 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13156 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13157 currInstallFlags = isExternal(pkg) 13158 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13159 13160 if (newInstallFlags == currInstallFlags) { 13161 Slog.w(TAG, "No move required. Trying to move to same location"); 13162 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13163 } else { 13164 if (pkg.isForwardLocked()) { 13165 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13166 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13167 } 13168 } 13169 } 13170 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13171 pkg.mOperationPending = true; 13172 } 13173 } 13174 13175 codeFile = new File(pkg.codePath); 13176 installerPackageName = ps.installerPackageName; 13177 packageAbiOverride = ps.cpuAbiOverrideString; 13178 } 13179 } 13180 13181 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13182 try { 13183 observer.packageMoved(packageName, returnCode); 13184 } catch (RemoteException ignored) { 13185 } 13186 return; 13187 } 13188 13189 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13190 @Override 13191 public void onUserActionRequired(Intent intent) throws RemoteException { 13192 throw new IllegalStateException(); 13193 } 13194 13195 @Override 13196 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13197 Bundle extras) throws RemoteException { 13198 Slog.d(TAG, "Install result for move: " 13199 + PackageManager.installStatusToString(returnCode, msg)); 13200 13201 // We usually have a new package now after the install, but if 13202 // we failed we need to clear the pending flag on the original 13203 // package object. 13204 synchronized (mPackages) { 13205 final PackageParser.Package pkg = mPackages.get(packageName); 13206 if (pkg != null) { 13207 pkg.mOperationPending = false; 13208 } 13209 } 13210 13211 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13212 switch (status) { 13213 case PackageInstaller.STATUS_SUCCESS: 13214 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13215 break; 13216 case PackageInstaller.STATUS_FAILURE_STORAGE: 13217 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13218 break; 13219 default: 13220 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13221 break; 13222 } 13223 } 13224 }; 13225 13226 // Treat a move like reinstalling an existing app, which ensures that we 13227 // process everythign uniformly, like unpacking native libraries. 13228 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13229 13230 final Message msg = mHandler.obtainMessage(INIT_COPY); 13231 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13232 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13233 installerPackageName, null, user, packageAbiOverride); 13234 mHandler.sendMessage(msg); 13235 } 13236 13237 @Override 13238 public boolean setInstallLocation(int loc) { 13239 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13240 null); 13241 if (getInstallLocation() == loc) { 13242 return true; 13243 } 13244 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13245 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13246 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13247 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13248 return true; 13249 } 13250 return false; 13251 } 13252 13253 @Override 13254 public int getInstallLocation() { 13255 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13256 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13257 PackageHelper.APP_INSTALL_AUTO); 13258 } 13259 13260 /** Called by UserManagerService */ 13261 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13262 mDirtyUsers.remove(userHandle); 13263 mSettings.removeUserLPw(userHandle); 13264 mPendingBroadcasts.remove(userHandle); 13265 if (mInstaller != null) { 13266 // Technically, we shouldn't be doing this with the package lock 13267 // held. However, this is very rare, and there is already so much 13268 // other disk I/O going on, that we'll let it slide for now. 13269 mInstaller.removeUserDataDirs(userHandle); 13270 } 13271 mUserNeedsBadging.delete(userHandle); 13272 removeUnusedPackagesLILPw(userManager, userHandle); 13273 } 13274 13275 /** 13276 * We're removing userHandle and would like to remove any downloaded packages 13277 * that are no longer in use by any other user. 13278 * @param userHandle the user being removed 13279 */ 13280 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13281 final boolean DEBUG_CLEAN_APKS = false; 13282 int [] users = userManager.getUserIdsLPr(); 13283 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13284 while (psit.hasNext()) { 13285 PackageSetting ps = psit.next(); 13286 if (ps.pkg == null) { 13287 continue; 13288 } 13289 final String packageName = ps.pkg.packageName; 13290 // Skip over if system app 13291 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13292 continue; 13293 } 13294 if (DEBUG_CLEAN_APKS) { 13295 Slog.i(TAG, "Checking package " + packageName); 13296 } 13297 boolean keep = false; 13298 for (int i = 0; i < users.length; i++) { 13299 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13300 keep = true; 13301 if (DEBUG_CLEAN_APKS) { 13302 Slog.i(TAG, " Keeping package " + packageName + " for user " 13303 + users[i]); 13304 } 13305 break; 13306 } 13307 } 13308 if (!keep) { 13309 if (DEBUG_CLEAN_APKS) { 13310 Slog.i(TAG, " Removing package " + packageName); 13311 } 13312 mHandler.post(new Runnable() { 13313 public void run() { 13314 deletePackageX(packageName, userHandle, 0); 13315 } //end run 13316 }); 13317 } 13318 } 13319 } 13320 13321 /** Called by UserManagerService */ 13322 void createNewUserLILPw(int userHandle, File path) { 13323 if (mInstaller != null) { 13324 mInstaller.createUserConfig(userHandle); 13325 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13326 } 13327 } 13328 13329 @Override 13330 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13331 mContext.enforceCallingOrSelfPermission( 13332 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13333 "Only package verification agents can read the verifier device identity"); 13334 13335 synchronized (mPackages) { 13336 return mSettings.getVerifierDeviceIdentityLPw(); 13337 } 13338 } 13339 13340 @Override 13341 public void setPermissionEnforced(String permission, boolean enforced) { 13342 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13343 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13344 synchronized (mPackages) { 13345 if (mSettings.mReadExternalStorageEnforced == null 13346 || mSettings.mReadExternalStorageEnforced != enforced) { 13347 mSettings.mReadExternalStorageEnforced = enforced; 13348 mSettings.writeLPr(); 13349 } 13350 } 13351 // kill any non-foreground processes so we restart them and 13352 // grant/revoke the GID. 13353 final IActivityManager am = ActivityManagerNative.getDefault(); 13354 if (am != null) { 13355 final long token = Binder.clearCallingIdentity(); 13356 try { 13357 am.killProcessesBelowForeground("setPermissionEnforcement"); 13358 } catch (RemoteException e) { 13359 } finally { 13360 Binder.restoreCallingIdentity(token); 13361 } 13362 } 13363 } else { 13364 throw new IllegalArgumentException("No selective enforcement for " + permission); 13365 } 13366 } 13367 13368 @Override 13369 @Deprecated 13370 public boolean isPermissionEnforced(String permission) { 13371 return true; 13372 } 13373 13374 @Override 13375 public boolean isStorageLow() { 13376 final long token = Binder.clearCallingIdentity(); 13377 try { 13378 final DeviceStorageMonitorInternal 13379 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13380 if (dsm != null) { 13381 return dsm.isMemoryLow(); 13382 } else { 13383 return false; 13384 } 13385 } finally { 13386 Binder.restoreCallingIdentity(token); 13387 } 13388 } 13389 13390 @Override 13391 public IPackageInstaller getPackageInstaller() { 13392 return mInstallerService; 13393 } 13394 13395 private boolean userNeedsBadging(int userId) { 13396 int index = mUserNeedsBadging.indexOfKey(userId); 13397 if (index < 0) { 13398 final UserInfo userInfo; 13399 final long token = Binder.clearCallingIdentity(); 13400 try { 13401 userInfo = sUserManager.getUserInfo(userId); 13402 } finally { 13403 Binder.restoreCallingIdentity(token); 13404 } 13405 final boolean b; 13406 if (userInfo != null && userInfo.isManagedProfile()) { 13407 b = true; 13408 } else { 13409 b = false; 13410 } 13411 mUserNeedsBadging.put(userId, b); 13412 return b; 13413 } 13414 return mUserNeedsBadging.valueAt(index); 13415 } 13416 13417 @Override 13418 public KeySet getKeySetByAlias(String packageName, String alias) { 13419 if (packageName == null || alias == null) { 13420 return null; 13421 } 13422 synchronized(mPackages) { 13423 final PackageParser.Package pkg = mPackages.get(packageName); 13424 if (pkg == null) { 13425 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13426 throw new IllegalArgumentException("Unknown package: " + packageName); 13427 } 13428 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13429 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13430 } 13431 } 13432 13433 @Override 13434 public KeySet getSigningKeySet(String packageName) { 13435 if (packageName == null) { 13436 return null; 13437 } 13438 synchronized(mPackages) { 13439 final PackageParser.Package pkg = mPackages.get(packageName); 13440 if (pkg == null) { 13441 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13442 throw new IllegalArgumentException("Unknown package: " + packageName); 13443 } 13444 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13445 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13446 throw new SecurityException("May not access signing KeySet of other apps."); 13447 } 13448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13449 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13450 } 13451 } 13452 13453 @Override 13454 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13455 if (packageName == null || ks == null) { 13456 return false; 13457 } 13458 synchronized(mPackages) { 13459 final PackageParser.Package pkg = mPackages.get(packageName); 13460 if (pkg == null) { 13461 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13462 throw new IllegalArgumentException("Unknown package: " + packageName); 13463 } 13464 IBinder ksh = ks.getToken(); 13465 if (ksh instanceof KeySetHandle) { 13466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13467 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13468 } 13469 return false; 13470 } 13471 } 13472 13473 @Override 13474 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13475 if (packageName == null || ks == null) { 13476 return false; 13477 } 13478 synchronized(mPackages) { 13479 final PackageParser.Package pkg = mPackages.get(packageName); 13480 if (pkg == null) { 13481 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13482 throw new IllegalArgumentException("Unknown package: " + packageName); 13483 } 13484 IBinder ksh = ks.getToken(); 13485 if (ksh instanceof KeySetHandle) { 13486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13487 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13488 } 13489 return false; 13490 } 13491 } 13492 13493 public void getUsageStatsIfNoPackageUsageInfo() { 13494 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13495 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13496 if (usm == null) { 13497 throw new IllegalStateException("UsageStatsManager must be initialized"); 13498 } 13499 long now = System.currentTimeMillis(); 13500 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13501 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13502 String packageName = entry.getKey(); 13503 PackageParser.Package pkg = mPackages.get(packageName); 13504 if (pkg == null) { 13505 continue; 13506 } 13507 UsageStats usage = entry.getValue(); 13508 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13509 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13510 } 13511 } 13512 } 13513 13514 /** 13515 * Check and throw if the given before/after packages would be considered a 13516 * downgrade. 13517 */ 13518 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13519 throws PackageManagerException { 13520 if (after.versionCode < before.mVersionCode) { 13521 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13522 "Update version code " + after.versionCode + " is older than current " 13523 + before.mVersionCode); 13524 } else if (after.versionCode == before.mVersionCode) { 13525 if (after.baseRevisionCode < before.baseRevisionCode) { 13526 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13527 "Update base revision code " + after.baseRevisionCode 13528 + " is older than current " + before.baseRevisionCode); 13529 } 13530 13531 if (!ArrayUtils.isEmpty(after.splitNames)) { 13532 for (int i = 0; i < after.splitNames.length; i++) { 13533 final String splitName = after.splitNames[i]; 13534 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13535 if (j != -1) { 13536 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13537 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13538 "Update split " + splitName + " revision code " 13539 + after.splitRevisionCodes[i] + " is older than current " 13540 + before.splitRevisionCodes[j]); 13541 } 13542 } 13543 } 13544 } 13545 } 13546 } 13547} 13548