PackageManagerService.java revision 7119be2531c1763749c2b5ed9d427ed506fe9aff
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 static final boolean RUNTIME_PERMISSIONS_ENABLED = 252 SystemProperties.getInt("ro.runtime.permissions.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 static final int SCAN_REQUIRE_KNOWN = 1<<12; 279 280 static final int REMOVE_CHATTY = 1<<16; 281 282 /** 283 * Timeout (in milliseconds) after which the watchdog should declare that 284 * our handler thread is wedged. The usual default for such things is one 285 * minute but we sometimes do very lengthy I/O operations on this thread, 286 * such as installing multi-gigabyte applications, so ours needs to be longer. 287 */ 288 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 289 290 /** 291 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 292 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 293 * settings entry if available, otherwise we use the hardcoded default. If it's been 294 * more than this long since the last fstrim, we force one during the boot sequence. 295 * 296 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 297 * one gets run at the next available charging+idle time. This final mandatory 298 * no-fstrim check kicks in only of the other scheduling criteria is never met. 299 */ 300 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 301 302 /** 303 * Whether verification is enabled by default. 304 */ 305 private static final boolean DEFAULT_VERIFY_ENABLE = true; 306 307 /** 308 * The default maximum time to wait for the verification agent to return in 309 * milliseconds. 310 */ 311 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 312 313 /** 314 * The default response for package verification timeout. 315 * 316 * This can be either PackageManager.VERIFICATION_ALLOW or 317 * PackageManager.VERIFICATION_REJECT. 318 */ 319 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 320 321 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 322 323 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 324 DEFAULT_CONTAINER_PACKAGE, 325 "com.android.defcontainer.DefaultContainerService"); 326 327 private static final String KILL_APP_REASON_GIDS_CHANGED = 328 "permission grant or revoke changed gids"; 329 330 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 331 "permissions revoked"; 332 333 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 334 335 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 336 337 /** Permission grant: not grant the permission. */ 338 private static final int GRANT_DENIED = 1; 339 340 /** Permission grant: grant the permission as an install permission. */ 341 private static final int GRANT_INSTALL = 2; 342 343 /** Permission grant: grant the permission as a runtime one. */ 344 private static final int GRANT_RUNTIME = 3; 345 346 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 347 private static final int GRANT_UPGRADE = 4; 348 349 final ServiceThread mHandlerThread; 350 351 final PackageHandler mHandler; 352 353 /** 354 * Messages for {@link #mHandler} that need to wait for system ready before 355 * being dispatched. 356 */ 357 private ArrayList<Message> mPostSystemReadyMessages; 358 359 final int mSdkVersion = Build.VERSION.SDK_INT; 360 361 final Context mContext; 362 final boolean mFactoryTest; 363 final boolean mOnlyCore; 364 final boolean mLazyDexOpt; 365 final long mDexOptLRUThresholdInMills; 366 final DisplayMetrics mMetrics; 367 final int mDefParseFlags; 368 final String[] mSeparateProcesses; 369 final boolean mIsUpgrade; 370 371 // This is where all application persistent data goes. 372 final File mAppDataDir; 373 374 // This is where all application persistent data goes for secondary users. 375 final File mUserAppDataDir; 376 377 /** The location for ASEC container files on internal storage. */ 378 final String mAsecInternalPath; 379 380 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 381 // LOCK HELD. Can be called with mInstallLock held. 382 final Installer mInstaller; 383 384 /** Directory where installed third-party apps stored */ 385 final File mAppInstallDir; 386 387 /** 388 * Directory to which applications installed internally have their 389 * 32 bit native libraries copied. 390 */ 391 private File mAppLib32InstallDir; 392 393 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 394 // apps. 395 final File mDrmAppPrivateInstallDir; 396 397 // ---------------------------------------------------------------- 398 399 // Lock for state used when installing and doing other long running 400 // operations. Methods that must be called with this lock held have 401 // the suffix "LI". 402 final Object mInstallLock = new Object(); 403 404 // ---------------------------------------------------------------- 405 406 // Keys are String (package name), values are Package. This also serves 407 // as the lock for the global state. Methods that must be called with 408 // this lock held have the prefix "LP". 409 final ArrayMap<String, PackageParser.Package> mPackages = 410 new ArrayMap<String, PackageParser.Package>(); 411 412 // Tracks available target package names -> overlay package paths. 413 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 414 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 415 416 final Settings mSettings; 417 boolean mRestoredSettings; 418 419 // System configuration read by SystemConfig. 420 final int[] mGlobalGids; 421 final SparseArray<ArraySet<String>> mSystemPermissions; 422 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 423 424 // If mac_permissions.xml was found for seinfo labeling. 425 boolean mFoundPolicyFile; 426 427 // If a recursive restorecon of /data/data/<pkg> is needed. 428 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 429 430 public static final class SharedLibraryEntry { 431 public final String path; 432 public final String apk; 433 434 SharedLibraryEntry(String _path, String _apk) { 435 path = _path; 436 apk = _apk; 437 } 438 } 439 440 // Currently known shared libraries. 441 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 442 new ArrayMap<String, SharedLibraryEntry>(); 443 444 // All available activities, for your resolving pleasure. 445 final ActivityIntentResolver mActivities = 446 new ActivityIntentResolver(); 447 448 // All available receivers, for your resolving pleasure. 449 final ActivityIntentResolver mReceivers = 450 new ActivityIntentResolver(); 451 452 // All available services, for your resolving pleasure. 453 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 454 455 // All available providers, for your resolving pleasure. 456 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 457 458 // Mapping from provider base names (first directory in content URI codePath) 459 // to the provider information. 460 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 461 new ArrayMap<String, PackageParser.Provider>(); 462 463 // Mapping from instrumentation class names to info about them. 464 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 465 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 466 467 // Mapping from permission names to info about them. 468 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 469 new ArrayMap<String, PackageParser.PermissionGroup>(); 470 471 // Packages whose data we have transfered into another package, thus 472 // should no longer exist. 473 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 474 475 // Broadcast actions that are only available to the system. 476 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 477 478 /** List of packages waiting for verification. */ 479 final SparseArray<PackageVerificationState> mPendingVerification 480 = new SparseArray<PackageVerificationState>(); 481 482 /** Set of packages associated with each app op permission. */ 483 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 484 485 final PackageInstallerService mInstallerService; 486 487 private final PackageDexOptimizer mPackageDexOptimizer; 488 // Cache of users who need badging. 489 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 490 491 /** Token for keys in mPendingVerification. */ 492 private int mPendingVerificationToken = 0; 493 494 volatile boolean mSystemReady; 495 volatile boolean mSafeMode; 496 volatile boolean mHasSystemUidErrors; 497 498 ApplicationInfo mAndroidApplication; 499 final ActivityInfo mResolveActivity = new ActivityInfo(); 500 final ResolveInfo mResolveInfo = new ResolveInfo(); 501 ComponentName mResolveComponentName; 502 PackageParser.Package mPlatformPackage; 503 ComponentName mCustomResolverComponentName; 504 505 boolean mResolverReplaced = false; 506 507 // Set of pending broadcasts for aggregating enable/disable of components. 508 static class PendingPackageBroadcasts { 509 // for each user id, a map of <package name -> components within that package> 510 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 511 512 public PendingPackageBroadcasts() { 513 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 514 } 515 516 public ArrayList<String> get(int userId, String packageName) { 517 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 518 return packages.get(packageName); 519 } 520 521 public void put(int userId, String packageName, ArrayList<String> components) { 522 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 523 packages.put(packageName, components); 524 } 525 526 public void remove(int userId, String packageName) { 527 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 528 if (packages != null) { 529 packages.remove(packageName); 530 } 531 } 532 533 public void remove(int userId) { 534 mUidMap.remove(userId); 535 } 536 537 public int userIdCount() { 538 return mUidMap.size(); 539 } 540 541 public int userIdAt(int n) { 542 return mUidMap.keyAt(n); 543 } 544 545 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 546 return mUidMap.get(userId); 547 } 548 549 public int size() { 550 // total number of pending broadcast entries across all userIds 551 int num = 0; 552 for (int i = 0; i< mUidMap.size(); i++) { 553 num += mUidMap.valueAt(i).size(); 554 } 555 return num; 556 } 557 558 public void clear() { 559 mUidMap.clear(); 560 } 561 562 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 563 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 564 if (map == null) { 565 map = new ArrayMap<String, ArrayList<String>>(); 566 mUidMap.put(userId, map); 567 } 568 return map; 569 } 570 } 571 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 572 573 // Service Connection to remote media container service to copy 574 // package uri's from external media onto secure containers 575 // or internal storage. 576 private IMediaContainerService mContainerService = null; 577 578 static final int SEND_PENDING_BROADCAST = 1; 579 static final int MCS_BOUND = 3; 580 static final int END_COPY = 4; 581 static final int INIT_COPY = 5; 582 static final int MCS_UNBIND = 6; 583 static final int START_CLEANING_PACKAGE = 7; 584 static final int FIND_INSTALL_LOC = 8; 585 static final int POST_INSTALL = 9; 586 static final int MCS_RECONNECT = 10; 587 static final int MCS_GIVE_UP = 11; 588 static final int UPDATED_MEDIA_STATUS = 12; 589 static final int WRITE_SETTINGS = 13; 590 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 591 static final int PACKAGE_VERIFIED = 15; 592 static final int CHECK_PENDING_VERIFICATION = 16; 593 594 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 595 596 // Delay time in millisecs 597 static final int BROADCAST_DELAY = 10 * 1000; 598 599 static UserManagerService sUserManager; 600 601 // Stores a list of users whose package restrictions file needs to be updated 602 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 603 604 final private DefaultContainerConnection mDefContainerConn = 605 new DefaultContainerConnection(); 606 class DefaultContainerConnection implements ServiceConnection { 607 public void onServiceConnected(ComponentName name, IBinder service) { 608 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 609 IMediaContainerService imcs = 610 IMediaContainerService.Stub.asInterface(service); 611 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 612 } 613 614 public void onServiceDisconnected(ComponentName name) { 615 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 616 } 617 }; 618 619 // Recordkeeping of restore-after-install operations that are currently in flight 620 // between the Package Manager and the Backup Manager 621 class PostInstallData { 622 public InstallArgs args; 623 public PackageInstalledInfo res; 624 625 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 626 args = _a; 627 res = _r; 628 } 629 }; 630 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 631 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 632 633 private final String mRequiredVerifierPackage; 634 635 private final PackageUsage mPackageUsage = new PackageUsage(); 636 637 private class PackageUsage { 638 private static final int WRITE_INTERVAL 639 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 640 641 private final Object mFileLock = new Object(); 642 private final AtomicLong mLastWritten = new AtomicLong(0); 643 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 644 645 private boolean mIsHistoricalPackageUsageAvailable = true; 646 647 boolean isHistoricalPackageUsageAvailable() { 648 return mIsHistoricalPackageUsageAvailable; 649 } 650 651 void write(boolean force) { 652 if (force) { 653 writeInternal(); 654 return; 655 } 656 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 657 && !DEBUG_DEXOPT) { 658 return; 659 } 660 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 661 new Thread("PackageUsage_DiskWriter") { 662 @Override 663 public void run() { 664 try { 665 writeInternal(); 666 } finally { 667 mBackgroundWriteRunning.set(false); 668 } 669 } 670 }.start(); 671 } 672 } 673 674 private void writeInternal() { 675 synchronized (mPackages) { 676 synchronized (mFileLock) { 677 AtomicFile file = getFile(); 678 FileOutputStream f = null; 679 try { 680 f = file.startWrite(); 681 BufferedOutputStream out = new BufferedOutputStream(f); 682 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 683 StringBuilder sb = new StringBuilder(); 684 for (PackageParser.Package pkg : mPackages.values()) { 685 if (pkg.mLastPackageUsageTimeInMills == 0) { 686 continue; 687 } 688 sb.setLength(0); 689 sb.append(pkg.packageName); 690 sb.append(' '); 691 sb.append((long)pkg.mLastPackageUsageTimeInMills); 692 sb.append('\n'); 693 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 694 } 695 out.flush(); 696 file.finishWrite(f); 697 } catch (IOException e) { 698 if (f != null) { 699 file.failWrite(f); 700 } 701 Log.e(TAG, "Failed to write package usage times", e); 702 } 703 } 704 } 705 mLastWritten.set(SystemClock.elapsedRealtime()); 706 } 707 708 void readLP() { 709 synchronized (mFileLock) { 710 AtomicFile file = getFile(); 711 BufferedInputStream in = null; 712 try { 713 in = new BufferedInputStream(file.openRead()); 714 StringBuffer sb = new StringBuffer(); 715 while (true) { 716 String packageName = readToken(in, sb, ' '); 717 if (packageName == null) { 718 break; 719 } 720 String timeInMillisString = readToken(in, sb, '\n'); 721 if (timeInMillisString == null) { 722 throw new IOException("Failed to find last usage time for package " 723 + packageName); 724 } 725 PackageParser.Package pkg = mPackages.get(packageName); 726 if (pkg == null) { 727 continue; 728 } 729 long timeInMillis; 730 try { 731 timeInMillis = Long.parseLong(timeInMillisString.toString()); 732 } catch (NumberFormatException e) { 733 throw new IOException("Failed to parse " + timeInMillisString 734 + " as a long.", e); 735 } 736 pkg.mLastPackageUsageTimeInMills = timeInMillis; 737 } 738 } catch (FileNotFoundException expected) { 739 mIsHistoricalPackageUsageAvailable = false; 740 } catch (IOException e) { 741 Log.w(TAG, "Failed to read package usage times", e); 742 } finally { 743 IoUtils.closeQuietly(in); 744 } 745 } 746 mLastWritten.set(SystemClock.elapsedRealtime()); 747 } 748 749 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 750 throws IOException { 751 sb.setLength(0); 752 while (true) { 753 int ch = in.read(); 754 if (ch == -1) { 755 if (sb.length() == 0) { 756 return null; 757 } 758 throw new IOException("Unexpected EOF"); 759 } 760 if (ch == endOfToken) { 761 return sb.toString(); 762 } 763 sb.append((char)ch); 764 } 765 } 766 767 private AtomicFile getFile() { 768 File dataDir = Environment.getDataDirectory(); 769 File systemDir = new File(dataDir, "system"); 770 File fname = new File(systemDir, "package-usage.list"); 771 return new AtomicFile(fname); 772 } 773 } 774 775 class PackageHandler extends Handler { 776 private boolean mBound = false; 777 final ArrayList<HandlerParams> mPendingInstalls = 778 new ArrayList<HandlerParams>(); 779 780 private boolean connectToService() { 781 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 782 " DefaultContainerService"); 783 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 784 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 785 if (mContext.bindServiceAsUser(service, mDefContainerConn, 786 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 787 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 788 mBound = true; 789 return true; 790 } 791 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 792 return false; 793 } 794 795 private void disconnectService() { 796 mContainerService = null; 797 mBound = false; 798 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 799 mContext.unbindService(mDefContainerConn); 800 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 801 } 802 803 PackageHandler(Looper looper) { 804 super(looper); 805 } 806 807 public void handleMessage(Message msg) { 808 try { 809 doHandleMessage(msg); 810 } finally { 811 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 812 } 813 } 814 815 void doHandleMessage(Message msg) { 816 switch (msg.what) { 817 case INIT_COPY: { 818 HandlerParams params = (HandlerParams) msg.obj; 819 int idx = mPendingInstalls.size(); 820 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 821 // If a bind was already initiated we dont really 822 // need to do anything. The pending install 823 // will be processed later on. 824 if (!mBound) { 825 // If this is the only one pending we might 826 // have to bind to the service again. 827 if (!connectToService()) { 828 Slog.e(TAG, "Failed to bind to media container service"); 829 params.serviceError(); 830 return; 831 } else { 832 // Once we bind to the service, the first 833 // pending request will be processed. 834 mPendingInstalls.add(idx, params); 835 } 836 } else { 837 mPendingInstalls.add(idx, params); 838 // Already bound to the service. Just make 839 // sure we trigger off processing the first request. 840 if (idx == 0) { 841 mHandler.sendEmptyMessage(MCS_BOUND); 842 } 843 } 844 break; 845 } 846 case MCS_BOUND: { 847 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 848 if (msg.obj != null) { 849 mContainerService = (IMediaContainerService) msg.obj; 850 } 851 if (mContainerService == null) { 852 // Something seriously wrong. Bail out 853 Slog.e(TAG, "Cannot bind to media container service"); 854 for (HandlerParams params : mPendingInstalls) { 855 // Indicate service bind error 856 params.serviceError(); 857 } 858 mPendingInstalls.clear(); 859 } else if (mPendingInstalls.size() > 0) { 860 HandlerParams params = mPendingInstalls.get(0); 861 if (params != null) { 862 if (params.startCopy()) { 863 // We are done... look for more work or to 864 // go idle. 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Checking for more work or unbind..."); 867 // Delete pending install 868 if (mPendingInstalls.size() > 0) { 869 mPendingInstalls.remove(0); 870 } 871 if (mPendingInstalls.size() == 0) { 872 if (mBound) { 873 if (DEBUG_SD_INSTALL) Log.i(TAG, 874 "Posting delayed MCS_UNBIND"); 875 removeMessages(MCS_UNBIND); 876 Message ubmsg = obtainMessage(MCS_UNBIND); 877 // Unbind after a little delay, to avoid 878 // continual thrashing. 879 sendMessageDelayed(ubmsg, 10000); 880 } 881 } else { 882 // There are more pending requests in queue. 883 // Just post MCS_BOUND message to trigger processing 884 // of next pending install. 885 if (DEBUG_SD_INSTALL) Log.i(TAG, 886 "Posting MCS_BOUND for next work"); 887 mHandler.sendEmptyMessage(MCS_BOUND); 888 } 889 } 890 } 891 } else { 892 // Should never happen ideally. 893 Slog.w(TAG, "Empty queue"); 894 } 895 break; 896 } 897 case MCS_RECONNECT: { 898 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 899 if (mPendingInstalls.size() > 0) { 900 if (mBound) { 901 disconnectService(); 902 } 903 if (!connectToService()) { 904 Slog.e(TAG, "Failed to bind to media container service"); 905 for (HandlerParams params : mPendingInstalls) { 906 // Indicate service bind error 907 params.serviceError(); 908 } 909 mPendingInstalls.clear(); 910 } 911 } 912 break; 913 } 914 case MCS_UNBIND: { 915 // If there is no actual work left, then time to unbind. 916 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 917 918 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 919 if (mBound) { 920 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 921 922 disconnectService(); 923 } 924 } else if (mPendingInstalls.size() > 0) { 925 // There are more pending requests in queue. 926 // Just post MCS_BOUND message to trigger processing 927 // of next pending install. 928 mHandler.sendEmptyMessage(MCS_BOUND); 929 } 930 931 break; 932 } 933 case MCS_GIVE_UP: { 934 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 935 mPendingInstalls.remove(0); 936 break; 937 } 938 case SEND_PENDING_BROADCAST: { 939 String packages[]; 940 ArrayList<String> components[]; 941 int size = 0; 942 int uids[]; 943 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 944 synchronized (mPackages) { 945 if (mPendingBroadcasts == null) { 946 return; 947 } 948 size = mPendingBroadcasts.size(); 949 if (size <= 0) { 950 // Nothing to be done. Just return 951 return; 952 } 953 packages = new String[size]; 954 components = new ArrayList[size]; 955 uids = new int[size]; 956 int i = 0; // filling out the above arrays 957 958 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 959 int packageUserId = mPendingBroadcasts.userIdAt(n); 960 Iterator<Map.Entry<String, ArrayList<String>>> it 961 = mPendingBroadcasts.packagesForUserId(packageUserId) 962 .entrySet().iterator(); 963 while (it.hasNext() && i < size) { 964 Map.Entry<String, ArrayList<String>> ent = it.next(); 965 packages[i] = ent.getKey(); 966 components[i] = ent.getValue(); 967 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 968 uids[i] = (ps != null) 969 ? UserHandle.getUid(packageUserId, ps.appId) 970 : -1; 971 i++; 972 } 973 } 974 size = i; 975 mPendingBroadcasts.clear(); 976 } 977 // Send broadcasts 978 for (int i = 0; i < size; i++) { 979 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 break; 983 } 984 case START_CLEANING_PACKAGE: { 985 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 986 final String packageName = (String)msg.obj; 987 final int userId = msg.arg1; 988 final boolean andCode = msg.arg2 != 0; 989 synchronized (mPackages) { 990 if (userId == UserHandle.USER_ALL) { 991 int[] users = sUserManager.getUserIds(); 992 for (int user : users) { 993 mSettings.addPackageToCleanLPw( 994 new PackageCleanItem(user, packageName, andCode)); 995 } 996 } else { 997 mSettings.addPackageToCleanLPw( 998 new PackageCleanItem(userId, packageName, andCode)); 999 } 1000 } 1001 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1002 startCleaningPackages(); 1003 } break; 1004 case POST_INSTALL: { 1005 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1006 PostInstallData data = mRunningInstalls.get(msg.arg1); 1007 mRunningInstalls.delete(msg.arg1); 1008 boolean deleteOld = false; 1009 1010 if (data != null) { 1011 InstallArgs args = data.args; 1012 PackageInstalledInfo res = data.res; 1013 1014 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1015 res.removedInfo.sendBroadcast(false, true, false); 1016 Bundle extras = new Bundle(1); 1017 extras.putInt(Intent.EXTRA_UID, res.uid); 1018 1019 // Now that we successfully installed the package, grant runtime 1020 // permissions if requested before broadcasting the install. 1021 if ((args.installFlags 1022 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1023 grantRequestedRuntimePermissions(res.pkg, 1024 args.user.getIdentifier()); 1025 } 1026 1027 // Determine the set of users who are adding this 1028 // package for the first time vs. those who are seeing 1029 // an update. 1030 int[] firstUsers; 1031 int[] updateUsers = new int[0]; 1032 if (res.origUsers == null || res.origUsers.length == 0) { 1033 firstUsers = res.newUsers; 1034 } else { 1035 firstUsers = new int[0]; 1036 for (int i=0; i<res.newUsers.length; i++) { 1037 int user = res.newUsers[i]; 1038 boolean isNew = true; 1039 for (int j=0; j<res.origUsers.length; j++) { 1040 if (res.origUsers[j] == user) { 1041 isNew = false; 1042 break; 1043 } 1044 } 1045 if (isNew) { 1046 int[] newFirst = new int[firstUsers.length+1]; 1047 System.arraycopy(firstUsers, 0, newFirst, 0, 1048 firstUsers.length); 1049 newFirst[firstUsers.length] = user; 1050 firstUsers = newFirst; 1051 } else { 1052 int[] newUpdate = new int[updateUsers.length+1]; 1053 System.arraycopy(updateUsers, 0, newUpdate, 0, 1054 updateUsers.length); 1055 newUpdate[updateUsers.length] = user; 1056 updateUsers = newUpdate; 1057 } 1058 } 1059 } 1060 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1061 res.pkg.applicationInfo.packageName, 1062 extras, null, null, firstUsers); 1063 final boolean update = res.removedInfo.removedPackage != null; 1064 if (update) { 1065 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1066 } 1067 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1068 res.pkg.applicationInfo.packageName, 1069 extras, null, null, updateUsers); 1070 if (update) { 1071 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1072 res.pkg.applicationInfo.packageName, 1073 extras, null, null, updateUsers); 1074 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1075 null, null, 1076 res.pkg.applicationInfo.packageName, null, updateUsers); 1077 1078 // treat asec-hosted packages like removable media on upgrade 1079 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1080 if (DEBUG_INSTALL) { 1081 Slog.i(TAG, "upgrading pkg " + res.pkg 1082 + " is ASEC-hosted -> AVAILABLE"); 1083 } 1084 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1085 ArrayList<String> pkgList = new ArrayList<String>(1); 1086 pkgList.add(res.pkg.applicationInfo.packageName); 1087 sendResourcesChangedBroadcast(true, true, 1088 pkgList,uidArray, null); 1089 } 1090 } 1091 if (res.removedInfo.args != null) { 1092 // Remove the replaced package's older resources safely now 1093 deleteOld = true; 1094 } 1095 1096 // Log current value of "unknown sources" setting 1097 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1098 getUnknownSourcesSettings()); 1099 } 1100 // Force a gc to clear up things 1101 Runtime.getRuntime().gc(); 1102 // We delete after a gc for applications on sdcard. 1103 if (deleteOld) { 1104 synchronized (mInstallLock) { 1105 res.removedInfo.args.doPostDeleteLI(true); 1106 } 1107 } 1108 if (args.observer != null) { 1109 try { 1110 Bundle extras = extrasForInstallResult(res); 1111 args.observer.onPackageInstalled(res.name, res.returnCode, 1112 res.returnMsg, extras); 1113 } catch (RemoteException e) { 1114 Slog.i(TAG, "Observer no longer exists."); 1115 } 1116 } 1117 } else { 1118 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1119 } 1120 } break; 1121 case UPDATED_MEDIA_STATUS: { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1123 boolean reportStatus = msg.arg1 == 1; 1124 boolean doGc = msg.arg2 == 1; 1125 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1126 if (doGc) { 1127 // Force a gc to clear up stale containers. 1128 Runtime.getRuntime().gc(); 1129 } 1130 if (msg.obj != null) { 1131 @SuppressWarnings("unchecked") 1132 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1134 // Unload containers 1135 unloadAllContainers(args); 1136 } 1137 if (reportStatus) { 1138 try { 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1140 PackageHelper.getMountService().finishMediaUpdate(); 1141 } catch (RemoteException e) { 1142 Log.e(TAG, "MountService not running?"); 1143 } 1144 } 1145 } break; 1146 case WRITE_SETTINGS: { 1147 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1148 synchronized (mPackages) { 1149 removeMessages(WRITE_SETTINGS); 1150 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1151 mSettings.writeLPr(); 1152 mDirtyUsers.clear(); 1153 } 1154 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1155 } break; 1156 case WRITE_PACKAGE_RESTRICTIONS: { 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1158 synchronized (mPackages) { 1159 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1160 for (int userId : mDirtyUsers) { 1161 mSettings.writePackageRestrictionsLPr(userId); 1162 } 1163 mDirtyUsers.clear(); 1164 } 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 } break; 1167 case CHECK_PENDING_VERIFICATION: { 1168 final int verificationId = msg.arg1; 1169 final PackageVerificationState state = mPendingVerification.get(verificationId); 1170 1171 if ((state != null) && !state.timeoutExtended()) { 1172 final InstallArgs args = state.getInstallArgs(); 1173 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1174 1175 Slog.i(TAG, "Verification timed out for " + originUri); 1176 mPendingVerification.remove(verificationId); 1177 1178 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1179 1180 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1181 Slog.i(TAG, "Continuing with installation of " + originUri); 1182 state.setVerifierResponse(Binder.getCallingUid(), 1183 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1184 broadcastPackageVerified(verificationId, originUri, 1185 PackageManager.VERIFICATION_ALLOW, 1186 state.getInstallArgs().getUser()); 1187 try { 1188 ret = args.copyApk(mContainerService, true); 1189 } catch (RemoteException e) { 1190 Slog.e(TAG, "Could not contact the ContainerService"); 1191 } 1192 } else { 1193 broadcastPackageVerified(verificationId, originUri, 1194 PackageManager.VERIFICATION_REJECT, 1195 state.getInstallArgs().getUser()); 1196 } 1197 1198 processPendingInstall(args, ret); 1199 mHandler.sendEmptyMessage(MCS_UNBIND); 1200 } 1201 break; 1202 } 1203 case PACKAGE_VERIFIED: { 1204 final int verificationId = msg.arg1; 1205 1206 final PackageVerificationState state = mPendingVerification.get(verificationId); 1207 if (state == null) { 1208 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1209 break; 1210 } 1211 1212 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1213 1214 state.setVerifierResponse(response.callerUid, response.code); 1215 1216 if (state.isVerificationComplete()) { 1217 mPendingVerification.remove(verificationId); 1218 1219 final InstallArgs args = state.getInstallArgs(); 1220 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1221 1222 int ret; 1223 if (state.isInstallAllowed()) { 1224 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1225 broadcastPackageVerified(verificationId, originUri, 1226 response.code, state.getInstallArgs().getUser()); 1227 try { 1228 ret = args.copyApk(mContainerService, true); 1229 } catch (RemoteException e) { 1230 Slog.e(TAG, "Could not contact the ContainerService"); 1231 } 1232 } else { 1233 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1234 } 1235 1236 processPendingInstall(args, ret); 1237 1238 mHandler.sendEmptyMessage(MCS_UNBIND); 1239 } 1240 1241 break; 1242 } 1243 } 1244 } 1245 } 1246 1247 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1248 if (userId >= UserHandle.USER_OWNER) { 1249 grantRequestedRuntimePermissionsForUser(pkg, userId); 1250 } else if (userId == UserHandle.USER_ALL) { 1251 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1252 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1253 } 1254 } 1255 } 1256 1257 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1258 SettingBase sb = (SettingBase) pkg.mExtras; 1259 if (sb == null) { 1260 return; 1261 } 1262 1263 PermissionsState permissionsState = sb.getPermissionsState(); 1264 1265 for (String permission : pkg.requestedPermissions) { 1266 BasePermission bp = mSettings.mPermissions.get(permission); 1267 if (bp != null && bp.isRuntime()) { 1268 permissionsState.grantRuntimePermission(bp, userId); 1269 } 1270 } 1271 } 1272 1273 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1274 Bundle extras = null; 1275 switch (res.returnCode) { 1276 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1277 extras = new Bundle(); 1278 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1279 res.origPermission); 1280 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1281 res.origPackage); 1282 break; 1283 } 1284 } 1285 return extras; 1286 } 1287 1288 void scheduleWriteSettingsLocked() { 1289 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1290 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1291 } 1292 } 1293 1294 void scheduleWritePackageRestrictionsLocked(int userId) { 1295 if (!sUserManager.exists(userId)) return; 1296 mDirtyUsers.add(userId); 1297 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1298 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1299 } 1300 } 1301 1302 public static PackageManagerService main(Context context, Installer installer, 1303 boolean factoryTest, boolean onlyCore) { 1304 PackageManagerService m = new PackageManagerService(context, installer, 1305 factoryTest, onlyCore); 1306 ServiceManager.addService("package", m); 1307 return m; 1308 } 1309 1310 static String[] splitString(String str, char sep) { 1311 int count = 1; 1312 int i = 0; 1313 while ((i=str.indexOf(sep, i)) >= 0) { 1314 count++; 1315 i++; 1316 } 1317 1318 String[] res = new String[count]; 1319 i=0; 1320 count = 0; 1321 int lastI=0; 1322 while ((i=str.indexOf(sep, i)) >= 0) { 1323 res[count] = str.substring(lastI, i); 1324 count++; 1325 i++; 1326 lastI = i; 1327 } 1328 res[count] = str.substring(lastI, str.length()); 1329 return res; 1330 } 1331 1332 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1333 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1334 Context.DISPLAY_SERVICE); 1335 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1336 } 1337 1338 public PackageManagerService(Context context, Installer installer, 1339 boolean factoryTest, boolean onlyCore) { 1340 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1341 SystemClock.uptimeMillis()); 1342 1343 if (mSdkVersion <= 0) { 1344 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1345 } 1346 1347 mContext = context; 1348 mFactoryTest = factoryTest; 1349 mOnlyCore = onlyCore; 1350 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1351 mMetrics = new DisplayMetrics(); 1352 mSettings = new Settings(mContext, mPackages); 1353 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1354 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1355 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1356 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1357 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1358 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1359 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1360 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1361 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1362 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1363 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1364 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1365 1366 // TODO: add a property to control this? 1367 long dexOptLRUThresholdInMinutes; 1368 if (mLazyDexOpt) { 1369 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1370 } else { 1371 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1372 } 1373 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1374 1375 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1376 if (separateProcesses != null && separateProcesses.length() > 0) { 1377 if ("*".equals(separateProcesses)) { 1378 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1379 mSeparateProcesses = null; 1380 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1381 } else { 1382 mDefParseFlags = 0; 1383 mSeparateProcesses = separateProcesses.split(","); 1384 Slog.w(TAG, "Running with debug.separate_processes: " 1385 + separateProcesses); 1386 } 1387 } else { 1388 mDefParseFlags = 0; 1389 mSeparateProcesses = null; 1390 } 1391 1392 mInstaller = installer; 1393 mPackageDexOptimizer = new PackageDexOptimizer(this); 1394 1395 getDefaultDisplayMetrics(context, mMetrics); 1396 1397 SystemConfig systemConfig = SystemConfig.getInstance(); 1398 mGlobalGids = systemConfig.getGlobalGids(); 1399 mSystemPermissions = systemConfig.getSystemPermissions(); 1400 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1401 1402 synchronized (mInstallLock) { 1403 // writer 1404 synchronized (mPackages) { 1405 mHandlerThread = new ServiceThread(TAG, 1406 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1407 mHandlerThread.start(); 1408 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1409 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1410 1411 File dataDir = Environment.getDataDirectory(); 1412 mAppDataDir = new File(dataDir, "data"); 1413 mAppInstallDir = new File(dataDir, "app"); 1414 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1415 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1416 mUserAppDataDir = new File(dataDir, "user"); 1417 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1418 1419 sUserManager = new UserManagerService(context, this, 1420 mInstallLock, mPackages); 1421 1422 // Propagate permission configuration in to package manager. 1423 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1424 = systemConfig.getPermissions(); 1425 for (int i=0; i<permConfig.size(); i++) { 1426 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1427 BasePermission bp = mSettings.mPermissions.get(perm.name); 1428 if (bp == null) { 1429 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1430 mSettings.mPermissions.put(perm.name, bp); 1431 } 1432 if (perm.gids != null) { 1433 bp.setGids(perm.gids, perm.perUser); 1434 } 1435 } 1436 1437 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1438 for (int i=0; i<libConfig.size(); i++) { 1439 mSharedLibraries.put(libConfig.keyAt(i), 1440 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1441 } 1442 1443 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1444 1445 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1446 mSdkVersion, mOnlyCore); 1447 1448 String customResolverActivity = Resources.getSystem().getString( 1449 R.string.config_customResolverActivity); 1450 if (TextUtils.isEmpty(customResolverActivity)) { 1451 customResolverActivity = null; 1452 } else { 1453 mCustomResolverComponentName = ComponentName.unflattenFromString( 1454 customResolverActivity); 1455 } 1456 1457 long startTime = SystemClock.uptimeMillis(); 1458 1459 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1460 startTime); 1461 1462 // Set flag to monitor and not change apk file paths when 1463 // scanning install directories. 1464 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1465 1466 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1467 1468 /** 1469 * Add everything in the in the boot class path to the 1470 * list of process files because dexopt will have been run 1471 * if necessary during zygote startup. 1472 */ 1473 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1474 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1475 1476 if (bootClassPath != null) { 1477 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1478 for (String element : bootClassPathElements) { 1479 alreadyDexOpted.add(element); 1480 } 1481 } else { 1482 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1483 } 1484 1485 if (systemServerClassPath != null) { 1486 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1487 for (String element : systemServerClassPathElements) { 1488 alreadyDexOpted.add(element); 1489 } 1490 } else { 1491 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1492 } 1493 1494 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1495 final String[] dexCodeInstructionSets = 1496 getDexCodeInstructionSets( 1497 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1498 1499 /** 1500 * Ensure all external libraries have had dexopt run on them. 1501 */ 1502 if (mSharedLibraries.size() > 0) { 1503 // NOTE: For now, we're compiling these system "shared libraries" 1504 // (and framework jars) into all available architectures. It's possible 1505 // to compile them only when we come across an app that uses them (there's 1506 // already logic for that in scanPackageLI) but that adds some complexity. 1507 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1508 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1509 final String lib = libEntry.path; 1510 if (lib == null) { 1511 continue; 1512 } 1513 1514 try { 1515 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1516 dexCodeInstructionSet, 1517 false); 1518 if (dexoptRequired != DexFile.UP_TO_DATE) { 1519 alreadyDexOpted.add(lib); 1520 1521 // The list of "shared libraries" we have at this point is 1522 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1523 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1524 } else { 1525 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1526 } 1527 } 1528 } catch (FileNotFoundException e) { 1529 Slog.w(TAG, "Library not found: " + lib); 1530 } catch (IOException e) { 1531 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1532 + e.getMessage()); 1533 } 1534 } 1535 } 1536 } 1537 1538 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1539 1540 // Gross hack for now: we know this file doesn't contain any 1541 // code, so don't dexopt it to avoid the resulting log spew. 1542 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1543 1544 // Gross hack for now: we know this file is only part of 1545 // the boot class path for art, so don't dexopt it to 1546 // avoid the resulting log spew. 1547 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1548 1549 /** 1550 * And there are a number of commands implemented in Java, which 1551 * we currently need to do the dexopt on so that they can be 1552 * run from a non-root shell. 1553 */ 1554 String[] frameworkFiles = frameworkDir.list(); 1555 if (frameworkFiles != null) { 1556 // TODO: We could compile these only for the most preferred ABI. We should 1557 // first double check that the dex files for these commands are not referenced 1558 // by other system apps. 1559 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1560 for (int i=0; i<frameworkFiles.length; i++) { 1561 File libPath = new File(frameworkDir, frameworkFiles[i]); 1562 String path = libPath.getPath(); 1563 // Skip the file if we already did it. 1564 if (alreadyDexOpted.contains(path)) { 1565 continue; 1566 } 1567 // Skip the file if it is not a type we want to dexopt. 1568 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1569 continue; 1570 } 1571 try { 1572 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1573 dexCodeInstructionSet, 1574 false); 1575 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1576 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1577 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1578 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1579 } 1580 } catch (FileNotFoundException e) { 1581 Slog.w(TAG, "Jar not found: " + path); 1582 } catch (IOException e) { 1583 Slog.w(TAG, "Exception reading jar: " + path, e); 1584 } 1585 } 1586 } 1587 } 1588 1589 // Collect vendor overlay packages. 1590 // (Do this before scanning any apps.) 1591 // For security and version matching reason, only consider 1592 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1593 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1594 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1595 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1596 1597 // Find base frameworks (resource packages without code). 1598 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1599 | PackageParser.PARSE_IS_SYSTEM_DIR 1600 | PackageParser.PARSE_IS_PRIVILEGED, 1601 scanFlags | SCAN_NO_DEX, 0); 1602 1603 // Collected privileged system packages. 1604 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1605 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1606 | PackageParser.PARSE_IS_SYSTEM_DIR 1607 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1608 1609 // Collect ordinary system packages. 1610 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1611 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1612 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1613 1614 // Collect all vendor packages. 1615 File vendorAppDir = new File("/vendor/app"); 1616 try { 1617 vendorAppDir = vendorAppDir.getCanonicalFile(); 1618 } catch (IOException e) { 1619 // failed to look up canonical path, continue with original one 1620 } 1621 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1622 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1623 1624 // Collect all OEM packages. 1625 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1626 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1627 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1628 1629 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1630 mInstaller.moveFiles(); 1631 1632 // Prune any system packages that no longer exist. 1633 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1634 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1635 if (!mOnlyCore) { 1636 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1637 while (psit.hasNext()) { 1638 PackageSetting ps = psit.next(); 1639 1640 /* 1641 * If this is not a system app, it can't be a 1642 * disable system app. 1643 */ 1644 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1645 continue; 1646 } 1647 1648 /* 1649 * If the package is scanned, it's not erased. 1650 */ 1651 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1652 if (scannedPkg != null) { 1653 /* 1654 * If the system app is both scanned and in the 1655 * disabled packages list, then it must have been 1656 * added via OTA. Remove it from the currently 1657 * scanned package so the previously user-installed 1658 * application can be scanned. 1659 */ 1660 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1661 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1662 + ps.name + "; removing system app. Last known codePath=" 1663 + ps.codePathString + ", installStatus=" + ps.installStatus 1664 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1665 + scannedPkg.mVersionCode); 1666 removePackageLI(ps, true); 1667 expectingBetter.put(ps.name, ps.codePath); 1668 } 1669 1670 continue; 1671 } 1672 1673 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1674 psit.remove(); 1675 logCriticalInfo(Log.WARN, "System package " + ps.name 1676 + " no longer exists; wiping its data"); 1677 removeDataDirsLI(ps.name); 1678 } else { 1679 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1680 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1681 possiblyDeletedUpdatedSystemApps.add(ps.name); 1682 } 1683 } 1684 } 1685 } 1686 1687 //look for any incomplete package installations 1688 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1689 //clean up list 1690 for(int i = 0; i < deletePkgsList.size(); i++) { 1691 //clean up here 1692 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1693 } 1694 //delete tmp files 1695 deleteTempPackageFiles(); 1696 1697 // Remove any shared userIDs that have no associated packages 1698 mSettings.pruneSharedUsersLPw(); 1699 1700 if (!mOnlyCore) { 1701 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1702 SystemClock.uptimeMillis()); 1703 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 1704 1705 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1706 scanFlags | SCAN_REQUIRE_KNOWN, 0); 1707 1708 /** 1709 * Remove disable package settings for any updated system 1710 * apps that were removed via an OTA. If they're not a 1711 * previously-updated app, remove them completely. 1712 * Otherwise, just revoke their system-level permissions. 1713 */ 1714 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1715 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1716 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1717 1718 String msg; 1719 if (deletedPkg == null) { 1720 msg = "Updated system package " + deletedAppName 1721 + " no longer exists; wiping its data"; 1722 removeDataDirsLI(deletedAppName); 1723 } else { 1724 msg = "Updated system app + " + deletedAppName 1725 + " no longer present; removing system privileges for " 1726 + deletedAppName; 1727 1728 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1729 1730 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1731 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1732 } 1733 logCriticalInfo(Log.WARN, msg); 1734 } 1735 1736 /** 1737 * Make sure all system apps that we expected to appear on 1738 * the userdata partition actually showed up. If they never 1739 * appeared, crawl back and revive the system version. 1740 */ 1741 for (int i = 0; i < expectingBetter.size(); i++) { 1742 final String packageName = expectingBetter.keyAt(i); 1743 if (!mPackages.containsKey(packageName)) { 1744 final File scanFile = expectingBetter.valueAt(i); 1745 1746 logCriticalInfo(Log.WARN, "Expected better " + packageName 1747 + " but never showed up; reverting to system"); 1748 1749 final int reparseFlags; 1750 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1751 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1752 | PackageParser.PARSE_IS_SYSTEM_DIR 1753 | PackageParser.PARSE_IS_PRIVILEGED; 1754 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1755 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1756 | PackageParser.PARSE_IS_SYSTEM_DIR; 1757 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1758 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1759 | PackageParser.PARSE_IS_SYSTEM_DIR; 1760 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1761 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1762 | PackageParser.PARSE_IS_SYSTEM_DIR; 1763 } else { 1764 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1765 continue; 1766 } 1767 1768 mSettings.enableSystemPackageLPw(packageName); 1769 1770 try { 1771 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1772 } catch (PackageManagerException e) { 1773 Slog.e(TAG, "Failed to parse original system package: " 1774 + e.getMessage()); 1775 } 1776 } 1777 } 1778 } 1779 1780 // Now that we know all of the shared libraries, update all clients to have 1781 // the correct library paths. 1782 updateAllSharedLibrariesLPw(); 1783 1784 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1785 // NOTE: We ignore potential failures here during a system scan (like 1786 // the rest of the commands above) because there's precious little we 1787 // can do about it. A settings error is reported, though. 1788 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1789 false /* force dexopt */, false /* defer dexopt */); 1790 } 1791 1792 // Now that we know all the packages we are keeping, 1793 // read and update their last usage times. 1794 mPackageUsage.readLP(); 1795 1796 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1797 SystemClock.uptimeMillis()); 1798 Slog.i(TAG, "Time to scan packages: " 1799 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1800 + " seconds"); 1801 1802 // If the platform SDK has changed since the last time we booted, 1803 // we need to re-grant app permission to catch any new ones that 1804 // appear. This is really a hack, and means that apps can in some 1805 // cases get permissions that the user didn't initially explicitly 1806 // allow... it would be nice to have some better way to handle 1807 // this situation. 1808 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1809 != mSdkVersion; 1810 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1811 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1812 + "; regranting permissions for internal storage"); 1813 mSettings.mInternalSdkPlatform = mSdkVersion; 1814 1815 1816 // We keep track for which users we granted permissions to be able 1817 // to grant runtime permissions to system apps for newly appeared 1818 // users. If we supported runtime permissions during the previous 1819 // boot, then we already granted permissions for all device users. 1820 // In such a case we set the users for which we granted permissions 1821 // to avoid clobbering of runtime permissions we granted to system 1822 // apps but the user revoked later. 1823 if (PackageManagerService.RUNTIME_PERMISSIONS_ENABLED && 1824 mSettings.mRuntimePermissionEnabled) { 1825 final int[] userIds = UserManagerService.getInstance().getUserIds(); 1826 for (PackageSetting ps : mSettings.mPackages.values()) { 1827 ps.setPermissionsUpdatedForUserIds(userIds); 1828 } 1829 for (SharedUserSetting sus : mSettings.mSharedUsers.values()) { 1830 sus.setPermissionsUpdatedForUserIds(userIds); 1831 } 1832 } 1833 1834 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1835 | (regrantPermissions 1836 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1837 : 0)); 1838 1839 // If this is the first boot, and it is a normal boot, then 1840 // we need to initialize the default preferred apps. 1841 if (!mRestoredSettings && !onlyCore) { 1842 mSettings.readDefaultPreferredAppsLPw(this, 0); 1843 } 1844 1845 // If this is first boot after an OTA, and a normal boot, then 1846 // we need to clear code cache directories. 1847 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1848 if (mIsUpgrade && !onlyCore) { 1849 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1850 for (String pkgName : mSettings.mPackages.keySet()) { 1851 deleteCodeCacheDirsLI(pkgName); 1852 } 1853 mSettings.mFingerprint = Build.FINGERPRINT; 1854 } 1855 1856 // All the changes are done during package scanning. 1857 mSettings.updateInternalDatabaseVersion(); 1858 1859 // can downgrade to reader 1860 mSettings.writeLPr(); 1861 1862 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1863 SystemClock.uptimeMillis()); 1864 1865 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1866 } // synchronized (mPackages) 1867 } // synchronized (mInstallLock) 1868 1869 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1870 1871 // Now after opening every single application zip, make sure they 1872 // are all flushed. Not really needed, but keeps things nice and 1873 // tidy. 1874 Runtime.getRuntime().gc(); 1875 } 1876 1877 @Override 1878 public boolean isFirstBoot() { 1879 return !mRestoredSettings; 1880 } 1881 1882 @Override 1883 public boolean isOnlyCoreApps() { 1884 return mOnlyCore; 1885 } 1886 1887 @Override 1888 public boolean isUpgrade() { 1889 return mIsUpgrade; 1890 } 1891 1892 private String getRequiredVerifierLPr() { 1893 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1894 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1895 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1896 1897 String requiredVerifier = null; 1898 1899 final int N = receivers.size(); 1900 for (int i = 0; i < N; i++) { 1901 final ResolveInfo info = receivers.get(i); 1902 1903 if (info.activityInfo == null) { 1904 continue; 1905 } 1906 1907 final String packageName = info.activityInfo.packageName; 1908 1909 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 1910 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 1911 continue; 1912 } 1913 1914 if (requiredVerifier != null) { 1915 throw new RuntimeException("There can be only one required verifier"); 1916 } 1917 1918 requiredVerifier = packageName; 1919 } 1920 1921 return requiredVerifier; 1922 } 1923 1924 @Override 1925 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1926 throws RemoteException { 1927 try { 1928 return super.onTransact(code, data, reply, flags); 1929 } catch (RuntimeException e) { 1930 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1931 Slog.wtf(TAG, "Package Manager Crash", e); 1932 } 1933 throw e; 1934 } 1935 } 1936 1937 void cleanupInstallFailedPackage(PackageSetting ps) { 1938 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1939 1940 removeDataDirsLI(ps.name); 1941 if (ps.codePath != null) { 1942 if (ps.codePath.isDirectory()) { 1943 FileUtils.deleteContents(ps.codePath); 1944 } 1945 ps.codePath.delete(); 1946 } 1947 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1948 if (ps.resourcePath.isDirectory()) { 1949 FileUtils.deleteContents(ps.resourcePath); 1950 } 1951 ps.resourcePath.delete(); 1952 } 1953 mSettings.removePackageLPw(ps.name); 1954 } 1955 1956 static int[] appendInts(int[] cur, int[] add) { 1957 if (add == null) return cur; 1958 if (cur == null) return add; 1959 final int N = add.length; 1960 for (int i=0; i<N; i++) { 1961 cur = appendInt(cur, add[i]); 1962 } 1963 return cur; 1964 } 1965 1966 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1967 if (!sUserManager.exists(userId)) return null; 1968 final PackageSetting ps = (PackageSetting) p.mExtras; 1969 if (ps == null) { 1970 return null; 1971 } 1972 1973 final PermissionsState permissionsState = ps.getPermissionsState(); 1974 1975 final int[] gids = permissionsState.computeGids(userId); 1976 final Set<String> permissions = permissionsState.getPermissions(userId); 1977 final PackageUserState state = ps.readUserState(userId); 1978 1979 return PackageParser.generatePackageInfo(p, gids, flags, 1980 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 1981 } 1982 1983 @Override 1984 public boolean isPackageAvailable(String packageName, int userId) { 1985 if (!sUserManager.exists(userId)) return false; 1986 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1987 synchronized (mPackages) { 1988 PackageParser.Package p = mPackages.get(packageName); 1989 if (p != null) { 1990 final PackageSetting ps = (PackageSetting) p.mExtras; 1991 if (ps != null) { 1992 final PackageUserState state = ps.readUserState(userId); 1993 if (state != null) { 1994 return PackageParser.isAvailable(state); 1995 } 1996 } 1997 } 1998 } 1999 return false; 2000 } 2001 2002 @Override 2003 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2004 if (!sUserManager.exists(userId)) return null; 2005 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2006 // reader 2007 synchronized (mPackages) { 2008 PackageParser.Package p = mPackages.get(packageName); 2009 if (DEBUG_PACKAGE_INFO) 2010 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2011 if (p != null) { 2012 return generatePackageInfo(p, flags, userId); 2013 } 2014 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2015 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2016 } 2017 } 2018 return null; 2019 } 2020 2021 @Override 2022 public String[] currentToCanonicalPackageNames(String[] names) { 2023 String[] out = new String[names.length]; 2024 // reader 2025 synchronized (mPackages) { 2026 for (int i=names.length-1; i>=0; i--) { 2027 PackageSetting ps = mSettings.mPackages.get(names[i]); 2028 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2029 } 2030 } 2031 return out; 2032 } 2033 2034 @Override 2035 public String[] canonicalToCurrentPackageNames(String[] names) { 2036 String[] out = new String[names.length]; 2037 // reader 2038 synchronized (mPackages) { 2039 for (int i=names.length-1; i>=0; i--) { 2040 String cur = mSettings.mRenamedPackages.get(names[i]); 2041 out[i] = cur != null ? cur : names[i]; 2042 } 2043 } 2044 return out; 2045 } 2046 2047 @Override 2048 public int getPackageUid(String packageName, int userId) { 2049 if (!sUserManager.exists(userId)) return -1; 2050 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2051 2052 // reader 2053 synchronized (mPackages) { 2054 PackageParser.Package p = mPackages.get(packageName); 2055 if(p != null) { 2056 return UserHandle.getUid(userId, p.applicationInfo.uid); 2057 } 2058 PackageSetting ps = mSettings.mPackages.get(packageName); 2059 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2060 return -1; 2061 } 2062 p = ps.pkg; 2063 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2064 } 2065 } 2066 2067 @Override 2068 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2069 if (!sUserManager.exists(userId)) { 2070 return null; 2071 } 2072 2073 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2074 "getPackageGids"); 2075 2076 // reader 2077 synchronized (mPackages) { 2078 PackageParser.Package p = mPackages.get(packageName); 2079 if (DEBUG_PACKAGE_INFO) { 2080 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2081 } 2082 if (p != null) { 2083 PackageSetting ps = (PackageSetting) p.mExtras; 2084 return ps.getPermissionsState().computeGids(userId); 2085 } 2086 } 2087 2088 return null; 2089 } 2090 2091 static PermissionInfo generatePermissionInfo( 2092 BasePermission bp, int flags) { 2093 if (bp.perm != null) { 2094 return PackageParser.generatePermissionInfo(bp.perm, flags); 2095 } 2096 PermissionInfo pi = new PermissionInfo(); 2097 pi.name = bp.name; 2098 pi.packageName = bp.sourcePackage; 2099 pi.nonLocalizedLabel = bp.name; 2100 pi.protectionLevel = bp.protectionLevel; 2101 return pi; 2102 } 2103 2104 @Override 2105 public PermissionInfo getPermissionInfo(String name, int flags) { 2106 // reader 2107 synchronized (mPackages) { 2108 final BasePermission p = mSettings.mPermissions.get(name); 2109 if (p != null) { 2110 return generatePermissionInfo(p, flags); 2111 } 2112 return null; 2113 } 2114 } 2115 2116 @Override 2117 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2118 // reader 2119 synchronized (mPackages) { 2120 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2121 for (BasePermission p : mSettings.mPermissions.values()) { 2122 if (group == null) { 2123 if (p.perm == null || p.perm.info.group == null) { 2124 out.add(generatePermissionInfo(p, flags)); 2125 } 2126 } else { 2127 if (p.perm != null && group.equals(p.perm.info.group)) { 2128 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2129 } 2130 } 2131 } 2132 2133 if (out.size() > 0) { 2134 return out; 2135 } 2136 return mPermissionGroups.containsKey(group) ? out : null; 2137 } 2138 } 2139 2140 @Override 2141 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2142 // reader 2143 synchronized (mPackages) { 2144 return PackageParser.generatePermissionGroupInfo( 2145 mPermissionGroups.get(name), flags); 2146 } 2147 } 2148 2149 @Override 2150 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2151 // reader 2152 synchronized (mPackages) { 2153 final int N = mPermissionGroups.size(); 2154 ArrayList<PermissionGroupInfo> out 2155 = new ArrayList<PermissionGroupInfo>(N); 2156 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2157 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2158 } 2159 return out; 2160 } 2161 } 2162 2163 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2164 int userId) { 2165 if (!sUserManager.exists(userId)) return null; 2166 PackageSetting ps = mSettings.mPackages.get(packageName); 2167 if (ps != null) { 2168 if (ps.pkg == null) { 2169 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2170 flags, userId); 2171 if (pInfo != null) { 2172 return pInfo.applicationInfo; 2173 } 2174 return null; 2175 } 2176 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2177 ps.readUserState(userId), userId); 2178 } 2179 return null; 2180 } 2181 2182 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2183 int userId) { 2184 if (!sUserManager.exists(userId)) return null; 2185 PackageSetting ps = mSettings.mPackages.get(packageName); 2186 if (ps != null) { 2187 PackageParser.Package pkg = ps.pkg; 2188 if (pkg == null) { 2189 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2190 return null; 2191 } 2192 // Only data remains, so we aren't worried about code paths 2193 pkg = new PackageParser.Package(packageName); 2194 pkg.applicationInfo.packageName = packageName; 2195 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2196 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2197 pkg.applicationInfo.dataDir = 2198 getDataPathForPackage(packageName, 0).getPath(); 2199 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2200 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2201 } 2202 return generatePackageInfo(pkg, flags, userId); 2203 } 2204 return null; 2205 } 2206 2207 @Override 2208 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2209 if (!sUserManager.exists(userId)) return null; 2210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2211 // writer 2212 synchronized (mPackages) { 2213 PackageParser.Package p = mPackages.get(packageName); 2214 if (DEBUG_PACKAGE_INFO) Log.v( 2215 TAG, "getApplicationInfo " + packageName 2216 + ": " + p); 2217 if (p != null) { 2218 PackageSetting ps = mSettings.mPackages.get(packageName); 2219 if (ps == null) return null; 2220 // Note: isEnabledLP() does not apply here - always return info 2221 return PackageParser.generateApplicationInfo( 2222 p, flags, ps.readUserState(userId), userId); 2223 } 2224 if ("android".equals(packageName)||"system".equals(packageName)) { 2225 return mAndroidApplication; 2226 } 2227 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2228 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2229 } 2230 } 2231 return null; 2232 } 2233 2234 2235 @Override 2236 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2237 mContext.enforceCallingOrSelfPermission( 2238 android.Manifest.permission.CLEAR_APP_CACHE, null); 2239 // Queue up an async operation since clearing cache may take a little while. 2240 mHandler.post(new Runnable() { 2241 public void run() { 2242 mHandler.removeCallbacks(this); 2243 int retCode = -1; 2244 synchronized (mInstallLock) { 2245 retCode = mInstaller.freeCache(freeStorageSize); 2246 if (retCode < 0) { 2247 Slog.w(TAG, "Couldn't clear application caches"); 2248 } 2249 } 2250 if (observer != null) { 2251 try { 2252 observer.onRemoveCompleted(null, (retCode >= 0)); 2253 } catch (RemoteException e) { 2254 Slog.w(TAG, "RemoveException when invoking call back"); 2255 } 2256 } 2257 } 2258 }); 2259 } 2260 2261 @Override 2262 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2263 mContext.enforceCallingOrSelfPermission( 2264 android.Manifest.permission.CLEAR_APP_CACHE, null); 2265 // Queue up an async operation since clearing cache may take a little while. 2266 mHandler.post(new Runnable() { 2267 public void run() { 2268 mHandler.removeCallbacks(this); 2269 int retCode = -1; 2270 synchronized (mInstallLock) { 2271 retCode = mInstaller.freeCache(freeStorageSize); 2272 if (retCode < 0) { 2273 Slog.w(TAG, "Couldn't clear application caches"); 2274 } 2275 } 2276 if(pi != null) { 2277 try { 2278 // Callback via pending intent 2279 int code = (retCode >= 0) ? 1 : 0; 2280 pi.sendIntent(null, code, null, 2281 null, null); 2282 } catch (SendIntentException e1) { 2283 Slog.i(TAG, "Failed to send pending intent"); 2284 } 2285 } 2286 } 2287 }); 2288 } 2289 2290 void freeStorage(long freeStorageSize) throws IOException { 2291 synchronized (mInstallLock) { 2292 if (mInstaller.freeCache(freeStorageSize) < 0) { 2293 throw new IOException("Failed to free enough space"); 2294 } 2295 } 2296 } 2297 2298 @Override 2299 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2300 if (!sUserManager.exists(userId)) return null; 2301 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2302 synchronized (mPackages) { 2303 PackageParser.Activity a = mActivities.mActivities.get(component); 2304 2305 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2306 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2307 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2308 if (ps == null) return null; 2309 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2310 userId); 2311 } 2312 if (mResolveComponentName.equals(component)) { 2313 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2314 new PackageUserState(), userId); 2315 } 2316 } 2317 return null; 2318 } 2319 2320 @Override 2321 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2322 String resolvedType) { 2323 synchronized (mPackages) { 2324 PackageParser.Activity a = mActivities.mActivities.get(component); 2325 if (a == null) { 2326 return false; 2327 } 2328 for (int i=0; i<a.intents.size(); i++) { 2329 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2330 intent.getData(), intent.getCategories(), TAG) >= 0) { 2331 return true; 2332 } 2333 } 2334 return false; 2335 } 2336 } 2337 2338 @Override 2339 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2340 if (!sUserManager.exists(userId)) return null; 2341 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2342 synchronized (mPackages) { 2343 PackageParser.Activity a = mReceivers.mActivities.get(component); 2344 if (DEBUG_PACKAGE_INFO) Log.v( 2345 TAG, "getReceiverInfo " + component + ": " + a); 2346 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2347 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2348 if (ps == null) return null; 2349 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2350 userId); 2351 } 2352 } 2353 return null; 2354 } 2355 2356 @Override 2357 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2358 if (!sUserManager.exists(userId)) return null; 2359 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2360 synchronized (mPackages) { 2361 PackageParser.Service s = mServices.mServices.get(component); 2362 if (DEBUG_PACKAGE_INFO) Log.v( 2363 TAG, "getServiceInfo " + component + ": " + s); 2364 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2365 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2366 if (ps == null) return null; 2367 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2368 userId); 2369 } 2370 } 2371 return null; 2372 } 2373 2374 @Override 2375 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2376 if (!sUserManager.exists(userId)) return null; 2377 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2378 synchronized (mPackages) { 2379 PackageParser.Provider p = mProviders.mProviders.get(component); 2380 if (DEBUG_PACKAGE_INFO) Log.v( 2381 TAG, "getProviderInfo " + component + ": " + p); 2382 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2383 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2384 if (ps == null) return null; 2385 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2386 userId); 2387 } 2388 } 2389 return null; 2390 } 2391 2392 @Override 2393 public String[] getSystemSharedLibraryNames() { 2394 Set<String> libSet; 2395 synchronized (mPackages) { 2396 libSet = mSharedLibraries.keySet(); 2397 int size = libSet.size(); 2398 if (size > 0) { 2399 String[] libs = new String[size]; 2400 libSet.toArray(libs); 2401 return libs; 2402 } 2403 } 2404 return null; 2405 } 2406 2407 /** 2408 * @hide 2409 */ 2410 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2411 synchronized (mPackages) { 2412 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2413 if (lib != null && lib.apk != null) { 2414 return mPackages.get(lib.apk); 2415 } 2416 } 2417 return null; 2418 } 2419 2420 @Override 2421 public FeatureInfo[] getSystemAvailableFeatures() { 2422 Collection<FeatureInfo> featSet; 2423 synchronized (mPackages) { 2424 featSet = mAvailableFeatures.values(); 2425 int size = featSet.size(); 2426 if (size > 0) { 2427 FeatureInfo[] features = new FeatureInfo[size+1]; 2428 featSet.toArray(features); 2429 FeatureInfo fi = new FeatureInfo(); 2430 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2431 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2432 features[size] = fi; 2433 return features; 2434 } 2435 } 2436 return null; 2437 } 2438 2439 @Override 2440 public boolean hasSystemFeature(String name) { 2441 synchronized (mPackages) { 2442 return mAvailableFeatures.containsKey(name); 2443 } 2444 } 2445 2446 private void checkValidCaller(int uid, int userId) { 2447 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2448 return; 2449 2450 throw new SecurityException("Caller uid=" + uid 2451 + " is not privileged to communicate with user=" + userId); 2452 } 2453 2454 @Override 2455 public int checkPermission(String permName, String pkgName, int userId) { 2456 if (!sUserManager.exists(userId)) { 2457 return PackageManager.PERMISSION_DENIED; 2458 } 2459 2460 synchronized (mPackages) { 2461 final PackageParser.Package p = mPackages.get(pkgName); 2462 if (p != null && p.mExtras != null) { 2463 final PackageSetting ps = (PackageSetting) p.mExtras; 2464 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2465 return PackageManager.PERMISSION_GRANTED; 2466 } 2467 } 2468 } 2469 2470 return PackageManager.PERMISSION_DENIED; 2471 } 2472 2473 @Override 2474 public int checkUidPermission(String permName, int uid) { 2475 final int userId = UserHandle.getUserId(uid); 2476 2477 if (!sUserManager.exists(userId)) { 2478 return PackageManager.PERMISSION_DENIED; 2479 } 2480 2481 synchronized (mPackages) { 2482 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2483 if (obj != null) { 2484 final SettingBase ps = (SettingBase) obj; 2485 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2486 return PackageManager.PERMISSION_GRANTED; 2487 } 2488 } else { 2489 ArraySet<String> perms = mSystemPermissions.get(uid); 2490 if (perms != null && perms.contains(permName)) { 2491 return PackageManager.PERMISSION_GRANTED; 2492 } 2493 } 2494 } 2495 2496 return PackageManager.PERMISSION_DENIED; 2497 } 2498 2499 /** 2500 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2501 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2502 * @param checkShell TODO(yamasani): 2503 * @param message the message to log on security exception 2504 */ 2505 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2506 boolean checkShell, String message) { 2507 if (userId < 0) { 2508 throw new IllegalArgumentException("Invalid userId " + userId); 2509 } 2510 if (checkShell) { 2511 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2512 } 2513 if (userId == UserHandle.getUserId(callingUid)) return; 2514 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2515 if (requireFullPermission) { 2516 mContext.enforceCallingOrSelfPermission( 2517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2518 } else { 2519 try { 2520 mContext.enforceCallingOrSelfPermission( 2521 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2522 } catch (SecurityException se) { 2523 mContext.enforceCallingOrSelfPermission( 2524 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2525 } 2526 } 2527 } 2528 } 2529 2530 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2531 if (callingUid == Process.SHELL_UID) { 2532 if (userHandle >= 0 2533 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2534 throw new SecurityException("Shell does not have permission to access user " 2535 + userHandle); 2536 } else if (userHandle < 0) { 2537 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2538 + Debug.getCallers(3)); 2539 } 2540 } 2541 } 2542 2543 private BasePermission findPermissionTreeLP(String permName) { 2544 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2545 if (permName.startsWith(bp.name) && 2546 permName.length() > bp.name.length() && 2547 permName.charAt(bp.name.length()) == '.') { 2548 return bp; 2549 } 2550 } 2551 return null; 2552 } 2553 2554 private BasePermission checkPermissionTreeLP(String permName) { 2555 if (permName != null) { 2556 BasePermission bp = findPermissionTreeLP(permName); 2557 if (bp != null) { 2558 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2559 return bp; 2560 } 2561 throw new SecurityException("Calling uid " 2562 + Binder.getCallingUid() 2563 + " is not allowed to add to permission tree " 2564 + bp.name + " owned by uid " + bp.uid); 2565 } 2566 } 2567 throw new SecurityException("No permission tree found for " + permName); 2568 } 2569 2570 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2571 if (s1 == null) { 2572 return s2 == null; 2573 } 2574 if (s2 == null) { 2575 return false; 2576 } 2577 if (s1.getClass() != s2.getClass()) { 2578 return false; 2579 } 2580 return s1.equals(s2); 2581 } 2582 2583 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2584 if (pi1.icon != pi2.icon) return false; 2585 if (pi1.logo != pi2.logo) return false; 2586 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2587 if (!compareStrings(pi1.name, pi2.name)) return false; 2588 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2589 // We'll take care of setting this one. 2590 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2591 // These are not currently stored in settings. 2592 //if (!compareStrings(pi1.group, pi2.group)) return false; 2593 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2594 //if (pi1.labelRes != pi2.labelRes) return false; 2595 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2596 return true; 2597 } 2598 2599 int permissionInfoFootprint(PermissionInfo info) { 2600 int size = info.name.length(); 2601 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2602 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2603 return size; 2604 } 2605 2606 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2607 int size = 0; 2608 for (BasePermission perm : mSettings.mPermissions.values()) { 2609 if (perm.uid == tree.uid) { 2610 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2611 } 2612 } 2613 return size; 2614 } 2615 2616 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2617 // We calculate the max size of permissions defined by this uid and throw 2618 // if that plus the size of 'info' would exceed our stated maximum. 2619 if (tree.uid != Process.SYSTEM_UID) { 2620 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2621 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2622 throw new SecurityException("Permission tree size cap exceeded"); 2623 } 2624 } 2625 } 2626 2627 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2628 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2629 throw new SecurityException("Label must be specified in permission"); 2630 } 2631 BasePermission tree = checkPermissionTreeLP(info.name); 2632 BasePermission bp = mSettings.mPermissions.get(info.name); 2633 boolean added = bp == null; 2634 boolean changed = true; 2635 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2636 if (added) { 2637 enforcePermissionCapLocked(info, tree); 2638 bp = new BasePermission(info.name, tree.sourcePackage, 2639 BasePermission.TYPE_DYNAMIC); 2640 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2641 throw new SecurityException( 2642 "Not allowed to modify non-dynamic permission " 2643 + info.name); 2644 } else { 2645 if (bp.protectionLevel == fixedLevel 2646 && bp.perm.owner.equals(tree.perm.owner) 2647 && bp.uid == tree.uid 2648 && comparePermissionInfos(bp.perm.info, info)) { 2649 changed = false; 2650 } 2651 } 2652 bp.protectionLevel = fixedLevel; 2653 info = new PermissionInfo(info); 2654 info.protectionLevel = fixedLevel; 2655 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2656 bp.perm.info.packageName = tree.perm.info.packageName; 2657 bp.uid = tree.uid; 2658 if (added) { 2659 mSettings.mPermissions.put(info.name, bp); 2660 } 2661 if (changed) { 2662 if (!async) { 2663 mSettings.writeLPr(); 2664 } else { 2665 scheduleWriteSettingsLocked(); 2666 } 2667 } 2668 return added; 2669 } 2670 2671 @Override 2672 public boolean addPermission(PermissionInfo info) { 2673 synchronized (mPackages) { 2674 return addPermissionLocked(info, false); 2675 } 2676 } 2677 2678 @Override 2679 public boolean addPermissionAsync(PermissionInfo info) { 2680 synchronized (mPackages) { 2681 return addPermissionLocked(info, true); 2682 } 2683 } 2684 2685 @Override 2686 public void removePermission(String name) { 2687 synchronized (mPackages) { 2688 checkPermissionTreeLP(name); 2689 BasePermission bp = mSettings.mPermissions.get(name); 2690 if (bp != null) { 2691 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2692 throw new SecurityException( 2693 "Not allowed to modify non-dynamic permission " 2694 + name); 2695 } 2696 mSettings.mPermissions.remove(name); 2697 mSettings.writeLPr(); 2698 } 2699 } 2700 } 2701 2702 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 2703 BasePermission bp) { 2704 int index = pkg.requestedPermissions.indexOf(bp.name); 2705 if (index == -1) { 2706 throw new SecurityException("Package " + pkg.packageName 2707 + " has not requested permission " + bp.name); 2708 } 2709 if (!bp.isRuntime()) { 2710 throw new SecurityException("Permission " + bp.name 2711 + " is not a changeable permission type"); 2712 } 2713 } 2714 2715 @Override 2716 public boolean grantPermission(String packageName, String name, int userId) { 2717 if (!sUserManager.exists(userId)) { 2718 return false; 2719 } 2720 2721 mContext.enforceCallingOrSelfPermission( 2722 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2723 "grantPermission"); 2724 2725 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2726 "grantPermission"); 2727 2728 synchronized (mPackages) { 2729 final PackageParser.Package pkg = mPackages.get(packageName); 2730 if (pkg == null) { 2731 throw new IllegalArgumentException("Unknown package: " + packageName); 2732 } 2733 2734 final BasePermission bp = mSettings.mPermissions.get(name); 2735 if (bp == null) { 2736 throw new IllegalArgumentException("Unknown permission: " + name); 2737 } 2738 2739 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2740 2741 final SettingBase sb = (SettingBase) pkg.mExtras; 2742 if (sb == null) { 2743 throw new IllegalArgumentException("Unknown package: " + packageName); 2744 } 2745 2746 final PermissionsState permissionsState = sb.getPermissionsState(); 2747 2748 final int result = permissionsState.grantRuntimePermission(bp, userId); 2749 switch (result) { 2750 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 2751 return false; 2752 } 2753 2754 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 2755 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 2756 } break; 2757 } 2758 2759 // Not critical if that is lost - app has to request again. 2760 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 2761 2762 return true; 2763 } 2764 } 2765 2766 @Override 2767 public boolean revokePermission(String packageName, String name, int userId) { 2768 if (!sUserManager.exists(userId)) { 2769 return false; 2770 } 2771 2772 mContext.enforceCallingOrSelfPermission( 2773 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2774 "revokePermission"); 2775 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2777 "revokePermission"); 2778 2779 synchronized (mPackages) { 2780 final PackageParser.Package pkg = mPackages.get(packageName); 2781 if (pkg == null) { 2782 throw new IllegalArgumentException("Unknown package: " + packageName); 2783 } 2784 2785 final BasePermission bp = mSettings.mPermissions.get(name); 2786 if (bp == null) { 2787 throw new IllegalArgumentException("Unknown permission: " + name); 2788 } 2789 2790 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2791 2792 final SettingBase sb = (SettingBase) pkg.mExtras; 2793 if (sb == null) { 2794 throw new IllegalArgumentException("Unknown package: " + packageName); 2795 } 2796 2797 final PermissionsState permissionsState = sb.getPermissionsState(); 2798 2799 if (permissionsState.revokeRuntimePermission(bp, userId) == 2800 PermissionsState.PERMISSION_OPERATION_FAILURE) { 2801 return false; 2802 } 2803 2804 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 2805 2806 // Critical, after this call all should never have the permission. 2807 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 2808 2809 return true; 2810 } 2811 } 2812 2813 @Override 2814 public boolean isProtectedBroadcast(String actionName) { 2815 synchronized (mPackages) { 2816 return mProtectedBroadcasts.contains(actionName); 2817 } 2818 } 2819 2820 @Override 2821 public int checkSignatures(String pkg1, String pkg2) { 2822 synchronized (mPackages) { 2823 final PackageParser.Package p1 = mPackages.get(pkg1); 2824 final PackageParser.Package p2 = mPackages.get(pkg2); 2825 if (p1 == null || p1.mExtras == null 2826 || p2 == null || p2.mExtras == null) { 2827 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2828 } 2829 return compareSignatures(p1.mSignatures, p2.mSignatures); 2830 } 2831 } 2832 2833 @Override 2834 public int checkUidSignatures(int uid1, int uid2) { 2835 // Map to base uids. 2836 uid1 = UserHandle.getAppId(uid1); 2837 uid2 = UserHandle.getAppId(uid2); 2838 // reader 2839 synchronized (mPackages) { 2840 Signature[] s1; 2841 Signature[] s2; 2842 Object obj = mSettings.getUserIdLPr(uid1); 2843 if (obj != null) { 2844 if (obj instanceof SharedUserSetting) { 2845 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2846 } else if (obj instanceof PackageSetting) { 2847 s1 = ((PackageSetting)obj).signatures.mSignatures; 2848 } else { 2849 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2850 } 2851 } else { 2852 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2853 } 2854 obj = mSettings.getUserIdLPr(uid2); 2855 if (obj != null) { 2856 if (obj instanceof SharedUserSetting) { 2857 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2858 } else if (obj instanceof PackageSetting) { 2859 s2 = ((PackageSetting)obj).signatures.mSignatures; 2860 } else { 2861 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2862 } 2863 } else { 2864 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2865 } 2866 return compareSignatures(s1, s2); 2867 } 2868 } 2869 2870 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 2871 final long identity = Binder.clearCallingIdentity(); 2872 try { 2873 if (sb instanceof SharedUserSetting) { 2874 SharedUserSetting sus = (SharedUserSetting) sb; 2875 final int packageCount = sus.packages.size(); 2876 for (int i = 0; i < packageCount; i++) { 2877 PackageSetting susPs = sus.packages.valueAt(i); 2878 if (userId == UserHandle.USER_ALL) { 2879 killApplication(susPs.pkg.packageName, susPs.appId, reason); 2880 } else { 2881 final int uid = UserHandle.getUid(userId, susPs.appId); 2882 killUid(uid, reason); 2883 } 2884 } 2885 } else if (sb instanceof PackageSetting) { 2886 PackageSetting ps = (PackageSetting) sb; 2887 if (userId == UserHandle.USER_ALL) { 2888 killApplication(ps.pkg.packageName, ps.appId, reason); 2889 } else { 2890 final int uid = UserHandle.getUid(userId, ps.appId); 2891 killUid(uid, reason); 2892 } 2893 } 2894 } finally { 2895 Binder.restoreCallingIdentity(identity); 2896 } 2897 } 2898 2899 private static void killUid(int uid, String reason) { 2900 IActivityManager am = ActivityManagerNative.getDefault(); 2901 if (am != null) { 2902 try { 2903 am.killUid(uid, reason); 2904 } catch (RemoteException e) { 2905 /* ignore - same process */ 2906 } 2907 } 2908 } 2909 2910 /** 2911 * Compares two sets of signatures. Returns: 2912 * <br /> 2913 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2914 * <br /> 2915 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2916 * <br /> 2917 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2918 * <br /> 2919 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2920 * <br /> 2921 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2922 */ 2923 static int compareSignatures(Signature[] s1, Signature[] s2) { 2924 if (s1 == null) { 2925 return s2 == null 2926 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2927 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2928 } 2929 2930 if (s2 == null) { 2931 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2932 } 2933 2934 if (s1.length != s2.length) { 2935 return PackageManager.SIGNATURE_NO_MATCH; 2936 } 2937 2938 // Since both signature sets are of size 1, we can compare without HashSets. 2939 if (s1.length == 1) { 2940 return s1[0].equals(s2[0]) ? 2941 PackageManager.SIGNATURE_MATCH : 2942 PackageManager.SIGNATURE_NO_MATCH; 2943 } 2944 2945 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2946 for (Signature sig : s1) { 2947 set1.add(sig); 2948 } 2949 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2950 for (Signature sig : s2) { 2951 set2.add(sig); 2952 } 2953 // Make sure s2 contains all signatures in s1. 2954 if (set1.equals(set2)) { 2955 return PackageManager.SIGNATURE_MATCH; 2956 } 2957 return PackageManager.SIGNATURE_NO_MATCH; 2958 } 2959 2960 /** 2961 * If the database version for this type of package (internal storage or 2962 * external storage) is less than the version where package signatures 2963 * were updated, return true. 2964 */ 2965 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2966 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2967 DatabaseVersion.SIGNATURE_END_ENTITY)) 2968 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2969 DatabaseVersion.SIGNATURE_END_ENTITY)); 2970 } 2971 2972 /** 2973 * Used for backward compatibility to make sure any packages with 2974 * certificate chains get upgraded to the new style. {@code existingSigs} 2975 * will be in the old format (since they were stored on disk from before the 2976 * system upgrade) and {@code scannedSigs} will be in the newer format. 2977 */ 2978 private int compareSignaturesCompat(PackageSignatures existingSigs, 2979 PackageParser.Package scannedPkg) { 2980 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2981 return PackageManager.SIGNATURE_NO_MATCH; 2982 } 2983 2984 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2985 for (Signature sig : existingSigs.mSignatures) { 2986 existingSet.add(sig); 2987 } 2988 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2989 for (Signature sig : scannedPkg.mSignatures) { 2990 try { 2991 Signature[] chainSignatures = sig.getChainSignatures(); 2992 for (Signature chainSig : chainSignatures) { 2993 scannedCompatSet.add(chainSig); 2994 } 2995 } catch (CertificateEncodingException e) { 2996 scannedCompatSet.add(sig); 2997 } 2998 } 2999 /* 3000 * Make sure the expanded scanned set contains all signatures in the 3001 * existing one. 3002 */ 3003 if (scannedCompatSet.equals(existingSet)) { 3004 // Migrate the old signatures to the new scheme. 3005 existingSigs.assignSignatures(scannedPkg.mSignatures); 3006 // The new KeySets will be re-added later in the scanning process. 3007 synchronized (mPackages) { 3008 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3009 } 3010 return PackageManager.SIGNATURE_MATCH; 3011 } 3012 return PackageManager.SIGNATURE_NO_MATCH; 3013 } 3014 3015 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3016 if (isExternal(scannedPkg)) { 3017 return mSettings.isExternalDatabaseVersionOlderThan( 3018 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3019 } else { 3020 return mSettings.isInternalDatabaseVersionOlderThan( 3021 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3022 } 3023 } 3024 3025 private int compareSignaturesRecover(PackageSignatures existingSigs, 3026 PackageParser.Package scannedPkg) { 3027 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3028 return PackageManager.SIGNATURE_NO_MATCH; 3029 } 3030 3031 String msg = null; 3032 try { 3033 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3034 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3035 + scannedPkg.packageName); 3036 return PackageManager.SIGNATURE_MATCH; 3037 } 3038 } catch (CertificateException e) { 3039 msg = e.getMessage(); 3040 } 3041 3042 logCriticalInfo(Log.INFO, 3043 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3044 return PackageManager.SIGNATURE_NO_MATCH; 3045 } 3046 3047 @Override 3048 public String[] getPackagesForUid(int uid) { 3049 uid = UserHandle.getAppId(uid); 3050 // reader 3051 synchronized (mPackages) { 3052 Object obj = mSettings.getUserIdLPr(uid); 3053 if (obj instanceof SharedUserSetting) { 3054 final SharedUserSetting sus = (SharedUserSetting) obj; 3055 final int N = sus.packages.size(); 3056 final String[] res = new String[N]; 3057 final Iterator<PackageSetting> it = sus.packages.iterator(); 3058 int i = 0; 3059 while (it.hasNext()) { 3060 res[i++] = it.next().name; 3061 } 3062 return res; 3063 } else if (obj instanceof PackageSetting) { 3064 final PackageSetting ps = (PackageSetting) obj; 3065 return new String[] { ps.name }; 3066 } 3067 } 3068 return null; 3069 } 3070 3071 @Override 3072 public String getNameForUid(int uid) { 3073 // reader 3074 synchronized (mPackages) { 3075 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3076 if (obj instanceof SharedUserSetting) { 3077 final SharedUserSetting sus = (SharedUserSetting) obj; 3078 return sus.name + ":" + sus.userId; 3079 } else if (obj instanceof PackageSetting) { 3080 final PackageSetting ps = (PackageSetting) obj; 3081 return ps.name; 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public int getUidForSharedUser(String sharedUserName) { 3089 if(sharedUserName == null) { 3090 return -1; 3091 } 3092 // reader 3093 synchronized (mPackages) { 3094 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3095 if (suid == null) { 3096 return -1; 3097 } 3098 return suid.userId; 3099 } 3100 } 3101 3102 @Override 3103 public int getFlagsForUid(int uid) { 3104 synchronized (mPackages) { 3105 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3106 if (obj instanceof SharedUserSetting) { 3107 final SharedUserSetting sus = (SharedUserSetting) obj; 3108 return sus.pkgFlags; 3109 } else if (obj instanceof PackageSetting) { 3110 final PackageSetting ps = (PackageSetting) obj; 3111 return ps.pkgFlags; 3112 } 3113 } 3114 return 0; 3115 } 3116 3117 @Override 3118 public int getPrivateFlagsForUid(int uid) { 3119 synchronized (mPackages) { 3120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3121 if (obj instanceof SharedUserSetting) { 3122 final SharedUserSetting sus = (SharedUserSetting) obj; 3123 return sus.pkgPrivateFlags; 3124 } else if (obj instanceof PackageSetting) { 3125 final PackageSetting ps = (PackageSetting) obj; 3126 return ps.pkgPrivateFlags; 3127 } 3128 } 3129 return 0; 3130 } 3131 3132 @Override 3133 public boolean isUidPrivileged(int uid) { 3134 uid = UserHandle.getAppId(uid); 3135 // reader 3136 synchronized (mPackages) { 3137 Object obj = mSettings.getUserIdLPr(uid); 3138 if (obj instanceof SharedUserSetting) { 3139 final SharedUserSetting sus = (SharedUserSetting) obj; 3140 final Iterator<PackageSetting> it = sus.packages.iterator(); 3141 while (it.hasNext()) { 3142 if (it.next().isPrivileged()) { 3143 return true; 3144 } 3145 } 3146 } else if (obj instanceof PackageSetting) { 3147 final PackageSetting ps = (PackageSetting) obj; 3148 return ps.isPrivileged(); 3149 } 3150 } 3151 return false; 3152 } 3153 3154 @Override 3155 public String[] getAppOpPermissionPackages(String permissionName) { 3156 synchronized (mPackages) { 3157 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3158 if (pkgs == null) { 3159 return null; 3160 } 3161 return pkgs.toArray(new String[pkgs.size()]); 3162 } 3163 } 3164 3165 @Override 3166 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3167 int flags, int userId) { 3168 if (!sUserManager.exists(userId)) return null; 3169 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3170 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3171 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3172 } 3173 3174 @Override 3175 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3176 IntentFilter filter, int match, ComponentName activity) { 3177 final int userId = UserHandle.getCallingUserId(); 3178 if (DEBUG_PREFERRED) { 3179 Log.v(TAG, "setLastChosenActivity intent=" + intent 3180 + " resolvedType=" + resolvedType 3181 + " flags=" + flags 3182 + " filter=" + filter 3183 + " match=" + match 3184 + " activity=" + activity); 3185 filter.dump(new PrintStreamPrinter(System.out), " "); 3186 } 3187 intent.setComponent(null); 3188 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3189 // Find any earlier preferred or last chosen entries and nuke them 3190 findPreferredActivity(intent, resolvedType, 3191 flags, query, 0, false, true, false, userId); 3192 // Add the new activity as the last chosen for this filter 3193 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3194 "Setting last chosen"); 3195 } 3196 3197 @Override 3198 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3199 final int userId = UserHandle.getCallingUserId(); 3200 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3201 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3202 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3203 false, false, false, userId); 3204 } 3205 3206 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3207 int flags, List<ResolveInfo> query, int userId) { 3208 if (query != null) { 3209 final int N = query.size(); 3210 if (N == 1) { 3211 return query.get(0); 3212 } else if (N > 1) { 3213 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3214 // If there is more than one activity with the same priority, 3215 // then let the user decide between them. 3216 ResolveInfo r0 = query.get(0); 3217 ResolveInfo r1 = query.get(1); 3218 if (DEBUG_INTENT_MATCHING || debug) { 3219 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3220 + r1.activityInfo.name + "=" + r1.priority); 3221 } 3222 // If the first activity has a higher priority, or a different 3223 // default, then it is always desireable to pick it. 3224 if (r0.priority != r1.priority 3225 || r0.preferredOrder != r1.preferredOrder 3226 || r0.isDefault != r1.isDefault) { 3227 return query.get(0); 3228 } 3229 // If we have saved a preference for a preferred activity for 3230 // this Intent, use that. 3231 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3232 flags, query, r0.priority, true, false, debug, userId); 3233 if (ri != null) { 3234 return ri; 3235 } 3236 if (userId != 0) { 3237 ri = new ResolveInfo(mResolveInfo); 3238 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3239 ri.activityInfo.applicationInfo = new ApplicationInfo( 3240 ri.activityInfo.applicationInfo); 3241 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3242 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3243 return ri; 3244 } 3245 return mResolveInfo; 3246 } 3247 } 3248 return null; 3249 } 3250 3251 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3252 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3253 final int N = query.size(); 3254 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3255 .get(userId); 3256 // Get the list of persistent preferred activities that handle the intent 3257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3258 List<PersistentPreferredActivity> pprefs = ppir != null 3259 ? ppir.queryIntent(intent, resolvedType, 3260 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3261 : null; 3262 if (pprefs != null && pprefs.size() > 0) { 3263 final int M = pprefs.size(); 3264 for (int i=0; i<M; i++) { 3265 final PersistentPreferredActivity ppa = pprefs.get(i); 3266 if (DEBUG_PREFERRED || debug) { 3267 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3268 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3269 + "\n component=" + ppa.mComponent); 3270 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3271 } 3272 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3273 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3274 if (DEBUG_PREFERRED || debug) { 3275 Slog.v(TAG, "Found persistent preferred activity:"); 3276 if (ai != null) { 3277 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3278 } else { 3279 Slog.v(TAG, " null"); 3280 } 3281 } 3282 if (ai == null) { 3283 // This previously registered persistent preferred activity 3284 // component is no longer known. Ignore it and do NOT remove it. 3285 continue; 3286 } 3287 for (int j=0; j<N; j++) { 3288 final ResolveInfo ri = query.get(j); 3289 if (!ri.activityInfo.applicationInfo.packageName 3290 .equals(ai.applicationInfo.packageName)) { 3291 continue; 3292 } 3293 if (!ri.activityInfo.name.equals(ai.name)) { 3294 continue; 3295 } 3296 // Found a persistent preference that can handle the intent. 3297 if (DEBUG_PREFERRED || debug) { 3298 Slog.v(TAG, "Returning persistent preferred activity: " + 3299 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3300 } 3301 return ri; 3302 } 3303 } 3304 } 3305 return null; 3306 } 3307 3308 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3309 List<ResolveInfo> query, int priority, boolean always, 3310 boolean removeMatches, boolean debug, int userId) { 3311 if (!sUserManager.exists(userId)) return null; 3312 // writer 3313 synchronized (mPackages) { 3314 if (intent.getSelector() != null) { 3315 intent = intent.getSelector(); 3316 } 3317 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3318 3319 // Try to find a matching persistent preferred activity. 3320 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3321 debug, userId); 3322 3323 // If a persistent preferred activity matched, use it. 3324 if (pri != null) { 3325 return pri; 3326 } 3327 3328 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3329 // Get the list of preferred activities that handle the intent 3330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3331 List<PreferredActivity> prefs = pir != null 3332 ? pir.queryIntent(intent, resolvedType, 3333 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3334 : null; 3335 if (prefs != null && prefs.size() > 0) { 3336 boolean changed = false; 3337 try { 3338 // First figure out how good the original match set is. 3339 // We will only allow preferred activities that came 3340 // from the same match quality. 3341 int match = 0; 3342 3343 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3344 3345 final int N = query.size(); 3346 for (int j=0; j<N; j++) { 3347 final ResolveInfo ri = query.get(j); 3348 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3349 + ": 0x" + Integer.toHexString(match)); 3350 if (ri.match > match) { 3351 match = ri.match; 3352 } 3353 } 3354 3355 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3356 + Integer.toHexString(match)); 3357 3358 match &= IntentFilter.MATCH_CATEGORY_MASK; 3359 final int M = prefs.size(); 3360 for (int i=0; i<M; i++) { 3361 final PreferredActivity pa = prefs.get(i); 3362 if (DEBUG_PREFERRED || debug) { 3363 Slog.v(TAG, "Checking PreferredActivity ds=" 3364 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3365 + "\n component=" + pa.mPref.mComponent); 3366 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3367 } 3368 if (pa.mPref.mMatch != match) { 3369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3370 + Integer.toHexString(pa.mPref.mMatch)); 3371 continue; 3372 } 3373 // If it's not an "always" type preferred activity and that's what we're 3374 // looking for, skip it. 3375 if (always && !pa.mPref.mAlways) { 3376 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3377 continue; 3378 } 3379 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3380 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3381 if (DEBUG_PREFERRED || debug) { 3382 Slog.v(TAG, "Found preferred activity:"); 3383 if (ai != null) { 3384 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3385 } else { 3386 Slog.v(TAG, " null"); 3387 } 3388 } 3389 if (ai == null) { 3390 // This previously registered preferred activity 3391 // component is no longer known. Most likely an update 3392 // to the app was installed and in the new version this 3393 // component no longer exists. Clean it up by removing 3394 // it from the preferred activities list, and skip it. 3395 Slog.w(TAG, "Removing dangling preferred activity: " 3396 + pa.mPref.mComponent); 3397 pir.removeFilter(pa); 3398 changed = true; 3399 continue; 3400 } 3401 for (int j=0; j<N; j++) { 3402 final ResolveInfo ri = query.get(j); 3403 if (!ri.activityInfo.applicationInfo.packageName 3404 .equals(ai.applicationInfo.packageName)) { 3405 continue; 3406 } 3407 if (!ri.activityInfo.name.equals(ai.name)) { 3408 continue; 3409 } 3410 3411 if (removeMatches) { 3412 pir.removeFilter(pa); 3413 changed = true; 3414 if (DEBUG_PREFERRED) { 3415 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3416 } 3417 break; 3418 } 3419 3420 // Okay we found a previously set preferred or last chosen app. 3421 // If the result set is different from when this 3422 // was created, we need to clear it and re-ask the 3423 // user their preference, if we're looking for an "always" type entry. 3424 if (always && !pa.mPref.sameSet(query)) { 3425 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3426 + intent + " type " + resolvedType); 3427 if (DEBUG_PREFERRED) { 3428 Slog.v(TAG, "Removing preferred activity since set changed " 3429 + pa.mPref.mComponent); 3430 } 3431 pir.removeFilter(pa); 3432 // Re-add the filter as a "last chosen" entry (!always) 3433 PreferredActivity lastChosen = new PreferredActivity( 3434 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3435 pir.addFilter(lastChosen); 3436 changed = true; 3437 return null; 3438 } 3439 3440 // Yay! Either the set matched or we're looking for the last chosen 3441 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3442 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3443 return ri; 3444 } 3445 } 3446 } finally { 3447 if (changed) { 3448 if (DEBUG_PREFERRED) { 3449 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3450 } 3451 scheduleWritePackageRestrictionsLocked(userId); 3452 } 3453 } 3454 } 3455 } 3456 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3457 return null; 3458 } 3459 3460 /* 3461 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3462 */ 3463 @Override 3464 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3465 int targetUserId) { 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3468 List<CrossProfileIntentFilter> matches = 3469 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3470 if (matches != null) { 3471 int size = matches.size(); 3472 for (int i = 0; i < size; i++) { 3473 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3474 } 3475 } 3476 return false; 3477 } 3478 3479 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3480 String resolvedType, int userId) { 3481 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3482 if (resolver != null) { 3483 return resolver.queryIntent(intent, resolvedType, false, userId); 3484 } 3485 return null; 3486 } 3487 3488 @Override 3489 public List<ResolveInfo> queryIntentActivities(Intent intent, 3490 String resolvedType, int flags, int userId) { 3491 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3492 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3493 ComponentName comp = intent.getComponent(); 3494 if (comp == null) { 3495 if (intent.getSelector() != null) { 3496 intent = intent.getSelector(); 3497 comp = intent.getComponent(); 3498 } 3499 } 3500 3501 if (comp != null) { 3502 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3503 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3504 if (ai != null) { 3505 final ResolveInfo ri = new ResolveInfo(); 3506 ri.activityInfo = ai; 3507 list.add(ri); 3508 } 3509 return list; 3510 } 3511 3512 // reader 3513 synchronized (mPackages) { 3514 final String pkgName = intent.getPackage(); 3515 if (pkgName == null) { 3516 List<CrossProfileIntentFilter> matchingFilters = 3517 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3518 // Check for results that need to skip the current profile. 3519 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3520 resolvedType, flags, userId); 3521 if (resolveInfo != null) { 3522 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3523 result.add(resolveInfo); 3524 return filterIfNotPrimaryUser(result, userId); 3525 } 3526 // Check for cross profile results. 3527 resolveInfo = queryCrossProfileIntents( 3528 matchingFilters, intent, resolvedType, flags, userId); 3529 3530 // Check for results in the current profile. 3531 List<ResolveInfo> result = mActivities.queryIntent( 3532 intent, resolvedType, flags, userId); 3533 if (resolveInfo != null) { 3534 result.add(resolveInfo); 3535 Collections.sort(result, mResolvePrioritySorter); 3536 } 3537 return filterIfNotPrimaryUser(result, userId); 3538 } 3539 final PackageParser.Package pkg = mPackages.get(pkgName); 3540 if (pkg != null) { 3541 return filterIfNotPrimaryUser( 3542 mActivities.queryIntentForPackage( 3543 intent, resolvedType, flags, pkg.activities, userId), 3544 userId); 3545 } 3546 return new ArrayList<ResolveInfo>(); 3547 } 3548 } 3549 3550 /** 3551 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3552 * 3553 * @return filtered list 3554 */ 3555 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3556 if (userId == UserHandle.USER_OWNER) { 3557 return resolveInfos; 3558 } 3559 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3560 ResolveInfo info = resolveInfos.get(i); 3561 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3562 resolveInfos.remove(i); 3563 } 3564 } 3565 return resolveInfos; 3566 } 3567 3568 3569 private ResolveInfo querySkipCurrentProfileIntents( 3570 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3571 int flags, int sourceUserId) { 3572 if (matchingFilters != null) { 3573 int size = matchingFilters.size(); 3574 for (int i = 0; i < size; i ++) { 3575 CrossProfileIntentFilter filter = matchingFilters.get(i); 3576 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3577 // Checking if there are activities in the target user that can handle the 3578 // intent. 3579 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3580 flags, sourceUserId); 3581 if (resolveInfo != null) { 3582 return resolveInfo; 3583 } 3584 } 3585 } 3586 } 3587 return null; 3588 } 3589 3590 // Return matching ResolveInfo if any for skip current profile intent filters. 3591 private ResolveInfo queryCrossProfileIntents( 3592 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3593 int flags, int sourceUserId) { 3594 if (matchingFilters != null) { 3595 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3596 // match the same intent. For performance reasons, it is better not to 3597 // run queryIntent twice for the same userId 3598 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3599 int size = matchingFilters.size(); 3600 for (int i = 0; i < size; i++) { 3601 CrossProfileIntentFilter filter = matchingFilters.get(i); 3602 int targetUserId = filter.getTargetUserId(); 3603 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3604 && !alreadyTriedUserIds.get(targetUserId)) { 3605 // Checking if there are activities in the target user that can handle the 3606 // intent. 3607 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3608 flags, sourceUserId); 3609 if (resolveInfo != null) return resolveInfo; 3610 alreadyTriedUserIds.put(targetUserId, true); 3611 } 3612 } 3613 } 3614 return null; 3615 } 3616 3617 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3618 String resolvedType, int flags, int sourceUserId) { 3619 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3620 resolvedType, flags, filter.getTargetUserId()); 3621 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3622 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3623 } 3624 return null; 3625 } 3626 3627 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3628 int sourceUserId, int targetUserId) { 3629 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3630 String className; 3631 if (targetUserId == UserHandle.USER_OWNER) { 3632 className = FORWARD_INTENT_TO_USER_OWNER; 3633 } else { 3634 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3635 } 3636 ComponentName forwardingActivityComponentName = new ComponentName( 3637 mAndroidApplication.packageName, className); 3638 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3639 sourceUserId); 3640 if (targetUserId == UserHandle.USER_OWNER) { 3641 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3642 forwardingResolveInfo.noResourceId = true; 3643 } 3644 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3645 forwardingResolveInfo.priority = 0; 3646 forwardingResolveInfo.preferredOrder = 0; 3647 forwardingResolveInfo.match = 0; 3648 forwardingResolveInfo.isDefault = true; 3649 forwardingResolveInfo.filter = filter; 3650 forwardingResolveInfo.targetUserId = targetUserId; 3651 return forwardingResolveInfo; 3652 } 3653 3654 @Override 3655 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3656 Intent[] specifics, String[] specificTypes, Intent intent, 3657 String resolvedType, int flags, int userId) { 3658 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3659 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3660 false, "query intent activity options"); 3661 final String resultsAction = intent.getAction(); 3662 3663 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3664 | PackageManager.GET_RESOLVED_FILTER, userId); 3665 3666 if (DEBUG_INTENT_MATCHING) { 3667 Log.v(TAG, "Query " + intent + ": " + results); 3668 } 3669 3670 int specificsPos = 0; 3671 int N; 3672 3673 // todo: note that the algorithm used here is O(N^2). This 3674 // isn't a problem in our current environment, but if we start running 3675 // into situations where we have more than 5 or 10 matches then this 3676 // should probably be changed to something smarter... 3677 3678 // First we go through and resolve each of the specific items 3679 // that were supplied, taking care of removing any corresponding 3680 // duplicate items in the generic resolve list. 3681 if (specifics != null) { 3682 for (int i=0; i<specifics.length; i++) { 3683 final Intent sintent = specifics[i]; 3684 if (sintent == null) { 3685 continue; 3686 } 3687 3688 if (DEBUG_INTENT_MATCHING) { 3689 Log.v(TAG, "Specific #" + i + ": " + sintent); 3690 } 3691 3692 String action = sintent.getAction(); 3693 if (resultsAction != null && resultsAction.equals(action)) { 3694 // If this action was explicitly requested, then don't 3695 // remove things that have it. 3696 action = null; 3697 } 3698 3699 ResolveInfo ri = null; 3700 ActivityInfo ai = null; 3701 3702 ComponentName comp = sintent.getComponent(); 3703 if (comp == null) { 3704 ri = resolveIntent( 3705 sintent, 3706 specificTypes != null ? specificTypes[i] : null, 3707 flags, userId); 3708 if (ri == null) { 3709 continue; 3710 } 3711 if (ri == mResolveInfo) { 3712 // ACK! Must do something better with this. 3713 } 3714 ai = ri.activityInfo; 3715 comp = new ComponentName(ai.applicationInfo.packageName, 3716 ai.name); 3717 } else { 3718 ai = getActivityInfo(comp, flags, userId); 3719 if (ai == null) { 3720 continue; 3721 } 3722 } 3723 3724 // Look for any generic query activities that are duplicates 3725 // of this specific one, and remove them from the results. 3726 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3727 N = results.size(); 3728 int j; 3729 for (j=specificsPos; j<N; j++) { 3730 ResolveInfo sri = results.get(j); 3731 if ((sri.activityInfo.name.equals(comp.getClassName()) 3732 && sri.activityInfo.applicationInfo.packageName.equals( 3733 comp.getPackageName())) 3734 || (action != null && sri.filter.matchAction(action))) { 3735 results.remove(j); 3736 if (DEBUG_INTENT_MATCHING) Log.v( 3737 TAG, "Removing duplicate item from " + j 3738 + " due to specific " + specificsPos); 3739 if (ri == null) { 3740 ri = sri; 3741 } 3742 j--; 3743 N--; 3744 } 3745 } 3746 3747 // Add this specific item to its proper place. 3748 if (ri == null) { 3749 ri = new ResolveInfo(); 3750 ri.activityInfo = ai; 3751 } 3752 results.add(specificsPos, ri); 3753 ri.specificIndex = i; 3754 specificsPos++; 3755 } 3756 } 3757 3758 // Now we go through the remaining generic results and remove any 3759 // duplicate actions that are found here. 3760 N = results.size(); 3761 for (int i=specificsPos; i<N-1; i++) { 3762 final ResolveInfo rii = results.get(i); 3763 if (rii.filter == null) { 3764 continue; 3765 } 3766 3767 // Iterate over all of the actions of this result's intent 3768 // filter... typically this should be just one. 3769 final Iterator<String> it = rii.filter.actionsIterator(); 3770 if (it == null) { 3771 continue; 3772 } 3773 while (it.hasNext()) { 3774 final String action = it.next(); 3775 if (resultsAction != null && resultsAction.equals(action)) { 3776 // If this action was explicitly requested, then don't 3777 // remove things that have it. 3778 continue; 3779 } 3780 for (int j=i+1; j<N; j++) { 3781 final ResolveInfo rij = results.get(j); 3782 if (rij.filter != null && rij.filter.hasAction(action)) { 3783 results.remove(j); 3784 if (DEBUG_INTENT_MATCHING) Log.v( 3785 TAG, "Removing duplicate item from " + j 3786 + " due to action " + action + " at " + i); 3787 j--; 3788 N--; 3789 } 3790 } 3791 } 3792 3793 // If the caller didn't request filter information, drop it now 3794 // so we don't have to marshall/unmarshall it. 3795 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3796 rii.filter = null; 3797 } 3798 } 3799 3800 // Filter out the caller activity if so requested. 3801 if (caller != null) { 3802 N = results.size(); 3803 for (int i=0; i<N; i++) { 3804 ActivityInfo ainfo = results.get(i).activityInfo; 3805 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3806 && caller.getClassName().equals(ainfo.name)) { 3807 results.remove(i); 3808 break; 3809 } 3810 } 3811 } 3812 3813 // If the caller didn't request filter information, 3814 // drop them now so we don't have to 3815 // marshall/unmarshall it. 3816 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3817 N = results.size(); 3818 for (int i=0; i<N; i++) { 3819 results.get(i).filter = null; 3820 } 3821 } 3822 3823 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3824 return results; 3825 } 3826 3827 @Override 3828 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3829 int userId) { 3830 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3831 ComponentName comp = intent.getComponent(); 3832 if (comp == null) { 3833 if (intent.getSelector() != null) { 3834 intent = intent.getSelector(); 3835 comp = intent.getComponent(); 3836 } 3837 } 3838 if (comp != null) { 3839 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3840 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3841 if (ai != null) { 3842 ResolveInfo ri = new ResolveInfo(); 3843 ri.activityInfo = ai; 3844 list.add(ri); 3845 } 3846 return list; 3847 } 3848 3849 // reader 3850 synchronized (mPackages) { 3851 String pkgName = intent.getPackage(); 3852 if (pkgName == null) { 3853 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3854 } 3855 final PackageParser.Package pkg = mPackages.get(pkgName); 3856 if (pkg != null) { 3857 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3858 userId); 3859 } 3860 return null; 3861 } 3862 } 3863 3864 @Override 3865 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3866 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3867 if (!sUserManager.exists(userId)) return null; 3868 if (query != null) { 3869 if (query.size() >= 1) { 3870 // If there is more than one service with the same priority, 3871 // just arbitrarily pick the first one. 3872 return query.get(0); 3873 } 3874 } 3875 return null; 3876 } 3877 3878 @Override 3879 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3880 int userId) { 3881 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3882 ComponentName comp = intent.getComponent(); 3883 if (comp == null) { 3884 if (intent.getSelector() != null) { 3885 intent = intent.getSelector(); 3886 comp = intent.getComponent(); 3887 } 3888 } 3889 if (comp != null) { 3890 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3891 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3892 if (si != null) { 3893 final ResolveInfo ri = new ResolveInfo(); 3894 ri.serviceInfo = si; 3895 list.add(ri); 3896 } 3897 return list; 3898 } 3899 3900 // reader 3901 synchronized (mPackages) { 3902 String pkgName = intent.getPackage(); 3903 if (pkgName == null) { 3904 return mServices.queryIntent(intent, resolvedType, flags, userId); 3905 } 3906 final PackageParser.Package pkg = mPackages.get(pkgName); 3907 if (pkg != null) { 3908 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3909 userId); 3910 } 3911 return null; 3912 } 3913 } 3914 3915 @Override 3916 public List<ResolveInfo> queryIntentContentProviders( 3917 Intent intent, String resolvedType, int flags, int userId) { 3918 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3919 ComponentName comp = intent.getComponent(); 3920 if (comp == null) { 3921 if (intent.getSelector() != null) { 3922 intent = intent.getSelector(); 3923 comp = intent.getComponent(); 3924 } 3925 } 3926 if (comp != null) { 3927 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3928 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3929 if (pi != null) { 3930 final ResolveInfo ri = new ResolveInfo(); 3931 ri.providerInfo = pi; 3932 list.add(ri); 3933 } 3934 return list; 3935 } 3936 3937 // reader 3938 synchronized (mPackages) { 3939 String pkgName = intent.getPackage(); 3940 if (pkgName == null) { 3941 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3942 } 3943 final PackageParser.Package pkg = mPackages.get(pkgName); 3944 if (pkg != null) { 3945 return mProviders.queryIntentForPackage( 3946 intent, resolvedType, flags, pkg.providers, userId); 3947 } 3948 return null; 3949 } 3950 } 3951 3952 @Override 3953 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3954 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3955 3956 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3957 3958 // writer 3959 synchronized (mPackages) { 3960 ArrayList<PackageInfo> list; 3961 if (listUninstalled) { 3962 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3963 for (PackageSetting ps : mSettings.mPackages.values()) { 3964 PackageInfo pi; 3965 if (ps.pkg != null) { 3966 pi = generatePackageInfo(ps.pkg, flags, userId); 3967 } else { 3968 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3969 } 3970 if (pi != null) { 3971 list.add(pi); 3972 } 3973 } 3974 } else { 3975 list = new ArrayList<PackageInfo>(mPackages.size()); 3976 for (PackageParser.Package p : mPackages.values()) { 3977 PackageInfo pi = generatePackageInfo(p, flags, userId); 3978 if (pi != null) { 3979 list.add(pi); 3980 } 3981 } 3982 } 3983 3984 return new ParceledListSlice<PackageInfo>(list); 3985 } 3986 } 3987 3988 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3989 String[] permissions, boolean[] tmp, int flags, int userId) { 3990 int numMatch = 0; 3991 final PermissionsState permissionsState = ps.getPermissionsState(); 3992 for (int i=0; i<permissions.length; i++) { 3993 final String permission = permissions[i]; 3994 if (permissionsState.hasPermission(permission, userId)) { 3995 tmp[i] = true; 3996 numMatch++; 3997 } else { 3998 tmp[i] = false; 3999 } 4000 } 4001 if (numMatch == 0) { 4002 return; 4003 } 4004 PackageInfo pi; 4005 if (ps.pkg != null) { 4006 pi = generatePackageInfo(ps.pkg, flags, userId); 4007 } else { 4008 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4009 } 4010 // The above might return null in cases of uninstalled apps or install-state 4011 // skew across users/profiles. 4012 if (pi != null) { 4013 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4014 if (numMatch == permissions.length) { 4015 pi.requestedPermissions = permissions; 4016 } else { 4017 pi.requestedPermissions = new String[numMatch]; 4018 numMatch = 0; 4019 for (int i=0; i<permissions.length; i++) { 4020 if (tmp[i]) { 4021 pi.requestedPermissions[numMatch] = permissions[i]; 4022 numMatch++; 4023 } 4024 } 4025 } 4026 } 4027 list.add(pi); 4028 } 4029 } 4030 4031 @Override 4032 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4033 String[] permissions, int flags, int userId) { 4034 if (!sUserManager.exists(userId)) return null; 4035 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4036 4037 // writer 4038 synchronized (mPackages) { 4039 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4040 boolean[] tmpBools = new boolean[permissions.length]; 4041 if (listUninstalled) { 4042 for (PackageSetting ps : mSettings.mPackages.values()) { 4043 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4044 } 4045 } else { 4046 for (PackageParser.Package pkg : mPackages.values()) { 4047 PackageSetting ps = (PackageSetting)pkg.mExtras; 4048 if (ps != null) { 4049 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4050 userId); 4051 } 4052 } 4053 } 4054 4055 return new ParceledListSlice<PackageInfo>(list); 4056 } 4057 } 4058 4059 @Override 4060 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4061 if (!sUserManager.exists(userId)) return null; 4062 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4063 4064 // writer 4065 synchronized (mPackages) { 4066 ArrayList<ApplicationInfo> list; 4067 if (listUninstalled) { 4068 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4069 for (PackageSetting ps : mSettings.mPackages.values()) { 4070 ApplicationInfo ai; 4071 if (ps.pkg != null) { 4072 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4073 ps.readUserState(userId), userId); 4074 } else { 4075 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4076 } 4077 if (ai != null) { 4078 list.add(ai); 4079 } 4080 } 4081 } else { 4082 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4083 for (PackageParser.Package p : mPackages.values()) { 4084 if (p.mExtras != null) { 4085 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4086 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4087 if (ai != null) { 4088 list.add(ai); 4089 } 4090 } 4091 } 4092 } 4093 4094 return new ParceledListSlice<ApplicationInfo>(list); 4095 } 4096 } 4097 4098 public List<ApplicationInfo> getPersistentApplications(int flags) { 4099 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4100 4101 // reader 4102 synchronized (mPackages) { 4103 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4104 final int userId = UserHandle.getCallingUserId(); 4105 while (i.hasNext()) { 4106 final PackageParser.Package p = i.next(); 4107 if (p.applicationInfo != null 4108 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4109 && (!mSafeMode || isSystemApp(p))) { 4110 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4111 if (ps != null) { 4112 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4113 ps.readUserState(userId), userId); 4114 if (ai != null) { 4115 finalList.add(ai); 4116 } 4117 } 4118 } 4119 } 4120 } 4121 4122 return finalList; 4123 } 4124 4125 @Override 4126 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4127 if (!sUserManager.exists(userId)) return null; 4128 // reader 4129 synchronized (mPackages) { 4130 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4131 PackageSetting ps = provider != null 4132 ? mSettings.mPackages.get(provider.owner.packageName) 4133 : null; 4134 return ps != null 4135 && mSettings.isEnabledLPr(provider.info, flags, userId) 4136 && (!mSafeMode || (provider.info.applicationInfo.flags 4137 &ApplicationInfo.FLAG_SYSTEM) != 0) 4138 ? PackageParser.generateProviderInfo(provider, flags, 4139 ps.readUserState(userId), userId) 4140 : null; 4141 } 4142 } 4143 4144 /** 4145 * @deprecated 4146 */ 4147 @Deprecated 4148 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4149 // reader 4150 synchronized (mPackages) { 4151 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4152 .entrySet().iterator(); 4153 final int userId = UserHandle.getCallingUserId(); 4154 while (i.hasNext()) { 4155 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4156 PackageParser.Provider p = entry.getValue(); 4157 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4158 4159 if (ps != null && p.syncable 4160 && (!mSafeMode || (p.info.applicationInfo.flags 4161 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4162 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4163 ps.readUserState(userId), userId); 4164 if (info != null) { 4165 outNames.add(entry.getKey()); 4166 outInfo.add(info); 4167 } 4168 } 4169 } 4170 } 4171 } 4172 4173 @Override 4174 public List<ProviderInfo> queryContentProviders(String processName, 4175 int uid, int flags) { 4176 ArrayList<ProviderInfo> finalList = null; 4177 // reader 4178 synchronized (mPackages) { 4179 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4180 final int userId = processName != null ? 4181 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4182 while (i.hasNext()) { 4183 final PackageParser.Provider p = i.next(); 4184 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4185 if (ps != null && p.info.authority != null 4186 && (processName == null 4187 || (p.info.processName.equals(processName) 4188 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4189 && mSettings.isEnabledLPr(p.info, flags, userId) 4190 && (!mSafeMode 4191 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4192 if (finalList == null) { 4193 finalList = new ArrayList<ProviderInfo>(3); 4194 } 4195 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4196 ps.readUserState(userId), userId); 4197 if (info != null) { 4198 finalList.add(info); 4199 } 4200 } 4201 } 4202 } 4203 4204 if (finalList != null) { 4205 Collections.sort(finalList, mProviderInitOrderSorter); 4206 } 4207 4208 return finalList; 4209 } 4210 4211 @Override 4212 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4213 int flags) { 4214 // reader 4215 synchronized (mPackages) { 4216 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4217 return PackageParser.generateInstrumentationInfo(i, flags); 4218 } 4219 } 4220 4221 @Override 4222 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4223 int flags) { 4224 ArrayList<InstrumentationInfo> finalList = 4225 new ArrayList<InstrumentationInfo>(); 4226 4227 // reader 4228 synchronized (mPackages) { 4229 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4230 while (i.hasNext()) { 4231 final PackageParser.Instrumentation p = i.next(); 4232 if (targetPackage == null 4233 || targetPackage.equals(p.info.targetPackage)) { 4234 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4235 flags); 4236 if (ii != null) { 4237 finalList.add(ii); 4238 } 4239 } 4240 } 4241 } 4242 4243 return finalList; 4244 } 4245 4246 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4247 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4248 if (overlays == null) { 4249 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4250 return; 4251 } 4252 for (PackageParser.Package opkg : overlays.values()) { 4253 // Not much to do if idmap fails: we already logged the error 4254 // and we certainly don't want to abort installation of pkg simply 4255 // because an overlay didn't fit properly. For these reasons, 4256 // ignore the return value of createIdmapForPackagePairLI. 4257 createIdmapForPackagePairLI(pkg, opkg); 4258 } 4259 } 4260 4261 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4262 PackageParser.Package opkg) { 4263 if (!opkg.mTrustedOverlay) { 4264 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4265 opkg.baseCodePath + ": overlay not trusted"); 4266 return false; 4267 } 4268 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4269 if (overlaySet == null) { 4270 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4271 opkg.baseCodePath + " but target package has no known overlays"); 4272 return false; 4273 } 4274 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4275 // TODO: generate idmap for split APKs 4276 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4277 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4278 + opkg.baseCodePath); 4279 return false; 4280 } 4281 PackageParser.Package[] overlayArray = 4282 overlaySet.values().toArray(new PackageParser.Package[0]); 4283 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4284 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4285 return p1.mOverlayPriority - p2.mOverlayPriority; 4286 } 4287 }; 4288 Arrays.sort(overlayArray, cmp); 4289 4290 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4291 int i = 0; 4292 for (PackageParser.Package p : overlayArray) { 4293 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4294 } 4295 return true; 4296 } 4297 4298 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4299 final File[] files = dir.listFiles(); 4300 if (ArrayUtils.isEmpty(files)) { 4301 Log.d(TAG, "No files in app dir " + dir); 4302 return; 4303 } 4304 4305 if (DEBUG_PACKAGE_SCANNING) { 4306 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4307 + " flags=0x" + Integer.toHexString(parseFlags)); 4308 } 4309 4310 for (File file : files) { 4311 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4312 && !PackageInstallerService.isStageName(file.getName()); 4313 if (!isPackage) { 4314 // Ignore entries which are not packages 4315 continue; 4316 } 4317 try { 4318 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4319 scanFlags, currentTime, null); 4320 } catch (PackageManagerException e) { 4321 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4322 4323 // Delete invalid userdata apps 4324 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4325 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4326 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4327 if (file.isDirectory()) { 4328 FileUtils.deleteContents(file); 4329 } 4330 file.delete(); 4331 } 4332 } 4333 } 4334 } 4335 4336 private static File getSettingsProblemFile() { 4337 File dataDir = Environment.getDataDirectory(); 4338 File systemDir = new File(dataDir, "system"); 4339 File fname = new File(systemDir, "uiderrors.txt"); 4340 return fname; 4341 } 4342 4343 static void reportSettingsProblem(int priority, String msg) { 4344 logCriticalInfo(priority, msg); 4345 } 4346 4347 static void logCriticalInfo(int priority, String msg) { 4348 Slog.println(priority, TAG, msg); 4349 EventLogTags.writePmCriticalInfo(msg); 4350 try { 4351 File fname = getSettingsProblemFile(); 4352 FileOutputStream out = new FileOutputStream(fname, true); 4353 PrintWriter pw = new FastPrintWriter(out); 4354 SimpleDateFormat formatter = new SimpleDateFormat(); 4355 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4356 pw.println(dateString + ": " + msg); 4357 pw.close(); 4358 FileUtils.setPermissions( 4359 fname.toString(), 4360 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4361 -1, -1); 4362 } catch (java.io.IOException e) { 4363 } 4364 } 4365 4366 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4367 PackageParser.Package pkg, File srcFile, int parseFlags) 4368 throws PackageManagerException { 4369 if (ps != null 4370 && ps.codePath.equals(srcFile) 4371 && ps.timeStamp == srcFile.lastModified() 4372 && !isCompatSignatureUpdateNeeded(pkg) 4373 && !isRecoverSignatureUpdateNeeded(pkg)) { 4374 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4375 if (ps.signatures.mSignatures != null 4376 && ps.signatures.mSignatures.length != 0 4377 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4378 // Optimization: reuse the existing cached certificates 4379 // if the package appears to be unchanged. 4380 pkg.mSignatures = ps.signatures.mSignatures; 4381 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4382 synchronized (mPackages) { 4383 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4384 } 4385 return; 4386 } 4387 4388 Slog.w(TAG, "PackageSetting for " + ps.name 4389 + " is missing signatures. Collecting certs again to recover them."); 4390 } else { 4391 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4392 } 4393 4394 try { 4395 pp.collectCertificates(pkg, parseFlags); 4396 pp.collectManifestDigest(pkg); 4397 } catch (PackageParserException e) { 4398 throw PackageManagerException.from(e); 4399 } 4400 } 4401 4402 /* 4403 * Scan a package and return the newly parsed package. 4404 * Returns null in case of errors and the error code is stored in mLastScanError 4405 */ 4406 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4407 long currentTime, UserHandle user) throws PackageManagerException { 4408 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4409 parseFlags |= mDefParseFlags; 4410 PackageParser pp = new PackageParser(); 4411 pp.setSeparateProcesses(mSeparateProcesses); 4412 pp.setOnlyCoreApps(mOnlyCore); 4413 pp.setDisplayMetrics(mMetrics); 4414 4415 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4416 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4417 } 4418 4419 final PackageParser.Package pkg; 4420 try { 4421 pkg = pp.parsePackage(scanFile, parseFlags); 4422 } catch (PackageParserException e) { 4423 throw PackageManagerException.from(e); 4424 } 4425 4426 PackageSetting ps = null; 4427 PackageSetting updatedPkg; 4428 // reader 4429 synchronized (mPackages) { 4430 // Look to see if we already know about this package. 4431 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4432 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4433 // This package has been renamed to its original name. Let's 4434 // use that. 4435 ps = mSettings.peekPackageLPr(oldName); 4436 } 4437 // If there was no original package, see one for the real package name. 4438 if (ps == null) { 4439 ps = mSettings.peekPackageLPr(pkg.packageName); 4440 } 4441 // Check to see if this package could be hiding/updating a system 4442 // package. Must look for it either under the original or real 4443 // package name depending on our state. 4444 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4445 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4446 } 4447 boolean updatedPkgBetter = false; 4448 // First check if this is a system package that may involve an update 4449 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4450 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4451 // it needs to drop FLAG_PRIVILEGED. 4452 if (locationIsPrivileged(scanFile)) { 4453 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4454 } else { 4455 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4456 } 4457 4458 if (ps != null && !ps.codePath.equals(scanFile)) { 4459 // The path has changed from what was last scanned... check the 4460 // version of the new path against what we have stored to determine 4461 // what to do. 4462 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4463 if (pkg.mVersionCode <= ps.versionCode) { 4464 // The system package has been updated and the code path does not match 4465 // Ignore entry. Skip it. 4466 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4467 + " ignored: updated version " + ps.versionCode 4468 + " better than this " + pkg.mVersionCode); 4469 if (!updatedPkg.codePath.equals(scanFile)) { 4470 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4471 + ps.name + " changing from " + updatedPkg.codePathString 4472 + " to " + scanFile); 4473 updatedPkg.codePath = scanFile; 4474 updatedPkg.codePathString = scanFile.toString(); 4475 updatedPkg.resourcePath = scanFile; 4476 updatedPkg.resourcePathString = scanFile.toString(); 4477 } 4478 updatedPkg.pkg = pkg; 4479 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4480 } else { 4481 // The current app on the system partition is better than 4482 // what we have updated to on the data partition; switch 4483 // back to the system partition version. 4484 // At this point, its safely assumed that package installation for 4485 // apps in system partition will go through. If not there won't be a working 4486 // version of the app 4487 // writer 4488 synchronized (mPackages) { 4489 // Just remove the loaded entries from package lists. 4490 mPackages.remove(ps.name); 4491 } 4492 4493 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4494 + " reverting from " + ps.codePathString 4495 + ": new version " + pkg.mVersionCode 4496 + " better than installed " + ps.versionCode); 4497 4498 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4499 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4500 getAppDexInstructionSets(ps)); 4501 synchronized (mInstallLock) { 4502 args.cleanUpResourcesLI(); 4503 } 4504 synchronized (mPackages) { 4505 mSettings.enableSystemPackageLPw(ps.name); 4506 } 4507 updatedPkgBetter = true; 4508 } 4509 } 4510 } 4511 4512 if (updatedPkg != null) { 4513 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4514 // initially 4515 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4516 4517 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4518 // flag set initially 4519 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4520 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4521 } 4522 } 4523 4524 // Verify certificates against what was last scanned 4525 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4526 4527 /* 4528 * A new system app appeared, but we already had a non-system one of the 4529 * same name installed earlier. 4530 */ 4531 boolean shouldHideSystemApp = false; 4532 if (updatedPkg == null && ps != null 4533 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4534 /* 4535 * Check to make sure the signatures match first. If they don't, 4536 * wipe the installed application and its data. 4537 */ 4538 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4539 != PackageManager.SIGNATURE_MATCH) { 4540 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4541 + " signatures don't match existing userdata copy; removing"); 4542 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4543 ps = null; 4544 } else { 4545 /* 4546 * If the newly-added system app is an older version than the 4547 * already installed version, hide it. It will be scanned later 4548 * and re-added like an update. 4549 */ 4550 if (pkg.mVersionCode <= ps.versionCode) { 4551 shouldHideSystemApp = true; 4552 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4553 + " but new version " + pkg.mVersionCode + " better than installed " 4554 + ps.versionCode + "; hiding system"); 4555 } else { 4556 /* 4557 * The newly found system app is a newer version that the 4558 * one previously installed. Simply remove the 4559 * already-installed application and replace it with our own 4560 * while keeping the application data. 4561 */ 4562 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4563 + " reverting from " + ps.codePathString + ": new version " 4564 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4565 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4566 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4567 getAppDexInstructionSets(ps)); 4568 synchronized (mInstallLock) { 4569 args.cleanUpResourcesLI(); 4570 } 4571 } 4572 } 4573 } 4574 4575 // The apk is forward locked (not public) if its code and resources 4576 // are kept in different files. (except for app in either system or 4577 // vendor path). 4578 // TODO grab this value from PackageSettings 4579 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4580 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4581 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4582 } 4583 } 4584 4585 // TODO: extend to support forward-locked splits 4586 String resourcePath = null; 4587 String baseResourcePath = null; 4588 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4589 if (ps != null && ps.resourcePathString != null) { 4590 resourcePath = ps.resourcePathString; 4591 baseResourcePath = ps.resourcePathString; 4592 } else { 4593 // Should not happen at all. Just log an error. 4594 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4595 } 4596 } else { 4597 resourcePath = pkg.codePath; 4598 baseResourcePath = pkg.baseCodePath; 4599 } 4600 4601 // Set application objects path explicitly. 4602 pkg.applicationInfo.setCodePath(pkg.codePath); 4603 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4604 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4605 pkg.applicationInfo.setResourcePath(resourcePath); 4606 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4607 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4608 4609 // Note that we invoke the following method only if we are about to unpack an application 4610 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4611 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4612 4613 /* 4614 * If the system app should be overridden by a previously installed 4615 * data, hide the system app now and let the /data/app scan pick it up 4616 * again. 4617 */ 4618 if (shouldHideSystemApp) { 4619 synchronized (mPackages) { 4620 /* 4621 * We have to grant systems permissions before we hide, because 4622 * grantPermissions will assume the package update is trying to 4623 * expand its permissions. 4624 */ 4625 grantPermissionsLPw(pkg, true, pkg.packageName); 4626 mSettings.disableSystemPackageLPw(pkg.packageName); 4627 } 4628 } 4629 4630 return scannedPkg; 4631 } 4632 4633 private static String fixProcessName(String defProcessName, 4634 String processName, int uid) { 4635 if (processName == null) { 4636 return defProcessName; 4637 } 4638 return processName; 4639 } 4640 4641 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4642 throws PackageManagerException { 4643 if (pkgSetting.signatures.mSignatures != null) { 4644 // Already existing package. Make sure signatures match 4645 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4646 == PackageManager.SIGNATURE_MATCH; 4647 if (!match) { 4648 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4649 == PackageManager.SIGNATURE_MATCH; 4650 } 4651 if (!match) { 4652 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4653 == PackageManager.SIGNATURE_MATCH; 4654 } 4655 if (!match) { 4656 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4657 + pkg.packageName + " signatures do not match the " 4658 + "previously installed version; ignoring!"); 4659 } 4660 } 4661 4662 // Check for shared user signatures 4663 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4664 // Already existing package. Make sure signatures match 4665 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4666 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4667 if (!match) { 4668 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4669 == PackageManager.SIGNATURE_MATCH; 4670 } 4671 if (!match) { 4672 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4673 == PackageManager.SIGNATURE_MATCH; 4674 } 4675 if (!match) { 4676 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4677 "Package " + pkg.packageName 4678 + " has no signatures that match those in shared user " 4679 + pkgSetting.sharedUser.name + "; ignoring!"); 4680 } 4681 } 4682 } 4683 4684 /** 4685 * Enforces that only the system UID or root's UID can call a method exposed 4686 * via Binder. 4687 * 4688 * @param message used as message if SecurityException is thrown 4689 * @throws SecurityException if the caller is not system or root 4690 */ 4691 private static final void enforceSystemOrRoot(String message) { 4692 final int uid = Binder.getCallingUid(); 4693 if (uid != Process.SYSTEM_UID && uid != 0) { 4694 throw new SecurityException(message); 4695 } 4696 } 4697 4698 @Override 4699 public void performBootDexOpt() { 4700 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4701 4702 // Before everything else, see whether we need to fstrim. 4703 try { 4704 IMountService ms = PackageHelper.getMountService(); 4705 if (ms != null) { 4706 final boolean isUpgrade = isUpgrade(); 4707 boolean doTrim = isUpgrade; 4708 if (doTrim) { 4709 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4710 } else { 4711 final long interval = android.provider.Settings.Global.getLong( 4712 mContext.getContentResolver(), 4713 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4714 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4715 if (interval > 0) { 4716 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4717 if (timeSinceLast > interval) { 4718 doTrim = true; 4719 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4720 + "; running immediately"); 4721 } 4722 } 4723 } 4724 if (doTrim) { 4725 if (!isFirstBoot()) { 4726 try { 4727 ActivityManagerNative.getDefault().showBootMessage( 4728 mContext.getResources().getString( 4729 R.string.android_upgrading_fstrim), true); 4730 } catch (RemoteException e) { 4731 } 4732 } 4733 ms.runMaintenance(); 4734 } 4735 } else { 4736 Slog.e(TAG, "Mount service unavailable!"); 4737 } 4738 } catch (RemoteException e) { 4739 // Can't happen; MountService is local 4740 } 4741 4742 final ArraySet<PackageParser.Package> pkgs; 4743 synchronized (mPackages) { 4744 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4745 } 4746 4747 if (pkgs != null) { 4748 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4749 // in case the device runs out of space. 4750 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4751 // Give priority to core apps. 4752 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4753 PackageParser.Package pkg = it.next(); 4754 if (pkg.coreApp) { 4755 if (DEBUG_DEXOPT) { 4756 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4757 } 4758 sortedPkgs.add(pkg); 4759 it.remove(); 4760 } 4761 } 4762 // Give priority to system apps that listen for pre boot complete. 4763 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4764 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4765 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4766 PackageParser.Package pkg = it.next(); 4767 if (pkgNames.contains(pkg.packageName)) { 4768 if (DEBUG_DEXOPT) { 4769 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4770 } 4771 sortedPkgs.add(pkg); 4772 it.remove(); 4773 } 4774 } 4775 // Give priority to system apps. 4776 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4777 PackageParser.Package pkg = it.next(); 4778 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4779 if (DEBUG_DEXOPT) { 4780 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4781 } 4782 sortedPkgs.add(pkg); 4783 it.remove(); 4784 } 4785 } 4786 // Give priority to updated system apps. 4787 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4788 PackageParser.Package pkg = it.next(); 4789 if (isUpdatedSystemApp(pkg)) { 4790 if (DEBUG_DEXOPT) { 4791 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4792 } 4793 sortedPkgs.add(pkg); 4794 it.remove(); 4795 } 4796 } 4797 // Give priority to apps that listen for boot complete. 4798 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4799 pkgNames = getPackageNamesForIntent(intent); 4800 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4801 PackageParser.Package pkg = it.next(); 4802 if (pkgNames.contains(pkg.packageName)) { 4803 if (DEBUG_DEXOPT) { 4804 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4805 } 4806 sortedPkgs.add(pkg); 4807 it.remove(); 4808 } 4809 } 4810 // Filter out packages that aren't recently used. 4811 filterRecentlyUsedApps(pkgs); 4812 // Add all remaining apps. 4813 for (PackageParser.Package pkg : pkgs) { 4814 if (DEBUG_DEXOPT) { 4815 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4816 } 4817 sortedPkgs.add(pkg); 4818 } 4819 4820 // If we want to be lazy, filter everything that wasn't recently used. 4821 if (mLazyDexOpt) { 4822 filterRecentlyUsedApps(sortedPkgs); 4823 } 4824 4825 int i = 0; 4826 int total = sortedPkgs.size(); 4827 File dataDir = Environment.getDataDirectory(); 4828 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4829 if (lowThreshold == 0) { 4830 throw new IllegalStateException("Invalid low memory threshold"); 4831 } 4832 for (PackageParser.Package pkg : sortedPkgs) { 4833 long usableSpace = dataDir.getUsableSpace(); 4834 if (usableSpace < lowThreshold) { 4835 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4836 break; 4837 } 4838 performBootDexOpt(pkg, ++i, total); 4839 } 4840 } 4841 } 4842 4843 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4844 // Filter out packages that aren't recently used. 4845 // 4846 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4847 // should do a full dexopt. 4848 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4849 int total = pkgs.size(); 4850 int skipped = 0; 4851 long now = System.currentTimeMillis(); 4852 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4853 PackageParser.Package pkg = i.next(); 4854 long then = pkg.mLastPackageUsageTimeInMills; 4855 if (then + mDexOptLRUThresholdInMills < now) { 4856 if (DEBUG_DEXOPT) { 4857 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4858 ((then == 0) ? "never" : new Date(then))); 4859 } 4860 i.remove(); 4861 skipped++; 4862 } 4863 } 4864 if (DEBUG_DEXOPT) { 4865 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4866 } 4867 } 4868 } 4869 4870 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4871 List<ResolveInfo> ris = null; 4872 try { 4873 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4874 intent, null, 0, UserHandle.USER_OWNER); 4875 } catch (RemoteException e) { 4876 } 4877 ArraySet<String> pkgNames = new ArraySet<String>(); 4878 if (ris != null) { 4879 for (ResolveInfo ri : ris) { 4880 pkgNames.add(ri.activityInfo.packageName); 4881 } 4882 } 4883 return pkgNames; 4884 } 4885 4886 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4887 if (DEBUG_DEXOPT) { 4888 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4889 } 4890 if (!isFirstBoot()) { 4891 try { 4892 ActivityManagerNative.getDefault().showBootMessage( 4893 mContext.getResources().getString(R.string.android_upgrading_apk, 4894 curr, total), true); 4895 } catch (RemoteException e) { 4896 } 4897 } 4898 PackageParser.Package p = pkg; 4899 synchronized (mInstallLock) { 4900 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4901 false /* force dex */, false /* defer */, true /* include dependencies */); 4902 } 4903 } 4904 4905 @Override 4906 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4907 return performDexOpt(packageName, instructionSet, false); 4908 } 4909 4910 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4911 if (info.primaryCpuAbi == null) { 4912 return getPreferredInstructionSet(); 4913 } 4914 4915 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4916 } 4917 4918 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4919 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4920 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4921 if (!dexopt && !updateUsage) { 4922 // We aren't going to dexopt or update usage, so bail early. 4923 return false; 4924 } 4925 PackageParser.Package p; 4926 final String targetInstructionSet; 4927 synchronized (mPackages) { 4928 p = mPackages.get(packageName); 4929 if (p == null) { 4930 return false; 4931 } 4932 if (updateUsage) { 4933 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4934 } 4935 mPackageUsage.write(false); 4936 if (!dexopt) { 4937 // We aren't going to dexopt, so bail early. 4938 return false; 4939 } 4940 4941 targetInstructionSet = instructionSet != null ? instructionSet : 4942 getPrimaryInstructionSet(p.applicationInfo); 4943 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4944 return false; 4945 } 4946 } 4947 4948 synchronized (mInstallLock) { 4949 final String[] instructionSets = new String[] { targetInstructionSet }; 4950 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4951 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4952 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4953 } 4954 } 4955 4956 public ArraySet<String> getPackagesThatNeedDexOpt() { 4957 ArraySet<String> pkgs = null; 4958 synchronized (mPackages) { 4959 for (PackageParser.Package p : mPackages.values()) { 4960 if (DEBUG_DEXOPT) { 4961 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4962 } 4963 if (!p.mDexOptPerformed.isEmpty()) { 4964 continue; 4965 } 4966 if (pkgs == null) { 4967 pkgs = new ArraySet<String>(); 4968 } 4969 pkgs.add(p.packageName); 4970 } 4971 } 4972 return pkgs; 4973 } 4974 4975 public void shutdown() { 4976 mPackageUsage.write(true); 4977 } 4978 4979 @Override 4980 public void forceDexOpt(String packageName) { 4981 enforceSystemOrRoot("forceDexOpt"); 4982 4983 PackageParser.Package pkg; 4984 synchronized (mPackages) { 4985 pkg = mPackages.get(packageName); 4986 if (pkg == null) { 4987 throw new IllegalArgumentException("Missing package: " + packageName); 4988 } 4989 } 4990 4991 synchronized (mInstallLock) { 4992 final String[] instructionSets = new String[] { 4993 getPrimaryInstructionSet(pkg.applicationInfo) }; 4994 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4995 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4996 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4997 throw new IllegalStateException("Failed to dexopt: " + res); 4998 } 4999 } 5000 } 5001 5002 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5003 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5004 Slog.w(TAG, "Unable to update from " + oldPkg.name 5005 + " to " + newPkg.packageName 5006 + ": old package not in system partition"); 5007 return false; 5008 } else if (mPackages.get(oldPkg.name) != null) { 5009 Slog.w(TAG, "Unable to update from " + oldPkg.name 5010 + " to " + newPkg.packageName 5011 + ": old package still exists"); 5012 return false; 5013 } 5014 return true; 5015 } 5016 5017 private File getDataPathForPackage(String packageName, int userId) { 5018 /* 5019 * Until we fully support multiple users, return the directory we 5020 * previously would have. The PackageManagerTests will need to be 5021 * revised when this is changed back.. 5022 */ 5023 if (userId == 0) { 5024 return new File(mAppDataDir, packageName); 5025 } else { 5026 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5027 + File.separator + packageName); 5028 } 5029 } 5030 5031 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5032 int[] users = sUserManager.getUserIds(); 5033 int res = mInstaller.install(packageName, uid, uid, seinfo); 5034 if (res < 0) { 5035 return res; 5036 } 5037 for (int user : users) { 5038 if (user != 0) { 5039 res = mInstaller.createUserData(packageName, 5040 UserHandle.getUid(user, uid), user, seinfo); 5041 if (res < 0) { 5042 return res; 5043 } 5044 } 5045 } 5046 return res; 5047 } 5048 5049 private int removeDataDirsLI(String packageName) { 5050 int[] users = sUserManager.getUserIds(); 5051 int res = 0; 5052 for (int user : users) { 5053 int resInner = mInstaller.remove(packageName, user); 5054 if (resInner < 0) { 5055 res = resInner; 5056 } 5057 } 5058 5059 return res; 5060 } 5061 5062 private int deleteCodeCacheDirsLI(String packageName) { 5063 int[] users = sUserManager.getUserIds(); 5064 int res = 0; 5065 for (int user : users) { 5066 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5067 if (resInner < 0) { 5068 res = resInner; 5069 } 5070 } 5071 return res; 5072 } 5073 5074 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5075 PackageParser.Package changingLib) { 5076 if (file.path != null) { 5077 usesLibraryFiles.add(file.path); 5078 return; 5079 } 5080 PackageParser.Package p = mPackages.get(file.apk); 5081 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5082 // If we are doing this while in the middle of updating a library apk, 5083 // then we need to make sure to use that new apk for determining the 5084 // dependencies here. (We haven't yet finished committing the new apk 5085 // to the package manager state.) 5086 if (p == null || p.packageName.equals(changingLib.packageName)) { 5087 p = changingLib; 5088 } 5089 } 5090 if (p != null) { 5091 usesLibraryFiles.addAll(p.getAllCodePaths()); 5092 } 5093 } 5094 5095 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5096 PackageParser.Package changingLib) throws PackageManagerException { 5097 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5098 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5099 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5100 for (int i=0; i<N; i++) { 5101 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5102 if (file == null) { 5103 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5104 "Package " + pkg.packageName + " requires unavailable shared library " 5105 + pkg.usesLibraries.get(i) + "; failing!"); 5106 } 5107 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5108 } 5109 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5110 for (int i=0; i<N; i++) { 5111 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5112 if (file == null) { 5113 Slog.w(TAG, "Package " + pkg.packageName 5114 + " desires unavailable shared library " 5115 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5116 } else { 5117 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5118 } 5119 } 5120 N = usesLibraryFiles.size(); 5121 if (N > 0) { 5122 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5123 } else { 5124 pkg.usesLibraryFiles = null; 5125 } 5126 } 5127 } 5128 5129 private static boolean hasString(List<String> list, List<String> which) { 5130 if (list == null) { 5131 return false; 5132 } 5133 for (int i=list.size()-1; i>=0; i--) { 5134 for (int j=which.size()-1; j>=0; j--) { 5135 if (which.get(j).equals(list.get(i))) { 5136 return true; 5137 } 5138 } 5139 } 5140 return false; 5141 } 5142 5143 private void updateAllSharedLibrariesLPw() { 5144 for (PackageParser.Package pkg : mPackages.values()) { 5145 try { 5146 updateSharedLibrariesLPw(pkg, null); 5147 } catch (PackageManagerException e) { 5148 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5149 } 5150 } 5151 } 5152 5153 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5154 PackageParser.Package changingPkg) { 5155 ArrayList<PackageParser.Package> res = null; 5156 for (PackageParser.Package pkg : mPackages.values()) { 5157 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5158 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5159 if (res == null) { 5160 res = new ArrayList<PackageParser.Package>(); 5161 } 5162 res.add(pkg); 5163 try { 5164 updateSharedLibrariesLPw(pkg, changingPkg); 5165 } catch (PackageManagerException e) { 5166 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5167 } 5168 } 5169 } 5170 return res; 5171 } 5172 5173 /** 5174 * Derive the value of the {@code cpuAbiOverride} based on the provided 5175 * value and an optional stored value from the package settings. 5176 */ 5177 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5178 String cpuAbiOverride = null; 5179 5180 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5181 cpuAbiOverride = null; 5182 } else if (abiOverride != null) { 5183 cpuAbiOverride = abiOverride; 5184 } else if (settings != null) { 5185 cpuAbiOverride = settings.cpuAbiOverrideString; 5186 } 5187 5188 return cpuAbiOverride; 5189 } 5190 5191 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5192 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5193 boolean success = false; 5194 try { 5195 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5196 currentTime, user); 5197 success = true; 5198 return res; 5199 } finally { 5200 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5201 removeDataDirsLI(pkg.packageName); 5202 } 5203 } 5204 } 5205 5206 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5207 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5208 final File scanFile = new File(pkg.codePath); 5209 if (pkg.applicationInfo.getCodePath() == null || 5210 pkg.applicationInfo.getResourcePath() == null) { 5211 // Bail out. The resource and code paths haven't been set. 5212 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5213 "Code and resource paths haven't been set correctly"); 5214 } 5215 5216 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5217 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5218 } else { 5219 // Only allow system apps to be flagged as core apps. 5220 pkg.coreApp = false; 5221 } 5222 5223 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5224 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5225 } 5226 5227 if (mCustomResolverComponentName != null && 5228 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5229 setUpCustomResolverActivity(pkg); 5230 } 5231 5232 if (pkg.packageName.equals("android")) { 5233 synchronized (mPackages) { 5234 if (mAndroidApplication != null) { 5235 Slog.w(TAG, "*************************************************"); 5236 Slog.w(TAG, "Core android package being redefined. Skipping."); 5237 Slog.w(TAG, " file=" + scanFile); 5238 Slog.w(TAG, "*************************************************"); 5239 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5240 "Core android package being redefined. Skipping."); 5241 } 5242 5243 // Set up information for our fall-back user intent resolution activity. 5244 mPlatformPackage = pkg; 5245 pkg.mVersionCode = mSdkVersion; 5246 mAndroidApplication = pkg.applicationInfo; 5247 5248 if (!mResolverReplaced) { 5249 mResolveActivity.applicationInfo = mAndroidApplication; 5250 mResolveActivity.name = ResolverActivity.class.getName(); 5251 mResolveActivity.packageName = mAndroidApplication.packageName; 5252 mResolveActivity.processName = "system:ui"; 5253 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5254 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5255 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5256 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5257 mResolveActivity.exported = true; 5258 mResolveActivity.enabled = true; 5259 mResolveInfo.activityInfo = mResolveActivity; 5260 mResolveInfo.priority = 0; 5261 mResolveInfo.preferredOrder = 0; 5262 mResolveInfo.match = 0; 5263 mResolveComponentName = new ComponentName( 5264 mAndroidApplication.packageName, mResolveActivity.name); 5265 } 5266 } 5267 } 5268 5269 if (DEBUG_PACKAGE_SCANNING) { 5270 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5271 Log.d(TAG, "Scanning package " + pkg.packageName); 5272 } 5273 5274 if (mPackages.containsKey(pkg.packageName) 5275 || mSharedLibraries.containsKey(pkg.packageName)) { 5276 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5277 "Application package " + pkg.packageName 5278 + " already installed. Skipping duplicate."); 5279 } 5280 5281 // If we're only installing presumed-existing packages, require that the 5282 // scanned APK is both already known and at the path previously established 5283 // for it. Previously unknown packages we pick up normally, but if we have an 5284 // a priori expectation about this package's install presence, enforce it. 5285 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5286 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5287 if (known != null) { 5288 if (DEBUG_PACKAGE_SCANNING) { 5289 Log.d(TAG, "Examining " + pkg.codePath 5290 + " and requiring known paths " + known.codePathString 5291 + " & " + known.resourcePathString); 5292 } 5293 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5294 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5295 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5296 "Application package " + pkg.packageName 5297 + " found at " + pkg.applicationInfo.getCodePath() 5298 + " but expected at " + known.codePathString + "; ignoring."); 5299 } 5300 } 5301 } 5302 5303 // Initialize package source and resource directories 5304 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5305 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5306 5307 SharedUserSetting suid = null; 5308 PackageSetting pkgSetting = null; 5309 5310 if (!isSystemApp(pkg)) { 5311 // Only system apps can use these features. 5312 pkg.mOriginalPackages = null; 5313 pkg.mRealPackage = null; 5314 pkg.mAdoptPermissions = null; 5315 } 5316 5317 // writer 5318 synchronized (mPackages) { 5319 if (pkg.mSharedUserId != null) { 5320 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5321 if (suid == null) { 5322 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5323 "Creating application package " + pkg.packageName 5324 + " for shared user failed"); 5325 } 5326 if (DEBUG_PACKAGE_SCANNING) { 5327 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5328 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5329 + "): packages=" + suid.packages); 5330 } 5331 } 5332 5333 // Check if we are renaming from an original package name. 5334 PackageSetting origPackage = null; 5335 String realName = null; 5336 if (pkg.mOriginalPackages != null) { 5337 // This package may need to be renamed to a previously 5338 // installed name. Let's check on that... 5339 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5340 if (pkg.mOriginalPackages.contains(renamed)) { 5341 // This package had originally been installed as the 5342 // original name, and we have already taken care of 5343 // transitioning to the new one. Just update the new 5344 // one to continue using the old name. 5345 realName = pkg.mRealPackage; 5346 if (!pkg.packageName.equals(renamed)) { 5347 // Callers into this function may have already taken 5348 // care of renaming the package; only do it here if 5349 // it is not already done. 5350 pkg.setPackageName(renamed); 5351 } 5352 5353 } else { 5354 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5355 if ((origPackage = mSettings.peekPackageLPr( 5356 pkg.mOriginalPackages.get(i))) != null) { 5357 // We do have the package already installed under its 5358 // original name... should we use it? 5359 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5360 // New package is not compatible with original. 5361 origPackage = null; 5362 continue; 5363 } else if (origPackage.sharedUser != null) { 5364 // Make sure uid is compatible between packages. 5365 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5366 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5367 + " to " + pkg.packageName + ": old uid " 5368 + origPackage.sharedUser.name 5369 + " differs from " + pkg.mSharedUserId); 5370 origPackage = null; 5371 continue; 5372 } 5373 } else { 5374 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5375 + pkg.packageName + " to old name " + origPackage.name); 5376 } 5377 break; 5378 } 5379 } 5380 } 5381 } 5382 5383 if (mTransferedPackages.contains(pkg.packageName)) { 5384 Slog.w(TAG, "Package " + pkg.packageName 5385 + " was transferred to another, but its .apk remains"); 5386 } 5387 5388 // Just create the setting, don't add it yet. For already existing packages 5389 // the PkgSetting exists already and doesn't have to be created. 5390 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5391 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5392 pkg.applicationInfo.primaryCpuAbi, 5393 pkg.applicationInfo.secondaryCpuAbi, 5394 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5395 user, false); 5396 if (pkgSetting == null) { 5397 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5398 "Creating application package " + pkg.packageName + " failed"); 5399 } 5400 5401 if (pkgSetting.origPackage != null) { 5402 // If we are first transitioning from an original package, 5403 // fix up the new package's name now. We need to do this after 5404 // looking up the package under its new name, so getPackageLP 5405 // can take care of fiddling things correctly. 5406 pkg.setPackageName(origPackage.name); 5407 5408 // File a report about this. 5409 String msg = "New package " + pkgSetting.realName 5410 + " renamed to replace old package " + pkgSetting.name; 5411 reportSettingsProblem(Log.WARN, msg); 5412 5413 // Make a note of it. 5414 mTransferedPackages.add(origPackage.name); 5415 5416 // No longer need to retain this. 5417 pkgSetting.origPackage = null; 5418 } 5419 5420 if (realName != null) { 5421 // Make a note of it. 5422 mTransferedPackages.add(pkg.packageName); 5423 } 5424 5425 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5426 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5427 } 5428 5429 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5430 // Check all shared libraries and map to their actual file path. 5431 // We only do this here for apps not on a system dir, because those 5432 // are the only ones that can fail an install due to this. We 5433 // will take care of the system apps by updating all of their 5434 // library paths after the scan is done. 5435 updateSharedLibrariesLPw(pkg, null); 5436 } 5437 5438 if (mFoundPolicyFile) { 5439 SELinuxMMAC.assignSeinfoValue(pkg); 5440 } 5441 5442 pkg.applicationInfo.uid = pkgSetting.appId; 5443 pkg.mExtras = pkgSetting; 5444 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5445 try { 5446 verifySignaturesLP(pkgSetting, pkg); 5447 // We just determined the app is signed correctly, so bring 5448 // over the latest parsed certs. 5449 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5450 } catch (PackageManagerException e) { 5451 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5452 throw e; 5453 } 5454 // The signature has changed, but this package is in the system 5455 // image... let's recover! 5456 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5457 // However... if this package is part of a shared user, but it 5458 // doesn't match the signature of the shared user, let's fail. 5459 // What this means is that you can't change the signatures 5460 // associated with an overall shared user, which doesn't seem all 5461 // that unreasonable. 5462 if (pkgSetting.sharedUser != null) { 5463 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5464 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5465 throw new PackageManagerException( 5466 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5467 "Signature mismatch for shared user : " 5468 + pkgSetting.sharedUser); 5469 } 5470 } 5471 // File a report about this. 5472 String msg = "System package " + pkg.packageName 5473 + " signature changed; retaining data."; 5474 reportSettingsProblem(Log.WARN, msg); 5475 } 5476 } else { 5477 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5478 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5479 + pkg.packageName + " upgrade keys do not match the " 5480 + "previously installed version"); 5481 } else { 5482 // We just determined the app is signed correctly, so bring 5483 // over the latest parsed certs. 5484 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5485 } 5486 } 5487 // Verify that this new package doesn't have any content providers 5488 // that conflict with existing packages. Only do this if the 5489 // package isn't already installed, since we don't want to break 5490 // things that are installed. 5491 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5492 final int N = pkg.providers.size(); 5493 int i; 5494 for (i=0; i<N; i++) { 5495 PackageParser.Provider p = pkg.providers.get(i); 5496 if (p.info.authority != null) { 5497 String names[] = p.info.authority.split(";"); 5498 for (int j = 0; j < names.length; j++) { 5499 if (mProvidersByAuthority.containsKey(names[j])) { 5500 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5501 final String otherPackageName = 5502 ((other != null && other.getComponentName() != null) ? 5503 other.getComponentName().getPackageName() : "?"); 5504 throw new PackageManagerException( 5505 INSTALL_FAILED_CONFLICTING_PROVIDER, 5506 "Can't install because provider name " + names[j] 5507 + " (in package " + pkg.applicationInfo.packageName 5508 + ") is already used by " + otherPackageName); 5509 } 5510 } 5511 } 5512 } 5513 } 5514 5515 if (pkg.mAdoptPermissions != null) { 5516 // This package wants to adopt ownership of permissions from 5517 // another package. 5518 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5519 final String origName = pkg.mAdoptPermissions.get(i); 5520 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5521 if (orig != null) { 5522 if (verifyPackageUpdateLPr(orig, pkg)) { 5523 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5524 + pkg.packageName); 5525 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5526 } 5527 } 5528 } 5529 } 5530 } 5531 5532 final String pkgName = pkg.packageName; 5533 5534 final long scanFileTime = scanFile.lastModified(); 5535 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5536 pkg.applicationInfo.processName = fixProcessName( 5537 pkg.applicationInfo.packageName, 5538 pkg.applicationInfo.processName, 5539 pkg.applicationInfo.uid); 5540 5541 File dataPath; 5542 if (mPlatformPackage == pkg) { 5543 // The system package is special. 5544 dataPath = new File(Environment.getDataDirectory(), "system"); 5545 5546 pkg.applicationInfo.dataDir = dataPath.getPath(); 5547 5548 } else { 5549 // This is a normal package, need to make its data directory. 5550 dataPath = getDataPathForPackage(pkg.packageName, 0); 5551 5552 boolean uidError = false; 5553 if (dataPath.exists()) { 5554 int currentUid = 0; 5555 try { 5556 StructStat stat = Os.stat(dataPath.getPath()); 5557 currentUid = stat.st_uid; 5558 } catch (ErrnoException e) { 5559 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5560 } 5561 5562 // If we have mismatched owners for the data path, we have a problem. 5563 if (currentUid != pkg.applicationInfo.uid) { 5564 boolean recovered = false; 5565 if (currentUid == 0) { 5566 // The directory somehow became owned by root. Wow. 5567 // This is probably because the system was stopped while 5568 // installd was in the middle of messing with its libs 5569 // directory. Ask installd to fix that. 5570 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5571 pkg.applicationInfo.uid); 5572 if (ret >= 0) { 5573 recovered = true; 5574 String msg = "Package " + pkg.packageName 5575 + " unexpectedly changed to uid 0; recovered to " + 5576 + pkg.applicationInfo.uid; 5577 reportSettingsProblem(Log.WARN, msg); 5578 } 5579 } 5580 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5581 || (scanFlags&SCAN_BOOTING) != 0)) { 5582 // If this is a system app, we can at least delete its 5583 // current data so the application will still work. 5584 int ret = removeDataDirsLI(pkgName); 5585 if (ret >= 0) { 5586 // TODO: Kill the processes first 5587 // Old data gone! 5588 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5589 ? "System package " : "Third party package "; 5590 String msg = prefix + pkg.packageName 5591 + " has changed from uid: " 5592 + currentUid + " to " 5593 + pkg.applicationInfo.uid + "; old data erased"; 5594 reportSettingsProblem(Log.WARN, msg); 5595 recovered = true; 5596 5597 // And now re-install the app. 5598 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5599 pkg.applicationInfo.seinfo); 5600 if (ret == -1) { 5601 // Ack should not happen! 5602 msg = prefix + pkg.packageName 5603 + " could not have data directory re-created after delete."; 5604 reportSettingsProblem(Log.WARN, msg); 5605 throw new PackageManagerException( 5606 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5607 } 5608 } 5609 if (!recovered) { 5610 mHasSystemUidErrors = true; 5611 } 5612 } else if (!recovered) { 5613 // If we allow this install to proceed, we will be broken. 5614 // Abort, abort! 5615 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5616 "scanPackageLI"); 5617 } 5618 if (!recovered) { 5619 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5620 + pkg.applicationInfo.uid + "/fs_" 5621 + currentUid; 5622 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5623 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5624 String msg = "Package " + pkg.packageName 5625 + " has mismatched uid: " 5626 + currentUid + " on disk, " 5627 + pkg.applicationInfo.uid + " in settings"; 5628 // writer 5629 synchronized (mPackages) { 5630 mSettings.mReadMessages.append(msg); 5631 mSettings.mReadMessages.append('\n'); 5632 uidError = true; 5633 if (!pkgSetting.uidError) { 5634 reportSettingsProblem(Log.ERROR, msg); 5635 } 5636 } 5637 } 5638 } 5639 pkg.applicationInfo.dataDir = dataPath.getPath(); 5640 if (mShouldRestoreconData) { 5641 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5642 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5643 pkg.applicationInfo.uid); 5644 } 5645 } else { 5646 if (DEBUG_PACKAGE_SCANNING) { 5647 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5648 Log.v(TAG, "Want this data dir: " + dataPath); 5649 } 5650 //invoke installer to do the actual installation 5651 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5652 pkg.applicationInfo.seinfo); 5653 if (ret < 0) { 5654 // Error from installer 5655 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5656 "Unable to create data dirs [errorCode=" + ret + "]"); 5657 } 5658 5659 if (dataPath.exists()) { 5660 pkg.applicationInfo.dataDir = dataPath.getPath(); 5661 } else { 5662 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5663 pkg.applicationInfo.dataDir = null; 5664 } 5665 } 5666 5667 pkgSetting.uidError = uidError; 5668 } 5669 5670 final String path = scanFile.getPath(); 5671 final String codePath = pkg.applicationInfo.getCodePath(); 5672 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5673 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5674 setBundledAppAbisAndRoots(pkg, pkgSetting); 5675 5676 // If we haven't found any native libraries for the app, check if it has 5677 // renderscript code. We'll need to force the app to 32 bit if it has 5678 // renderscript bitcode. 5679 if (pkg.applicationInfo.primaryCpuAbi == null 5680 && pkg.applicationInfo.secondaryCpuAbi == null 5681 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5682 NativeLibraryHelper.Handle handle = null; 5683 try { 5684 handle = NativeLibraryHelper.Handle.create(scanFile); 5685 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5686 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5687 } 5688 } catch (IOException ioe) { 5689 Slog.w(TAG, "Error scanning system app : " + ioe); 5690 } finally { 5691 IoUtils.closeQuietly(handle); 5692 } 5693 } 5694 5695 setNativeLibraryPaths(pkg); 5696 } else { 5697 // TODO: We can probably be smarter about this stuff. For installed apps, 5698 // we can calculate this information at install time once and for all. For 5699 // system apps, we can probably assume that this information doesn't change 5700 // after the first boot scan. As things stand, we do lots of unnecessary work. 5701 5702 // Give ourselves some initial paths; we'll come back for another 5703 // pass once we've determined ABI below. 5704 setNativeLibraryPaths(pkg); 5705 5706 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5707 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5708 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5709 5710 NativeLibraryHelper.Handle handle = null; 5711 try { 5712 handle = NativeLibraryHelper.Handle.create(scanFile); 5713 // TODO(multiArch): This can be null for apps that didn't go through the 5714 // usual installation process. We can calculate it again, like we 5715 // do during install time. 5716 // 5717 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5718 // unnecessary. 5719 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5720 5721 // Null out the abis so that they can be recalculated. 5722 pkg.applicationInfo.primaryCpuAbi = null; 5723 pkg.applicationInfo.secondaryCpuAbi = null; 5724 if (isMultiArch(pkg.applicationInfo)) { 5725 // Warn if we've set an abiOverride for multi-lib packages.. 5726 // By definition, we need to copy both 32 and 64 bit libraries for 5727 // such packages. 5728 if (pkg.cpuAbiOverride != null 5729 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5730 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5731 } 5732 5733 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5734 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5735 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5736 if (isAsec) { 5737 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5738 } else { 5739 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5740 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5741 useIsaSpecificSubdirs); 5742 } 5743 } 5744 5745 maybeThrowExceptionForMultiArchCopy( 5746 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5747 5748 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5749 if (isAsec) { 5750 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5751 } else { 5752 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5753 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5754 useIsaSpecificSubdirs); 5755 } 5756 } 5757 5758 maybeThrowExceptionForMultiArchCopy( 5759 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5760 5761 if (abi64 >= 0) { 5762 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5763 } 5764 5765 if (abi32 >= 0) { 5766 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5767 if (abi64 >= 0) { 5768 pkg.applicationInfo.secondaryCpuAbi = abi; 5769 } else { 5770 pkg.applicationInfo.primaryCpuAbi = abi; 5771 } 5772 } 5773 } else { 5774 String[] abiList = (cpuAbiOverride != null) ? 5775 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5776 5777 // Enable gross and lame hacks for apps that are built with old 5778 // SDK tools. We must scan their APKs for renderscript bitcode and 5779 // not launch them if it's present. Don't bother checking on devices 5780 // that don't have 64 bit support. 5781 boolean needsRenderScriptOverride = false; 5782 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5783 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5784 abiList = Build.SUPPORTED_32_BIT_ABIS; 5785 needsRenderScriptOverride = true; 5786 } 5787 5788 final int copyRet; 5789 if (isAsec) { 5790 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5791 } else { 5792 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5793 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5794 } 5795 5796 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5797 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5798 "Error unpackaging native libs for app, errorCode=" + copyRet); 5799 } 5800 5801 if (copyRet >= 0) { 5802 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5803 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5804 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5805 } else if (needsRenderScriptOverride) { 5806 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5807 } 5808 } 5809 } catch (IOException ioe) { 5810 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5811 } finally { 5812 IoUtils.closeQuietly(handle); 5813 } 5814 5815 // Now that we've calculated the ABIs and determined if it's an internal app, 5816 // we will go ahead and populate the nativeLibraryPath. 5817 setNativeLibraryPaths(pkg); 5818 5819 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5820 final int[] userIds = sUserManager.getUserIds(); 5821 synchronized (mInstallLock) { 5822 // Create a native library symlink only if we have native libraries 5823 // and if the native libraries are 32 bit libraries. We do not provide 5824 // this symlink for 64 bit libraries. 5825 if (pkg.applicationInfo.primaryCpuAbi != null && 5826 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5827 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5828 for (int userId : userIds) { 5829 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5830 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5831 "Failed linking native library dir (user=" + userId + ")"); 5832 } 5833 } 5834 } 5835 } 5836 } 5837 5838 // This is a special case for the "system" package, where the ABI is 5839 // dictated by the zygote configuration (and init.rc). We should keep track 5840 // of this ABI so that we can deal with "normal" applications that run under 5841 // the same UID correctly. 5842 if (mPlatformPackage == pkg) { 5843 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5844 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5845 } 5846 5847 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5848 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5849 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5850 // Copy the derived override back to the parsed package, so that we can 5851 // update the package settings accordingly. 5852 pkg.cpuAbiOverride = cpuAbiOverride; 5853 5854 if (DEBUG_ABI_SELECTION) { 5855 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5856 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5857 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5858 } 5859 5860 // Push the derived path down into PackageSettings so we know what to 5861 // clean up at uninstall time. 5862 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5863 5864 if (DEBUG_ABI_SELECTION) { 5865 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5866 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5867 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5868 } 5869 5870 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5871 // We don't do this here during boot because we can do it all 5872 // at once after scanning all existing packages. 5873 // 5874 // We also do this *before* we perform dexopt on this package, so that 5875 // we can avoid redundant dexopts, and also to make sure we've got the 5876 // code and package path correct. 5877 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5878 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5879 } 5880 5881 if ((scanFlags & SCAN_NO_DEX) == 0) { 5882 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5883 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5884 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5885 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5886 } 5887 } 5888 5889 if (mFactoryTest && pkg.requestedPermissions.contains( 5890 android.Manifest.permission.FACTORY_TEST)) { 5891 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5892 } 5893 5894 ArrayList<PackageParser.Package> clientLibPkgs = null; 5895 5896 // writer 5897 synchronized (mPackages) { 5898 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5899 // Only system apps can add new shared libraries. 5900 if (pkg.libraryNames != null) { 5901 for (int i=0; i<pkg.libraryNames.size(); i++) { 5902 String name = pkg.libraryNames.get(i); 5903 boolean allowed = false; 5904 if (isUpdatedSystemApp(pkg)) { 5905 // New library entries can only be added through the 5906 // system image. This is important to get rid of a lot 5907 // of nasty edge cases: for example if we allowed a non- 5908 // system update of the app to add a library, then uninstalling 5909 // the update would make the library go away, and assumptions 5910 // we made such as through app install filtering would now 5911 // have allowed apps on the device which aren't compatible 5912 // with it. Better to just have the restriction here, be 5913 // conservative, and create many fewer cases that can negatively 5914 // impact the user experience. 5915 final PackageSetting sysPs = mSettings 5916 .getDisabledSystemPkgLPr(pkg.packageName); 5917 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5918 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5919 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5920 allowed = true; 5921 allowed = true; 5922 break; 5923 } 5924 } 5925 } 5926 } else { 5927 allowed = true; 5928 } 5929 if (allowed) { 5930 if (!mSharedLibraries.containsKey(name)) { 5931 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5932 } else if (!name.equals(pkg.packageName)) { 5933 Slog.w(TAG, "Package " + pkg.packageName + " library " 5934 + name + " already exists; skipping"); 5935 } 5936 } else { 5937 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5938 + name + " that is not declared on system image; skipping"); 5939 } 5940 } 5941 if ((scanFlags&SCAN_BOOTING) == 0) { 5942 // If we are not booting, we need to update any applications 5943 // that are clients of our shared library. If we are booting, 5944 // this will all be done once the scan is complete. 5945 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5946 } 5947 } 5948 } 5949 } 5950 5951 // We also need to dexopt any apps that are dependent on this library. Note that 5952 // if these fail, we should abort the install since installing the library will 5953 // result in some apps being broken. 5954 if (clientLibPkgs != null) { 5955 if ((scanFlags & SCAN_NO_DEX) == 0) { 5956 for (int i = 0; i < clientLibPkgs.size(); i++) { 5957 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5958 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5959 null /* instruction sets */, forceDex, 5960 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5961 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5962 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5963 "scanPackageLI failed to dexopt clientLibPkgs"); 5964 } 5965 } 5966 } 5967 } 5968 5969 // Request the ActivityManager to kill the process(only for existing packages) 5970 // so that we do not end up in a confused state while the user is still using the older 5971 // version of the application while the new one gets installed. 5972 if ((scanFlags & SCAN_REPLACING) != 0) { 5973 killApplication(pkg.applicationInfo.packageName, 5974 pkg.applicationInfo.uid, "update pkg"); 5975 } 5976 5977 // Also need to kill any apps that are dependent on the library. 5978 if (clientLibPkgs != null) { 5979 for (int i=0; i<clientLibPkgs.size(); i++) { 5980 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5981 killApplication(clientPkg.applicationInfo.packageName, 5982 clientPkg.applicationInfo.uid, "update lib"); 5983 } 5984 } 5985 5986 // writer 5987 synchronized (mPackages) { 5988 // We don't expect installation to fail beyond this point 5989 5990 // Add the new setting to mSettings 5991 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5992 // Add the new setting to mPackages 5993 mPackages.put(pkg.applicationInfo.packageName, pkg); 5994 // Make sure we don't accidentally delete its data. 5995 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5996 while (iter.hasNext()) { 5997 PackageCleanItem item = iter.next(); 5998 if (pkgName.equals(item.packageName)) { 5999 iter.remove(); 6000 } 6001 } 6002 6003 // Take care of first install / last update times. 6004 if (currentTime != 0) { 6005 if (pkgSetting.firstInstallTime == 0) { 6006 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6007 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6008 pkgSetting.lastUpdateTime = currentTime; 6009 } 6010 } else if (pkgSetting.firstInstallTime == 0) { 6011 // We need *something*. Take time time stamp of the file. 6012 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6013 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6014 if (scanFileTime != pkgSetting.timeStamp) { 6015 // A package on the system image has changed; consider this 6016 // to be an update. 6017 pkgSetting.lastUpdateTime = scanFileTime; 6018 } 6019 } 6020 6021 // Add the package's KeySets to the global KeySetManagerService 6022 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6023 try { 6024 // Old KeySetData no longer valid. 6025 ksms.removeAppKeySetDataLPw(pkg.packageName); 6026 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6027 if (pkg.mKeySetMapping != null) { 6028 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6029 pkg.mKeySetMapping.entrySet()) { 6030 if (entry.getValue() != null) { 6031 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6032 entry.getValue(), entry.getKey()); 6033 } 6034 } 6035 if (pkg.mUpgradeKeySets != null) { 6036 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6037 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6038 } 6039 } 6040 } 6041 } catch (NullPointerException e) { 6042 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6043 } catch (IllegalArgumentException e) { 6044 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6045 } 6046 6047 int N = pkg.providers.size(); 6048 StringBuilder r = null; 6049 int i; 6050 for (i=0; i<N; i++) { 6051 PackageParser.Provider p = pkg.providers.get(i); 6052 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6053 p.info.processName, pkg.applicationInfo.uid); 6054 mProviders.addProvider(p); 6055 p.syncable = p.info.isSyncable; 6056 if (p.info.authority != null) { 6057 String names[] = p.info.authority.split(";"); 6058 p.info.authority = null; 6059 for (int j = 0; j < names.length; j++) { 6060 if (j == 1 && p.syncable) { 6061 // We only want the first authority for a provider to possibly be 6062 // syncable, so if we already added this provider using a different 6063 // authority clear the syncable flag. We copy the provider before 6064 // changing it because the mProviders object contains a reference 6065 // to a provider that we don't want to change. 6066 // Only do this for the second authority since the resulting provider 6067 // object can be the same for all future authorities for this provider. 6068 p = new PackageParser.Provider(p); 6069 p.syncable = false; 6070 } 6071 if (!mProvidersByAuthority.containsKey(names[j])) { 6072 mProvidersByAuthority.put(names[j], p); 6073 if (p.info.authority == null) { 6074 p.info.authority = names[j]; 6075 } else { 6076 p.info.authority = p.info.authority + ";" + names[j]; 6077 } 6078 if (DEBUG_PACKAGE_SCANNING) { 6079 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6080 Log.d(TAG, "Registered content provider: " + names[j] 6081 + ", className = " + p.info.name + ", isSyncable = " 6082 + p.info.isSyncable); 6083 } 6084 } else { 6085 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6086 Slog.w(TAG, "Skipping provider name " + names[j] + 6087 " (in package " + pkg.applicationInfo.packageName + 6088 "): name already used by " 6089 + ((other != null && other.getComponentName() != null) 6090 ? other.getComponentName().getPackageName() : "?")); 6091 } 6092 } 6093 } 6094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6095 if (r == null) { 6096 r = new StringBuilder(256); 6097 } else { 6098 r.append(' '); 6099 } 6100 r.append(p.info.name); 6101 } 6102 } 6103 if (r != null) { 6104 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6105 } 6106 6107 N = pkg.services.size(); 6108 r = null; 6109 for (i=0; i<N; i++) { 6110 PackageParser.Service s = pkg.services.get(i); 6111 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6112 s.info.processName, pkg.applicationInfo.uid); 6113 mServices.addService(s); 6114 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6115 if (r == null) { 6116 r = new StringBuilder(256); 6117 } else { 6118 r.append(' '); 6119 } 6120 r.append(s.info.name); 6121 } 6122 } 6123 if (r != null) { 6124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6125 } 6126 6127 N = pkg.receivers.size(); 6128 r = null; 6129 for (i=0; i<N; i++) { 6130 PackageParser.Activity a = pkg.receivers.get(i); 6131 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6132 a.info.processName, pkg.applicationInfo.uid); 6133 mReceivers.addActivity(a, "receiver"); 6134 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6135 if (r == null) { 6136 r = new StringBuilder(256); 6137 } else { 6138 r.append(' '); 6139 } 6140 r.append(a.info.name); 6141 } 6142 } 6143 if (r != null) { 6144 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6145 } 6146 6147 N = pkg.activities.size(); 6148 r = null; 6149 for (i=0; i<N; i++) { 6150 PackageParser.Activity a = pkg.activities.get(i); 6151 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6152 a.info.processName, pkg.applicationInfo.uid); 6153 mActivities.addActivity(a, "activity"); 6154 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6155 if (r == null) { 6156 r = new StringBuilder(256); 6157 } else { 6158 r.append(' '); 6159 } 6160 r.append(a.info.name); 6161 } 6162 } 6163 if (r != null) { 6164 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6165 } 6166 6167 N = pkg.permissionGroups.size(); 6168 r = null; 6169 for (i=0; i<N; i++) { 6170 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6171 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6172 if (cur == null) { 6173 mPermissionGroups.put(pg.info.name, pg); 6174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6175 if (r == null) { 6176 r = new StringBuilder(256); 6177 } else { 6178 r.append(' '); 6179 } 6180 r.append(pg.info.name); 6181 } 6182 } else { 6183 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6184 + pg.info.packageName + " ignored: original from " 6185 + cur.info.packageName); 6186 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6187 if (r == null) { 6188 r = new StringBuilder(256); 6189 } else { 6190 r.append(' '); 6191 } 6192 r.append("DUP:"); 6193 r.append(pg.info.name); 6194 } 6195 } 6196 } 6197 if (r != null) { 6198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6199 } 6200 6201 N = pkg.permissions.size(); 6202 r = null; 6203 for (i=0; i<N; i++) { 6204 PackageParser.Permission p = pkg.permissions.get(i); 6205 ArrayMap<String, BasePermission> permissionMap = 6206 p.tree ? mSettings.mPermissionTrees 6207 : mSettings.mPermissions; 6208 p.group = mPermissionGroups.get(p.info.group); 6209 if (p.info.group == null || p.group != null) { 6210 BasePermission bp = permissionMap.get(p.info.name); 6211 6212 // Allow system apps to redefine non-system permissions 6213 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6214 final boolean currentOwnerIsSystem = (bp.perm != null 6215 && isSystemApp(bp.perm.owner)); 6216 if (isSystemApp(p.owner)) { 6217 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6218 // It's a built-in permission and no owner, take ownership now 6219 bp.packageSetting = pkgSetting; 6220 bp.perm = p; 6221 bp.uid = pkg.applicationInfo.uid; 6222 bp.sourcePackage = p.info.packageName; 6223 } else if (!currentOwnerIsSystem) { 6224 String msg = "New decl " + p.owner + " of permission " 6225 + p.info.name + " is system; overriding " + bp.sourcePackage; 6226 reportSettingsProblem(Log.WARN, msg); 6227 bp = null; 6228 } 6229 } 6230 } 6231 6232 if (bp == null) { 6233 bp = new BasePermission(p.info.name, p.info.packageName, 6234 BasePermission.TYPE_NORMAL); 6235 permissionMap.put(p.info.name, bp); 6236 } 6237 6238 if (bp.perm == null) { 6239 if (bp.sourcePackage == null 6240 || bp.sourcePackage.equals(p.info.packageName)) { 6241 BasePermission tree = findPermissionTreeLP(p.info.name); 6242 if (tree == null 6243 || tree.sourcePackage.equals(p.info.packageName)) { 6244 bp.packageSetting = pkgSetting; 6245 bp.perm = p; 6246 bp.uid = pkg.applicationInfo.uid; 6247 bp.sourcePackage = p.info.packageName; 6248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6249 if (r == null) { 6250 r = new StringBuilder(256); 6251 } else { 6252 r.append(' '); 6253 } 6254 r.append(p.info.name); 6255 } 6256 } else { 6257 Slog.w(TAG, "Permission " + p.info.name + " from package " 6258 + p.info.packageName + " ignored: base tree " 6259 + tree.name + " is from package " 6260 + tree.sourcePackage); 6261 } 6262 } else { 6263 Slog.w(TAG, "Permission " + p.info.name + " from package " 6264 + p.info.packageName + " ignored: original from " 6265 + bp.sourcePackage); 6266 } 6267 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6268 if (r == null) { 6269 r = new StringBuilder(256); 6270 } else { 6271 r.append(' '); 6272 } 6273 r.append("DUP:"); 6274 r.append(p.info.name); 6275 } 6276 if (bp.perm == p) { 6277 bp.protectionLevel = p.info.protectionLevel; 6278 } 6279 } else { 6280 Slog.w(TAG, "Permission " + p.info.name + " from package " 6281 + p.info.packageName + " ignored: no group " 6282 + p.group); 6283 } 6284 } 6285 if (r != null) { 6286 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6287 } 6288 6289 N = pkg.instrumentation.size(); 6290 r = null; 6291 for (i=0; i<N; i++) { 6292 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6293 a.info.packageName = pkg.applicationInfo.packageName; 6294 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6295 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6296 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6297 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6298 a.info.dataDir = pkg.applicationInfo.dataDir; 6299 6300 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6301 // need other information about the application, like the ABI and what not ? 6302 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6303 mInstrumentation.put(a.getComponentName(), a); 6304 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6305 if (r == null) { 6306 r = new StringBuilder(256); 6307 } else { 6308 r.append(' '); 6309 } 6310 r.append(a.info.name); 6311 } 6312 } 6313 if (r != null) { 6314 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6315 } 6316 6317 if (pkg.protectedBroadcasts != null) { 6318 N = pkg.protectedBroadcasts.size(); 6319 for (i=0; i<N; i++) { 6320 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6321 } 6322 } 6323 6324 pkgSetting.setTimeStamp(scanFileTime); 6325 6326 // Create idmap files for pairs of (packages, overlay packages). 6327 // Note: "android", ie framework-res.apk, is handled by native layers. 6328 if (pkg.mOverlayTarget != null) { 6329 // This is an overlay package. 6330 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6331 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6332 mOverlays.put(pkg.mOverlayTarget, 6333 new ArrayMap<String, PackageParser.Package>()); 6334 } 6335 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6336 map.put(pkg.packageName, pkg); 6337 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6338 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6339 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6340 "scanPackageLI failed to createIdmap"); 6341 } 6342 } 6343 } else if (mOverlays.containsKey(pkg.packageName) && 6344 !pkg.packageName.equals("android")) { 6345 // This is a regular package, with one or more known overlay packages. 6346 createIdmapsForPackageLI(pkg); 6347 } 6348 } 6349 6350 return pkg; 6351 } 6352 6353 /** 6354 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6355 * i.e, so that all packages can be run inside a single process if required. 6356 * 6357 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6358 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6359 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6360 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6361 * updating a package that belongs to a shared user. 6362 * 6363 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6364 * adds unnecessary complexity. 6365 */ 6366 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6367 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6368 String requiredInstructionSet = null; 6369 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6370 requiredInstructionSet = VMRuntime.getInstructionSet( 6371 scannedPackage.applicationInfo.primaryCpuAbi); 6372 } 6373 6374 PackageSetting requirer = null; 6375 for (PackageSetting ps : packagesForUser) { 6376 // If packagesForUser contains scannedPackage, we skip it. This will happen 6377 // when scannedPackage is an update of an existing package. Without this check, 6378 // we will never be able to change the ABI of any package belonging to a shared 6379 // user, even if it's compatible with other packages. 6380 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6381 if (ps.primaryCpuAbiString == null) { 6382 continue; 6383 } 6384 6385 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6386 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6387 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6388 // this but there's not much we can do. 6389 String errorMessage = "Instruction set mismatch, " 6390 + ((requirer == null) ? "[caller]" : requirer) 6391 + " requires " + requiredInstructionSet + " whereas " + ps 6392 + " requires " + instructionSet; 6393 Slog.w(TAG, errorMessage); 6394 } 6395 6396 if (requiredInstructionSet == null) { 6397 requiredInstructionSet = instructionSet; 6398 requirer = ps; 6399 } 6400 } 6401 } 6402 6403 if (requiredInstructionSet != null) { 6404 String adjustedAbi; 6405 if (requirer != null) { 6406 // requirer != null implies that either scannedPackage was null or that scannedPackage 6407 // did not require an ABI, in which case we have to adjust scannedPackage to match 6408 // the ABI of the set (which is the same as requirer's ABI) 6409 adjustedAbi = requirer.primaryCpuAbiString; 6410 if (scannedPackage != null) { 6411 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6412 } 6413 } else { 6414 // requirer == null implies that we're updating all ABIs in the set to 6415 // match scannedPackage. 6416 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6417 } 6418 6419 for (PackageSetting ps : packagesForUser) { 6420 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6421 if (ps.primaryCpuAbiString != null) { 6422 continue; 6423 } 6424 6425 ps.primaryCpuAbiString = adjustedAbi; 6426 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6427 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6428 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6429 6430 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6431 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6432 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6433 ps.primaryCpuAbiString = null; 6434 ps.pkg.applicationInfo.primaryCpuAbi = null; 6435 return; 6436 } else { 6437 mInstaller.rmdex(ps.codePathString, 6438 getDexCodeInstructionSet(getPreferredInstructionSet())); 6439 } 6440 } 6441 } 6442 } 6443 } 6444 } 6445 6446 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6447 synchronized (mPackages) { 6448 mResolverReplaced = true; 6449 // Set up information for custom user intent resolution activity. 6450 mResolveActivity.applicationInfo = pkg.applicationInfo; 6451 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6452 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6453 mResolveActivity.processName = pkg.applicationInfo.packageName; 6454 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6455 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6456 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6457 mResolveActivity.theme = 0; 6458 mResolveActivity.exported = true; 6459 mResolveActivity.enabled = true; 6460 mResolveInfo.activityInfo = mResolveActivity; 6461 mResolveInfo.priority = 0; 6462 mResolveInfo.preferredOrder = 0; 6463 mResolveInfo.match = 0; 6464 mResolveComponentName = mCustomResolverComponentName; 6465 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6466 mResolveComponentName); 6467 } 6468 } 6469 6470 private static String calculateBundledApkRoot(final String codePathString) { 6471 final File codePath = new File(codePathString); 6472 final File codeRoot; 6473 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6474 codeRoot = Environment.getRootDirectory(); 6475 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6476 codeRoot = Environment.getOemDirectory(); 6477 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6478 codeRoot = Environment.getVendorDirectory(); 6479 } else { 6480 // Unrecognized code path; take its top real segment as the apk root: 6481 // e.g. /something/app/blah.apk => /something 6482 try { 6483 File f = codePath.getCanonicalFile(); 6484 File parent = f.getParentFile(); // non-null because codePath is a file 6485 File tmp; 6486 while ((tmp = parent.getParentFile()) != null) { 6487 f = parent; 6488 parent = tmp; 6489 } 6490 codeRoot = f; 6491 Slog.w(TAG, "Unrecognized code path " 6492 + codePath + " - using " + codeRoot); 6493 } catch (IOException e) { 6494 // Can't canonicalize the code path -- shenanigans? 6495 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6496 return Environment.getRootDirectory().getPath(); 6497 } 6498 } 6499 return codeRoot.getPath(); 6500 } 6501 6502 /** 6503 * Derive and set the location of native libraries for the given package, 6504 * which varies depending on where and how the package was installed. 6505 */ 6506 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6507 final ApplicationInfo info = pkg.applicationInfo; 6508 final String codePath = pkg.codePath; 6509 final File codeFile = new File(codePath); 6510 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6511 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6512 6513 info.nativeLibraryRootDir = null; 6514 info.nativeLibraryRootRequiresIsa = false; 6515 info.nativeLibraryDir = null; 6516 info.secondaryNativeLibraryDir = null; 6517 6518 if (isApkFile(codeFile)) { 6519 // Monolithic install 6520 if (bundledApp) { 6521 // If "/system/lib64/apkname" exists, assume that is the per-package 6522 // native library directory to use; otherwise use "/system/lib/apkname". 6523 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6524 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6525 getPrimaryInstructionSet(info)); 6526 6527 // This is a bundled system app so choose the path based on the ABI. 6528 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6529 // is just the default path. 6530 final String apkName = deriveCodePathName(codePath); 6531 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6532 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6533 apkName).getAbsolutePath(); 6534 6535 if (info.secondaryCpuAbi != null) { 6536 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6537 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6538 secondaryLibDir, apkName).getAbsolutePath(); 6539 } 6540 } else if (asecApp) { 6541 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6542 .getAbsolutePath(); 6543 } else { 6544 final String apkName = deriveCodePathName(codePath); 6545 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6546 .getAbsolutePath(); 6547 } 6548 6549 info.nativeLibraryRootRequiresIsa = false; 6550 info.nativeLibraryDir = info.nativeLibraryRootDir; 6551 } else { 6552 // Cluster install 6553 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6554 info.nativeLibraryRootRequiresIsa = true; 6555 6556 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6557 getPrimaryInstructionSet(info)).getAbsolutePath(); 6558 6559 if (info.secondaryCpuAbi != null) { 6560 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6561 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6562 } 6563 } 6564 } 6565 6566 /** 6567 * Calculate the abis and roots for a bundled app. These can uniquely 6568 * be determined from the contents of the system partition, i.e whether 6569 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6570 * of this information, and instead assume that the system was built 6571 * sensibly. 6572 */ 6573 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6574 PackageSetting pkgSetting) { 6575 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6576 6577 // If "/system/lib64/apkname" exists, assume that is the per-package 6578 // native library directory to use; otherwise use "/system/lib/apkname". 6579 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6580 setBundledAppAbi(pkg, apkRoot, apkName); 6581 // pkgSetting might be null during rescan following uninstall of updates 6582 // to a bundled app, so accommodate that possibility. The settings in 6583 // that case will be established later from the parsed package. 6584 // 6585 // If the settings aren't null, sync them up with what we've just derived. 6586 // note that apkRoot isn't stored in the package settings. 6587 if (pkgSetting != null) { 6588 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6589 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6590 } 6591 } 6592 6593 /** 6594 * Deduces the ABI of a bundled app and sets the relevant fields on the 6595 * parsed pkg object. 6596 * 6597 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6598 * under which system libraries are installed. 6599 * @param apkName the name of the installed package. 6600 */ 6601 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6602 final File codeFile = new File(pkg.codePath); 6603 6604 final boolean has64BitLibs; 6605 final boolean has32BitLibs; 6606 if (isApkFile(codeFile)) { 6607 // Monolithic install 6608 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6609 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6610 } else { 6611 // Cluster install 6612 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6613 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6614 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6615 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6616 has64BitLibs = (new File(rootDir, isa)).exists(); 6617 } else { 6618 has64BitLibs = false; 6619 } 6620 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6621 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6622 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6623 has32BitLibs = (new File(rootDir, isa)).exists(); 6624 } else { 6625 has32BitLibs = false; 6626 } 6627 } 6628 6629 if (has64BitLibs && !has32BitLibs) { 6630 // The package has 64 bit libs, but not 32 bit libs. Its primary 6631 // ABI should be 64 bit. We can safely assume here that the bundled 6632 // native libraries correspond to the most preferred ABI in the list. 6633 6634 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6635 pkg.applicationInfo.secondaryCpuAbi = null; 6636 } else if (has32BitLibs && !has64BitLibs) { 6637 // The package has 32 bit libs but not 64 bit libs. Its primary 6638 // ABI should be 32 bit. 6639 6640 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6641 pkg.applicationInfo.secondaryCpuAbi = null; 6642 } else if (has32BitLibs && has64BitLibs) { 6643 // The application has both 64 and 32 bit bundled libraries. We check 6644 // here that the app declares multiArch support, and warn if it doesn't. 6645 // 6646 // We will be lenient here and record both ABIs. The primary will be the 6647 // ABI that's higher on the list, i.e, a device that's configured to prefer 6648 // 64 bit apps will see a 64 bit primary ABI, 6649 6650 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6651 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6652 } 6653 6654 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6655 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6656 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6657 } else { 6658 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6659 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6660 } 6661 } else { 6662 pkg.applicationInfo.primaryCpuAbi = null; 6663 pkg.applicationInfo.secondaryCpuAbi = null; 6664 } 6665 } 6666 6667 private void killApplication(String pkgName, int appId, String reason) { 6668 // Request the ActivityManager to kill the process(only for existing packages) 6669 // so that we do not end up in a confused state while the user is still using the older 6670 // version of the application while the new one gets installed. 6671 IActivityManager am = ActivityManagerNative.getDefault(); 6672 if (am != null) { 6673 try { 6674 am.killApplicationWithAppId(pkgName, appId, reason); 6675 } catch (RemoteException e) { 6676 } 6677 } 6678 } 6679 6680 void removePackageLI(PackageSetting ps, boolean chatty) { 6681 if (DEBUG_INSTALL) { 6682 if (chatty) 6683 Log.d(TAG, "Removing package " + ps.name); 6684 } 6685 6686 // writer 6687 synchronized (mPackages) { 6688 mPackages.remove(ps.name); 6689 final PackageParser.Package pkg = ps.pkg; 6690 if (pkg != null) { 6691 cleanPackageDataStructuresLILPw(pkg, chatty); 6692 } 6693 } 6694 } 6695 6696 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6697 if (DEBUG_INSTALL) { 6698 if (chatty) 6699 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6700 } 6701 6702 // writer 6703 synchronized (mPackages) { 6704 mPackages.remove(pkg.applicationInfo.packageName); 6705 cleanPackageDataStructuresLILPw(pkg, chatty); 6706 } 6707 } 6708 6709 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6710 int N = pkg.providers.size(); 6711 StringBuilder r = null; 6712 int i; 6713 for (i=0; i<N; i++) { 6714 PackageParser.Provider p = pkg.providers.get(i); 6715 mProviders.removeProvider(p); 6716 if (p.info.authority == null) { 6717 6718 /* There was another ContentProvider with this authority when 6719 * this app was installed so this authority is null, 6720 * Ignore it as we don't have to unregister the provider. 6721 */ 6722 continue; 6723 } 6724 String names[] = p.info.authority.split(";"); 6725 for (int j = 0; j < names.length; j++) { 6726 if (mProvidersByAuthority.get(names[j]) == p) { 6727 mProvidersByAuthority.remove(names[j]); 6728 if (DEBUG_REMOVE) { 6729 if (chatty) 6730 Log.d(TAG, "Unregistered content provider: " + names[j] 6731 + ", className = " + p.info.name + ", isSyncable = " 6732 + p.info.isSyncable); 6733 } 6734 } 6735 } 6736 if (DEBUG_REMOVE && chatty) { 6737 if (r == null) { 6738 r = new StringBuilder(256); 6739 } else { 6740 r.append(' '); 6741 } 6742 r.append(p.info.name); 6743 } 6744 } 6745 if (r != null) { 6746 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6747 } 6748 6749 N = pkg.services.size(); 6750 r = null; 6751 for (i=0; i<N; i++) { 6752 PackageParser.Service s = pkg.services.get(i); 6753 mServices.removeService(s); 6754 if (chatty) { 6755 if (r == null) { 6756 r = new StringBuilder(256); 6757 } else { 6758 r.append(' '); 6759 } 6760 r.append(s.info.name); 6761 } 6762 } 6763 if (r != null) { 6764 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6765 } 6766 6767 N = pkg.receivers.size(); 6768 r = null; 6769 for (i=0; i<N; i++) { 6770 PackageParser.Activity a = pkg.receivers.get(i); 6771 mReceivers.removeActivity(a, "receiver"); 6772 if (DEBUG_REMOVE && chatty) { 6773 if (r == null) { 6774 r = new StringBuilder(256); 6775 } else { 6776 r.append(' '); 6777 } 6778 r.append(a.info.name); 6779 } 6780 } 6781 if (r != null) { 6782 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6783 } 6784 6785 N = pkg.activities.size(); 6786 r = null; 6787 for (i=0; i<N; i++) { 6788 PackageParser.Activity a = pkg.activities.get(i); 6789 mActivities.removeActivity(a, "activity"); 6790 if (DEBUG_REMOVE && chatty) { 6791 if (r == null) { 6792 r = new StringBuilder(256); 6793 } else { 6794 r.append(' '); 6795 } 6796 r.append(a.info.name); 6797 } 6798 } 6799 if (r != null) { 6800 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6801 } 6802 6803 N = pkg.permissions.size(); 6804 r = null; 6805 for (i=0; i<N; i++) { 6806 PackageParser.Permission p = pkg.permissions.get(i); 6807 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6808 if (bp == null) { 6809 bp = mSettings.mPermissionTrees.get(p.info.name); 6810 } 6811 if (bp != null && bp.perm == p) { 6812 bp.perm = null; 6813 if (DEBUG_REMOVE && chatty) { 6814 if (r == null) { 6815 r = new StringBuilder(256); 6816 } else { 6817 r.append(' '); 6818 } 6819 r.append(p.info.name); 6820 } 6821 } 6822 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6823 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6824 if (appOpPerms != null) { 6825 appOpPerms.remove(pkg.packageName); 6826 } 6827 } 6828 } 6829 if (r != null) { 6830 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6831 } 6832 6833 N = pkg.requestedPermissions.size(); 6834 r = null; 6835 for (i=0; i<N; i++) { 6836 String perm = pkg.requestedPermissions.get(i); 6837 BasePermission bp = mSettings.mPermissions.get(perm); 6838 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6839 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6840 if (appOpPerms != null) { 6841 appOpPerms.remove(pkg.packageName); 6842 if (appOpPerms.isEmpty()) { 6843 mAppOpPermissionPackages.remove(perm); 6844 } 6845 } 6846 } 6847 } 6848 if (r != null) { 6849 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6850 } 6851 6852 N = pkg.instrumentation.size(); 6853 r = null; 6854 for (i=0; i<N; i++) { 6855 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6856 mInstrumentation.remove(a.getComponentName()); 6857 if (DEBUG_REMOVE && chatty) { 6858 if (r == null) { 6859 r = new StringBuilder(256); 6860 } else { 6861 r.append(' '); 6862 } 6863 r.append(a.info.name); 6864 } 6865 } 6866 if (r != null) { 6867 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6868 } 6869 6870 r = null; 6871 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6872 // Only system apps can hold shared libraries. 6873 if (pkg.libraryNames != null) { 6874 for (i=0; i<pkg.libraryNames.size(); i++) { 6875 String name = pkg.libraryNames.get(i); 6876 SharedLibraryEntry cur = mSharedLibraries.get(name); 6877 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6878 mSharedLibraries.remove(name); 6879 if (DEBUG_REMOVE && chatty) { 6880 if (r == null) { 6881 r = new StringBuilder(256); 6882 } else { 6883 r.append(' '); 6884 } 6885 r.append(name); 6886 } 6887 } 6888 } 6889 } 6890 } 6891 if (r != null) { 6892 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6893 } 6894 } 6895 6896 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6897 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6898 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6899 return true; 6900 } 6901 } 6902 return false; 6903 } 6904 6905 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6906 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6907 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6908 6909 private void updatePermissionsLPw(String changingPkg, 6910 PackageParser.Package pkgInfo, int flags) { 6911 // Make sure there are no dangling permission trees. 6912 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6913 while (it.hasNext()) { 6914 final BasePermission bp = it.next(); 6915 if (bp.packageSetting == null) { 6916 // We may not yet have parsed the package, so just see if 6917 // we still know about its settings. 6918 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6919 } 6920 if (bp.packageSetting == null) { 6921 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6922 + " from package " + bp.sourcePackage); 6923 it.remove(); 6924 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6925 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6926 Slog.i(TAG, "Removing old permission tree: " + bp.name 6927 + " from package " + bp.sourcePackage); 6928 flags |= UPDATE_PERMISSIONS_ALL; 6929 it.remove(); 6930 } 6931 } 6932 } 6933 6934 // Make sure all dynamic permissions have been assigned to a package, 6935 // and make sure there are no dangling permissions. 6936 it = mSettings.mPermissions.values().iterator(); 6937 while (it.hasNext()) { 6938 final BasePermission bp = it.next(); 6939 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6940 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6941 + bp.name + " pkg=" + bp.sourcePackage 6942 + " info=" + bp.pendingInfo); 6943 if (bp.packageSetting == null && bp.pendingInfo != null) { 6944 final BasePermission tree = findPermissionTreeLP(bp.name); 6945 if (tree != null && tree.perm != null) { 6946 bp.packageSetting = tree.packageSetting; 6947 bp.perm = new PackageParser.Permission(tree.perm.owner, 6948 new PermissionInfo(bp.pendingInfo)); 6949 bp.perm.info.packageName = tree.perm.info.packageName; 6950 bp.perm.info.name = bp.name; 6951 bp.uid = tree.uid; 6952 } 6953 } 6954 } 6955 if (bp.packageSetting == null) { 6956 // We may not yet have parsed the package, so just see if 6957 // we still know about its settings. 6958 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6959 } 6960 if (bp.packageSetting == null) { 6961 Slog.w(TAG, "Removing dangling permission: " + bp.name 6962 + " from package " + bp.sourcePackage); 6963 it.remove(); 6964 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6965 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6966 Slog.i(TAG, "Removing old permission: " + bp.name 6967 + " from package " + bp.sourcePackage); 6968 flags |= UPDATE_PERMISSIONS_ALL; 6969 it.remove(); 6970 } 6971 } 6972 } 6973 6974 // Now update the permissions for all packages, in particular 6975 // replace the granted permissions of the system packages. 6976 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6977 for (PackageParser.Package pkg : mPackages.values()) { 6978 if (pkg != pkgInfo) { 6979 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6980 changingPkg); 6981 } 6982 } 6983 } 6984 6985 if (pkgInfo != null) { 6986 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6987 } 6988 } 6989 6990 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6991 String packageOfInterest) { 6992 // IMPORTANT: There are two types of permissions: install and runtime. 6993 // Install time permissions are granted when the app is installed to 6994 // all device users and users added in the future. Runtime permissions 6995 // are granted at runtime explicitly to specific users. Normal and signature 6996 // protected permissions are install time permissions. Dangerous permissions 6997 // are install permissions if the app's target SDK is Lollipop MR1 or older, 6998 // otherwise they are runtime permissions. This function does not manage 6999 // runtime permissions except for the case an app targeting Lollipop MR1 7000 // being upgraded to target a newer SDK, in which case dangerous permissions 7001 // are transformed from install time to runtime ones. 7002 7003 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7004 if (ps == null) { 7005 return; 7006 } 7007 7008 PermissionsState permissionsState = ps.getPermissionsState(); 7009 PermissionsState origPermissions = permissionsState; 7010 7011 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7012 7013 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7014 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7015 7016 boolean changedInstallPermission = false; 7017 7018 if (replace) { 7019 ps.installPermissionsFixed = false; 7020 origPermissions = new PermissionsState(permissionsState); 7021 permissionsState.reset(); 7022 } 7023 7024 permissionsState.setGlobalGids(mGlobalGids); 7025 7026 final int N = pkg.requestedPermissions.size(); 7027 for (int i=0; i<N; i++) { 7028 final String name = pkg.requestedPermissions.get(i); 7029 final BasePermission bp = mSettings.mPermissions.get(name); 7030 7031 if (DEBUG_INSTALL) { 7032 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7033 } 7034 7035 if (bp == null || bp.packageSetting == null) { 7036 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7037 Slog.w(TAG, "Unknown permission " + name 7038 + " in package " + pkg.packageName); 7039 } 7040 continue; 7041 } 7042 7043 final String perm = bp.name; 7044 boolean allowedSig = false; 7045 int grant = GRANT_DENIED; 7046 7047 // Keep track of app op permissions. 7048 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7049 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7050 if (pkgs == null) { 7051 pkgs = new ArraySet<>(); 7052 mAppOpPermissionPackages.put(bp.name, pkgs); 7053 } 7054 pkgs.add(pkg.packageName); 7055 } 7056 7057 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7058 switch (level) { 7059 case PermissionInfo.PROTECTION_NORMAL: { 7060 // For all apps normal permissions are install time ones. 7061 grant = GRANT_INSTALL; 7062 } break; 7063 7064 case PermissionInfo.PROTECTION_DANGEROUS: { 7065 if (!RUNTIME_PERMISSIONS_ENABLED 7066 || pkg.applicationInfo.targetSdkVersion 7067 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7068 // For legacy apps dangerous permissions are install time ones. 7069 grant = GRANT_INSTALL; 7070 } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7071 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7072 if (origPermissions.hasInstallPermission(bp.name)) { 7073 // If a system app had an install permission, then the app was 7074 // upgraded and we grant the permissions as runtime to all users. 7075 grant = GRANT_UPGRADE; 7076 upgradeUserIds = currentUserIds; 7077 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7078 // If users changed since the last permissions update for a 7079 // system app, we grant the permission as runtime to the new users. 7080 grant = GRANT_UPGRADE; 7081 upgradeUserIds = currentUserIds; 7082 for (int userId : updatedUserIds) { 7083 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7084 } 7085 } else { 7086 // Otherwise, we grant the permission as runtime if the app 7087 // already had it, i.e. we preserve runtime permissions. 7088 grant = GRANT_RUNTIME; 7089 } 7090 } else if (origPermissions.hasInstallPermission(bp.name)) { 7091 // For legacy apps that became modern, install becomes runtime. 7092 grant = GRANT_UPGRADE; 7093 upgradeUserIds = currentUserIds; 7094 } else if (replace) { 7095 // For upgraded modern apps keep runtime permissions unchanged. 7096 grant = GRANT_RUNTIME; 7097 } 7098 } break; 7099 7100 case PermissionInfo.PROTECTION_SIGNATURE: { 7101 // For all apps signature permissions are install time ones. 7102 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7103 if (allowedSig) { 7104 grant = GRANT_INSTALL; 7105 } 7106 } break; 7107 } 7108 7109 if (DEBUG_INSTALL) { 7110 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7111 } 7112 7113 if (grant != GRANT_DENIED) { 7114 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7115 // If this is an existing, non-system package, then 7116 // we can't add any new permissions to it. 7117 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7118 // Except... if this is a permission that was added 7119 // to the platform (note: need to only do this when 7120 // updating the platform). 7121 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7122 grant = GRANT_DENIED; 7123 } 7124 } 7125 } 7126 7127 switch (grant) { 7128 case GRANT_INSTALL: { 7129 // Grant an install permission. 7130 if (permissionsState.grantInstallPermission(bp) != 7131 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7132 changedInstallPermission = true; 7133 } 7134 } break; 7135 7136 case GRANT_RUNTIME: { 7137 // Grant previously granted runtime permissions. 7138 for (int userId : UserManagerService.getInstance().getUserIds()) { 7139 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7140 if (permissionsState.grantRuntimePermission(bp, userId) == 7141 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7142 // If we cannot put the permission as it was, we have to write. 7143 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7144 changedRuntimePermissionUserIds, userId); 7145 } 7146 } 7147 } 7148 } break; 7149 7150 case GRANT_UPGRADE: { 7151 // Grant runtime permissions for a previously held install permission. 7152 permissionsState.revokeInstallPermission(bp); 7153 for (int userId : upgradeUserIds) { 7154 if (permissionsState.grantRuntimePermission(bp, userId) != 7155 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7156 // If we granted the permission, we have to write. 7157 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7158 changedRuntimePermissionUserIds, userId); 7159 } 7160 } 7161 } break; 7162 7163 default: { 7164 if (packageOfInterest == null 7165 || packageOfInterest.equals(pkg.packageName)) { 7166 Slog.w(TAG, "Not granting permission " + perm 7167 + " to package " + pkg.packageName 7168 + " because it was previously installed without"); 7169 } 7170 } break; 7171 } 7172 } else { 7173 if (permissionsState.revokeInstallPermission(bp) != 7174 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7175 changedInstallPermission = true; 7176 Slog.i(TAG, "Un-granting permission " + perm 7177 + " from package " + pkg.packageName 7178 + " (protectionLevel=" + bp.protectionLevel 7179 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7180 + ")"); 7181 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7182 // Don't print warning for app op permissions, since it is fine for them 7183 // not to be granted, there is a UI for the user to decide. 7184 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7185 Slog.w(TAG, "Not granting permission " + perm 7186 + " to package " + pkg.packageName 7187 + " (protectionLevel=" + bp.protectionLevel 7188 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7189 + ")"); 7190 } 7191 } 7192 } 7193 } 7194 7195 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7196 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7197 // This is the first that we have heard about this package, so the 7198 // permissions we have now selected are fixed until explicitly 7199 // changed. 7200 ps.installPermissionsFixed = true; 7201 } 7202 7203 ps.setPermissionsUpdatedForUserIds(changedRuntimePermissionUserIds); 7204 7205 // Persist the runtime permissions state for users with changes. 7206 for (int userId : changedRuntimePermissionUserIds) { 7207 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7208 } 7209 } 7210 7211 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7212 boolean allowed = false; 7213 final int NP = PackageParser.NEW_PERMISSIONS.length; 7214 for (int ip=0; ip<NP; ip++) { 7215 final PackageParser.NewPermissionInfo npi 7216 = PackageParser.NEW_PERMISSIONS[ip]; 7217 if (npi.name.equals(perm) 7218 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7219 allowed = true; 7220 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7221 + pkg.packageName); 7222 break; 7223 } 7224 } 7225 return allowed; 7226 } 7227 7228 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7229 BasePermission bp, PermissionsState origPermissions) { 7230 boolean allowed; 7231 allowed = (compareSignatures( 7232 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7233 == PackageManager.SIGNATURE_MATCH) 7234 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7235 == PackageManager.SIGNATURE_MATCH); 7236 if (!allowed && (bp.protectionLevel 7237 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7238 if (isSystemApp(pkg)) { 7239 // For updated system applications, a system permission 7240 // is granted only if it had been defined by the original application. 7241 if (isUpdatedSystemApp(pkg)) { 7242 final PackageSetting sysPs = mSettings 7243 .getDisabledSystemPkgLPr(pkg.packageName); 7244 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7245 // If the original was granted this permission, we take 7246 // that grant decision as read and propagate it to the 7247 // update. 7248 if (sysPs.isPrivileged()) { 7249 allowed = true; 7250 } 7251 } else { 7252 // The system apk may have been updated with an older 7253 // version of the one on the data partition, but which 7254 // granted a new system permission that it didn't have 7255 // before. In this case we do want to allow the app to 7256 // now get the new permission if the ancestral apk is 7257 // privileged to get it. 7258 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7259 for (int j=0; 7260 j<sysPs.pkg.requestedPermissions.size(); j++) { 7261 if (perm.equals( 7262 sysPs.pkg.requestedPermissions.get(j))) { 7263 allowed = true; 7264 break; 7265 } 7266 } 7267 } 7268 } 7269 } else { 7270 allowed = isPrivilegedApp(pkg); 7271 } 7272 } 7273 } 7274 if (!allowed && (bp.protectionLevel 7275 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7276 // For development permissions, a development permission 7277 // is granted only if it was already granted. 7278 allowed = origPermissions.hasInstallPermission(perm); 7279 } 7280 return allowed; 7281 } 7282 7283 final class ActivityIntentResolver 7284 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7285 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7286 boolean defaultOnly, int userId) { 7287 if (!sUserManager.exists(userId)) return null; 7288 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7289 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7290 } 7291 7292 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7293 int userId) { 7294 if (!sUserManager.exists(userId)) return null; 7295 mFlags = flags; 7296 return super.queryIntent(intent, resolvedType, 7297 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7298 } 7299 7300 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7301 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7302 if (!sUserManager.exists(userId)) return null; 7303 if (packageActivities == null) { 7304 return null; 7305 } 7306 mFlags = flags; 7307 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7308 final int N = packageActivities.size(); 7309 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7310 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7311 7312 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7313 for (int i = 0; i < N; ++i) { 7314 intentFilters = packageActivities.get(i).intents; 7315 if (intentFilters != null && intentFilters.size() > 0) { 7316 PackageParser.ActivityIntentInfo[] array = 7317 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7318 intentFilters.toArray(array); 7319 listCut.add(array); 7320 } 7321 } 7322 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7323 } 7324 7325 public final void addActivity(PackageParser.Activity a, String type) { 7326 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7327 mActivities.put(a.getComponentName(), a); 7328 if (DEBUG_SHOW_INFO) 7329 Log.v( 7330 TAG, " " + type + " " + 7331 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7332 if (DEBUG_SHOW_INFO) 7333 Log.v(TAG, " Class=" + a.info.name); 7334 final int NI = a.intents.size(); 7335 for (int j=0; j<NI; j++) { 7336 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7337 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7338 intent.setPriority(0); 7339 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7340 + a.className + " with priority > 0, forcing to 0"); 7341 } 7342 if (DEBUG_SHOW_INFO) { 7343 Log.v(TAG, " IntentFilter:"); 7344 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7345 } 7346 if (!intent.debugCheck()) { 7347 Log.w(TAG, "==> For Activity " + a.info.name); 7348 } 7349 addFilter(intent); 7350 } 7351 } 7352 7353 public final void removeActivity(PackageParser.Activity a, String type) { 7354 mActivities.remove(a.getComponentName()); 7355 if (DEBUG_SHOW_INFO) { 7356 Log.v(TAG, " " + type + " " 7357 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7358 : a.info.name) + ":"); 7359 Log.v(TAG, " Class=" + a.info.name); 7360 } 7361 final int NI = a.intents.size(); 7362 for (int j=0; j<NI; j++) { 7363 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7364 if (DEBUG_SHOW_INFO) { 7365 Log.v(TAG, " IntentFilter:"); 7366 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7367 } 7368 removeFilter(intent); 7369 } 7370 } 7371 7372 @Override 7373 protected boolean allowFilterResult( 7374 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7375 ActivityInfo filterAi = filter.activity.info; 7376 for (int i=dest.size()-1; i>=0; i--) { 7377 ActivityInfo destAi = dest.get(i).activityInfo; 7378 if (destAi.name == filterAi.name 7379 && destAi.packageName == filterAi.packageName) { 7380 return false; 7381 } 7382 } 7383 return true; 7384 } 7385 7386 @Override 7387 protected ActivityIntentInfo[] newArray(int size) { 7388 return new ActivityIntentInfo[size]; 7389 } 7390 7391 @Override 7392 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7393 if (!sUserManager.exists(userId)) return true; 7394 PackageParser.Package p = filter.activity.owner; 7395 if (p != null) { 7396 PackageSetting ps = (PackageSetting)p.mExtras; 7397 if (ps != null) { 7398 // System apps are never considered stopped for purposes of 7399 // filtering, because there may be no way for the user to 7400 // actually re-launch them. 7401 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7402 && ps.getStopped(userId); 7403 } 7404 } 7405 return false; 7406 } 7407 7408 @Override 7409 protected boolean isPackageForFilter(String packageName, 7410 PackageParser.ActivityIntentInfo info) { 7411 return packageName.equals(info.activity.owner.packageName); 7412 } 7413 7414 @Override 7415 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7416 int match, int userId) { 7417 if (!sUserManager.exists(userId)) return null; 7418 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7419 return null; 7420 } 7421 final PackageParser.Activity activity = info.activity; 7422 if (mSafeMode && (activity.info.applicationInfo.flags 7423 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7424 return null; 7425 } 7426 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7427 if (ps == null) { 7428 return null; 7429 } 7430 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7431 ps.readUserState(userId), userId); 7432 if (ai == null) { 7433 return null; 7434 } 7435 final ResolveInfo res = new ResolveInfo(); 7436 res.activityInfo = ai; 7437 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7438 res.filter = info; 7439 } 7440 res.priority = info.getPriority(); 7441 res.preferredOrder = activity.owner.mPreferredOrder; 7442 //System.out.println("Result: " + res.activityInfo.className + 7443 // " = " + res.priority); 7444 res.match = match; 7445 res.isDefault = info.hasDefault; 7446 res.labelRes = info.labelRes; 7447 res.nonLocalizedLabel = info.nonLocalizedLabel; 7448 if (userNeedsBadging(userId)) { 7449 res.noResourceId = true; 7450 } else { 7451 res.icon = info.icon; 7452 } 7453 res.system = isSystemApp(res.activityInfo.applicationInfo); 7454 return res; 7455 } 7456 7457 @Override 7458 protected void sortResults(List<ResolveInfo> results) { 7459 Collections.sort(results, mResolvePrioritySorter); 7460 } 7461 7462 @Override 7463 protected void dumpFilter(PrintWriter out, String prefix, 7464 PackageParser.ActivityIntentInfo filter) { 7465 out.print(prefix); out.print( 7466 Integer.toHexString(System.identityHashCode(filter.activity))); 7467 out.print(' '); 7468 filter.activity.printComponentShortName(out); 7469 out.print(" filter "); 7470 out.println(Integer.toHexString(System.identityHashCode(filter))); 7471 } 7472 7473 @Override 7474 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7475 return filter.activity; 7476 } 7477 7478 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7479 PackageParser.Activity activity = (PackageParser.Activity)label; 7480 out.print(prefix); out.print( 7481 Integer.toHexString(System.identityHashCode(activity))); 7482 out.print(' '); 7483 activity.printComponentShortName(out); 7484 if (count > 1) { 7485 out.print(" ("); out.print(count); out.print(" filters)"); 7486 } 7487 out.println(); 7488 } 7489 7490// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7491// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7492// final List<ResolveInfo> retList = Lists.newArrayList(); 7493// while (i.hasNext()) { 7494// final ResolveInfo resolveInfo = i.next(); 7495// if (isEnabledLP(resolveInfo.activityInfo)) { 7496// retList.add(resolveInfo); 7497// } 7498// } 7499// return retList; 7500// } 7501 7502 // Keys are String (activity class name), values are Activity. 7503 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7504 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7505 private int mFlags; 7506 } 7507 7508 private final class ServiceIntentResolver 7509 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7510 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7511 boolean defaultOnly, int userId) { 7512 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7513 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7514 } 7515 7516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7517 int userId) { 7518 if (!sUserManager.exists(userId)) return null; 7519 mFlags = flags; 7520 return super.queryIntent(intent, resolvedType, 7521 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7522 } 7523 7524 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7525 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7526 if (!sUserManager.exists(userId)) return null; 7527 if (packageServices == null) { 7528 return null; 7529 } 7530 mFlags = flags; 7531 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7532 final int N = packageServices.size(); 7533 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7534 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7535 7536 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7537 for (int i = 0; i < N; ++i) { 7538 intentFilters = packageServices.get(i).intents; 7539 if (intentFilters != null && intentFilters.size() > 0) { 7540 PackageParser.ServiceIntentInfo[] array = 7541 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7542 intentFilters.toArray(array); 7543 listCut.add(array); 7544 } 7545 } 7546 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7547 } 7548 7549 public final void addService(PackageParser.Service s) { 7550 mServices.put(s.getComponentName(), s); 7551 if (DEBUG_SHOW_INFO) { 7552 Log.v(TAG, " " 7553 + (s.info.nonLocalizedLabel != null 7554 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7555 Log.v(TAG, " Class=" + s.info.name); 7556 } 7557 final int NI = s.intents.size(); 7558 int j; 7559 for (j=0; j<NI; j++) { 7560 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7561 if (DEBUG_SHOW_INFO) { 7562 Log.v(TAG, " IntentFilter:"); 7563 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7564 } 7565 if (!intent.debugCheck()) { 7566 Log.w(TAG, "==> For Service " + s.info.name); 7567 } 7568 addFilter(intent); 7569 } 7570 } 7571 7572 public final void removeService(PackageParser.Service s) { 7573 mServices.remove(s.getComponentName()); 7574 if (DEBUG_SHOW_INFO) { 7575 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7576 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7577 Log.v(TAG, " Class=" + s.info.name); 7578 } 7579 final int NI = s.intents.size(); 7580 int j; 7581 for (j=0; j<NI; j++) { 7582 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7583 if (DEBUG_SHOW_INFO) { 7584 Log.v(TAG, " IntentFilter:"); 7585 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7586 } 7587 removeFilter(intent); 7588 } 7589 } 7590 7591 @Override 7592 protected boolean allowFilterResult( 7593 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7594 ServiceInfo filterSi = filter.service.info; 7595 for (int i=dest.size()-1; i>=0; i--) { 7596 ServiceInfo destAi = dest.get(i).serviceInfo; 7597 if (destAi.name == filterSi.name 7598 && destAi.packageName == filterSi.packageName) { 7599 return false; 7600 } 7601 } 7602 return true; 7603 } 7604 7605 @Override 7606 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7607 return new PackageParser.ServiceIntentInfo[size]; 7608 } 7609 7610 @Override 7611 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7612 if (!sUserManager.exists(userId)) return true; 7613 PackageParser.Package p = filter.service.owner; 7614 if (p != null) { 7615 PackageSetting ps = (PackageSetting)p.mExtras; 7616 if (ps != null) { 7617 // System apps are never considered stopped for purposes of 7618 // filtering, because there may be no way for the user to 7619 // actually re-launch them. 7620 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7621 && ps.getStopped(userId); 7622 } 7623 } 7624 return false; 7625 } 7626 7627 @Override 7628 protected boolean isPackageForFilter(String packageName, 7629 PackageParser.ServiceIntentInfo info) { 7630 return packageName.equals(info.service.owner.packageName); 7631 } 7632 7633 @Override 7634 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7635 int match, int userId) { 7636 if (!sUserManager.exists(userId)) return null; 7637 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7638 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7639 return null; 7640 } 7641 final PackageParser.Service service = info.service; 7642 if (mSafeMode && (service.info.applicationInfo.flags 7643 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7644 return null; 7645 } 7646 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7647 if (ps == null) { 7648 return null; 7649 } 7650 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7651 ps.readUserState(userId), userId); 7652 if (si == null) { 7653 return null; 7654 } 7655 final ResolveInfo res = new ResolveInfo(); 7656 res.serviceInfo = si; 7657 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7658 res.filter = filter; 7659 } 7660 res.priority = info.getPriority(); 7661 res.preferredOrder = service.owner.mPreferredOrder; 7662 //System.out.println("Result: " + res.activityInfo.className + 7663 // " = " + res.priority); 7664 res.match = match; 7665 res.isDefault = info.hasDefault; 7666 res.labelRes = info.labelRes; 7667 res.nonLocalizedLabel = info.nonLocalizedLabel; 7668 res.icon = info.icon; 7669 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7670 return res; 7671 } 7672 7673 @Override 7674 protected void sortResults(List<ResolveInfo> results) { 7675 Collections.sort(results, mResolvePrioritySorter); 7676 } 7677 7678 @Override 7679 protected void dumpFilter(PrintWriter out, String prefix, 7680 PackageParser.ServiceIntentInfo filter) { 7681 out.print(prefix); out.print( 7682 Integer.toHexString(System.identityHashCode(filter.service))); 7683 out.print(' '); 7684 filter.service.printComponentShortName(out); 7685 out.print(" filter "); 7686 out.println(Integer.toHexString(System.identityHashCode(filter))); 7687 } 7688 7689 @Override 7690 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7691 return filter.service; 7692 } 7693 7694 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7695 PackageParser.Service service = (PackageParser.Service)label; 7696 out.print(prefix); out.print( 7697 Integer.toHexString(System.identityHashCode(service))); 7698 out.print(' '); 7699 service.printComponentShortName(out); 7700 if (count > 1) { 7701 out.print(" ("); out.print(count); out.print(" filters)"); 7702 } 7703 out.println(); 7704 } 7705 7706// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7707// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7708// final List<ResolveInfo> retList = Lists.newArrayList(); 7709// while (i.hasNext()) { 7710// final ResolveInfo resolveInfo = (ResolveInfo) i; 7711// if (isEnabledLP(resolveInfo.serviceInfo)) { 7712// retList.add(resolveInfo); 7713// } 7714// } 7715// return retList; 7716// } 7717 7718 // Keys are String (activity class name), values are Activity. 7719 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7720 = new ArrayMap<ComponentName, PackageParser.Service>(); 7721 private int mFlags; 7722 }; 7723 7724 private final class ProviderIntentResolver 7725 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7726 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7727 boolean defaultOnly, int userId) { 7728 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7729 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7730 } 7731 7732 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7733 int userId) { 7734 if (!sUserManager.exists(userId)) 7735 return null; 7736 mFlags = flags; 7737 return super.queryIntent(intent, resolvedType, 7738 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7739 } 7740 7741 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7742 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7743 if (!sUserManager.exists(userId)) 7744 return null; 7745 if (packageProviders == null) { 7746 return null; 7747 } 7748 mFlags = flags; 7749 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7750 final int N = packageProviders.size(); 7751 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7752 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7753 7754 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7755 for (int i = 0; i < N; ++i) { 7756 intentFilters = packageProviders.get(i).intents; 7757 if (intentFilters != null && intentFilters.size() > 0) { 7758 PackageParser.ProviderIntentInfo[] array = 7759 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7760 intentFilters.toArray(array); 7761 listCut.add(array); 7762 } 7763 } 7764 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7765 } 7766 7767 public final void addProvider(PackageParser.Provider p) { 7768 if (mProviders.containsKey(p.getComponentName())) { 7769 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7770 return; 7771 } 7772 7773 mProviders.put(p.getComponentName(), p); 7774 if (DEBUG_SHOW_INFO) { 7775 Log.v(TAG, " " 7776 + (p.info.nonLocalizedLabel != null 7777 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7778 Log.v(TAG, " Class=" + p.info.name); 7779 } 7780 final int NI = p.intents.size(); 7781 int j; 7782 for (j = 0; j < NI; j++) { 7783 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7784 if (DEBUG_SHOW_INFO) { 7785 Log.v(TAG, " IntentFilter:"); 7786 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7787 } 7788 if (!intent.debugCheck()) { 7789 Log.w(TAG, "==> For Provider " + p.info.name); 7790 } 7791 addFilter(intent); 7792 } 7793 } 7794 7795 public final void removeProvider(PackageParser.Provider p) { 7796 mProviders.remove(p.getComponentName()); 7797 if (DEBUG_SHOW_INFO) { 7798 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7799 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7800 Log.v(TAG, " Class=" + p.info.name); 7801 } 7802 final int NI = p.intents.size(); 7803 int j; 7804 for (j = 0; j < NI; j++) { 7805 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7806 if (DEBUG_SHOW_INFO) { 7807 Log.v(TAG, " IntentFilter:"); 7808 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7809 } 7810 removeFilter(intent); 7811 } 7812 } 7813 7814 @Override 7815 protected boolean allowFilterResult( 7816 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7817 ProviderInfo filterPi = filter.provider.info; 7818 for (int i = dest.size() - 1; i >= 0; i--) { 7819 ProviderInfo destPi = dest.get(i).providerInfo; 7820 if (destPi.name == filterPi.name 7821 && destPi.packageName == filterPi.packageName) { 7822 return false; 7823 } 7824 } 7825 return true; 7826 } 7827 7828 @Override 7829 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7830 return new PackageParser.ProviderIntentInfo[size]; 7831 } 7832 7833 @Override 7834 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7835 if (!sUserManager.exists(userId)) 7836 return true; 7837 PackageParser.Package p = filter.provider.owner; 7838 if (p != null) { 7839 PackageSetting ps = (PackageSetting) p.mExtras; 7840 if (ps != null) { 7841 // System apps are never considered stopped for purposes of 7842 // filtering, because there may be no way for the user to 7843 // actually re-launch them. 7844 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7845 && ps.getStopped(userId); 7846 } 7847 } 7848 return false; 7849 } 7850 7851 @Override 7852 protected boolean isPackageForFilter(String packageName, 7853 PackageParser.ProviderIntentInfo info) { 7854 return packageName.equals(info.provider.owner.packageName); 7855 } 7856 7857 @Override 7858 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7859 int match, int userId) { 7860 if (!sUserManager.exists(userId)) 7861 return null; 7862 final PackageParser.ProviderIntentInfo info = filter; 7863 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7864 return null; 7865 } 7866 final PackageParser.Provider provider = info.provider; 7867 if (mSafeMode && (provider.info.applicationInfo.flags 7868 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7869 return null; 7870 } 7871 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7872 if (ps == null) { 7873 return null; 7874 } 7875 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7876 ps.readUserState(userId), userId); 7877 if (pi == null) { 7878 return null; 7879 } 7880 final ResolveInfo res = new ResolveInfo(); 7881 res.providerInfo = pi; 7882 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7883 res.filter = filter; 7884 } 7885 res.priority = info.getPriority(); 7886 res.preferredOrder = provider.owner.mPreferredOrder; 7887 res.match = match; 7888 res.isDefault = info.hasDefault; 7889 res.labelRes = info.labelRes; 7890 res.nonLocalizedLabel = info.nonLocalizedLabel; 7891 res.icon = info.icon; 7892 res.system = isSystemApp(res.providerInfo.applicationInfo); 7893 return res; 7894 } 7895 7896 @Override 7897 protected void sortResults(List<ResolveInfo> results) { 7898 Collections.sort(results, mResolvePrioritySorter); 7899 } 7900 7901 @Override 7902 protected void dumpFilter(PrintWriter out, String prefix, 7903 PackageParser.ProviderIntentInfo filter) { 7904 out.print(prefix); 7905 out.print( 7906 Integer.toHexString(System.identityHashCode(filter.provider))); 7907 out.print(' '); 7908 filter.provider.printComponentShortName(out); 7909 out.print(" filter "); 7910 out.println(Integer.toHexString(System.identityHashCode(filter))); 7911 } 7912 7913 @Override 7914 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7915 return filter.provider; 7916 } 7917 7918 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7919 PackageParser.Provider provider = (PackageParser.Provider)label; 7920 out.print(prefix); out.print( 7921 Integer.toHexString(System.identityHashCode(provider))); 7922 out.print(' '); 7923 provider.printComponentShortName(out); 7924 if (count > 1) { 7925 out.print(" ("); out.print(count); out.print(" filters)"); 7926 } 7927 out.println(); 7928 } 7929 7930 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7931 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7932 private int mFlags; 7933 }; 7934 7935 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7936 new Comparator<ResolveInfo>() { 7937 public int compare(ResolveInfo r1, ResolveInfo r2) { 7938 int v1 = r1.priority; 7939 int v2 = r2.priority; 7940 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7941 if (v1 != v2) { 7942 return (v1 > v2) ? -1 : 1; 7943 } 7944 v1 = r1.preferredOrder; 7945 v2 = r2.preferredOrder; 7946 if (v1 != v2) { 7947 return (v1 > v2) ? -1 : 1; 7948 } 7949 if (r1.isDefault != r2.isDefault) { 7950 return r1.isDefault ? -1 : 1; 7951 } 7952 v1 = r1.match; 7953 v2 = r2.match; 7954 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7955 if (v1 != v2) { 7956 return (v1 > v2) ? -1 : 1; 7957 } 7958 if (r1.system != r2.system) { 7959 return r1.system ? -1 : 1; 7960 } 7961 return 0; 7962 } 7963 }; 7964 7965 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7966 new Comparator<ProviderInfo>() { 7967 public int compare(ProviderInfo p1, ProviderInfo p2) { 7968 final int v1 = p1.initOrder; 7969 final int v2 = p2.initOrder; 7970 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7971 } 7972 }; 7973 7974 static final void sendPackageBroadcast(String action, String pkg, 7975 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7976 int[] userIds) { 7977 IActivityManager am = ActivityManagerNative.getDefault(); 7978 if (am != null) { 7979 try { 7980 if (userIds == null) { 7981 userIds = am.getRunningUserIds(); 7982 } 7983 for (int id : userIds) { 7984 final Intent intent = new Intent(action, 7985 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7986 if (extras != null) { 7987 intent.putExtras(extras); 7988 } 7989 if (targetPkg != null) { 7990 intent.setPackage(targetPkg); 7991 } 7992 // Modify the UID when posting to other users 7993 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7994 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7995 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7996 intent.putExtra(Intent.EXTRA_UID, uid); 7997 } 7998 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7999 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8000 if (DEBUG_BROADCASTS) { 8001 RuntimeException here = new RuntimeException("here"); 8002 here.fillInStackTrace(); 8003 Slog.d(TAG, "Sending to user " + id + ": " 8004 + intent.toShortString(false, true, false, false) 8005 + " " + intent.getExtras(), here); 8006 } 8007 am.broadcastIntent(null, intent, null, finishedReceiver, 8008 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8009 finishedReceiver != null, false, id); 8010 } 8011 } catch (RemoteException ex) { 8012 } 8013 } 8014 } 8015 8016 /** 8017 * Check if the external storage media is available. This is true if there 8018 * is a mounted external storage medium or if the external storage is 8019 * emulated. 8020 */ 8021 private boolean isExternalMediaAvailable() { 8022 return mMediaMounted || Environment.isExternalStorageEmulated(); 8023 } 8024 8025 @Override 8026 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8027 // writer 8028 synchronized (mPackages) { 8029 if (!isExternalMediaAvailable()) { 8030 // If the external storage is no longer mounted at this point, 8031 // the caller may not have been able to delete all of this 8032 // packages files and can not delete any more. Bail. 8033 return null; 8034 } 8035 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8036 if (lastPackage != null) { 8037 pkgs.remove(lastPackage); 8038 } 8039 if (pkgs.size() > 0) { 8040 return pkgs.get(0); 8041 } 8042 } 8043 return null; 8044 } 8045 8046 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8047 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8048 userId, andCode ? 1 : 0, packageName); 8049 if (mSystemReady) { 8050 msg.sendToTarget(); 8051 } else { 8052 if (mPostSystemReadyMessages == null) { 8053 mPostSystemReadyMessages = new ArrayList<>(); 8054 } 8055 mPostSystemReadyMessages.add(msg); 8056 } 8057 } 8058 8059 void startCleaningPackages() { 8060 // reader 8061 synchronized (mPackages) { 8062 if (!isExternalMediaAvailable()) { 8063 return; 8064 } 8065 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8066 return; 8067 } 8068 } 8069 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8070 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8071 IActivityManager am = ActivityManagerNative.getDefault(); 8072 if (am != null) { 8073 try { 8074 am.startService(null, intent, null, UserHandle.USER_OWNER); 8075 } catch (RemoteException e) { 8076 } 8077 } 8078 } 8079 8080 @Override 8081 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8082 int installFlags, String installerPackageName, VerificationParams verificationParams, 8083 String packageAbiOverride) { 8084 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8085 packageAbiOverride, UserHandle.getCallingUserId()); 8086 } 8087 8088 @Override 8089 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8090 int installFlags, String installerPackageName, VerificationParams verificationParams, 8091 String packageAbiOverride, int userId) { 8092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8093 8094 final int callingUid = Binder.getCallingUid(); 8095 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8096 8097 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8098 try { 8099 if (observer != null) { 8100 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8101 } 8102 } catch (RemoteException re) { 8103 } 8104 return; 8105 } 8106 8107 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8108 installFlags |= PackageManager.INSTALL_FROM_ADB; 8109 8110 } else { 8111 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8112 // about installerPackageName. 8113 8114 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8115 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8116 } 8117 8118 UserHandle user; 8119 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8120 user = UserHandle.ALL; 8121 } else { 8122 user = new UserHandle(userId); 8123 } 8124 8125 verificationParams.setInstallerUid(callingUid); 8126 8127 final File originFile = new File(originPath); 8128 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8129 8130 final Message msg = mHandler.obtainMessage(INIT_COPY); 8131 msg.obj = new InstallParams(origin, observer, installFlags, 8132 installerPackageName, verificationParams, user, packageAbiOverride); 8133 mHandler.sendMessage(msg); 8134 } 8135 8136 void installStage(String packageName, File stagedDir, String stagedCid, 8137 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8138 String installerPackageName, int installerUid, UserHandle user) { 8139 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8140 params.referrerUri, installerUid, null); 8141 8142 final OriginInfo origin; 8143 if (stagedDir != null) { 8144 origin = OriginInfo.fromStagedFile(stagedDir); 8145 } else { 8146 origin = OriginInfo.fromStagedContainer(stagedCid); 8147 } 8148 8149 final Message msg = mHandler.obtainMessage(INIT_COPY); 8150 msg.obj = new InstallParams(origin, observer, params.installFlags, 8151 installerPackageName, verifParams, user, params.abiOverride); 8152 mHandler.sendMessage(msg); 8153 } 8154 8155 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8156 Bundle extras = new Bundle(1); 8157 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8158 8159 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8160 packageName, extras, null, null, new int[] {userId}); 8161 try { 8162 IActivityManager am = ActivityManagerNative.getDefault(); 8163 final boolean isSystem = 8164 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8165 if (isSystem && am.isUserRunning(userId, false)) { 8166 // The just-installed/enabled app is bundled on the system, so presumed 8167 // to be able to run automatically without needing an explicit launch. 8168 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8169 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8170 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8171 .setPackage(packageName); 8172 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8173 android.app.AppOpsManager.OP_NONE, false, false, userId); 8174 } 8175 } catch (RemoteException e) { 8176 // shouldn't happen 8177 Slog.w(TAG, "Unable to bootstrap installed package", e); 8178 } 8179 } 8180 8181 @Override 8182 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8183 int userId) { 8184 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8185 PackageSetting pkgSetting; 8186 final int uid = Binder.getCallingUid(); 8187 enforceCrossUserPermission(uid, userId, true, true, 8188 "setApplicationHiddenSetting for user " + userId); 8189 8190 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8191 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8192 return false; 8193 } 8194 8195 long callingId = Binder.clearCallingIdentity(); 8196 try { 8197 boolean sendAdded = false; 8198 boolean sendRemoved = false; 8199 // writer 8200 synchronized (mPackages) { 8201 pkgSetting = mSettings.mPackages.get(packageName); 8202 if (pkgSetting == null) { 8203 return false; 8204 } 8205 if (pkgSetting.getHidden(userId) != hidden) { 8206 pkgSetting.setHidden(hidden, userId); 8207 mSettings.writePackageRestrictionsLPr(userId); 8208 if (hidden) { 8209 sendRemoved = true; 8210 } else { 8211 sendAdded = true; 8212 } 8213 } 8214 } 8215 if (sendAdded) { 8216 sendPackageAddedForUser(packageName, pkgSetting, userId); 8217 return true; 8218 } 8219 if (sendRemoved) { 8220 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8221 "hiding pkg"); 8222 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8223 } 8224 } finally { 8225 Binder.restoreCallingIdentity(callingId); 8226 } 8227 return false; 8228 } 8229 8230 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8231 int userId) { 8232 final PackageRemovedInfo info = new PackageRemovedInfo(); 8233 info.removedPackage = packageName; 8234 info.removedUsers = new int[] {userId}; 8235 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8236 info.sendBroadcast(false, false, false); 8237 } 8238 8239 /** 8240 * Returns true if application is not found or there was an error. Otherwise it returns 8241 * the hidden state of the package for the given user. 8242 */ 8243 @Override 8244 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8245 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8246 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8247 false, "getApplicationHidden for user " + userId); 8248 PackageSetting pkgSetting; 8249 long callingId = Binder.clearCallingIdentity(); 8250 try { 8251 // writer 8252 synchronized (mPackages) { 8253 pkgSetting = mSettings.mPackages.get(packageName); 8254 if (pkgSetting == null) { 8255 return true; 8256 } 8257 return pkgSetting.getHidden(userId); 8258 } 8259 } finally { 8260 Binder.restoreCallingIdentity(callingId); 8261 } 8262 } 8263 8264 /** 8265 * @hide 8266 */ 8267 @Override 8268 public int installExistingPackageAsUser(String packageName, int userId) { 8269 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8270 null); 8271 PackageSetting pkgSetting; 8272 final int uid = Binder.getCallingUid(); 8273 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8274 + userId); 8275 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8276 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8277 } 8278 8279 long callingId = Binder.clearCallingIdentity(); 8280 try { 8281 boolean sendAdded = false; 8282 Bundle extras = new Bundle(1); 8283 8284 // writer 8285 synchronized (mPackages) { 8286 pkgSetting = mSettings.mPackages.get(packageName); 8287 if (pkgSetting == null) { 8288 return PackageManager.INSTALL_FAILED_INVALID_URI; 8289 } 8290 if (!pkgSetting.getInstalled(userId)) { 8291 pkgSetting.setInstalled(true, userId); 8292 pkgSetting.setHidden(false, userId); 8293 mSettings.writePackageRestrictionsLPr(userId); 8294 sendAdded = true; 8295 } 8296 } 8297 8298 if (sendAdded) { 8299 sendPackageAddedForUser(packageName, pkgSetting, userId); 8300 } 8301 } finally { 8302 Binder.restoreCallingIdentity(callingId); 8303 } 8304 8305 return PackageManager.INSTALL_SUCCEEDED; 8306 } 8307 8308 boolean isUserRestricted(int userId, String restrictionKey) { 8309 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8310 if (restrictions.getBoolean(restrictionKey, false)) { 8311 Log.w(TAG, "User is restricted: " + restrictionKey); 8312 return true; 8313 } 8314 return false; 8315 } 8316 8317 @Override 8318 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8319 mContext.enforceCallingOrSelfPermission( 8320 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8321 "Only package verification agents can verify applications"); 8322 8323 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8324 final PackageVerificationResponse response = new PackageVerificationResponse( 8325 verificationCode, Binder.getCallingUid()); 8326 msg.arg1 = id; 8327 msg.obj = response; 8328 mHandler.sendMessage(msg); 8329 } 8330 8331 @Override 8332 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8333 long millisecondsToDelay) { 8334 mContext.enforceCallingOrSelfPermission( 8335 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8336 "Only package verification agents can extend verification timeouts"); 8337 8338 final PackageVerificationState state = mPendingVerification.get(id); 8339 final PackageVerificationResponse response = new PackageVerificationResponse( 8340 verificationCodeAtTimeout, Binder.getCallingUid()); 8341 8342 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8343 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8344 } 8345 if (millisecondsToDelay < 0) { 8346 millisecondsToDelay = 0; 8347 } 8348 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8349 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8350 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8351 } 8352 8353 if ((state != null) && !state.timeoutExtended()) { 8354 state.extendTimeout(); 8355 8356 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8357 msg.arg1 = id; 8358 msg.obj = response; 8359 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8360 } 8361 } 8362 8363 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8364 int verificationCode, UserHandle user) { 8365 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8366 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8367 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8368 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8369 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8370 8371 mContext.sendBroadcastAsUser(intent, user, 8372 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8373 } 8374 8375 private ComponentName matchComponentForVerifier(String packageName, 8376 List<ResolveInfo> receivers) { 8377 ActivityInfo targetReceiver = null; 8378 8379 final int NR = receivers.size(); 8380 for (int i = 0; i < NR; i++) { 8381 final ResolveInfo info = receivers.get(i); 8382 if (info.activityInfo == null) { 8383 continue; 8384 } 8385 8386 if (packageName.equals(info.activityInfo.packageName)) { 8387 targetReceiver = info.activityInfo; 8388 break; 8389 } 8390 } 8391 8392 if (targetReceiver == null) { 8393 return null; 8394 } 8395 8396 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8397 } 8398 8399 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8400 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8401 if (pkgInfo.verifiers.length == 0) { 8402 return null; 8403 } 8404 8405 final int N = pkgInfo.verifiers.length; 8406 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8407 for (int i = 0; i < N; i++) { 8408 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8409 8410 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8411 receivers); 8412 if (comp == null) { 8413 continue; 8414 } 8415 8416 final int verifierUid = getUidForVerifier(verifierInfo); 8417 if (verifierUid == -1) { 8418 continue; 8419 } 8420 8421 if (DEBUG_VERIFY) { 8422 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8423 + " with the correct signature"); 8424 } 8425 sufficientVerifiers.add(comp); 8426 verificationState.addSufficientVerifier(verifierUid); 8427 } 8428 8429 return sufficientVerifiers; 8430 } 8431 8432 private int getUidForVerifier(VerifierInfo verifierInfo) { 8433 synchronized (mPackages) { 8434 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8435 if (pkg == null) { 8436 return -1; 8437 } else if (pkg.mSignatures.length != 1) { 8438 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8439 + " has more than one signature; ignoring"); 8440 return -1; 8441 } 8442 8443 /* 8444 * If the public key of the package's signature does not match 8445 * our expected public key, then this is a different package and 8446 * we should skip. 8447 */ 8448 8449 final byte[] expectedPublicKey; 8450 try { 8451 final Signature verifierSig = pkg.mSignatures[0]; 8452 final PublicKey publicKey = verifierSig.getPublicKey(); 8453 expectedPublicKey = publicKey.getEncoded(); 8454 } catch (CertificateException e) { 8455 return -1; 8456 } 8457 8458 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8459 8460 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8461 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8462 + " does not have the expected public key; ignoring"); 8463 return -1; 8464 } 8465 8466 return pkg.applicationInfo.uid; 8467 } 8468 } 8469 8470 @Override 8471 public void finishPackageInstall(int token) { 8472 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8473 8474 if (DEBUG_INSTALL) { 8475 Slog.v(TAG, "BM finishing package install for " + token); 8476 } 8477 8478 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8479 mHandler.sendMessage(msg); 8480 } 8481 8482 /** 8483 * Get the verification agent timeout. 8484 * 8485 * @return verification timeout in milliseconds 8486 */ 8487 private long getVerificationTimeout() { 8488 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8489 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8490 DEFAULT_VERIFICATION_TIMEOUT); 8491 } 8492 8493 /** 8494 * Get the default verification agent response code. 8495 * 8496 * @return default verification response code 8497 */ 8498 private int getDefaultVerificationResponse() { 8499 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8500 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8501 DEFAULT_VERIFICATION_RESPONSE); 8502 } 8503 8504 /** 8505 * Check whether or not package verification has been enabled. 8506 * 8507 * @return true if verification should be performed 8508 */ 8509 private boolean isVerificationEnabled(int userId, int installFlags) { 8510 if (!DEFAULT_VERIFY_ENABLE) { 8511 return false; 8512 } 8513 8514 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8515 8516 // Check if installing from ADB 8517 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8518 // Do not run verification in a test harness environment 8519 if (ActivityManager.isRunningInTestHarness()) { 8520 return false; 8521 } 8522 if (ensureVerifyAppsEnabled) { 8523 return true; 8524 } 8525 // Check if the developer does not want package verification for ADB installs 8526 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8527 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8528 return false; 8529 } 8530 } 8531 8532 if (ensureVerifyAppsEnabled) { 8533 return true; 8534 } 8535 8536 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8537 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8538 } 8539 8540 /** 8541 * Get the "allow unknown sources" setting. 8542 * 8543 * @return the current "allow unknown sources" setting 8544 */ 8545 private int getUnknownSourcesSettings() { 8546 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8547 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8548 -1); 8549 } 8550 8551 @Override 8552 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8553 final int uid = Binder.getCallingUid(); 8554 // writer 8555 synchronized (mPackages) { 8556 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8557 if (targetPackageSetting == null) { 8558 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8559 } 8560 8561 PackageSetting installerPackageSetting; 8562 if (installerPackageName != null) { 8563 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8564 if (installerPackageSetting == null) { 8565 throw new IllegalArgumentException("Unknown installer package: " 8566 + installerPackageName); 8567 } 8568 } else { 8569 installerPackageSetting = null; 8570 } 8571 8572 Signature[] callerSignature; 8573 Object obj = mSettings.getUserIdLPr(uid); 8574 if (obj != null) { 8575 if (obj instanceof SharedUserSetting) { 8576 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8577 } else if (obj instanceof PackageSetting) { 8578 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8579 } else { 8580 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8581 } 8582 } else { 8583 throw new SecurityException("Unknown calling uid " + uid); 8584 } 8585 8586 // Verify: can't set installerPackageName to a package that is 8587 // not signed with the same cert as the caller. 8588 if (installerPackageSetting != null) { 8589 if (compareSignatures(callerSignature, 8590 installerPackageSetting.signatures.mSignatures) 8591 != PackageManager.SIGNATURE_MATCH) { 8592 throw new SecurityException( 8593 "Caller does not have same cert as new installer package " 8594 + installerPackageName); 8595 } 8596 } 8597 8598 // Verify: if target already has an installer package, it must 8599 // be signed with the same cert as the caller. 8600 if (targetPackageSetting.installerPackageName != null) { 8601 PackageSetting setting = mSettings.mPackages.get( 8602 targetPackageSetting.installerPackageName); 8603 // If the currently set package isn't valid, then it's always 8604 // okay to change it. 8605 if (setting != null) { 8606 if (compareSignatures(callerSignature, 8607 setting.signatures.mSignatures) 8608 != PackageManager.SIGNATURE_MATCH) { 8609 throw new SecurityException( 8610 "Caller does not have same cert as old installer package " 8611 + targetPackageSetting.installerPackageName); 8612 } 8613 } 8614 } 8615 8616 // Okay! 8617 targetPackageSetting.installerPackageName = installerPackageName; 8618 scheduleWriteSettingsLocked(); 8619 } 8620 } 8621 8622 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8623 // Queue up an async operation since the package installation may take a little while. 8624 mHandler.post(new Runnable() { 8625 public void run() { 8626 mHandler.removeCallbacks(this); 8627 // Result object to be returned 8628 PackageInstalledInfo res = new PackageInstalledInfo(); 8629 res.returnCode = currentStatus; 8630 res.uid = -1; 8631 res.pkg = null; 8632 res.removedInfo = new PackageRemovedInfo(); 8633 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8634 args.doPreInstall(res.returnCode); 8635 synchronized (mInstallLock) { 8636 installPackageLI(args, res); 8637 } 8638 args.doPostInstall(res.returnCode, res.uid); 8639 } 8640 8641 // A restore should be performed at this point if (a) the install 8642 // succeeded, (b) the operation is not an update, and (c) the new 8643 // package has not opted out of backup participation. 8644 final boolean update = res.removedInfo.removedPackage != null; 8645 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8646 boolean doRestore = !update 8647 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8648 8649 // Set up the post-install work request bookkeeping. This will be used 8650 // and cleaned up by the post-install event handling regardless of whether 8651 // there's a restore pass performed. Token values are >= 1. 8652 int token; 8653 if (mNextInstallToken < 0) mNextInstallToken = 1; 8654 token = mNextInstallToken++; 8655 8656 PostInstallData data = new PostInstallData(args, res); 8657 mRunningInstalls.put(token, data); 8658 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8659 8660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8661 // Pass responsibility to the Backup Manager. It will perform a 8662 // restore if appropriate, then pass responsibility back to the 8663 // Package Manager to run the post-install observer callbacks 8664 // and broadcasts. 8665 IBackupManager bm = IBackupManager.Stub.asInterface( 8666 ServiceManager.getService(Context.BACKUP_SERVICE)); 8667 if (bm != null) { 8668 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8669 + " to BM for possible restore"); 8670 try { 8671 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8672 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8673 } else { 8674 doRestore = false; 8675 } 8676 } catch (RemoteException e) { 8677 // can't happen; the backup manager is local 8678 } catch (Exception e) { 8679 Slog.e(TAG, "Exception trying to enqueue restore", e); 8680 doRestore = false; 8681 } 8682 } else { 8683 Slog.e(TAG, "Backup Manager not found!"); 8684 doRestore = false; 8685 } 8686 } 8687 8688 if (!doRestore) { 8689 // No restore possible, or the Backup Manager was mysteriously not 8690 // available -- just fire the post-install work request directly. 8691 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8692 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8693 mHandler.sendMessage(msg); 8694 } 8695 } 8696 }); 8697 } 8698 8699 private abstract class HandlerParams { 8700 private static final int MAX_RETRIES = 4; 8701 8702 /** 8703 * Number of times startCopy() has been attempted and had a non-fatal 8704 * error. 8705 */ 8706 private int mRetries = 0; 8707 8708 /** User handle for the user requesting the information or installation. */ 8709 private final UserHandle mUser; 8710 8711 HandlerParams(UserHandle user) { 8712 mUser = user; 8713 } 8714 8715 UserHandle getUser() { 8716 return mUser; 8717 } 8718 8719 final boolean startCopy() { 8720 boolean res; 8721 try { 8722 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8723 8724 if (++mRetries > MAX_RETRIES) { 8725 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8726 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8727 handleServiceError(); 8728 return false; 8729 } else { 8730 handleStartCopy(); 8731 res = true; 8732 } 8733 } catch (RemoteException e) { 8734 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8735 mHandler.sendEmptyMessage(MCS_RECONNECT); 8736 res = false; 8737 } 8738 handleReturnCode(); 8739 return res; 8740 } 8741 8742 final void serviceError() { 8743 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8744 handleServiceError(); 8745 handleReturnCode(); 8746 } 8747 8748 abstract void handleStartCopy() throws RemoteException; 8749 abstract void handleServiceError(); 8750 abstract void handleReturnCode(); 8751 } 8752 8753 class MeasureParams extends HandlerParams { 8754 private final PackageStats mStats; 8755 private boolean mSuccess; 8756 8757 private final IPackageStatsObserver mObserver; 8758 8759 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8760 super(new UserHandle(stats.userHandle)); 8761 mObserver = observer; 8762 mStats = stats; 8763 } 8764 8765 @Override 8766 public String toString() { 8767 return "MeasureParams{" 8768 + Integer.toHexString(System.identityHashCode(this)) 8769 + " " + mStats.packageName + "}"; 8770 } 8771 8772 @Override 8773 void handleStartCopy() throws RemoteException { 8774 synchronized (mInstallLock) { 8775 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8776 } 8777 8778 if (mSuccess) { 8779 final boolean mounted; 8780 if (Environment.isExternalStorageEmulated()) { 8781 mounted = true; 8782 } else { 8783 final String status = Environment.getExternalStorageState(); 8784 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8785 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8786 } 8787 8788 if (mounted) { 8789 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8790 8791 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8792 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8793 8794 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8795 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8796 8797 // Always subtract cache size, since it's a subdirectory 8798 mStats.externalDataSize -= mStats.externalCacheSize; 8799 8800 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8801 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8802 8803 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8804 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8805 } 8806 } 8807 } 8808 8809 @Override 8810 void handleReturnCode() { 8811 if (mObserver != null) { 8812 try { 8813 mObserver.onGetStatsCompleted(mStats, mSuccess); 8814 } catch (RemoteException e) { 8815 Slog.i(TAG, "Observer no longer exists."); 8816 } 8817 } 8818 } 8819 8820 @Override 8821 void handleServiceError() { 8822 Slog.e(TAG, "Could not measure application " + mStats.packageName 8823 + " external storage"); 8824 } 8825 } 8826 8827 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8828 throws RemoteException { 8829 long result = 0; 8830 for (File path : paths) { 8831 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8832 } 8833 return result; 8834 } 8835 8836 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8837 for (File path : paths) { 8838 try { 8839 mcs.clearDirectory(path.getAbsolutePath()); 8840 } catch (RemoteException e) { 8841 } 8842 } 8843 } 8844 8845 static class OriginInfo { 8846 /** 8847 * Location where install is coming from, before it has been 8848 * copied/renamed into place. This could be a single monolithic APK 8849 * file, or a cluster directory. This location may be untrusted. 8850 */ 8851 final File file; 8852 final String cid; 8853 8854 /** 8855 * Flag indicating that {@link #file} or {@link #cid} has already been 8856 * staged, meaning downstream users don't need to defensively copy the 8857 * contents. 8858 */ 8859 final boolean staged; 8860 8861 /** 8862 * Flag indicating that {@link #file} or {@link #cid} is an already 8863 * installed app that is being moved. 8864 */ 8865 final boolean existing; 8866 8867 final String resolvedPath; 8868 final File resolvedFile; 8869 8870 static OriginInfo fromNothing() { 8871 return new OriginInfo(null, null, false, false); 8872 } 8873 8874 static OriginInfo fromUntrustedFile(File file) { 8875 return new OriginInfo(file, null, false, false); 8876 } 8877 8878 static OriginInfo fromExistingFile(File file) { 8879 return new OriginInfo(file, null, false, true); 8880 } 8881 8882 static OriginInfo fromStagedFile(File file) { 8883 return new OriginInfo(file, null, true, false); 8884 } 8885 8886 static OriginInfo fromStagedContainer(String cid) { 8887 return new OriginInfo(null, cid, true, false); 8888 } 8889 8890 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8891 this.file = file; 8892 this.cid = cid; 8893 this.staged = staged; 8894 this.existing = existing; 8895 8896 if (cid != null) { 8897 resolvedPath = PackageHelper.getSdDir(cid); 8898 resolvedFile = new File(resolvedPath); 8899 } else if (file != null) { 8900 resolvedPath = file.getAbsolutePath(); 8901 resolvedFile = file; 8902 } else { 8903 resolvedPath = null; 8904 resolvedFile = null; 8905 } 8906 } 8907 } 8908 8909 class InstallParams extends HandlerParams { 8910 final OriginInfo origin; 8911 final IPackageInstallObserver2 observer; 8912 int installFlags; 8913 final String installerPackageName; 8914 final VerificationParams verificationParams; 8915 private InstallArgs mArgs; 8916 private int mRet; 8917 final String packageAbiOverride; 8918 8919 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8920 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8921 String packageAbiOverride) { 8922 super(user); 8923 this.origin = origin; 8924 this.observer = observer; 8925 this.installFlags = installFlags; 8926 this.installerPackageName = installerPackageName; 8927 this.verificationParams = verificationParams; 8928 this.packageAbiOverride = packageAbiOverride; 8929 } 8930 8931 @Override 8932 public String toString() { 8933 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8934 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8935 } 8936 8937 public ManifestDigest getManifestDigest() { 8938 if (verificationParams == null) { 8939 return null; 8940 } 8941 return verificationParams.getManifestDigest(); 8942 } 8943 8944 private int installLocationPolicy(PackageInfoLite pkgLite) { 8945 String packageName = pkgLite.packageName; 8946 int installLocation = pkgLite.installLocation; 8947 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8948 // reader 8949 synchronized (mPackages) { 8950 PackageParser.Package pkg = mPackages.get(packageName); 8951 if (pkg != null) { 8952 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8953 // Check for downgrading. 8954 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8955 try { 8956 checkDowngrade(pkg, pkgLite); 8957 } catch (PackageManagerException e) { 8958 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8959 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8960 } 8961 } 8962 // Check for updated system application. 8963 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8964 if (onSd) { 8965 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8966 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8967 } 8968 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8969 } else { 8970 if (onSd) { 8971 // Install flag overrides everything. 8972 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8973 } 8974 // If current upgrade specifies particular preference 8975 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8976 // Application explicitly specified internal. 8977 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8978 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8979 // App explictly prefers external. Let policy decide 8980 } else { 8981 // Prefer previous location 8982 if (isExternal(pkg)) { 8983 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8984 } 8985 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8986 } 8987 } 8988 } else { 8989 // Invalid install. Return error code 8990 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8991 } 8992 } 8993 } 8994 // All the special cases have been taken care of. 8995 // Return result based on recommended install location. 8996 if (onSd) { 8997 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8998 } 8999 return pkgLite.recommendedInstallLocation; 9000 } 9001 9002 /* 9003 * Invoke remote method to get package information and install 9004 * location values. Override install location based on default 9005 * policy if needed and then create install arguments based 9006 * on the install location. 9007 */ 9008 public void handleStartCopy() throws RemoteException { 9009 int ret = PackageManager.INSTALL_SUCCEEDED; 9010 9011 // If we're already staged, we've firmly committed to an install location 9012 if (origin.staged) { 9013 if (origin.file != null) { 9014 installFlags |= PackageManager.INSTALL_INTERNAL; 9015 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9016 } else if (origin.cid != null) { 9017 installFlags |= PackageManager.INSTALL_EXTERNAL; 9018 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9019 } else { 9020 throw new IllegalStateException("Invalid stage location"); 9021 } 9022 } 9023 9024 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9025 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9026 9027 PackageInfoLite pkgLite = null; 9028 9029 if (onInt && onSd) { 9030 // Check if both bits are set. 9031 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9032 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9033 } else { 9034 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9035 packageAbiOverride); 9036 9037 /* 9038 * If we have too little free space, try to free cache 9039 * before giving up. 9040 */ 9041 if (!origin.staged && pkgLite.recommendedInstallLocation 9042 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9043 // TODO: focus freeing disk space on the target device 9044 final StorageManager storage = StorageManager.from(mContext); 9045 final long lowThreshold = storage.getStorageLowBytes( 9046 Environment.getDataDirectory()); 9047 9048 final long sizeBytes = mContainerService.calculateInstalledSize( 9049 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9050 9051 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9052 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9053 installFlags, packageAbiOverride); 9054 } 9055 9056 /* 9057 * The cache free must have deleted the file we 9058 * downloaded to install. 9059 * 9060 * TODO: fix the "freeCache" call to not delete 9061 * the file we care about. 9062 */ 9063 if (pkgLite.recommendedInstallLocation 9064 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9065 pkgLite.recommendedInstallLocation 9066 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9067 } 9068 } 9069 } 9070 9071 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9072 int loc = pkgLite.recommendedInstallLocation; 9073 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9074 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9075 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9076 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9077 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9078 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9079 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9080 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9081 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9082 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9083 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9084 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9085 } else { 9086 // Override with defaults if needed. 9087 loc = installLocationPolicy(pkgLite); 9088 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9089 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9090 } else if (!onSd && !onInt) { 9091 // Override install location with flags 9092 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9093 // Set the flag to install on external media. 9094 installFlags |= PackageManager.INSTALL_EXTERNAL; 9095 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9096 } else { 9097 // Make sure the flag for installing on external 9098 // media is unset 9099 installFlags |= PackageManager.INSTALL_INTERNAL; 9100 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9101 } 9102 } 9103 } 9104 } 9105 9106 final InstallArgs args = createInstallArgs(this); 9107 mArgs = args; 9108 9109 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9110 /* 9111 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9112 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9113 */ 9114 int userIdentifier = getUser().getIdentifier(); 9115 if (userIdentifier == UserHandle.USER_ALL 9116 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9117 userIdentifier = UserHandle.USER_OWNER; 9118 } 9119 9120 /* 9121 * Determine if we have any installed package verifiers. If we 9122 * do, then we'll defer to them to verify the packages. 9123 */ 9124 final int requiredUid = mRequiredVerifierPackage == null ? -1 9125 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9126 if (!origin.existing && requiredUid != -1 9127 && isVerificationEnabled(userIdentifier, installFlags)) { 9128 final Intent verification = new Intent( 9129 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9130 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9131 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9132 PACKAGE_MIME_TYPE); 9133 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9134 9135 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9136 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9137 0 /* TODO: Which userId? */); 9138 9139 if (DEBUG_VERIFY) { 9140 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9141 + verification.toString() + " with " + pkgLite.verifiers.length 9142 + " optional verifiers"); 9143 } 9144 9145 final int verificationId = mPendingVerificationToken++; 9146 9147 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9148 9149 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9150 installerPackageName); 9151 9152 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9153 installFlags); 9154 9155 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9156 pkgLite.packageName); 9157 9158 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9159 pkgLite.versionCode); 9160 9161 if (verificationParams != null) { 9162 if (verificationParams.getVerificationURI() != null) { 9163 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9164 verificationParams.getVerificationURI()); 9165 } 9166 if (verificationParams.getOriginatingURI() != null) { 9167 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9168 verificationParams.getOriginatingURI()); 9169 } 9170 if (verificationParams.getReferrer() != null) { 9171 verification.putExtra(Intent.EXTRA_REFERRER, 9172 verificationParams.getReferrer()); 9173 } 9174 if (verificationParams.getOriginatingUid() >= 0) { 9175 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9176 verificationParams.getOriginatingUid()); 9177 } 9178 if (verificationParams.getInstallerUid() >= 0) { 9179 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9180 verificationParams.getInstallerUid()); 9181 } 9182 } 9183 9184 final PackageVerificationState verificationState = new PackageVerificationState( 9185 requiredUid, args); 9186 9187 mPendingVerification.append(verificationId, verificationState); 9188 9189 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9190 receivers, verificationState); 9191 9192 /* 9193 * If any sufficient verifiers were listed in the package 9194 * manifest, attempt to ask them. 9195 */ 9196 if (sufficientVerifiers != null) { 9197 final int N = sufficientVerifiers.size(); 9198 if (N == 0) { 9199 Slog.i(TAG, "Additional verifiers required, but none installed."); 9200 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9201 } else { 9202 for (int i = 0; i < N; i++) { 9203 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9204 9205 final Intent sufficientIntent = new Intent(verification); 9206 sufficientIntent.setComponent(verifierComponent); 9207 9208 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9209 } 9210 } 9211 } 9212 9213 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9214 mRequiredVerifierPackage, receivers); 9215 if (ret == PackageManager.INSTALL_SUCCEEDED 9216 && mRequiredVerifierPackage != null) { 9217 /* 9218 * Send the intent to the required verification agent, 9219 * but only start the verification timeout after the 9220 * target BroadcastReceivers have run. 9221 */ 9222 verification.setComponent(requiredVerifierComponent); 9223 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9224 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9225 new BroadcastReceiver() { 9226 @Override 9227 public void onReceive(Context context, Intent intent) { 9228 final Message msg = mHandler 9229 .obtainMessage(CHECK_PENDING_VERIFICATION); 9230 msg.arg1 = verificationId; 9231 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9232 } 9233 }, null, 0, null, null); 9234 9235 /* 9236 * We don't want the copy to proceed until verification 9237 * succeeds, so null out this field. 9238 */ 9239 mArgs = null; 9240 } 9241 } else { 9242 /* 9243 * No package verification is enabled, so immediately start 9244 * the remote call to initiate copy using temporary file. 9245 */ 9246 ret = args.copyApk(mContainerService, true); 9247 } 9248 } 9249 9250 mRet = ret; 9251 } 9252 9253 @Override 9254 void handleReturnCode() { 9255 // If mArgs is null, then MCS couldn't be reached. When it 9256 // reconnects, it will try again to install. At that point, this 9257 // will succeed. 9258 if (mArgs != null) { 9259 processPendingInstall(mArgs, mRet); 9260 } 9261 } 9262 9263 @Override 9264 void handleServiceError() { 9265 mArgs = createInstallArgs(this); 9266 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9267 } 9268 9269 public boolean isForwardLocked() { 9270 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9271 } 9272 } 9273 9274 /** 9275 * Used during creation of InstallArgs 9276 * 9277 * @param installFlags package installation flags 9278 * @return true if should be installed on external storage 9279 */ 9280 private static boolean installOnSd(int installFlags) { 9281 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9282 return false; 9283 } 9284 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9285 return true; 9286 } 9287 return false; 9288 } 9289 9290 /** 9291 * Used during creation of InstallArgs 9292 * 9293 * @param installFlags package installation flags 9294 * @return true if should be installed as forward locked 9295 */ 9296 private static boolean installForwardLocked(int installFlags) { 9297 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9298 } 9299 9300 private InstallArgs createInstallArgs(InstallParams params) { 9301 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9302 return new AsecInstallArgs(params); 9303 } else { 9304 return new FileInstallArgs(params); 9305 } 9306 } 9307 9308 /** 9309 * Create args that describe an existing installed package. Typically used 9310 * when cleaning up old installs, or used as a move source. 9311 */ 9312 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9313 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9314 final boolean isInAsec; 9315 if (installOnSd(installFlags)) { 9316 /* Apps on SD card are always in ASEC containers. */ 9317 isInAsec = true; 9318 } else if (installForwardLocked(installFlags) 9319 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9320 /* 9321 * Forward-locked apps are only in ASEC containers if they're the 9322 * new style 9323 */ 9324 isInAsec = true; 9325 } else { 9326 isInAsec = false; 9327 } 9328 9329 if (isInAsec) { 9330 return new AsecInstallArgs(codePath, instructionSets, 9331 installOnSd(installFlags), installForwardLocked(installFlags)); 9332 } else { 9333 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9334 instructionSets); 9335 } 9336 } 9337 9338 static abstract class InstallArgs { 9339 /** @see InstallParams#origin */ 9340 final OriginInfo origin; 9341 9342 final IPackageInstallObserver2 observer; 9343 // Always refers to PackageManager flags only 9344 final int installFlags; 9345 final String installerPackageName; 9346 final ManifestDigest manifestDigest; 9347 final UserHandle user; 9348 final String abiOverride; 9349 9350 // The list of instruction sets supported by this app. This is currently 9351 // only used during the rmdex() phase to clean up resources. We can get rid of this 9352 // if we move dex files under the common app path. 9353 /* nullable */ String[] instructionSets; 9354 9355 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9356 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9357 String[] instructionSets, String abiOverride) { 9358 this.origin = origin; 9359 this.installFlags = installFlags; 9360 this.observer = observer; 9361 this.installerPackageName = installerPackageName; 9362 this.manifestDigest = manifestDigest; 9363 this.user = user; 9364 this.instructionSets = instructionSets; 9365 this.abiOverride = abiOverride; 9366 } 9367 9368 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9369 abstract int doPreInstall(int status); 9370 9371 /** 9372 * Rename package into final resting place. All paths on the given 9373 * scanned package should be updated to reflect the rename. 9374 */ 9375 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9376 abstract int doPostInstall(int status, int uid); 9377 9378 /** @see PackageSettingBase#codePathString */ 9379 abstract String getCodePath(); 9380 /** @see PackageSettingBase#resourcePathString */ 9381 abstract String getResourcePath(); 9382 abstract String getLegacyNativeLibraryPath(); 9383 9384 // Need installer lock especially for dex file removal. 9385 abstract void cleanUpResourcesLI(); 9386 abstract boolean doPostDeleteLI(boolean delete); 9387 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9388 9389 /** 9390 * Called before the source arguments are copied. This is used mostly 9391 * for MoveParams when it needs to read the source file to put it in the 9392 * destination. 9393 */ 9394 int doPreCopy() { 9395 return PackageManager.INSTALL_SUCCEEDED; 9396 } 9397 9398 /** 9399 * Called after the source arguments are copied. This is used mostly for 9400 * MoveParams when it needs to read the source file to put it in the 9401 * destination. 9402 * 9403 * @return 9404 */ 9405 int doPostCopy(int uid) { 9406 return PackageManager.INSTALL_SUCCEEDED; 9407 } 9408 9409 protected boolean isFwdLocked() { 9410 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9411 } 9412 9413 protected boolean isExternal() { 9414 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9415 } 9416 9417 UserHandle getUser() { 9418 return user; 9419 } 9420 } 9421 9422 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9423 if (!allCodePaths.isEmpty()) { 9424 if (instructionSets == null) { 9425 throw new IllegalStateException("instructionSet == null"); 9426 } 9427 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9428 for (String codePath : allCodePaths) { 9429 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9430 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9431 if (retCode < 0) { 9432 Slog.w(TAG, "Couldn't remove dex file for package: " 9433 + " at location " + codePath + ", retcode=" + retCode); 9434 // we don't consider this to be a failure of the core package deletion 9435 } 9436 } 9437 } 9438 } 9439 } 9440 9441 /** 9442 * Logic to handle installation of non-ASEC applications, including copying 9443 * and renaming logic. 9444 */ 9445 class FileInstallArgs extends InstallArgs { 9446 private File codeFile; 9447 private File resourceFile; 9448 private File legacyNativeLibraryPath; 9449 9450 // Example topology: 9451 // /data/app/com.example/base.apk 9452 // /data/app/com.example/split_foo.apk 9453 // /data/app/com.example/lib/arm/libfoo.so 9454 // /data/app/com.example/lib/arm64/libfoo.so 9455 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9456 9457 /** New install */ 9458 FileInstallArgs(InstallParams params) { 9459 super(params.origin, params.observer, params.installFlags, 9460 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9461 null /* instruction sets */, params.packageAbiOverride); 9462 if (isFwdLocked()) { 9463 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9464 } 9465 } 9466 9467 /** Existing install */ 9468 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9469 String[] instructionSets) { 9470 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9471 this.codeFile = (codePath != null) ? new File(codePath) : null; 9472 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9473 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9474 new File(legacyNativeLibraryPath) : null; 9475 } 9476 9477 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9478 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9479 isFwdLocked(), abiOverride); 9480 9481 final StorageManager storage = StorageManager.from(mContext); 9482 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9483 } 9484 9485 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9486 if (origin.staged) { 9487 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9488 codeFile = origin.file; 9489 resourceFile = origin.file; 9490 return PackageManager.INSTALL_SUCCEEDED; 9491 } 9492 9493 try { 9494 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9495 codeFile = tempDir; 9496 resourceFile = tempDir; 9497 } catch (IOException e) { 9498 Slog.w(TAG, "Failed to create copy file: " + e); 9499 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9500 } 9501 9502 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9503 @Override 9504 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9505 if (!FileUtils.isValidExtFilename(name)) { 9506 throw new IllegalArgumentException("Invalid filename: " + name); 9507 } 9508 try { 9509 final File file = new File(codeFile, name); 9510 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9511 O_RDWR | O_CREAT, 0644); 9512 Os.chmod(file.getAbsolutePath(), 0644); 9513 return new ParcelFileDescriptor(fd); 9514 } catch (ErrnoException e) { 9515 throw new RemoteException("Failed to open: " + e.getMessage()); 9516 } 9517 } 9518 }; 9519 9520 int ret = PackageManager.INSTALL_SUCCEEDED; 9521 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9522 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9523 Slog.e(TAG, "Failed to copy package"); 9524 return ret; 9525 } 9526 9527 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9528 NativeLibraryHelper.Handle handle = null; 9529 try { 9530 handle = NativeLibraryHelper.Handle.create(codeFile); 9531 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9532 abiOverride); 9533 } catch (IOException e) { 9534 Slog.e(TAG, "Copying native libraries failed", e); 9535 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9536 } finally { 9537 IoUtils.closeQuietly(handle); 9538 } 9539 9540 return ret; 9541 } 9542 9543 int doPreInstall(int status) { 9544 if (status != PackageManager.INSTALL_SUCCEEDED) { 9545 cleanUp(); 9546 } 9547 return status; 9548 } 9549 9550 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9551 if (status != PackageManager.INSTALL_SUCCEEDED) { 9552 cleanUp(); 9553 return false; 9554 } else { 9555 final File beforeCodeFile = codeFile; 9556 final File afterCodeFile = getNextCodePath(pkg.packageName); 9557 9558 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9559 try { 9560 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9561 } catch (ErrnoException e) { 9562 Slog.d(TAG, "Failed to rename", e); 9563 return false; 9564 } 9565 9566 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9567 Slog.d(TAG, "Failed to restorecon"); 9568 return false; 9569 } 9570 9571 // Reflect the rename internally 9572 codeFile = afterCodeFile; 9573 resourceFile = afterCodeFile; 9574 9575 // Reflect the rename in scanned details 9576 pkg.codePath = afterCodeFile.getAbsolutePath(); 9577 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9578 pkg.baseCodePath); 9579 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9580 pkg.splitCodePaths); 9581 9582 // Reflect the rename in app info 9583 pkg.applicationInfo.setCodePath(pkg.codePath); 9584 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9585 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9586 pkg.applicationInfo.setResourcePath(pkg.codePath); 9587 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9588 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9589 9590 return true; 9591 } 9592 } 9593 9594 int doPostInstall(int status, int uid) { 9595 if (status != PackageManager.INSTALL_SUCCEEDED) { 9596 cleanUp(); 9597 } 9598 return status; 9599 } 9600 9601 @Override 9602 String getCodePath() { 9603 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9604 } 9605 9606 @Override 9607 String getResourcePath() { 9608 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9609 } 9610 9611 @Override 9612 String getLegacyNativeLibraryPath() { 9613 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9614 } 9615 9616 private boolean cleanUp() { 9617 if (codeFile == null || !codeFile.exists()) { 9618 return false; 9619 } 9620 9621 if (codeFile.isDirectory()) { 9622 FileUtils.deleteContents(codeFile); 9623 } 9624 codeFile.delete(); 9625 9626 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9627 resourceFile.delete(); 9628 } 9629 9630 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9631 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9632 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9633 } 9634 legacyNativeLibraryPath.delete(); 9635 } 9636 9637 return true; 9638 } 9639 9640 void cleanUpResourcesLI() { 9641 // Try enumerating all code paths before deleting 9642 List<String> allCodePaths = Collections.EMPTY_LIST; 9643 if (codeFile != null && codeFile.exists()) { 9644 try { 9645 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9646 allCodePaths = pkg.getAllCodePaths(); 9647 } catch (PackageParserException e) { 9648 // Ignored; we tried our best 9649 } 9650 } 9651 9652 cleanUp(); 9653 removeDexFiles(allCodePaths, instructionSets); 9654 } 9655 9656 boolean doPostDeleteLI(boolean delete) { 9657 // XXX err, shouldn't we respect the delete flag? 9658 cleanUpResourcesLI(); 9659 return true; 9660 } 9661 } 9662 9663 private boolean isAsecExternal(String cid) { 9664 final String asecPath = PackageHelper.getSdFilesystem(cid); 9665 return !asecPath.startsWith(mAsecInternalPath); 9666 } 9667 9668 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9669 PackageManagerException { 9670 if (copyRet < 0) { 9671 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9672 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9673 throw new PackageManagerException(copyRet, message); 9674 } 9675 } 9676 } 9677 9678 /** 9679 * Extract the MountService "container ID" from the full code path of an 9680 * .apk. 9681 */ 9682 static String cidFromCodePath(String fullCodePath) { 9683 int eidx = fullCodePath.lastIndexOf("/"); 9684 String subStr1 = fullCodePath.substring(0, eidx); 9685 int sidx = subStr1.lastIndexOf("/"); 9686 return subStr1.substring(sidx+1, eidx); 9687 } 9688 9689 /** 9690 * Logic to handle installation of ASEC applications, including copying and 9691 * renaming logic. 9692 */ 9693 class AsecInstallArgs extends InstallArgs { 9694 static final String RES_FILE_NAME = "pkg.apk"; 9695 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9696 9697 String cid; 9698 String packagePath; 9699 String resourcePath; 9700 String legacyNativeLibraryDir; 9701 9702 /** New install */ 9703 AsecInstallArgs(InstallParams params) { 9704 super(params.origin, params.observer, params.installFlags, 9705 params.installerPackageName, params.getManifestDigest(), 9706 params.getUser(), null /* instruction sets */, 9707 params.packageAbiOverride); 9708 } 9709 9710 /** Existing install */ 9711 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9712 boolean isExternal, boolean isForwardLocked) { 9713 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9714 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9715 instructionSets, null); 9716 // Hackily pretend we're still looking at a full code path 9717 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9718 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9719 } 9720 9721 // Extract cid from fullCodePath 9722 int eidx = fullCodePath.lastIndexOf("/"); 9723 String subStr1 = fullCodePath.substring(0, eidx); 9724 int sidx = subStr1.lastIndexOf("/"); 9725 cid = subStr1.substring(sidx+1, eidx); 9726 setMountPath(subStr1); 9727 } 9728 9729 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9730 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9731 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9732 instructionSets, null); 9733 this.cid = cid; 9734 setMountPath(PackageHelper.getSdDir(cid)); 9735 } 9736 9737 void createCopyFile() { 9738 cid = mInstallerService.allocateExternalStageCidLegacy(); 9739 } 9740 9741 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9742 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9743 abiOverride); 9744 9745 final File target; 9746 if (isExternal()) { 9747 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9748 } else { 9749 target = Environment.getDataDirectory(); 9750 } 9751 9752 final StorageManager storage = StorageManager.from(mContext); 9753 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9754 } 9755 9756 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9757 if (origin.staged) { 9758 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9759 cid = origin.cid; 9760 setMountPath(PackageHelper.getSdDir(cid)); 9761 return PackageManager.INSTALL_SUCCEEDED; 9762 } 9763 9764 if (temp) { 9765 createCopyFile(); 9766 } else { 9767 /* 9768 * Pre-emptively destroy the container since it's destroyed if 9769 * copying fails due to it existing anyway. 9770 */ 9771 PackageHelper.destroySdDir(cid); 9772 } 9773 9774 final String newMountPath = imcs.copyPackageToContainer( 9775 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9776 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9777 9778 if (newMountPath != null) { 9779 setMountPath(newMountPath); 9780 return PackageManager.INSTALL_SUCCEEDED; 9781 } else { 9782 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9783 } 9784 } 9785 9786 @Override 9787 String getCodePath() { 9788 return packagePath; 9789 } 9790 9791 @Override 9792 String getResourcePath() { 9793 return resourcePath; 9794 } 9795 9796 @Override 9797 String getLegacyNativeLibraryPath() { 9798 return legacyNativeLibraryDir; 9799 } 9800 9801 int doPreInstall(int status) { 9802 if (status != PackageManager.INSTALL_SUCCEEDED) { 9803 // Destroy container 9804 PackageHelper.destroySdDir(cid); 9805 } else { 9806 boolean mounted = PackageHelper.isContainerMounted(cid); 9807 if (!mounted) { 9808 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9809 Process.SYSTEM_UID); 9810 if (newMountPath != null) { 9811 setMountPath(newMountPath); 9812 } else { 9813 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9814 } 9815 } 9816 } 9817 return status; 9818 } 9819 9820 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9821 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9822 String newMountPath = null; 9823 if (PackageHelper.isContainerMounted(cid)) { 9824 // Unmount the container 9825 if (!PackageHelper.unMountSdDir(cid)) { 9826 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9827 return false; 9828 } 9829 } 9830 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9831 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9832 " which might be stale. Will try to clean up."); 9833 // Clean up the stale container and proceed to recreate. 9834 if (!PackageHelper.destroySdDir(newCacheId)) { 9835 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9836 return false; 9837 } 9838 // Successfully cleaned up stale container. Try to rename again. 9839 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9840 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9841 + " inspite of cleaning it up."); 9842 return false; 9843 } 9844 } 9845 if (!PackageHelper.isContainerMounted(newCacheId)) { 9846 Slog.w(TAG, "Mounting container " + newCacheId); 9847 newMountPath = PackageHelper.mountSdDir(newCacheId, 9848 getEncryptKey(), Process.SYSTEM_UID); 9849 } else { 9850 newMountPath = PackageHelper.getSdDir(newCacheId); 9851 } 9852 if (newMountPath == null) { 9853 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9854 return false; 9855 } 9856 Log.i(TAG, "Succesfully renamed " + cid + 9857 " to " + newCacheId + 9858 " at new path: " + newMountPath); 9859 cid = newCacheId; 9860 9861 final File beforeCodeFile = new File(packagePath); 9862 setMountPath(newMountPath); 9863 final File afterCodeFile = new File(packagePath); 9864 9865 // Reflect the rename in scanned details 9866 pkg.codePath = afterCodeFile.getAbsolutePath(); 9867 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9868 pkg.baseCodePath); 9869 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9870 pkg.splitCodePaths); 9871 9872 // Reflect the rename in app info 9873 pkg.applicationInfo.setCodePath(pkg.codePath); 9874 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9875 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9876 pkg.applicationInfo.setResourcePath(pkg.codePath); 9877 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9878 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9879 9880 return true; 9881 } 9882 9883 private void setMountPath(String mountPath) { 9884 final File mountFile = new File(mountPath); 9885 9886 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9887 if (monolithicFile.exists()) { 9888 packagePath = monolithicFile.getAbsolutePath(); 9889 if (isFwdLocked()) { 9890 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9891 } else { 9892 resourcePath = packagePath; 9893 } 9894 } else { 9895 packagePath = mountFile.getAbsolutePath(); 9896 resourcePath = packagePath; 9897 } 9898 9899 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9900 } 9901 9902 int doPostInstall(int status, int uid) { 9903 if (status != PackageManager.INSTALL_SUCCEEDED) { 9904 cleanUp(); 9905 } else { 9906 final int groupOwner; 9907 final String protectedFile; 9908 if (isFwdLocked()) { 9909 groupOwner = UserHandle.getSharedAppGid(uid); 9910 protectedFile = RES_FILE_NAME; 9911 } else { 9912 groupOwner = -1; 9913 protectedFile = null; 9914 } 9915 9916 if (uid < Process.FIRST_APPLICATION_UID 9917 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9918 Slog.e(TAG, "Failed to finalize " + cid); 9919 PackageHelper.destroySdDir(cid); 9920 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9921 } 9922 9923 boolean mounted = PackageHelper.isContainerMounted(cid); 9924 if (!mounted) { 9925 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9926 } 9927 } 9928 return status; 9929 } 9930 9931 private void cleanUp() { 9932 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9933 9934 // Destroy secure container 9935 PackageHelper.destroySdDir(cid); 9936 } 9937 9938 private List<String> getAllCodePaths() { 9939 final File codeFile = new File(getCodePath()); 9940 if (codeFile != null && codeFile.exists()) { 9941 try { 9942 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9943 return pkg.getAllCodePaths(); 9944 } catch (PackageParserException e) { 9945 // Ignored; we tried our best 9946 } 9947 } 9948 return Collections.EMPTY_LIST; 9949 } 9950 9951 void cleanUpResourcesLI() { 9952 // Enumerate all code paths before deleting 9953 cleanUpResourcesLI(getAllCodePaths()); 9954 } 9955 9956 private void cleanUpResourcesLI(List<String> allCodePaths) { 9957 cleanUp(); 9958 removeDexFiles(allCodePaths, instructionSets); 9959 } 9960 9961 9962 9963 String getPackageName() { 9964 return getAsecPackageName(cid); 9965 } 9966 9967 boolean doPostDeleteLI(boolean delete) { 9968 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9969 final List<String> allCodePaths = getAllCodePaths(); 9970 boolean mounted = PackageHelper.isContainerMounted(cid); 9971 if (mounted) { 9972 // Unmount first 9973 if (PackageHelper.unMountSdDir(cid)) { 9974 mounted = false; 9975 } 9976 } 9977 if (!mounted && delete) { 9978 cleanUpResourcesLI(allCodePaths); 9979 } 9980 return !mounted; 9981 } 9982 9983 @Override 9984 int doPreCopy() { 9985 if (isFwdLocked()) { 9986 if (!PackageHelper.fixSdPermissions(cid, 9987 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9988 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9989 } 9990 } 9991 9992 return PackageManager.INSTALL_SUCCEEDED; 9993 } 9994 9995 @Override 9996 int doPostCopy(int uid) { 9997 if (isFwdLocked()) { 9998 if (uid < Process.FIRST_APPLICATION_UID 9999 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10000 RES_FILE_NAME)) { 10001 Slog.e(TAG, "Failed to finalize " + cid); 10002 PackageHelper.destroySdDir(cid); 10003 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10004 } 10005 } 10006 10007 return PackageManager.INSTALL_SUCCEEDED; 10008 } 10009 } 10010 10011 static String getAsecPackageName(String packageCid) { 10012 int idx = packageCid.lastIndexOf("-"); 10013 if (idx == -1) { 10014 return packageCid; 10015 } 10016 return packageCid.substring(0, idx); 10017 } 10018 10019 // Utility method used to create code paths based on package name and available index. 10020 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10021 String idxStr = ""; 10022 int idx = 1; 10023 // Fall back to default value of idx=1 if prefix is not 10024 // part of oldCodePath 10025 if (oldCodePath != null) { 10026 String subStr = oldCodePath; 10027 // Drop the suffix right away 10028 if (suffix != null && subStr.endsWith(suffix)) { 10029 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10030 } 10031 // If oldCodePath already contains prefix find out the 10032 // ending index to either increment or decrement. 10033 int sidx = subStr.lastIndexOf(prefix); 10034 if (sidx != -1) { 10035 subStr = subStr.substring(sidx + prefix.length()); 10036 if (subStr != null) { 10037 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10038 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10039 } 10040 try { 10041 idx = Integer.parseInt(subStr); 10042 if (idx <= 1) { 10043 idx++; 10044 } else { 10045 idx--; 10046 } 10047 } catch(NumberFormatException e) { 10048 } 10049 } 10050 } 10051 } 10052 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10053 return prefix + idxStr; 10054 } 10055 10056 private File getNextCodePath(String packageName) { 10057 int suffix = 1; 10058 File result; 10059 do { 10060 result = new File(mAppInstallDir, packageName + "-" + suffix); 10061 suffix++; 10062 } while (result.exists()); 10063 return result; 10064 } 10065 10066 // Utility method used to ignore ADD/REMOVE events 10067 // by directory observer. 10068 private static boolean ignoreCodePath(String fullPathStr) { 10069 String apkName = deriveCodePathName(fullPathStr); 10070 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10071 if (idx != -1 && ((idx+1) < apkName.length())) { 10072 // Make sure the package ends with a numeral 10073 String version = apkName.substring(idx+1); 10074 try { 10075 Integer.parseInt(version); 10076 return true; 10077 } catch (NumberFormatException e) {} 10078 } 10079 return false; 10080 } 10081 10082 // Utility method that returns the relative package path with respect 10083 // to the installation directory. Like say for /data/data/com.test-1.apk 10084 // string com.test-1 is returned. 10085 static String deriveCodePathName(String codePath) { 10086 if (codePath == null) { 10087 return null; 10088 } 10089 final File codeFile = new File(codePath); 10090 final String name = codeFile.getName(); 10091 if (codeFile.isDirectory()) { 10092 return name; 10093 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10094 final int lastDot = name.lastIndexOf('.'); 10095 return name.substring(0, lastDot); 10096 } else { 10097 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10098 return null; 10099 } 10100 } 10101 10102 class PackageInstalledInfo { 10103 String name; 10104 int uid; 10105 // The set of users that originally had this package installed. 10106 int[] origUsers; 10107 // The set of users that now have this package installed. 10108 int[] newUsers; 10109 PackageParser.Package pkg; 10110 int returnCode; 10111 String returnMsg; 10112 PackageRemovedInfo removedInfo; 10113 10114 public void setError(int code, String msg) { 10115 returnCode = code; 10116 returnMsg = msg; 10117 Slog.w(TAG, msg); 10118 } 10119 10120 public void setError(String msg, PackageParserException e) { 10121 returnCode = e.error; 10122 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10123 Slog.w(TAG, msg, e); 10124 } 10125 10126 public void setError(String msg, PackageManagerException e) { 10127 returnCode = e.error; 10128 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10129 Slog.w(TAG, msg, e); 10130 } 10131 10132 // In some error cases we want to convey more info back to the observer 10133 String origPackage; 10134 String origPermission; 10135 } 10136 10137 /* 10138 * Install a non-existing package. 10139 */ 10140 private void installNewPackageLI(PackageParser.Package pkg, 10141 int parseFlags, int scanFlags, UserHandle user, 10142 String installerPackageName, PackageInstalledInfo res) { 10143 // Remember this for later, in case we need to rollback this install 10144 String pkgName = pkg.packageName; 10145 10146 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10147 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10148 synchronized(mPackages) { 10149 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10150 // A package with the same name is already installed, though 10151 // it has been renamed to an older name. The package we 10152 // are trying to install should be installed as an update to 10153 // the existing one, but that has not been requested, so bail. 10154 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10155 + " without first uninstalling package running as " 10156 + mSettings.mRenamedPackages.get(pkgName)); 10157 return; 10158 } 10159 if (mPackages.containsKey(pkgName)) { 10160 // Don't allow installation over an existing package with the same name. 10161 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10162 + " without first uninstalling."); 10163 return; 10164 } 10165 } 10166 10167 try { 10168 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10169 System.currentTimeMillis(), user); 10170 10171 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10172 // delete the partially installed application. the data directory will have to be 10173 // restored if it was already existing 10174 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10175 // remove package from internal structures. Note that we want deletePackageX to 10176 // delete the package data and cache directories that it created in 10177 // scanPackageLocked, unless those directories existed before we even tried to 10178 // install. 10179 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10180 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10181 res.removedInfo, true); 10182 } 10183 10184 } catch (PackageManagerException e) { 10185 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10186 } 10187 } 10188 10189 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10190 // Upgrade keysets are being used. Determine if new package has a superset of the 10191 // required keys. 10192 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10194 for (int i = 0; i < upgradeKeySets.length; i++) { 10195 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10196 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10197 return true; 10198 } 10199 } 10200 return false; 10201 } 10202 10203 private void replacePackageLI(PackageParser.Package pkg, 10204 int parseFlags, int scanFlags, UserHandle user, 10205 String installerPackageName, PackageInstalledInfo res) { 10206 PackageParser.Package oldPackage; 10207 String pkgName = pkg.packageName; 10208 int[] allUsers; 10209 boolean[] perUserInstalled; 10210 10211 // First find the old package info and check signatures 10212 synchronized(mPackages) { 10213 oldPackage = mPackages.get(pkgName); 10214 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10215 PackageSetting ps = mSettings.mPackages.get(pkgName); 10216 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10217 // default to original signature matching 10218 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10219 != PackageManager.SIGNATURE_MATCH) { 10220 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10221 "New package has a different signature: " + pkgName); 10222 return; 10223 } 10224 } else { 10225 if(!checkUpgradeKeySetLP(ps, pkg)) { 10226 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10227 "New package not signed by keys specified by upgrade-keysets: " 10228 + pkgName); 10229 return; 10230 } 10231 } 10232 10233 // In case of rollback, remember per-user/profile install state 10234 allUsers = sUserManager.getUserIds(); 10235 perUserInstalled = new boolean[allUsers.length]; 10236 for (int i = 0; i < allUsers.length; i++) { 10237 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10238 } 10239 } 10240 10241 boolean sysPkg = (isSystemApp(oldPackage)); 10242 if (sysPkg) { 10243 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10244 user, allUsers, perUserInstalled, installerPackageName, res); 10245 } else { 10246 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10247 user, allUsers, perUserInstalled, installerPackageName, res); 10248 } 10249 } 10250 10251 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10252 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10253 int[] allUsers, boolean[] perUserInstalled, 10254 String installerPackageName, PackageInstalledInfo res) { 10255 String pkgName = deletedPackage.packageName; 10256 boolean deletedPkg = true; 10257 boolean updatedSettings = false; 10258 10259 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10260 + deletedPackage); 10261 long origUpdateTime; 10262 if (pkg.mExtras != null) { 10263 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10264 } else { 10265 origUpdateTime = 0; 10266 } 10267 10268 // First delete the existing package while retaining the data directory 10269 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10270 res.removedInfo, true)) { 10271 // If the existing package wasn't successfully deleted 10272 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10273 deletedPkg = false; 10274 } else { 10275 // Successfully deleted the old package; proceed with replace. 10276 10277 // If deleted package lived in a container, give users a chance to 10278 // relinquish resources before killing. 10279 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10280 if (DEBUG_INSTALL) { 10281 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10282 } 10283 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10284 final ArrayList<String> pkgList = new ArrayList<String>(1); 10285 pkgList.add(deletedPackage.applicationInfo.packageName); 10286 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10287 } 10288 10289 deleteCodeCacheDirsLI(pkgName); 10290 try { 10291 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10292 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10293 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10294 user); 10295 updatedSettings = true; 10296 } catch (PackageManagerException e) { 10297 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10298 } 10299 } 10300 10301 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10302 // remove package from internal structures. Note that we want deletePackageX to 10303 // delete the package data and cache directories that it created in 10304 // scanPackageLocked, unless those directories existed before we even tried to 10305 // install. 10306 if(updatedSettings) { 10307 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10308 deletePackageLI( 10309 pkgName, null, true, allUsers, perUserInstalled, 10310 PackageManager.DELETE_KEEP_DATA, 10311 res.removedInfo, true); 10312 } 10313 // Since we failed to install the new package we need to restore the old 10314 // package that we deleted. 10315 if (deletedPkg) { 10316 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10317 File restoreFile = new File(deletedPackage.codePath); 10318 // Parse old package 10319 boolean oldOnSd = isExternal(deletedPackage); 10320 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10321 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10322 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10323 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10324 try { 10325 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10326 } catch (PackageManagerException e) { 10327 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10328 + e.getMessage()); 10329 return; 10330 } 10331 // Restore of old package succeeded. Update permissions. 10332 // writer 10333 synchronized (mPackages) { 10334 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10335 UPDATE_PERMISSIONS_ALL); 10336 // can downgrade to reader 10337 mSettings.writeLPr(); 10338 } 10339 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10340 } 10341 } 10342 } 10343 10344 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10345 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10346 int[] allUsers, boolean[] perUserInstalled, 10347 String installerPackageName, PackageInstalledInfo res) { 10348 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10349 + ", old=" + deletedPackage); 10350 boolean disabledSystem = false; 10351 boolean updatedSettings = false; 10352 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10353 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10354 != 0) { 10355 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10356 } 10357 String packageName = deletedPackage.packageName; 10358 if (packageName == null) { 10359 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10360 "Attempt to delete null packageName."); 10361 return; 10362 } 10363 PackageParser.Package oldPkg; 10364 PackageSetting oldPkgSetting; 10365 // reader 10366 synchronized (mPackages) { 10367 oldPkg = mPackages.get(packageName); 10368 oldPkgSetting = mSettings.mPackages.get(packageName); 10369 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10370 (oldPkgSetting == null)) { 10371 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10372 "Couldn't find package:" + packageName + " information"); 10373 return; 10374 } 10375 } 10376 10377 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10378 10379 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10380 res.removedInfo.removedPackage = packageName; 10381 // Remove existing system package 10382 removePackageLI(oldPkgSetting, true); 10383 // writer 10384 synchronized (mPackages) { 10385 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10386 if (!disabledSystem && deletedPackage != null) { 10387 // We didn't need to disable the .apk as a current system package, 10388 // which means we are replacing another update that is already 10389 // installed. We need to make sure to delete the older one's .apk. 10390 res.removedInfo.args = createInstallArgsForExisting(0, 10391 deletedPackage.applicationInfo.getCodePath(), 10392 deletedPackage.applicationInfo.getResourcePath(), 10393 deletedPackage.applicationInfo.nativeLibraryRootDir, 10394 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10395 } else { 10396 res.removedInfo.args = null; 10397 } 10398 } 10399 10400 // Successfully disabled the old package. Now proceed with re-installation 10401 deleteCodeCacheDirsLI(packageName); 10402 10403 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10404 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10405 10406 PackageParser.Package newPackage = null; 10407 try { 10408 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10409 if (newPackage.mExtras != null) { 10410 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10411 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10412 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10413 10414 // is the update attempting to change shared user? that isn't going to work... 10415 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10416 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10417 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10418 + " to " + newPkgSetting.sharedUser); 10419 updatedSettings = true; 10420 } 10421 } 10422 10423 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10424 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10425 user); 10426 updatedSettings = true; 10427 } 10428 10429 } catch (PackageManagerException e) { 10430 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10431 } 10432 10433 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10434 // Re installation failed. Restore old information 10435 // Remove new pkg information 10436 if (newPackage != null) { 10437 removeInstalledPackageLI(newPackage, true); 10438 } 10439 // Add back the old system package 10440 try { 10441 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10442 } catch (PackageManagerException e) { 10443 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10444 } 10445 // Restore the old system information in Settings 10446 synchronized (mPackages) { 10447 if (disabledSystem) { 10448 mSettings.enableSystemPackageLPw(packageName); 10449 } 10450 if (updatedSettings) { 10451 mSettings.setInstallerPackageName(packageName, 10452 oldPkgSetting.installerPackageName); 10453 } 10454 mSettings.writeLPr(); 10455 } 10456 } 10457 } 10458 10459 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10460 int[] allUsers, boolean[] perUserInstalled, 10461 PackageInstalledInfo res, UserHandle user) { 10462 String pkgName = newPackage.packageName; 10463 synchronized (mPackages) { 10464 //write settings. the installStatus will be incomplete at this stage. 10465 //note that the new package setting would have already been 10466 //added to mPackages. It hasn't been persisted yet. 10467 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10468 mSettings.writeLPr(); 10469 } 10470 10471 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10472 10473 synchronized (mPackages) { 10474 updatePermissionsLPw(newPackage.packageName, newPackage, 10475 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10476 ? UPDATE_PERMISSIONS_ALL : 0)); 10477 // For system-bundled packages, we assume that installing an upgraded version 10478 // of the package implies that the user actually wants to run that new code, 10479 // so we enable the package. 10480 PackageSetting ps = mSettings.mPackages.get(pkgName); 10481 if (ps != null) { 10482 if (isSystemApp(newPackage)) { 10483 // NB: implicit assumption that system package upgrades apply to all users 10484 if (DEBUG_INSTALL) { 10485 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10486 } 10487 if (res.origUsers != null) { 10488 for (int userHandle : res.origUsers) { 10489 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10490 userHandle, installerPackageName); 10491 } 10492 } 10493 // Also convey the prior install/uninstall state 10494 if (allUsers != null && perUserInstalled != null) { 10495 for (int i = 0; i < allUsers.length; i++) { 10496 if (DEBUG_INSTALL) { 10497 Slog.d(TAG, " user " + allUsers[i] 10498 + " => " + perUserInstalled[i]); 10499 } 10500 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10501 } 10502 // these install state changes will be persisted in the 10503 // upcoming call to mSettings.writeLPr(). 10504 } 10505 } 10506 // It's implied that when a user requests installation, they want the app to be 10507 // installed and enabled. 10508 int userId = user.getIdentifier(); 10509 if (userId != UserHandle.USER_ALL) { 10510 ps.setInstalled(true, userId); 10511 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10512 } 10513 } 10514 res.name = pkgName; 10515 res.uid = newPackage.applicationInfo.uid; 10516 res.pkg = newPackage; 10517 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10518 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10519 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10520 //to update install status 10521 mSettings.writeLPr(); 10522 } 10523 } 10524 10525 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10526 final int installFlags = args.installFlags; 10527 String installerPackageName = args.installerPackageName; 10528 File tmpPackageFile = new File(args.getCodePath()); 10529 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10530 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10531 boolean replace = false; 10532 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10533 // Result object to be returned 10534 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10535 10536 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10537 // Retrieve PackageSettings and parse package 10538 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10539 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10540 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10541 PackageParser pp = new PackageParser(); 10542 pp.setSeparateProcesses(mSeparateProcesses); 10543 pp.setDisplayMetrics(mMetrics); 10544 10545 final PackageParser.Package pkg; 10546 try { 10547 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10548 } catch (PackageParserException e) { 10549 res.setError("Failed parse during installPackageLI", e); 10550 return; 10551 } 10552 10553 // Mark that we have an install time CPU ABI override. 10554 pkg.cpuAbiOverride = args.abiOverride; 10555 10556 String pkgName = res.name = pkg.packageName; 10557 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10558 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10559 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10560 return; 10561 } 10562 } 10563 10564 try { 10565 pp.collectCertificates(pkg, parseFlags); 10566 pp.collectManifestDigest(pkg); 10567 } catch (PackageParserException e) { 10568 res.setError("Failed collect during installPackageLI", e); 10569 return; 10570 } 10571 10572 /* If the installer passed in a manifest digest, compare it now. */ 10573 if (args.manifestDigest != null) { 10574 if (DEBUG_INSTALL) { 10575 final String parsedManifest = pkg.manifestDigest == null ? "null" 10576 : pkg.manifestDigest.toString(); 10577 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10578 + parsedManifest); 10579 } 10580 10581 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10582 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10583 return; 10584 } 10585 } else if (DEBUG_INSTALL) { 10586 final String parsedManifest = pkg.manifestDigest == null 10587 ? "null" : pkg.manifestDigest.toString(); 10588 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10589 } 10590 10591 // Get rid of all references to package scan path via parser. 10592 pp = null; 10593 String oldCodePath = null; 10594 boolean systemApp = false; 10595 synchronized (mPackages) { 10596 // Check if installing already existing package 10597 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10598 String oldName = mSettings.mRenamedPackages.get(pkgName); 10599 if (pkg.mOriginalPackages != null 10600 && pkg.mOriginalPackages.contains(oldName) 10601 && mPackages.containsKey(oldName)) { 10602 // This package is derived from an original package, 10603 // and this device has been updating from that original 10604 // name. We must continue using the original name, so 10605 // rename the new package here. 10606 pkg.setPackageName(oldName); 10607 pkgName = pkg.packageName; 10608 replace = true; 10609 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10610 + oldName + " pkgName=" + pkgName); 10611 } else if (mPackages.containsKey(pkgName)) { 10612 // This package, under its official name, already exists 10613 // on the device; we should replace it. 10614 replace = true; 10615 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10616 } 10617 } 10618 10619 PackageSetting ps = mSettings.mPackages.get(pkgName); 10620 if (ps != null) { 10621 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10622 10623 // Quick sanity check that we're signed correctly if updating; 10624 // we'll check this again later when scanning, but we want to 10625 // bail early here before tripping over redefined permissions. 10626 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10627 try { 10628 verifySignaturesLP(ps, pkg); 10629 } catch (PackageManagerException e) { 10630 res.setError(e.error, e.getMessage()); 10631 return; 10632 } 10633 } else { 10634 if (!checkUpgradeKeySetLP(ps, pkg)) { 10635 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10636 + pkg.packageName + " upgrade keys do not match the " 10637 + "previously installed version"); 10638 return; 10639 } 10640 } 10641 10642 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10643 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10644 systemApp = (ps.pkg.applicationInfo.flags & 10645 ApplicationInfo.FLAG_SYSTEM) != 0; 10646 } 10647 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10648 } 10649 10650 // Check whether the newly-scanned package wants to define an already-defined perm 10651 int N = pkg.permissions.size(); 10652 for (int i = N-1; i >= 0; i--) { 10653 PackageParser.Permission perm = pkg.permissions.get(i); 10654 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10655 if (bp != null) { 10656 // If the defining package is signed with our cert, it's okay. This 10657 // also includes the "updating the same package" case, of course. 10658 // "updating same package" could also involve key-rotation. 10659 final boolean sigsOk; 10660 if (!bp.sourcePackage.equals(pkg.packageName) 10661 || !(bp.packageSetting instanceof PackageSetting) 10662 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10663 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10664 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10665 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10666 } else { 10667 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10668 } 10669 if (!sigsOk) { 10670 // If the owning package is the system itself, we log but allow 10671 // install to proceed; we fail the install on all other permission 10672 // redefinitions. 10673 if (!bp.sourcePackage.equals("android")) { 10674 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10675 + pkg.packageName + " attempting to redeclare permission " 10676 + perm.info.name + " already owned by " + bp.sourcePackage); 10677 res.origPermission = perm.info.name; 10678 res.origPackage = bp.sourcePackage; 10679 return; 10680 } else { 10681 Slog.w(TAG, "Package " + pkg.packageName 10682 + " attempting to redeclare system permission " 10683 + perm.info.name + "; ignoring new declaration"); 10684 pkg.permissions.remove(i); 10685 } 10686 } 10687 } 10688 } 10689 10690 } 10691 10692 if (systemApp && onSd) { 10693 // Disable updates to system apps on sdcard 10694 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10695 "Cannot install updates to system apps on sdcard"); 10696 return; 10697 } 10698 10699 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10700 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10701 return; 10702 } 10703 10704 if (replace) { 10705 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10706 installerPackageName, res); 10707 } else { 10708 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10709 args.user, installerPackageName, res); 10710 } 10711 synchronized (mPackages) { 10712 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10713 if (ps != null) { 10714 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10715 } 10716 } 10717 } 10718 10719 private static boolean isMultiArch(PackageSetting ps) { 10720 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10721 } 10722 10723 private static boolean isMultiArch(ApplicationInfo info) { 10724 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10725 } 10726 10727 private static boolean isExternal(PackageParser.Package pkg) { 10728 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10729 } 10730 10731 private static boolean isExternal(PackageSetting ps) { 10732 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10733 } 10734 10735 private static boolean isExternal(ApplicationInfo info) { 10736 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10737 } 10738 10739 private static boolean isSystemApp(PackageParser.Package pkg) { 10740 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10741 } 10742 10743 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10744 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10745 } 10746 10747 private static boolean isSystemApp(ApplicationInfo info) { 10748 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10749 } 10750 10751 private static boolean isSystemApp(PackageSetting ps) { 10752 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10753 } 10754 10755 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10756 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10757 } 10758 10759 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10760 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10761 } 10762 10763 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10764 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10765 } 10766 10767 private int packageFlagsToInstallFlags(PackageSetting ps) { 10768 int installFlags = 0; 10769 if (isExternal(ps)) { 10770 installFlags |= PackageManager.INSTALL_EXTERNAL; 10771 } 10772 if (ps.isForwardLocked()) { 10773 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10774 } 10775 return installFlags; 10776 } 10777 10778 private void deleteTempPackageFiles() { 10779 final FilenameFilter filter = new FilenameFilter() { 10780 public boolean accept(File dir, String name) { 10781 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10782 } 10783 }; 10784 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10785 file.delete(); 10786 } 10787 } 10788 10789 @Override 10790 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10791 int flags) { 10792 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10793 flags); 10794 } 10795 10796 @Override 10797 public void deletePackage(final String packageName, 10798 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10799 mContext.enforceCallingOrSelfPermission( 10800 android.Manifest.permission.DELETE_PACKAGES, null); 10801 final int uid = Binder.getCallingUid(); 10802 if (UserHandle.getUserId(uid) != userId) { 10803 mContext.enforceCallingPermission( 10804 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10805 "deletePackage for user " + userId); 10806 } 10807 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10808 try { 10809 observer.onPackageDeleted(packageName, 10810 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10811 } catch (RemoteException re) { 10812 } 10813 return; 10814 } 10815 10816 boolean uninstallBlocked = false; 10817 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10818 int[] users = sUserManager.getUserIds(); 10819 for (int i = 0; i < users.length; ++i) { 10820 if (getBlockUninstallForUser(packageName, users[i])) { 10821 uninstallBlocked = true; 10822 break; 10823 } 10824 } 10825 } else { 10826 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10827 } 10828 if (uninstallBlocked) { 10829 try { 10830 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10831 null); 10832 } catch (RemoteException re) { 10833 } 10834 return; 10835 } 10836 10837 if (DEBUG_REMOVE) { 10838 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10839 } 10840 // Queue up an async operation since the package deletion may take a little while. 10841 mHandler.post(new Runnable() { 10842 public void run() { 10843 mHandler.removeCallbacks(this); 10844 final int returnCode = deletePackageX(packageName, userId, flags); 10845 if (observer != null) { 10846 try { 10847 observer.onPackageDeleted(packageName, returnCode, null); 10848 } catch (RemoteException e) { 10849 Log.i(TAG, "Observer no longer exists."); 10850 } //end catch 10851 } //end if 10852 } //end run 10853 }); 10854 } 10855 10856 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10857 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10858 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10859 try { 10860 if (dpm != null) { 10861 if (dpm.isDeviceOwner(packageName)) { 10862 return true; 10863 } 10864 int[] users; 10865 if (userId == UserHandle.USER_ALL) { 10866 users = sUserManager.getUserIds(); 10867 } else { 10868 users = new int[]{userId}; 10869 } 10870 for (int i = 0; i < users.length; ++i) { 10871 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10872 return true; 10873 } 10874 } 10875 } 10876 } catch (RemoteException e) { 10877 } 10878 return false; 10879 } 10880 10881 /** 10882 * This method is an internal method that could be get invoked either 10883 * to delete an installed package or to clean up a failed installation. 10884 * After deleting an installed package, a broadcast is sent to notify any 10885 * listeners that the package has been installed. For cleaning up a failed 10886 * installation, the broadcast is not necessary since the package's 10887 * installation wouldn't have sent the initial broadcast either 10888 * The key steps in deleting a package are 10889 * deleting the package information in internal structures like mPackages, 10890 * deleting the packages base directories through installd 10891 * updating mSettings to reflect current status 10892 * persisting settings for later use 10893 * sending a broadcast if necessary 10894 */ 10895 private int deletePackageX(String packageName, int userId, int flags) { 10896 final PackageRemovedInfo info = new PackageRemovedInfo(); 10897 final boolean res; 10898 10899 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10900 ? UserHandle.ALL : new UserHandle(userId); 10901 10902 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10903 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10904 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10905 } 10906 10907 boolean removedForAllUsers = false; 10908 boolean systemUpdate = false; 10909 10910 // for the uninstall-updates case and restricted profiles, remember the per- 10911 // userhandle installed state 10912 int[] allUsers; 10913 boolean[] perUserInstalled; 10914 synchronized (mPackages) { 10915 PackageSetting ps = mSettings.mPackages.get(packageName); 10916 allUsers = sUserManager.getUserIds(); 10917 perUserInstalled = new boolean[allUsers.length]; 10918 for (int i = 0; i < allUsers.length; i++) { 10919 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10920 } 10921 } 10922 10923 synchronized (mInstallLock) { 10924 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10925 res = deletePackageLI(packageName, removeForUser, 10926 true, allUsers, perUserInstalled, 10927 flags | REMOVE_CHATTY, info, true); 10928 systemUpdate = info.isRemovedPackageSystemUpdate; 10929 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10930 removedForAllUsers = true; 10931 } 10932 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10933 + " removedForAllUsers=" + removedForAllUsers); 10934 } 10935 10936 if (res) { 10937 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10938 10939 // If the removed package was a system update, the old system package 10940 // was re-enabled; we need to broadcast this information 10941 if (systemUpdate) { 10942 Bundle extras = new Bundle(1); 10943 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10944 ? info.removedAppId : info.uid); 10945 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10946 10947 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10948 extras, null, null, null); 10949 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10950 extras, null, null, null); 10951 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10952 null, packageName, null, null); 10953 } 10954 } 10955 // Force a gc here. 10956 Runtime.getRuntime().gc(); 10957 // Delete the resources here after sending the broadcast to let 10958 // other processes clean up before deleting resources. 10959 if (info.args != null) { 10960 synchronized (mInstallLock) { 10961 info.args.doPostDeleteLI(true); 10962 } 10963 } 10964 10965 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10966 } 10967 10968 static class PackageRemovedInfo { 10969 String removedPackage; 10970 int uid = -1; 10971 int removedAppId = -1; 10972 int[] removedUsers = null; 10973 boolean isRemovedPackageSystemUpdate = false; 10974 // Clean up resources deleted packages. 10975 InstallArgs args = null; 10976 10977 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10978 Bundle extras = new Bundle(1); 10979 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10980 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10981 if (replacing) { 10982 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10983 } 10984 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10985 if (removedPackage != null) { 10986 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10987 extras, null, null, removedUsers); 10988 if (fullRemove && !replacing) { 10989 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10990 extras, null, null, removedUsers); 10991 } 10992 } 10993 if (removedAppId >= 0) { 10994 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10995 removedUsers); 10996 } 10997 } 10998 } 10999 11000 /* 11001 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11002 * flag is not set, the data directory is removed as well. 11003 * make sure this flag is set for partially installed apps. If not its meaningless to 11004 * delete a partially installed application. 11005 */ 11006 private void removePackageDataLI(PackageSetting ps, 11007 int[] allUserHandles, boolean[] perUserInstalled, 11008 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11009 String packageName = ps.name; 11010 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11011 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11012 // Retrieve object to delete permissions for shared user later on 11013 final PackageSetting deletedPs; 11014 // reader 11015 synchronized (mPackages) { 11016 deletedPs = mSettings.mPackages.get(packageName); 11017 if (outInfo != null) { 11018 outInfo.removedPackage = packageName; 11019 outInfo.removedUsers = deletedPs != null 11020 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11021 : null; 11022 } 11023 } 11024 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11025 removeDataDirsLI(packageName); 11026 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11027 } 11028 // writer 11029 synchronized (mPackages) { 11030 if (deletedPs != null) { 11031 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11032 if (outInfo != null) { 11033 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11034 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11035 } 11036 updatePermissionsLPw(deletedPs.name, null, 0); 11037 if (deletedPs.sharedUser != null) { 11038 // Remove permissions associated with package. Since runtime 11039 // permissions are per user we have to kill the removed package 11040 // or packages running under the shared user of the removed 11041 // package if revoking the permissions requested only by the removed 11042 // package is successful and this causes a change in gids. 11043 for (int userId : UserManagerService.getInstance().getUserIds()) { 11044 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11045 userId); 11046 if (userIdToKill == userId) { 11047 // If gids changed for this user, kill all affected packages. 11048 killSettingPackagesForUser(deletedPs, userIdToKill, 11049 KILL_APP_REASON_GIDS_CHANGED); 11050 } else if (userIdToKill == UserHandle.USER_ALL) { 11051 // If gids changed for all users, kill them all - done. 11052 killSettingPackagesForUser(deletedPs, userIdToKill, 11053 KILL_APP_REASON_GIDS_CHANGED); 11054 break; 11055 } 11056 } 11057 } 11058 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11059 } 11060 // make sure to preserve per-user disabled state if this removal was just 11061 // a downgrade of a system app to the factory package 11062 if (allUserHandles != null && perUserInstalled != null) { 11063 if (DEBUG_REMOVE) { 11064 Slog.d(TAG, "Propagating install state across downgrade"); 11065 } 11066 for (int i = 0; i < allUserHandles.length; i++) { 11067 if (DEBUG_REMOVE) { 11068 Slog.d(TAG, " user " + allUserHandles[i] 11069 + " => " + perUserInstalled[i]); 11070 } 11071 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11072 } 11073 } 11074 } 11075 // can downgrade to reader 11076 if (writeSettings) { 11077 // Save settings now 11078 mSettings.writeLPr(); 11079 } 11080 } 11081 if (outInfo != null) { 11082 // A user ID was deleted here. Go through all users and remove it 11083 // from KeyStore. 11084 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11085 } 11086 } 11087 11088 static boolean locationIsPrivileged(File path) { 11089 try { 11090 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11091 .getCanonicalPath(); 11092 return path.getCanonicalPath().startsWith(privilegedAppDir); 11093 } catch (IOException e) { 11094 Slog.e(TAG, "Unable to access code path " + path); 11095 } 11096 return false; 11097 } 11098 11099 /* 11100 * Tries to delete system package. 11101 */ 11102 private boolean deleteSystemPackageLI(PackageSetting newPs, 11103 int[] allUserHandles, boolean[] perUserInstalled, 11104 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11105 final boolean applyUserRestrictions 11106 = (allUserHandles != null) && (perUserInstalled != null); 11107 PackageSetting disabledPs = null; 11108 // Confirm if the system package has been updated 11109 // An updated system app can be deleted. This will also have to restore 11110 // the system pkg from system partition 11111 // reader 11112 synchronized (mPackages) { 11113 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11114 } 11115 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11116 + " disabledPs=" + disabledPs); 11117 if (disabledPs == null) { 11118 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11119 return false; 11120 } else if (DEBUG_REMOVE) { 11121 Slog.d(TAG, "Deleting system pkg from data partition"); 11122 } 11123 if (DEBUG_REMOVE) { 11124 if (applyUserRestrictions) { 11125 Slog.d(TAG, "Remembering install states:"); 11126 for (int i = 0; i < allUserHandles.length; i++) { 11127 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11128 } 11129 } 11130 } 11131 // Delete the updated package 11132 outInfo.isRemovedPackageSystemUpdate = true; 11133 if (disabledPs.versionCode < newPs.versionCode) { 11134 // Delete data for downgrades 11135 flags &= ~PackageManager.DELETE_KEEP_DATA; 11136 } else { 11137 // Preserve data by setting flag 11138 flags |= PackageManager.DELETE_KEEP_DATA; 11139 } 11140 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11141 allUserHandles, perUserInstalled, outInfo, writeSettings); 11142 if (!ret) { 11143 return false; 11144 } 11145 // writer 11146 synchronized (mPackages) { 11147 // Reinstate the old system package 11148 mSettings.enableSystemPackageLPw(newPs.name); 11149 // Remove any native libraries from the upgraded package. 11150 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11151 } 11152 // Install the system package 11153 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11154 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11155 if (locationIsPrivileged(disabledPs.codePath)) { 11156 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11157 } 11158 11159 final PackageParser.Package newPkg; 11160 try { 11161 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11162 } catch (PackageManagerException e) { 11163 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11164 return false; 11165 } 11166 11167 // writer 11168 synchronized (mPackages) { 11169 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11170 updatePermissionsLPw(newPkg.packageName, newPkg, 11171 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11172 if (applyUserRestrictions) { 11173 if (DEBUG_REMOVE) { 11174 Slog.d(TAG, "Propagating install state across reinstall"); 11175 } 11176 for (int i = 0; i < allUserHandles.length; i++) { 11177 if (DEBUG_REMOVE) { 11178 Slog.d(TAG, " user " + allUserHandles[i] 11179 + " => " + perUserInstalled[i]); 11180 } 11181 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11182 } 11183 // Regardless of writeSettings we need to ensure that this restriction 11184 // state propagation is persisted 11185 mSettings.writeAllUsersPackageRestrictionsLPr(); 11186 } 11187 // can downgrade to reader here 11188 if (writeSettings) { 11189 mSettings.writeLPr(); 11190 } 11191 } 11192 return true; 11193 } 11194 11195 private boolean deleteInstalledPackageLI(PackageSetting ps, 11196 boolean deleteCodeAndResources, int flags, 11197 int[] allUserHandles, boolean[] perUserInstalled, 11198 PackageRemovedInfo outInfo, boolean writeSettings) { 11199 if (outInfo != null) { 11200 outInfo.uid = ps.appId; 11201 } 11202 11203 // Delete package data from internal structures and also remove data if flag is set 11204 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11205 11206 // Delete application code and resources 11207 if (deleteCodeAndResources && (outInfo != null)) { 11208 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11209 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11210 getAppDexInstructionSets(ps)); 11211 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11212 } 11213 return true; 11214 } 11215 11216 @Override 11217 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11218 int userId) { 11219 mContext.enforceCallingOrSelfPermission( 11220 android.Manifest.permission.DELETE_PACKAGES, null); 11221 synchronized (mPackages) { 11222 PackageSetting ps = mSettings.mPackages.get(packageName); 11223 if (ps == null) { 11224 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11225 return false; 11226 } 11227 if (!ps.getInstalled(userId)) { 11228 // Can't block uninstall for an app that is not installed or enabled. 11229 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11230 return false; 11231 } 11232 ps.setBlockUninstall(blockUninstall, userId); 11233 mSettings.writePackageRestrictionsLPr(userId); 11234 } 11235 return true; 11236 } 11237 11238 @Override 11239 public boolean getBlockUninstallForUser(String packageName, int userId) { 11240 synchronized (mPackages) { 11241 PackageSetting ps = mSettings.mPackages.get(packageName); 11242 if (ps == null) { 11243 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11244 return false; 11245 } 11246 return ps.getBlockUninstall(userId); 11247 } 11248 } 11249 11250 /* 11251 * This method handles package deletion in general 11252 */ 11253 private boolean deletePackageLI(String packageName, UserHandle user, 11254 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11255 int flags, PackageRemovedInfo outInfo, 11256 boolean writeSettings) { 11257 if (packageName == null) { 11258 Slog.w(TAG, "Attempt to delete null packageName."); 11259 return false; 11260 } 11261 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11262 PackageSetting ps; 11263 boolean dataOnly = false; 11264 int removeUser = -1; 11265 int appId = -1; 11266 synchronized (mPackages) { 11267 ps = mSettings.mPackages.get(packageName); 11268 if (ps == null) { 11269 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11270 return false; 11271 } 11272 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11273 && user.getIdentifier() != UserHandle.USER_ALL) { 11274 // The caller is asking that the package only be deleted for a single 11275 // user. To do this, we just mark its uninstalled state and delete 11276 // its data. If this is a system app, we only allow this to happen if 11277 // they have set the special DELETE_SYSTEM_APP which requests different 11278 // semantics than normal for uninstalling system apps. 11279 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11280 ps.setUserState(user.getIdentifier(), 11281 COMPONENT_ENABLED_STATE_DEFAULT, 11282 false, //installed 11283 true, //stopped 11284 true, //notLaunched 11285 false, //hidden 11286 null, null, null, 11287 false // blockUninstall 11288 ); 11289 if (!isSystemApp(ps)) { 11290 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11291 // Other user still have this package installed, so all 11292 // we need to do is clear this user's data and save that 11293 // it is uninstalled. 11294 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11295 removeUser = user.getIdentifier(); 11296 appId = ps.appId; 11297 mSettings.writePackageRestrictionsLPr(removeUser); 11298 } else { 11299 // We need to set it back to 'installed' so the uninstall 11300 // broadcasts will be sent correctly. 11301 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11302 ps.setInstalled(true, user.getIdentifier()); 11303 } 11304 } else { 11305 // This is a system app, so we assume that the 11306 // other users still have this package installed, so all 11307 // we need to do is clear this user's data and save that 11308 // it is uninstalled. 11309 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11310 removeUser = user.getIdentifier(); 11311 appId = ps.appId; 11312 mSettings.writePackageRestrictionsLPr(removeUser); 11313 } 11314 } 11315 } 11316 11317 if (removeUser >= 0) { 11318 // From above, we determined that we are deleting this only 11319 // for a single user. Continue the work here. 11320 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11321 if (outInfo != null) { 11322 outInfo.removedPackage = packageName; 11323 outInfo.removedAppId = appId; 11324 outInfo.removedUsers = new int[] {removeUser}; 11325 } 11326 mInstaller.clearUserData(packageName, removeUser); 11327 removeKeystoreDataIfNeeded(removeUser, appId); 11328 schedulePackageCleaning(packageName, removeUser, false); 11329 return true; 11330 } 11331 11332 if (dataOnly) { 11333 // Delete application data first 11334 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11335 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11336 return true; 11337 } 11338 11339 boolean ret = false; 11340 if (isSystemApp(ps)) { 11341 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11342 // When an updated system application is deleted we delete the existing resources as well and 11343 // fall back to existing code in system partition 11344 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11345 flags, outInfo, writeSettings); 11346 } else { 11347 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11348 // Kill application pre-emptively especially for apps on sd. 11349 killApplication(packageName, ps.appId, "uninstall pkg"); 11350 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11351 allUserHandles, perUserInstalled, 11352 outInfo, writeSettings); 11353 } 11354 11355 return ret; 11356 } 11357 11358 private final class ClearStorageConnection implements ServiceConnection { 11359 IMediaContainerService mContainerService; 11360 11361 @Override 11362 public void onServiceConnected(ComponentName name, IBinder service) { 11363 synchronized (this) { 11364 mContainerService = IMediaContainerService.Stub.asInterface(service); 11365 notifyAll(); 11366 } 11367 } 11368 11369 @Override 11370 public void onServiceDisconnected(ComponentName name) { 11371 } 11372 } 11373 11374 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11375 final boolean mounted; 11376 if (Environment.isExternalStorageEmulated()) { 11377 mounted = true; 11378 } else { 11379 final String status = Environment.getExternalStorageState(); 11380 11381 mounted = status.equals(Environment.MEDIA_MOUNTED) 11382 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11383 } 11384 11385 if (!mounted) { 11386 return; 11387 } 11388 11389 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11390 int[] users; 11391 if (userId == UserHandle.USER_ALL) { 11392 users = sUserManager.getUserIds(); 11393 } else { 11394 users = new int[] { userId }; 11395 } 11396 final ClearStorageConnection conn = new ClearStorageConnection(); 11397 if (mContext.bindServiceAsUser( 11398 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11399 try { 11400 for (int curUser : users) { 11401 long timeout = SystemClock.uptimeMillis() + 5000; 11402 synchronized (conn) { 11403 long now = SystemClock.uptimeMillis(); 11404 while (conn.mContainerService == null && now < timeout) { 11405 try { 11406 conn.wait(timeout - now); 11407 } catch (InterruptedException e) { 11408 } 11409 } 11410 } 11411 if (conn.mContainerService == null) { 11412 return; 11413 } 11414 11415 final UserEnvironment userEnv = new UserEnvironment(curUser); 11416 clearDirectory(conn.mContainerService, 11417 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11418 if (allData) { 11419 clearDirectory(conn.mContainerService, 11420 userEnv.buildExternalStorageAppDataDirs(packageName)); 11421 clearDirectory(conn.mContainerService, 11422 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11423 } 11424 } 11425 } finally { 11426 mContext.unbindService(conn); 11427 } 11428 } 11429 } 11430 11431 @Override 11432 public void clearApplicationUserData(final String packageName, 11433 final IPackageDataObserver observer, final int userId) { 11434 mContext.enforceCallingOrSelfPermission( 11435 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11436 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11437 // Queue up an async operation since the package deletion may take a little while. 11438 mHandler.post(new Runnable() { 11439 public void run() { 11440 mHandler.removeCallbacks(this); 11441 final boolean succeeded; 11442 synchronized (mInstallLock) { 11443 succeeded = clearApplicationUserDataLI(packageName, userId); 11444 } 11445 clearExternalStorageDataSync(packageName, userId, true); 11446 if (succeeded) { 11447 // invoke DeviceStorageMonitor's update method to clear any notifications 11448 DeviceStorageMonitorInternal 11449 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11450 if (dsm != null) { 11451 dsm.checkMemory(); 11452 } 11453 } 11454 if(observer != null) { 11455 try { 11456 observer.onRemoveCompleted(packageName, succeeded); 11457 } catch (RemoteException e) { 11458 Log.i(TAG, "Observer no longer exists."); 11459 } 11460 } //end if observer 11461 } //end run 11462 }); 11463 } 11464 11465 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11466 if (packageName == null) { 11467 Slog.w(TAG, "Attempt to delete null packageName."); 11468 return false; 11469 } 11470 11471 // Try finding details about the requested package 11472 PackageParser.Package pkg; 11473 synchronized (mPackages) { 11474 pkg = mPackages.get(packageName); 11475 if (pkg == null) { 11476 final PackageSetting ps = mSettings.mPackages.get(packageName); 11477 if (ps != null) { 11478 pkg = ps.pkg; 11479 } 11480 } 11481 } 11482 11483 if (pkg == null) { 11484 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11485 } 11486 11487 // Always delete data directories for package, even if we found no other 11488 // record of app. This helps users recover from UID mismatches without 11489 // resorting to a full data wipe. 11490 int retCode = mInstaller.clearUserData(packageName, userId); 11491 if (retCode < 0) { 11492 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11493 return false; 11494 } 11495 11496 if (pkg == null) { 11497 return false; 11498 } 11499 11500 if (pkg != null && pkg.applicationInfo != null) { 11501 final int appId = pkg.applicationInfo.uid; 11502 removeKeystoreDataIfNeeded(userId, appId); 11503 } 11504 11505 // Create a native library symlink only if we have native libraries 11506 // and if the native libraries are 32 bit libraries. We do not provide 11507 // this symlink for 64 bit libraries. 11508 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11509 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11510 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11511 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11512 Slog.w(TAG, "Failed linking native library dir"); 11513 return false; 11514 } 11515 } 11516 11517 return true; 11518 } 11519 11520 /** 11521 * Remove entries from the keystore daemon. Will only remove it if the 11522 * {@code appId} is valid. 11523 */ 11524 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11525 if (appId < 0) { 11526 return; 11527 } 11528 11529 final KeyStore keyStore = KeyStore.getInstance(); 11530 if (keyStore != null) { 11531 if (userId == UserHandle.USER_ALL) { 11532 for (final int individual : sUserManager.getUserIds()) { 11533 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11534 } 11535 } else { 11536 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11537 } 11538 } else { 11539 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11540 } 11541 } 11542 11543 @Override 11544 public void deleteApplicationCacheFiles(final String packageName, 11545 final IPackageDataObserver observer) { 11546 mContext.enforceCallingOrSelfPermission( 11547 android.Manifest.permission.DELETE_CACHE_FILES, null); 11548 // Queue up an async operation since the package deletion may take a little while. 11549 final int userId = UserHandle.getCallingUserId(); 11550 mHandler.post(new Runnable() { 11551 public void run() { 11552 mHandler.removeCallbacks(this); 11553 final boolean succeded; 11554 synchronized (mInstallLock) { 11555 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11556 } 11557 clearExternalStorageDataSync(packageName, userId, false); 11558 if(observer != null) { 11559 try { 11560 observer.onRemoveCompleted(packageName, succeded); 11561 } catch (RemoteException e) { 11562 Log.i(TAG, "Observer no longer exists."); 11563 } 11564 } //end if observer 11565 } //end run 11566 }); 11567 } 11568 11569 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11570 if (packageName == null) { 11571 Slog.w(TAG, "Attempt to delete null packageName."); 11572 return false; 11573 } 11574 PackageParser.Package p; 11575 synchronized (mPackages) { 11576 p = mPackages.get(packageName); 11577 } 11578 if (p == null) { 11579 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11580 return false; 11581 } 11582 final ApplicationInfo applicationInfo = p.applicationInfo; 11583 if (applicationInfo == null) { 11584 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11585 return false; 11586 } 11587 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11588 if (retCode < 0) { 11589 Slog.w(TAG, "Couldn't remove cache files for package: " 11590 + packageName + " u" + userId); 11591 return false; 11592 } 11593 return true; 11594 } 11595 11596 @Override 11597 public void getPackageSizeInfo(final String packageName, int userHandle, 11598 final IPackageStatsObserver observer) { 11599 mContext.enforceCallingOrSelfPermission( 11600 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11601 if (packageName == null) { 11602 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11603 } 11604 11605 PackageStats stats = new PackageStats(packageName, userHandle); 11606 11607 /* 11608 * Queue up an async operation since the package measurement may take a 11609 * little while. 11610 */ 11611 Message msg = mHandler.obtainMessage(INIT_COPY); 11612 msg.obj = new MeasureParams(stats, observer); 11613 mHandler.sendMessage(msg); 11614 } 11615 11616 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11617 PackageStats pStats) { 11618 if (packageName == null) { 11619 Slog.w(TAG, "Attempt to get size of null packageName."); 11620 return false; 11621 } 11622 PackageParser.Package p; 11623 boolean dataOnly = false; 11624 String libDirRoot = null; 11625 String asecPath = null; 11626 PackageSetting ps = null; 11627 synchronized (mPackages) { 11628 p = mPackages.get(packageName); 11629 ps = mSettings.mPackages.get(packageName); 11630 if(p == null) { 11631 dataOnly = true; 11632 if((ps == null) || (ps.pkg == null)) { 11633 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11634 return false; 11635 } 11636 p = ps.pkg; 11637 } 11638 if (ps != null) { 11639 libDirRoot = ps.legacyNativeLibraryPathString; 11640 } 11641 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11642 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11643 if (secureContainerId != null) { 11644 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11645 } 11646 } 11647 } 11648 String publicSrcDir = null; 11649 if(!dataOnly) { 11650 final ApplicationInfo applicationInfo = p.applicationInfo; 11651 if (applicationInfo == null) { 11652 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11653 return false; 11654 } 11655 if (p.isForwardLocked()) { 11656 publicSrcDir = applicationInfo.getBaseResourcePath(); 11657 } 11658 } 11659 // TODO: extend to measure size of split APKs 11660 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11661 // not just the first level. 11662 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11663 // just the primary. 11664 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11665 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11666 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11667 if (res < 0) { 11668 return false; 11669 } 11670 11671 // Fix-up for forward-locked applications in ASEC containers. 11672 if (!isExternal(p)) { 11673 pStats.codeSize += pStats.externalCodeSize; 11674 pStats.externalCodeSize = 0L; 11675 } 11676 11677 return true; 11678 } 11679 11680 11681 @Override 11682 public void addPackageToPreferred(String packageName) { 11683 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11684 } 11685 11686 @Override 11687 public void removePackageFromPreferred(String packageName) { 11688 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11689 } 11690 11691 @Override 11692 public List<PackageInfo> getPreferredPackages(int flags) { 11693 return new ArrayList<PackageInfo>(); 11694 } 11695 11696 private int getUidTargetSdkVersionLockedLPr(int uid) { 11697 Object obj = mSettings.getUserIdLPr(uid); 11698 if (obj instanceof SharedUserSetting) { 11699 final SharedUserSetting sus = (SharedUserSetting) obj; 11700 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11701 final Iterator<PackageSetting> it = sus.packages.iterator(); 11702 while (it.hasNext()) { 11703 final PackageSetting ps = it.next(); 11704 if (ps.pkg != null) { 11705 int v = ps.pkg.applicationInfo.targetSdkVersion; 11706 if (v < vers) vers = v; 11707 } 11708 } 11709 return vers; 11710 } else if (obj instanceof PackageSetting) { 11711 final PackageSetting ps = (PackageSetting) obj; 11712 if (ps.pkg != null) { 11713 return ps.pkg.applicationInfo.targetSdkVersion; 11714 } 11715 } 11716 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11717 } 11718 11719 @Override 11720 public void addPreferredActivity(IntentFilter filter, int match, 11721 ComponentName[] set, ComponentName activity, int userId) { 11722 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11723 "Adding preferred"); 11724 } 11725 11726 private void addPreferredActivityInternal(IntentFilter filter, int match, 11727 ComponentName[] set, ComponentName activity, boolean always, int userId, 11728 String opname) { 11729 // writer 11730 int callingUid = Binder.getCallingUid(); 11731 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11732 if (filter.countActions() == 0) { 11733 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11734 return; 11735 } 11736 synchronized (mPackages) { 11737 if (mContext.checkCallingOrSelfPermission( 11738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11739 != PackageManager.PERMISSION_GRANTED) { 11740 if (getUidTargetSdkVersionLockedLPr(callingUid) 11741 < Build.VERSION_CODES.FROYO) { 11742 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11743 + callingUid); 11744 return; 11745 } 11746 mContext.enforceCallingOrSelfPermission( 11747 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11748 } 11749 11750 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11751 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11752 + userId + ":"); 11753 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11754 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11755 scheduleWritePackageRestrictionsLocked(userId); 11756 } 11757 } 11758 11759 @Override 11760 public void replacePreferredActivity(IntentFilter filter, int match, 11761 ComponentName[] set, ComponentName activity, int userId) { 11762 if (filter.countActions() != 1) { 11763 throw new IllegalArgumentException( 11764 "replacePreferredActivity expects filter to have only 1 action."); 11765 } 11766 if (filter.countDataAuthorities() != 0 11767 || filter.countDataPaths() != 0 11768 || filter.countDataSchemes() > 1 11769 || filter.countDataTypes() != 0) { 11770 throw new IllegalArgumentException( 11771 "replacePreferredActivity expects filter to have no data authorities, " + 11772 "paths, or types; and at most one scheme."); 11773 } 11774 11775 final int callingUid = Binder.getCallingUid(); 11776 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11777 synchronized (mPackages) { 11778 if (mContext.checkCallingOrSelfPermission( 11779 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11780 != PackageManager.PERMISSION_GRANTED) { 11781 if (getUidTargetSdkVersionLockedLPr(callingUid) 11782 < Build.VERSION_CODES.FROYO) { 11783 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11784 + Binder.getCallingUid()); 11785 return; 11786 } 11787 mContext.enforceCallingOrSelfPermission( 11788 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11789 } 11790 11791 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11792 if (pir != null) { 11793 // Get all of the existing entries that exactly match this filter. 11794 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11795 if (existing != null && existing.size() == 1) { 11796 PreferredActivity cur = existing.get(0); 11797 if (DEBUG_PREFERRED) { 11798 Slog.i(TAG, "Checking replace of preferred:"); 11799 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11800 if (!cur.mPref.mAlways) { 11801 Slog.i(TAG, " -- CUR; not mAlways!"); 11802 } else { 11803 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11804 Slog.i(TAG, " -- CUR: mSet=" 11805 + Arrays.toString(cur.mPref.mSetComponents)); 11806 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11807 Slog.i(TAG, " -- NEW: mMatch=" 11808 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11809 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11810 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11811 } 11812 } 11813 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11814 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11815 && cur.mPref.sameSet(set)) { 11816 // Setting the preferred activity to what it happens to be already 11817 if (DEBUG_PREFERRED) { 11818 Slog.i(TAG, "Replacing with same preferred activity " 11819 + cur.mPref.mShortComponent + " for user " 11820 + userId + ":"); 11821 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11822 } 11823 return; 11824 } 11825 } 11826 11827 if (existing != null) { 11828 if (DEBUG_PREFERRED) { 11829 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11830 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11831 } 11832 for (int i = 0; i < existing.size(); i++) { 11833 PreferredActivity pa = existing.get(i); 11834 if (DEBUG_PREFERRED) { 11835 Slog.i(TAG, "Removing existing preferred activity " 11836 + pa.mPref.mComponent + ":"); 11837 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11838 } 11839 pir.removeFilter(pa); 11840 } 11841 } 11842 } 11843 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11844 "Replacing preferred"); 11845 } 11846 } 11847 11848 @Override 11849 public void clearPackagePreferredActivities(String packageName) { 11850 final int uid = Binder.getCallingUid(); 11851 // writer 11852 synchronized (mPackages) { 11853 PackageParser.Package pkg = mPackages.get(packageName); 11854 if (pkg == null || pkg.applicationInfo.uid != uid) { 11855 if (mContext.checkCallingOrSelfPermission( 11856 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11857 != PackageManager.PERMISSION_GRANTED) { 11858 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11859 < Build.VERSION_CODES.FROYO) { 11860 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11861 + Binder.getCallingUid()); 11862 return; 11863 } 11864 mContext.enforceCallingOrSelfPermission( 11865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11866 } 11867 } 11868 11869 int user = UserHandle.getCallingUserId(); 11870 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11871 scheduleWritePackageRestrictionsLocked(user); 11872 } 11873 } 11874 } 11875 11876 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11877 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11878 ArrayList<PreferredActivity> removed = null; 11879 boolean changed = false; 11880 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11881 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11882 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11883 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11884 continue; 11885 } 11886 Iterator<PreferredActivity> it = pir.filterIterator(); 11887 while (it.hasNext()) { 11888 PreferredActivity pa = it.next(); 11889 // Mark entry for removal only if it matches the package name 11890 // and the entry is of type "always". 11891 if (packageName == null || 11892 (pa.mPref.mComponent.getPackageName().equals(packageName) 11893 && pa.mPref.mAlways)) { 11894 if (removed == null) { 11895 removed = new ArrayList<PreferredActivity>(); 11896 } 11897 removed.add(pa); 11898 } 11899 } 11900 if (removed != null) { 11901 for (int j=0; j<removed.size(); j++) { 11902 PreferredActivity pa = removed.get(j); 11903 pir.removeFilter(pa); 11904 } 11905 changed = true; 11906 } 11907 } 11908 return changed; 11909 } 11910 11911 @Override 11912 public void resetPreferredActivities(int userId) { 11913 /* TODO: Actually use userId. Why is it being passed in? */ 11914 mContext.enforceCallingOrSelfPermission( 11915 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11916 // writer 11917 synchronized (mPackages) { 11918 int user = UserHandle.getCallingUserId(); 11919 clearPackagePreferredActivitiesLPw(null, user); 11920 mSettings.readDefaultPreferredAppsLPw(this, user); 11921 scheduleWritePackageRestrictionsLocked(user); 11922 } 11923 } 11924 11925 @Override 11926 public int getPreferredActivities(List<IntentFilter> outFilters, 11927 List<ComponentName> outActivities, String packageName) { 11928 11929 int num = 0; 11930 final int userId = UserHandle.getCallingUserId(); 11931 // reader 11932 synchronized (mPackages) { 11933 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11934 if (pir != null) { 11935 final Iterator<PreferredActivity> it = pir.filterIterator(); 11936 while (it.hasNext()) { 11937 final PreferredActivity pa = it.next(); 11938 if (packageName == null 11939 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11940 && pa.mPref.mAlways)) { 11941 if (outFilters != null) { 11942 outFilters.add(new IntentFilter(pa)); 11943 } 11944 if (outActivities != null) { 11945 outActivities.add(pa.mPref.mComponent); 11946 } 11947 } 11948 } 11949 } 11950 } 11951 11952 return num; 11953 } 11954 11955 @Override 11956 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11957 int userId) { 11958 int callingUid = Binder.getCallingUid(); 11959 if (callingUid != Process.SYSTEM_UID) { 11960 throw new SecurityException( 11961 "addPersistentPreferredActivity can only be run by the system"); 11962 } 11963 if (filter.countActions() == 0) { 11964 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11965 return; 11966 } 11967 synchronized (mPackages) { 11968 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11969 " :"); 11970 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11971 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11972 new PersistentPreferredActivity(filter, activity)); 11973 scheduleWritePackageRestrictionsLocked(userId); 11974 } 11975 } 11976 11977 @Override 11978 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11979 int callingUid = Binder.getCallingUid(); 11980 if (callingUid != Process.SYSTEM_UID) { 11981 throw new SecurityException( 11982 "clearPackagePersistentPreferredActivities can only be run by the system"); 11983 } 11984 ArrayList<PersistentPreferredActivity> removed = null; 11985 boolean changed = false; 11986 synchronized (mPackages) { 11987 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11988 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11989 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11990 .valueAt(i); 11991 if (userId != thisUserId) { 11992 continue; 11993 } 11994 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11995 while (it.hasNext()) { 11996 PersistentPreferredActivity ppa = it.next(); 11997 // Mark entry for removal only if it matches the package name. 11998 if (ppa.mComponent.getPackageName().equals(packageName)) { 11999 if (removed == null) { 12000 removed = new ArrayList<PersistentPreferredActivity>(); 12001 } 12002 removed.add(ppa); 12003 } 12004 } 12005 if (removed != null) { 12006 for (int j=0; j<removed.size(); j++) { 12007 PersistentPreferredActivity ppa = removed.get(j); 12008 ppir.removeFilter(ppa); 12009 } 12010 changed = true; 12011 } 12012 } 12013 12014 if (changed) { 12015 scheduleWritePackageRestrictionsLocked(userId); 12016 } 12017 } 12018 } 12019 12020 @Override 12021 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12022 int sourceUserId, int targetUserId, int flags) { 12023 mContext.enforceCallingOrSelfPermission( 12024 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12025 int callingUid = Binder.getCallingUid(); 12026 enforceOwnerRights(ownerPackage, callingUid); 12027 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12028 if (intentFilter.countActions() == 0) { 12029 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12030 return; 12031 } 12032 synchronized (mPackages) { 12033 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12034 ownerPackage, targetUserId, flags); 12035 CrossProfileIntentResolver resolver = 12036 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12037 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12038 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12039 if (existing != null) { 12040 int size = existing.size(); 12041 for (int i = 0; i < size; i++) { 12042 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12043 return; 12044 } 12045 } 12046 } 12047 resolver.addFilter(newFilter); 12048 scheduleWritePackageRestrictionsLocked(sourceUserId); 12049 } 12050 } 12051 12052 @Override 12053 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12054 mContext.enforceCallingOrSelfPermission( 12055 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12056 int callingUid = Binder.getCallingUid(); 12057 enforceOwnerRights(ownerPackage, callingUid); 12058 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12059 synchronized (mPackages) { 12060 CrossProfileIntentResolver resolver = 12061 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12062 ArraySet<CrossProfileIntentFilter> set = 12063 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12064 for (CrossProfileIntentFilter filter : set) { 12065 if (filter.getOwnerPackage().equals(ownerPackage)) { 12066 resolver.removeFilter(filter); 12067 } 12068 } 12069 scheduleWritePackageRestrictionsLocked(sourceUserId); 12070 } 12071 } 12072 12073 // Enforcing that callingUid is owning pkg on userId 12074 private void enforceOwnerRights(String pkg, int callingUid) { 12075 // The system owns everything. 12076 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12077 return; 12078 } 12079 int callingUserId = UserHandle.getUserId(callingUid); 12080 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12081 if (pi == null) { 12082 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12083 + callingUserId); 12084 } 12085 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12086 throw new SecurityException("Calling uid " + callingUid 12087 + " does not own package " + pkg); 12088 } 12089 } 12090 12091 @Override 12092 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12093 Intent intent = new Intent(Intent.ACTION_MAIN); 12094 intent.addCategory(Intent.CATEGORY_HOME); 12095 12096 final int callingUserId = UserHandle.getCallingUserId(); 12097 List<ResolveInfo> list = queryIntentActivities(intent, null, 12098 PackageManager.GET_META_DATA, callingUserId); 12099 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12100 true, false, false, callingUserId); 12101 12102 allHomeCandidates.clear(); 12103 if (list != null) { 12104 for (ResolveInfo ri : list) { 12105 allHomeCandidates.add(ri); 12106 } 12107 } 12108 return (preferred == null || preferred.activityInfo == null) 12109 ? null 12110 : new ComponentName(preferred.activityInfo.packageName, 12111 preferred.activityInfo.name); 12112 } 12113 12114 @Override 12115 public void setApplicationEnabledSetting(String appPackageName, 12116 int newState, int flags, int userId, String callingPackage) { 12117 if (!sUserManager.exists(userId)) return; 12118 if (callingPackage == null) { 12119 callingPackage = Integer.toString(Binder.getCallingUid()); 12120 } 12121 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12122 } 12123 12124 @Override 12125 public void setComponentEnabledSetting(ComponentName componentName, 12126 int newState, int flags, int userId) { 12127 if (!sUserManager.exists(userId)) return; 12128 setEnabledSetting(componentName.getPackageName(), 12129 componentName.getClassName(), newState, flags, userId, null); 12130 } 12131 12132 private void setEnabledSetting(final String packageName, String className, int newState, 12133 final int flags, int userId, String callingPackage) { 12134 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12135 || newState == COMPONENT_ENABLED_STATE_ENABLED 12136 || newState == COMPONENT_ENABLED_STATE_DISABLED 12137 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12138 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12139 throw new IllegalArgumentException("Invalid new component state: " 12140 + newState); 12141 } 12142 PackageSetting pkgSetting; 12143 final int uid = Binder.getCallingUid(); 12144 final int permission = mContext.checkCallingOrSelfPermission( 12145 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12146 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12147 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12148 boolean sendNow = false; 12149 boolean isApp = (className == null); 12150 String componentName = isApp ? packageName : className; 12151 int packageUid = -1; 12152 ArrayList<String> components; 12153 12154 // writer 12155 synchronized (mPackages) { 12156 pkgSetting = mSettings.mPackages.get(packageName); 12157 if (pkgSetting == null) { 12158 if (className == null) { 12159 throw new IllegalArgumentException( 12160 "Unknown package: " + packageName); 12161 } 12162 throw new IllegalArgumentException( 12163 "Unknown component: " + packageName 12164 + "/" + className); 12165 } 12166 // Allow root and verify that userId is not being specified by a different user 12167 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12168 throw new SecurityException( 12169 "Permission Denial: attempt to change component state from pid=" 12170 + Binder.getCallingPid() 12171 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12172 } 12173 if (className == null) { 12174 // We're dealing with an application/package level state change 12175 if (pkgSetting.getEnabled(userId) == newState) { 12176 // Nothing to do 12177 return; 12178 } 12179 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12180 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12181 // Don't care about who enables an app. 12182 callingPackage = null; 12183 } 12184 pkgSetting.setEnabled(newState, userId, callingPackage); 12185 // pkgSetting.pkg.mSetEnabled = newState; 12186 } else { 12187 // We're dealing with a component level state change 12188 // First, verify that this is a valid class name. 12189 PackageParser.Package pkg = pkgSetting.pkg; 12190 if (pkg == null || !pkg.hasComponentClassName(className)) { 12191 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12192 throw new IllegalArgumentException("Component class " + className 12193 + " does not exist in " + packageName); 12194 } else { 12195 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12196 + className + " does not exist in " + packageName); 12197 } 12198 } 12199 switch (newState) { 12200 case COMPONENT_ENABLED_STATE_ENABLED: 12201 if (!pkgSetting.enableComponentLPw(className, userId)) { 12202 return; 12203 } 12204 break; 12205 case COMPONENT_ENABLED_STATE_DISABLED: 12206 if (!pkgSetting.disableComponentLPw(className, userId)) { 12207 return; 12208 } 12209 break; 12210 case COMPONENT_ENABLED_STATE_DEFAULT: 12211 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12212 return; 12213 } 12214 break; 12215 default: 12216 Slog.e(TAG, "Invalid new component state: " + newState); 12217 return; 12218 } 12219 } 12220 scheduleWritePackageRestrictionsLocked(userId); 12221 components = mPendingBroadcasts.get(userId, packageName); 12222 final boolean newPackage = components == null; 12223 if (newPackage) { 12224 components = new ArrayList<String>(); 12225 } 12226 if (!components.contains(componentName)) { 12227 components.add(componentName); 12228 } 12229 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12230 sendNow = true; 12231 // Purge entry from pending broadcast list if another one exists already 12232 // since we are sending one right away. 12233 mPendingBroadcasts.remove(userId, packageName); 12234 } else { 12235 if (newPackage) { 12236 mPendingBroadcasts.put(userId, packageName, components); 12237 } 12238 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12239 // Schedule a message 12240 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12241 } 12242 } 12243 } 12244 12245 long callingId = Binder.clearCallingIdentity(); 12246 try { 12247 if (sendNow) { 12248 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12249 sendPackageChangedBroadcast(packageName, 12250 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12251 } 12252 } finally { 12253 Binder.restoreCallingIdentity(callingId); 12254 } 12255 } 12256 12257 private void sendPackageChangedBroadcast(String packageName, 12258 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12259 if (DEBUG_INSTALL) 12260 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12261 + componentNames); 12262 Bundle extras = new Bundle(4); 12263 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12264 String nameList[] = new String[componentNames.size()]; 12265 componentNames.toArray(nameList); 12266 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12267 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12268 extras.putInt(Intent.EXTRA_UID, packageUid); 12269 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12270 new int[] {UserHandle.getUserId(packageUid)}); 12271 } 12272 12273 @Override 12274 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12275 if (!sUserManager.exists(userId)) return; 12276 final int uid = Binder.getCallingUid(); 12277 final int permission = mContext.checkCallingOrSelfPermission( 12278 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12279 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12280 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12281 // writer 12282 synchronized (mPackages) { 12283 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12284 uid, userId)) { 12285 scheduleWritePackageRestrictionsLocked(userId); 12286 } 12287 } 12288 } 12289 12290 @Override 12291 public String getInstallerPackageName(String packageName) { 12292 // reader 12293 synchronized (mPackages) { 12294 return mSettings.getInstallerPackageNameLPr(packageName); 12295 } 12296 } 12297 12298 @Override 12299 public int getApplicationEnabledSetting(String packageName, int userId) { 12300 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12301 int uid = Binder.getCallingUid(); 12302 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12303 // reader 12304 synchronized (mPackages) { 12305 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12306 } 12307 } 12308 12309 @Override 12310 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12311 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12312 int uid = Binder.getCallingUid(); 12313 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12314 // reader 12315 synchronized (mPackages) { 12316 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12317 } 12318 } 12319 12320 @Override 12321 public void enterSafeMode() { 12322 enforceSystemOrRoot("Only the system can request entering safe mode"); 12323 12324 if (!mSystemReady) { 12325 mSafeMode = true; 12326 } 12327 } 12328 12329 @Override 12330 public void systemReady() { 12331 mSystemReady = true; 12332 12333 // Read the compatibilty setting when the system is ready. 12334 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12335 mContext.getContentResolver(), 12336 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12337 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12338 if (DEBUG_SETTINGS) { 12339 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12340 } 12341 12342 synchronized (mPackages) { 12343 // Verify that all of the preferred activity components actually 12344 // exist. It is possible for applications to be updated and at 12345 // that point remove a previously declared activity component that 12346 // had been set as a preferred activity. We try to clean this up 12347 // the next time we encounter that preferred activity, but it is 12348 // possible for the user flow to never be able to return to that 12349 // situation so here we do a sanity check to make sure we haven't 12350 // left any junk around. 12351 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12352 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12353 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12354 removed.clear(); 12355 for (PreferredActivity pa : pir.filterSet()) { 12356 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12357 removed.add(pa); 12358 } 12359 } 12360 if (removed.size() > 0) { 12361 for (int r=0; r<removed.size(); r++) { 12362 PreferredActivity pa = removed.get(r); 12363 Slog.w(TAG, "Removing dangling preferred activity: " 12364 + pa.mPref.mComponent); 12365 pir.removeFilter(pa); 12366 } 12367 mSettings.writePackageRestrictionsLPr( 12368 mSettings.mPreferredActivities.keyAt(i)); 12369 } 12370 } 12371 } 12372 sUserManager.systemReady(); 12373 12374 // Kick off any messages waiting for system ready 12375 if (mPostSystemReadyMessages != null) { 12376 for (Message msg : mPostSystemReadyMessages) { 12377 msg.sendToTarget(); 12378 } 12379 mPostSystemReadyMessages = null; 12380 } 12381 } 12382 12383 @Override 12384 public boolean isSafeMode() { 12385 return mSafeMode; 12386 } 12387 12388 @Override 12389 public boolean hasSystemUidErrors() { 12390 return mHasSystemUidErrors; 12391 } 12392 12393 static String arrayToString(int[] array) { 12394 StringBuffer buf = new StringBuffer(128); 12395 buf.append('['); 12396 if (array != null) { 12397 for (int i=0; i<array.length; i++) { 12398 if (i > 0) buf.append(", "); 12399 buf.append(array[i]); 12400 } 12401 } 12402 buf.append(']'); 12403 return buf.toString(); 12404 } 12405 12406 static class DumpState { 12407 public static final int DUMP_LIBS = 1 << 0; 12408 public static final int DUMP_FEATURES = 1 << 1; 12409 public static final int DUMP_RESOLVERS = 1 << 2; 12410 public static final int DUMP_PERMISSIONS = 1 << 3; 12411 public static final int DUMP_PACKAGES = 1 << 4; 12412 public static final int DUMP_SHARED_USERS = 1 << 5; 12413 public static final int DUMP_MESSAGES = 1 << 6; 12414 public static final int DUMP_PROVIDERS = 1 << 7; 12415 public static final int DUMP_VERIFIERS = 1 << 8; 12416 public static final int DUMP_PREFERRED = 1 << 9; 12417 public static final int DUMP_PREFERRED_XML = 1 << 10; 12418 public static final int DUMP_KEYSETS = 1 << 11; 12419 public static final int DUMP_VERSION = 1 << 12; 12420 public static final int DUMP_INSTALLS = 1 << 13; 12421 12422 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12423 12424 private int mTypes; 12425 12426 private int mOptions; 12427 12428 private boolean mTitlePrinted; 12429 12430 private SharedUserSetting mSharedUser; 12431 12432 public boolean isDumping(int type) { 12433 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12434 return true; 12435 } 12436 12437 return (mTypes & type) != 0; 12438 } 12439 12440 public void setDump(int type) { 12441 mTypes |= type; 12442 } 12443 12444 public boolean isOptionEnabled(int option) { 12445 return (mOptions & option) != 0; 12446 } 12447 12448 public void setOptionEnabled(int option) { 12449 mOptions |= option; 12450 } 12451 12452 public boolean onTitlePrinted() { 12453 final boolean printed = mTitlePrinted; 12454 mTitlePrinted = true; 12455 return printed; 12456 } 12457 12458 public boolean getTitlePrinted() { 12459 return mTitlePrinted; 12460 } 12461 12462 public void setTitlePrinted(boolean enabled) { 12463 mTitlePrinted = enabled; 12464 } 12465 12466 public SharedUserSetting getSharedUser() { 12467 return mSharedUser; 12468 } 12469 12470 public void setSharedUser(SharedUserSetting user) { 12471 mSharedUser = user; 12472 } 12473 } 12474 12475 @Override 12476 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12477 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12478 != PackageManager.PERMISSION_GRANTED) { 12479 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12480 + Binder.getCallingPid() 12481 + ", uid=" + Binder.getCallingUid() 12482 + " without permission " 12483 + android.Manifest.permission.DUMP); 12484 return; 12485 } 12486 12487 DumpState dumpState = new DumpState(); 12488 boolean fullPreferred = false; 12489 boolean checkin = false; 12490 12491 String packageName = null; 12492 12493 int opti = 0; 12494 while (opti < args.length) { 12495 String opt = args[opti]; 12496 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12497 break; 12498 } 12499 opti++; 12500 12501 if ("-a".equals(opt)) { 12502 // Right now we only know how to print all. 12503 } else if ("-h".equals(opt)) { 12504 pw.println("Package manager dump options:"); 12505 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12506 pw.println(" --checkin: dump for a checkin"); 12507 pw.println(" -f: print details of intent filters"); 12508 pw.println(" -h: print this help"); 12509 pw.println(" cmd may be one of:"); 12510 pw.println(" l[ibraries]: list known shared libraries"); 12511 pw.println(" f[ibraries]: list device features"); 12512 pw.println(" k[eysets]: print known keysets"); 12513 pw.println(" r[esolvers]: dump intent resolvers"); 12514 pw.println(" perm[issions]: dump permissions"); 12515 pw.println(" pref[erred]: print preferred package settings"); 12516 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12517 pw.println(" prov[iders]: dump content providers"); 12518 pw.println(" p[ackages]: dump installed packages"); 12519 pw.println(" s[hared-users]: dump shared user IDs"); 12520 pw.println(" m[essages]: print collected runtime messages"); 12521 pw.println(" v[erifiers]: print package verifier info"); 12522 pw.println(" version: print database version info"); 12523 pw.println(" write: write current settings now"); 12524 pw.println(" <package.name>: info about given package"); 12525 pw.println(" installs: details about install sessions"); 12526 return; 12527 } else if ("--checkin".equals(opt)) { 12528 checkin = true; 12529 } else if ("-f".equals(opt)) { 12530 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12531 } else { 12532 pw.println("Unknown argument: " + opt + "; use -h for help"); 12533 } 12534 } 12535 12536 // Is the caller requesting to dump a particular piece of data? 12537 if (opti < args.length) { 12538 String cmd = args[opti]; 12539 opti++; 12540 // Is this a package name? 12541 if ("android".equals(cmd) || cmd.contains(".")) { 12542 packageName = cmd; 12543 // When dumping a single package, we always dump all of its 12544 // filter information since the amount of data will be reasonable. 12545 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12546 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12547 dumpState.setDump(DumpState.DUMP_LIBS); 12548 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12549 dumpState.setDump(DumpState.DUMP_FEATURES); 12550 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12551 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12552 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12553 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12554 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12555 dumpState.setDump(DumpState.DUMP_PREFERRED); 12556 } else if ("preferred-xml".equals(cmd)) { 12557 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12558 if (opti < args.length && "--full".equals(args[opti])) { 12559 fullPreferred = true; 12560 opti++; 12561 } 12562 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12563 dumpState.setDump(DumpState.DUMP_PACKAGES); 12564 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12565 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12566 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12567 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12568 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12569 dumpState.setDump(DumpState.DUMP_MESSAGES); 12570 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12571 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12572 } else if ("version".equals(cmd)) { 12573 dumpState.setDump(DumpState.DUMP_VERSION); 12574 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12575 dumpState.setDump(DumpState.DUMP_KEYSETS); 12576 } else if ("installs".equals(cmd)) { 12577 dumpState.setDump(DumpState.DUMP_INSTALLS); 12578 } else if ("write".equals(cmd)) { 12579 synchronized (mPackages) { 12580 mSettings.writeLPr(); 12581 pw.println("Settings written."); 12582 return; 12583 } 12584 } 12585 } 12586 12587 if (checkin) { 12588 pw.println("vers,1"); 12589 } 12590 12591 // reader 12592 synchronized (mPackages) { 12593 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12594 if (!checkin) { 12595 if (dumpState.onTitlePrinted()) 12596 pw.println(); 12597 pw.println("Database versions:"); 12598 pw.print(" SDK Version:"); 12599 pw.print(" internal="); 12600 pw.print(mSettings.mInternalSdkPlatform); 12601 pw.print(" external="); 12602 pw.println(mSettings.mExternalSdkPlatform); 12603 pw.print(" DB Version:"); 12604 pw.print(" internal="); 12605 pw.print(mSettings.mInternalDatabaseVersion); 12606 pw.print(" external="); 12607 pw.println(mSettings.mExternalDatabaseVersion); 12608 } 12609 } 12610 12611 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12612 if (!checkin) { 12613 if (dumpState.onTitlePrinted()) 12614 pw.println(); 12615 pw.println("Verifiers:"); 12616 pw.print(" Required: "); 12617 pw.print(mRequiredVerifierPackage); 12618 pw.print(" (uid="); 12619 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12620 pw.println(")"); 12621 } else if (mRequiredVerifierPackage != null) { 12622 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12623 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12624 } 12625 } 12626 12627 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12628 boolean printedHeader = false; 12629 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12630 while (it.hasNext()) { 12631 String name = it.next(); 12632 SharedLibraryEntry ent = mSharedLibraries.get(name); 12633 if (!checkin) { 12634 if (!printedHeader) { 12635 if (dumpState.onTitlePrinted()) 12636 pw.println(); 12637 pw.println("Libraries:"); 12638 printedHeader = true; 12639 } 12640 pw.print(" "); 12641 } else { 12642 pw.print("lib,"); 12643 } 12644 pw.print(name); 12645 if (!checkin) { 12646 pw.print(" -> "); 12647 } 12648 if (ent.path != null) { 12649 if (!checkin) { 12650 pw.print("(jar) "); 12651 pw.print(ent.path); 12652 } else { 12653 pw.print(",jar,"); 12654 pw.print(ent.path); 12655 } 12656 } else { 12657 if (!checkin) { 12658 pw.print("(apk) "); 12659 pw.print(ent.apk); 12660 } else { 12661 pw.print(",apk,"); 12662 pw.print(ent.apk); 12663 } 12664 } 12665 pw.println(); 12666 } 12667 } 12668 12669 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12670 if (dumpState.onTitlePrinted()) 12671 pw.println(); 12672 if (!checkin) { 12673 pw.println("Features:"); 12674 } 12675 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12676 while (it.hasNext()) { 12677 String name = it.next(); 12678 if (!checkin) { 12679 pw.print(" "); 12680 } else { 12681 pw.print("feat,"); 12682 } 12683 pw.println(name); 12684 } 12685 } 12686 12687 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12688 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12689 : "Activity Resolver Table:", " ", packageName, 12690 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12691 dumpState.setTitlePrinted(true); 12692 } 12693 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12694 : "Receiver Resolver Table:", " ", packageName, 12695 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12696 dumpState.setTitlePrinted(true); 12697 } 12698 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12699 : "Service Resolver Table:", " ", packageName, 12700 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12701 dumpState.setTitlePrinted(true); 12702 } 12703 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12704 : "Provider Resolver Table:", " ", packageName, 12705 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12706 dumpState.setTitlePrinted(true); 12707 } 12708 } 12709 12710 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12711 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12712 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12713 int user = mSettings.mPreferredActivities.keyAt(i); 12714 if (pir.dump(pw, 12715 dumpState.getTitlePrinted() 12716 ? "\nPreferred Activities User " + user + ":" 12717 : "Preferred Activities User " + user + ":", " ", 12718 packageName, true, false)) { 12719 dumpState.setTitlePrinted(true); 12720 } 12721 } 12722 } 12723 12724 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12725 pw.flush(); 12726 FileOutputStream fout = new FileOutputStream(fd); 12727 BufferedOutputStream str = new BufferedOutputStream(fout); 12728 XmlSerializer serializer = new FastXmlSerializer(); 12729 try { 12730 serializer.setOutput(str, "utf-8"); 12731 serializer.startDocument(null, true); 12732 serializer.setFeature( 12733 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12734 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12735 serializer.endDocument(); 12736 serializer.flush(); 12737 } catch (IllegalArgumentException e) { 12738 pw.println("Failed writing: " + e); 12739 } catch (IllegalStateException e) { 12740 pw.println("Failed writing: " + e); 12741 } catch (IOException e) { 12742 pw.println("Failed writing: " + e); 12743 } 12744 } 12745 12746 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12747 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12748 if (packageName == null) { 12749 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12750 if (iperm == 0) { 12751 if (dumpState.onTitlePrinted()) 12752 pw.println(); 12753 pw.println("AppOp Permissions:"); 12754 } 12755 pw.print(" AppOp Permission "); 12756 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12757 pw.println(":"); 12758 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12759 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12760 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12761 } 12762 } 12763 } 12764 } 12765 12766 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12767 boolean printedSomething = false; 12768 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12769 if (packageName != null && !packageName.equals(p.info.packageName)) { 12770 continue; 12771 } 12772 if (!printedSomething) { 12773 if (dumpState.onTitlePrinted()) 12774 pw.println(); 12775 pw.println("Registered ContentProviders:"); 12776 printedSomething = true; 12777 } 12778 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12779 pw.print(" "); pw.println(p.toString()); 12780 } 12781 printedSomething = false; 12782 for (Map.Entry<String, PackageParser.Provider> entry : 12783 mProvidersByAuthority.entrySet()) { 12784 PackageParser.Provider p = entry.getValue(); 12785 if (packageName != null && !packageName.equals(p.info.packageName)) { 12786 continue; 12787 } 12788 if (!printedSomething) { 12789 if (dumpState.onTitlePrinted()) 12790 pw.println(); 12791 pw.println("ContentProvider Authorities:"); 12792 printedSomething = true; 12793 } 12794 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12795 pw.print(" "); pw.println(p.toString()); 12796 if (p.info != null && p.info.applicationInfo != null) { 12797 final String appInfo = p.info.applicationInfo.toString(); 12798 pw.print(" applicationInfo="); pw.println(appInfo); 12799 } 12800 } 12801 } 12802 12803 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12804 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12805 } 12806 12807 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12808 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12809 } 12810 12811 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12812 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12813 } 12814 12815 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12816 // XXX should handle packageName != null by dumping only install data that 12817 // the given package is involved with. 12818 if (dumpState.onTitlePrinted()) pw.println(); 12819 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12820 } 12821 12822 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12823 if (dumpState.onTitlePrinted()) pw.println(); 12824 mSettings.dumpReadMessagesLPr(pw, dumpState); 12825 12826 pw.println(); 12827 pw.println("Package warning messages:"); 12828 BufferedReader in = null; 12829 String line = null; 12830 try { 12831 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12832 while ((line = in.readLine()) != null) { 12833 if (line.contains("ignored: updated version")) continue; 12834 pw.println(line); 12835 } 12836 } catch (IOException ignored) { 12837 } finally { 12838 IoUtils.closeQuietly(in); 12839 } 12840 } 12841 12842 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12843 BufferedReader in = null; 12844 String line = null; 12845 try { 12846 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12847 while ((line = in.readLine()) != null) { 12848 if (line.contains("ignored: updated version")) continue; 12849 pw.print("msg,"); 12850 pw.println(line); 12851 } 12852 } catch (IOException ignored) { 12853 } finally { 12854 IoUtils.closeQuietly(in); 12855 } 12856 } 12857 } 12858 } 12859 12860 // ------- apps on sdcard specific code ------- 12861 static final boolean DEBUG_SD_INSTALL = false; 12862 12863 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12864 12865 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12866 12867 private boolean mMediaMounted = false; 12868 12869 static String getEncryptKey() { 12870 try { 12871 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12872 SD_ENCRYPTION_KEYSTORE_NAME); 12873 if (sdEncKey == null) { 12874 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12875 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12876 if (sdEncKey == null) { 12877 Slog.e(TAG, "Failed to create encryption keys"); 12878 return null; 12879 } 12880 } 12881 return sdEncKey; 12882 } catch (NoSuchAlgorithmException nsae) { 12883 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12884 return null; 12885 } catch (IOException ioe) { 12886 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12887 return null; 12888 } 12889 } 12890 12891 /* 12892 * Update media status on PackageManager. 12893 */ 12894 @Override 12895 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12896 int callingUid = Binder.getCallingUid(); 12897 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12898 throw new SecurityException("Media status can only be updated by the system"); 12899 } 12900 // reader; this apparently protects mMediaMounted, but should probably 12901 // be a different lock in that case. 12902 synchronized (mPackages) { 12903 Log.i(TAG, "Updating external media status from " 12904 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12905 + (mediaStatus ? "mounted" : "unmounted")); 12906 if (DEBUG_SD_INSTALL) 12907 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12908 + ", mMediaMounted=" + mMediaMounted); 12909 if (mediaStatus == mMediaMounted) { 12910 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12911 : 0, -1); 12912 mHandler.sendMessage(msg); 12913 return; 12914 } 12915 mMediaMounted = mediaStatus; 12916 } 12917 // Queue up an async operation since the package installation may take a 12918 // little while. 12919 mHandler.post(new Runnable() { 12920 public void run() { 12921 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12922 } 12923 }); 12924 } 12925 12926 /** 12927 * Called by MountService when the initial ASECs to scan are available. 12928 * Should block until all the ASEC containers are finished being scanned. 12929 */ 12930 public void scanAvailableAsecs() { 12931 updateExternalMediaStatusInner(true, false, false); 12932 if (mShouldRestoreconData) { 12933 SELinuxMMAC.setRestoreconDone(); 12934 mShouldRestoreconData = false; 12935 } 12936 } 12937 12938 /* 12939 * Collect information of applications on external media, map them against 12940 * existing containers and update information based on current mount status. 12941 * Please note that we always have to report status if reportStatus has been 12942 * set to true especially when unloading packages. 12943 */ 12944 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12945 boolean externalStorage) { 12946 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12947 int[] uidArr = EmptyArray.INT; 12948 12949 final String[] list = PackageHelper.getSecureContainerList(); 12950 if (ArrayUtils.isEmpty(list)) { 12951 Log.i(TAG, "No secure containers found"); 12952 } else { 12953 // Process list of secure containers and categorize them 12954 // as active or stale based on their package internal state. 12955 12956 // reader 12957 synchronized (mPackages) { 12958 for (String cid : list) { 12959 // Leave stages untouched for now; installer service owns them 12960 if (PackageInstallerService.isStageName(cid)) continue; 12961 12962 if (DEBUG_SD_INSTALL) 12963 Log.i(TAG, "Processing container " + cid); 12964 String pkgName = getAsecPackageName(cid); 12965 if (pkgName == null) { 12966 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12967 continue; 12968 } 12969 if (DEBUG_SD_INSTALL) 12970 Log.i(TAG, "Looking for pkg : " + pkgName); 12971 12972 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12973 if (ps == null) { 12974 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12975 continue; 12976 } 12977 12978 /* 12979 * Skip packages that are not external if we're unmounting 12980 * external storage. 12981 */ 12982 if (externalStorage && !isMounted && !isExternal(ps)) { 12983 continue; 12984 } 12985 12986 final AsecInstallArgs args = new AsecInstallArgs(cid, 12987 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12988 // The package status is changed only if the code path 12989 // matches between settings and the container id. 12990 if (ps.codePathString != null 12991 && ps.codePathString.startsWith(args.getCodePath())) { 12992 if (DEBUG_SD_INSTALL) { 12993 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12994 + " at code path: " + ps.codePathString); 12995 } 12996 12997 // We do have a valid package installed on sdcard 12998 processCids.put(args, ps.codePathString); 12999 final int uid = ps.appId; 13000 if (uid != -1) { 13001 uidArr = ArrayUtils.appendInt(uidArr, uid); 13002 } 13003 } else { 13004 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13005 + ps.codePathString); 13006 } 13007 } 13008 } 13009 13010 Arrays.sort(uidArr); 13011 } 13012 13013 // Process packages with valid entries. 13014 if (isMounted) { 13015 if (DEBUG_SD_INSTALL) 13016 Log.i(TAG, "Loading packages"); 13017 loadMediaPackages(processCids, uidArr); 13018 startCleaningPackages(); 13019 mInstallerService.onSecureContainersAvailable(); 13020 } else { 13021 if (DEBUG_SD_INSTALL) 13022 Log.i(TAG, "Unloading packages"); 13023 unloadMediaPackages(processCids, uidArr, reportStatus); 13024 } 13025 } 13026 13027 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13028 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13029 int size = pkgList.size(); 13030 if (size > 0) { 13031 // Send broadcasts here 13032 Bundle extras = new Bundle(); 13033 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13034 .toArray(new String[size])); 13035 if (uidArr != null) { 13036 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13037 } 13038 if (replacing) { 13039 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13040 } 13041 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13042 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13043 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13044 } 13045 } 13046 13047 /* 13048 * Look at potentially valid container ids from processCids If package 13049 * information doesn't match the one on record or package scanning fails, 13050 * the cid is added to list of removeCids. We currently don't delete stale 13051 * containers. 13052 */ 13053 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13054 ArrayList<String> pkgList = new ArrayList<String>(); 13055 Set<AsecInstallArgs> keys = processCids.keySet(); 13056 13057 for (AsecInstallArgs args : keys) { 13058 String codePath = processCids.get(args); 13059 if (DEBUG_SD_INSTALL) 13060 Log.i(TAG, "Loading container : " + args.cid); 13061 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13062 try { 13063 // Make sure there are no container errors first. 13064 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13065 Slog.e(TAG, "Failed to mount cid : " + args.cid 13066 + " when installing from sdcard"); 13067 continue; 13068 } 13069 // Check code path here. 13070 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13071 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13072 + " does not match one in settings " + codePath); 13073 continue; 13074 } 13075 // Parse package 13076 int parseFlags = mDefParseFlags; 13077 if (args.isExternal()) { 13078 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13079 } 13080 if (args.isFwdLocked()) { 13081 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13082 } 13083 13084 synchronized (mInstallLock) { 13085 PackageParser.Package pkg = null; 13086 try { 13087 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13088 } catch (PackageManagerException e) { 13089 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13090 } 13091 // Scan the package 13092 if (pkg != null) { 13093 /* 13094 * TODO why is the lock being held? doPostInstall is 13095 * called in other places without the lock. This needs 13096 * to be straightened out. 13097 */ 13098 // writer 13099 synchronized (mPackages) { 13100 retCode = PackageManager.INSTALL_SUCCEEDED; 13101 pkgList.add(pkg.packageName); 13102 // Post process args 13103 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13104 pkg.applicationInfo.uid); 13105 } 13106 } else { 13107 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13108 } 13109 } 13110 13111 } finally { 13112 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13113 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13114 } 13115 } 13116 } 13117 // writer 13118 synchronized (mPackages) { 13119 // If the platform SDK has changed since the last time we booted, 13120 // we need to re-grant app permission to catch any new ones that 13121 // appear. This is really a hack, and means that apps can in some 13122 // cases get permissions that the user didn't initially explicitly 13123 // allow... it would be nice to have some better way to handle 13124 // this situation. 13125 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13126 if (regrantPermissions) 13127 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13128 + mSdkVersion + "; regranting permissions for external storage"); 13129 mSettings.mExternalSdkPlatform = mSdkVersion; 13130 13131 // Make sure group IDs have been assigned, and any permission 13132 // changes in other apps are accounted for 13133 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13134 | (regrantPermissions 13135 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13136 : 0)); 13137 13138 mSettings.updateExternalDatabaseVersion(); 13139 13140 // can downgrade to reader 13141 // Persist settings 13142 mSettings.writeLPr(); 13143 } 13144 // Send a broadcast to let everyone know we are done processing 13145 if (pkgList.size() > 0) { 13146 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13147 } 13148 } 13149 13150 /* 13151 * Utility method to unload a list of specified containers 13152 */ 13153 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13154 // Just unmount all valid containers. 13155 for (AsecInstallArgs arg : cidArgs) { 13156 synchronized (mInstallLock) { 13157 arg.doPostDeleteLI(false); 13158 } 13159 } 13160 } 13161 13162 /* 13163 * Unload packages mounted on external media. This involves deleting package 13164 * data from internal structures, sending broadcasts about diabled packages, 13165 * gc'ing to free up references, unmounting all secure containers 13166 * corresponding to packages on external media, and posting a 13167 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13168 * that we always have to post this message if status has been requested no 13169 * matter what. 13170 */ 13171 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13172 final boolean reportStatus) { 13173 if (DEBUG_SD_INSTALL) 13174 Log.i(TAG, "unloading media packages"); 13175 ArrayList<String> pkgList = new ArrayList<String>(); 13176 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13177 final Set<AsecInstallArgs> keys = processCids.keySet(); 13178 for (AsecInstallArgs args : keys) { 13179 String pkgName = args.getPackageName(); 13180 if (DEBUG_SD_INSTALL) 13181 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13182 // Delete package internally 13183 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13184 synchronized (mInstallLock) { 13185 boolean res = deletePackageLI(pkgName, null, false, null, null, 13186 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13187 if (res) { 13188 pkgList.add(pkgName); 13189 } else { 13190 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13191 failedList.add(args); 13192 } 13193 } 13194 } 13195 13196 // reader 13197 synchronized (mPackages) { 13198 // We didn't update the settings after removing each package; 13199 // write them now for all packages. 13200 mSettings.writeLPr(); 13201 } 13202 13203 // We have to absolutely send UPDATED_MEDIA_STATUS only 13204 // after confirming that all the receivers processed the ordered 13205 // broadcast when packages get disabled, force a gc to clean things up. 13206 // and unload all the containers. 13207 if (pkgList.size() > 0) { 13208 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13209 new IIntentReceiver.Stub() { 13210 public void performReceive(Intent intent, int resultCode, String data, 13211 Bundle extras, boolean ordered, boolean sticky, 13212 int sendingUser) throws RemoteException { 13213 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13214 reportStatus ? 1 : 0, 1, keys); 13215 mHandler.sendMessage(msg); 13216 } 13217 }); 13218 } else { 13219 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13220 keys); 13221 mHandler.sendMessage(msg); 13222 } 13223 } 13224 13225 /** Binder call */ 13226 @Override 13227 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13228 final int flags) { 13229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13230 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13231 int returnCode = PackageManager.MOVE_SUCCEEDED; 13232 int currInstallFlags = 0; 13233 int newInstallFlags = 0; 13234 13235 File codeFile = null; 13236 String installerPackageName = null; 13237 String packageAbiOverride = null; 13238 13239 // reader 13240 synchronized (mPackages) { 13241 final PackageParser.Package pkg = mPackages.get(packageName); 13242 final PackageSetting ps = mSettings.mPackages.get(packageName); 13243 if (pkg == null || ps == null) { 13244 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13245 } else { 13246 // Disable moving fwd locked apps and system packages 13247 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13248 Slog.w(TAG, "Cannot move system application"); 13249 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13250 } else if (pkg.mOperationPending) { 13251 Slog.w(TAG, "Attempt to move package which has pending operations"); 13252 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13253 } else { 13254 // Find install location first 13255 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13256 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13257 Slog.w(TAG, "Ambigous flags specified for move location."); 13258 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13259 } else { 13260 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13261 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13262 currInstallFlags = isExternal(pkg) 13263 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13264 13265 if (newInstallFlags == currInstallFlags) { 13266 Slog.w(TAG, "No move required. Trying to move to same location"); 13267 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13268 } else { 13269 if (pkg.isForwardLocked()) { 13270 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13271 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13272 } 13273 } 13274 } 13275 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13276 pkg.mOperationPending = true; 13277 } 13278 } 13279 13280 codeFile = new File(pkg.codePath); 13281 installerPackageName = ps.installerPackageName; 13282 packageAbiOverride = ps.cpuAbiOverrideString; 13283 } 13284 } 13285 13286 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13287 try { 13288 observer.packageMoved(packageName, returnCode); 13289 } catch (RemoteException ignored) { 13290 } 13291 return; 13292 } 13293 13294 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13295 @Override 13296 public void onUserActionRequired(Intent intent) throws RemoteException { 13297 throw new IllegalStateException(); 13298 } 13299 13300 @Override 13301 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13302 Bundle extras) throws RemoteException { 13303 Slog.d(TAG, "Install result for move: " 13304 + PackageManager.installStatusToString(returnCode, msg)); 13305 13306 // We usually have a new package now after the install, but if 13307 // we failed we need to clear the pending flag on the original 13308 // package object. 13309 synchronized (mPackages) { 13310 final PackageParser.Package pkg = mPackages.get(packageName); 13311 if (pkg != null) { 13312 pkg.mOperationPending = false; 13313 } 13314 } 13315 13316 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13317 switch (status) { 13318 case PackageInstaller.STATUS_SUCCESS: 13319 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13320 break; 13321 case PackageInstaller.STATUS_FAILURE_STORAGE: 13322 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13323 break; 13324 default: 13325 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13326 break; 13327 } 13328 } 13329 }; 13330 13331 // Treat a move like reinstalling an existing app, which ensures that we 13332 // process everythign uniformly, like unpacking native libraries. 13333 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13334 13335 final Message msg = mHandler.obtainMessage(INIT_COPY); 13336 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13337 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13338 installerPackageName, null, user, packageAbiOverride); 13339 mHandler.sendMessage(msg); 13340 } 13341 13342 @Override 13343 public boolean setInstallLocation(int loc) { 13344 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13345 null); 13346 if (getInstallLocation() == loc) { 13347 return true; 13348 } 13349 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13350 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13351 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13352 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13353 return true; 13354 } 13355 return false; 13356 } 13357 13358 @Override 13359 public int getInstallLocation() { 13360 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13361 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13362 PackageHelper.APP_INSTALL_AUTO); 13363 } 13364 13365 /** Called by UserManagerService */ 13366 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13367 mDirtyUsers.remove(userHandle); 13368 mSettings.removeUserLPw(userHandle); 13369 mPendingBroadcasts.remove(userHandle); 13370 if (mInstaller != null) { 13371 // Technically, we shouldn't be doing this with the package lock 13372 // held. However, this is very rare, and there is already so much 13373 // other disk I/O going on, that we'll let it slide for now. 13374 mInstaller.removeUserDataDirs(userHandle); 13375 } 13376 mUserNeedsBadging.delete(userHandle); 13377 removeUnusedPackagesLILPw(userManager, userHandle); 13378 } 13379 13380 /** 13381 * We're removing userHandle and would like to remove any downloaded packages 13382 * that are no longer in use by any other user. 13383 * @param userHandle the user being removed 13384 */ 13385 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13386 final boolean DEBUG_CLEAN_APKS = false; 13387 int [] users = userManager.getUserIdsLPr(); 13388 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13389 while (psit.hasNext()) { 13390 PackageSetting ps = psit.next(); 13391 if (ps.pkg == null) { 13392 continue; 13393 } 13394 final String packageName = ps.pkg.packageName; 13395 // Skip over if system app 13396 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13397 continue; 13398 } 13399 if (DEBUG_CLEAN_APKS) { 13400 Slog.i(TAG, "Checking package " + packageName); 13401 } 13402 boolean keep = false; 13403 for (int i = 0; i < users.length; i++) { 13404 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13405 keep = true; 13406 if (DEBUG_CLEAN_APKS) { 13407 Slog.i(TAG, " Keeping package " + packageName + " for user " 13408 + users[i]); 13409 } 13410 break; 13411 } 13412 } 13413 if (!keep) { 13414 if (DEBUG_CLEAN_APKS) { 13415 Slog.i(TAG, " Removing package " + packageName); 13416 } 13417 mHandler.post(new Runnable() { 13418 public void run() { 13419 deletePackageX(packageName, userHandle, 0); 13420 } //end run 13421 }); 13422 } 13423 } 13424 } 13425 13426 /** Called by UserManagerService */ 13427 void createNewUserLILPw(int userHandle, File path) { 13428 if (mInstaller != null) { 13429 mInstaller.createUserConfig(userHandle); 13430 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13431 } 13432 } 13433 13434 void newUserCreatedLILPw(int userHandle) { 13435 // Adding a user requires updating runtime permissions for system apps. 13436 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13437 } 13438 13439 @Override 13440 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13441 mContext.enforceCallingOrSelfPermission( 13442 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13443 "Only package verification agents can read the verifier device identity"); 13444 13445 synchronized (mPackages) { 13446 return mSettings.getVerifierDeviceIdentityLPw(); 13447 } 13448 } 13449 13450 @Override 13451 public void setPermissionEnforced(String permission, boolean enforced) { 13452 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13453 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13454 synchronized (mPackages) { 13455 if (mSettings.mReadExternalStorageEnforced == null 13456 || mSettings.mReadExternalStorageEnforced != enforced) { 13457 mSettings.mReadExternalStorageEnforced = enforced; 13458 mSettings.writeLPr(); 13459 } 13460 } 13461 // kill any non-foreground processes so we restart them and 13462 // grant/revoke the GID. 13463 final IActivityManager am = ActivityManagerNative.getDefault(); 13464 if (am != null) { 13465 final long token = Binder.clearCallingIdentity(); 13466 try { 13467 am.killProcessesBelowForeground("setPermissionEnforcement"); 13468 } catch (RemoteException e) { 13469 } finally { 13470 Binder.restoreCallingIdentity(token); 13471 } 13472 } 13473 } else { 13474 throw new IllegalArgumentException("No selective enforcement for " + permission); 13475 } 13476 } 13477 13478 @Override 13479 @Deprecated 13480 public boolean isPermissionEnforced(String permission) { 13481 return true; 13482 } 13483 13484 @Override 13485 public boolean isStorageLow() { 13486 final long token = Binder.clearCallingIdentity(); 13487 try { 13488 final DeviceStorageMonitorInternal 13489 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13490 if (dsm != null) { 13491 return dsm.isMemoryLow(); 13492 } else { 13493 return false; 13494 } 13495 } finally { 13496 Binder.restoreCallingIdentity(token); 13497 } 13498 } 13499 13500 @Override 13501 public IPackageInstaller getPackageInstaller() { 13502 return mInstallerService; 13503 } 13504 13505 private boolean userNeedsBadging(int userId) { 13506 int index = mUserNeedsBadging.indexOfKey(userId); 13507 if (index < 0) { 13508 final UserInfo userInfo; 13509 final long token = Binder.clearCallingIdentity(); 13510 try { 13511 userInfo = sUserManager.getUserInfo(userId); 13512 } finally { 13513 Binder.restoreCallingIdentity(token); 13514 } 13515 final boolean b; 13516 if (userInfo != null && userInfo.isManagedProfile()) { 13517 b = true; 13518 } else { 13519 b = false; 13520 } 13521 mUserNeedsBadging.put(userId, b); 13522 return b; 13523 } 13524 return mUserNeedsBadging.valueAt(index); 13525 } 13526 13527 @Override 13528 public KeySet getKeySetByAlias(String packageName, String alias) { 13529 if (packageName == null || alias == null) { 13530 return null; 13531 } 13532 synchronized(mPackages) { 13533 final PackageParser.Package pkg = mPackages.get(packageName); 13534 if (pkg == null) { 13535 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13536 throw new IllegalArgumentException("Unknown package: " + packageName); 13537 } 13538 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13539 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13540 } 13541 } 13542 13543 @Override 13544 public KeySet getSigningKeySet(String packageName) { 13545 if (packageName == null) { 13546 return null; 13547 } 13548 synchronized(mPackages) { 13549 final PackageParser.Package pkg = mPackages.get(packageName); 13550 if (pkg == null) { 13551 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13552 throw new IllegalArgumentException("Unknown package: " + packageName); 13553 } 13554 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13555 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13556 throw new SecurityException("May not access signing KeySet of other apps."); 13557 } 13558 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13559 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13560 } 13561 } 13562 13563 @Override 13564 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13565 if (packageName == null || ks == null) { 13566 return false; 13567 } 13568 synchronized(mPackages) { 13569 final PackageParser.Package pkg = mPackages.get(packageName); 13570 if (pkg == null) { 13571 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13572 throw new IllegalArgumentException("Unknown package: " + packageName); 13573 } 13574 IBinder ksh = ks.getToken(); 13575 if (ksh instanceof KeySetHandle) { 13576 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13577 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13578 } 13579 return false; 13580 } 13581 } 13582 13583 @Override 13584 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13585 if (packageName == null || ks == null) { 13586 return false; 13587 } 13588 synchronized(mPackages) { 13589 final PackageParser.Package pkg = mPackages.get(packageName); 13590 if (pkg == null) { 13591 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13592 throw new IllegalArgumentException("Unknown package: " + packageName); 13593 } 13594 IBinder ksh = ks.getToken(); 13595 if (ksh instanceof KeySetHandle) { 13596 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13597 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13598 } 13599 return false; 13600 } 13601 } 13602 13603 public void getUsageStatsIfNoPackageUsageInfo() { 13604 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13605 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13606 if (usm == null) { 13607 throw new IllegalStateException("UsageStatsManager must be initialized"); 13608 } 13609 long now = System.currentTimeMillis(); 13610 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13611 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13612 String packageName = entry.getKey(); 13613 PackageParser.Package pkg = mPackages.get(packageName); 13614 if (pkg == null) { 13615 continue; 13616 } 13617 UsageStats usage = entry.getValue(); 13618 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13619 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13620 } 13621 } 13622 } 13623 13624 /** 13625 * Check and throw if the given before/after packages would be considered a 13626 * downgrade. 13627 */ 13628 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13629 throws PackageManagerException { 13630 if (after.versionCode < before.mVersionCode) { 13631 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13632 "Update version code " + after.versionCode + " is older than current " 13633 + before.mVersionCode); 13634 } else if (after.versionCode == before.mVersionCode) { 13635 if (after.baseRevisionCode < before.baseRevisionCode) { 13636 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13637 "Update base revision code " + after.baseRevisionCode 13638 + " is older than current " + before.baseRevisionCode); 13639 } 13640 13641 if (!ArrayUtils.isEmpty(after.splitNames)) { 13642 for (int i = 0; i < after.splitNames.length; i++) { 13643 final String splitName = after.splitNames[i]; 13644 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13645 if (j != -1) { 13646 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13647 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13648 "Update split " + splitName + " revision code " 13649 + after.splitRevisionCodes[i] + " is older than current " 13650 + before.splitRevisionCodes[j]); 13651 } 13652 } 13653 } 13654 } 13655 } 13656 } 13657} 13658