PackageManagerService.java revision 3695b8a1488a6cc331feba1c2ab359888656bf7c
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 58import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 60import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 61 62import android.util.ArrayMap; 63 64import com.android.internal.R; 65import com.android.internal.app.IMediaContainerService; 66import com.android.internal.app.ResolverActivity; 67import com.android.internal.content.NativeLibraryHelper; 68import com.android.internal.content.PackageHelper; 69import com.android.internal.os.IParcelFileDescriptorFactory; 70import com.android.internal.util.ArrayUtils; 71import com.android.internal.util.FastPrintWriter; 72import com.android.internal.util.FastXmlSerializer; 73import com.android.internal.util.IndentingPrintWriter; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.AppGlobals; 88import android.app.IActivityManager; 89import android.app.admin.IDevicePolicyManager; 90import android.app.backup.IBackupManager; 91import android.app.usage.UsageStats; 92import android.app.usage.UsageStatsManager; 93import android.content.BroadcastReceiver; 94import android.content.ComponentName; 95import android.content.Context; 96import android.content.IIntentReceiver; 97import android.content.Intent; 98import android.content.IntentFilter; 99import android.content.IntentSender; 100import android.content.IntentSender.SendIntentException; 101import android.content.ServiceConnection; 102import android.content.pm.ActivityInfo; 103import android.content.pm.ApplicationInfo; 104import android.content.pm.FeatureInfo; 105import android.content.pm.IPackageDataObserver; 106import android.content.pm.IPackageDeleteObserver; 107import android.content.pm.IPackageDeleteObserver2; 108import android.content.pm.IPackageInstallObserver2; 109import android.content.pm.IPackageInstaller; 110import android.content.pm.IPackageManager; 111import android.content.pm.IPackageMoveObserver; 112import android.content.pm.IPackageStatsObserver; 113import android.content.pm.InstrumentationInfo; 114import android.content.pm.KeySet; 115import android.content.pm.ManifestDigest; 116import android.content.pm.PackageCleanItem; 117import android.content.pm.PackageInfo; 118import android.content.pm.PackageInfoLite; 119import android.content.pm.PackageInstaller; 120import android.content.pm.PackageManager; 121import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 122import android.content.pm.PackageParser.ActivityIntentInfo; 123import android.content.pm.PackageParser.PackageLite; 124import android.content.pm.PackageParser.PackageParserException; 125import android.content.pm.PackageParser; 126import android.content.pm.PackageStats; 127import android.content.pm.PackageUserState; 128import android.content.pm.ParceledListSlice; 129import android.content.pm.PermissionGroupInfo; 130import android.content.pm.PermissionInfo; 131import android.content.pm.ProviderInfo; 132import android.content.pm.ResolveInfo; 133import android.content.pm.ServiceInfo; 134import android.content.pm.Signature; 135import android.content.pm.UserInfo; 136import android.content.pm.VerificationParams; 137import android.content.pm.VerifierDeviceIdentity; 138import android.content.pm.VerifierInfo; 139import android.content.res.Resources; 140import android.hardware.display.DisplayManager; 141import android.net.Uri; 142import android.os.Binder; 143import android.os.Build; 144import android.os.Bundle; 145import android.os.Environment; 146import android.os.Environment.UserEnvironment; 147import android.os.storage.IMountService; 148import android.os.storage.StorageManager; 149import android.os.Debug; 150import android.os.FileUtils; 151import android.os.Handler; 152import android.os.IBinder; 153import android.os.Looper; 154import android.os.Message; 155import android.os.Parcel; 156import android.os.ParcelFileDescriptor; 157import android.os.Process; 158import android.os.RemoteException; 159import android.os.SELinux; 160import android.os.ServiceManager; 161import android.os.SystemClock; 162import android.os.SystemProperties; 163import android.os.UserHandle; 164import android.os.UserManager; 165import android.security.KeyStore; 166import android.security.SystemKeyStore; 167import android.system.ErrnoException; 168import android.system.Os; 169import android.system.StructStat; 170import android.text.TextUtils; 171import android.text.format.DateUtils; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.view.Display; 184 185import java.io.BufferedInputStream; 186import java.io.BufferedOutputStream; 187import java.io.BufferedReader; 188import java.io.File; 189import java.io.FileDescriptor; 190import java.io.FileNotFoundException; 191import java.io.FileOutputStream; 192import java.io.FileReader; 193import java.io.FilenameFilter; 194import java.io.IOException; 195import java.io.InputStream; 196import java.io.PrintWriter; 197import java.nio.charset.StandardCharsets; 198import java.security.NoSuchAlgorithmException; 199import java.security.PublicKey; 200import java.security.cert.CertificateEncodingException; 201import java.security.cert.CertificateException; 202import java.text.SimpleDateFormat; 203import java.util.ArrayList; 204import java.util.Arrays; 205import java.util.Collection; 206import java.util.Collections; 207import java.util.Comparator; 208import java.util.Date; 209import java.util.Iterator; 210import java.util.List; 211import java.util.Map; 212import java.util.Objects; 213import java.util.Set; 214import java.util.concurrent.atomic.AtomicBoolean; 215import java.util.concurrent.atomic.AtomicLong; 216 217import dalvik.system.DexFile; 218import dalvik.system.VMRuntime; 219 220import libcore.io.IoUtils; 221import libcore.util.EmptyArray; 222 223/** 224 * Keep track of all those .apks everywhere. 225 * 226 * This is very central to the platform's security; please run the unit 227 * tests whenever making modifications here: 228 * 229mmm frameworks/base/tests/AndroidTests 230adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 231adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 232 * 233 * {@hide} 234 */ 235public class PackageManagerService extends IPackageManager.Stub { 236 static final String TAG = "PackageManager"; 237 static final boolean DEBUG_SETTINGS = false; 238 static final boolean DEBUG_PREFERRED = false; 239 static final boolean DEBUG_UPGRADE = false; 240 private static final boolean DEBUG_INSTALL = false; 241 private static final boolean DEBUG_REMOVE = false; 242 private static final boolean DEBUG_BROADCASTS = false; 243 private static final boolean DEBUG_SHOW_INFO = false; 244 private static final boolean DEBUG_PACKAGE_INFO = false; 245 private static final boolean DEBUG_INTENT_MATCHING = false; 246 private static final boolean DEBUG_PACKAGE_SCANNING = false; 247 private static final boolean DEBUG_VERIFY = false; 248 private static final boolean DEBUG_DEXOPT = false; 249 private static final boolean DEBUG_ABI_SELECTION = false; 250 251 private static final boolean RUNTIME_PERMISSIONS_ENABLED = 252 SystemProperties.getInt("ro.runtime.premissions.enabled", 0) == 1; 253 254 private static final int RADIO_UID = Process.PHONE_UID; 255 private static final int LOG_UID = Process.LOG_UID; 256 private static final int NFC_UID = Process.NFC_UID; 257 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 258 private static final int SHELL_UID = Process.SHELL_UID; 259 260 // Cap the size of permission trees that 3rd party apps can define 261 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 262 263 // Suffix used during package installation when copying/moving 264 // package apks to install directory. 265 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 266 267 static final int SCAN_NO_DEX = 1<<1; 268 static final int SCAN_FORCE_DEX = 1<<2; 269 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 270 static final int SCAN_NEW_INSTALL = 1<<4; 271 static final int SCAN_NO_PATHS = 1<<5; 272 static final int SCAN_UPDATE_TIME = 1<<6; 273 static final int SCAN_DEFER_DEX = 1<<7; 274 static final int SCAN_BOOTING = 1<<8; 275 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 276 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 277 static final int SCAN_REPLACING = 1<<11; 278 279 static final int REMOVE_CHATTY = 1<<16; 280 281 /** 282 * Timeout (in milliseconds) after which the watchdog should declare that 283 * our handler thread is wedged. The usual default for such things is one 284 * minute but we sometimes do very lengthy I/O operations on this thread, 285 * such as installing multi-gigabyte applications, so ours needs to be longer. 286 */ 287 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 288 289 /** 290 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 291 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 292 * settings entry if available, otherwise we use the hardcoded default. If it's been 293 * more than this long since the last fstrim, we force one during the boot sequence. 294 * 295 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 296 * one gets run at the next available charging+idle time. This final mandatory 297 * no-fstrim check kicks in only of the other scheduling criteria is never met. 298 */ 299 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 300 301 /** 302 * Whether verification is enabled by default. 303 */ 304 private static final boolean DEFAULT_VERIFY_ENABLE = true; 305 306 /** 307 * The default maximum time to wait for the verification agent to return in 308 * milliseconds. 309 */ 310 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 311 312 /** 313 * The default response for package verification timeout. 314 * 315 * This can be either PackageManager.VERIFICATION_ALLOW or 316 * PackageManager.VERIFICATION_REJECT. 317 */ 318 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 319 320 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 321 322 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 323 DEFAULT_CONTAINER_PACKAGE, 324 "com.android.defcontainer.DefaultContainerService"); 325 326 private static final String KILL_APP_REASON_GIDS_CHANGED = 327 "permission grant or revoke changed gids"; 328 329 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 330 "permissions revoked"; 331 332 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 333 334 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 335 336 /** Permission grant: not grant the permission. */ 337 private static final int GRANT_DENIED = 1; 338 339 /** Permission grant: grant the permission as an install permission. */ 340 private static final int GRANT_INSTALL = 2; 341 342 /** Permission grant: grant the permission as a runtime permission. */ 343 private static final int GRANT_RUNTIME = 3; 344 345 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 346 private static final int GRANT_UPGRADE = 4; 347 348 final ServiceThread mHandlerThread; 349 350 final PackageHandler mHandler; 351 352 /** 353 * Messages for {@link #mHandler} that need to wait for system ready before 354 * being dispatched. 355 */ 356 private ArrayList<Message> mPostSystemReadyMessages; 357 358 final int mSdkVersion = Build.VERSION.SDK_INT; 359 360 final Context mContext; 361 final boolean mFactoryTest; 362 final boolean mOnlyCore; 363 final boolean mLazyDexOpt; 364 final long mDexOptLRUThresholdInMills; 365 final DisplayMetrics mMetrics; 366 final int mDefParseFlags; 367 final String[] mSeparateProcesses; 368 final boolean mIsUpgrade; 369 370 // This is where all application persistent data goes. 371 final File mAppDataDir; 372 373 // This is where all application persistent data goes for secondary users. 374 final File mUserAppDataDir; 375 376 /** The location for ASEC container files on internal storage. */ 377 final String mAsecInternalPath; 378 379 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 380 // LOCK HELD. Can be called with mInstallLock held. 381 final Installer mInstaller; 382 383 /** Directory where installed third-party apps stored */ 384 final File mAppInstallDir; 385 386 /** 387 * Directory to which applications installed internally have their 388 * 32 bit native libraries copied. 389 */ 390 private File mAppLib32InstallDir; 391 392 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 393 // apps. 394 final File mDrmAppPrivateInstallDir; 395 396 // ---------------------------------------------------------------- 397 398 // Lock for state used when installing and doing other long running 399 // operations. Methods that must be called with this lock held have 400 // the suffix "LI". 401 final Object mInstallLock = new Object(); 402 403 // ---------------------------------------------------------------- 404 405 // Keys are String (package name), values are Package. This also serves 406 // as the lock for the global state. Methods that must be called with 407 // this lock held have the prefix "LP". 408 final ArrayMap<String, PackageParser.Package> mPackages = 409 new ArrayMap<String, PackageParser.Package>(); 410 411 // Tracks available target package names -> overlay package paths. 412 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 413 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 414 415 final Settings mSettings; 416 boolean mRestoredSettings; 417 418 // System configuration read by SystemConfig. 419 final int[] mGlobalGids; 420 final SparseArray<ArraySet<String>> mSystemPermissions; 421 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 422 423 // If mac_permissions.xml was found for seinfo labeling. 424 boolean mFoundPolicyFile; 425 426 // If a recursive restorecon of /data/data/<pkg> is needed. 427 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 428 429 public static final class SharedLibraryEntry { 430 public final String path; 431 public final String apk; 432 433 SharedLibraryEntry(String _path, String _apk) { 434 path = _path; 435 apk = _apk; 436 } 437 } 438 439 // Currently known shared libraries. 440 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 441 new ArrayMap<String, SharedLibraryEntry>(); 442 443 // All available activities, for your resolving pleasure. 444 final ActivityIntentResolver mActivities = 445 new ActivityIntentResolver(); 446 447 // All available receivers, for your resolving pleasure. 448 final ActivityIntentResolver mReceivers = 449 new ActivityIntentResolver(); 450 451 // All available services, for your resolving pleasure. 452 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 453 454 // All available providers, for your resolving pleasure. 455 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 456 457 // Mapping from provider base names (first directory in content URI codePath) 458 // to the provider information. 459 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 460 new ArrayMap<String, PackageParser.Provider>(); 461 462 // Mapping from instrumentation class names to info about them. 463 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 464 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 465 466 // Mapping from permission names to info about them. 467 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 468 new ArrayMap<String, PackageParser.PermissionGroup>(); 469 470 // Packages whose data we have transfered into another package, thus 471 // should no longer exist. 472 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 473 474 // Broadcast actions that are only available to the system. 475 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 476 477 /** List of packages waiting for verification. */ 478 final SparseArray<PackageVerificationState> mPendingVerification 479 = new SparseArray<PackageVerificationState>(); 480 481 /** Set of packages associated with each app op permission. */ 482 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 483 484 final PackageInstallerService mInstallerService; 485 486 private final PackageDexOptimizer mPackageDexOptimizer; 487 // Cache of users who need badging. 488 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 489 490 /** Token for keys in mPendingVerification. */ 491 private int mPendingVerificationToken = 0; 492 493 volatile boolean mSystemReady; 494 volatile boolean mSafeMode; 495 volatile boolean mHasSystemUidErrors; 496 497 ApplicationInfo mAndroidApplication; 498 final ActivityInfo mResolveActivity = new ActivityInfo(); 499 final ResolveInfo mResolveInfo = new ResolveInfo(); 500 ComponentName mResolveComponentName; 501 PackageParser.Package mPlatformPackage; 502 ComponentName mCustomResolverComponentName; 503 504 boolean mResolverReplaced = false; 505 506 // Set of pending broadcasts for aggregating enable/disable of components. 507 static class PendingPackageBroadcasts { 508 // for each user id, a map of <package name -> components within that package> 509 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 510 511 public PendingPackageBroadcasts() { 512 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 513 } 514 515 public ArrayList<String> get(int userId, String packageName) { 516 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 517 return packages.get(packageName); 518 } 519 520 public void put(int userId, String packageName, ArrayList<String> components) { 521 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 522 packages.put(packageName, components); 523 } 524 525 public void remove(int userId, String packageName) { 526 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 527 if (packages != null) { 528 packages.remove(packageName); 529 } 530 } 531 532 public void remove(int userId) { 533 mUidMap.remove(userId); 534 } 535 536 public int userIdCount() { 537 return mUidMap.size(); 538 } 539 540 public int userIdAt(int n) { 541 return mUidMap.keyAt(n); 542 } 543 544 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 545 return mUidMap.get(userId); 546 } 547 548 public int size() { 549 // total number of pending broadcast entries across all userIds 550 int num = 0; 551 for (int i = 0; i< mUidMap.size(); i++) { 552 num += mUidMap.valueAt(i).size(); 553 } 554 return num; 555 } 556 557 public void clear() { 558 mUidMap.clear(); 559 } 560 561 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 562 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 563 if (map == null) { 564 map = new ArrayMap<String, ArrayList<String>>(); 565 mUidMap.put(userId, map); 566 } 567 return map; 568 } 569 } 570 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 571 572 // Service Connection to remote media container service to copy 573 // package uri's from external media onto secure containers 574 // or internal storage. 575 private IMediaContainerService mContainerService = null; 576 577 static final int SEND_PENDING_BROADCAST = 1; 578 static final int MCS_BOUND = 3; 579 static final int END_COPY = 4; 580 static final int INIT_COPY = 5; 581 static final int MCS_UNBIND = 6; 582 static final int START_CLEANING_PACKAGE = 7; 583 static final int FIND_INSTALL_LOC = 8; 584 static final int POST_INSTALL = 9; 585 static final int MCS_RECONNECT = 10; 586 static final int MCS_GIVE_UP = 11; 587 static final int UPDATED_MEDIA_STATUS = 12; 588 static final int WRITE_SETTINGS = 13; 589 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 590 static final int PACKAGE_VERIFIED = 15; 591 static final int CHECK_PENDING_VERIFICATION = 16; 592 593 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 594 595 // Delay time in millisecs 596 static final int BROADCAST_DELAY = 10 * 1000; 597 598 static UserManagerService sUserManager; 599 600 // Stores a list of users whose package restrictions file needs to be updated 601 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 602 603 final private DefaultContainerConnection mDefContainerConn = 604 new DefaultContainerConnection(); 605 class DefaultContainerConnection implements ServiceConnection { 606 public void onServiceConnected(ComponentName name, IBinder service) { 607 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 608 IMediaContainerService imcs = 609 IMediaContainerService.Stub.asInterface(service); 610 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 611 } 612 613 public void onServiceDisconnected(ComponentName name) { 614 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 615 } 616 }; 617 618 // Recordkeeping of restore-after-install operations that are currently in flight 619 // between the Package Manager and the Backup Manager 620 class PostInstallData { 621 public InstallArgs args; 622 public PackageInstalledInfo res; 623 624 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 625 args = _a; 626 res = _r; 627 } 628 }; 629 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 630 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 631 632 private final String mRequiredVerifierPackage; 633 634 private final PackageUsage mPackageUsage = new PackageUsage(); 635 636 private class PackageUsage { 637 private static final int WRITE_INTERVAL 638 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 639 640 private final Object mFileLock = new Object(); 641 private final AtomicLong mLastWritten = new AtomicLong(0); 642 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 643 644 private boolean mIsHistoricalPackageUsageAvailable = true; 645 646 boolean isHistoricalPackageUsageAvailable() { 647 return mIsHistoricalPackageUsageAvailable; 648 } 649 650 void write(boolean force) { 651 if (force) { 652 writeInternal(); 653 return; 654 } 655 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 656 && !DEBUG_DEXOPT) { 657 return; 658 } 659 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 660 new Thread("PackageUsage_DiskWriter") { 661 @Override 662 public void run() { 663 try { 664 writeInternal(); 665 } finally { 666 mBackgroundWriteRunning.set(false); 667 } 668 } 669 }.start(); 670 } 671 } 672 673 private void writeInternal() { 674 synchronized (mPackages) { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 FileOutputStream f = null; 678 try { 679 f = file.startWrite(); 680 BufferedOutputStream out = new BufferedOutputStream(f); 681 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 682 StringBuilder sb = new StringBuilder(); 683 for (PackageParser.Package pkg : mPackages.values()) { 684 if (pkg.mLastPackageUsageTimeInMills == 0) { 685 continue; 686 } 687 sb.setLength(0); 688 sb.append(pkg.packageName); 689 sb.append(' '); 690 sb.append((long)pkg.mLastPackageUsageTimeInMills); 691 sb.append('\n'); 692 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 693 } 694 out.flush(); 695 file.finishWrite(f); 696 } catch (IOException e) { 697 if (f != null) { 698 file.failWrite(f); 699 } 700 Log.e(TAG, "Failed to write package usage times", e); 701 } 702 } 703 } 704 mLastWritten.set(SystemClock.elapsedRealtime()); 705 } 706 707 void readLP() { 708 synchronized (mFileLock) { 709 AtomicFile file = getFile(); 710 BufferedInputStream in = null; 711 try { 712 in = new BufferedInputStream(file.openRead()); 713 StringBuffer sb = new StringBuffer(); 714 while (true) { 715 String packageName = readToken(in, sb, ' '); 716 if (packageName == null) { 717 break; 718 } 719 String timeInMillisString = readToken(in, sb, '\n'); 720 if (timeInMillisString == null) { 721 throw new IOException("Failed to find last usage time for package " 722 + packageName); 723 } 724 PackageParser.Package pkg = mPackages.get(packageName); 725 if (pkg == null) { 726 continue; 727 } 728 long timeInMillis; 729 try { 730 timeInMillis = Long.parseLong(timeInMillisString.toString()); 731 } catch (NumberFormatException e) { 732 throw new IOException("Failed to parse " + timeInMillisString 733 + " as a long.", e); 734 } 735 pkg.mLastPackageUsageTimeInMills = timeInMillis; 736 } 737 } catch (FileNotFoundException expected) { 738 mIsHistoricalPackageUsageAvailable = false; 739 } catch (IOException e) { 740 Log.w(TAG, "Failed to read package usage times", e); 741 } finally { 742 IoUtils.closeQuietly(in); 743 } 744 } 745 mLastWritten.set(SystemClock.elapsedRealtime()); 746 } 747 748 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 749 throws IOException { 750 sb.setLength(0); 751 while (true) { 752 int ch = in.read(); 753 if (ch == -1) { 754 if (sb.length() == 0) { 755 return null; 756 } 757 throw new IOException("Unexpected EOF"); 758 } 759 if (ch == endOfToken) { 760 return sb.toString(); 761 } 762 sb.append((char)ch); 763 } 764 } 765 766 private AtomicFile getFile() { 767 File dataDir = Environment.getDataDirectory(); 768 File systemDir = new File(dataDir, "system"); 769 File fname = new File(systemDir, "package-usage.list"); 770 return new AtomicFile(fname); 771 } 772 } 773 774 class PackageHandler extends Handler { 775 private boolean mBound = false; 776 final ArrayList<HandlerParams> mPendingInstalls = 777 new ArrayList<HandlerParams>(); 778 779 private boolean connectToService() { 780 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 781 " DefaultContainerService"); 782 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 783 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 784 if (mContext.bindServiceAsUser(service, mDefContainerConn, 785 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 786 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 787 mBound = true; 788 return true; 789 } 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 return false; 792 } 793 794 private void disconnectService() { 795 mContainerService = null; 796 mBound = false; 797 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 798 mContext.unbindService(mDefContainerConn); 799 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 800 } 801 802 PackageHandler(Looper looper) { 803 super(looper); 804 } 805 806 public void handleMessage(Message msg) { 807 try { 808 doHandleMessage(msg); 809 } finally { 810 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 811 } 812 } 813 814 void doHandleMessage(Message msg) { 815 switch (msg.what) { 816 case INIT_COPY: { 817 HandlerParams params = (HandlerParams) msg.obj; 818 int idx = mPendingInstalls.size(); 819 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 820 // If a bind was already initiated we dont really 821 // need to do anything. The pending install 822 // will be processed later on. 823 if (!mBound) { 824 // If this is the only one pending we might 825 // have to bind to the service again. 826 if (!connectToService()) { 827 Slog.e(TAG, "Failed to bind to media container service"); 828 params.serviceError(); 829 return; 830 } else { 831 // Once we bind to the service, the first 832 // pending request will be processed. 833 mPendingInstalls.add(idx, params); 834 } 835 } else { 836 mPendingInstalls.add(idx, params); 837 // Already bound to the service. Just make 838 // sure we trigger off processing the first request. 839 if (idx == 0) { 840 mHandler.sendEmptyMessage(MCS_BOUND); 841 } 842 } 843 break; 844 } 845 case MCS_BOUND: { 846 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 847 if (msg.obj != null) { 848 mContainerService = (IMediaContainerService) msg.obj; 849 } 850 if (mContainerService == null) { 851 // Something seriously wrong. Bail out 852 Slog.e(TAG, "Cannot bind to media container service"); 853 for (HandlerParams params : mPendingInstalls) { 854 // Indicate service bind error 855 params.serviceError(); 856 } 857 mPendingInstalls.clear(); 858 } else if (mPendingInstalls.size() > 0) { 859 HandlerParams params = mPendingInstalls.get(0); 860 if (params != null) { 861 if (params.startCopy()) { 862 // We are done... look for more work or to 863 // go idle. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Checking for more work or unbind..."); 866 // Delete pending install 867 if (mPendingInstalls.size() > 0) { 868 mPendingInstalls.remove(0); 869 } 870 if (mPendingInstalls.size() == 0) { 871 if (mBound) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, 873 "Posting delayed MCS_UNBIND"); 874 removeMessages(MCS_UNBIND); 875 Message ubmsg = obtainMessage(MCS_UNBIND); 876 // Unbind after a little delay, to avoid 877 // continual thrashing. 878 sendMessageDelayed(ubmsg, 10000); 879 } 880 } else { 881 // There are more pending requests in queue. 882 // Just post MCS_BOUND message to trigger processing 883 // of next pending install. 884 if (DEBUG_SD_INSTALL) Log.i(TAG, 885 "Posting MCS_BOUND for next work"); 886 mHandler.sendEmptyMessage(MCS_BOUND); 887 } 888 } 889 } 890 } else { 891 // Should never happen ideally. 892 Slog.w(TAG, "Empty queue"); 893 } 894 break; 895 } 896 case MCS_RECONNECT: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 898 if (mPendingInstalls.size() > 0) { 899 if (mBound) { 900 disconnectService(); 901 } 902 if (!connectToService()) { 903 Slog.e(TAG, "Failed to bind to media container service"); 904 for (HandlerParams params : mPendingInstalls) { 905 // Indicate service bind error 906 params.serviceError(); 907 } 908 mPendingInstalls.clear(); 909 } 910 } 911 break; 912 } 913 case MCS_UNBIND: { 914 // If there is no actual work left, then time to unbind. 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 916 917 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 918 if (mBound) { 919 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 920 921 disconnectService(); 922 } 923 } else if (mPendingInstalls.size() > 0) { 924 // There are more pending requests in queue. 925 // Just post MCS_BOUND message to trigger processing 926 // of next pending install. 927 mHandler.sendEmptyMessage(MCS_BOUND); 928 } 929 930 break; 931 } 932 case MCS_GIVE_UP: { 933 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 934 mPendingInstalls.remove(0); 935 break; 936 } 937 case SEND_PENDING_BROADCAST: { 938 String packages[]; 939 ArrayList<String> components[]; 940 int size = 0; 941 int uids[]; 942 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 943 synchronized (mPackages) { 944 if (mPendingBroadcasts == null) { 945 return; 946 } 947 size = mPendingBroadcasts.size(); 948 if (size <= 0) { 949 // Nothing to be done. Just return 950 return; 951 } 952 packages = new String[size]; 953 components = new ArrayList[size]; 954 uids = new int[size]; 955 int i = 0; // filling out the above arrays 956 957 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 958 int packageUserId = mPendingBroadcasts.userIdAt(n); 959 Iterator<Map.Entry<String, ArrayList<String>>> it 960 = mPendingBroadcasts.packagesForUserId(packageUserId) 961 .entrySet().iterator(); 962 while (it.hasNext() && i < size) { 963 Map.Entry<String, ArrayList<String>> ent = it.next(); 964 packages[i] = ent.getKey(); 965 components[i] = ent.getValue(); 966 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 967 uids[i] = (ps != null) 968 ? UserHandle.getUid(packageUserId, ps.appId) 969 : -1; 970 i++; 971 } 972 } 973 size = i; 974 mPendingBroadcasts.clear(); 975 } 976 // Send broadcasts 977 for (int i = 0; i < size; i++) { 978 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 break; 982 } 983 case START_CLEANING_PACKAGE: { 984 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 985 final String packageName = (String)msg.obj; 986 final int userId = msg.arg1; 987 final boolean andCode = msg.arg2 != 0; 988 synchronized (mPackages) { 989 if (userId == UserHandle.USER_ALL) { 990 int[] users = sUserManager.getUserIds(); 991 for (int user : users) { 992 mSettings.addPackageToCleanLPw( 993 new PackageCleanItem(user, packageName, andCode)); 994 } 995 } else { 996 mSettings.addPackageToCleanLPw( 997 new PackageCleanItem(userId, packageName, andCode)); 998 } 999 } 1000 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1001 startCleaningPackages(); 1002 } break; 1003 case POST_INSTALL: { 1004 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1005 PostInstallData data = mRunningInstalls.get(msg.arg1); 1006 mRunningInstalls.delete(msg.arg1); 1007 boolean deleteOld = false; 1008 1009 if (data != null) { 1010 InstallArgs args = data.args; 1011 PackageInstalledInfo res = data.res; 1012 1013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1014 res.removedInfo.sendBroadcast(false, true, false); 1015 Bundle extras = new Bundle(1); 1016 extras.putInt(Intent.EXTRA_UID, res.uid); 1017 1018 // Now that we successfully installed the package, grant runtime 1019 // permissions if requested before broadcasting the install. 1020 if ((args.installFlags 1021 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1022 grantRequestedRuntimePermissions(res.pkg, 1023 args.user.getIdentifier()); 1024 } 1025 1026 // Determine the set of users who are adding this 1027 // package for the first time vs. those who are seeing 1028 // an update. 1029 int[] firstUsers; 1030 int[] updateUsers = new int[0]; 1031 if (res.origUsers == null || res.origUsers.length == 0) { 1032 firstUsers = res.newUsers; 1033 } else { 1034 firstUsers = new int[0]; 1035 for (int i=0; i<res.newUsers.length; i++) { 1036 int user = res.newUsers[i]; 1037 boolean isNew = true; 1038 for (int j=0; j<res.origUsers.length; j++) { 1039 if (res.origUsers[j] == user) { 1040 isNew = false; 1041 break; 1042 } 1043 } 1044 if (isNew) { 1045 int[] newFirst = new int[firstUsers.length+1]; 1046 System.arraycopy(firstUsers, 0, newFirst, 0, 1047 firstUsers.length); 1048 newFirst[firstUsers.length] = user; 1049 firstUsers = newFirst; 1050 } else { 1051 int[] newUpdate = new int[updateUsers.length+1]; 1052 System.arraycopy(updateUsers, 0, newUpdate, 0, 1053 updateUsers.length); 1054 newUpdate[updateUsers.length] = user; 1055 updateUsers = newUpdate; 1056 } 1057 } 1058 } 1059 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1060 res.pkg.applicationInfo.packageName, 1061 extras, null, null, firstUsers); 1062 final boolean update = res.removedInfo.removedPackage != null; 1063 if (update) { 1064 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1065 } 1066 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1067 res.pkg.applicationInfo.packageName, 1068 extras, null, null, updateUsers); 1069 if (update) { 1070 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1071 res.pkg.applicationInfo.packageName, 1072 extras, null, null, updateUsers); 1073 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1074 null, null, 1075 res.pkg.applicationInfo.packageName, null, updateUsers); 1076 1077 // treat asec-hosted packages like removable media on upgrade 1078 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1079 if (DEBUG_INSTALL) { 1080 Slog.i(TAG, "upgrading pkg " + res.pkg 1081 + " is ASEC-hosted -> AVAILABLE"); 1082 } 1083 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1084 ArrayList<String> pkgList = new ArrayList<String>(1); 1085 pkgList.add(res.pkg.applicationInfo.packageName); 1086 sendResourcesChangedBroadcast(true, true, 1087 pkgList,uidArray, null); 1088 } 1089 } 1090 if (res.removedInfo.args != null) { 1091 // Remove the replaced package's older resources safely now 1092 deleteOld = true; 1093 } 1094 1095 // Log current value of "unknown sources" setting 1096 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1097 getUnknownSourcesSettings()); 1098 } 1099 // Force a gc to clear up things 1100 Runtime.getRuntime().gc(); 1101 // We delete after a gc for applications on sdcard. 1102 if (deleteOld) { 1103 synchronized (mInstallLock) { 1104 res.removedInfo.args.doPostDeleteLI(true); 1105 } 1106 } 1107 if (args.observer != null) { 1108 try { 1109 Bundle extras = extrasForInstallResult(res); 1110 args.observer.onPackageInstalled(res.name, res.returnCode, 1111 res.returnMsg, extras); 1112 } catch (RemoteException e) { 1113 Slog.i(TAG, "Observer no longer exists."); 1114 } 1115 } 1116 } else { 1117 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1118 } 1119 } break; 1120 case UPDATED_MEDIA_STATUS: { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1122 boolean reportStatus = msg.arg1 == 1; 1123 boolean doGc = msg.arg2 == 1; 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1125 if (doGc) { 1126 // Force a gc to clear up stale containers. 1127 Runtime.getRuntime().gc(); 1128 } 1129 if (msg.obj != null) { 1130 @SuppressWarnings("unchecked") 1131 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1132 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1133 // Unload containers 1134 unloadAllContainers(args); 1135 } 1136 if (reportStatus) { 1137 try { 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1139 PackageHelper.getMountService().finishMediaUpdate(); 1140 } catch (RemoteException e) { 1141 Log.e(TAG, "MountService not running?"); 1142 } 1143 } 1144 } break; 1145 case WRITE_SETTINGS: { 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1147 synchronized (mPackages) { 1148 removeMessages(WRITE_SETTINGS); 1149 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1150 mSettings.writeLPr(); 1151 mDirtyUsers.clear(); 1152 } 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1154 } break; 1155 case WRITE_PACKAGE_RESTRICTIONS: { 1156 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1157 synchronized (mPackages) { 1158 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1159 for (int userId : mDirtyUsers) { 1160 mSettings.writePackageRestrictionsLPr(userId); 1161 } 1162 mDirtyUsers.clear(); 1163 } 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1165 } break; 1166 case CHECK_PENDING_VERIFICATION: { 1167 final int verificationId = msg.arg1; 1168 final PackageVerificationState state = mPendingVerification.get(verificationId); 1169 1170 if ((state != null) && !state.timeoutExtended()) { 1171 final InstallArgs args = state.getInstallArgs(); 1172 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1173 1174 Slog.i(TAG, "Verification timed out for " + originUri); 1175 mPendingVerification.remove(verificationId); 1176 1177 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1178 1179 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1180 Slog.i(TAG, "Continuing with installation of " + originUri); 1181 state.setVerifierResponse(Binder.getCallingUid(), 1182 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1183 broadcastPackageVerified(verificationId, originUri, 1184 PackageManager.VERIFICATION_ALLOW, 1185 state.getInstallArgs().getUser()); 1186 try { 1187 ret = args.copyApk(mContainerService, true); 1188 } catch (RemoteException e) { 1189 Slog.e(TAG, "Could not contact the ContainerService"); 1190 } 1191 } else { 1192 broadcastPackageVerified(verificationId, originUri, 1193 PackageManager.VERIFICATION_REJECT, 1194 state.getInstallArgs().getUser()); 1195 } 1196 1197 processPendingInstall(args, ret); 1198 mHandler.sendEmptyMessage(MCS_UNBIND); 1199 } 1200 break; 1201 } 1202 case PACKAGE_VERIFIED: { 1203 final int verificationId = msg.arg1; 1204 1205 final PackageVerificationState state = mPendingVerification.get(verificationId); 1206 if (state == null) { 1207 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1208 break; 1209 } 1210 1211 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1212 1213 state.setVerifierResponse(response.callerUid, response.code); 1214 1215 if (state.isVerificationComplete()) { 1216 mPendingVerification.remove(verificationId); 1217 1218 final InstallArgs args = state.getInstallArgs(); 1219 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1220 1221 int ret; 1222 if (state.isInstallAllowed()) { 1223 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1224 broadcastPackageVerified(verificationId, originUri, 1225 response.code, state.getInstallArgs().getUser()); 1226 try { 1227 ret = args.copyApk(mContainerService, true); 1228 } catch (RemoteException e) { 1229 Slog.e(TAG, "Could not contact the ContainerService"); 1230 } 1231 } else { 1232 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1233 } 1234 1235 processPendingInstall(args, ret); 1236 1237 mHandler.sendEmptyMessage(MCS_UNBIND); 1238 } 1239 1240 break; 1241 } 1242 } 1243 } 1244 } 1245 1246 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1247 if (userId >= UserHandle.USER_OWNER) { 1248 grantRequestedRuntimePermissionsForUser(pkg, userId); 1249 } else if (userId == UserHandle.USER_ALL) { 1250 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1251 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1252 } 1253 } 1254 } 1255 1256 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1257 SettingBase sb = (SettingBase) pkg.mExtras; 1258 if (sb == null) { 1259 return; 1260 } 1261 1262 PermissionsState permissionsState = sb.getPermissionsState(); 1263 1264 for (String permission : pkg.requestedPermissions) { 1265 BasePermission bp = mSettings.mPermissions.get(permission); 1266 if (bp != null && bp.isRuntime()) { 1267 permissionsState.grantRuntimePermission(bp, userId); 1268 } 1269 } 1270 } 1271 1272 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1273 Bundle extras = null; 1274 switch (res.returnCode) { 1275 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1276 extras = new Bundle(); 1277 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1278 res.origPermission); 1279 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1280 res.origPackage); 1281 break; 1282 } 1283 } 1284 return extras; 1285 } 1286 1287 void scheduleWriteSettingsLocked() { 1288 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1289 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1290 } 1291 } 1292 1293 void scheduleWritePackageRestrictionsLocked(int userId) { 1294 if (!sUserManager.exists(userId)) return; 1295 mDirtyUsers.add(userId); 1296 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1297 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1298 } 1299 } 1300 1301 public static PackageManagerService main(Context context, Installer installer, 1302 boolean factoryTest, boolean onlyCore) { 1303 PackageManagerService m = new PackageManagerService(context, installer, 1304 factoryTest, onlyCore); 1305 ServiceManager.addService("package", m); 1306 return m; 1307 } 1308 1309 static String[] splitString(String str, char sep) { 1310 int count = 1; 1311 int i = 0; 1312 while ((i=str.indexOf(sep, i)) >= 0) { 1313 count++; 1314 i++; 1315 } 1316 1317 String[] res = new String[count]; 1318 i=0; 1319 count = 0; 1320 int lastI=0; 1321 while ((i=str.indexOf(sep, i)) >= 0) { 1322 res[count] = str.substring(lastI, i); 1323 count++; 1324 i++; 1325 lastI = i; 1326 } 1327 res[count] = str.substring(lastI, str.length()); 1328 return res; 1329 } 1330 1331 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1332 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1333 Context.DISPLAY_SERVICE); 1334 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1335 } 1336 1337 public PackageManagerService(Context context, Installer installer, 1338 boolean factoryTest, boolean onlyCore) { 1339 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1340 SystemClock.uptimeMillis()); 1341 1342 if (mSdkVersion <= 0) { 1343 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1344 } 1345 1346 mContext = context; 1347 mFactoryTest = factoryTest; 1348 mOnlyCore = onlyCore; 1349 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1350 mMetrics = new DisplayMetrics(); 1351 mSettings = new Settings(mContext, mPackages); 1352 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1353 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1354 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1355 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1356 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1357 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1358 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1359 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1360 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1361 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1362 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1363 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1364 1365 // TODO: add a property to control this? 1366 long dexOptLRUThresholdInMinutes; 1367 if (mLazyDexOpt) { 1368 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1369 } else { 1370 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1371 } 1372 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1373 1374 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1375 if (separateProcesses != null && separateProcesses.length() > 0) { 1376 if ("*".equals(separateProcesses)) { 1377 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1378 mSeparateProcesses = null; 1379 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1380 } else { 1381 mDefParseFlags = 0; 1382 mSeparateProcesses = separateProcesses.split(","); 1383 Slog.w(TAG, "Running with debug.separate_processes: " 1384 + separateProcesses); 1385 } 1386 } else { 1387 mDefParseFlags = 0; 1388 mSeparateProcesses = null; 1389 } 1390 1391 mInstaller = installer; 1392 mPackageDexOptimizer = new PackageDexOptimizer(this); 1393 1394 getDefaultDisplayMetrics(context, mMetrics); 1395 1396 SystemConfig systemConfig = SystemConfig.getInstance(); 1397 mGlobalGids = systemConfig.getGlobalGids(); 1398 mSystemPermissions = systemConfig.getSystemPermissions(); 1399 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1400 1401 synchronized (mInstallLock) { 1402 // writer 1403 synchronized (mPackages) { 1404 mHandlerThread = new ServiceThread(TAG, 1405 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1406 mHandlerThread.start(); 1407 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1408 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1409 1410 File dataDir = Environment.getDataDirectory(); 1411 mAppDataDir = new File(dataDir, "data"); 1412 mAppInstallDir = new File(dataDir, "app"); 1413 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1414 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1415 mUserAppDataDir = new File(dataDir, "user"); 1416 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1417 1418 sUserManager = new UserManagerService(context, this, 1419 mInstallLock, mPackages); 1420 1421 // Propagate permission configuration in to package manager. 1422 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1423 = systemConfig.getPermissions(); 1424 for (int i=0; i<permConfig.size(); i++) { 1425 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1426 BasePermission bp = mSettings.mPermissions.get(perm.name); 1427 if (bp == null) { 1428 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1429 mSettings.mPermissions.put(perm.name, bp); 1430 } 1431 if (perm.gids != null) { 1432 bp.setGids(perm.gids, perm.perUser); 1433 } 1434 } 1435 1436 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1437 for (int i=0; i<libConfig.size(); i++) { 1438 mSharedLibraries.put(libConfig.keyAt(i), 1439 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1440 } 1441 1442 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1443 1444 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1445 mSdkVersion, mOnlyCore); 1446 1447 String customResolverActivity = Resources.getSystem().getString( 1448 R.string.config_customResolverActivity); 1449 if (TextUtils.isEmpty(customResolverActivity)) { 1450 customResolverActivity = null; 1451 } else { 1452 mCustomResolverComponentName = ComponentName.unflattenFromString( 1453 customResolverActivity); 1454 } 1455 1456 long startTime = SystemClock.uptimeMillis(); 1457 1458 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1459 startTime); 1460 1461 // Set flag to monitor and not change apk file paths when 1462 // scanning install directories. 1463 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1464 1465 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1466 1467 /** 1468 * Add everything in the in the boot class path to the 1469 * list of process files because dexopt will have been run 1470 * if necessary during zygote startup. 1471 */ 1472 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1473 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1474 1475 if (bootClassPath != null) { 1476 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1477 for (String element : bootClassPathElements) { 1478 alreadyDexOpted.add(element); 1479 } 1480 } else { 1481 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1482 } 1483 1484 if (systemServerClassPath != null) { 1485 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1486 for (String element : systemServerClassPathElements) { 1487 alreadyDexOpted.add(element); 1488 } 1489 } else { 1490 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1491 } 1492 1493 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1494 final String[] dexCodeInstructionSets = 1495 getDexCodeInstructionSets( 1496 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1497 1498 /** 1499 * Ensure all external libraries have had dexopt run on them. 1500 */ 1501 if (mSharedLibraries.size() > 0) { 1502 // NOTE: For now, we're compiling these system "shared libraries" 1503 // (and framework jars) into all available architectures. It's possible 1504 // to compile them only when we come across an app that uses them (there's 1505 // already logic for that in scanPackageLI) but that adds some complexity. 1506 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1507 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1508 final String lib = libEntry.path; 1509 if (lib == null) { 1510 continue; 1511 } 1512 1513 try { 1514 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1515 dexCodeInstructionSet, 1516 false); 1517 if (dexoptRequired != DexFile.UP_TO_DATE) { 1518 alreadyDexOpted.add(lib); 1519 1520 // The list of "shared libraries" we have at this point is 1521 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1522 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1523 } else { 1524 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1525 } 1526 } 1527 } catch (FileNotFoundException e) { 1528 Slog.w(TAG, "Library not found: " + lib); 1529 } catch (IOException e) { 1530 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1531 + e.getMessage()); 1532 } 1533 } 1534 } 1535 } 1536 1537 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1538 1539 // Gross hack for now: we know this file doesn't contain any 1540 // code, so don't dexopt it to avoid the resulting log spew. 1541 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1542 1543 // Gross hack for now: we know this file is only part of 1544 // the boot class path for art, so don't dexopt it to 1545 // avoid the resulting log spew. 1546 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1547 1548 /** 1549 * And there are a number of commands implemented in Java, which 1550 * we currently need to do the dexopt on so that they can be 1551 * run from a non-root shell. 1552 */ 1553 String[] frameworkFiles = frameworkDir.list(); 1554 if (frameworkFiles != null) { 1555 // TODO: We could compile these only for the most preferred ABI. We should 1556 // first double check that the dex files for these commands are not referenced 1557 // by other system apps. 1558 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1559 for (int i=0; i<frameworkFiles.length; i++) { 1560 File libPath = new File(frameworkDir, frameworkFiles[i]); 1561 String path = libPath.getPath(); 1562 // Skip the file if we already did it. 1563 if (alreadyDexOpted.contains(path)) { 1564 continue; 1565 } 1566 // Skip the file if it is not a type we want to dexopt. 1567 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1568 continue; 1569 } 1570 try { 1571 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1572 dexCodeInstructionSet, 1573 false); 1574 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1575 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1576 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1577 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1578 } 1579 } catch (FileNotFoundException e) { 1580 Slog.w(TAG, "Jar not found: " + path); 1581 } catch (IOException e) { 1582 Slog.w(TAG, "Exception reading jar: " + path, e); 1583 } 1584 } 1585 } 1586 } 1587 1588 // Collect vendor overlay packages. 1589 // (Do this before scanning any apps.) 1590 // For security and version matching reason, only consider 1591 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1592 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1593 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1594 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1595 1596 // Find base frameworks (resource packages without code). 1597 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1598 | PackageParser.PARSE_IS_SYSTEM_DIR 1599 | PackageParser.PARSE_IS_PRIVILEGED, 1600 scanFlags | SCAN_NO_DEX, 0); 1601 1602 // Collected privileged system packages. 1603 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1604 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1605 | PackageParser.PARSE_IS_SYSTEM_DIR 1606 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1607 1608 // Collect ordinary system packages. 1609 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1610 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1611 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1612 1613 // Collect all vendor packages. 1614 File vendorAppDir = new File("/vendor/app"); 1615 try { 1616 vendorAppDir = vendorAppDir.getCanonicalFile(); 1617 } catch (IOException e) { 1618 // failed to look up canonical path, continue with original one 1619 } 1620 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1621 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1622 1623 // Collect all OEM packages. 1624 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1625 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1626 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1627 1628 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1629 mInstaller.moveFiles(); 1630 1631 // Prune any system packages that no longer exist. 1632 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1633 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1634 if (!mOnlyCore) { 1635 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1636 while (psit.hasNext()) { 1637 PackageSetting ps = psit.next(); 1638 1639 /* 1640 * If this is not a system app, it can't be a 1641 * disable system app. 1642 */ 1643 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1644 continue; 1645 } 1646 1647 /* 1648 * If the package is scanned, it's not erased. 1649 */ 1650 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1651 if (scannedPkg != null) { 1652 /* 1653 * If the system app is both scanned and in the 1654 * disabled packages list, then it must have been 1655 * added via OTA. Remove it from the currently 1656 * scanned package so the previously user-installed 1657 * application can be scanned. 1658 */ 1659 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1660 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1661 + ps.name + "; removing system app. Last known codePath=" 1662 + ps.codePathString + ", installStatus=" + ps.installStatus 1663 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1664 + scannedPkg.mVersionCode); 1665 removePackageLI(ps, true); 1666 expectingBetter.put(ps.name, ps.codePath); 1667 } 1668 1669 continue; 1670 } 1671 1672 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1673 psit.remove(); 1674 logCriticalInfo(Log.WARN, "System package " + ps.name 1675 + " no longer exists; wiping its data"); 1676 removeDataDirsLI(ps.name); 1677 } else { 1678 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1679 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1680 possiblyDeletedUpdatedSystemApps.add(ps.name); 1681 } 1682 } 1683 } 1684 } 1685 1686 //look for any incomplete package installations 1687 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1688 //clean up list 1689 for(int i = 0; i < deletePkgsList.size(); i++) { 1690 //clean up here 1691 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1692 } 1693 //delete tmp files 1694 deleteTempPackageFiles(); 1695 1696 // Remove any shared userIDs that have no associated packages 1697 mSettings.pruneSharedUsersLPw(); 1698 1699 if (!mOnlyCore) { 1700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1701 SystemClock.uptimeMillis()); 1702 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1703 1704 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1705 scanFlags, 0); 1706 1707 /** 1708 * Remove disable package settings for any updated system 1709 * apps that were removed via an OTA. If they're not a 1710 * previously-updated app, remove them completely. 1711 * Otherwise, just revoke their system-level permissions. 1712 */ 1713 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1714 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1715 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1716 1717 String msg; 1718 if (deletedPkg == null) { 1719 msg = "Updated system package " + deletedAppName 1720 + " no longer exists; wiping its data"; 1721 removeDataDirsLI(deletedAppName); 1722 } else { 1723 msg = "Updated system app + " + deletedAppName 1724 + " no longer present; removing system privileges for " 1725 + deletedAppName; 1726 1727 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1728 1729 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1730 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1731 } 1732 logCriticalInfo(Log.WARN, msg); 1733 } 1734 1735 /** 1736 * Make sure all system apps that we expected to appear on 1737 * the userdata partition actually showed up. If they never 1738 * appeared, crawl back and revive the system version. 1739 */ 1740 for (int i = 0; i < expectingBetter.size(); i++) { 1741 final String packageName = expectingBetter.keyAt(i); 1742 if (!mPackages.containsKey(packageName)) { 1743 final File scanFile = expectingBetter.valueAt(i); 1744 1745 logCriticalInfo(Log.WARN, "Expected better " + packageName 1746 + " but never showed up; reverting to system"); 1747 1748 final int reparseFlags; 1749 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1750 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1751 | PackageParser.PARSE_IS_SYSTEM_DIR 1752 | PackageParser.PARSE_IS_PRIVILEGED; 1753 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1754 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1755 | PackageParser.PARSE_IS_SYSTEM_DIR; 1756 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1757 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1758 | PackageParser.PARSE_IS_SYSTEM_DIR; 1759 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1760 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1761 | PackageParser.PARSE_IS_SYSTEM_DIR; 1762 } else { 1763 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1764 continue; 1765 } 1766 1767 mSettings.enableSystemPackageLPw(packageName); 1768 1769 try { 1770 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1771 } catch (PackageManagerException e) { 1772 Slog.e(TAG, "Failed to parse original system package: " 1773 + e.getMessage()); 1774 } 1775 } 1776 } 1777 } 1778 1779 // Now that we know all of the shared libraries, update all clients to have 1780 // the correct library paths. 1781 updateAllSharedLibrariesLPw(); 1782 1783 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1784 // NOTE: We ignore potential failures here during a system scan (like 1785 // the rest of the commands above) because there's precious little we 1786 // can do about it. A settings error is reported, though. 1787 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1788 false /* force dexopt */, false /* defer dexopt */); 1789 } 1790 1791 // Now that we know all the packages we are keeping, 1792 // read and update their last usage times. 1793 mPackageUsage.readLP(); 1794 1795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1796 SystemClock.uptimeMillis()); 1797 Slog.i(TAG, "Time to scan packages: " 1798 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1799 + " seconds"); 1800 1801 // If the platform SDK has changed since the last time we booted, 1802 // we need to re-grant app permission to catch any new ones that 1803 // appear. This is really a hack, and means that apps can in some 1804 // cases get permissions that the user didn't initially explicitly 1805 // allow... it would be nice to have some better way to handle 1806 // this situation. 1807 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1808 != mSdkVersion; 1809 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1810 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1811 + "; regranting permissions for internal storage"); 1812 mSettings.mInternalSdkPlatform = mSdkVersion; 1813 1814 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1815 | (regrantPermissions 1816 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1817 : 0)); 1818 1819 // If this is the first boot, and it is a normal boot, then 1820 // we need to initialize the default preferred apps. 1821 if (!mRestoredSettings && !onlyCore) { 1822 mSettings.readDefaultPreferredAppsLPw(this, 0); 1823 } 1824 1825 // If this is first boot after an OTA, and a normal boot, then 1826 // we need to clear code cache directories. 1827 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1828 if (mIsUpgrade && !onlyCore) { 1829 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1830 for (String pkgName : mSettings.mPackages.keySet()) { 1831 deleteCodeCacheDirsLI(pkgName); 1832 } 1833 mSettings.mFingerprint = Build.FINGERPRINT; 1834 } 1835 1836 // All the changes are done during package scanning. 1837 mSettings.updateInternalDatabaseVersion(); 1838 1839 // can downgrade to reader 1840 mSettings.writeLPr(); 1841 1842 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1843 SystemClock.uptimeMillis()); 1844 1845 1846 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1847 } // synchronized (mPackages) 1848 } // synchronized (mInstallLock) 1849 1850 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1851 1852 // Now after opening every single application zip, make sure they 1853 // are all flushed. Not really needed, but keeps things nice and 1854 // tidy. 1855 Runtime.getRuntime().gc(); 1856 } 1857 1858 @Override 1859 public boolean isFirstBoot() { 1860 return !mRestoredSettings; 1861 } 1862 1863 @Override 1864 public boolean isOnlyCoreApps() { 1865 return mOnlyCore; 1866 } 1867 1868 @Override 1869 public boolean isUpgrade() { 1870 return mIsUpgrade; 1871 } 1872 1873 private String getRequiredVerifierLPr() { 1874 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1875 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1876 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1877 1878 String requiredVerifier = null; 1879 1880 final int N = receivers.size(); 1881 for (int i = 0; i < N; i++) { 1882 final ResolveInfo info = receivers.get(i); 1883 1884 if (info.activityInfo == null) { 1885 continue; 1886 } 1887 1888 final String packageName = info.activityInfo.packageName; 1889 1890 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 1891 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 1892 continue; 1893 } 1894 1895 if (requiredVerifier != null) { 1896 throw new RuntimeException("There can be only one required verifier"); 1897 } 1898 1899 requiredVerifier = packageName; 1900 } 1901 1902 return requiredVerifier; 1903 } 1904 1905 @Override 1906 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1907 throws RemoteException { 1908 try { 1909 return super.onTransact(code, data, reply, flags); 1910 } catch (RuntimeException e) { 1911 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1912 Slog.wtf(TAG, "Package Manager Crash", e); 1913 } 1914 throw e; 1915 } 1916 } 1917 1918 void cleanupInstallFailedPackage(PackageSetting ps) { 1919 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1920 1921 removeDataDirsLI(ps.name); 1922 if (ps.codePath != null) { 1923 if (ps.codePath.isDirectory()) { 1924 FileUtils.deleteContents(ps.codePath); 1925 } 1926 ps.codePath.delete(); 1927 } 1928 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1929 if (ps.resourcePath.isDirectory()) { 1930 FileUtils.deleteContents(ps.resourcePath); 1931 } 1932 ps.resourcePath.delete(); 1933 } 1934 mSettings.removePackageLPw(ps.name); 1935 } 1936 1937 static int[] appendInts(int[] cur, int[] add) { 1938 if (add == null) return cur; 1939 if (cur == null) return add; 1940 final int N = add.length; 1941 for (int i=0; i<N; i++) { 1942 cur = appendInt(cur, add[i]); 1943 } 1944 return cur; 1945 } 1946 1947 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1948 if (!sUserManager.exists(userId)) return null; 1949 final PackageSetting ps = (PackageSetting) p.mExtras; 1950 if (ps == null) { 1951 return null; 1952 } 1953 1954 final PermissionsState permissionsState = ps.getPermissionsState(); 1955 1956 final int[] gids = permissionsState.computeGids(userId); 1957 final Set<String> permissions = permissionsState.getPermissions(userId); 1958 final PackageUserState state = ps.readUserState(userId); 1959 1960 return PackageParser.generatePackageInfo(p, gids, flags, 1961 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 1962 } 1963 1964 @Override 1965 public boolean isPackageAvailable(String packageName, int userId) { 1966 if (!sUserManager.exists(userId)) return false; 1967 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1968 synchronized (mPackages) { 1969 PackageParser.Package p = mPackages.get(packageName); 1970 if (p != null) { 1971 final PackageSetting ps = (PackageSetting) p.mExtras; 1972 if (ps != null) { 1973 final PackageUserState state = ps.readUserState(userId); 1974 if (state != null) { 1975 return PackageParser.isAvailable(state); 1976 } 1977 } 1978 } 1979 } 1980 return false; 1981 } 1982 1983 @Override 1984 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1985 if (!sUserManager.exists(userId)) return null; 1986 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1987 // reader 1988 synchronized (mPackages) { 1989 PackageParser.Package p = mPackages.get(packageName); 1990 if (DEBUG_PACKAGE_INFO) 1991 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1992 if (p != null) { 1993 return generatePackageInfo(p, flags, userId); 1994 } 1995 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1996 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1997 } 1998 } 1999 return null; 2000 } 2001 2002 @Override 2003 public String[] currentToCanonicalPackageNames(String[] names) { 2004 String[] out = new String[names.length]; 2005 // reader 2006 synchronized (mPackages) { 2007 for (int i=names.length-1; i>=0; i--) { 2008 PackageSetting ps = mSettings.mPackages.get(names[i]); 2009 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2010 } 2011 } 2012 return out; 2013 } 2014 2015 @Override 2016 public String[] canonicalToCurrentPackageNames(String[] names) { 2017 String[] out = new String[names.length]; 2018 // reader 2019 synchronized (mPackages) { 2020 for (int i=names.length-1; i>=0; i--) { 2021 String cur = mSettings.mRenamedPackages.get(names[i]); 2022 out[i] = cur != null ? cur : names[i]; 2023 } 2024 } 2025 return out; 2026 } 2027 2028 @Override 2029 public int getPackageUid(String packageName, int userId) { 2030 if (!sUserManager.exists(userId)) return -1; 2031 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2032 2033 // reader 2034 synchronized (mPackages) { 2035 PackageParser.Package p = mPackages.get(packageName); 2036 if(p != null) { 2037 return UserHandle.getUid(userId, p.applicationInfo.uid); 2038 } 2039 PackageSetting ps = mSettings.mPackages.get(packageName); 2040 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2041 return -1; 2042 } 2043 p = ps.pkg; 2044 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2045 } 2046 } 2047 2048 @Override 2049 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2050 if (!sUserManager.exists(userId)) { 2051 return null; 2052 } 2053 2054 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2055 "getPackageGids"); 2056 2057 // reader 2058 synchronized (mPackages) { 2059 PackageParser.Package p = mPackages.get(packageName); 2060 if (DEBUG_PACKAGE_INFO) { 2061 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2062 } 2063 if (p != null) { 2064 PackageSetting ps = (PackageSetting) p.mExtras; 2065 return ps.getPermissionsState().computeGids(userId); 2066 } 2067 } 2068 2069 return null; 2070 } 2071 2072 static PermissionInfo generatePermissionInfo( 2073 BasePermission bp, int flags) { 2074 if (bp.perm != null) { 2075 return PackageParser.generatePermissionInfo(bp.perm, flags); 2076 } 2077 PermissionInfo pi = new PermissionInfo(); 2078 pi.name = bp.name; 2079 pi.packageName = bp.sourcePackage; 2080 pi.nonLocalizedLabel = bp.name; 2081 pi.protectionLevel = bp.protectionLevel; 2082 return pi; 2083 } 2084 2085 @Override 2086 public PermissionInfo getPermissionInfo(String name, int flags) { 2087 // reader 2088 synchronized (mPackages) { 2089 final BasePermission p = mSettings.mPermissions.get(name); 2090 if (p != null) { 2091 return generatePermissionInfo(p, flags); 2092 } 2093 return null; 2094 } 2095 } 2096 2097 @Override 2098 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2099 // reader 2100 synchronized (mPackages) { 2101 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2102 for (BasePermission p : mSettings.mPermissions.values()) { 2103 if (group == null) { 2104 if (p.perm == null || p.perm.info.group == null) { 2105 out.add(generatePermissionInfo(p, flags)); 2106 } 2107 } else { 2108 if (p.perm != null && group.equals(p.perm.info.group)) { 2109 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2110 } 2111 } 2112 } 2113 2114 if (out.size() > 0) { 2115 return out; 2116 } 2117 return mPermissionGroups.containsKey(group) ? out : null; 2118 } 2119 } 2120 2121 @Override 2122 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2123 // reader 2124 synchronized (mPackages) { 2125 return PackageParser.generatePermissionGroupInfo( 2126 mPermissionGroups.get(name), flags); 2127 } 2128 } 2129 2130 @Override 2131 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2132 // reader 2133 synchronized (mPackages) { 2134 final int N = mPermissionGroups.size(); 2135 ArrayList<PermissionGroupInfo> out 2136 = new ArrayList<PermissionGroupInfo>(N); 2137 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2138 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2139 } 2140 return out; 2141 } 2142 } 2143 2144 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2145 int userId) { 2146 if (!sUserManager.exists(userId)) return null; 2147 PackageSetting ps = mSettings.mPackages.get(packageName); 2148 if (ps != null) { 2149 if (ps.pkg == null) { 2150 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2151 flags, userId); 2152 if (pInfo != null) { 2153 return pInfo.applicationInfo; 2154 } 2155 return null; 2156 } 2157 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2158 ps.readUserState(userId), userId); 2159 } 2160 return null; 2161 } 2162 2163 private PackageInfo generatePackageInfoFromSettingsLPw(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 PackageParser.Package pkg = ps.pkg; 2169 if (pkg == null) { 2170 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2171 return null; 2172 } 2173 // Only data remains, so we aren't worried about code paths 2174 pkg = new PackageParser.Package(packageName); 2175 pkg.applicationInfo.packageName = packageName; 2176 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2177 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2178 pkg.applicationInfo.dataDir = 2179 getDataPathForPackage(packageName, 0).getPath(); 2180 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2181 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2182 } 2183 return generatePackageInfo(pkg, flags, userId); 2184 } 2185 return null; 2186 } 2187 2188 @Override 2189 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2190 if (!sUserManager.exists(userId)) return null; 2191 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2192 // writer 2193 synchronized (mPackages) { 2194 PackageParser.Package p = mPackages.get(packageName); 2195 if (DEBUG_PACKAGE_INFO) Log.v( 2196 TAG, "getApplicationInfo " + packageName 2197 + ": " + p); 2198 if (p != null) { 2199 PackageSetting ps = mSettings.mPackages.get(packageName); 2200 if (ps == null) return null; 2201 // Note: isEnabledLP() does not apply here - always return info 2202 return PackageParser.generateApplicationInfo( 2203 p, flags, ps.readUserState(userId), userId); 2204 } 2205 if ("android".equals(packageName)||"system".equals(packageName)) { 2206 return mAndroidApplication; 2207 } 2208 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2209 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2210 } 2211 } 2212 return null; 2213 } 2214 2215 2216 @Override 2217 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2218 mContext.enforceCallingOrSelfPermission( 2219 android.Manifest.permission.CLEAR_APP_CACHE, null); 2220 // Queue up an async operation since clearing cache may take a little while. 2221 mHandler.post(new Runnable() { 2222 public void run() { 2223 mHandler.removeCallbacks(this); 2224 int retCode = -1; 2225 synchronized (mInstallLock) { 2226 retCode = mInstaller.freeCache(freeStorageSize); 2227 if (retCode < 0) { 2228 Slog.w(TAG, "Couldn't clear application caches"); 2229 } 2230 } 2231 if (observer != null) { 2232 try { 2233 observer.onRemoveCompleted(null, (retCode >= 0)); 2234 } catch (RemoteException e) { 2235 Slog.w(TAG, "RemoveException when invoking call back"); 2236 } 2237 } 2238 } 2239 }); 2240 } 2241 2242 @Override 2243 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2244 mContext.enforceCallingOrSelfPermission( 2245 android.Manifest.permission.CLEAR_APP_CACHE, null); 2246 // Queue up an async operation since clearing cache may take a little while. 2247 mHandler.post(new Runnable() { 2248 public void run() { 2249 mHandler.removeCallbacks(this); 2250 int retCode = -1; 2251 synchronized (mInstallLock) { 2252 retCode = mInstaller.freeCache(freeStorageSize); 2253 if (retCode < 0) { 2254 Slog.w(TAG, "Couldn't clear application caches"); 2255 } 2256 } 2257 if(pi != null) { 2258 try { 2259 // Callback via pending intent 2260 int code = (retCode >= 0) ? 1 : 0; 2261 pi.sendIntent(null, code, null, 2262 null, null); 2263 } catch (SendIntentException e1) { 2264 Slog.i(TAG, "Failed to send pending intent"); 2265 } 2266 } 2267 } 2268 }); 2269 } 2270 2271 void freeStorage(long freeStorageSize) throws IOException { 2272 synchronized (mInstallLock) { 2273 if (mInstaller.freeCache(freeStorageSize) < 0) { 2274 throw new IOException("Failed to free enough space"); 2275 } 2276 } 2277 } 2278 2279 @Override 2280 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2281 if (!sUserManager.exists(userId)) return null; 2282 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2283 synchronized (mPackages) { 2284 PackageParser.Activity a = mActivities.mActivities.get(component); 2285 2286 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2287 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2288 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2289 if (ps == null) return null; 2290 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2291 userId); 2292 } 2293 if (mResolveComponentName.equals(component)) { 2294 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2295 new PackageUserState(), userId); 2296 } 2297 } 2298 return null; 2299 } 2300 2301 @Override 2302 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2303 String resolvedType) { 2304 synchronized (mPackages) { 2305 PackageParser.Activity a = mActivities.mActivities.get(component); 2306 if (a == null) { 2307 return false; 2308 } 2309 for (int i=0; i<a.intents.size(); i++) { 2310 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2311 intent.getData(), intent.getCategories(), TAG) >= 0) { 2312 return true; 2313 } 2314 } 2315 return false; 2316 } 2317 } 2318 2319 @Override 2320 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2321 if (!sUserManager.exists(userId)) return null; 2322 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2323 synchronized (mPackages) { 2324 PackageParser.Activity a = mReceivers.mActivities.get(component); 2325 if (DEBUG_PACKAGE_INFO) Log.v( 2326 TAG, "getReceiverInfo " + component + ": " + a); 2327 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2328 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2329 if (ps == null) return null; 2330 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2331 userId); 2332 } 2333 } 2334 return null; 2335 } 2336 2337 @Override 2338 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2339 if (!sUserManager.exists(userId)) return null; 2340 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2341 synchronized (mPackages) { 2342 PackageParser.Service s = mServices.mServices.get(component); 2343 if (DEBUG_PACKAGE_INFO) Log.v( 2344 TAG, "getServiceInfo " + component + ": " + s); 2345 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2346 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2347 if (ps == null) return null; 2348 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2349 userId); 2350 } 2351 } 2352 return null; 2353 } 2354 2355 @Override 2356 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2357 if (!sUserManager.exists(userId)) return null; 2358 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2359 synchronized (mPackages) { 2360 PackageParser.Provider p = mProviders.mProviders.get(component); 2361 if (DEBUG_PACKAGE_INFO) Log.v( 2362 TAG, "getProviderInfo " + component + ": " + p); 2363 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2364 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2365 if (ps == null) return null; 2366 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2367 userId); 2368 } 2369 } 2370 return null; 2371 } 2372 2373 @Override 2374 public String[] getSystemSharedLibraryNames() { 2375 Set<String> libSet; 2376 synchronized (mPackages) { 2377 libSet = mSharedLibraries.keySet(); 2378 int size = libSet.size(); 2379 if (size > 0) { 2380 String[] libs = new String[size]; 2381 libSet.toArray(libs); 2382 return libs; 2383 } 2384 } 2385 return null; 2386 } 2387 2388 /** 2389 * @hide 2390 */ 2391 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2392 synchronized (mPackages) { 2393 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2394 if (lib != null && lib.apk != null) { 2395 return mPackages.get(lib.apk); 2396 } 2397 } 2398 return null; 2399 } 2400 2401 @Override 2402 public FeatureInfo[] getSystemAvailableFeatures() { 2403 Collection<FeatureInfo> featSet; 2404 synchronized (mPackages) { 2405 featSet = mAvailableFeatures.values(); 2406 int size = featSet.size(); 2407 if (size > 0) { 2408 FeatureInfo[] features = new FeatureInfo[size+1]; 2409 featSet.toArray(features); 2410 FeatureInfo fi = new FeatureInfo(); 2411 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2412 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2413 features[size] = fi; 2414 return features; 2415 } 2416 } 2417 return null; 2418 } 2419 2420 @Override 2421 public boolean hasSystemFeature(String name) { 2422 synchronized (mPackages) { 2423 return mAvailableFeatures.containsKey(name); 2424 } 2425 } 2426 2427 private void checkValidCaller(int uid, int userId) { 2428 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2429 return; 2430 2431 throw new SecurityException("Caller uid=" + uid 2432 + " is not privileged to communicate with user=" + userId); 2433 } 2434 2435 @Override 2436 public int checkPermission(String permName, String pkgName, int userId) { 2437 if (!sUserManager.exists(userId)) { 2438 return PackageManager.PERMISSION_DENIED; 2439 } 2440 2441 synchronized (mPackages) { 2442 final PackageParser.Package p = mPackages.get(pkgName); 2443 if (p != null && p.mExtras != null) { 2444 final PackageSetting ps = (PackageSetting) p.mExtras; 2445 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2446 return PackageManager.PERMISSION_GRANTED; 2447 } 2448 } 2449 } 2450 2451 return PackageManager.PERMISSION_DENIED; 2452 } 2453 2454 @Override 2455 public int checkUidPermission(String permName, int uid) { 2456 final int userId = UserHandle.getUserId(uid); 2457 2458 if (!sUserManager.exists(userId)) { 2459 return PackageManager.PERMISSION_DENIED; 2460 } 2461 2462 synchronized (mPackages) { 2463 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2464 if (obj != null) { 2465 final SettingBase ps = (SettingBase) obj; 2466 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2467 return PackageManager.PERMISSION_GRANTED; 2468 } 2469 } else { 2470 ArraySet<String> perms = mSystemPermissions.get(uid); 2471 if (perms != null && perms.contains(permName)) { 2472 return PackageManager.PERMISSION_GRANTED; 2473 } 2474 } 2475 } 2476 2477 return PackageManager.PERMISSION_DENIED; 2478 } 2479 2480 /** 2481 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2482 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2483 * @param checkShell TODO(yamasani): 2484 * @param message the message to log on security exception 2485 */ 2486 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2487 boolean checkShell, String message) { 2488 if (userId < 0) { 2489 throw new IllegalArgumentException("Invalid userId " + userId); 2490 } 2491 if (checkShell) { 2492 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2493 } 2494 if (userId == UserHandle.getUserId(callingUid)) return; 2495 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2496 if (requireFullPermission) { 2497 mContext.enforceCallingOrSelfPermission( 2498 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2499 } else { 2500 try { 2501 mContext.enforceCallingOrSelfPermission( 2502 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2503 } catch (SecurityException se) { 2504 mContext.enforceCallingOrSelfPermission( 2505 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2506 } 2507 } 2508 } 2509 } 2510 2511 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2512 if (callingUid == Process.SHELL_UID) { 2513 if (userHandle >= 0 2514 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2515 throw new SecurityException("Shell does not have permission to access user " 2516 + userHandle); 2517 } else if (userHandle < 0) { 2518 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2519 + Debug.getCallers(3)); 2520 } 2521 } 2522 } 2523 2524 private BasePermission findPermissionTreeLP(String permName) { 2525 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2526 if (permName.startsWith(bp.name) && 2527 permName.length() > bp.name.length() && 2528 permName.charAt(bp.name.length()) == '.') { 2529 return bp; 2530 } 2531 } 2532 return null; 2533 } 2534 2535 private BasePermission checkPermissionTreeLP(String permName) { 2536 if (permName != null) { 2537 BasePermission bp = findPermissionTreeLP(permName); 2538 if (bp != null) { 2539 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2540 return bp; 2541 } 2542 throw new SecurityException("Calling uid " 2543 + Binder.getCallingUid() 2544 + " is not allowed to add to permission tree " 2545 + bp.name + " owned by uid " + bp.uid); 2546 } 2547 } 2548 throw new SecurityException("No permission tree found for " + permName); 2549 } 2550 2551 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2552 if (s1 == null) { 2553 return s2 == null; 2554 } 2555 if (s2 == null) { 2556 return false; 2557 } 2558 if (s1.getClass() != s2.getClass()) { 2559 return false; 2560 } 2561 return s1.equals(s2); 2562 } 2563 2564 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2565 if (pi1.icon != pi2.icon) return false; 2566 if (pi1.logo != pi2.logo) return false; 2567 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2568 if (!compareStrings(pi1.name, pi2.name)) return false; 2569 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2570 // We'll take care of setting this one. 2571 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2572 // These are not currently stored in settings. 2573 //if (!compareStrings(pi1.group, pi2.group)) return false; 2574 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2575 //if (pi1.labelRes != pi2.labelRes) return false; 2576 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2577 return true; 2578 } 2579 2580 int permissionInfoFootprint(PermissionInfo info) { 2581 int size = info.name.length(); 2582 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2583 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2584 return size; 2585 } 2586 2587 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2588 int size = 0; 2589 for (BasePermission perm : mSettings.mPermissions.values()) { 2590 if (perm.uid == tree.uid) { 2591 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2592 } 2593 } 2594 return size; 2595 } 2596 2597 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2598 // We calculate the max size of permissions defined by this uid and throw 2599 // if that plus the size of 'info' would exceed our stated maximum. 2600 if (tree.uid != Process.SYSTEM_UID) { 2601 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2602 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2603 throw new SecurityException("Permission tree size cap exceeded"); 2604 } 2605 } 2606 } 2607 2608 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2609 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2610 throw new SecurityException("Label must be specified in permission"); 2611 } 2612 BasePermission tree = checkPermissionTreeLP(info.name); 2613 BasePermission bp = mSettings.mPermissions.get(info.name); 2614 boolean added = bp == null; 2615 boolean changed = true; 2616 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2617 if (added) { 2618 enforcePermissionCapLocked(info, tree); 2619 bp = new BasePermission(info.name, tree.sourcePackage, 2620 BasePermission.TYPE_DYNAMIC); 2621 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2622 throw new SecurityException( 2623 "Not allowed to modify non-dynamic permission " 2624 + info.name); 2625 } else { 2626 if (bp.protectionLevel == fixedLevel 2627 && bp.perm.owner.equals(tree.perm.owner) 2628 && bp.uid == tree.uid 2629 && comparePermissionInfos(bp.perm.info, info)) { 2630 changed = false; 2631 } 2632 } 2633 bp.protectionLevel = fixedLevel; 2634 info = new PermissionInfo(info); 2635 info.protectionLevel = fixedLevel; 2636 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2637 bp.perm.info.packageName = tree.perm.info.packageName; 2638 bp.uid = tree.uid; 2639 if (added) { 2640 mSettings.mPermissions.put(info.name, bp); 2641 } 2642 if (changed) { 2643 if (!async) { 2644 mSettings.writeLPr(); 2645 } else { 2646 scheduleWriteSettingsLocked(); 2647 } 2648 } 2649 return added; 2650 } 2651 2652 @Override 2653 public boolean addPermission(PermissionInfo info) { 2654 synchronized (mPackages) { 2655 return addPermissionLocked(info, false); 2656 } 2657 } 2658 2659 @Override 2660 public boolean addPermissionAsync(PermissionInfo info) { 2661 synchronized (mPackages) { 2662 return addPermissionLocked(info, true); 2663 } 2664 } 2665 2666 @Override 2667 public void removePermission(String name) { 2668 synchronized (mPackages) { 2669 checkPermissionTreeLP(name); 2670 BasePermission bp = mSettings.mPermissions.get(name); 2671 if (bp != null) { 2672 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2673 throw new SecurityException( 2674 "Not allowed to modify non-dynamic permission " 2675 + name); 2676 } 2677 mSettings.mPermissions.remove(name); 2678 mSettings.writeLPr(); 2679 } 2680 } 2681 } 2682 2683 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 2684 BasePermission bp) { 2685 int index = pkg.requestedPermissions.indexOf(bp.name); 2686 if (index == -1) { 2687 throw new SecurityException("Package " + pkg.packageName 2688 + " has not requested permission " + bp.name); 2689 } 2690 if (!bp.isRuntime()) { 2691 throw new SecurityException("Permission " + bp.name 2692 + " is not a changeable permission type"); 2693 } 2694 } 2695 2696 @Override 2697 public boolean grantPermission(String packageName, String name, int userId) { 2698 if (!sUserManager.exists(userId)) { 2699 return false; 2700 } 2701 2702 mContext.enforceCallingOrSelfPermission( 2703 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2704 "grantPermission"); 2705 2706 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2707 "grantPermission"); 2708 2709 synchronized (mPackages) { 2710 final PackageParser.Package pkg = mPackages.get(packageName); 2711 if (pkg == null) { 2712 throw new IllegalArgumentException("Unknown package: " + packageName); 2713 } 2714 2715 final BasePermission bp = mSettings.mPermissions.get(name); 2716 if (bp == null) { 2717 throw new IllegalArgumentException("Unknown permission: " + name); 2718 } 2719 2720 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2721 2722 final SettingBase sb = (SettingBase) pkg.mExtras; 2723 if (sb == null) { 2724 throw new IllegalArgumentException("Unknown package: " + packageName); 2725 } 2726 2727 final PermissionsState permissionsState = sb.getPermissionsState(); 2728 2729 final int result = permissionsState.grantRuntimePermission(bp, userId); 2730 switch (result) { 2731 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 2732 return false; 2733 } 2734 2735 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 2736 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 2737 } break; 2738 } 2739 2740 // Not critical if that is lost - app has to request again. 2741 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 2742 2743 return true; 2744 } 2745 } 2746 2747 @Override 2748 public boolean revokePermission(String packageName, String name, int userId) { 2749 if (!sUserManager.exists(userId)) { 2750 return false; 2751 } 2752 2753 mContext.enforceCallingOrSelfPermission( 2754 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2755 "revokePermission"); 2756 2757 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2758 "revokePermission"); 2759 2760 synchronized (mPackages) { 2761 final PackageParser.Package pkg = mPackages.get(packageName); 2762 if (pkg == null) { 2763 throw new IllegalArgumentException("Unknown package: " + packageName); 2764 } 2765 2766 final BasePermission bp = mSettings.mPermissions.get(name); 2767 if (bp == null) { 2768 throw new IllegalArgumentException("Unknown permission: " + name); 2769 } 2770 2771 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2772 2773 final SettingBase sb = (SettingBase) pkg.mExtras; 2774 if (sb == null) { 2775 throw new IllegalArgumentException("Unknown package: " + packageName); 2776 } 2777 2778 final PermissionsState permissionsState = sb.getPermissionsState(); 2779 2780 if (permissionsState.revokeRuntimePermission(bp, userId) == 2781 PermissionsState.PERMISSION_OPERATION_FAILURE) { 2782 return false; 2783 } 2784 2785 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 2786 2787 // Critical, after this call all should never have the permission. 2788 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 2789 2790 return true; 2791 } 2792 } 2793 2794 @Override 2795 public boolean isProtectedBroadcast(String actionName) { 2796 synchronized (mPackages) { 2797 return mProtectedBroadcasts.contains(actionName); 2798 } 2799 } 2800 2801 @Override 2802 public int checkSignatures(String pkg1, String pkg2) { 2803 synchronized (mPackages) { 2804 final PackageParser.Package p1 = mPackages.get(pkg1); 2805 final PackageParser.Package p2 = mPackages.get(pkg2); 2806 if (p1 == null || p1.mExtras == null 2807 || p2 == null || p2.mExtras == null) { 2808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2809 } 2810 return compareSignatures(p1.mSignatures, p2.mSignatures); 2811 } 2812 } 2813 2814 @Override 2815 public int checkUidSignatures(int uid1, int uid2) { 2816 // Map to base uids. 2817 uid1 = UserHandle.getAppId(uid1); 2818 uid2 = UserHandle.getAppId(uid2); 2819 // reader 2820 synchronized (mPackages) { 2821 Signature[] s1; 2822 Signature[] s2; 2823 Object obj = mSettings.getUserIdLPr(uid1); 2824 if (obj != null) { 2825 if (obj instanceof SharedUserSetting) { 2826 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2827 } else if (obj instanceof PackageSetting) { 2828 s1 = ((PackageSetting)obj).signatures.mSignatures; 2829 } else { 2830 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2831 } 2832 } else { 2833 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2834 } 2835 obj = mSettings.getUserIdLPr(uid2); 2836 if (obj != null) { 2837 if (obj instanceof SharedUserSetting) { 2838 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2839 } else if (obj instanceof PackageSetting) { 2840 s2 = ((PackageSetting)obj).signatures.mSignatures; 2841 } else { 2842 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2843 } 2844 } else { 2845 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2846 } 2847 return compareSignatures(s1, s2); 2848 } 2849 } 2850 2851 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 2852 final long identity = Binder.clearCallingIdentity(); 2853 try { 2854 if (sb instanceof SharedUserSetting) { 2855 SharedUserSetting sus = (SharedUserSetting) sb; 2856 final int packageCount = sus.packages.size(); 2857 for (int i = 0; i < packageCount; i++) { 2858 PackageSetting susPs = sus.packages.valueAt(i); 2859 if (userId == UserHandle.USER_ALL) { 2860 killApplication(susPs.pkg.packageName, susPs.appId, reason); 2861 } else { 2862 final int uid = UserHandle.getUid(userId, susPs.appId); 2863 killUid(uid, reason); 2864 } 2865 } 2866 } else if (sb instanceof PackageSetting) { 2867 PackageSetting ps = (PackageSetting) sb; 2868 if (userId == UserHandle.USER_ALL) { 2869 killApplication(ps.pkg.packageName, ps.appId, reason); 2870 } else { 2871 final int uid = UserHandle.getUid(userId, ps.appId); 2872 killUid(uid, reason); 2873 } 2874 } 2875 } finally { 2876 Binder.restoreCallingIdentity(identity); 2877 } 2878 } 2879 2880 private static void killUid(int uid, String reason) { 2881 IActivityManager am = ActivityManagerNative.getDefault(); 2882 if (am != null) { 2883 try { 2884 am.killUid(uid, reason); 2885 } catch (RemoteException e) { 2886 /* ignore - same process */ 2887 } 2888 } 2889 } 2890 2891 /** 2892 * Compares two sets of signatures. Returns: 2893 * <br /> 2894 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2895 * <br /> 2896 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2897 * <br /> 2898 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2899 * <br /> 2900 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2901 * <br /> 2902 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2903 */ 2904 static int compareSignatures(Signature[] s1, Signature[] s2) { 2905 if (s1 == null) { 2906 return s2 == null 2907 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2908 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2909 } 2910 2911 if (s2 == null) { 2912 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2913 } 2914 2915 if (s1.length != s2.length) { 2916 return PackageManager.SIGNATURE_NO_MATCH; 2917 } 2918 2919 // Since both signature sets are of size 1, we can compare without HashSets. 2920 if (s1.length == 1) { 2921 return s1[0].equals(s2[0]) ? 2922 PackageManager.SIGNATURE_MATCH : 2923 PackageManager.SIGNATURE_NO_MATCH; 2924 } 2925 2926 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2927 for (Signature sig : s1) { 2928 set1.add(sig); 2929 } 2930 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2931 for (Signature sig : s2) { 2932 set2.add(sig); 2933 } 2934 // Make sure s2 contains all signatures in s1. 2935 if (set1.equals(set2)) { 2936 return PackageManager.SIGNATURE_MATCH; 2937 } 2938 return PackageManager.SIGNATURE_NO_MATCH; 2939 } 2940 2941 /** 2942 * If the database version for this type of package (internal storage or 2943 * external storage) is less than the version where package signatures 2944 * were updated, return true. 2945 */ 2946 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2947 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2948 DatabaseVersion.SIGNATURE_END_ENTITY)) 2949 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2950 DatabaseVersion.SIGNATURE_END_ENTITY)); 2951 } 2952 2953 /** 2954 * Used for backward compatibility to make sure any packages with 2955 * certificate chains get upgraded to the new style. {@code existingSigs} 2956 * will be in the old format (since they were stored on disk from before the 2957 * system upgrade) and {@code scannedSigs} will be in the newer format. 2958 */ 2959 private int compareSignaturesCompat(PackageSignatures existingSigs, 2960 PackageParser.Package scannedPkg) { 2961 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2962 return PackageManager.SIGNATURE_NO_MATCH; 2963 } 2964 2965 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2966 for (Signature sig : existingSigs.mSignatures) { 2967 existingSet.add(sig); 2968 } 2969 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2970 for (Signature sig : scannedPkg.mSignatures) { 2971 try { 2972 Signature[] chainSignatures = sig.getChainSignatures(); 2973 for (Signature chainSig : chainSignatures) { 2974 scannedCompatSet.add(chainSig); 2975 } 2976 } catch (CertificateEncodingException e) { 2977 scannedCompatSet.add(sig); 2978 } 2979 } 2980 /* 2981 * Make sure the expanded scanned set contains all signatures in the 2982 * existing one. 2983 */ 2984 if (scannedCompatSet.equals(existingSet)) { 2985 // Migrate the old signatures to the new scheme. 2986 existingSigs.assignSignatures(scannedPkg.mSignatures); 2987 // The new KeySets will be re-added later in the scanning process. 2988 synchronized (mPackages) { 2989 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2990 } 2991 return PackageManager.SIGNATURE_MATCH; 2992 } 2993 return PackageManager.SIGNATURE_NO_MATCH; 2994 } 2995 2996 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2997 if (isExternal(scannedPkg)) { 2998 return mSettings.isExternalDatabaseVersionOlderThan( 2999 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3000 } else { 3001 return mSettings.isInternalDatabaseVersionOlderThan( 3002 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3003 } 3004 } 3005 3006 private int compareSignaturesRecover(PackageSignatures existingSigs, 3007 PackageParser.Package scannedPkg) { 3008 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3009 return PackageManager.SIGNATURE_NO_MATCH; 3010 } 3011 3012 String msg = null; 3013 try { 3014 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3015 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3016 + scannedPkg.packageName); 3017 return PackageManager.SIGNATURE_MATCH; 3018 } 3019 } catch (CertificateException e) { 3020 msg = e.getMessage(); 3021 } 3022 3023 logCriticalInfo(Log.INFO, 3024 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3025 return PackageManager.SIGNATURE_NO_MATCH; 3026 } 3027 3028 @Override 3029 public String[] getPackagesForUid(int uid) { 3030 uid = UserHandle.getAppId(uid); 3031 // reader 3032 synchronized (mPackages) { 3033 Object obj = mSettings.getUserIdLPr(uid); 3034 if (obj instanceof SharedUserSetting) { 3035 final SharedUserSetting sus = (SharedUserSetting) obj; 3036 final int N = sus.packages.size(); 3037 final String[] res = new String[N]; 3038 final Iterator<PackageSetting> it = sus.packages.iterator(); 3039 int i = 0; 3040 while (it.hasNext()) { 3041 res[i++] = it.next().name; 3042 } 3043 return res; 3044 } else if (obj instanceof PackageSetting) { 3045 final PackageSetting ps = (PackageSetting) obj; 3046 return new String[] { ps.name }; 3047 } 3048 } 3049 return null; 3050 } 3051 3052 @Override 3053 public String getNameForUid(int uid) { 3054 // reader 3055 synchronized (mPackages) { 3056 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3057 if (obj instanceof SharedUserSetting) { 3058 final SharedUserSetting sus = (SharedUserSetting) obj; 3059 return sus.name + ":" + sus.userId; 3060 } else if (obj instanceof PackageSetting) { 3061 final PackageSetting ps = (PackageSetting) obj; 3062 return ps.name; 3063 } 3064 } 3065 return null; 3066 } 3067 3068 @Override 3069 public int getUidForSharedUser(String sharedUserName) { 3070 if(sharedUserName == null) { 3071 return -1; 3072 } 3073 // reader 3074 synchronized (mPackages) { 3075 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3076 if (suid == null) { 3077 return -1; 3078 } 3079 return suid.userId; 3080 } 3081 } 3082 3083 @Override 3084 public int getFlagsForUid(int uid) { 3085 synchronized (mPackages) { 3086 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3087 if (obj instanceof SharedUserSetting) { 3088 final SharedUserSetting sus = (SharedUserSetting) obj; 3089 return sus.pkgFlags; 3090 } else if (obj instanceof PackageSetting) { 3091 final PackageSetting ps = (PackageSetting) obj; 3092 return ps.pkgFlags; 3093 } 3094 } 3095 return 0; 3096 } 3097 3098 @Override 3099 public int getPrivateFlagsForUid(int uid) { 3100 synchronized (mPackages) { 3101 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3102 if (obj instanceof SharedUserSetting) { 3103 final SharedUserSetting sus = (SharedUserSetting) obj; 3104 return sus.pkgPrivateFlags; 3105 } else if (obj instanceof PackageSetting) { 3106 final PackageSetting ps = (PackageSetting) obj; 3107 return ps.pkgPrivateFlags; 3108 } 3109 } 3110 return 0; 3111 } 3112 3113 @Override 3114 public boolean isUidPrivileged(int uid) { 3115 uid = UserHandle.getAppId(uid); 3116 // reader 3117 synchronized (mPackages) { 3118 Object obj = mSettings.getUserIdLPr(uid); 3119 if (obj instanceof SharedUserSetting) { 3120 final SharedUserSetting sus = (SharedUserSetting) obj; 3121 final Iterator<PackageSetting> it = sus.packages.iterator(); 3122 while (it.hasNext()) { 3123 if (it.next().isPrivileged()) { 3124 return true; 3125 } 3126 } 3127 } else if (obj instanceof PackageSetting) { 3128 final PackageSetting ps = (PackageSetting) obj; 3129 return ps.isPrivileged(); 3130 } 3131 } 3132 return false; 3133 } 3134 3135 @Override 3136 public String[] getAppOpPermissionPackages(String permissionName) { 3137 synchronized (mPackages) { 3138 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3139 if (pkgs == null) { 3140 return null; 3141 } 3142 return pkgs.toArray(new String[pkgs.size()]); 3143 } 3144 } 3145 3146 @Override 3147 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3148 int flags, int userId) { 3149 if (!sUserManager.exists(userId)) return null; 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3151 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3152 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3153 } 3154 3155 @Override 3156 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3157 IntentFilter filter, int match, ComponentName activity) { 3158 final int userId = UserHandle.getCallingUserId(); 3159 if (DEBUG_PREFERRED) { 3160 Log.v(TAG, "setLastChosenActivity intent=" + intent 3161 + " resolvedType=" + resolvedType 3162 + " flags=" + flags 3163 + " filter=" + filter 3164 + " match=" + match 3165 + " activity=" + activity); 3166 filter.dump(new PrintStreamPrinter(System.out), " "); 3167 } 3168 intent.setComponent(null); 3169 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3170 // Find any earlier preferred or last chosen entries and nuke them 3171 findPreferredActivity(intent, resolvedType, 3172 flags, query, 0, false, true, false, userId); 3173 // Add the new activity as the last chosen for this filter 3174 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3175 "Setting last chosen"); 3176 } 3177 3178 @Override 3179 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3180 final int userId = UserHandle.getCallingUserId(); 3181 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3182 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3183 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3184 false, false, false, userId); 3185 } 3186 3187 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3188 int flags, List<ResolveInfo> query, int userId) { 3189 if (query != null) { 3190 final int N = query.size(); 3191 if (N == 1) { 3192 return query.get(0); 3193 } else if (N > 1) { 3194 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3195 // If there is more than one activity with the same priority, 3196 // then let the user decide between them. 3197 ResolveInfo r0 = query.get(0); 3198 ResolveInfo r1 = query.get(1); 3199 if (DEBUG_INTENT_MATCHING || debug) { 3200 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3201 + r1.activityInfo.name + "=" + r1.priority); 3202 } 3203 // If the first activity has a higher priority, or a different 3204 // default, then it is always desireable to pick it. 3205 if (r0.priority != r1.priority 3206 || r0.preferredOrder != r1.preferredOrder 3207 || r0.isDefault != r1.isDefault) { 3208 return query.get(0); 3209 } 3210 // If we have saved a preference for a preferred activity for 3211 // this Intent, use that. 3212 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3213 flags, query, r0.priority, true, false, debug, userId); 3214 if (ri != null) { 3215 return ri; 3216 } 3217 if (userId != 0) { 3218 ri = new ResolveInfo(mResolveInfo); 3219 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3220 ri.activityInfo.applicationInfo = new ApplicationInfo( 3221 ri.activityInfo.applicationInfo); 3222 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3223 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3224 return ri; 3225 } 3226 return mResolveInfo; 3227 } 3228 } 3229 return null; 3230 } 3231 3232 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3233 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3234 final int N = query.size(); 3235 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3236 .get(userId); 3237 // Get the list of persistent preferred activities that handle the intent 3238 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3239 List<PersistentPreferredActivity> pprefs = ppir != null 3240 ? ppir.queryIntent(intent, resolvedType, 3241 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3242 : null; 3243 if (pprefs != null && pprefs.size() > 0) { 3244 final int M = pprefs.size(); 3245 for (int i=0; i<M; i++) { 3246 final PersistentPreferredActivity ppa = pprefs.get(i); 3247 if (DEBUG_PREFERRED || debug) { 3248 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3249 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3250 + "\n component=" + ppa.mComponent); 3251 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3252 } 3253 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3254 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3255 if (DEBUG_PREFERRED || debug) { 3256 Slog.v(TAG, "Found persistent preferred activity:"); 3257 if (ai != null) { 3258 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3259 } else { 3260 Slog.v(TAG, " null"); 3261 } 3262 } 3263 if (ai == null) { 3264 // This previously registered persistent preferred activity 3265 // component is no longer known. Ignore it and do NOT remove it. 3266 continue; 3267 } 3268 for (int j=0; j<N; j++) { 3269 final ResolveInfo ri = query.get(j); 3270 if (!ri.activityInfo.applicationInfo.packageName 3271 .equals(ai.applicationInfo.packageName)) { 3272 continue; 3273 } 3274 if (!ri.activityInfo.name.equals(ai.name)) { 3275 continue; 3276 } 3277 // Found a persistent preference that can handle the intent. 3278 if (DEBUG_PREFERRED || debug) { 3279 Slog.v(TAG, "Returning persistent preferred activity: " + 3280 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3281 } 3282 return ri; 3283 } 3284 } 3285 } 3286 return null; 3287 } 3288 3289 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3290 List<ResolveInfo> query, int priority, boolean always, 3291 boolean removeMatches, boolean debug, int userId) { 3292 if (!sUserManager.exists(userId)) return null; 3293 // writer 3294 synchronized (mPackages) { 3295 if (intent.getSelector() != null) { 3296 intent = intent.getSelector(); 3297 } 3298 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3299 3300 // Try to find a matching persistent preferred activity. 3301 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3302 debug, userId); 3303 3304 // If a persistent preferred activity matched, use it. 3305 if (pri != null) { 3306 return pri; 3307 } 3308 3309 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3310 // Get the list of preferred activities that handle the intent 3311 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3312 List<PreferredActivity> prefs = pir != null 3313 ? pir.queryIntent(intent, resolvedType, 3314 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3315 : null; 3316 if (prefs != null && prefs.size() > 0) { 3317 boolean changed = false; 3318 try { 3319 // First figure out how good the original match set is. 3320 // We will only allow preferred activities that came 3321 // from the same match quality. 3322 int match = 0; 3323 3324 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3325 3326 final int N = query.size(); 3327 for (int j=0; j<N; j++) { 3328 final ResolveInfo ri = query.get(j); 3329 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3330 + ": 0x" + Integer.toHexString(match)); 3331 if (ri.match > match) { 3332 match = ri.match; 3333 } 3334 } 3335 3336 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3337 + Integer.toHexString(match)); 3338 3339 match &= IntentFilter.MATCH_CATEGORY_MASK; 3340 final int M = prefs.size(); 3341 for (int i=0; i<M; i++) { 3342 final PreferredActivity pa = prefs.get(i); 3343 if (DEBUG_PREFERRED || debug) { 3344 Slog.v(TAG, "Checking PreferredActivity ds=" 3345 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3346 + "\n component=" + pa.mPref.mComponent); 3347 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3348 } 3349 if (pa.mPref.mMatch != match) { 3350 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3351 + Integer.toHexString(pa.mPref.mMatch)); 3352 continue; 3353 } 3354 // If it's not an "always" type preferred activity and that's what we're 3355 // looking for, skip it. 3356 if (always && !pa.mPref.mAlways) { 3357 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3358 continue; 3359 } 3360 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3361 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3362 if (DEBUG_PREFERRED || debug) { 3363 Slog.v(TAG, "Found preferred activity:"); 3364 if (ai != null) { 3365 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3366 } else { 3367 Slog.v(TAG, " null"); 3368 } 3369 } 3370 if (ai == null) { 3371 // This previously registered preferred activity 3372 // component is no longer known. Most likely an update 3373 // to the app was installed and in the new version this 3374 // component no longer exists. Clean it up by removing 3375 // it from the preferred activities list, and skip it. 3376 Slog.w(TAG, "Removing dangling preferred activity: " 3377 + pa.mPref.mComponent); 3378 pir.removeFilter(pa); 3379 changed = true; 3380 continue; 3381 } 3382 for (int j=0; j<N; j++) { 3383 final ResolveInfo ri = query.get(j); 3384 if (!ri.activityInfo.applicationInfo.packageName 3385 .equals(ai.applicationInfo.packageName)) { 3386 continue; 3387 } 3388 if (!ri.activityInfo.name.equals(ai.name)) { 3389 continue; 3390 } 3391 3392 if (removeMatches) { 3393 pir.removeFilter(pa); 3394 changed = true; 3395 if (DEBUG_PREFERRED) { 3396 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3397 } 3398 break; 3399 } 3400 3401 // Okay we found a previously set preferred or last chosen app. 3402 // If the result set is different from when this 3403 // was created, we need to clear it and re-ask the 3404 // user their preference, if we're looking for an "always" type entry. 3405 if (always && !pa.mPref.sameSet(query)) { 3406 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3407 + intent + " type " + resolvedType); 3408 if (DEBUG_PREFERRED) { 3409 Slog.v(TAG, "Removing preferred activity since set changed " 3410 + pa.mPref.mComponent); 3411 } 3412 pir.removeFilter(pa); 3413 // Re-add the filter as a "last chosen" entry (!always) 3414 PreferredActivity lastChosen = new PreferredActivity( 3415 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3416 pir.addFilter(lastChosen); 3417 changed = true; 3418 return null; 3419 } 3420 3421 // Yay! Either the set matched or we're looking for the last chosen 3422 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3423 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3424 return ri; 3425 } 3426 } 3427 } finally { 3428 if (changed) { 3429 if (DEBUG_PREFERRED) { 3430 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3431 } 3432 scheduleWritePackageRestrictionsLocked(userId); 3433 } 3434 } 3435 } 3436 } 3437 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3438 return null; 3439 } 3440 3441 /* 3442 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3443 */ 3444 @Override 3445 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3446 int targetUserId) { 3447 mContext.enforceCallingOrSelfPermission( 3448 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3449 List<CrossProfileIntentFilter> matches = 3450 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3451 if (matches != null) { 3452 int size = matches.size(); 3453 for (int i = 0; i < size; i++) { 3454 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3455 } 3456 } 3457 return false; 3458 } 3459 3460 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3461 String resolvedType, int userId) { 3462 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3463 if (resolver != null) { 3464 return resolver.queryIntent(intent, resolvedType, false, userId); 3465 } 3466 return null; 3467 } 3468 3469 @Override 3470 public List<ResolveInfo> queryIntentActivities(Intent intent, 3471 String resolvedType, int flags, int userId) { 3472 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3473 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3474 ComponentName comp = intent.getComponent(); 3475 if (comp == null) { 3476 if (intent.getSelector() != null) { 3477 intent = intent.getSelector(); 3478 comp = intent.getComponent(); 3479 } 3480 } 3481 3482 if (comp != null) { 3483 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3484 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3485 if (ai != null) { 3486 final ResolveInfo ri = new ResolveInfo(); 3487 ri.activityInfo = ai; 3488 list.add(ri); 3489 } 3490 return list; 3491 } 3492 3493 // reader 3494 synchronized (mPackages) { 3495 final String pkgName = intent.getPackage(); 3496 if (pkgName == null) { 3497 List<CrossProfileIntentFilter> matchingFilters = 3498 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3499 // Check for results that need to skip the current profile. 3500 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3501 resolvedType, flags, userId); 3502 if (resolveInfo != null) { 3503 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3504 result.add(resolveInfo); 3505 return filterIfNotPrimaryUser(result, userId); 3506 } 3507 // Check for cross profile results. 3508 resolveInfo = queryCrossProfileIntents( 3509 matchingFilters, intent, resolvedType, flags, userId); 3510 3511 // Check for results in the current profile. 3512 List<ResolveInfo> result = mActivities.queryIntent( 3513 intent, resolvedType, flags, userId); 3514 if (resolveInfo != null) { 3515 result.add(resolveInfo); 3516 Collections.sort(result, mResolvePrioritySorter); 3517 } 3518 return filterIfNotPrimaryUser(result, userId); 3519 } 3520 final PackageParser.Package pkg = mPackages.get(pkgName); 3521 if (pkg != null) { 3522 return filterIfNotPrimaryUser( 3523 mActivities.queryIntentForPackage( 3524 intent, resolvedType, flags, pkg.activities, userId), 3525 userId); 3526 } 3527 return new ArrayList<ResolveInfo>(); 3528 } 3529 } 3530 3531 /** 3532 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3533 * 3534 * @return filtered list 3535 */ 3536 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3537 if (userId == UserHandle.USER_OWNER) { 3538 return resolveInfos; 3539 } 3540 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3541 ResolveInfo info = resolveInfos.get(i); 3542 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3543 resolveInfos.remove(i); 3544 } 3545 } 3546 return resolveInfos; 3547 } 3548 3549 3550 private ResolveInfo querySkipCurrentProfileIntents( 3551 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3552 int flags, int sourceUserId) { 3553 if (matchingFilters != null) { 3554 int size = matchingFilters.size(); 3555 for (int i = 0; i < size; i ++) { 3556 CrossProfileIntentFilter filter = matchingFilters.get(i); 3557 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3558 // Checking if there are activities in the target user that can handle the 3559 // intent. 3560 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3561 flags, sourceUserId); 3562 if (resolveInfo != null) { 3563 return resolveInfo; 3564 } 3565 } 3566 } 3567 } 3568 return null; 3569 } 3570 3571 // Return matching ResolveInfo if any for skip current profile intent filters. 3572 private ResolveInfo queryCrossProfileIntents( 3573 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3574 int flags, int sourceUserId) { 3575 if (matchingFilters != null) { 3576 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3577 // match the same intent. For performance reasons, it is better not to 3578 // run queryIntent twice for the same userId 3579 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3580 int size = matchingFilters.size(); 3581 for (int i = 0; i < size; i++) { 3582 CrossProfileIntentFilter filter = matchingFilters.get(i); 3583 int targetUserId = filter.getTargetUserId(); 3584 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3585 && !alreadyTriedUserIds.get(targetUserId)) { 3586 // Checking if there are activities in the target user that can handle the 3587 // intent. 3588 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3589 flags, sourceUserId); 3590 if (resolveInfo != null) return resolveInfo; 3591 alreadyTriedUserIds.put(targetUserId, true); 3592 } 3593 } 3594 } 3595 return null; 3596 } 3597 3598 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3599 String resolvedType, int flags, int sourceUserId) { 3600 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3601 resolvedType, flags, filter.getTargetUserId()); 3602 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3603 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3604 } 3605 return null; 3606 } 3607 3608 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3609 int sourceUserId, int targetUserId) { 3610 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3611 String className; 3612 if (targetUserId == UserHandle.USER_OWNER) { 3613 className = FORWARD_INTENT_TO_USER_OWNER; 3614 } else { 3615 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3616 } 3617 ComponentName forwardingActivityComponentName = new ComponentName( 3618 mAndroidApplication.packageName, className); 3619 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3620 sourceUserId); 3621 if (targetUserId == UserHandle.USER_OWNER) { 3622 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3623 forwardingResolveInfo.noResourceId = true; 3624 } 3625 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3626 forwardingResolveInfo.priority = 0; 3627 forwardingResolveInfo.preferredOrder = 0; 3628 forwardingResolveInfo.match = 0; 3629 forwardingResolveInfo.isDefault = true; 3630 forwardingResolveInfo.filter = filter; 3631 forwardingResolveInfo.targetUserId = targetUserId; 3632 return forwardingResolveInfo; 3633 } 3634 3635 @Override 3636 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3637 Intent[] specifics, String[] specificTypes, Intent intent, 3638 String resolvedType, int flags, int userId) { 3639 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3640 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3641 false, "query intent activity options"); 3642 final String resultsAction = intent.getAction(); 3643 3644 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3645 | PackageManager.GET_RESOLVED_FILTER, userId); 3646 3647 if (DEBUG_INTENT_MATCHING) { 3648 Log.v(TAG, "Query " + intent + ": " + results); 3649 } 3650 3651 int specificsPos = 0; 3652 int N; 3653 3654 // todo: note that the algorithm used here is O(N^2). This 3655 // isn't a problem in our current environment, but if we start running 3656 // into situations where we have more than 5 or 10 matches then this 3657 // should probably be changed to something smarter... 3658 3659 // First we go through and resolve each of the specific items 3660 // that were supplied, taking care of removing any corresponding 3661 // duplicate items in the generic resolve list. 3662 if (specifics != null) { 3663 for (int i=0; i<specifics.length; i++) { 3664 final Intent sintent = specifics[i]; 3665 if (sintent == null) { 3666 continue; 3667 } 3668 3669 if (DEBUG_INTENT_MATCHING) { 3670 Log.v(TAG, "Specific #" + i + ": " + sintent); 3671 } 3672 3673 String action = sintent.getAction(); 3674 if (resultsAction != null && resultsAction.equals(action)) { 3675 // If this action was explicitly requested, then don't 3676 // remove things that have it. 3677 action = null; 3678 } 3679 3680 ResolveInfo ri = null; 3681 ActivityInfo ai = null; 3682 3683 ComponentName comp = sintent.getComponent(); 3684 if (comp == null) { 3685 ri = resolveIntent( 3686 sintent, 3687 specificTypes != null ? specificTypes[i] : null, 3688 flags, userId); 3689 if (ri == null) { 3690 continue; 3691 } 3692 if (ri == mResolveInfo) { 3693 // ACK! Must do something better with this. 3694 } 3695 ai = ri.activityInfo; 3696 comp = new ComponentName(ai.applicationInfo.packageName, 3697 ai.name); 3698 } else { 3699 ai = getActivityInfo(comp, flags, userId); 3700 if (ai == null) { 3701 continue; 3702 } 3703 } 3704 3705 // Look for any generic query activities that are duplicates 3706 // of this specific one, and remove them from the results. 3707 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3708 N = results.size(); 3709 int j; 3710 for (j=specificsPos; j<N; j++) { 3711 ResolveInfo sri = results.get(j); 3712 if ((sri.activityInfo.name.equals(comp.getClassName()) 3713 && sri.activityInfo.applicationInfo.packageName.equals( 3714 comp.getPackageName())) 3715 || (action != null && sri.filter.matchAction(action))) { 3716 results.remove(j); 3717 if (DEBUG_INTENT_MATCHING) Log.v( 3718 TAG, "Removing duplicate item from " + j 3719 + " due to specific " + specificsPos); 3720 if (ri == null) { 3721 ri = sri; 3722 } 3723 j--; 3724 N--; 3725 } 3726 } 3727 3728 // Add this specific item to its proper place. 3729 if (ri == null) { 3730 ri = new ResolveInfo(); 3731 ri.activityInfo = ai; 3732 } 3733 results.add(specificsPos, ri); 3734 ri.specificIndex = i; 3735 specificsPos++; 3736 } 3737 } 3738 3739 // Now we go through the remaining generic results and remove any 3740 // duplicate actions that are found here. 3741 N = results.size(); 3742 for (int i=specificsPos; i<N-1; i++) { 3743 final ResolveInfo rii = results.get(i); 3744 if (rii.filter == null) { 3745 continue; 3746 } 3747 3748 // Iterate over all of the actions of this result's intent 3749 // filter... typically this should be just one. 3750 final Iterator<String> it = rii.filter.actionsIterator(); 3751 if (it == null) { 3752 continue; 3753 } 3754 while (it.hasNext()) { 3755 final String action = it.next(); 3756 if (resultsAction != null && resultsAction.equals(action)) { 3757 // If this action was explicitly requested, then don't 3758 // remove things that have it. 3759 continue; 3760 } 3761 for (int j=i+1; j<N; j++) { 3762 final ResolveInfo rij = results.get(j); 3763 if (rij.filter != null && rij.filter.hasAction(action)) { 3764 results.remove(j); 3765 if (DEBUG_INTENT_MATCHING) Log.v( 3766 TAG, "Removing duplicate item from " + j 3767 + " due to action " + action + " at " + i); 3768 j--; 3769 N--; 3770 } 3771 } 3772 } 3773 3774 // If the caller didn't request filter information, drop it now 3775 // so we don't have to marshall/unmarshall it. 3776 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3777 rii.filter = null; 3778 } 3779 } 3780 3781 // Filter out the caller activity if so requested. 3782 if (caller != null) { 3783 N = results.size(); 3784 for (int i=0; i<N; i++) { 3785 ActivityInfo ainfo = results.get(i).activityInfo; 3786 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3787 && caller.getClassName().equals(ainfo.name)) { 3788 results.remove(i); 3789 break; 3790 } 3791 } 3792 } 3793 3794 // If the caller didn't request filter information, 3795 // drop them now so we don't have to 3796 // marshall/unmarshall it. 3797 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3798 N = results.size(); 3799 for (int i=0; i<N; i++) { 3800 results.get(i).filter = null; 3801 } 3802 } 3803 3804 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3805 return results; 3806 } 3807 3808 @Override 3809 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3810 int userId) { 3811 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3812 ComponentName comp = intent.getComponent(); 3813 if (comp == null) { 3814 if (intent.getSelector() != null) { 3815 intent = intent.getSelector(); 3816 comp = intent.getComponent(); 3817 } 3818 } 3819 if (comp != null) { 3820 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3821 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3822 if (ai != null) { 3823 ResolveInfo ri = new ResolveInfo(); 3824 ri.activityInfo = ai; 3825 list.add(ri); 3826 } 3827 return list; 3828 } 3829 3830 // reader 3831 synchronized (mPackages) { 3832 String pkgName = intent.getPackage(); 3833 if (pkgName == null) { 3834 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3835 } 3836 final PackageParser.Package pkg = mPackages.get(pkgName); 3837 if (pkg != null) { 3838 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3839 userId); 3840 } 3841 return null; 3842 } 3843 } 3844 3845 @Override 3846 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3847 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3848 if (!sUserManager.exists(userId)) return null; 3849 if (query != null) { 3850 if (query.size() >= 1) { 3851 // If there is more than one service with the same priority, 3852 // just arbitrarily pick the first one. 3853 return query.get(0); 3854 } 3855 } 3856 return null; 3857 } 3858 3859 @Override 3860 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3861 int userId) { 3862 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3863 ComponentName comp = intent.getComponent(); 3864 if (comp == null) { 3865 if (intent.getSelector() != null) { 3866 intent = intent.getSelector(); 3867 comp = intent.getComponent(); 3868 } 3869 } 3870 if (comp != null) { 3871 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3872 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3873 if (si != null) { 3874 final ResolveInfo ri = new ResolveInfo(); 3875 ri.serviceInfo = si; 3876 list.add(ri); 3877 } 3878 return list; 3879 } 3880 3881 // reader 3882 synchronized (mPackages) { 3883 String pkgName = intent.getPackage(); 3884 if (pkgName == null) { 3885 return mServices.queryIntent(intent, resolvedType, flags, userId); 3886 } 3887 final PackageParser.Package pkg = mPackages.get(pkgName); 3888 if (pkg != null) { 3889 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3890 userId); 3891 } 3892 return null; 3893 } 3894 } 3895 3896 @Override 3897 public List<ResolveInfo> queryIntentContentProviders( 3898 Intent intent, String resolvedType, int flags, int userId) { 3899 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3900 ComponentName comp = intent.getComponent(); 3901 if (comp == null) { 3902 if (intent.getSelector() != null) { 3903 intent = intent.getSelector(); 3904 comp = intent.getComponent(); 3905 } 3906 } 3907 if (comp != null) { 3908 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3909 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3910 if (pi != null) { 3911 final ResolveInfo ri = new ResolveInfo(); 3912 ri.providerInfo = pi; 3913 list.add(ri); 3914 } 3915 return list; 3916 } 3917 3918 // reader 3919 synchronized (mPackages) { 3920 String pkgName = intent.getPackage(); 3921 if (pkgName == null) { 3922 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3923 } 3924 final PackageParser.Package pkg = mPackages.get(pkgName); 3925 if (pkg != null) { 3926 return mProviders.queryIntentForPackage( 3927 intent, resolvedType, flags, pkg.providers, userId); 3928 } 3929 return null; 3930 } 3931 } 3932 3933 @Override 3934 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3935 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3936 3937 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3938 3939 // writer 3940 synchronized (mPackages) { 3941 ArrayList<PackageInfo> list; 3942 if (listUninstalled) { 3943 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3944 for (PackageSetting ps : mSettings.mPackages.values()) { 3945 PackageInfo pi; 3946 if (ps.pkg != null) { 3947 pi = generatePackageInfo(ps.pkg, flags, userId); 3948 } else { 3949 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3950 } 3951 if (pi != null) { 3952 list.add(pi); 3953 } 3954 } 3955 } else { 3956 list = new ArrayList<PackageInfo>(mPackages.size()); 3957 for (PackageParser.Package p : mPackages.values()) { 3958 PackageInfo pi = generatePackageInfo(p, flags, userId); 3959 if (pi != null) { 3960 list.add(pi); 3961 } 3962 } 3963 } 3964 3965 return new ParceledListSlice<PackageInfo>(list); 3966 } 3967 } 3968 3969 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3970 String[] permissions, boolean[] tmp, int flags, int userId) { 3971 int numMatch = 0; 3972 final PermissionsState permissionsState = ps.getPermissionsState(); 3973 for (int i=0; i<permissions.length; i++) { 3974 final String permission = permissions[i]; 3975 if (permissionsState.hasPermission(permission, userId)) { 3976 tmp[i] = true; 3977 numMatch++; 3978 } else { 3979 tmp[i] = false; 3980 } 3981 } 3982 if (numMatch == 0) { 3983 return; 3984 } 3985 PackageInfo pi; 3986 if (ps.pkg != null) { 3987 pi = generatePackageInfo(ps.pkg, flags, userId); 3988 } else { 3989 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3990 } 3991 // The above might return null in cases of uninstalled apps or install-state 3992 // skew across users/profiles. 3993 if (pi != null) { 3994 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3995 if (numMatch == permissions.length) { 3996 pi.requestedPermissions = permissions; 3997 } else { 3998 pi.requestedPermissions = new String[numMatch]; 3999 numMatch = 0; 4000 for (int i=0; i<permissions.length; i++) { 4001 if (tmp[i]) { 4002 pi.requestedPermissions[numMatch] = permissions[i]; 4003 numMatch++; 4004 } 4005 } 4006 } 4007 } 4008 list.add(pi); 4009 } 4010 } 4011 4012 @Override 4013 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4014 String[] permissions, int flags, int userId) { 4015 if (!sUserManager.exists(userId)) return null; 4016 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4017 4018 // writer 4019 synchronized (mPackages) { 4020 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4021 boolean[] tmpBools = new boolean[permissions.length]; 4022 if (listUninstalled) { 4023 for (PackageSetting ps : mSettings.mPackages.values()) { 4024 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4025 } 4026 } else { 4027 for (PackageParser.Package pkg : mPackages.values()) { 4028 PackageSetting ps = (PackageSetting)pkg.mExtras; 4029 if (ps != null) { 4030 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4031 userId); 4032 } 4033 } 4034 } 4035 4036 return new ParceledListSlice<PackageInfo>(list); 4037 } 4038 } 4039 4040 @Override 4041 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4042 if (!sUserManager.exists(userId)) return null; 4043 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4044 4045 // writer 4046 synchronized (mPackages) { 4047 ArrayList<ApplicationInfo> list; 4048 if (listUninstalled) { 4049 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4050 for (PackageSetting ps : mSettings.mPackages.values()) { 4051 ApplicationInfo ai; 4052 if (ps.pkg != null) { 4053 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4054 ps.readUserState(userId), userId); 4055 } else { 4056 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4057 } 4058 if (ai != null) { 4059 list.add(ai); 4060 } 4061 } 4062 } else { 4063 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4064 for (PackageParser.Package p : mPackages.values()) { 4065 if (p.mExtras != null) { 4066 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4067 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4068 if (ai != null) { 4069 list.add(ai); 4070 } 4071 } 4072 } 4073 } 4074 4075 return new ParceledListSlice<ApplicationInfo>(list); 4076 } 4077 } 4078 4079 public List<ApplicationInfo> getPersistentApplications(int flags) { 4080 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4081 4082 // reader 4083 synchronized (mPackages) { 4084 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4085 final int userId = UserHandle.getCallingUserId(); 4086 while (i.hasNext()) { 4087 final PackageParser.Package p = i.next(); 4088 if (p.applicationInfo != null 4089 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4090 && (!mSafeMode || isSystemApp(p))) { 4091 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4092 if (ps != null) { 4093 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4094 ps.readUserState(userId), userId); 4095 if (ai != null) { 4096 finalList.add(ai); 4097 } 4098 } 4099 } 4100 } 4101 } 4102 4103 return finalList; 4104 } 4105 4106 @Override 4107 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4108 if (!sUserManager.exists(userId)) return null; 4109 // reader 4110 synchronized (mPackages) { 4111 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4112 PackageSetting ps = provider != null 4113 ? mSettings.mPackages.get(provider.owner.packageName) 4114 : null; 4115 return ps != null 4116 && mSettings.isEnabledLPr(provider.info, flags, userId) 4117 && (!mSafeMode || (provider.info.applicationInfo.flags 4118 &ApplicationInfo.FLAG_SYSTEM) != 0) 4119 ? PackageParser.generateProviderInfo(provider, flags, 4120 ps.readUserState(userId), userId) 4121 : null; 4122 } 4123 } 4124 4125 /** 4126 * @deprecated 4127 */ 4128 @Deprecated 4129 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4130 // reader 4131 synchronized (mPackages) { 4132 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4133 .entrySet().iterator(); 4134 final int userId = UserHandle.getCallingUserId(); 4135 while (i.hasNext()) { 4136 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4137 PackageParser.Provider p = entry.getValue(); 4138 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4139 4140 if (ps != null && p.syncable 4141 && (!mSafeMode || (p.info.applicationInfo.flags 4142 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4143 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4144 ps.readUserState(userId), userId); 4145 if (info != null) { 4146 outNames.add(entry.getKey()); 4147 outInfo.add(info); 4148 } 4149 } 4150 } 4151 } 4152 } 4153 4154 @Override 4155 public List<ProviderInfo> queryContentProviders(String processName, 4156 int uid, int flags) { 4157 ArrayList<ProviderInfo> finalList = null; 4158 // reader 4159 synchronized (mPackages) { 4160 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4161 final int userId = processName != null ? 4162 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4163 while (i.hasNext()) { 4164 final PackageParser.Provider p = i.next(); 4165 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4166 if (ps != null && p.info.authority != null 4167 && (processName == null 4168 || (p.info.processName.equals(processName) 4169 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4170 && mSettings.isEnabledLPr(p.info, flags, userId) 4171 && (!mSafeMode 4172 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4173 if (finalList == null) { 4174 finalList = new ArrayList<ProviderInfo>(3); 4175 } 4176 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4177 ps.readUserState(userId), userId); 4178 if (info != null) { 4179 finalList.add(info); 4180 } 4181 } 4182 } 4183 } 4184 4185 if (finalList != null) { 4186 Collections.sort(finalList, mProviderInitOrderSorter); 4187 } 4188 4189 return finalList; 4190 } 4191 4192 @Override 4193 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4194 int flags) { 4195 // reader 4196 synchronized (mPackages) { 4197 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4198 return PackageParser.generateInstrumentationInfo(i, flags); 4199 } 4200 } 4201 4202 @Override 4203 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4204 int flags) { 4205 ArrayList<InstrumentationInfo> finalList = 4206 new ArrayList<InstrumentationInfo>(); 4207 4208 // reader 4209 synchronized (mPackages) { 4210 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4211 while (i.hasNext()) { 4212 final PackageParser.Instrumentation p = i.next(); 4213 if (targetPackage == null 4214 || targetPackage.equals(p.info.targetPackage)) { 4215 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4216 flags); 4217 if (ii != null) { 4218 finalList.add(ii); 4219 } 4220 } 4221 } 4222 } 4223 4224 return finalList; 4225 } 4226 4227 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4228 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4229 if (overlays == null) { 4230 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4231 return; 4232 } 4233 for (PackageParser.Package opkg : overlays.values()) { 4234 // Not much to do if idmap fails: we already logged the error 4235 // and we certainly don't want to abort installation of pkg simply 4236 // because an overlay didn't fit properly. For these reasons, 4237 // ignore the return value of createIdmapForPackagePairLI. 4238 createIdmapForPackagePairLI(pkg, opkg); 4239 } 4240 } 4241 4242 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4243 PackageParser.Package opkg) { 4244 if (!opkg.mTrustedOverlay) { 4245 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4246 opkg.baseCodePath + ": overlay not trusted"); 4247 return false; 4248 } 4249 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4250 if (overlaySet == null) { 4251 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4252 opkg.baseCodePath + " but target package has no known overlays"); 4253 return false; 4254 } 4255 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4256 // TODO: generate idmap for split APKs 4257 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4258 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4259 + opkg.baseCodePath); 4260 return false; 4261 } 4262 PackageParser.Package[] overlayArray = 4263 overlaySet.values().toArray(new PackageParser.Package[0]); 4264 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4265 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4266 return p1.mOverlayPriority - p2.mOverlayPriority; 4267 } 4268 }; 4269 Arrays.sort(overlayArray, cmp); 4270 4271 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4272 int i = 0; 4273 for (PackageParser.Package p : overlayArray) { 4274 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4275 } 4276 return true; 4277 } 4278 4279 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4280 final File[] files = dir.listFiles(); 4281 if (ArrayUtils.isEmpty(files)) { 4282 Log.d(TAG, "No files in app dir " + dir); 4283 return; 4284 } 4285 4286 if (DEBUG_PACKAGE_SCANNING) { 4287 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4288 + " flags=0x" + Integer.toHexString(parseFlags)); 4289 } 4290 4291 for (File file : files) { 4292 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4293 && !PackageInstallerService.isStageName(file.getName()); 4294 if (!isPackage) { 4295 // Ignore entries which are not packages 4296 continue; 4297 } 4298 try { 4299 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4300 scanFlags, currentTime, null); 4301 } catch (PackageManagerException e) { 4302 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4303 4304 // Delete invalid userdata apps 4305 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4306 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4307 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4308 if (file.isDirectory()) { 4309 FileUtils.deleteContents(file); 4310 } 4311 file.delete(); 4312 } 4313 } 4314 } 4315 } 4316 4317 private static File getSettingsProblemFile() { 4318 File dataDir = Environment.getDataDirectory(); 4319 File systemDir = new File(dataDir, "system"); 4320 File fname = new File(systemDir, "uiderrors.txt"); 4321 return fname; 4322 } 4323 4324 static void reportSettingsProblem(int priority, String msg) { 4325 logCriticalInfo(priority, msg); 4326 } 4327 4328 static void logCriticalInfo(int priority, String msg) { 4329 Slog.println(priority, TAG, msg); 4330 EventLogTags.writePmCriticalInfo(msg); 4331 try { 4332 File fname = getSettingsProblemFile(); 4333 FileOutputStream out = new FileOutputStream(fname, true); 4334 PrintWriter pw = new FastPrintWriter(out); 4335 SimpleDateFormat formatter = new SimpleDateFormat(); 4336 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4337 pw.println(dateString + ": " + msg); 4338 pw.close(); 4339 FileUtils.setPermissions( 4340 fname.toString(), 4341 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4342 -1, -1); 4343 } catch (java.io.IOException e) { 4344 } 4345 } 4346 4347 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4348 PackageParser.Package pkg, File srcFile, int parseFlags) 4349 throws PackageManagerException { 4350 if (ps != null 4351 && ps.codePath.equals(srcFile) 4352 && ps.timeStamp == srcFile.lastModified() 4353 && !isCompatSignatureUpdateNeeded(pkg) 4354 && !isRecoverSignatureUpdateNeeded(pkg)) { 4355 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4356 if (ps.signatures.mSignatures != null 4357 && ps.signatures.mSignatures.length != 0 4358 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4359 // Optimization: reuse the existing cached certificates 4360 // if the package appears to be unchanged. 4361 pkg.mSignatures = ps.signatures.mSignatures; 4362 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4363 synchronized (mPackages) { 4364 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4365 } 4366 return; 4367 } 4368 4369 Slog.w(TAG, "PackageSetting for " + ps.name 4370 + " is missing signatures. Collecting certs again to recover them."); 4371 } else { 4372 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4373 } 4374 4375 try { 4376 pp.collectCertificates(pkg, parseFlags); 4377 pp.collectManifestDigest(pkg); 4378 } catch (PackageParserException e) { 4379 throw PackageManagerException.from(e); 4380 } 4381 } 4382 4383 /* 4384 * Scan a package and return the newly parsed package. 4385 * Returns null in case of errors and the error code is stored in mLastScanError 4386 */ 4387 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4388 long currentTime, UserHandle user) throws PackageManagerException { 4389 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4390 parseFlags |= mDefParseFlags; 4391 PackageParser pp = new PackageParser(); 4392 pp.setSeparateProcesses(mSeparateProcesses); 4393 pp.setOnlyCoreApps(mOnlyCore); 4394 pp.setDisplayMetrics(mMetrics); 4395 4396 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4397 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4398 } 4399 4400 final PackageParser.Package pkg; 4401 try { 4402 pkg = pp.parsePackage(scanFile, parseFlags); 4403 } catch (PackageParserException e) { 4404 throw PackageManagerException.from(e); 4405 } 4406 4407 PackageSetting ps = null; 4408 PackageSetting updatedPkg; 4409 // reader 4410 synchronized (mPackages) { 4411 // Look to see if we already know about this package. 4412 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4413 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4414 // This package has been renamed to its original name. Let's 4415 // use that. 4416 ps = mSettings.peekPackageLPr(oldName); 4417 } 4418 // If there was no original package, see one for the real package name. 4419 if (ps == null) { 4420 ps = mSettings.peekPackageLPr(pkg.packageName); 4421 } 4422 // Check to see if this package could be hiding/updating a system 4423 // package. Must look for it either under the original or real 4424 // package name depending on our state. 4425 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4426 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4427 } 4428 boolean updatedPkgBetter = false; 4429 // First check if this is a system package that may involve an update 4430 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4431 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4432 // it needs to drop FLAG_PRIVILEGED. 4433 if (locationIsPrivileged(scanFile)) { 4434 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4435 } else { 4436 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4437 } 4438 4439 if (ps != null && !ps.codePath.equals(scanFile)) { 4440 // The path has changed from what was last scanned... check the 4441 // version of the new path against what we have stored to determine 4442 // what to do. 4443 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4444 if (pkg.mVersionCode <= ps.versionCode) { 4445 // The system package has been updated and the code path does not match 4446 // Ignore entry. Skip it. 4447 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4448 + " ignored: updated version " + ps.versionCode 4449 + " better than this " + pkg.mVersionCode); 4450 if (!updatedPkg.codePath.equals(scanFile)) { 4451 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4452 + ps.name + " changing from " + updatedPkg.codePathString 4453 + " to " + scanFile); 4454 updatedPkg.codePath = scanFile; 4455 updatedPkg.codePathString = scanFile.toString(); 4456 updatedPkg.resourcePath = scanFile; 4457 updatedPkg.resourcePathString = scanFile.toString(); 4458 } 4459 updatedPkg.pkg = pkg; 4460 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4461 } else { 4462 // The current app on the system partition is better than 4463 // what we have updated to on the data partition; switch 4464 // back to the system partition version. 4465 // At this point, its safely assumed that package installation for 4466 // apps in system partition will go through. If not there won't be a working 4467 // version of the app 4468 // writer 4469 synchronized (mPackages) { 4470 // Just remove the loaded entries from package lists. 4471 mPackages.remove(ps.name); 4472 } 4473 4474 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4475 + " reverting from " + ps.codePathString 4476 + ": new version " + pkg.mVersionCode 4477 + " better than installed " + ps.versionCode); 4478 4479 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4480 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4481 getAppDexInstructionSets(ps)); 4482 synchronized (mInstallLock) { 4483 args.cleanUpResourcesLI(); 4484 } 4485 synchronized (mPackages) { 4486 mSettings.enableSystemPackageLPw(ps.name); 4487 } 4488 updatedPkgBetter = true; 4489 } 4490 } 4491 } 4492 4493 if (updatedPkg != null) { 4494 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4495 // initially 4496 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4497 4498 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4499 // flag set initially 4500 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4501 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4502 } 4503 } 4504 4505 // Verify certificates against what was last scanned 4506 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4507 4508 /* 4509 * A new system app appeared, but we already had a non-system one of the 4510 * same name installed earlier. 4511 */ 4512 boolean shouldHideSystemApp = false; 4513 if (updatedPkg == null && ps != null 4514 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4515 /* 4516 * Check to make sure the signatures match first. If they don't, 4517 * wipe the installed application and its data. 4518 */ 4519 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4520 != PackageManager.SIGNATURE_MATCH) { 4521 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4522 + " signatures don't match existing userdata copy; removing"); 4523 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4524 ps = null; 4525 } else { 4526 /* 4527 * If the newly-added system app is an older version than the 4528 * already installed version, hide it. It will be scanned later 4529 * and re-added like an update. 4530 */ 4531 if (pkg.mVersionCode <= ps.versionCode) { 4532 shouldHideSystemApp = true; 4533 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4534 + " but new version " + pkg.mVersionCode + " better than installed " 4535 + ps.versionCode + "; hiding system"); 4536 } else { 4537 /* 4538 * The newly found system app is a newer version that the 4539 * one previously installed. Simply remove the 4540 * already-installed application and replace it with our own 4541 * while keeping the application data. 4542 */ 4543 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4544 + " reverting from " + ps.codePathString + ": new version " 4545 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4546 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4547 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4548 getAppDexInstructionSets(ps)); 4549 synchronized (mInstallLock) { 4550 args.cleanUpResourcesLI(); 4551 } 4552 } 4553 } 4554 } 4555 4556 // The apk is forward locked (not public) if its code and resources 4557 // are kept in different files. (except for app in either system or 4558 // vendor path). 4559 // TODO grab this value from PackageSettings 4560 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4561 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4562 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4563 } 4564 } 4565 4566 // TODO: extend to support forward-locked splits 4567 String resourcePath = null; 4568 String baseResourcePath = null; 4569 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4570 if (ps != null && ps.resourcePathString != null) { 4571 resourcePath = ps.resourcePathString; 4572 baseResourcePath = ps.resourcePathString; 4573 } else { 4574 // Should not happen at all. Just log an error. 4575 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4576 } 4577 } else { 4578 resourcePath = pkg.codePath; 4579 baseResourcePath = pkg.baseCodePath; 4580 } 4581 4582 // Set application objects path explicitly. 4583 pkg.applicationInfo.setCodePath(pkg.codePath); 4584 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4585 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4586 pkg.applicationInfo.setResourcePath(resourcePath); 4587 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4588 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4589 4590 // Note that we invoke the following method only if we are about to unpack an application 4591 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4592 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4593 4594 /* 4595 * If the system app should be overridden by a previously installed 4596 * data, hide the system app now and let the /data/app scan pick it up 4597 * again. 4598 */ 4599 if (shouldHideSystemApp) { 4600 synchronized (mPackages) { 4601 /* 4602 * We have to grant systems permissions before we hide, because 4603 * grantPermissions will assume the package update is trying to 4604 * expand its permissions. 4605 */ 4606 grantPermissionsLPw(pkg, true, pkg.packageName); 4607 mSettings.disableSystemPackageLPw(pkg.packageName); 4608 } 4609 } 4610 4611 return scannedPkg; 4612 } 4613 4614 private static String fixProcessName(String defProcessName, 4615 String processName, int uid) { 4616 if (processName == null) { 4617 return defProcessName; 4618 } 4619 return processName; 4620 } 4621 4622 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4623 throws PackageManagerException { 4624 if (pkgSetting.signatures.mSignatures != null) { 4625 // Already existing package. Make sure signatures match 4626 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4627 == PackageManager.SIGNATURE_MATCH; 4628 if (!match) { 4629 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4630 == PackageManager.SIGNATURE_MATCH; 4631 } 4632 if (!match) { 4633 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4634 == PackageManager.SIGNATURE_MATCH; 4635 } 4636 if (!match) { 4637 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4638 + pkg.packageName + " signatures do not match the " 4639 + "previously installed version; ignoring!"); 4640 } 4641 } 4642 4643 // Check for shared user signatures 4644 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4645 // Already existing package. Make sure signatures match 4646 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4647 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4648 if (!match) { 4649 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4650 == PackageManager.SIGNATURE_MATCH; 4651 } 4652 if (!match) { 4653 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4654 == PackageManager.SIGNATURE_MATCH; 4655 } 4656 if (!match) { 4657 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4658 "Package " + pkg.packageName 4659 + " has no signatures that match those in shared user " 4660 + pkgSetting.sharedUser.name + "; ignoring!"); 4661 } 4662 } 4663 } 4664 4665 /** 4666 * Enforces that only the system UID or root's UID can call a method exposed 4667 * via Binder. 4668 * 4669 * @param message used as message if SecurityException is thrown 4670 * @throws SecurityException if the caller is not system or root 4671 */ 4672 private static final void enforceSystemOrRoot(String message) { 4673 final int uid = Binder.getCallingUid(); 4674 if (uid != Process.SYSTEM_UID && uid != 0) { 4675 throw new SecurityException(message); 4676 } 4677 } 4678 4679 @Override 4680 public void performBootDexOpt() { 4681 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4682 4683 // Before everything else, see whether we need to fstrim. 4684 try { 4685 IMountService ms = PackageHelper.getMountService(); 4686 if (ms != null) { 4687 final boolean isUpgrade = isUpgrade(); 4688 boolean doTrim = isUpgrade; 4689 if (doTrim) { 4690 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4691 } else { 4692 final long interval = android.provider.Settings.Global.getLong( 4693 mContext.getContentResolver(), 4694 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4695 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4696 if (interval > 0) { 4697 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4698 if (timeSinceLast > interval) { 4699 doTrim = true; 4700 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4701 + "; running immediately"); 4702 } 4703 } 4704 } 4705 if (doTrim) { 4706 if (!isFirstBoot()) { 4707 try { 4708 ActivityManagerNative.getDefault().showBootMessage( 4709 mContext.getResources().getString( 4710 R.string.android_upgrading_fstrim), true); 4711 } catch (RemoteException e) { 4712 } 4713 } 4714 ms.runMaintenance(); 4715 } 4716 } else { 4717 Slog.e(TAG, "Mount service unavailable!"); 4718 } 4719 } catch (RemoteException e) { 4720 // Can't happen; MountService is local 4721 } 4722 4723 final ArraySet<PackageParser.Package> pkgs; 4724 synchronized (mPackages) { 4725 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4726 } 4727 4728 if (pkgs != null) { 4729 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4730 // in case the device runs out of space. 4731 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4732 // Give priority to core apps. 4733 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4734 PackageParser.Package pkg = it.next(); 4735 if (pkg.coreApp) { 4736 if (DEBUG_DEXOPT) { 4737 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4738 } 4739 sortedPkgs.add(pkg); 4740 it.remove(); 4741 } 4742 } 4743 // Give priority to system apps that listen for pre boot complete. 4744 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4745 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4746 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4747 PackageParser.Package pkg = it.next(); 4748 if (pkgNames.contains(pkg.packageName)) { 4749 if (DEBUG_DEXOPT) { 4750 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4751 } 4752 sortedPkgs.add(pkg); 4753 it.remove(); 4754 } 4755 } 4756 // Give priority to system apps. 4757 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4758 PackageParser.Package pkg = it.next(); 4759 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4760 if (DEBUG_DEXOPT) { 4761 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4762 } 4763 sortedPkgs.add(pkg); 4764 it.remove(); 4765 } 4766 } 4767 // Give priority to updated system apps. 4768 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4769 PackageParser.Package pkg = it.next(); 4770 if (isUpdatedSystemApp(pkg)) { 4771 if (DEBUG_DEXOPT) { 4772 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4773 } 4774 sortedPkgs.add(pkg); 4775 it.remove(); 4776 } 4777 } 4778 // Give priority to apps that listen for boot complete. 4779 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4780 pkgNames = getPackageNamesForIntent(intent); 4781 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4782 PackageParser.Package pkg = it.next(); 4783 if (pkgNames.contains(pkg.packageName)) { 4784 if (DEBUG_DEXOPT) { 4785 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4786 } 4787 sortedPkgs.add(pkg); 4788 it.remove(); 4789 } 4790 } 4791 // Filter out packages that aren't recently used. 4792 filterRecentlyUsedApps(pkgs); 4793 // Add all remaining apps. 4794 for (PackageParser.Package pkg : pkgs) { 4795 if (DEBUG_DEXOPT) { 4796 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4797 } 4798 sortedPkgs.add(pkg); 4799 } 4800 4801 // If we want to be lazy, filter everything that wasn't recently used. 4802 if (mLazyDexOpt) { 4803 filterRecentlyUsedApps(sortedPkgs); 4804 } 4805 4806 int i = 0; 4807 int total = sortedPkgs.size(); 4808 File dataDir = Environment.getDataDirectory(); 4809 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4810 if (lowThreshold == 0) { 4811 throw new IllegalStateException("Invalid low memory threshold"); 4812 } 4813 for (PackageParser.Package pkg : sortedPkgs) { 4814 long usableSpace = dataDir.getUsableSpace(); 4815 if (usableSpace < lowThreshold) { 4816 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4817 break; 4818 } 4819 performBootDexOpt(pkg, ++i, total); 4820 } 4821 } 4822 } 4823 4824 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4825 // Filter out packages that aren't recently used. 4826 // 4827 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4828 // should do a full dexopt. 4829 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4830 int total = pkgs.size(); 4831 int skipped = 0; 4832 long now = System.currentTimeMillis(); 4833 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4834 PackageParser.Package pkg = i.next(); 4835 long then = pkg.mLastPackageUsageTimeInMills; 4836 if (then + mDexOptLRUThresholdInMills < now) { 4837 if (DEBUG_DEXOPT) { 4838 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4839 ((then == 0) ? "never" : new Date(then))); 4840 } 4841 i.remove(); 4842 skipped++; 4843 } 4844 } 4845 if (DEBUG_DEXOPT) { 4846 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4847 } 4848 } 4849 } 4850 4851 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4852 List<ResolveInfo> ris = null; 4853 try { 4854 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4855 intent, null, 0, UserHandle.USER_OWNER); 4856 } catch (RemoteException e) { 4857 } 4858 ArraySet<String> pkgNames = new ArraySet<String>(); 4859 if (ris != null) { 4860 for (ResolveInfo ri : ris) { 4861 pkgNames.add(ri.activityInfo.packageName); 4862 } 4863 } 4864 return pkgNames; 4865 } 4866 4867 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4868 if (DEBUG_DEXOPT) { 4869 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4870 } 4871 if (!isFirstBoot()) { 4872 try { 4873 ActivityManagerNative.getDefault().showBootMessage( 4874 mContext.getResources().getString(R.string.android_upgrading_apk, 4875 curr, total), true); 4876 } catch (RemoteException e) { 4877 } 4878 } 4879 PackageParser.Package p = pkg; 4880 synchronized (mInstallLock) { 4881 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4882 false /* force dex */, false /* defer */, true /* include dependencies */); 4883 } 4884 } 4885 4886 @Override 4887 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4888 return performDexOpt(packageName, instructionSet, false); 4889 } 4890 4891 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4892 if (info.primaryCpuAbi == null) { 4893 return getPreferredInstructionSet(); 4894 } 4895 4896 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4897 } 4898 4899 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4900 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4901 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4902 if (!dexopt && !updateUsage) { 4903 // We aren't going to dexopt or update usage, so bail early. 4904 return false; 4905 } 4906 PackageParser.Package p; 4907 final String targetInstructionSet; 4908 synchronized (mPackages) { 4909 p = mPackages.get(packageName); 4910 if (p == null) { 4911 return false; 4912 } 4913 if (updateUsage) { 4914 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4915 } 4916 mPackageUsage.write(false); 4917 if (!dexopt) { 4918 // We aren't going to dexopt, so bail early. 4919 return false; 4920 } 4921 4922 targetInstructionSet = instructionSet != null ? instructionSet : 4923 getPrimaryInstructionSet(p.applicationInfo); 4924 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4925 return false; 4926 } 4927 } 4928 4929 synchronized (mInstallLock) { 4930 final String[] instructionSets = new String[] { targetInstructionSet }; 4931 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4932 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4933 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4934 } 4935 } 4936 4937 public ArraySet<String> getPackagesThatNeedDexOpt() { 4938 ArraySet<String> pkgs = null; 4939 synchronized (mPackages) { 4940 for (PackageParser.Package p : mPackages.values()) { 4941 if (DEBUG_DEXOPT) { 4942 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4943 } 4944 if (!p.mDexOptPerformed.isEmpty()) { 4945 continue; 4946 } 4947 if (pkgs == null) { 4948 pkgs = new ArraySet<String>(); 4949 } 4950 pkgs.add(p.packageName); 4951 } 4952 } 4953 return pkgs; 4954 } 4955 4956 public void shutdown() { 4957 mPackageUsage.write(true); 4958 } 4959 4960 @Override 4961 public void forceDexOpt(String packageName) { 4962 enforceSystemOrRoot("forceDexOpt"); 4963 4964 PackageParser.Package pkg; 4965 synchronized (mPackages) { 4966 pkg = mPackages.get(packageName); 4967 if (pkg == null) { 4968 throw new IllegalArgumentException("Missing package: " + packageName); 4969 } 4970 } 4971 4972 synchronized (mInstallLock) { 4973 final String[] instructionSets = new String[] { 4974 getPrimaryInstructionSet(pkg.applicationInfo) }; 4975 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4976 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4977 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4978 throw new IllegalStateException("Failed to dexopt: " + res); 4979 } 4980 } 4981 } 4982 4983 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4984 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4985 Slog.w(TAG, "Unable to update from " + oldPkg.name 4986 + " to " + newPkg.packageName 4987 + ": old package not in system partition"); 4988 return false; 4989 } else if (mPackages.get(oldPkg.name) != null) { 4990 Slog.w(TAG, "Unable to update from " + oldPkg.name 4991 + " to " + newPkg.packageName 4992 + ": old package still exists"); 4993 return false; 4994 } 4995 return true; 4996 } 4997 4998 private File getDataPathForPackage(String packageName, int userId) { 4999 /* 5000 * Until we fully support multiple users, return the directory we 5001 * previously would have. The PackageManagerTests will need to be 5002 * revised when this is changed back.. 5003 */ 5004 if (userId == 0) { 5005 return new File(mAppDataDir, packageName); 5006 } else { 5007 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5008 + File.separator + packageName); 5009 } 5010 } 5011 5012 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5013 int[] users = sUserManager.getUserIds(); 5014 int res = mInstaller.install(packageName, uid, uid, seinfo); 5015 if (res < 0) { 5016 return res; 5017 } 5018 for (int user : users) { 5019 if (user != 0) { 5020 res = mInstaller.createUserData(packageName, 5021 UserHandle.getUid(user, uid), user, seinfo); 5022 if (res < 0) { 5023 return res; 5024 } 5025 } 5026 } 5027 return res; 5028 } 5029 5030 private int removeDataDirsLI(String packageName) { 5031 int[] users = sUserManager.getUserIds(); 5032 int res = 0; 5033 for (int user : users) { 5034 int resInner = mInstaller.remove(packageName, user); 5035 if (resInner < 0) { 5036 res = resInner; 5037 } 5038 } 5039 5040 return res; 5041 } 5042 5043 private int deleteCodeCacheDirsLI(String packageName) { 5044 int[] users = sUserManager.getUserIds(); 5045 int res = 0; 5046 for (int user : users) { 5047 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5048 if (resInner < 0) { 5049 res = resInner; 5050 } 5051 } 5052 return res; 5053 } 5054 5055 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5056 PackageParser.Package changingLib) { 5057 if (file.path != null) { 5058 usesLibraryFiles.add(file.path); 5059 return; 5060 } 5061 PackageParser.Package p = mPackages.get(file.apk); 5062 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5063 // If we are doing this while in the middle of updating a library apk, 5064 // then we need to make sure to use that new apk for determining the 5065 // dependencies here. (We haven't yet finished committing the new apk 5066 // to the package manager state.) 5067 if (p == null || p.packageName.equals(changingLib.packageName)) { 5068 p = changingLib; 5069 } 5070 } 5071 if (p != null) { 5072 usesLibraryFiles.addAll(p.getAllCodePaths()); 5073 } 5074 } 5075 5076 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5077 PackageParser.Package changingLib) throws PackageManagerException { 5078 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5079 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5080 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5081 for (int i=0; i<N; i++) { 5082 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5083 if (file == null) { 5084 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5085 "Package " + pkg.packageName + " requires unavailable shared library " 5086 + pkg.usesLibraries.get(i) + "; failing!"); 5087 } 5088 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5089 } 5090 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5091 for (int i=0; i<N; i++) { 5092 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5093 if (file == null) { 5094 Slog.w(TAG, "Package " + pkg.packageName 5095 + " desires unavailable shared library " 5096 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5097 } else { 5098 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5099 } 5100 } 5101 N = usesLibraryFiles.size(); 5102 if (N > 0) { 5103 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5104 } else { 5105 pkg.usesLibraryFiles = null; 5106 } 5107 } 5108 } 5109 5110 private static boolean hasString(List<String> list, List<String> which) { 5111 if (list == null) { 5112 return false; 5113 } 5114 for (int i=list.size()-1; i>=0; i--) { 5115 for (int j=which.size()-1; j>=0; j--) { 5116 if (which.get(j).equals(list.get(i))) { 5117 return true; 5118 } 5119 } 5120 } 5121 return false; 5122 } 5123 5124 private void updateAllSharedLibrariesLPw() { 5125 for (PackageParser.Package pkg : mPackages.values()) { 5126 try { 5127 updateSharedLibrariesLPw(pkg, null); 5128 } catch (PackageManagerException e) { 5129 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5130 } 5131 } 5132 } 5133 5134 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5135 PackageParser.Package changingPkg) { 5136 ArrayList<PackageParser.Package> res = null; 5137 for (PackageParser.Package pkg : mPackages.values()) { 5138 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5139 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5140 if (res == null) { 5141 res = new ArrayList<PackageParser.Package>(); 5142 } 5143 res.add(pkg); 5144 try { 5145 updateSharedLibrariesLPw(pkg, changingPkg); 5146 } catch (PackageManagerException e) { 5147 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5148 } 5149 } 5150 } 5151 return res; 5152 } 5153 5154 /** 5155 * Derive the value of the {@code cpuAbiOverride} based on the provided 5156 * value and an optional stored value from the package settings. 5157 */ 5158 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5159 String cpuAbiOverride = null; 5160 5161 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5162 cpuAbiOverride = null; 5163 } else if (abiOverride != null) { 5164 cpuAbiOverride = abiOverride; 5165 } else if (settings != null) { 5166 cpuAbiOverride = settings.cpuAbiOverrideString; 5167 } 5168 5169 return cpuAbiOverride; 5170 } 5171 5172 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5173 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5174 boolean success = false; 5175 try { 5176 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5177 currentTime, user); 5178 success = true; 5179 return res; 5180 } finally { 5181 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5182 removeDataDirsLI(pkg.packageName); 5183 } 5184 } 5185 } 5186 5187 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5188 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5189 final File scanFile = new File(pkg.codePath); 5190 if (pkg.applicationInfo.getCodePath() == null || 5191 pkg.applicationInfo.getResourcePath() == null) { 5192 // Bail out. The resource and code paths haven't been set. 5193 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5194 "Code and resource paths haven't been set correctly"); 5195 } 5196 5197 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5198 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5199 } else { 5200 // Only allow system apps to be flagged as core apps. 5201 pkg.coreApp = false; 5202 } 5203 5204 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5205 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5206 } 5207 5208 if (mCustomResolverComponentName != null && 5209 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5210 setUpCustomResolverActivity(pkg); 5211 } 5212 5213 if (pkg.packageName.equals("android")) { 5214 synchronized (mPackages) { 5215 if (mAndroidApplication != null) { 5216 Slog.w(TAG, "*************************************************"); 5217 Slog.w(TAG, "Core android package being redefined. Skipping."); 5218 Slog.w(TAG, " file=" + scanFile); 5219 Slog.w(TAG, "*************************************************"); 5220 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5221 "Core android package being redefined. Skipping."); 5222 } 5223 5224 // Set up information for our fall-back user intent resolution activity. 5225 mPlatformPackage = pkg; 5226 pkg.mVersionCode = mSdkVersion; 5227 mAndroidApplication = pkg.applicationInfo; 5228 5229 if (!mResolverReplaced) { 5230 mResolveActivity.applicationInfo = mAndroidApplication; 5231 mResolveActivity.name = ResolverActivity.class.getName(); 5232 mResolveActivity.packageName = mAndroidApplication.packageName; 5233 mResolveActivity.processName = "system:ui"; 5234 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5235 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5236 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5237 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5238 mResolveActivity.exported = true; 5239 mResolveActivity.enabled = true; 5240 mResolveInfo.activityInfo = mResolveActivity; 5241 mResolveInfo.priority = 0; 5242 mResolveInfo.preferredOrder = 0; 5243 mResolveInfo.match = 0; 5244 mResolveComponentName = new ComponentName( 5245 mAndroidApplication.packageName, mResolveActivity.name); 5246 } 5247 } 5248 } 5249 5250 if (DEBUG_PACKAGE_SCANNING) { 5251 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5252 Log.d(TAG, "Scanning package " + pkg.packageName); 5253 } 5254 5255 if (mPackages.containsKey(pkg.packageName) 5256 || mSharedLibraries.containsKey(pkg.packageName)) { 5257 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5258 "Application package " + pkg.packageName 5259 + " already installed. Skipping duplicate."); 5260 } 5261 5262 // Initialize package source and resource directories 5263 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5264 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5265 5266 SharedUserSetting suid = null; 5267 PackageSetting pkgSetting = null; 5268 5269 if (!isSystemApp(pkg)) { 5270 // Only system apps can use these features. 5271 pkg.mOriginalPackages = null; 5272 pkg.mRealPackage = null; 5273 pkg.mAdoptPermissions = null; 5274 } 5275 5276 // writer 5277 synchronized (mPackages) { 5278 if (pkg.mSharedUserId != null) { 5279 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5280 if (suid == null) { 5281 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5282 "Creating application package " + pkg.packageName 5283 + " for shared user failed"); 5284 } 5285 if (DEBUG_PACKAGE_SCANNING) { 5286 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5287 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5288 + "): packages=" + suid.packages); 5289 } 5290 } 5291 5292 // Check if we are renaming from an original package name. 5293 PackageSetting origPackage = null; 5294 String realName = null; 5295 if (pkg.mOriginalPackages != null) { 5296 // This package may need to be renamed to a previously 5297 // installed name. Let's check on that... 5298 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5299 if (pkg.mOriginalPackages.contains(renamed)) { 5300 // This package had originally been installed as the 5301 // original name, and we have already taken care of 5302 // transitioning to the new one. Just update the new 5303 // one to continue using the old name. 5304 realName = pkg.mRealPackage; 5305 if (!pkg.packageName.equals(renamed)) { 5306 // Callers into this function may have already taken 5307 // care of renaming the package; only do it here if 5308 // it is not already done. 5309 pkg.setPackageName(renamed); 5310 } 5311 5312 } else { 5313 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5314 if ((origPackage = mSettings.peekPackageLPr( 5315 pkg.mOriginalPackages.get(i))) != null) { 5316 // We do have the package already installed under its 5317 // original name... should we use it? 5318 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5319 // New package is not compatible with original. 5320 origPackage = null; 5321 continue; 5322 } else if (origPackage.sharedUser != null) { 5323 // Make sure uid is compatible between packages. 5324 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5325 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5326 + " to " + pkg.packageName + ": old uid " 5327 + origPackage.sharedUser.name 5328 + " differs from " + pkg.mSharedUserId); 5329 origPackage = null; 5330 continue; 5331 } 5332 } else { 5333 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5334 + pkg.packageName + " to old name " + origPackage.name); 5335 } 5336 break; 5337 } 5338 } 5339 } 5340 } 5341 5342 if (mTransferedPackages.contains(pkg.packageName)) { 5343 Slog.w(TAG, "Package " + pkg.packageName 5344 + " was transferred to another, but its .apk remains"); 5345 } 5346 5347 // Just create the setting, don't add it yet. For already existing packages 5348 // the PkgSetting exists already and doesn't have to be created. 5349 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5350 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5351 pkg.applicationInfo.primaryCpuAbi, 5352 pkg.applicationInfo.secondaryCpuAbi, 5353 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5354 user, false); 5355 if (pkgSetting == null) { 5356 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5357 "Creating application package " + pkg.packageName + " failed"); 5358 } 5359 5360 if (pkgSetting.origPackage != null) { 5361 // If we are first transitioning from an original package, 5362 // fix up the new package's name now. We need to do this after 5363 // looking up the package under its new name, so getPackageLP 5364 // can take care of fiddling things correctly. 5365 pkg.setPackageName(origPackage.name); 5366 5367 // File a report about this. 5368 String msg = "New package " + pkgSetting.realName 5369 + " renamed to replace old package " + pkgSetting.name; 5370 reportSettingsProblem(Log.WARN, msg); 5371 5372 // Make a note of it. 5373 mTransferedPackages.add(origPackage.name); 5374 5375 // No longer need to retain this. 5376 pkgSetting.origPackage = null; 5377 } 5378 5379 if (realName != null) { 5380 // Make a note of it. 5381 mTransferedPackages.add(pkg.packageName); 5382 } 5383 5384 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5385 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5386 } 5387 5388 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5389 // Check all shared libraries and map to their actual file path. 5390 // We only do this here for apps not on a system dir, because those 5391 // are the only ones that can fail an install due to this. We 5392 // will take care of the system apps by updating all of their 5393 // library paths after the scan is done. 5394 updateSharedLibrariesLPw(pkg, null); 5395 } 5396 5397 if (mFoundPolicyFile) { 5398 SELinuxMMAC.assignSeinfoValue(pkg); 5399 } 5400 5401 pkg.applicationInfo.uid = pkgSetting.appId; 5402 pkg.mExtras = pkgSetting; 5403 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5404 try { 5405 verifySignaturesLP(pkgSetting, pkg); 5406 // We just determined the app is signed correctly, so bring 5407 // over the latest parsed certs. 5408 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5409 } catch (PackageManagerException e) { 5410 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5411 throw e; 5412 } 5413 // The signature has changed, but this package is in the system 5414 // image... let's recover! 5415 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5416 // However... if this package is part of a shared user, but it 5417 // doesn't match the signature of the shared user, let's fail. 5418 // What this means is that you can't change the signatures 5419 // associated with an overall shared user, which doesn't seem all 5420 // that unreasonable. 5421 if (pkgSetting.sharedUser != null) { 5422 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5423 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5424 throw new PackageManagerException( 5425 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5426 "Signature mismatch for shared user : " 5427 + pkgSetting.sharedUser); 5428 } 5429 } 5430 // File a report about this. 5431 String msg = "System package " + pkg.packageName 5432 + " signature changed; retaining data."; 5433 reportSettingsProblem(Log.WARN, msg); 5434 } 5435 } else { 5436 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5437 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5438 + pkg.packageName + " upgrade keys do not match the " 5439 + "previously installed version"); 5440 } else { 5441 // We just determined the app is signed correctly, so bring 5442 // over the latest parsed certs. 5443 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5444 } 5445 } 5446 // Verify that this new package doesn't have any content providers 5447 // that conflict with existing packages. Only do this if the 5448 // package isn't already installed, since we don't want to break 5449 // things that are installed. 5450 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5451 final int N = pkg.providers.size(); 5452 int i; 5453 for (i=0; i<N; i++) { 5454 PackageParser.Provider p = pkg.providers.get(i); 5455 if (p.info.authority != null) { 5456 String names[] = p.info.authority.split(";"); 5457 for (int j = 0; j < names.length; j++) { 5458 if (mProvidersByAuthority.containsKey(names[j])) { 5459 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5460 final String otherPackageName = 5461 ((other != null && other.getComponentName() != null) ? 5462 other.getComponentName().getPackageName() : "?"); 5463 throw new PackageManagerException( 5464 INSTALL_FAILED_CONFLICTING_PROVIDER, 5465 "Can't install because provider name " + names[j] 5466 + " (in package " + pkg.applicationInfo.packageName 5467 + ") is already used by " + otherPackageName); 5468 } 5469 } 5470 } 5471 } 5472 } 5473 5474 if (pkg.mAdoptPermissions != null) { 5475 // This package wants to adopt ownership of permissions from 5476 // another package. 5477 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5478 final String origName = pkg.mAdoptPermissions.get(i); 5479 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5480 if (orig != null) { 5481 if (verifyPackageUpdateLPr(orig, pkg)) { 5482 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5483 + pkg.packageName); 5484 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5485 } 5486 } 5487 } 5488 } 5489 } 5490 5491 final String pkgName = pkg.packageName; 5492 5493 final long scanFileTime = scanFile.lastModified(); 5494 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5495 pkg.applicationInfo.processName = fixProcessName( 5496 pkg.applicationInfo.packageName, 5497 pkg.applicationInfo.processName, 5498 pkg.applicationInfo.uid); 5499 5500 File dataPath; 5501 if (mPlatformPackage == pkg) { 5502 // The system package is special. 5503 dataPath = new File(Environment.getDataDirectory(), "system"); 5504 5505 pkg.applicationInfo.dataDir = dataPath.getPath(); 5506 5507 } else { 5508 // This is a normal package, need to make its data directory. 5509 dataPath = getDataPathForPackage(pkg.packageName, 0); 5510 5511 boolean uidError = false; 5512 if (dataPath.exists()) { 5513 int currentUid = 0; 5514 try { 5515 StructStat stat = Os.stat(dataPath.getPath()); 5516 currentUid = stat.st_uid; 5517 } catch (ErrnoException e) { 5518 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5519 } 5520 5521 // If we have mismatched owners for the data path, we have a problem. 5522 if (currentUid != pkg.applicationInfo.uid) { 5523 boolean recovered = false; 5524 if (currentUid == 0) { 5525 // The directory somehow became owned by root. Wow. 5526 // This is probably because the system was stopped while 5527 // installd was in the middle of messing with its libs 5528 // directory. Ask installd to fix that. 5529 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5530 pkg.applicationInfo.uid); 5531 if (ret >= 0) { 5532 recovered = true; 5533 String msg = "Package " + pkg.packageName 5534 + " unexpectedly changed to uid 0; recovered to " + 5535 + pkg.applicationInfo.uid; 5536 reportSettingsProblem(Log.WARN, msg); 5537 } 5538 } 5539 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5540 || (scanFlags&SCAN_BOOTING) != 0)) { 5541 // If this is a system app, we can at least delete its 5542 // current data so the application will still work. 5543 int ret = removeDataDirsLI(pkgName); 5544 if (ret >= 0) { 5545 // TODO: Kill the processes first 5546 // Old data gone! 5547 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5548 ? "System package " : "Third party package "; 5549 String msg = prefix + pkg.packageName 5550 + " has changed from uid: " 5551 + currentUid + " to " 5552 + pkg.applicationInfo.uid + "; old data erased"; 5553 reportSettingsProblem(Log.WARN, msg); 5554 recovered = true; 5555 5556 // And now re-install the app. 5557 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5558 pkg.applicationInfo.seinfo); 5559 if (ret == -1) { 5560 // Ack should not happen! 5561 msg = prefix + pkg.packageName 5562 + " could not have data directory re-created after delete."; 5563 reportSettingsProblem(Log.WARN, msg); 5564 throw new PackageManagerException( 5565 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5566 } 5567 } 5568 if (!recovered) { 5569 mHasSystemUidErrors = true; 5570 } 5571 } else if (!recovered) { 5572 // If we allow this install to proceed, we will be broken. 5573 // Abort, abort! 5574 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5575 "scanPackageLI"); 5576 } 5577 if (!recovered) { 5578 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5579 + pkg.applicationInfo.uid + "/fs_" 5580 + currentUid; 5581 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5582 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5583 String msg = "Package " + pkg.packageName 5584 + " has mismatched uid: " 5585 + currentUid + " on disk, " 5586 + pkg.applicationInfo.uid + " in settings"; 5587 // writer 5588 synchronized (mPackages) { 5589 mSettings.mReadMessages.append(msg); 5590 mSettings.mReadMessages.append('\n'); 5591 uidError = true; 5592 if (!pkgSetting.uidError) { 5593 reportSettingsProblem(Log.ERROR, msg); 5594 } 5595 } 5596 } 5597 } 5598 pkg.applicationInfo.dataDir = dataPath.getPath(); 5599 if (mShouldRestoreconData) { 5600 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5601 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5602 pkg.applicationInfo.uid); 5603 } 5604 } else { 5605 if (DEBUG_PACKAGE_SCANNING) { 5606 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5607 Log.v(TAG, "Want this data dir: " + dataPath); 5608 } 5609 //invoke installer to do the actual installation 5610 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5611 pkg.applicationInfo.seinfo); 5612 if (ret < 0) { 5613 // Error from installer 5614 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5615 "Unable to create data dirs [errorCode=" + ret + "]"); 5616 } 5617 5618 if (dataPath.exists()) { 5619 pkg.applicationInfo.dataDir = dataPath.getPath(); 5620 } else { 5621 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5622 pkg.applicationInfo.dataDir = null; 5623 } 5624 } 5625 5626 pkgSetting.uidError = uidError; 5627 } 5628 5629 final String path = scanFile.getPath(); 5630 final String codePath = pkg.applicationInfo.getCodePath(); 5631 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5632 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5633 setBundledAppAbisAndRoots(pkg, pkgSetting); 5634 5635 // If we haven't found any native libraries for the app, check if it has 5636 // renderscript code. We'll need to force the app to 32 bit if it has 5637 // renderscript bitcode. 5638 if (pkg.applicationInfo.primaryCpuAbi == null 5639 && pkg.applicationInfo.secondaryCpuAbi == null 5640 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5641 NativeLibraryHelper.Handle handle = null; 5642 try { 5643 handle = NativeLibraryHelper.Handle.create(scanFile); 5644 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5645 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5646 } 5647 } catch (IOException ioe) { 5648 Slog.w(TAG, "Error scanning system app : " + ioe); 5649 } finally { 5650 IoUtils.closeQuietly(handle); 5651 } 5652 } 5653 5654 setNativeLibraryPaths(pkg); 5655 } else { 5656 // TODO: We can probably be smarter about this stuff. For installed apps, 5657 // we can calculate this information at install time once and for all. For 5658 // system apps, we can probably assume that this information doesn't change 5659 // after the first boot scan. As things stand, we do lots of unnecessary work. 5660 5661 // Give ourselves some initial paths; we'll come back for another 5662 // pass once we've determined ABI below. 5663 setNativeLibraryPaths(pkg); 5664 5665 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5666 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5667 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5668 5669 NativeLibraryHelper.Handle handle = null; 5670 try { 5671 handle = NativeLibraryHelper.Handle.create(scanFile); 5672 // TODO(multiArch): This can be null for apps that didn't go through the 5673 // usual installation process. We can calculate it again, like we 5674 // do during install time. 5675 // 5676 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5677 // unnecessary. 5678 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5679 5680 // Null out the abis so that they can be recalculated. 5681 pkg.applicationInfo.primaryCpuAbi = null; 5682 pkg.applicationInfo.secondaryCpuAbi = null; 5683 if (isMultiArch(pkg.applicationInfo)) { 5684 // Warn if we've set an abiOverride for multi-lib packages.. 5685 // By definition, we need to copy both 32 and 64 bit libraries for 5686 // such packages. 5687 if (pkg.cpuAbiOverride != null 5688 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5689 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5690 } 5691 5692 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5693 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5694 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5695 if (isAsec) { 5696 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5697 } else { 5698 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5699 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5700 useIsaSpecificSubdirs); 5701 } 5702 } 5703 5704 maybeThrowExceptionForMultiArchCopy( 5705 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5706 5707 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5708 if (isAsec) { 5709 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5710 } else { 5711 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5712 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5713 useIsaSpecificSubdirs); 5714 } 5715 } 5716 5717 maybeThrowExceptionForMultiArchCopy( 5718 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5719 5720 if (abi64 >= 0) { 5721 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5722 } 5723 5724 if (abi32 >= 0) { 5725 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5726 if (abi64 >= 0) { 5727 pkg.applicationInfo.secondaryCpuAbi = abi; 5728 } else { 5729 pkg.applicationInfo.primaryCpuAbi = abi; 5730 } 5731 } 5732 } else { 5733 String[] abiList = (cpuAbiOverride != null) ? 5734 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5735 5736 // Enable gross and lame hacks for apps that are built with old 5737 // SDK tools. We must scan their APKs for renderscript bitcode and 5738 // not launch them if it's present. Don't bother checking on devices 5739 // that don't have 64 bit support. 5740 boolean needsRenderScriptOverride = false; 5741 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5742 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5743 abiList = Build.SUPPORTED_32_BIT_ABIS; 5744 needsRenderScriptOverride = true; 5745 } 5746 5747 final int copyRet; 5748 if (isAsec) { 5749 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5750 } else { 5751 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5752 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5753 } 5754 5755 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5756 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5757 "Error unpackaging native libs for app, errorCode=" + copyRet); 5758 } 5759 5760 if (copyRet >= 0) { 5761 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5762 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5763 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5764 } else if (needsRenderScriptOverride) { 5765 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5766 } 5767 } 5768 } catch (IOException ioe) { 5769 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5770 } finally { 5771 IoUtils.closeQuietly(handle); 5772 } 5773 5774 // Now that we've calculated the ABIs and determined if it's an internal app, 5775 // we will go ahead and populate the nativeLibraryPath. 5776 setNativeLibraryPaths(pkg); 5777 5778 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5779 final int[] userIds = sUserManager.getUserIds(); 5780 synchronized (mInstallLock) { 5781 // Create a native library symlink only if we have native libraries 5782 // and if the native libraries are 32 bit libraries. We do not provide 5783 // this symlink for 64 bit libraries. 5784 if (pkg.applicationInfo.primaryCpuAbi != null && 5785 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5786 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5787 for (int userId : userIds) { 5788 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5789 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5790 "Failed linking native library dir (user=" + userId + ")"); 5791 } 5792 } 5793 } 5794 } 5795 } 5796 5797 // This is a special case for the "system" package, where the ABI is 5798 // dictated by the zygote configuration (and init.rc). We should keep track 5799 // of this ABI so that we can deal with "normal" applications that run under 5800 // the same UID correctly. 5801 if (mPlatformPackage == pkg) { 5802 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5803 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5804 } 5805 5806 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5807 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5808 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5809 // Copy the derived override back to the parsed package, so that we can 5810 // update the package settings accordingly. 5811 pkg.cpuAbiOverride = cpuAbiOverride; 5812 5813 if (DEBUG_ABI_SELECTION) { 5814 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5815 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5816 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5817 } 5818 5819 // Push the derived path down into PackageSettings so we know what to 5820 // clean up at uninstall time. 5821 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5822 5823 if (DEBUG_ABI_SELECTION) { 5824 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5825 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5826 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5827 } 5828 5829 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5830 // We don't do this here during boot because we can do it all 5831 // at once after scanning all existing packages. 5832 // 5833 // We also do this *before* we perform dexopt on this package, so that 5834 // we can avoid redundant dexopts, and also to make sure we've got the 5835 // code and package path correct. 5836 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5837 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5838 } 5839 5840 if ((scanFlags & SCAN_NO_DEX) == 0) { 5841 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5842 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5843 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5844 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5845 } 5846 } 5847 5848 if (mFactoryTest && pkg.requestedPermissions.contains( 5849 android.Manifest.permission.FACTORY_TEST)) { 5850 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5851 } 5852 5853 ArrayList<PackageParser.Package> clientLibPkgs = null; 5854 5855 // writer 5856 synchronized (mPackages) { 5857 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5858 // Only system apps can add new shared libraries. 5859 if (pkg.libraryNames != null) { 5860 for (int i=0; i<pkg.libraryNames.size(); i++) { 5861 String name = pkg.libraryNames.get(i); 5862 boolean allowed = false; 5863 if (isUpdatedSystemApp(pkg)) { 5864 // New library entries can only be added through the 5865 // system image. This is important to get rid of a lot 5866 // of nasty edge cases: for example if we allowed a non- 5867 // system update of the app to add a library, then uninstalling 5868 // the update would make the library go away, and assumptions 5869 // we made such as through app install filtering would now 5870 // have allowed apps on the device which aren't compatible 5871 // with it. Better to just have the restriction here, be 5872 // conservative, and create many fewer cases that can negatively 5873 // impact the user experience. 5874 final PackageSetting sysPs = mSettings 5875 .getDisabledSystemPkgLPr(pkg.packageName); 5876 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5877 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5878 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5879 allowed = true; 5880 allowed = true; 5881 break; 5882 } 5883 } 5884 } 5885 } else { 5886 allowed = true; 5887 } 5888 if (allowed) { 5889 if (!mSharedLibraries.containsKey(name)) { 5890 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5891 } else if (!name.equals(pkg.packageName)) { 5892 Slog.w(TAG, "Package " + pkg.packageName + " library " 5893 + name + " already exists; skipping"); 5894 } 5895 } else { 5896 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5897 + name + " that is not declared on system image; skipping"); 5898 } 5899 } 5900 if ((scanFlags&SCAN_BOOTING) == 0) { 5901 // If we are not booting, we need to update any applications 5902 // that are clients of our shared library. If we are booting, 5903 // this will all be done once the scan is complete. 5904 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5905 } 5906 } 5907 } 5908 } 5909 5910 // We also need to dexopt any apps that are dependent on this library. Note that 5911 // if these fail, we should abort the install since installing the library will 5912 // result in some apps being broken. 5913 if (clientLibPkgs != null) { 5914 if ((scanFlags & SCAN_NO_DEX) == 0) { 5915 for (int i = 0; i < clientLibPkgs.size(); i++) { 5916 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5917 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5918 null /* instruction sets */, forceDex, 5919 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5920 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5921 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5922 "scanPackageLI failed to dexopt clientLibPkgs"); 5923 } 5924 } 5925 } 5926 } 5927 5928 // Request the ActivityManager to kill the process(only for existing packages) 5929 // so that we do not end up in a confused state while the user is still using the older 5930 // version of the application while the new one gets installed. 5931 if ((scanFlags & SCAN_REPLACING) != 0) { 5932 killApplication(pkg.applicationInfo.packageName, 5933 pkg.applicationInfo.uid, "update pkg"); 5934 } 5935 5936 // Also need to kill any apps that are dependent on the library. 5937 if (clientLibPkgs != null) { 5938 for (int i=0; i<clientLibPkgs.size(); i++) { 5939 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5940 killApplication(clientPkg.applicationInfo.packageName, 5941 clientPkg.applicationInfo.uid, "update lib"); 5942 } 5943 } 5944 5945 // writer 5946 synchronized (mPackages) { 5947 // We don't expect installation to fail beyond this point 5948 5949 // Add the new setting to mSettings 5950 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5951 // Add the new setting to mPackages 5952 mPackages.put(pkg.applicationInfo.packageName, pkg); 5953 // Make sure we don't accidentally delete its data. 5954 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5955 while (iter.hasNext()) { 5956 PackageCleanItem item = iter.next(); 5957 if (pkgName.equals(item.packageName)) { 5958 iter.remove(); 5959 } 5960 } 5961 5962 // Take care of first install / last update times. 5963 if (currentTime != 0) { 5964 if (pkgSetting.firstInstallTime == 0) { 5965 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5966 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5967 pkgSetting.lastUpdateTime = currentTime; 5968 } 5969 } else if (pkgSetting.firstInstallTime == 0) { 5970 // We need *something*. Take time time stamp of the file. 5971 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5972 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5973 if (scanFileTime != pkgSetting.timeStamp) { 5974 // A package on the system image has changed; consider this 5975 // to be an update. 5976 pkgSetting.lastUpdateTime = scanFileTime; 5977 } 5978 } 5979 5980 // Add the package's KeySets to the global KeySetManagerService 5981 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5982 try { 5983 // Old KeySetData no longer valid. 5984 ksms.removeAppKeySetDataLPw(pkg.packageName); 5985 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5986 if (pkg.mKeySetMapping != null) { 5987 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5988 pkg.mKeySetMapping.entrySet()) { 5989 if (entry.getValue() != null) { 5990 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5991 entry.getValue(), entry.getKey()); 5992 } 5993 } 5994 if (pkg.mUpgradeKeySets != null) { 5995 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5996 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5997 } 5998 } 5999 } 6000 } catch (NullPointerException e) { 6001 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6002 } catch (IllegalArgumentException e) { 6003 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6004 } 6005 6006 int N = pkg.providers.size(); 6007 StringBuilder r = null; 6008 int i; 6009 for (i=0; i<N; i++) { 6010 PackageParser.Provider p = pkg.providers.get(i); 6011 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6012 p.info.processName, pkg.applicationInfo.uid); 6013 mProviders.addProvider(p); 6014 p.syncable = p.info.isSyncable; 6015 if (p.info.authority != null) { 6016 String names[] = p.info.authority.split(";"); 6017 p.info.authority = null; 6018 for (int j = 0; j < names.length; j++) { 6019 if (j == 1 && p.syncable) { 6020 // We only want the first authority for a provider to possibly be 6021 // syncable, so if we already added this provider using a different 6022 // authority clear the syncable flag. We copy the provider before 6023 // changing it because the mProviders object contains a reference 6024 // to a provider that we don't want to change. 6025 // Only do this for the second authority since the resulting provider 6026 // object can be the same for all future authorities for this provider. 6027 p = new PackageParser.Provider(p); 6028 p.syncable = false; 6029 } 6030 if (!mProvidersByAuthority.containsKey(names[j])) { 6031 mProvidersByAuthority.put(names[j], p); 6032 if (p.info.authority == null) { 6033 p.info.authority = names[j]; 6034 } else { 6035 p.info.authority = p.info.authority + ";" + names[j]; 6036 } 6037 if (DEBUG_PACKAGE_SCANNING) { 6038 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6039 Log.d(TAG, "Registered content provider: " + names[j] 6040 + ", className = " + p.info.name + ", isSyncable = " 6041 + p.info.isSyncable); 6042 } 6043 } else { 6044 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6045 Slog.w(TAG, "Skipping provider name " + names[j] + 6046 " (in package " + pkg.applicationInfo.packageName + 6047 "): name already used by " 6048 + ((other != null && other.getComponentName() != null) 6049 ? other.getComponentName().getPackageName() : "?")); 6050 } 6051 } 6052 } 6053 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6054 if (r == null) { 6055 r = new StringBuilder(256); 6056 } else { 6057 r.append(' '); 6058 } 6059 r.append(p.info.name); 6060 } 6061 } 6062 if (r != null) { 6063 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6064 } 6065 6066 N = pkg.services.size(); 6067 r = null; 6068 for (i=0; i<N; i++) { 6069 PackageParser.Service s = pkg.services.get(i); 6070 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6071 s.info.processName, pkg.applicationInfo.uid); 6072 mServices.addService(s); 6073 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6074 if (r == null) { 6075 r = new StringBuilder(256); 6076 } else { 6077 r.append(' '); 6078 } 6079 r.append(s.info.name); 6080 } 6081 } 6082 if (r != null) { 6083 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6084 } 6085 6086 N = pkg.receivers.size(); 6087 r = null; 6088 for (i=0; i<N; i++) { 6089 PackageParser.Activity a = pkg.receivers.get(i); 6090 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6091 a.info.processName, pkg.applicationInfo.uid); 6092 mReceivers.addActivity(a, "receiver"); 6093 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6094 if (r == null) { 6095 r = new StringBuilder(256); 6096 } else { 6097 r.append(' '); 6098 } 6099 r.append(a.info.name); 6100 } 6101 } 6102 if (r != null) { 6103 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6104 } 6105 6106 N = pkg.activities.size(); 6107 r = null; 6108 for (i=0; i<N; i++) { 6109 PackageParser.Activity a = pkg.activities.get(i); 6110 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6111 a.info.processName, pkg.applicationInfo.uid); 6112 mActivities.addActivity(a, "activity"); 6113 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6114 if (r == null) { 6115 r = new StringBuilder(256); 6116 } else { 6117 r.append(' '); 6118 } 6119 r.append(a.info.name); 6120 } 6121 } 6122 if (r != null) { 6123 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6124 } 6125 6126 N = pkg.permissionGroups.size(); 6127 r = null; 6128 for (i=0; i<N; i++) { 6129 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6130 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6131 if (cur == null) { 6132 mPermissionGroups.put(pg.info.name, pg); 6133 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6134 if (r == null) { 6135 r = new StringBuilder(256); 6136 } else { 6137 r.append(' '); 6138 } 6139 r.append(pg.info.name); 6140 } 6141 } else { 6142 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6143 + pg.info.packageName + " ignored: original from " 6144 + cur.info.packageName); 6145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6146 if (r == null) { 6147 r = new StringBuilder(256); 6148 } else { 6149 r.append(' '); 6150 } 6151 r.append("DUP:"); 6152 r.append(pg.info.name); 6153 } 6154 } 6155 } 6156 if (r != null) { 6157 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6158 } 6159 6160 N = pkg.permissions.size(); 6161 r = null; 6162 for (i=0; i<N; i++) { 6163 PackageParser.Permission p = pkg.permissions.get(i); 6164 ArrayMap<String, BasePermission> permissionMap = 6165 p.tree ? mSettings.mPermissionTrees 6166 : mSettings.mPermissions; 6167 p.group = mPermissionGroups.get(p.info.group); 6168 if (p.info.group == null || p.group != null) { 6169 BasePermission bp = permissionMap.get(p.info.name); 6170 6171 // Allow system apps to redefine non-system permissions 6172 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6173 final boolean currentOwnerIsSystem = (bp.perm != null 6174 && isSystemApp(bp.perm.owner)); 6175 if (isSystemApp(p.owner)) { 6176 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6177 // It's a built-in permission and no owner, take ownership now 6178 bp.packageSetting = pkgSetting; 6179 bp.perm = p; 6180 bp.uid = pkg.applicationInfo.uid; 6181 bp.sourcePackage = p.info.packageName; 6182 } else if (!currentOwnerIsSystem) { 6183 String msg = "New decl " + p.owner + " of permission " 6184 + p.info.name + " is system; overriding " + bp.sourcePackage; 6185 reportSettingsProblem(Log.WARN, msg); 6186 bp = null; 6187 } 6188 } 6189 } 6190 6191 if (bp == null) { 6192 bp = new BasePermission(p.info.name, p.info.packageName, 6193 BasePermission.TYPE_NORMAL); 6194 permissionMap.put(p.info.name, bp); 6195 } 6196 6197 if (bp.perm == null) { 6198 if (bp.sourcePackage == null 6199 || bp.sourcePackage.equals(p.info.packageName)) { 6200 BasePermission tree = findPermissionTreeLP(p.info.name); 6201 if (tree == null 6202 || tree.sourcePackage.equals(p.info.packageName)) { 6203 bp.packageSetting = pkgSetting; 6204 bp.perm = p; 6205 bp.uid = pkg.applicationInfo.uid; 6206 bp.sourcePackage = p.info.packageName; 6207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6208 if (r == null) { 6209 r = new StringBuilder(256); 6210 } else { 6211 r.append(' '); 6212 } 6213 r.append(p.info.name); 6214 } 6215 } else { 6216 Slog.w(TAG, "Permission " + p.info.name + " from package " 6217 + p.info.packageName + " ignored: base tree " 6218 + tree.name + " is from package " 6219 + tree.sourcePackage); 6220 } 6221 } else { 6222 Slog.w(TAG, "Permission " + p.info.name + " from package " 6223 + p.info.packageName + " ignored: original from " 6224 + bp.sourcePackage); 6225 } 6226 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6227 if (r == null) { 6228 r = new StringBuilder(256); 6229 } else { 6230 r.append(' '); 6231 } 6232 r.append("DUP:"); 6233 r.append(p.info.name); 6234 } 6235 if (bp.perm == p) { 6236 bp.protectionLevel = p.info.protectionLevel; 6237 } 6238 } else { 6239 Slog.w(TAG, "Permission " + p.info.name + " from package " 6240 + p.info.packageName + " ignored: no group " 6241 + p.group); 6242 } 6243 } 6244 if (r != null) { 6245 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6246 } 6247 6248 N = pkg.instrumentation.size(); 6249 r = null; 6250 for (i=0; i<N; i++) { 6251 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6252 a.info.packageName = pkg.applicationInfo.packageName; 6253 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6254 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6255 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6256 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6257 a.info.dataDir = pkg.applicationInfo.dataDir; 6258 6259 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6260 // need other information about the application, like the ABI and what not ? 6261 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6262 mInstrumentation.put(a.getComponentName(), a); 6263 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6264 if (r == null) { 6265 r = new StringBuilder(256); 6266 } else { 6267 r.append(' '); 6268 } 6269 r.append(a.info.name); 6270 } 6271 } 6272 if (r != null) { 6273 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6274 } 6275 6276 if (pkg.protectedBroadcasts != null) { 6277 N = pkg.protectedBroadcasts.size(); 6278 for (i=0; i<N; i++) { 6279 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6280 } 6281 } 6282 6283 pkgSetting.setTimeStamp(scanFileTime); 6284 6285 // Create idmap files for pairs of (packages, overlay packages). 6286 // Note: "android", ie framework-res.apk, is handled by native layers. 6287 if (pkg.mOverlayTarget != null) { 6288 // This is an overlay package. 6289 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6290 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6291 mOverlays.put(pkg.mOverlayTarget, 6292 new ArrayMap<String, PackageParser.Package>()); 6293 } 6294 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6295 map.put(pkg.packageName, pkg); 6296 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6297 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6298 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6299 "scanPackageLI failed to createIdmap"); 6300 } 6301 } 6302 } else if (mOverlays.containsKey(pkg.packageName) && 6303 !pkg.packageName.equals("android")) { 6304 // This is a regular package, with one or more known overlay packages. 6305 createIdmapsForPackageLI(pkg); 6306 } 6307 } 6308 6309 return pkg; 6310 } 6311 6312 /** 6313 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6314 * i.e, so that all packages can be run inside a single process if required. 6315 * 6316 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6317 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6318 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6319 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6320 * updating a package that belongs to a shared user. 6321 * 6322 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6323 * adds unnecessary complexity. 6324 */ 6325 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6326 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6327 String requiredInstructionSet = null; 6328 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6329 requiredInstructionSet = VMRuntime.getInstructionSet( 6330 scannedPackage.applicationInfo.primaryCpuAbi); 6331 } 6332 6333 PackageSetting requirer = null; 6334 for (PackageSetting ps : packagesForUser) { 6335 // If packagesForUser contains scannedPackage, we skip it. This will happen 6336 // when scannedPackage is an update of an existing package. Without this check, 6337 // we will never be able to change the ABI of any package belonging to a shared 6338 // user, even if it's compatible with other packages. 6339 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6340 if (ps.primaryCpuAbiString == null) { 6341 continue; 6342 } 6343 6344 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6345 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6346 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6347 // this but there's not much we can do. 6348 String errorMessage = "Instruction set mismatch, " 6349 + ((requirer == null) ? "[caller]" : requirer) 6350 + " requires " + requiredInstructionSet + " whereas " + ps 6351 + " requires " + instructionSet; 6352 Slog.w(TAG, errorMessage); 6353 } 6354 6355 if (requiredInstructionSet == null) { 6356 requiredInstructionSet = instructionSet; 6357 requirer = ps; 6358 } 6359 } 6360 } 6361 6362 if (requiredInstructionSet != null) { 6363 String adjustedAbi; 6364 if (requirer != null) { 6365 // requirer != null implies that either scannedPackage was null or that scannedPackage 6366 // did not require an ABI, in which case we have to adjust scannedPackage to match 6367 // the ABI of the set (which is the same as requirer's ABI) 6368 adjustedAbi = requirer.primaryCpuAbiString; 6369 if (scannedPackage != null) { 6370 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6371 } 6372 } else { 6373 // requirer == null implies that we're updating all ABIs in the set to 6374 // match scannedPackage. 6375 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6376 } 6377 6378 for (PackageSetting ps : packagesForUser) { 6379 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6380 if (ps.primaryCpuAbiString != null) { 6381 continue; 6382 } 6383 6384 ps.primaryCpuAbiString = adjustedAbi; 6385 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6386 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6387 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6388 6389 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6390 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6391 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6392 ps.primaryCpuAbiString = null; 6393 ps.pkg.applicationInfo.primaryCpuAbi = null; 6394 return; 6395 } else { 6396 mInstaller.rmdex(ps.codePathString, 6397 getDexCodeInstructionSet(getPreferredInstructionSet())); 6398 } 6399 } 6400 } 6401 } 6402 } 6403 } 6404 6405 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6406 synchronized (mPackages) { 6407 mResolverReplaced = true; 6408 // Set up information for custom user intent resolution activity. 6409 mResolveActivity.applicationInfo = pkg.applicationInfo; 6410 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6411 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6412 mResolveActivity.processName = pkg.applicationInfo.packageName; 6413 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6414 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6415 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6416 mResolveActivity.theme = 0; 6417 mResolveActivity.exported = true; 6418 mResolveActivity.enabled = true; 6419 mResolveInfo.activityInfo = mResolveActivity; 6420 mResolveInfo.priority = 0; 6421 mResolveInfo.preferredOrder = 0; 6422 mResolveInfo.match = 0; 6423 mResolveComponentName = mCustomResolverComponentName; 6424 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6425 mResolveComponentName); 6426 } 6427 } 6428 6429 private static String calculateBundledApkRoot(final String codePathString) { 6430 final File codePath = new File(codePathString); 6431 final File codeRoot; 6432 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6433 codeRoot = Environment.getRootDirectory(); 6434 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6435 codeRoot = Environment.getOemDirectory(); 6436 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6437 codeRoot = Environment.getVendorDirectory(); 6438 } else { 6439 // Unrecognized code path; take its top real segment as the apk root: 6440 // e.g. /something/app/blah.apk => /something 6441 try { 6442 File f = codePath.getCanonicalFile(); 6443 File parent = f.getParentFile(); // non-null because codePath is a file 6444 File tmp; 6445 while ((tmp = parent.getParentFile()) != null) { 6446 f = parent; 6447 parent = tmp; 6448 } 6449 codeRoot = f; 6450 Slog.w(TAG, "Unrecognized code path " 6451 + codePath + " - using " + codeRoot); 6452 } catch (IOException e) { 6453 // Can't canonicalize the code path -- shenanigans? 6454 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6455 return Environment.getRootDirectory().getPath(); 6456 } 6457 } 6458 return codeRoot.getPath(); 6459 } 6460 6461 /** 6462 * Derive and set the location of native libraries for the given package, 6463 * which varies depending on where and how the package was installed. 6464 */ 6465 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6466 final ApplicationInfo info = pkg.applicationInfo; 6467 final String codePath = pkg.codePath; 6468 final File codeFile = new File(codePath); 6469 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6470 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6471 6472 info.nativeLibraryRootDir = null; 6473 info.nativeLibraryRootRequiresIsa = false; 6474 info.nativeLibraryDir = null; 6475 info.secondaryNativeLibraryDir = null; 6476 6477 if (isApkFile(codeFile)) { 6478 // Monolithic install 6479 if (bundledApp) { 6480 // If "/system/lib64/apkname" exists, assume that is the per-package 6481 // native library directory to use; otherwise use "/system/lib/apkname". 6482 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6483 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6484 getPrimaryInstructionSet(info)); 6485 6486 // This is a bundled system app so choose the path based on the ABI. 6487 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6488 // is just the default path. 6489 final String apkName = deriveCodePathName(codePath); 6490 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6491 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6492 apkName).getAbsolutePath(); 6493 6494 if (info.secondaryCpuAbi != null) { 6495 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6496 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6497 secondaryLibDir, apkName).getAbsolutePath(); 6498 } 6499 } else if (asecApp) { 6500 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6501 .getAbsolutePath(); 6502 } else { 6503 final String apkName = deriveCodePathName(codePath); 6504 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6505 .getAbsolutePath(); 6506 } 6507 6508 info.nativeLibraryRootRequiresIsa = false; 6509 info.nativeLibraryDir = info.nativeLibraryRootDir; 6510 } else { 6511 // Cluster install 6512 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6513 info.nativeLibraryRootRequiresIsa = true; 6514 6515 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6516 getPrimaryInstructionSet(info)).getAbsolutePath(); 6517 6518 if (info.secondaryCpuAbi != null) { 6519 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6520 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6521 } 6522 } 6523 } 6524 6525 /** 6526 * Calculate the abis and roots for a bundled app. These can uniquely 6527 * be determined from the contents of the system partition, i.e whether 6528 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6529 * of this information, and instead assume that the system was built 6530 * sensibly. 6531 */ 6532 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6533 PackageSetting pkgSetting) { 6534 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6535 6536 // If "/system/lib64/apkname" exists, assume that is the per-package 6537 // native library directory to use; otherwise use "/system/lib/apkname". 6538 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6539 setBundledAppAbi(pkg, apkRoot, apkName); 6540 // pkgSetting might be null during rescan following uninstall of updates 6541 // to a bundled app, so accommodate that possibility. The settings in 6542 // that case will be established later from the parsed package. 6543 // 6544 // If the settings aren't null, sync them up with what we've just derived. 6545 // note that apkRoot isn't stored in the package settings. 6546 if (pkgSetting != null) { 6547 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6548 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6549 } 6550 } 6551 6552 /** 6553 * Deduces the ABI of a bundled app and sets the relevant fields on the 6554 * parsed pkg object. 6555 * 6556 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6557 * under which system libraries are installed. 6558 * @param apkName the name of the installed package. 6559 */ 6560 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6561 final File codeFile = new File(pkg.codePath); 6562 6563 final boolean has64BitLibs; 6564 final boolean has32BitLibs; 6565 if (isApkFile(codeFile)) { 6566 // Monolithic install 6567 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6568 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6569 } else { 6570 // Cluster install 6571 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6572 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6573 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6574 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6575 has64BitLibs = (new File(rootDir, isa)).exists(); 6576 } else { 6577 has64BitLibs = false; 6578 } 6579 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6580 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6581 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6582 has32BitLibs = (new File(rootDir, isa)).exists(); 6583 } else { 6584 has32BitLibs = false; 6585 } 6586 } 6587 6588 if (has64BitLibs && !has32BitLibs) { 6589 // The package has 64 bit libs, but not 32 bit libs. Its primary 6590 // ABI should be 64 bit. We can safely assume here that the bundled 6591 // native libraries correspond to the most preferred ABI in the list. 6592 6593 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6594 pkg.applicationInfo.secondaryCpuAbi = null; 6595 } else if (has32BitLibs && !has64BitLibs) { 6596 // The package has 32 bit libs but not 64 bit libs. Its primary 6597 // ABI should be 32 bit. 6598 6599 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6600 pkg.applicationInfo.secondaryCpuAbi = null; 6601 } else if (has32BitLibs && has64BitLibs) { 6602 // The application has both 64 and 32 bit bundled libraries. We check 6603 // here that the app declares multiArch support, and warn if it doesn't. 6604 // 6605 // We will be lenient here and record both ABIs. The primary will be the 6606 // ABI that's higher on the list, i.e, a device that's configured to prefer 6607 // 64 bit apps will see a 64 bit primary ABI, 6608 6609 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6610 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6611 } 6612 6613 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6614 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6615 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6616 } else { 6617 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6618 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6619 } 6620 } else { 6621 pkg.applicationInfo.primaryCpuAbi = null; 6622 pkg.applicationInfo.secondaryCpuAbi = null; 6623 } 6624 } 6625 6626 private void killApplication(String pkgName, int appId, String reason) { 6627 // Request the ActivityManager to kill the process(only for existing packages) 6628 // so that we do not end up in a confused state while the user is still using the older 6629 // version of the application while the new one gets installed. 6630 IActivityManager am = ActivityManagerNative.getDefault(); 6631 if (am != null) { 6632 try { 6633 am.killApplicationWithAppId(pkgName, appId, reason); 6634 } catch (RemoteException e) { 6635 } 6636 } 6637 } 6638 6639 void removePackageLI(PackageSetting ps, boolean chatty) { 6640 if (DEBUG_INSTALL) { 6641 if (chatty) 6642 Log.d(TAG, "Removing package " + ps.name); 6643 } 6644 6645 // writer 6646 synchronized (mPackages) { 6647 mPackages.remove(ps.name); 6648 final PackageParser.Package pkg = ps.pkg; 6649 if (pkg != null) { 6650 cleanPackageDataStructuresLILPw(pkg, chatty); 6651 } 6652 } 6653 } 6654 6655 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6656 if (DEBUG_INSTALL) { 6657 if (chatty) 6658 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6659 } 6660 6661 // writer 6662 synchronized (mPackages) { 6663 mPackages.remove(pkg.applicationInfo.packageName); 6664 cleanPackageDataStructuresLILPw(pkg, chatty); 6665 } 6666 } 6667 6668 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6669 int N = pkg.providers.size(); 6670 StringBuilder r = null; 6671 int i; 6672 for (i=0; i<N; i++) { 6673 PackageParser.Provider p = pkg.providers.get(i); 6674 mProviders.removeProvider(p); 6675 if (p.info.authority == null) { 6676 6677 /* There was another ContentProvider with this authority when 6678 * this app was installed so this authority is null, 6679 * Ignore it as we don't have to unregister the provider. 6680 */ 6681 continue; 6682 } 6683 String names[] = p.info.authority.split(";"); 6684 for (int j = 0; j < names.length; j++) { 6685 if (mProvidersByAuthority.get(names[j]) == p) { 6686 mProvidersByAuthority.remove(names[j]); 6687 if (DEBUG_REMOVE) { 6688 if (chatty) 6689 Log.d(TAG, "Unregistered content provider: " + names[j] 6690 + ", className = " + p.info.name + ", isSyncable = " 6691 + p.info.isSyncable); 6692 } 6693 } 6694 } 6695 if (DEBUG_REMOVE && chatty) { 6696 if (r == null) { 6697 r = new StringBuilder(256); 6698 } else { 6699 r.append(' '); 6700 } 6701 r.append(p.info.name); 6702 } 6703 } 6704 if (r != null) { 6705 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6706 } 6707 6708 N = pkg.services.size(); 6709 r = null; 6710 for (i=0; i<N; i++) { 6711 PackageParser.Service s = pkg.services.get(i); 6712 mServices.removeService(s); 6713 if (chatty) { 6714 if (r == null) { 6715 r = new StringBuilder(256); 6716 } else { 6717 r.append(' '); 6718 } 6719 r.append(s.info.name); 6720 } 6721 } 6722 if (r != null) { 6723 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6724 } 6725 6726 N = pkg.receivers.size(); 6727 r = null; 6728 for (i=0; i<N; i++) { 6729 PackageParser.Activity a = pkg.receivers.get(i); 6730 mReceivers.removeActivity(a, "receiver"); 6731 if (DEBUG_REMOVE && chatty) { 6732 if (r == null) { 6733 r = new StringBuilder(256); 6734 } else { 6735 r.append(' '); 6736 } 6737 r.append(a.info.name); 6738 } 6739 } 6740 if (r != null) { 6741 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6742 } 6743 6744 N = pkg.activities.size(); 6745 r = null; 6746 for (i=0; i<N; i++) { 6747 PackageParser.Activity a = pkg.activities.get(i); 6748 mActivities.removeActivity(a, "activity"); 6749 if (DEBUG_REMOVE && chatty) { 6750 if (r == null) { 6751 r = new StringBuilder(256); 6752 } else { 6753 r.append(' '); 6754 } 6755 r.append(a.info.name); 6756 } 6757 } 6758 if (r != null) { 6759 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6760 } 6761 6762 N = pkg.permissions.size(); 6763 r = null; 6764 for (i=0; i<N; i++) { 6765 PackageParser.Permission p = pkg.permissions.get(i); 6766 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6767 if (bp == null) { 6768 bp = mSettings.mPermissionTrees.get(p.info.name); 6769 } 6770 if (bp != null && bp.perm == p) { 6771 bp.perm = null; 6772 if (DEBUG_REMOVE && chatty) { 6773 if (r == null) { 6774 r = new StringBuilder(256); 6775 } else { 6776 r.append(' '); 6777 } 6778 r.append(p.info.name); 6779 } 6780 } 6781 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6782 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6783 if (appOpPerms != null) { 6784 appOpPerms.remove(pkg.packageName); 6785 } 6786 } 6787 } 6788 if (r != null) { 6789 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6790 } 6791 6792 N = pkg.requestedPermissions.size(); 6793 r = null; 6794 for (i=0; i<N; i++) { 6795 String perm = pkg.requestedPermissions.get(i); 6796 BasePermission bp = mSettings.mPermissions.get(perm); 6797 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6798 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6799 if (appOpPerms != null) { 6800 appOpPerms.remove(pkg.packageName); 6801 if (appOpPerms.isEmpty()) { 6802 mAppOpPermissionPackages.remove(perm); 6803 } 6804 } 6805 } 6806 } 6807 if (r != null) { 6808 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6809 } 6810 6811 N = pkg.instrumentation.size(); 6812 r = null; 6813 for (i=0; i<N; i++) { 6814 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6815 mInstrumentation.remove(a.getComponentName()); 6816 if (DEBUG_REMOVE && chatty) { 6817 if (r == null) { 6818 r = new StringBuilder(256); 6819 } else { 6820 r.append(' '); 6821 } 6822 r.append(a.info.name); 6823 } 6824 } 6825 if (r != null) { 6826 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6827 } 6828 6829 r = null; 6830 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6831 // Only system apps can hold shared libraries. 6832 if (pkg.libraryNames != null) { 6833 for (i=0; i<pkg.libraryNames.size(); i++) { 6834 String name = pkg.libraryNames.get(i); 6835 SharedLibraryEntry cur = mSharedLibraries.get(name); 6836 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6837 mSharedLibraries.remove(name); 6838 if (DEBUG_REMOVE && chatty) { 6839 if (r == null) { 6840 r = new StringBuilder(256); 6841 } else { 6842 r.append(' '); 6843 } 6844 r.append(name); 6845 } 6846 } 6847 } 6848 } 6849 } 6850 if (r != null) { 6851 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6852 } 6853 } 6854 6855 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6856 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6857 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6858 return true; 6859 } 6860 } 6861 return false; 6862 } 6863 6864 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6865 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6866 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6867 6868 private void updatePermissionsLPw(String changingPkg, 6869 PackageParser.Package pkgInfo, int flags) { 6870 // Make sure there are no dangling permission trees. 6871 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6872 while (it.hasNext()) { 6873 final BasePermission bp = it.next(); 6874 if (bp.packageSetting == null) { 6875 // We may not yet have parsed the package, so just see if 6876 // we still know about its settings. 6877 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6878 } 6879 if (bp.packageSetting == null) { 6880 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6881 + " from package " + bp.sourcePackage); 6882 it.remove(); 6883 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6884 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6885 Slog.i(TAG, "Removing old permission tree: " + bp.name 6886 + " from package " + bp.sourcePackage); 6887 flags |= UPDATE_PERMISSIONS_ALL; 6888 it.remove(); 6889 } 6890 } 6891 } 6892 6893 // Make sure all dynamic permissions have been assigned to a package, 6894 // and make sure there are no dangling permissions. 6895 it = mSettings.mPermissions.values().iterator(); 6896 while (it.hasNext()) { 6897 final BasePermission bp = it.next(); 6898 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6899 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6900 + bp.name + " pkg=" + bp.sourcePackage 6901 + " info=" + bp.pendingInfo); 6902 if (bp.packageSetting == null && bp.pendingInfo != null) { 6903 final BasePermission tree = findPermissionTreeLP(bp.name); 6904 if (tree != null && tree.perm != null) { 6905 bp.packageSetting = tree.packageSetting; 6906 bp.perm = new PackageParser.Permission(tree.perm.owner, 6907 new PermissionInfo(bp.pendingInfo)); 6908 bp.perm.info.packageName = tree.perm.info.packageName; 6909 bp.perm.info.name = bp.name; 6910 bp.uid = tree.uid; 6911 } 6912 } 6913 } 6914 if (bp.packageSetting == null) { 6915 // We may not yet have parsed the package, so just see if 6916 // we still know about its settings. 6917 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6918 } 6919 if (bp.packageSetting == null) { 6920 Slog.w(TAG, "Removing dangling permission: " + bp.name 6921 + " from package " + bp.sourcePackage); 6922 it.remove(); 6923 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6924 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6925 Slog.i(TAG, "Removing old permission: " + bp.name 6926 + " from package " + bp.sourcePackage); 6927 flags |= UPDATE_PERMISSIONS_ALL; 6928 it.remove(); 6929 } 6930 } 6931 } 6932 6933 // Now update the permissions for all packages, in particular 6934 // replace the granted permissions of the system packages. 6935 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6936 for (PackageParser.Package pkg : mPackages.values()) { 6937 if (pkg != pkgInfo) { 6938 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6939 changingPkg); 6940 } 6941 } 6942 } 6943 6944 if (pkgInfo != null) { 6945 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6946 } 6947 } 6948 6949 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6950 String packageOfInterest) { 6951 // IMPORTANT: There are two types of permissions: install and runtime. 6952 // Install time permissions are granted when the app is installed to 6953 // all device users and users added in the future. Runtime permissions 6954 // are granted at runtime explicitly to specific users. Normal and signature 6955 // protected permissions are install time permissions. Dangerous permissions 6956 // are install permissions if the app's target SDK is Lollipop MR1 or older, 6957 // otherwise they are runtime permissions. This function does not manage 6958 // runtime permissions except for the case an app targeting Lollipop MR1 6959 // being upgraded to target a newer SDK, in which case dangerous permissions 6960 // are transformed from install time to runtime ones. 6961 6962 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6963 if (ps == null) { 6964 return; 6965 } 6966 6967 PermissionsState permissionsState = ps.getPermissionsState(); 6968 PermissionsState origPermissions = permissionsState; 6969 6970 boolean changedPermission = false; 6971 6972 if (replace) { 6973 ps.permissionsFixed = false; 6974 origPermissions = new PermissionsState(permissionsState); 6975 permissionsState.reset(); 6976 } 6977 6978 permissionsState.setGlobalGids(mGlobalGids); 6979 6980 final int N = pkg.requestedPermissions.size(); 6981 for (int i=0; i<N; i++) { 6982 final String name = pkg.requestedPermissions.get(i); 6983 final BasePermission bp = mSettings.mPermissions.get(name); 6984 6985 if (DEBUG_INSTALL) { 6986 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6987 } 6988 6989 if (bp == null || bp.packageSetting == null) { 6990 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6991 Slog.w(TAG, "Unknown permission " + name 6992 + " in package " + pkg.packageName); 6993 } 6994 continue; 6995 } 6996 6997 final String perm = bp.name; 6998 boolean allowedSig = false; 6999 int grant = GRANT_DENIED; 7000 7001 // Keep track of app op permissions. 7002 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7003 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7004 if (pkgs == null) { 7005 pkgs = new ArraySet<>(); 7006 mAppOpPermissionPackages.put(bp.name, pkgs); 7007 } 7008 pkgs.add(pkg.packageName); 7009 } 7010 7011 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7012 switch (level) { 7013 case PermissionInfo.PROTECTION_NORMAL: { 7014 // For all apps normal permissions are install time ones. 7015 grant = GRANT_INSTALL; 7016 } break; 7017 7018 case PermissionInfo.PROTECTION_DANGEROUS: { 7019 if (!RUNTIME_PERMISSIONS_ENABLED 7020 || pkg.applicationInfo.targetSdkVersion 7021 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7022 // For legacy apps dangerous permissions are install time ones. 7023 grant = GRANT_INSTALL; 7024 } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7025 // For modern system apps dangerous permissions are install time ones. 7026 grant = GRANT_INSTALL; 7027 } else { 7028 if (origPermissions.hasInstallPermission(bp.name)) { 7029 // For legacy apps that became modern, install becomes runtime. 7030 grant = GRANT_UPGRADE; 7031 } else if (replace) { 7032 // For upgraded modern apps keep runtime permissions unchanged. 7033 grant = GRANT_RUNTIME; 7034 } 7035 } 7036 } break; 7037 7038 case PermissionInfo.PROTECTION_SIGNATURE: { 7039 // For all apps signature permissions are install time ones. 7040 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7041 if (allowedSig) { 7042 grant = GRANT_INSTALL; 7043 } 7044 } break; 7045 } 7046 7047 if (DEBUG_INSTALL) { 7048 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7049 } 7050 7051 if (grant != GRANT_DENIED) { 7052 if (!isSystemApp(ps) && ps.permissionsFixed) { 7053 // If this is an existing, non-system package, then 7054 // we can't add any new permissions to it. 7055 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7056 // Except... if this is a permission that was added 7057 // to the platform (note: need to only do this when 7058 // updating the platform). 7059 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7060 grant = GRANT_DENIED; 7061 } 7062 } 7063 } 7064 7065 switch (grant) { 7066 case GRANT_INSTALL: { 7067 // Grant an install permission. 7068 if (permissionsState.grantInstallPermission(bp) != 7069 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7070 changedPermission = true; 7071 } 7072 } break; 7073 7074 case GRANT_RUNTIME: { 7075 // Grant previously granted runtime permissions. 7076 for (int userId : UserManagerService.getInstance().getUserIds()) { 7077 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7078 if (permissionsState.grantRuntimePermission(bp, userId) != 7079 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7080 changedPermission = true; 7081 } 7082 } 7083 } 7084 } break; 7085 7086 case GRANT_UPGRADE: { 7087 // Grant runtime permissions for a previously held install permission. 7088 permissionsState.revokeInstallPermission(bp); 7089 for (int userId : UserManagerService.getInstance().getUserIds()) { 7090 if (permissionsState.grantRuntimePermission(bp, userId) != 7091 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7092 changedPermission = true; 7093 } 7094 } 7095 } break; 7096 7097 default: { 7098 if (packageOfInterest == null 7099 || packageOfInterest.equals(pkg.packageName)) { 7100 Slog.w(TAG, "Not granting permission " + perm 7101 + " to package " + pkg.packageName 7102 + " because it was previously installed without"); 7103 } 7104 } break; 7105 } 7106 } else { 7107 if (permissionsState.revokeInstallPermission(bp) != 7108 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7109 changedPermission = true; 7110 Slog.i(TAG, "Un-granting permission " + perm 7111 + " from package " + pkg.packageName 7112 + " (protectionLevel=" + bp.protectionLevel 7113 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7114 + ")"); 7115 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7116 // Don't print warning for app op permissions, since it is fine for them 7117 // not to be granted, there is a UI for the user to decide. 7118 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7119 Slog.w(TAG, "Not granting permission " + perm 7120 + " to package " + pkg.packageName 7121 + " (protectionLevel=" + bp.protectionLevel 7122 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7123 + ")"); 7124 } 7125 } 7126 } 7127 } 7128 7129 if ((changedPermission || replace) && !ps.permissionsFixed && 7130 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7131 // This is the first that we have heard about this package, so the 7132 // permissions we have now selected are fixed until explicitly 7133 // changed. 7134 ps.permissionsFixed = true; 7135 } 7136 } 7137 7138 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7139 boolean allowed = false; 7140 final int NP = PackageParser.NEW_PERMISSIONS.length; 7141 for (int ip=0; ip<NP; ip++) { 7142 final PackageParser.NewPermissionInfo npi 7143 = PackageParser.NEW_PERMISSIONS[ip]; 7144 if (npi.name.equals(perm) 7145 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7146 allowed = true; 7147 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7148 + pkg.packageName); 7149 break; 7150 } 7151 } 7152 return allowed; 7153 } 7154 7155 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7156 BasePermission bp, PermissionsState origPermissions) { 7157 boolean allowed; 7158 allowed = (compareSignatures( 7159 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7160 == PackageManager.SIGNATURE_MATCH) 7161 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7162 == PackageManager.SIGNATURE_MATCH); 7163 if (!allowed && (bp.protectionLevel 7164 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7165 if (isSystemApp(pkg)) { 7166 // For updated system applications, a system permission 7167 // is granted only if it had been defined by the original application. 7168 if (isUpdatedSystemApp(pkg)) { 7169 final PackageSetting sysPs = mSettings 7170 .getDisabledSystemPkgLPr(pkg.packageName); 7171 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7172 // If the original was granted this permission, we take 7173 // that grant decision as read and propagate it to the 7174 // update. 7175 if (sysPs.isPrivileged()) { 7176 allowed = true; 7177 } 7178 } else { 7179 // The system apk may have been updated with an older 7180 // version of the one on the data partition, but which 7181 // granted a new system permission that it didn't have 7182 // before. In this case we do want to allow the app to 7183 // now get the new permission if the ancestral apk is 7184 // privileged to get it. 7185 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7186 for (int j=0; 7187 j<sysPs.pkg.requestedPermissions.size(); j++) { 7188 if (perm.equals( 7189 sysPs.pkg.requestedPermissions.get(j))) { 7190 allowed = true; 7191 break; 7192 } 7193 } 7194 } 7195 } 7196 } else { 7197 allowed = isPrivilegedApp(pkg); 7198 } 7199 } 7200 } 7201 if (!allowed && (bp.protectionLevel 7202 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7203 // For development permissions, a development permission 7204 // is granted only if it was already granted. 7205 allowed = origPermissions.hasInstallPermission(perm); 7206 } 7207 return allowed; 7208 } 7209 7210 final class ActivityIntentResolver 7211 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7212 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7213 boolean defaultOnly, int userId) { 7214 if (!sUserManager.exists(userId)) return null; 7215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7216 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7217 } 7218 7219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7220 int userId) { 7221 if (!sUserManager.exists(userId)) return null; 7222 mFlags = flags; 7223 return super.queryIntent(intent, resolvedType, 7224 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7225 } 7226 7227 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7228 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7229 if (!sUserManager.exists(userId)) return null; 7230 if (packageActivities == null) { 7231 return null; 7232 } 7233 mFlags = flags; 7234 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7235 final int N = packageActivities.size(); 7236 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7237 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7238 7239 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7240 for (int i = 0; i < N; ++i) { 7241 intentFilters = packageActivities.get(i).intents; 7242 if (intentFilters != null && intentFilters.size() > 0) { 7243 PackageParser.ActivityIntentInfo[] array = 7244 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7245 intentFilters.toArray(array); 7246 listCut.add(array); 7247 } 7248 } 7249 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7250 } 7251 7252 public final void addActivity(PackageParser.Activity a, String type) { 7253 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7254 mActivities.put(a.getComponentName(), a); 7255 if (DEBUG_SHOW_INFO) 7256 Log.v( 7257 TAG, " " + type + " " + 7258 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7259 if (DEBUG_SHOW_INFO) 7260 Log.v(TAG, " Class=" + a.info.name); 7261 final int NI = a.intents.size(); 7262 for (int j=0; j<NI; j++) { 7263 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7264 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7265 intent.setPriority(0); 7266 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7267 + a.className + " with priority > 0, forcing to 0"); 7268 } 7269 if (DEBUG_SHOW_INFO) { 7270 Log.v(TAG, " IntentFilter:"); 7271 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7272 } 7273 if (!intent.debugCheck()) { 7274 Log.w(TAG, "==> For Activity " + a.info.name); 7275 } 7276 addFilter(intent); 7277 } 7278 } 7279 7280 public final void removeActivity(PackageParser.Activity a, String type) { 7281 mActivities.remove(a.getComponentName()); 7282 if (DEBUG_SHOW_INFO) { 7283 Log.v(TAG, " " + type + " " 7284 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7285 : a.info.name) + ":"); 7286 Log.v(TAG, " Class=" + a.info.name); 7287 } 7288 final int NI = a.intents.size(); 7289 for (int j=0; j<NI; j++) { 7290 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7291 if (DEBUG_SHOW_INFO) { 7292 Log.v(TAG, " IntentFilter:"); 7293 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7294 } 7295 removeFilter(intent); 7296 } 7297 } 7298 7299 @Override 7300 protected boolean allowFilterResult( 7301 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7302 ActivityInfo filterAi = filter.activity.info; 7303 for (int i=dest.size()-1; i>=0; i--) { 7304 ActivityInfo destAi = dest.get(i).activityInfo; 7305 if (destAi.name == filterAi.name 7306 && destAi.packageName == filterAi.packageName) { 7307 return false; 7308 } 7309 } 7310 return true; 7311 } 7312 7313 @Override 7314 protected ActivityIntentInfo[] newArray(int size) { 7315 return new ActivityIntentInfo[size]; 7316 } 7317 7318 @Override 7319 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7320 if (!sUserManager.exists(userId)) return true; 7321 PackageParser.Package p = filter.activity.owner; 7322 if (p != null) { 7323 PackageSetting ps = (PackageSetting)p.mExtras; 7324 if (ps != null) { 7325 // System apps are never considered stopped for purposes of 7326 // filtering, because there may be no way for the user to 7327 // actually re-launch them. 7328 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7329 && ps.getStopped(userId); 7330 } 7331 } 7332 return false; 7333 } 7334 7335 @Override 7336 protected boolean isPackageForFilter(String packageName, 7337 PackageParser.ActivityIntentInfo info) { 7338 return packageName.equals(info.activity.owner.packageName); 7339 } 7340 7341 @Override 7342 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7343 int match, int userId) { 7344 if (!sUserManager.exists(userId)) return null; 7345 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7346 return null; 7347 } 7348 final PackageParser.Activity activity = info.activity; 7349 if (mSafeMode && (activity.info.applicationInfo.flags 7350 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7351 return null; 7352 } 7353 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7354 if (ps == null) { 7355 return null; 7356 } 7357 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7358 ps.readUserState(userId), userId); 7359 if (ai == null) { 7360 return null; 7361 } 7362 final ResolveInfo res = new ResolveInfo(); 7363 res.activityInfo = ai; 7364 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7365 res.filter = info; 7366 } 7367 res.priority = info.getPriority(); 7368 res.preferredOrder = activity.owner.mPreferredOrder; 7369 //System.out.println("Result: " + res.activityInfo.className + 7370 // " = " + res.priority); 7371 res.match = match; 7372 res.isDefault = info.hasDefault; 7373 res.labelRes = info.labelRes; 7374 res.nonLocalizedLabel = info.nonLocalizedLabel; 7375 if (userNeedsBadging(userId)) { 7376 res.noResourceId = true; 7377 } else { 7378 res.icon = info.icon; 7379 } 7380 res.system = isSystemApp(res.activityInfo.applicationInfo); 7381 return res; 7382 } 7383 7384 @Override 7385 protected void sortResults(List<ResolveInfo> results) { 7386 Collections.sort(results, mResolvePrioritySorter); 7387 } 7388 7389 @Override 7390 protected void dumpFilter(PrintWriter out, String prefix, 7391 PackageParser.ActivityIntentInfo filter) { 7392 out.print(prefix); out.print( 7393 Integer.toHexString(System.identityHashCode(filter.activity))); 7394 out.print(' '); 7395 filter.activity.printComponentShortName(out); 7396 out.print(" filter "); 7397 out.println(Integer.toHexString(System.identityHashCode(filter))); 7398 } 7399 7400 @Override 7401 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7402 return filter.activity; 7403 } 7404 7405 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7406 PackageParser.Activity activity = (PackageParser.Activity)label; 7407 out.print(prefix); out.print( 7408 Integer.toHexString(System.identityHashCode(activity))); 7409 out.print(' '); 7410 activity.printComponentShortName(out); 7411 if (count > 1) { 7412 out.print(" ("); out.print(count); out.print(" filters)"); 7413 } 7414 out.println(); 7415 } 7416 7417// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7418// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7419// final List<ResolveInfo> retList = Lists.newArrayList(); 7420// while (i.hasNext()) { 7421// final ResolveInfo resolveInfo = i.next(); 7422// if (isEnabledLP(resolveInfo.activityInfo)) { 7423// retList.add(resolveInfo); 7424// } 7425// } 7426// return retList; 7427// } 7428 7429 // Keys are String (activity class name), values are Activity. 7430 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7431 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7432 private int mFlags; 7433 } 7434 7435 private final class ServiceIntentResolver 7436 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7437 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7438 boolean defaultOnly, int userId) { 7439 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7440 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7441 } 7442 7443 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7444 int userId) { 7445 if (!sUserManager.exists(userId)) return null; 7446 mFlags = flags; 7447 return super.queryIntent(intent, resolvedType, 7448 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7449 } 7450 7451 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7452 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7453 if (!sUserManager.exists(userId)) return null; 7454 if (packageServices == null) { 7455 return null; 7456 } 7457 mFlags = flags; 7458 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7459 final int N = packageServices.size(); 7460 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7461 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7462 7463 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7464 for (int i = 0; i < N; ++i) { 7465 intentFilters = packageServices.get(i).intents; 7466 if (intentFilters != null && intentFilters.size() > 0) { 7467 PackageParser.ServiceIntentInfo[] array = 7468 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7469 intentFilters.toArray(array); 7470 listCut.add(array); 7471 } 7472 } 7473 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7474 } 7475 7476 public final void addService(PackageParser.Service s) { 7477 mServices.put(s.getComponentName(), s); 7478 if (DEBUG_SHOW_INFO) { 7479 Log.v(TAG, " " 7480 + (s.info.nonLocalizedLabel != null 7481 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7482 Log.v(TAG, " Class=" + s.info.name); 7483 } 7484 final int NI = s.intents.size(); 7485 int j; 7486 for (j=0; j<NI; j++) { 7487 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7488 if (DEBUG_SHOW_INFO) { 7489 Log.v(TAG, " IntentFilter:"); 7490 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7491 } 7492 if (!intent.debugCheck()) { 7493 Log.w(TAG, "==> For Service " + s.info.name); 7494 } 7495 addFilter(intent); 7496 } 7497 } 7498 7499 public final void removeService(PackageParser.Service s) { 7500 mServices.remove(s.getComponentName()); 7501 if (DEBUG_SHOW_INFO) { 7502 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7503 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7504 Log.v(TAG, " Class=" + s.info.name); 7505 } 7506 final int NI = s.intents.size(); 7507 int j; 7508 for (j=0; j<NI; j++) { 7509 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7510 if (DEBUG_SHOW_INFO) { 7511 Log.v(TAG, " IntentFilter:"); 7512 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7513 } 7514 removeFilter(intent); 7515 } 7516 } 7517 7518 @Override 7519 protected boolean allowFilterResult( 7520 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7521 ServiceInfo filterSi = filter.service.info; 7522 for (int i=dest.size()-1; i>=0; i--) { 7523 ServiceInfo destAi = dest.get(i).serviceInfo; 7524 if (destAi.name == filterSi.name 7525 && destAi.packageName == filterSi.packageName) { 7526 return false; 7527 } 7528 } 7529 return true; 7530 } 7531 7532 @Override 7533 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7534 return new PackageParser.ServiceIntentInfo[size]; 7535 } 7536 7537 @Override 7538 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7539 if (!sUserManager.exists(userId)) return true; 7540 PackageParser.Package p = filter.service.owner; 7541 if (p != null) { 7542 PackageSetting ps = (PackageSetting)p.mExtras; 7543 if (ps != null) { 7544 // System apps are never considered stopped for purposes of 7545 // filtering, because there may be no way for the user to 7546 // actually re-launch them. 7547 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7548 && ps.getStopped(userId); 7549 } 7550 } 7551 return false; 7552 } 7553 7554 @Override 7555 protected boolean isPackageForFilter(String packageName, 7556 PackageParser.ServiceIntentInfo info) { 7557 return packageName.equals(info.service.owner.packageName); 7558 } 7559 7560 @Override 7561 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7562 int match, int userId) { 7563 if (!sUserManager.exists(userId)) return null; 7564 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7565 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7566 return null; 7567 } 7568 final PackageParser.Service service = info.service; 7569 if (mSafeMode && (service.info.applicationInfo.flags 7570 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7571 return null; 7572 } 7573 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7574 if (ps == null) { 7575 return null; 7576 } 7577 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7578 ps.readUserState(userId), userId); 7579 if (si == null) { 7580 return null; 7581 } 7582 final ResolveInfo res = new ResolveInfo(); 7583 res.serviceInfo = si; 7584 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7585 res.filter = filter; 7586 } 7587 res.priority = info.getPriority(); 7588 res.preferredOrder = service.owner.mPreferredOrder; 7589 //System.out.println("Result: " + res.activityInfo.className + 7590 // " = " + res.priority); 7591 res.match = match; 7592 res.isDefault = info.hasDefault; 7593 res.labelRes = info.labelRes; 7594 res.nonLocalizedLabel = info.nonLocalizedLabel; 7595 res.icon = info.icon; 7596 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7597 return res; 7598 } 7599 7600 @Override 7601 protected void sortResults(List<ResolveInfo> results) { 7602 Collections.sort(results, mResolvePrioritySorter); 7603 } 7604 7605 @Override 7606 protected void dumpFilter(PrintWriter out, String prefix, 7607 PackageParser.ServiceIntentInfo filter) { 7608 out.print(prefix); out.print( 7609 Integer.toHexString(System.identityHashCode(filter.service))); 7610 out.print(' '); 7611 filter.service.printComponentShortName(out); 7612 out.print(" filter "); 7613 out.println(Integer.toHexString(System.identityHashCode(filter))); 7614 } 7615 7616 @Override 7617 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7618 return filter.service; 7619 } 7620 7621 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7622 PackageParser.Service service = (PackageParser.Service)label; 7623 out.print(prefix); out.print( 7624 Integer.toHexString(System.identityHashCode(service))); 7625 out.print(' '); 7626 service.printComponentShortName(out); 7627 if (count > 1) { 7628 out.print(" ("); out.print(count); out.print(" filters)"); 7629 } 7630 out.println(); 7631 } 7632 7633// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7634// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7635// final List<ResolveInfo> retList = Lists.newArrayList(); 7636// while (i.hasNext()) { 7637// final ResolveInfo resolveInfo = (ResolveInfo) i; 7638// if (isEnabledLP(resolveInfo.serviceInfo)) { 7639// retList.add(resolveInfo); 7640// } 7641// } 7642// return retList; 7643// } 7644 7645 // Keys are String (activity class name), values are Activity. 7646 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7647 = new ArrayMap<ComponentName, PackageParser.Service>(); 7648 private int mFlags; 7649 }; 7650 7651 private final class ProviderIntentResolver 7652 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7653 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7654 boolean defaultOnly, int userId) { 7655 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7656 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7657 } 7658 7659 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7660 int userId) { 7661 if (!sUserManager.exists(userId)) 7662 return null; 7663 mFlags = flags; 7664 return super.queryIntent(intent, resolvedType, 7665 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7666 } 7667 7668 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7669 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7670 if (!sUserManager.exists(userId)) 7671 return null; 7672 if (packageProviders == null) { 7673 return null; 7674 } 7675 mFlags = flags; 7676 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7677 final int N = packageProviders.size(); 7678 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7679 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7680 7681 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7682 for (int i = 0; i < N; ++i) { 7683 intentFilters = packageProviders.get(i).intents; 7684 if (intentFilters != null && intentFilters.size() > 0) { 7685 PackageParser.ProviderIntentInfo[] array = 7686 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7687 intentFilters.toArray(array); 7688 listCut.add(array); 7689 } 7690 } 7691 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7692 } 7693 7694 public final void addProvider(PackageParser.Provider p) { 7695 if (mProviders.containsKey(p.getComponentName())) { 7696 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7697 return; 7698 } 7699 7700 mProviders.put(p.getComponentName(), p); 7701 if (DEBUG_SHOW_INFO) { 7702 Log.v(TAG, " " 7703 + (p.info.nonLocalizedLabel != null 7704 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7705 Log.v(TAG, " Class=" + p.info.name); 7706 } 7707 final int NI = p.intents.size(); 7708 int j; 7709 for (j = 0; j < NI; j++) { 7710 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7711 if (DEBUG_SHOW_INFO) { 7712 Log.v(TAG, " IntentFilter:"); 7713 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7714 } 7715 if (!intent.debugCheck()) { 7716 Log.w(TAG, "==> For Provider " + p.info.name); 7717 } 7718 addFilter(intent); 7719 } 7720 } 7721 7722 public final void removeProvider(PackageParser.Provider p) { 7723 mProviders.remove(p.getComponentName()); 7724 if (DEBUG_SHOW_INFO) { 7725 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7726 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7727 Log.v(TAG, " Class=" + p.info.name); 7728 } 7729 final int NI = p.intents.size(); 7730 int j; 7731 for (j = 0; j < NI; j++) { 7732 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7733 if (DEBUG_SHOW_INFO) { 7734 Log.v(TAG, " IntentFilter:"); 7735 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7736 } 7737 removeFilter(intent); 7738 } 7739 } 7740 7741 @Override 7742 protected boolean allowFilterResult( 7743 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7744 ProviderInfo filterPi = filter.provider.info; 7745 for (int i = dest.size() - 1; i >= 0; i--) { 7746 ProviderInfo destPi = dest.get(i).providerInfo; 7747 if (destPi.name == filterPi.name 7748 && destPi.packageName == filterPi.packageName) { 7749 return false; 7750 } 7751 } 7752 return true; 7753 } 7754 7755 @Override 7756 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7757 return new PackageParser.ProviderIntentInfo[size]; 7758 } 7759 7760 @Override 7761 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7762 if (!sUserManager.exists(userId)) 7763 return true; 7764 PackageParser.Package p = filter.provider.owner; 7765 if (p != null) { 7766 PackageSetting ps = (PackageSetting) p.mExtras; 7767 if (ps != null) { 7768 // System apps are never considered stopped for purposes of 7769 // filtering, because there may be no way for the user to 7770 // actually re-launch them. 7771 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7772 && ps.getStopped(userId); 7773 } 7774 } 7775 return false; 7776 } 7777 7778 @Override 7779 protected boolean isPackageForFilter(String packageName, 7780 PackageParser.ProviderIntentInfo info) { 7781 return packageName.equals(info.provider.owner.packageName); 7782 } 7783 7784 @Override 7785 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7786 int match, int userId) { 7787 if (!sUserManager.exists(userId)) 7788 return null; 7789 final PackageParser.ProviderIntentInfo info = filter; 7790 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7791 return null; 7792 } 7793 final PackageParser.Provider provider = info.provider; 7794 if (mSafeMode && (provider.info.applicationInfo.flags 7795 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7796 return null; 7797 } 7798 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7799 if (ps == null) { 7800 return null; 7801 } 7802 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7803 ps.readUserState(userId), userId); 7804 if (pi == null) { 7805 return null; 7806 } 7807 final ResolveInfo res = new ResolveInfo(); 7808 res.providerInfo = pi; 7809 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7810 res.filter = filter; 7811 } 7812 res.priority = info.getPriority(); 7813 res.preferredOrder = provider.owner.mPreferredOrder; 7814 res.match = match; 7815 res.isDefault = info.hasDefault; 7816 res.labelRes = info.labelRes; 7817 res.nonLocalizedLabel = info.nonLocalizedLabel; 7818 res.icon = info.icon; 7819 res.system = isSystemApp(res.providerInfo.applicationInfo); 7820 return res; 7821 } 7822 7823 @Override 7824 protected void sortResults(List<ResolveInfo> results) { 7825 Collections.sort(results, mResolvePrioritySorter); 7826 } 7827 7828 @Override 7829 protected void dumpFilter(PrintWriter out, String prefix, 7830 PackageParser.ProviderIntentInfo filter) { 7831 out.print(prefix); 7832 out.print( 7833 Integer.toHexString(System.identityHashCode(filter.provider))); 7834 out.print(' '); 7835 filter.provider.printComponentShortName(out); 7836 out.print(" filter "); 7837 out.println(Integer.toHexString(System.identityHashCode(filter))); 7838 } 7839 7840 @Override 7841 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7842 return filter.provider; 7843 } 7844 7845 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7846 PackageParser.Provider provider = (PackageParser.Provider)label; 7847 out.print(prefix); out.print( 7848 Integer.toHexString(System.identityHashCode(provider))); 7849 out.print(' '); 7850 provider.printComponentShortName(out); 7851 if (count > 1) { 7852 out.print(" ("); out.print(count); out.print(" filters)"); 7853 } 7854 out.println(); 7855 } 7856 7857 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7858 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7859 private int mFlags; 7860 }; 7861 7862 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7863 new Comparator<ResolveInfo>() { 7864 public int compare(ResolveInfo r1, ResolveInfo r2) { 7865 int v1 = r1.priority; 7866 int v2 = r2.priority; 7867 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7868 if (v1 != v2) { 7869 return (v1 > v2) ? -1 : 1; 7870 } 7871 v1 = r1.preferredOrder; 7872 v2 = r2.preferredOrder; 7873 if (v1 != v2) { 7874 return (v1 > v2) ? -1 : 1; 7875 } 7876 if (r1.isDefault != r2.isDefault) { 7877 return r1.isDefault ? -1 : 1; 7878 } 7879 v1 = r1.match; 7880 v2 = r2.match; 7881 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7882 if (v1 != v2) { 7883 return (v1 > v2) ? -1 : 1; 7884 } 7885 if (r1.system != r2.system) { 7886 return r1.system ? -1 : 1; 7887 } 7888 return 0; 7889 } 7890 }; 7891 7892 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7893 new Comparator<ProviderInfo>() { 7894 public int compare(ProviderInfo p1, ProviderInfo p2) { 7895 final int v1 = p1.initOrder; 7896 final int v2 = p2.initOrder; 7897 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7898 } 7899 }; 7900 7901 static final void sendPackageBroadcast(String action, String pkg, 7902 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7903 int[] userIds) { 7904 IActivityManager am = ActivityManagerNative.getDefault(); 7905 if (am != null) { 7906 try { 7907 if (userIds == null) { 7908 userIds = am.getRunningUserIds(); 7909 } 7910 for (int id : userIds) { 7911 final Intent intent = new Intent(action, 7912 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7913 if (extras != null) { 7914 intent.putExtras(extras); 7915 } 7916 if (targetPkg != null) { 7917 intent.setPackage(targetPkg); 7918 } 7919 // Modify the UID when posting to other users 7920 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7921 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7922 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7923 intent.putExtra(Intent.EXTRA_UID, uid); 7924 } 7925 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7926 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7927 if (DEBUG_BROADCASTS) { 7928 RuntimeException here = new RuntimeException("here"); 7929 here.fillInStackTrace(); 7930 Slog.d(TAG, "Sending to user " + id + ": " 7931 + intent.toShortString(false, true, false, false) 7932 + " " + intent.getExtras(), here); 7933 } 7934 am.broadcastIntent(null, intent, null, finishedReceiver, 7935 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7936 finishedReceiver != null, false, id); 7937 } 7938 } catch (RemoteException ex) { 7939 } 7940 } 7941 } 7942 7943 /** 7944 * Check if the external storage media is available. This is true if there 7945 * is a mounted external storage medium or if the external storage is 7946 * emulated. 7947 */ 7948 private boolean isExternalMediaAvailable() { 7949 return mMediaMounted || Environment.isExternalStorageEmulated(); 7950 } 7951 7952 @Override 7953 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7954 // writer 7955 synchronized (mPackages) { 7956 if (!isExternalMediaAvailable()) { 7957 // If the external storage is no longer mounted at this point, 7958 // the caller may not have been able to delete all of this 7959 // packages files and can not delete any more. Bail. 7960 return null; 7961 } 7962 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7963 if (lastPackage != null) { 7964 pkgs.remove(lastPackage); 7965 } 7966 if (pkgs.size() > 0) { 7967 return pkgs.get(0); 7968 } 7969 } 7970 return null; 7971 } 7972 7973 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7974 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7975 userId, andCode ? 1 : 0, packageName); 7976 if (mSystemReady) { 7977 msg.sendToTarget(); 7978 } else { 7979 if (mPostSystemReadyMessages == null) { 7980 mPostSystemReadyMessages = new ArrayList<>(); 7981 } 7982 mPostSystemReadyMessages.add(msg); 7983 } 7984 } 7985 7986 void startCleaningPackages() { 7987 // reader 7988 synchronized (mPackages) { 7989 if (!isExternalMediaAvailable()) { 7990 return; 7991 } 7992 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7993 return; 7994 } 7995 } 7996 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7997 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7998 IActivityManager am = ActivityManagerNative.getDefault(); 7999 if (am != null) { 8000 try { 8001 am.startService(null, intent, null, UserHandle.USER_OWNER); 8002 } catch (RemoteException e) { 8003 } 8004 } 8005 } 8006 8007 @Override 8008 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8009 int installFlags, String installerPackageName, VerificationParams verificationParams, 8010 String packageAbiOverride) { 8011 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8012 packageAbiOverride, UserHandle.getCallingUserId()); 8013 } 8014 8015 @Override 8016 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8017 int installFlags, String installerPackageName, VerificationParams verificationParams, 8018 String packageAbiOverride, int userId) { 8019 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8020 8021 final int callingUid = Binder.getCallingUid(); 8022 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8023 8024 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8025 try { 8026 if (observer != null) { 8027 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8028 } 8029 } catch (RemoteException re) { 8030 } 8031 return; 8032 } 8033 8034 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8035 installFlags |= PackageManager.INSTALL_FROM_ADB; 8036 8037 } else { 8038 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8039 // about installerPackageName. 8040 8041 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8042 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8043 } 8044 8045 UserHandle user; 8046 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8047 user = UserHandle.ALL; 8048 } else { 8049 user = new UserHandle(userId); 8050 } 8051 8052 verificationParams.setInstallerUid(callingUid); 8053 8054 final File originFile = new File(originPath); 8055 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8056 8057 final Message msg = mHandler.obtainMessage(INIT_COPY); 8058 msg.obj = new InstallParams(origin, observer, installFlags, 8059 installerPackageName, verificationParams, user, packageAbiOverride); 8060 mHandler.sendMessage(msg); 8061 } 8062 8063 void installStage(String packageName, File stagedDir, String stagedCid, 8064 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8065 String installerPackageName, int installerUid, UserHandle user) { 8066 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8067 params.referrerUri, installerUid, null); 8068 8069 final OriginInfo origin; 8070 if (stagedDir != null) { 8071 origin = OriginInfo.fromStagedFile(stagedDir); 8072 } else { 8073 origin = OriginInfo.fromStagedContainer(stagedCid); 8074 } 8075 8076 final Message msg = mHandler.obtainMessage(INIT_COPY); 8077 msg.obj = new InstallParams(origin, observer, params.installFlags, 8078 installerPackageName, verifParams, user, params.abiOverride); 8079 mHandler.sendMessage(msg); 8080 } 8081 8082 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8083 Bundle extras = new Bundle(1); 8084 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8085 8086 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8087 packageName, extras, null, null, new int[] {userId}); 8088 try { 8089 IActivityManager am = ActivityManagerNative.getDefault(); 8090 final boolean isSystem = 8091 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8092 if (isSystem && am.isUserRunning(userId, false)) { 8093 // The just-installed/enabled app is bundled on the system, so presumed 8094 // to be able to run automatically without needing an explicit launch. 8095 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8096 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8097 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8098 .setPackage(packageName); 8099 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8100 android.app.AppOpsManager.OP_NONE, false, false, userId); 8101 } 8102 } catch (RemoteException e) { 8103 // shouldn't happen 8104 Slog.w(TAG, "Unable to bootstrap installed package", e); 8105 } 8106 } 8107 8108 @Override 8109 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8110 int userId) { 8111 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8112 PackageSetting pkgSetting; 8113 final int uid = Binder.getCallingUid(); 8114 enforceCrossUserPermission(uid, userId, true, true, 8115 "setApplicationHiddenSetting for user " + userId); 8116 8117 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8118 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8119 return false; 8120 } 8121 8122 long callingId = Binder.clearCallingIdentity(); 8123 try { 8124 boolean sendAdded = false; 8125 boolean sendRemoved = false; 8126 // writer 8127 synchronized (mPackages) { 8128 pkgSetting = mSettings.mPackages.get(packageName); 8129 if (pkgSetting == null) { 8130 return false; 8131 } 8132 if (pkgSetting.getHidden(userId) != hidden) { 8133 pkgSetting.setHidden(hidden, userId); 8134 mSettings.writePackageRestrictionsLPr(userId); 8135 if (hidden) { 8136 sendRemoved = true; 8137 } else { 8138 sendAdded = true; 8139 } 8140 } 8141 } 8142 if (sendAdded) { 8143 sendPackageAddedForUser(packageName, pkgSetting, userId); 8144 return true; 8145 } 8146 if (sendRemoved) { 8147 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8148 "hiding pkg"); 8149 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8150 } 8151 } finally { 8152 Binder.restoreCallingIdentity(callingId); 8153 } 8154 return false; 8155 } 8156 8157 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8158 int userId) { 8159 final PackageRemovedInfo info = new PackageRemovedInfo(); 8160 info.removedPackage = packageName; 8161 info.removedUsers = new int[] {userId}; 8162 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8163 info.sendBroadcast(false, false, false); 8164 } 8165 8166 /** 8167 * Returns true if application is not found or there was an error. Otherwise it returns 8168 * the hidden state of the package for the given user. 8169 */ 8170 @Override 8171 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8172 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8173 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8174 false, "getApplicationHidden for user " + userId); 8175 PackageSetting pkgSetting; 8176 long callingId = Binder.clearCallingIdentity(); 8177 try { 8178 // writer 8179 synchronized (mPackages) { 8180 pkgSetting = mSettings.mPackages.get(packageName); 8181 if (pkgSetting == null) { 8182 return true; 8183 } 8184 return pkgSetting.getHidden(userId); 8185 } 8186 } finally { 8187 Binder.restoreCallingIdentity(callingId); 8188 } 8189 } 8190 8191 /** 8192 * @hide 8193 */ 8194 @Override 8195 public int installExistingPackageAsUser(String packageName, int userId) { 8196 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8197 null); 8198 PackageSetting pkgSetting; 8199 final int uid = Binder.getCallingUid(); 8200 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8201 + userId); 8202 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8203 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8204 } 8205 8206 long callingId = Binder.clearCallingIdentity(); 8207 try { 8208 boolean sendAdded = false; 8209 Bundle extras = new Bundle(1); 8210 8211 // writer 8212 synchronized (mPackages) { 8213 pkgSetting = mSettings.mPackages.get(packageName); 8214 if (pkgSetting == null) { 8215 return PackageManager.INSTALL_FAILED_INVALID_URI; 8216 } 8217 if (!pkgSetting.getInstalled(userId)) { 8218 pkgSetting.setInstalled(true, userId); 8219 pkgSetting.setHidden(false, userId); 8220 mSettings.writePackageRestrictionsLPr(userId); 8221 sendAdded = true; 8222 } 8223 } 8224 8225 if (sendAdded) { 8226 sendPackageAddedForUser(packageName, pkgSetting, userId); 8227 } 8228 } finally { 8229 Binder.restoreCallingIdentity(callingId); 8230 } 8231 8232 return PackageManager.INSTALL_SUCCEEDED; 8233 } 8234 8235 boolean isUserRestricted(int userId, String restrictionKey) { 8236 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8237 if (restrictions.getBoolean(restrictionKey, false)) { 8238 Log.w(TAG, "User is restricted: " + restrictionKey); 8239 return true; 8240 } 8241 return false; 8242 } 8243 8244 @Override 8245 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8246 mContext.enforceCallingOrSelfPermission( 8247 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8248 "Only package verification agents can verify applications"); 8249 8250 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8251 final PackageVerificationResponse response = new PackageVerificationResponse( 8252 verificationCode, Binder.getCallingUid()); 8253 msg.arg1 = id; 8254 msg.obj = response; 8255 mHandler.sendMessage(msg); 8256 } 8257 8258 @Override 8259 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8260 long millisecondsToDelay) { 8261 mContext.enforceCallingOrSelfPermission( 8262 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8263 "Only package verification agents can extend verification timeouts"); 8264 8265 final PackageVerificationState state = mPendingVerification.get(id); 8266 final PackageVerificationResponse response = new PackageVerificationResponse( 8267 verificationCodeAtTimeout, Binder.getCallingUid()); 8268 8269 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8270 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8271 } 8272 if (millisecondsToDelay < 0) { 8273 millisecondsToDelay = 0; 8274 } 8275 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8276 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8277 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8278 } 8279 8280 if ((state != null) && !state.timeoutExtended()) { 8281 state.extendTimeout(); 8282 8283 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8284 msg.arg1 = id; 8285 msg.obj = response; 8286 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8287 } 8288 } 8289 8290 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8291 int verificationCode, UserHandle user) { 8292 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8293 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8294 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8295 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8296 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8297 8298 mContext.sendBroadcastAsUser(intent, user, 8299 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8300 } 8301 8302 private ComponentName matchComponentForVerifier(String packageName, 8303 List<ResolveInfo> receivers) { 8304 ActivityInfo targetReceiver = null; 8305 8306 final int NR = receivers.size(); 8307 for (int i = 0; i < NR; i++) { 8308 final ResolveInfo info = receivers.get(i); 8309 if (info.activityInfo == null) { 8310 continue; 8311 } 8312 8313 if (packageName.equals(info.activityInfo.packageName)) { 8314 targetReceiver = info.activityInfo; 8315 break; 8316 } 8317 } 8318 8319 if (targetReceiver == null) { 8320 return null; 8321 } 8322 8323 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8324 } 8325 8326 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8327 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8328 if (pkgInfo.verifiers.length == 0) { 8329 return null; 8330 } 8331 8332 final int N = pkgInfo.verifiers.length; 8333 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8334 for (int i = 0; i < N; i++) { 8335 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8336 8337 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8338 receivers); 8339 if (comp == null) { 8340 continue; 8341 } 8342 8343 final int verifierUid = getUidForVerifier(verifierInfo); 8344 if (verifierUid == -1) { 8345 continue; 8346 } 8347 8348 if (DEBUG_VERIFY) { 8349 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8350 + " with the correct signature"); 8351 } 8352 sufficientVerifiers.add(comp); 8353 verificationState.addSufficientVerifier(verifierUid); 8354 } 8355 8356 return sufficientVerifiers; 8357 } 8358 8359 private int getUidForVerifier(VerifierInfo verifierInfo) { 8360 synchronized (mPackages) { 8361 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8362 if (pkg == null) { 8363 return -1; 8364 } else if (pkg.mSignatures.length != 1) { 8365 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8366 + " has more than one signature; ignoring"); 8367 return -1; 8368 } 8369 8370 /* 8371 * If the public key of the package's signature does not match 8372 * our expected public key, then this is a different package and 8373 * we should skip. 8374 */ 8375 8376 final byte[] expectedPublicKey; 8377 try { 8378 final Signature verifierSig = pkg.mSignatures[0]; 8379 final PublicKey publicKey = verifierSig.getPublicKey(); 8380 expectedPublicKey = publicKey.getEncoded(); 8381 } catch (CertificateException e) { 8382 return -1; 8383 } 8384 8385 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8386 8387 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8388 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8389 + " does not have the expected public key; ignoring"); 8390 return -1; 8391 } 8392 8393 return pkg.applicationInfo.uid; 8394 } 8395 } 8396 8397 @Override 8398 public void finishPackageInstall(int token) { 8399 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8400 8401 if (DEBUG_INSTALL) { 8402 Slog.v(TAG, "BM finishing package install for " + token); 8403 } 8404 8405 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8406 mHandler.sendMessage(msg); 8407 } 8408 8409 /** 8410 * Get the verification agent timeout. 8411 * 8412 * @return verification timeout in milliseconds 8413 */ 8414 private long getVerificationTimeout() { 8415 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8416 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8417 DEFAULT_VERIFICATION_TIMEOUT); 8418 } 8419 8420 /** 8421 * Get the default verification agent response code. 8422 * 8423 * @return default verification response code 8424 */ 8425 private int getDefaultVerificationResponse() { 8426 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8427 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8428 DEFAULT_VERIFICATION_RESPONSE); 8429 } 8430 8431 /** 8432 * Check whether or not package verification has been enabled. 8433 * 8434 * @return true if verification should be performed 8435 */ 8436 private boolean isVerificationEnabled(int userId, int installFlags) { 8437 if (!DEFAULT_VERIFY_ENABLE) { 8438 return false; 8439 } 8440 8441 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8442 8443 // Check if installing from ADB 8444 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8445 // Do not run verification in a test harness environment 8446 if (ActivityManager.isRunningInTestHarness()) { 8447 return false; 8448 } 8449 if (ensureVerifyAppsEnabled) { 8450 return true; 8451 } 8452 // Check if the developer does not want package verification for ADB installs 8453 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8454 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8455 return false; 8456 } 8457 } 8458 8459 if (ensureVerifyAppsEnabled) { 8460 return true; 8461 } 8462 8463 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8464 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8465 } 8466 8467 /** 8468 * Get the "allow unknown sources" setting. 8469 * 8470 * @return the current "allow unknown sources" setting 8471 */ 8472 private int getUnknownSourcesSettings() { 8473 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8474 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8475 -1); 8476 } 8477 8478 @Override 8479 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8480 final int uid = Binder.getCallingUid(); 8481 // writer 8482 synchronized (mPackages) { 8483 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8484 if (targetPackageSetting == null) { 8485 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8486 } 8487 8488 PackageSetting installerPackageSetting; 8489 if (installerPackageName != null) { 8490 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8491 if (installerPackageSetting == null) { 8492 throw new IllegalArgumentException("Unknown installer package: " 8493 + installerPackageName); 8494 } 8495 } else { 8496 installerPackageSetting = null; 8497 } 8498 8499 Signature[] callerSignature; 8500 Object obj = mSettings.getUserIdLPr(uid); 8501 if (obj != null) { 8502 if (obj instanceof SharedUserSetting) { 8503 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8504 } else if (obj instanceof PackageSetting) { 8505 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8506 } else { 8507 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8508 } 8509 } else { 8510 throw new SecurityException("Unknown calling uid " + uid); 8511 } 8512 8513 // Verify: can't set installerPackageName to a package that is 8514 // not signed with the same cert as the caller. 8515 if (installerPackageSetting != null) { 8516 if (compareSignatures(callerSignature, 8517 installerPackageSetting.signatures.mSignatures) 8518 != PackageManager.SIGNATURE_MATCH) { 8519 throw new SecurityException( 8520 "Caller does not have same cert as new installer package " 8521 + installerPackageName); 8522 } 8523 } 8524 8525 // Verify: if target already has an installer package, it must 8526 // be signed with the same cert as the caller. 8527 if (targetPackageSetting.installerPackageName != null) { 8528 PackageSetting setting = mSettings.mPackages.get( 8529 targetPackageSetting.installerPackageName); 8530 // If the currently set package isn't valid, then it's always 8531 // okay to change it. 8532 if (setting != null) { 8533 if (compareSignatures(callerSignature, 8534 setting.signatures.mSignatures) 8535 != PackageManager.SIGNATURE_MATCH) { 8536 throw new SecurityException( 8537 "Caller does not have same cert as old installer package " 8538 + targetPackageSetting.installerPackageName); 8539 } 8540 } 8541 } 8542 8543 // Okay! 8544 targetPackageSetting.installerPackageName = installerPackageName; 8545 scheduleWriteSettingsLocked(); 8546 } 8547 } 8548 8549 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8550 // Queue up an async operation since the package installation may take a little while. 8551 mHandler.post(new Runnable() { 8552 public void run() { 8553 mHandler.removeCallbacks(this); 8554 // Result object to be returned 8555 PackageInstalledInfo res = new PackageInstalledInfo(); 8556 res.returnCode = currentStatus; 8557 res.uid = -1; 8558 res.pkg = null; 8559 res.removedInfo = new PackageRemovedInfo(); 8560 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8561 args.doPreInstall(res.returnCode); 8562 synchronized (mInstallLock) { 8563 installPackageLI(args, res); 8564 } 8565 args.doPostInstall(res.returnCode, res.uid); 8566 } 8567 8568 // A restore should be performed at this point if (a) the install 8569 // succeeded, (b) the operation is not an update, and (c) the new 8570 // package has not opted out of backup participation. 8571 final boolean update = res.removedInfo.removedPackage != null; 8572 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8573 boolean doRestore = !update 8574 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8575 8576 // Set up the post-install work request bookkeeping. This will be used 8577 // and cleaned up by the post-install event handling regardless of whether 8578 // there's a restore pass performed. Token values are >= 1. 8579 int token; 8580 if (mNextInstallToken < 0) mNextInstallToken = 1; 8581 token = mNextInstallToken++; 8582 8583 PostInstallData data = new PostInstallData(args, res); 8584 mRunningInstalls.put(token, data); 8585 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8586 8587 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8588 // Pass responsibility to the Backup Manager. It will perform a 8589 // restore if appropriate, then pass responsibility back to the 8590 // Package Manager to run the post-install observer callbacks 8591 // and broadcasts. 8592 IBackupManager bm = IBackupManager.Stub.asInterface( 8593 ServiceManager.getService(Context.BACKUP_SERVICE)); 8594 if (bm != null) { 8595 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8596 + " to BM for possible restore"); 8597 try { 8598 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8599 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8600 } else { 8601 doRestore = false; 8602 } 8603 } catch (RemoteException e) { 8604 // can't happen; the backup manager is local 8605 } catch (Exception e) { 8606 Slog.e(TAG, "Exception trying to enqueue restore", e); 8607 doRestore = false; 8608 } 8609 } else { 8610 Slog.e(TAG, "Backup Manager not found!"); 8611 doRestore = false; 8612 } 8613 } 8614 8615 if (!doRestore) { 8616 // No restore possible, or the Backup Manager was mysteriously not 8617 // available -- just fire the post-install work request directly. 8618 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8619 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8620 mHandler.sendMessage(msg); 8621 } 8622 } 8623 }); 8624 } 8625 8626 private abstract class HandlerParams { 8627 private static final int MAX_RETRIES = 4; 8628 8629 /** 8630 * Number of times startCopy() has been attempted and had a non-fatal 8631 * error. 8632 */ 8633 private int mRetries = 0; 8634 8635 /** User handle for the user requesting the information or installation. */ 8636 private final UserHandle mUser; 8637 8638 HandlerParams(UserHandle user) { 8639 mUser = user; 8640 } 8641 8642 UserHandle getUser() { 8643 return mUser; 8644 } 8645 8646 final boolean startCopy() { 8647 boolean res; 8648 try { 8649 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8650 8651 if (++mRetries > MAX_RETRIES) { 8652 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8653 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8654 handleServiceError(); 8655 return false; 8656 } else { 8657 handleStartCopy(); 8658 res = true; 8659 } 8660 } catch (RemoteException e) { 8661 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8662 mHandler.sendEmptyMessage(MCS_RECONNECT); 8663 res = false; 8664 } 8665 handleReturnCode(); 8666 return res; 8667 } 8668 8669 final void serviceError() { 8670 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8671 handleServiceError(); 8672 handleReturnCode(); 8673 } 8674 8675 abstract void handleStartCopy() throws RemoteException; 8676 abstract void handleServiceError(); 8677 abstract void handleReturnCode(); 8678 } 8679 8680 class MeasureParams extends HandlerParams { 8681 private final PackageStats mStats; 8682 private boolean mSuccess; 8683 8684 private final IPackageStatsObserver mObserver; 8685 8686 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8687 super(new UserHandle(stats.userHandle)); 8688 mObserver = observer; 8689 mStats = stats; 8690 } 8691 8692 @Override 8693 public String toString() { 8694 return "MeasureParams{" 8695 + Integer.toHexString(System.identityHashCode(this)) 8696 + " " + mStats.packageName + "}"; 8697 } 8698 8699 @Override 8700 void handleStartCopy() throws RemoteException { 8701 synchronized (mInstallLock) { 8702 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8703 } 8704 8705 if (mSuccess) { 8706 final boolean mounted; 8707 if (Environment.isExternalStorageEmulated()) { 8708 mounted = true; 8709 } else { 8710 final String status = Environment.getExternalStorageState(); 8711 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8712 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8713 } 8714 8715 if (mounted) { 8716 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8717 8718 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8719 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8720 8721 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8722 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8723 8724 // Always subtract cache size, since it's a subdirectory 8725 mStats.externalDataSize -= mStats.externalCacheSize; 8726 8727 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8728 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8729 8730 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8731 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8732 } 8733 } 8734 } 8735 8736 @Override 8737 void handleReturnCode() { 8738 if (mObserver != null) { 8739 try { 8740 mObserver.onGetStatsCompleted(mStats, mSuccess); 8741 } catch (RemoteException e) { 8742 Slog.i(TAG, "Observer no longer exists."); 8743 } 8744 } 8745 } 8746 8747 @Override 8748 void handleServiceError() { 8749 Slog.e(TAG, "Could not measure application " + mStats.packageName 8750 + " external storage"); 8751 } 8752 } 8753 8754 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8755 throws RemoteException { 8756 long result = 0; 8757 for (File path : paths) { 8758 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8759 } 8760 return result; 8761 } 8762 8763 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8764 for (File path : paths) { 8765 try { 8766 mcs.clearDirectory(path.getAbsolutePath()); 8767 } catch (RemoteException e) { 8768 } 8769 } 8770 } 8771 8772 static class OriginInfo { 8773 /** 8774 * Location where install is coming from, before it has been 8775 * copied/renamed into place. This could be a single monolithic APK 8776 * file, or a cluster directory. This location may be untrusted. 8777 */ 8778 final File file; 8779 final String cid; 8780 8781 /** 8782 * Flag indicating that {@link #file} or {@link #cid} has already been 8783 * staged, meaning downstream users don't need to defensively copy the 8784 * contents. 8785 */ 8786 final boolean staged; 8787 8788 /** 8789 * Flag indicating that {@link #file} or {@link #cid} is an already 8790 * installed app that is being moved. 8791 */ 8792 final boolean existing; 8793 8794 final String resolvedPath; 8795 final File resolvedFile; 8796 8797 static OriginInfo fromNothing() { 8798 return new OriginInfo(null, null, false, false); 8799 } 8800 8801 static OriginInfo fromUntrustedFile(File file) { 8802 return new OriginInfo(file, null, false, false); 8803 } 8804 8805 static OriginInfo fromExistingFile(File file) { 8806 return new OriginInfo(file, null, false, true); 8807 } 8808 8809 static OriginInfo fromStagedFile(File file) { 8810 return new OriginInfo(file, null, true, false); 8811 } 8812 8813 static OriginInfo fromStagedContainer(String cid) { 8814 return new OriginInfo(null, cid, true, false); 8815 } 8816 8817 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8818 this.file = file; 8819 this.cid = cid; 8820 this.staged = staged; 8821 this.existing = existing; 8822 8823 if (cid != null) { 8824 resolvedPath = PackageHelper.getSdDir(cid); 8825 resolvedFile = new File(resolvedPath); 8826 } else if (file != null) { 8827 resolvedPath = file.getAbsolutePath(); 8828 resolvedFile = file; 8829 } else { 8830 resolvedPath = null; 8831 resolvedFile = null; 8832 } 8833 } 8834 } 8835 8836 class InstallParams extends HandlerParams { 8837 final OriginInfo origin; 8838 final IPackageInstallObserver2 observer; 8839 int installFlags; 8840 final String installerPackageName; 8841 final VerificationParams verificationParams; 8842 private InstallArgs mArgs; 8843 private int mRet; 8844 final String packageAbiOverride; 8845 8846 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8847 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8848 String packageAbiOverride) { 8849 super(user); 8850 this.origin = origin; 8851 this.observer = observer; 8852 this.installFlags = installFlags; 8853 this.installerPackageName = installerPackageName; 8854 this.verificationParams = verificationParams; 8855 this.packageAbiOverride = packageAbiOverride; 8856 } 8857 8858 @Override 8859 public String toString() { 8860 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8861 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8862 } 8863 8864 public ManifestDigest getManifestDigest() { 8865 if (verificationParams == null) { 8866 return null; 8867 } 8868 return verificationParams.getManifestDigest(); 8869 } 8870 8871 private int installLocationPolicy(PackageInfoLite pkgLite) { 8872 String packageName = pkgLite.packageName; 8873 int installLocation = pkgLite.installLocation; 8874 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8875 // reader 8876 synchronized (mPackages) { 8877 PackageParser.Package pkg = mPackages.get(packageName); 8878 if (pkg != null) { 8879 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8880 // Check for downgrading. 8881 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8882 try { 8883 checkDowngrade(pkg, pkgLite); 8884 } catch (PackageManagerException e) { 8885 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8886 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8887 } 8888 } 8889 // Check for updated system application. 8890 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8891 if (onSd) { 8892 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8893 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8894 } 8895 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8896 } else { 8897 if (onSd) { 8898 // Install flag overrides everything. 8899 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8900 } 8901 // If current upgrade specifies particular preference 8902 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8903 // Application explicitly specified internal. 8904 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8905 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8906 // App explictly prefers external. Let policy decide 8907 } else { 8908 // Prefer previous location 8909 if (isExternal(pkg)) { 8910 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8911 } 8912 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8913 } 8914 } 8915 } else { 8916 // Invalid install. Return error code 8917 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8918 } 8919 } 8920 } 8921 // All the special cases have been taken care of. 8922 // Return result based on recommended install location. 8923 if (onSd) { 8924 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8925 } 8926 return pkgLite.recommendedInstallLocation; 8927 } 8928 8929 /* 8930 * Invoke remote method to get package information and install 8931 * location values. Override install location based on default 8932 * policy if needed and then create install arguments based 8933 * on the install location. 8934 */ 8935 public void handleStartCopy() throws RemoteException { 8936 int ret = PackageManager.INSTALL_SUCCEEDED; 8937 8938 // If we're already staged, we've firmly committed to an install location 8939 if (origin.staged) { 8940 if (origin.file != null) { 8941 installFlags |= PackageManager.INSTALL_INTERNAL; 8942 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8943 } else if (origin.cid != null) { 8944 installFlags |= PackageManager.INSTALL_EXTERNAL; 8945 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8946 } else { 8947 throw new IllegalStateException("Invalid stage location"); 8948 } 8949 } 8950 8951 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8952 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8953 8954 PackageInfoLite pkgLite = null; 8955 8956 if (onInt && onSd) { 8957 // Check if both bits are set. 8958 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8959 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8960 } else { 8961 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8962 packageAbiOverride); 8963 8964 /* 8965 * If we have too little free space, try to free cache 8966 * before giving up. 8967 */ 8968 if (!origin.staged && pkgLite.recommendedInstallLocation 8969 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8970 // TODO: focus freeing disk space on the target device 8971 final StorageManager storage = StorageManager.from(mContext); 8972 final long lowThreshold = storage.getStorageLowBytes( 8973 Environment.getDataDirectory()); 8974 8975 final long sizeBytes = mContainerService.calculateInstalledSize( 8976 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8977 8978 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8979 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8980 installFlags, packageAbiOverride); 8981 } 8982 8983 /* 8984 * The cache free must have deleted the file we 8985 * downloaded to install. 8986 * 8987 * TODO: fix the "freeCache" call to not delete 8988 * the file we care about. 8989 */ 8990 if (pkgLite.recommendedInstallLocation 8991 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8992 pkgLite.recommendedInstallLocation 8993 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8994 } 8995 } 8996 } 8997 8998 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8999 int loc = pkgLite.recommendedInstallLocation; 9000 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9001 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9002 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9003 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9004 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9005 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9006 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9007 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9008 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9009 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9010 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9011 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9012 } else { 9013 // Override with defaults if needed. 9014 loc = installLocationPolicy(pkgLite); 9015 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9016 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9017 } else if (!onSd && !onInt) { 9018 // Override install location with flags 9019 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9020 // Set the flag to install on external media. 9021 installFlags |= PackageManager.INSTALL_EXTERNAL; 9022 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9023 } else { 9024 // Make sure the flag for installing on external 9025 // media is unset 9026 installFlags |= PackageManager.INSTALL_INTERNAL; 9027 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9028 } 9029 } 9030 } 9031 } 9032 9033 final InstallArgs args = createInstallArgs(this); 9034 mArgs = args; 9035 9036 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9037 /* 9038 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9039 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9040 */ 9041 int userIdentifier = getUser().getIdentifier(); 9042 if (userIdentifier == UserHandle.USER_ALL 9043 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9044 userIdentifier = UserHandle.USER_OWNER; 9045 } 9046 9047 /* 9048 * Determine if we have any installed package verifiers. If we 9049 * do, then we'll defer to them to verify the packages. 9050 */ 9051 final int requiredUid = mRequiredVerifierPackage == null ? -1 9052 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9053 if (!origin.existing && requiredUid != -1 9054 && isVerificationEnabled(userIdentifier, installFlags)) { 9055 final Intent verification = new Intent( 9056 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9057 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9058 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9059 PACKAGE_MIME_TYPE); 9060 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9061 9062 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9063 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9064 0 /* TODO: Which userId? */); 9065 9066 if (DEBUG_VERIFY) { 9067 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9068 + verification.toString() + " with " + pkgLite.verifiers.length 9069 + " optional verifiers"); 9070 } 9071 9072 final int verificationId = mPendingVerificationToken++; 9073 9074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9075 9076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9077 installerPackageName); 9078 9079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9080 installFlags); 9081 9082 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9083 pkgLite.packageName); 9084 9085 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9086 pkgLite.versionCode); 9087 9088 if (verificationParams != null) { 9089 if (verificationParams.getVerificationURI() != null) { 9090 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9091 verificationParams.getVerificationURI()); 9092 } 9093 if (verificationParams.getOriginatingURI() != null) { 9094 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9095 verificationParams.getOriginatingURI()); 9096 } 9097 if (verificationParams.getReferrer() != null) { 9098 verification.putExtra(Intent.EXTRA_REFERRER, 9099 verificationParams.getReferrer()); 9100 } 9101 if (verificationParams.getOriginatingUid() >= 0) { 9102 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9103 verificationParams.getOriginatingUid()); 9104 } 9105 if (verificationParams.getInstallerUid() >= 0) { 9106 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9107 verificationParams.getInstallerUid()); 9108 } 9109 } 9110 9111 final PackageVerificationState verificationState = new PackageVerificationState( 9112 requiredUid, args); 9113 9114 mPendingVerification.append(verificationId, verificationState); 9115 9116 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9117 receivers, verificationState); 9118 9119 /* 9120 * If any sufficient verifiers were listed in the package 9121 * manifest, attempt to ask them. 9122 */ 9123 if (sufficientVerifiers != null) { 9124 final int N = sufficientVerifiers.size(); 9125 if (N == 0) { 9126 Slog.i(TAG, "Additional verifiers required, but none installed."); 9127 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9128 } else { 9129 for (int i = 0; i < N; i++) { 9130 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9131 9132 final Intent sufficientIntent = new Intent(verification); 9133 sufficientIntent.setComponent(verifierComponent); 9134 9135 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9136 } 9137 } 9138 } 9139 9140 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9141 mRequiredVerifierPackage, receivers); 9142 if (ret == PackageManager.INSTALL_SUCCEEDED 9143 && mRequiredVerifierPackage != null) { 9144 /* 9145 * Send the intent to the required verification agent, 9146 * but only start the verification timeout after the 9147 * target BroadcastReceivers have run. 9148 */ 9149 verification.setComponent(requiredVerifierComponent); 9150 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9151 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9152 new BroadcastReceiver() { 9153 @Override 9154 public void onReceive(Context context, Intent intent) { 9155 final Message msg = mHandler 9156 .obtainMessage(CHECK_PENDING_VERIFICATION); 9157 msg.arg1 = verificationId; 9158 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9159 } 9160 }, null, 0, null, null); 9161 9162 /* 9163 * We don't want the copy to proceed until verification 9164 * succeeds, so null out this field. 9165 */ 9166 mArgs = null; 9167 } 9168 } else { 9169 /* 9170 * No package verification is enabled, so immediately start 9171 * the remote call to initiate copy using temporary file. 9172 */ 9173 ret = args.copyApk(mContainerService, true); 9174 } 9175 } 9176 9177 mRet = ret; 9178 } 9179 9180 @Override 9181 void handleReturnCode() { 9182 // If mArgs is null, then MCS couldn't be reached. When it 9183 // reconnects, it will try again to install. At that point, this 9184 // will succeed. 9185 if (mArgs != null) { 9186 processPendingInstall(mArgs, mRet); 9187 } 9188 } 9189 9190 @Override 9191 void handleServiceError() { 9192 mArgs = createInstallArgs(this); 9193 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9194 } 9195 9196 public boolean isForwardLocked() { 9197 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9198 } 9199 } 9200 9201 /** 9202 * Used during creation of InstallArgs 9203 * 9204 * @param installFlags package installation flags 9205 * @return true if should be installed on external storage 9206 */ 9207 private static boolean installOnSd(int installFlags) { 9208 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9209 return false; 9210 } 9211 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9212 return true; 9213 } 9214 return false; 9215 } 9216 9217 /** 9218 * Used during creation of InstallArgs 9219 * 9220 * @param installFlags package installation flags 9221 * @return true if should be installed as forward locked 9222 */ 9223 private static boolean installForwardLocked(int installFlags) { 9224 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9225 } 9226 9227 private InstallArgs createInstallArgs(InstallParams params) { 9228 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9229 return new AsecInstallArgs(params); 9230 } else { 9231 return new FileInstallArgs(params); 9232 } 9233 } 9234 9235 /** 9236 * Create args that describe an existing installed package. Typically used 9237 * when cleaning up old installs, or used as a move source. 9238 */ 9239 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9240 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9241 final boolean isInAsec; 9242 if (installOnSd(installFlags)) { 9243 /* Apps on SD card are always in ASEC containers. */ 9244 isInAsec = true; 9245 } else if (installForwardLocked(installFlags) 9246 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9247 /* 9248 * Forward-locked apps are only in ASEC containers if they're the 9249 * new style 9250 */ 9251 isInAsec = true; 9252 } else { 9253 isInAsec = false; 9254 } 9255 9256 if (isInAsec) { 9257 return new AsecInstallArgs(codePath, instructionSets, 9258 installOnSd(installFlags), installForwardLocked(installFlags)); 9259 } else { 9260 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9261 instructionSets); 9262 } 9263 } 9264 9265 static abstract class InstallArgs { 9266 /** @see InstallParams#origin */ 9267 final OriginInfo origin; 9268 9269 final IPackageInstallObserver2 observer; 9270 // Always refers to PackageManager flags only 9271 final int installFlags; 9272 final String installerPackageName; 9273 final ManifestDigest manifestDigest; 9274 final UserHandle user; 9275 final String abiOverride; 9276 9277 // The list of instruction sets supported by this app. This is currently 9278 // only used during the rmdex() phase to clean up resources. We can get rid of this 9279 // if we move dex files under the common app path. 9280 /* nullable */ String[] instructionSets; 9281 9282 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9283 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9284 String[] instructionSets, String abiOverride) { 9285 this.origin = origin; 9286 this.installFlags = installFlags; 9287 this.observer = observer; 9288 this.installerPackageName = installerPackageName; 9289 this.manifestDigest = manifestDigest; 9290 this.user = user; 9291 this.instructionSets = instructionSets; 9292 this.abiOverride = abiOverride; 9293 } 9294 9295 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9296 abstract int doPreInstall(int status); 9297 9298 /** 9299 * Rename package into final resting place. All paths on the given 9300 * scanned package should be updated to reflect the rename. 9301 */ 9302 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9303 abstract int doPostInstall(int status, int uid); 9304 9305 /** @see PackageSettingBase#codePathString */ 9306 abstract String getCodePath(); 9307 /** @see PackageSettingBase#resourcePathString */ 9308 abstract String getResourcePath(); 9309 abstract String getLegacyNativeLibraryPath(); 9310 9311 // Need installer lock especially for dex file removal. 9312 abstract void cleanUpResourcesLI(); 9313 abstract boolean doPostDeleteLI(boolean delete); 9314 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9315 9316 /** 9317 * Called before the source arguments are copied. This is used mostly 9318 * for MoveParams when it needs to read the source file to put it in the 9319 * destination. 9320 */ 9321 int doPreCopy() { 9322 return PackageManager.INSTALL_SUCCEEDED; 9323 } 9324 9325 /** 9326 * Called after the source arguments are copied. This is used mostly for 9327 * MoveParams when it needs to read the source file to put it in the 9328 * destination. 9329 * 9330 * @return 9331 */ 9332 int doPostCopy(int uid) { 9333 return PackageManager.INSTALL_SUCCEEDED; 9334 } 9335 9336 protected boolean isFwdLocked() { 9337 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9338 } 9339 9340 protected boolean isExternal() { 9341 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9342 } 9343 9344 UserHandle getUser() { 9345 return user; 9346 } 9347 } 9348 9349 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9350 if (!allCodePaths.isEmpty()) { 9351 if (instructionSets == null) { 9352 throw new IllegalStateException("instructionSet == null"); 9353 } 9354 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9355 for (String codePath : allCodePaths) { 9356 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9357 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9358 if (retCode < 0) { 9359 Slog.w(TAG, "Couldn't remove dex file for package: " 9360 + " at location " + codePath + ", retcode=" + retCode); 9361 // we don't consider this to be a failure of the core package deletion 9362 } 9363 } 9364 } 9365 } 9366 } 9367 9368 /** 9369 * Logic to handle installation of non-ASEC applications, including copying 9370 * and renaming logic. 9371 */ 9372 class FileInstallArgs extends InstallArgs { 9373 private File codeFile; 9374 private File resourceFile; 9375 private File legacyNativeLibraryPath; 9376 9377 // Example topology: 9378 // /data/app/com.example/base.apk 9379 // /data/app/com.example/split_foo.apk 9380 // /data/app/com.example/lib/arm/libfoo.so 9381 // /data/app/com.example/lib/arm64/libfoo.so 9382 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9383 9384 /** New install */ 9385 FileInstallArgs(InstallParams params) { 9386 super(params.origin, params.observer, params.installFlags, 9387 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9388 null /* instruction sets */, params.packageAbiOverride); 9389 if (isFwdLocked()) { 9390 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9391 } 9392 } 9393 9394 /** Existing install */ 9395 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9396 String[] instructionSets) { 9397 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9398 this.codeFile = (codePath != null) ? new File(codePath) : null; 9399 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9400 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9401 new File(legacyNativeLibraryPath) : null; 9402 } 9403 9404 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9405 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9406 isFwdLocked(), abiOverride); 9407 9408 final StorageManager storage = StorageManager.from(mContext); 9409 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9410 } 9411 9412 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9413 if (origin.staged) { 9414 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9415 codeFile = origin.file; 9416 resourceFile = origin.file; 9417 return PackageManager.INSTALL_SUCCEEDED; 9418 } 9419 9420 try { 9421 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9422 codeFile = tempDir; 9423 resourceFile = tempDir; 9424 } catch (IOException e) { 9425 Slog.w(TAG, "Failed to create copy file: " + e); 9426 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9427 } 9428 9429 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9430 @Override 9431 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9432 if (!FileUtils.isValidExtFilename(name)) { 9433 throw new IllegalArgumentException("Invalid filename: " + name); 9434 } 9435 try { 9436 final File file = new File(codeFile, name); 9437 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9438 O_RDWR | O_CREAT, 0644); 9439 Os.chmod(file.getAbsolutePath(), 0644); 9440 return new ParcelFileDescriptor(fd); 9441 } catch (ErrnoException e) { 9442 throw new RemoteException("Failed to open: " + e.getMessage()); 9443 } 9444 } 9445 }; 9446 9447 int ret = PackageManager.INSTALL_SUCCEEDED; 9448 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9449 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9450 Slog.e(TAG, "Failed to copy package"); 9451 return ret; 9452 } 9453 9454 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9455 NativeLibraryHelper.Handle handle = null; 9456 try { 9457 handle = NativeLibraryHelper.Handle.create(codeFile); 9458 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9459 abiOverride); 9460 } catch (IOException e) { 9461 Slog.e(TAG, "Copying native libraries failed", e); 9462 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9463 } finally { 9464 IoUtils.closeQuietly(handle); 9465 } 9466 9467 return ret; 9468 } 9469 9470 int doPreInstall(int status) { 9471 if (status != PackageManager.INSTALL_SUCCEEDED) { 9472 cleanUp(); 9473 } 9474 return status; 9475 } 9476 9477 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9478 if (status != PackageManager.INSTALL_SUCCEEDED) { 9479 cleanUp(); 9480 return false; 9481 } else { 9482 final File beforeCodeFile = codeFile; 9483 final File afterCodeFile = getNextCodePath(pkg.packageName); 9484 9485 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9486 try { 9487 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9488 } catch (ErrnoException e) { 9489 Slog.d(TAG, "Failed to rename", e); 9490 return false; 9491 } 9492 9493 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9494 Slog.d(TAG, "Failed to restorecon"); 9495 return false; 9496 } 9497 9498 // Reflect the rename internally 9499 codeFile = afterCodeFile; 9500 resourceFile = afterCodeFile; 9501 9502 // Reflect the rename in scanned details 9503 pkg.codePath = afterCodeFile.getAbsolutePath(); 9504 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9505 pkg.baseCodePath); 9506 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9507 pkg.splitCodePaths); 9508 9509 // Reflect the rename in app info 9510 pkg.applicationInfo.setCodePath(pkg.codePath); 9511 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9512 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9513 pkg.applicationInfo.setResourcePath(pkg.codePath); 9514 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9515 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9516 9517 return true; 9518 } 9519 } 9520 9521 int doPostInstall(int status, int uid) { 9522 if (status != PackageManager.INSTALL_SUCCEEDED) { 9523 cleanUp(); 9524 } 9525 return status; 9526 } 9527 9528 @Override 9529 String getCodePath() { 9530 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9531 } 9532 9533 @Override 9534 String getResourcePath() { 9535 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9536 } 9537 9538 @Override 9539 String getLegacyNativeLibraryPath() { 9540 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9541 } 9542 9543 private boolean cleanUp() { 9544 if (codeFile == null || !codeFile.exists()) { 9545 return false; 9546 } 9547 9548 if (codeFile.isDirectory()) { 9549 FileUtils.deleteContents(codeFile); 9550 } 9551 codeFile.delete(); 9552 9553 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9554 resourceFile.delete(); 9555 } 9556 9557 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9558 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9559 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9560 } 9561 legacyNativeLibraryPath.delete(); 9562 } 9563 9564 return true; 9565 } 9566 9567 void cleanUpResourcesLI() { 9568 // Try enumerating all code paths before deleting 9569 List<String> allCodePaths = Collections.EMPTY_LIST; 9570 if (codeFile != null && codeFile.exists()) { 9571 try { 9572 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9573 allCodePaths = pkg.getAllCodePaths(); 9574 } catch (PackageParserException e) { 9575 // Ignored; we tried our best 9576 } 9577 } 9578 9579 cleanUp(); 9580 removeDexFiles(allCodePaths, instructionSets); 9581 } 9582 9583 boolean doPostDeleteLI(boolean delete) { 9584 // XXX err, shouldn't we respect the delete flag? 9585 cleanUpResourcesLI(); 9586 return true; 9587 } 9588 } 9589 9590 private boolean isAsecExternal(String cid) { 9591 final String asecPath = PackageHelper.getSdFilesystem(cid); 9592 return !asecPath.startsWith(mAsecInternalPath); 9593 } 9594 9595 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9596 PackageManagerException { 9597 if (copyRet < 0) { 9598 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9599 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9600 throw new PackageManagerException(copyRet, message); 9601 } 9602 } 9603 } 9604 9605 /** 9606 * Extract the MountService "container ID" from the full code path of an 9607 * .apk. 9608 */ 9609 static String cidFromCodePath(String fullCodePath) { 9610 int eidx = fullCodePath.lastIndexOf("/"); 9611 String subStr1 = fullCodePath.substring(0, eidx); 9612 int sidx = subStr1.lastIndexOf("/"); 9613 return subStr1.substring(sidx+1, eidx); 9614 } 9615 9616 /** 9617 * Logic to handle installation of ASEC applications, including copying and 9618 * renaming logic. 9619 */ 9620 class AsecInstallArgs extends InstallArgs { 9621 static final String RES_FILE_NAME = "pkg.apk"; 9622 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9623 9624 String cid; 9625 String packagePath; 9626 String resourcePath; 9627 String legacyNativeLibraryDir; 9628 9629 /** New install */ 9630 AsecInstallArgs(InstallParams params) { 9631 super(params.origin, params.observer, params.installFlags, 9632 params.installerPackageName, params.getManifestDigest(), 9633 params.getUser(), null /* instruction sets */, 9634 params.packageAbiOverride); 9635 } 9636 9637 /** Existing install */ 9638 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9639 boolean isExternal, boolean isForwardLocked) { 9640 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9641 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9642 instructionSets, null); 9643 // Hackily pretend we're still looking at a full code path 9644 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9645 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9646 } 9647 9648 // Extract cid from fullCodePath 9649 int eidx = fullCodePath.lastIndexOf("/"); 9650 String subStr1 = fullCodePath.substring(0, eidx); 9651 int sidx = subStr1.lastIndexOf("/"); 9652 cid = subStr1.substring(sidx+1, eidx); 9653 setMountPath(subStr1); 9654 } 9655 9656 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9657 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9658 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9659 instructionSets, null); 9660 this.cid = cid; 9661 setMountPath(PackageHelper.getSdDir(cid)); 9662 } 9663 9664 void createCopyFile() { 9665 cid = mInstallerService.allocateExternalStageCidLegacy(); 9666 } 9667 9668 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9669 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9670 abiOverride); 9671 9672 final File target; 9673 if (isExternal()) { 9674 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9675 } else { 9676 target = Environment.getDataDirectory(); 9677 } 9678 9679 final StorageManager storage = StorageManager.from(mContext); 9680 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9681 } 9682 9683 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9684 if (origin.staged) { 9685 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9686 cid = origin.cid; 9687 setMountPath(PackageHelper.getSdDir(cid)); 9688 return PackageManager.INSTALL_SUCCEEDED; 9689 } 9690 9691 if (temp) { 9692 createCopyFile(); 9693 } else { 9694 /* 9695 * Pre-emptively destroy the container since it's destroyed if 9696 * copying fails due to it existing anyway. 9697 */ 9698 PackageHelper.destroySdDir(cid); 9699 } 9700 9701 final String newMountPath = imcs.copyPackageToContainer( 9702 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9703 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9704 9705 if (newMountPath != null) { 9706 setMountPath(newMountPath); 9707 return PackageManager.INSTALL_SUCCEEDED; 9708 } else { 9709 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9710 } 9711 } 9712 9713 @Override 9714 String getCodePath() { 9715 return packagePath; 9716 } 9717 9718 @Override 9719 String getResourcePath() { 9720 return resourcePath; 9721 } 9722 9723 @Override 9724 String getLegacyNativeLibraryPath() { 9725 return legacyNativeLibraryDir; 9726 } 9727 9728 int doPreInstall(int status) { 9729 if (status != PackageManager.INSTALL_SUCCEEDED) { 9730 // Destroy container 9731 PackageHelper.destroySdDir(cid); 9732 } else { 9733 boolean mounted = PackageHelper.isContainerMounted(cid); 9734 if (!mounted) { 9735 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9736 Process.SYSTEM_UID); 9737 if (newMountPath != null) { 9738 setMountPath(newMountPath); 9739 } else { 9740 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9741 } 9742 } 9743 } 9744 return status; 9745 } 9746 9747 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9748 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9749 String newMountPath = null; 9750 if (PackageHelper.isContainerMounted(cid)) { 9751 // Unmount the container 9752 if (!PackageHelper.unMountSdDir(cid)) { 9753 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9754 return false; 9755 } 9756 } 9757 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9758 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9759 " which might be stale. Will try to clean up."); 9760 // Clean up the stale container and proceed to recreate. 9761 if (!PackageHelper.destroySdDir(newCacheId)) { 9762 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9763 return false; 9764 } 9765 // Successfully cleaned up stale container. Try to rename again. 9766 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9767 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9768 + " inspite of cleaning it up."); 9769 return false; 9770 } 9771 } 9772 if (!PackageHelper.isContainerMounted(newCacheId)) { 9773 Slog.w(TAG, "Mounting container " + newCacheId); 9774 newMountPath = PackageHelper.mountSdDir(newCacheId, 9775 getEncryptKey(), Process.SYSTEM_UID); 9776 } else { 9777 newMountPath = PackageHelper.getSdDir(newCacheId); 9778 } 9779 if (newMountPath == null) { 9780 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9781 return false; 9782 } 9783 Log.i(TAG, "Succesfully renamed " + cid + 9784 " to " + newCacheId + 9785 " at new path: " + newMountPath); 9786 cid = newCacheId; 9787 9788 final File beforeCodeFile = new File(packagePath); 9789 setMountPath(newMountPath); 9790 final File afterCodeFile = new File(packagePath); 9791 9792 // Reflect the rename in scanned details 9793 pkg.codePath = afterCodeFile.getAbsolutePath(); 9794 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9795 pkg.baseCodePath); 9796 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9797 pkg.splitCodePaths); 9798 9799 // Reflect the rename in app info 9800 pkg.applicationInfo.setCodePath(pkg.codePath); 9801 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9802 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9803 pkg.applicationInfo.setResourcePath(pkg.codePath); 9804 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9805 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9806 9807 return true; 9808 } 9809 9810 private void setMountPath(String mountPath) { 9811 final File mountFile = new File(mountPath); 9812 9813 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9814 if (monolithicFile.exists()) { 9815 packagePath = monolithicFile.getAbsolutePath(); 9816 if (isFwdLocked()) { 9817 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9818 } else { 9819 resourcePath = packagePath; 9820 } 9821 } else { 9822 packagePath = mountFile.getAbsolutePath(); 9823 resourcePath = packagePath; 9824 } 9825 9826 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9827 } 9828 9829 int doPostInstall(int status, int uid) { 9830 if (status != PackageManager.INSTALL_SUCCEEDED) { 9831 cleanUp(); 9832 } else { 9833 final int groupOwner; 9834 final String protectedFile; 9835 if (isFwdLocked()) { 9836 groupOwner = UserHandle.getSharedAppGid(uid); 9837 protectedFile = RES_FILE_NAME; 9838 } else { 9839 groupOwner = -1; 9840 protectedFile = null; 9841 } 9842 9843 if (uid < Process.FIRST_APPLICATION_UID 9844 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9845 Slog.e(TAG, "Failed to finalize " + cid); 9846 PackageHelper.destroySdDir(cid); 9847 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9848 } 9849 9850 boolean mounted = PackageHelper.isContainerMounted(cid); 9851 if (!mounted) { 9852 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9853 } 9854 } 9855 return status; 9856 } 9857 9858 private void cleanUp() { 9859 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9860 9861 // Destroy secure container 9862 PackageHelper.destroySdDir(cid); 9863 } 9864 9865 private List<String> getAllCodePaths() { 9866 final File codeFile = new File(getCodePath()); 9867 if (codeFile != null && codeFile.exists()) { 9868 try { 9869 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9870 return pkg.getAllCodePaths(); 9871 } catch (PackageParserException e) { 9872 // Ignored; we tried our best 9873 } 9874 } 9875 return Collections.EMPTY_LIST; 9876 } 9877 9878 void cleanUpResourcesLI() { 9879 // Enumerate all code paths before deleting 9880 cleanUpResourcesLI(getAllCodePaths()); 9881 } 9882 9883 private void cleanUpResourcesLI(List<String> allCodePaths) { 9884 cleanUp(); 9885 removeDexFiles(allCodePaths, instructionSets); 9886 } 9887 9888 9889 9890 String getPackageName() { 9891 return getAsecPackageName(cid); 9892 } 9893 9894 boolean doPostDeleteLI(boolean delete) { 9895 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9896 final List<String> allCodePaths = getAllCodePaths(); 9897 boolean mounted = PackageHelper.isContainerMounted(cid); 9898 if (mounted) { 9899 // Unmount first 9900 if (PackageHelper.unMountSdDir(cid)) { 9901 mounted = false; 9902 } 9903 } 9904 if (!mounted && delete) { 9905 cleanUpResourcesLI(allCodePaths); 9906 } 9907 return !mounted; 9908 } 9909 9910 @Override 9911 int doPreCopy() { 9912 if (isFwdLocked()) { 9913 if (!PackageHelper.fixSdPermissions(cid, 9914 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9915 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9916 } 9917 } 9918 9919 return PackageManager.INSTALL_SUCCEEDED; 9920 } 9921 9922 @Override 9923 int doPostCopy(int uid) { 9924 if (isFwdLocked()) { 9925 if (uid < Process.FIRST_APPLICATION_UID 9926 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9927 RES_FILE_NAME)) { 9928 Slog.e(TAG, "Failed to finalize " + cid); 9929 PackageHelper.destroySdDir(cid); 9930 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9931 } 9932 } 9933 9934 return PackageManager.INSTALL_SUCCEEDED; 9935 } 9936 } 9937 9938 static String getAsecPackageName(String packageCid) { 9939 int idx = packageCid.lastIndexOf("-"); 9940 if (idx == -1) { 9941 return packageCid; 9942 } 9943 return packageCid.substring(0, idx); 9944 } 9945 9946 // Utility method used to create code paths based on package name and available index. 9947 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9948 String idxStr = ""; 9949 int idx = 1; 9950 // Fall back to default value of idx=1 if prefix is not 9951 // part of oldCodePath 9952 if (oldCodePath != null) { 9953 String subStr = oldCodePath; 9954 // Drop the suffix right away 9955 if (suffix != null && subStr.endsWith(suffix)) { 9956 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9957 } 9958 // If oldCodePath already contains prefix find out the 9959 // ending index to either increment or decrement. 9960 int sidx = subStr.lastIndexOf(prefix); 9961 if (sidx != -1) { 9962 subStr = subStr.substring(sidx + prefix.length()); 9963 if (subStr != null) { 9964 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9965 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9966 } 9967 try { 9968 idx = Integer.parseInt(subStr); 9969 if (idx <= 1) { 9970 idx++; 9971 } else { 9972 idx--; 9973 } 9974 } catch(NumberFormatException e) { 9975 } 9976 } 9977 } 9978 } 9979 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9980 return prefix + idxStr; 9981 } 9982 9983 private File getNextCodePath(String packageName) { 9984 int suffix = 1; 9985 File result; 9986 do { 9987 result = new File(mAppInstallDir, packageName + "-" + suffix); 9988 suffix++; 9989 } while (result.exists()); 9990 return result; 9991 } 9992 9993 // Utility method used to ignore ADD/REMOVE events 9994 // by directory observer. 9995 private static boolean ignoreCodePath(String fullPathStr) { 9996 String apkName = deriveCodePathName(fullPathStr); 9997 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9998 if (idx != -1 && ((idx+1) < apkName.length())) { 9999 // Make sure the package ends with a numeral 10000 String version = apkName.substring(idx+1); 10001 try { 10002 Integer.parseInt(version); 10003 return true; 10004 } catch (NumberFormatException e) {} 10005 } 10006 return false; 10007 } 10008 10009 // Utility method that returns the relative package path with respect 10010 // to the installation directory. Like say for /data/data/com.test-1.apk 10011 // string com.test-1 is returned. 10012 static String deriveCodePathName(String codePath) { 10013 if (codePath == null) { 10014 return null; 10015 } 10016 final File codeFile = new File(codePath); 10017 final String name = codeFile.getName(); 10018 if (codeFile.isDirectory()) { 10019 return name; 10020 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10021 final int lastDot = name.lastIndexOf('.'); 10022 return name.substring(0, lastDot); 10023 } else { 10024 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10025 return null; 10026 } 10027 } 10028 10029 class PackageInstalledInfo { 10030 String name; 10031 int uid; 10032 // The set of users that originally had this package installed. 10033 int[] origUsers; 10034 // The set of users that now have this package installed. 10035 int[] newUsers; 10036 PackageParser.Package pkg; 10037 int returnCode; 10038 String returnMsg; 10039 PackageRemovedInfo removedInfo; 10040 10041 public void setError(int code, String msg) { 10042 returnCode = code; 10043 returnMsg = msg; 10044 Slog.w(TAG, msg); 10045 } 10046 10047 public void setError(String msg, PackageParserException e) { 10048 returnCode = e.error; 10049 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10050 Slog.w(TAG, msg, e); 10051 } 10052 10053 public void setError(String msg, PackageManagerException e) { 10054 returnCode = e.error; 10055 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10056 Slog.w(TAG, msg, e); 10057 } 10058 10059 // In some error cases we want to convey more info back to the observer 10060 String origPackage; 10061 String origPermission; 10062 } 10063 10064 /* 10065 * Install a non-existing package. 10066 */ 10067 private void installNewPackageLI(PackageParser.Package pkg, 10068 int parseFlags, int scanFlags, UserHandle user, 10069 String installerPackageName, PackageInstalledInfo res) { 10070 // Remember this for later, in case we need to rollback this install 10071 String pkgName = pkg.packageName; 10072 10073 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10074 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10075 synchronized(mPackages) { 10076 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10077 // A package with the same name is already installed, though 10078 // it has been renamed to an older name. The package we 10079 // are trying to install should be installed as an update to 10080 // the existing one, but that has not been requested, so bail. 10081 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10082 + " without first uninstalling package running as " 10083 + mSettings.mRenamedPackages.get(pkgName)); 10084 return; 10085 } 10086 if (mPackages.containsKey(pkgName)) { 10087 // Don't allow installation over an existing package with the same name. 10088 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10089 + " without first uninstalling."); 10090 return; 10091 } 10092 } 10093 10094 try { 10095 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10096 System.currentTimeMillis(), user); 10097 10098 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10099 // delete the partially installed application. the data directory will have to be 10100 // restored if it was already existing 10101 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10102 // remove package from internal structures. Note that we want deletePackageX to 10103 // delete the package data and cache directories that it created in 10104 // scanPackageLocked, unless those directories existed before we even tried to 10105 // install. 10106 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10107 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10108 res.removedInfo, true); 10109 } 10110 10111 } catch (PackageManagerException e) { 10112 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10113 } 10114 } 10115 10116 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10117 // Upgrade keysets are being used. Determine if new package has a superset of the 10118 // required keys. 10119 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10121 for (int i = 0; i < upgradeKeySets.length; i++) { 10122 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10123 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10124 return true; 10125 } 10126 } 10127 return false; 10128 } 10129 10130 private void replacePackageLI(PackageParser.Package pkg, 10131 int parseFlags, int scanFlags, UserHandle user, 10132 String installerPackageName, PackageInstalledInfo res) { 10133 PackageParser.Package oldPackage; 10134 String pkgName = pkg.packageName; 10135 int[] allUsers; 10136 boolean[] perUserInstalled; 10137 10138 // First find the old package info and check signatures 10139 synchronized(mPackages) { 10140 oldPackage = mPackages.get(pkgName); 10141 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10142 PackageSetting ps = mSettings.mPackages.get(pkgName); 10143 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10144 // default to original signature matching 10145 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10146 != PackageManager.SIGNATURE_MATCH) { 10147 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10148 "New package has a different signature: " + pkgName); 10149 return; 10150 } 10151 } else { 10152 if(!checkUpgradeKeySetLP(ps, pkg)) { 10153 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10154 "New package not signed by keys specified by upgrade-keysets: " 10155 + pkgName); 10156 return; 10157 } 10158 } 10159 10160 // In case of rollback, remember per-user/profile install state 10161 allUsers = sUserManager.getUserIds(); 10162 perUserInstalled = new boolean[allUsers.length]; 10163 for (int i = 0; i < allUsers.length; i++) { 10164 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10165 } 10166 } 10167 10168 boolean sysPkg = (isSystemApp(oldPackage)); 10169 if (sysPkg) { 10170 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10171 user, allUsers, perUserInstalled, installerPackageName, res); 10172 } else { 10173 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10174 user, allUsers, perUserInstalled, installerPackageName, res); 10175 } 10176 } 10177 10178 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10179 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10180 int[] allUsers, boolean[] perUserInstalled, 10181 String installerPackageName, PackageInstalledInfo res) { 10182 String pkgName = deletedPackage.packageName; 10183 boolean deletedPkg = true; 10184 boolean updatedSettings = false; 10185 10186 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10187 + deletedPackage); 10188 long origUpdateTime; 10189 if (pkg.mExtras != null) { 10190 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10191 } else { 10192 origUpdateTime = 0; 10193 } 10194 10195 // First delete the existing package while retaining the data directory 10196 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10197 res.removedInfo, true)) { 10198 // If the existing package wasn't successfully deleted 10199 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10200 deletedPkg = false; 10201 } else { 10202 // Successfully deleted the old package; proceed with replace. 10203 10204 // If deleted package lived in a container, give users a chance to 10205 // relinquish resources before killing. 10206 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10207 if (DEBUG_INSTALL) { 10208 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10209 } 10210 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10211 final ArrayList<String> pkgList = new ArrayList<String>(1); 10212 pkgList.add(deletedPackage.applicationInfo.packageName); 10213 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10214 } 10215 10216 deleteCodeCacheDirsLI(pkgName); 10217 try { 10218 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10219 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10220 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10221 user); 10222 updatedSettings = true; 10223 } catch (PackageManagerException e) { 10224 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10225 } 10226 } 10227 10228 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10229 // remove package from internal structures. Note that we want deletePackageX to 10230 // delete the package data and cache directories that it created in 10231 // scanPackageLocked, unless those directories existed before we even tried to 10232 // install. 10233 if(updatedSettings) { 10234 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10235 deletePackageLI( 10236 pkgName, null, true, allUsers, perUserInstalled, 10237 PackageManager.DELETE_KEEP_DATA, 10238 res.removedInfo, true); 10239 } 10240 // Since we failed to install the new package we need to restore the old 10241 // package that we deleted. 10242 if (deletedPkg) { 10243 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10244 File restoreFile = new File(deletedPackage.codePath); 10245 // Parse old package 10246 boolean oldOnSd = isExternal(deletedPackage); 10247 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10248 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10249 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10250 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10251 try { 10252 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10253 } catch (PackageManagerException e) { 10254 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10255 + e.getMessage()); 10256 return; 10257 } 10258 // Restore of old package succeeded. Update permissions. 10259 // writer 10260 synchronized (mPackages) { 10261 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10262 UPDATE_PERMISSIONS_ALL); 10263 // can downgrade to reader 10264 mSettings.writeLPr(); 10265 } 10266 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10267 } 10268 } 10269 } 10270 10271 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10272 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10273 int[] allUsers, boolean[] perUserInstalled, 10274 String installerPackageName, PackageInstalledInfo res) { 10275 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10276 + ", old=" + deletedPackage); 10277 boolean disabledSystem = false; 10278 boolean updatedSettings = false; 10279 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10280 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10281 != 0) { 10282 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10283 } 10284 String packageName = deletedPackage.packageName; 10285 if (packageName == null) { 10286 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10287 "Attempt to delete null packageName."); 10288 return; 10289 } 10290 PackageParser.Package oldPkg; 10291 PackageSetting oldPkgSetting; 10292 // reader 10293 synchronized (mPackages) { 10294 oldPkg = mPackages.get(packageName); 10295 oldPkgSetting = mSettings.mPackages.get(packageName); 10296 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10297 (oldPkgSetting == null)) { 10298 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10299 "Couldn't find package:" + packageName + " information"); 10300 return; 10301 } 10302 } 10303 10304 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10305 10306 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10307 res.removedInfo.removedPackage = packageName; 10308 // Remove existing system package 10309 removePackageLI(oldPkgSetting, true); 10310 // writer 10311 synchronized (mPackages) { 10312 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10313 if (!disabledSystem && deletedPackage != null) { 10314 // We didn't need to disable the .apk as a current system package, 10315 // which means we are replacing another update that is already 10316 // installed. We need to make sure to delete the older one's .apk. 10317 res.removedInfo.args = createInstallArgsForExisting(0, 10318 deletedPackage.applicationInfo.getCodePath(), 10319 deletedPackage.applicationInfo.getResourcePath(), 10320 deletedPackage.applicationInfo.nativeLibraryRootDir, 10321 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10322 } else { 10323 res.removedInfo.args = null; 10324 } 10325 } 10326 10327 // Successfully disabled the old package. Now proceed with re-installation 10328 deleteCodeCacheDirsLI(packageName); 10329 10330 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10331 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10332 10333 PackageParser.Package newPackage = null; 10334 try { 10335 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10336 if (newPackage.mExtras != null) { 10337 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10338 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10339 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10340 10341 // is the update attempting to change shared user? that isn't going to work... 10342 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10343 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10344 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10345 + " to " + newPkgSetting.sharedUser); 10346 updatedSettings = true; 10347 } 10348 } 10349 10350 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10351 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10352 user); 10353 updatedSettings = true; 10354 } 10355 10356 } catch (PackageManagerException e) { 10357 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10358 } 10359 10360 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10361 // Re installation failed. Restore old information 10362 // Remove new pkg information 10363 if (newPackage != null) { 10364 removeInstalledPackageLI(newPackage, true); 10365 } 10366 // Add back the old system package 10367 try { 10368 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10369 } catch (PackageManagerException e) { 10370 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10371 } 10372 // Restore the old system information in Settings 10373 synchronized (mPackages) { 10374 if (disabledSystem) { 10375 mSettings.enableSystemPackageLPw(packageName); 10376 } 10377 if (updatedSettings) { 10378 mSettings.setInstallerPackageName(packageName, 10379 oldPkgSetting.installerPackageName); 10380 } 10381 mSettings.writeLPr(); 10382 } 10383 } 10384 } 10385 10386 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10387 int[] allUsers, boolean[] perUserInstalled, 10388 PackageInstalledInfo res, UserHandle user) { 10389 String pkgName = newPackage.packageName; 10390 synchronized (mPackages) { 10391 //write settings. the installStatus will be incomplete at this stage. 10392 //note that the new package setting would have already been 10393 //added to mPackages. It hasn't been persisted yet. 10394 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10395 mSettings.writeLPr(); 10396 } 10397 10398 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10399 10400 synchronized (mPackages) { 10401 updatePermissionsLPw(newPackage.packageName, newPackage, 10402 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10403 ? UPDATE_PERMISSIONS_ALL : 0)); 10404 // For system-bundled packages, we assume that installing an upgraded version 10405 // of the package implies that the user actually wants to run that new code, 10406 // so we enable the package. 10407 PackageSetting ps = mSettings.mPackages.get(pkgName); 10408 if (ps != null) { 10409 if (isSystemApp(newPackage)) { 10410 // NB: implicit assumption that system package upgrades apply to all users 10411 if (DEBUG_INSTALL) { 10412 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10413 } 10414 if (res.origUsers != null) { 10415 for (int userHandle : res.origUsers) { 10416 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10417 userHandle, installerPackageName); 10418 } 10419 } 10420 // Also convey the prior install/uninstall state 10421 if (allUsers != null && perUserInstalled != null) { 10422 for (int i = 0; i < allUsers.length; i++) { 10423 if (DEBUG_INSTALL) { 10424 Slog.d(TAG, " user " + allUsers[i] 10425 + " => " + perUserInstalled[i]); 10426 } 10427 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10428 } 10429 // these install state changes will be persisted in the 10430 // upcoming call to mSettings.writeLPr(). 10431 } 10432 } 10433 // It's implied that when a user requests installation, they want the app to be 10434 // installed and enabled. 10435 int userId = user.getIdentifier(); 10436 if (userId != UserHandle.USER_ALL) { 10437 ps.setInstalled(true, userId); 10438 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10439 } 10440 } 10441 res.name = pkgName; 10442 res.uid = newPackage.applicationInfo.uid; 10443 res.pkg = newPackage; 10444 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10445 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10446 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10447 //to update install status 10448 mSettings.writeLPr(); 10449 } 10450 } 10451 10452 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10453 final int installFlags = args.installFlags; 10454 String installerPackageName = args.installerPackageName; 10455 File tmpPackageFile = new File(args.getCodePath()); 10456 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10457 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10458 boolean replace = false; 10459 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10460 // Result object to be returned 10461 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10462 10463 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10464 // Retrieve PackageSettings and parse package 10465 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10466 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10467 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10468 PackageParser pp = new PackageParser(); 10469 pp.setSeparateProcesses(mSeparateProcesses); 10470 pp.setDisplayMetrics(mMetrics); 10471 10472 final PackageParser.Package pkg; 10473 try { 10474 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10475 } catch (PackageParserException e) { 10476 res.setError("Failed parse during installPackageLI", e); 10477 return; 10478 } 10479 10480 // Mark that we have an install time CPU ABI override. 10481 pkg.cpuAbiOverride = args.abiOverride; 10482 10483 String pkgName = res.name = pkg.packageName; 10484 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10485 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10486 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10487 return; 10488 } 10489 } 10490 10491 try { 10492 pp.collectCertificates(pkg, parseFlags); 10493 pp.collectManifestDigest(pkg); 10494 } catch (PackageParserException e) { 10495 res.setError("Failed collect during installPackageLI", e); 10496 return; 10497 } 10498 10499 /* If the installer passed in a manifest digest, compare it now. */ 10500 if (args.manifestDigest != null) { 10501 if (DEBUG_INSTALL) { 10502 final String parsedManifest = pkg.manifestDigest == null ? "null" 10503 : pkg.manifestDigest.toString(); 10504 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10505 + parsedManifest); 10506 } 10507 10508 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10509 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10510 return; 10511 } 10512 } else if (DEBUG_INSTALL) { 10513 final String parsedManifest = pkg.manifestDigest == null 10514 ? "null" : pkg.manifestDigest.toString(); 10515 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10516 } 10517 10518 // Get rid of all references to package scan path via parser. 10519 pp = null; 10520 String oldCodePath = null; 10521 boolean systemApp = false; 10522 synchronized (mPackages) { 10523 // Check if installing already existing package 10524 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10525 String oldName = mSettings.mRenamedPackages.get(pkgName); 10526 if (pkg.mOriginalPackages != null 10527 && pkg.mOriginalPackages.contains(oldName) 10528 && mPackages.containsKey(oldName)) { 10529 // This package is derived from an original package, 10530 // and this device has been updating from that original 10531 // name. We must continue using the original name, so 10532 // rename the new package here. 10533 pkg.setPackageName(oldName); 10534 pkgName = pkg.packageName; 10535 replace = true; 10536 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10537 + oldName + " pkgName=" + pkgName); 10538 } else if (mPackages.containsKey(pkgName)) { 10539 // This package, under its official name, already exists 10540 // on the device; we should replace it. 10541 replace = true; 10542 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10543 } 10544 } 10545 10546 PackageSetting ps = mSettings.mPackages.get(pkgName); 10547 if (ps != null) { 10548 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10549 10550 // Quick sanity check that we're signed correctly if updating; 10551 // we'll check this again later when scanning, but we want to 10552 // bail early here before tripping over redefined permissions. 10553 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10554 try { 10555 verifySignaturesLP(ps, pkg); 10556 } catch (PackageManagerException e) { 10557 res.setError(e.error, e.getMessage()); 10558 return; 10559 } 10560 } else { 10561 if (!checkUpgradeKeySetLP(ps, pkg)) { 10562 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10563 + pkg.packageName + " upgrade keys do not match the " 10564 + "previously installed version"); 10565 return; 10566 } 10567 } 10568 10569 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10570 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10571 systemApp = (ps.pkg.applicationInfo.flags & 10572 ApplicationInfo.FLAG_SYSTEM) != 0; 10573 } 10574 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10575 } 10576 10577 // Check whether the newly-scanned package wants to define an already-defined perm 10578 int N = pkg.permissions.size(); 10579 for (int i = N-1; i >= 0; i--) { 10580 PackageParser.Permission perm = pkg.permissions.get(i); 10581 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10582 if (bp != null) { 10583 // If the defining package is signed with our cert, it's okay. This 10584 // also includes the "updating the same package" case, of course. 10585 // "updating same package" could also involve key-rotation. 10586 final boolean sigsOk; 10587 if (!bp.sourcePackage.equals(pkg.packageName) 10588 || !(bp.packageSetting instanceof PackageSetting) 10589 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10590 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10591 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10592 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10593 } else { 10594 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10595 } 10596 if (!sigsOk) { 10597 // If the owning package is the system itself, we log but allow 10598 // install to proceed; we fail the install on all other permission 10599 // redefinitions. 10600 if (!bp.sourcePackage.equals("android")) { 10601 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10602 + pkg.packageName + " attempting to redeclare permission " 10603 + perm.info.name + " already owned by " + bp.sourcePackage); 10604 res.origPermission = perm.info.name; 10605 res.origPackage = bp.sourcePackage; 10606 return; 10607 } else { 10608 Slog.w(TAG, "Package " + pkg.packageName 10609 + " attempting to redeclare system permission " 10610 + perm.info.name + "; ignoring new declaration"); 10611 pkg.permissions.remove(i); 10612 } 10613 } 10614 } 10615 } 10616 10617 } 10618 10619 if (systemApp && onSd) { 10620 // Disable updates to system apps on sdcard 10621 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10622 "Cannot install updates to system apps on sdcard"); 10623 return; 10624 } 10625 10626 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10627 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10628 return; 10629 } 10630 10631 if (replace) { 10632 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10633 installerPackageName, res); 10634 } else { 10635 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10636 args.user, installerPackageName, res); 10637 } 10638 synchronized (mPackages) { 10639 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10640 if (ps != null) { 10641 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10642 } 10643 } 10644 } 10645 10646 private static boolean isMultiArch(PackageSetting ps) { 10647 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10648 } 10649 10650 private static boolean isMultiArch(ApplicationInfo info) { 10651 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10652 } 10653 10654 private static boolean isExternal(PackageParser.Package pkg) { 10655 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10656 } 10657 10658 private static boolean isExternal(PackageSetting ps) { 10659 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10660 } 10661 10662 private static boolean isExternal(ApplicationInfo info) { 10663 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10664 } 10665 10666 private static boolean isSystemApp(PackageParser.Package pkg) { 10667 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10668 } 10669 10670 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10671 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10672 } 10673 10674 private static boolean isSystemApp(ApplicationInfo info) { 10675 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10676 } 10677 10678 private static boolean isSystemApp(PackageSetting ps) { 10679 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10680 } 10681 10682 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10683 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10684 } 10685 10686 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10687 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10688 } 10689 10690 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10691 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10692 } 10693 10694 private int packageFlagsToInstallFlags(PackageSetting ps) { 10695 int installFlags = 0; 10696 if (isExternal(ps)) { 10697 installFlags |= PackageManager.INSTALL_EXTERNAL; 10698 } 10699 if (ps.isForwardLocked()) { 10700 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10701 } 10702 return installFlags; 10703 } 10704 10705 private void deleteTempPackageFiles() { 10706 final FilenameFilter filter = new FilenameFilter() { 10707 public boolean accept(File dir, String name) { 10708 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10709 } 10710 }; 10711 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10712 file.delete(); 10713 } 10714 } 10715 10716 @Override 10717 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10718 int flags) { 10719 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10720 flags); 10721 } 10722 10723 @Override 10724 public void deletePackage(final String packageName, 10725 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10726 mContext.enforceCallingOrSelfPermission( 10727 android.Manifest.permission.DELETE_PACKAGES, null); 10728 final int uid = Binder.getCallingUid(); 10729 if (UserHandle.getUserId(uid) != userId) { 10730 mContext.enforceCallingPermission( 10731 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10732 "deletePackage for user " + userId); 10733 } 10734 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10735 try { 10736 observer.onPackageDeleted(packageName, 10737 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10738 } catch (RemoteException re) { 10739 } 10740 return; 10741 } 10742 10743 boolean uninstallBlocked = false; 10744 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10745 int[] users = sUserManager.getUserIds(); 10746 for (int i = 0; i < users.length; ++i) { 10747 if (getBlockUninstallForUser(packageName, users[i])) { 10748 uninstallBlocked = true; 10749 break; 10750 } 10751 } 10752 } else { 10753 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10754 } 10755 if (uninstallBlocked) { 10756 try { 10757 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10758 null); 10759 } catch (RemoteException re) { 10760 } 10761 return; 10762 } 10763 10764 if (DEBUG_REMOVE) { 10765 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10766 } 10767 // Queue up an async operation since the package deletion may take a little while. 10768 mHandler.post(new Runnable() { 10769 public void run() { 10770 mHandler.removeCallbacks(this); 10771 final int returnCode = deletePackageX(packageName, userId, flags); 10772 if (observer != null) { 10773 try { 10774 observer.onPackageDeleted(packageName, returnCode, null); 10775 } catch (RemoteException e) { 10776 Log.i(TAG, "Observer no longer exists."); 10777 } //end catch 10778 } //end if 10779 } //end run 10780 }); 10781 } 10782 10783 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10784 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10785 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10786 try { 10787 if (dpm != null) { 10788 if (dpm.isDeviceOwner(packageName)) { 10789 return true; 10790 } 10791 int[] users; 10792 if (userId == UserHandle.USER_ALL) { 10793 users = sUserManager.getUserIds(); 10794 } else { 10795 users = new int[]{userId}; 10796 } 10797 for (int i = 0; i < users.length; ++i) { 10798 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10799 return true; 10800 } 10801 } 10802 } 10803 } catch (RemoteException e) { 10804 } 10805 return false; 10806 } 10807 10808 /** 10809 * This method is an internal method that could be get invoked either 10810 * to delete an installed package or to clean up a failed installation. 10811 * After deleting an installed package, a broadcast is sent to notify any 10812 * listeners that the package has been installed. For cleaning up a failed 10813 * installation, the broadcast is not necessary since the package's 10814 * installation wouldn't have sent the initial broadcast either 10815 * The key steps in deleting a package are 10816 * deleting the package information in internal structures like mPackages, 10817 * deleting the packages base directories through installd 10818 * updating mSettings to reflect current status 10819 * persisting settings for later use 10820 * sending a broadcast if necessary 10821 */ 10822 private int deletePackageX(String packageName, int userId, int flags) { 10823 final PackageRemovedInfo info = new PackageRemovedInfo(); 10824 final boolean res; 10825 10826 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10827 ? UserHandle.ALL : new UserHandle(userId); 10828 10829 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10830 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10831 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10832 } 10833 10834 boolean removedForAllUsers = false; 10835 boolean systemUpdate = false; 10836 10837 // for the uninstall-updates case and restricted profiles, remember the per- 10838 // userhandle installed state 10839 int[] allUsers; 10840 boolean[] perUserInstalled; 10841 synchronized (mPackages) { 10842 PackageSetting ps = mSettings.mPackages.get(packageName); 10843 allUsers = sUserManager.getUserIds(); 10844 perUserInstalled = new boolean[allUsers.length]; 10845 for (int i = 0; i < allUsers.length; i++) { 10846 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10847 } 10848 } 10849 10850 synchronized (mInstallLock) { 10851 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10852 res = deletePackageLI(packageName, removeForUser, 10853 true, allUsers, perUserInstalled, 10854 flags | REMOVE_CHATTY, info, true); 10855 systemUpdate = info.isRemovedPackageSystemUpdate; 10856 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10857 removedForAllUsers = true; 10858 } 10859 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10860 + " removedForAllUsers=" + removedForAllUsers); 10861 } 10862 10863 if (res) { 10864 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10865 10866 // If the removed package was a system update, the old system package 10867 // was re-enabled; we need to broadcast this information 10868 if (systemUpdate) { 10869 Bundle extras = new Bundle(1); 10870 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10871 ? info.removedAppId : info.uid); 10872 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10873 10874 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10875 extras, null, null, null); 10876 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10877 extras, null, null, null); 10878 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10879 null, packageName, null, null); 10880 } 10881 } 10882 // Force a gc here. 10883 Runtime.getRuntime().gc(); 10884 // Delete the resources here after sending the broadcast to let 10885 // other processes clean up before deleting resources. 10886 if (info.args != null) { 10887 synchronized (mInstallLock) { 10888 info.args.doPostDeleteLI(true); 10889 } 10890 } 10891 10892 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10893 } 10894 10895 static class PackageRemovedInfo { 10896 String removedPackage; 10897 int uid = -1; 10898 int removedAppId = -1; 10899 int[] removedUsers = null; 10900 boolean isRemovedPackageSystemUpdate = false; 10901 // Clean up resources deleted packages. 10902 InstallArgs args = null; 10903 10904 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10905 Bundle extras = new Bundle(1); 10906 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10907 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10908 if (replacing) { 10909 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10910 } 10911 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10912 if (removedPackage != null) { 10913 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10914 extras, null, null, removedUsers); 10915 if (fullRemove && !replacing) { 10916 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10917 extras, null, null, removedUsers); 10918 } 10919 } 10920 if (removedAppId >= 0) { 10921 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10922 removedUsers); 10923 } 10924 } 10925 } 10926 10927 /* 10928 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10929 * flag is not set, the data directory is removed as well. 10930 * make sure this flag is set for partially installed apps. If not its meaningless to 10931 * delete a partially installed application. 10932 */ 10933 private void removePackageDataLI(PackageSetting ps, 10934 int[] allUserHandles, boolean[] perUserInstalled, 10935 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10936 String packageName = ps.name; 10937 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10938 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10939 // Retrieve object to delete permissions for shared user later on 10940 final PackageSetting deletedPs; 10941 // reader 10942 synchronized (mPackages) { 10943 deletedPs = mSettings.mPackages.get(packageName); 10944 if (outInfo != null) { 10945 outInfo.removedPackage = packageName; 10946 outInfo.removedUsers = deletedPs != null 10947 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10948 : null; 10949 } 10950 } 10951 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10952 removeDataDirsLI(packageName); 10953 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10954 } 10955 // writer 10956 synchronized (mPackages) { 10957 if (deletedPs != null) { 10958 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10959 if (outInfo != null) { 10960 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10961 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10962 } 10963 updatePermissionsLPw(deletedPs.name, null, 0); 10964 if (deletedPs.sharedUser != null) { 10965 // Remove permissions associated with package. Since runtime 10966 // permissions are per user we have to kill the removed package 10967 // or packages running under the shared user of the removed 10968 // package if revoking the permissions requested only by the removed 10969 // package is successful and this causes a change in gids. 10970 for (int userId : UserManagerService.getInstance().getUserIds()) { 10971 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 10972 userId); 10973 if (userIdToKill == userId) { 10974 // If gids changed for this user, kill all affected packages. 10975 killSettingPackagesForUser(deletedPs, userIdToKill, 10976 KILL_APP_REASON_GIDS_CHANGED); 10977 } else if (userIdToKill == UserHandle.USER_ALL) { 10978 // If gids changed for all users, kill them all - done. 10979 killSettingPackagesForUser(deletedPs, userIdToKill, 10980 KILL_APP_REASON_GIDS_CHANGED); 10981 break; 10982 } 10983 } 10984 } 10985 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10986 } 10987 // make sure to preserve per-user disabled state if this removal was just 10988 // a downgrade of a system app to the factory package 10989 if (allUserHandles != null && perUserInstalled != null) { 10990 if (DEBUG_REMOVE) { 10991 Slog.d(TAG, "Propagating install state across downgrade"); 10992 } 10993 for (int i = 0; i < allUserHandles.length; i++) { 10994 if (DEBUG_REMOVE) { 10995 Slog.d(TAG, " user " + allUserHandles[i] 10996 + " => " + perUserInstalled[i]); 10997 } 10998 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10999 } 11000 } 11001 } 11002 // can downgrade to reader 11003 if (writeSettings) { 11004 // Save settings now 11005 mSettings.writeLPr(); 11006 } 11007 } 11008 if (outInfo != null) { 11009 // A user ID was deleted here. Go through all users and remove it 11010 // from KeyStore. 11011 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11012 } 11013 } 11014 11015 static boolean locationIsPrivileged(File path) { 11016 try { 11017 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11018 .getCanonicalPath(); 11019 return path.getCanonicalPath().startsWith(privilegedAppDir); 11020 } catch (IOException e) { 11021 Slog.e(TAG, "Unable to access code path " + path); 11022 } 11023 return false; 11024 } 11025 11026 /* 11027 * Tries to delete system package. 11028 */ 11029 private boolean deleteSystemPackageLI(PackageSetting newPs, 11030 int[] allUserHandles, boolean[] perUserInstalled, 11031 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11032 final boolean applyUserRestrictions 11033 = (allUserHandles != null) && (perUserInstalled != null); 11034 PackageSetting disabledPs = null; 11035 // Confirm if the system package has been updated 11036 // An updated system app can be deleted. This will also have to restore 11037 // the system pkg from system partition 11038 // reader 11039 synchronized (mPackages) { 11040 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11041 } 11042 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11043 + " disabledPs=" + disabledPs); 11044 if (disabledPs == null) { 11045 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11046 return false; 11047 } else if (DEBUG_REMOVE) { 11048 Slog.d(TAG, "Deleting system pkg from data partition"); 11049 } 11050 if (DEBUG_REMOVE) { 11051 if (applyUserRestrictions) { 11052 Slog.d(TAG, "Remembering install states:"); 11053 for (int i = 0; i < allUserHandles.length; i++) { 11054 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11055 } 11056 } 11057 } 11058 // Delete the updated package 11059 outInfo.isRemovedPackageSystemUpdate = true; 11060 if (disabledPs.versionCode < newPs.versionCode) { 11061 // Delete data for downgrades 11062 flags &= ~PackageManager.DELETE_KEEP_DATA; 11063 } else { 11064 // Preserve data by setting flag 11065 flags |= PackageManager.DELETE_KEEP_DATA; 11066 } 11067 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11068 allUserHandles, perUserInstalled, outInfo, writeSettings); 11069 if (!ret) { 11070 return false; 11071 } 11072 // writer 11073 synchronized (mPackages) { 11074 // Reinstate the old system package 11075 mSettings.enableSystemPackageLPw(newPs.name); 11076 // Remove any native libraries from the upgraded package. 11077 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11078 } 11079 // Install the system package 11080 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11081 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11082 if (locationIsPrivileged(disabledPs.codePath)) { 11083 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11084 } 11085 11086 final PackageParser.Package newPkg; 11087 try { 11088 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11089 } catch (PackageManagerException e) { 11090 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11091 return false; 11092 } 11093 11094 // writer 11095 synchronized (mPackages) { 11096 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11097 updatePermissionsLPw(newPkg.packageName, newPkg, 11098 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11099 if (applyUserRestrictions) { 11100 if (DEBUG_REMOVE) { 11101 Slog.d(TAG, "Propagating install state across reinstall"); 11102 } 11103 for (int i = 0; i < allUserHandles.length; i++) { 11104 if (DEBUG_REMOVE) { 11105 Slog.d(TAG, " user " + allUserHandles[i] 11106 + " => " + perUserInstalled[i]); 11107 } 11108 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11109 } 11110 // Regardless of writeSettings we need to ensure that this restriction 11111 // state propagation is persisted 11112 mSettings.writeAllUsersPackageRestrictionsLPr(); 11113 } 11114 // can downgrade to reader here 11115 if (writeSettings) { 11116 mSettings.writeLPr(); 11117 } 11118 } 11119 return true; 11120 } 11121 11122 private boolean deleteInstalledPackageLI(PackageSetting ps, 11123 boolean deleteCodeAndResources, int flags, 11124 int[] allUserHandles, boolean[] perUserInstalled, 11125 PackageRemovedInfo outInfo, boolean writeSettings) { 11126 if (outInfo != null) { 11127 outInfo.uid = ps.appId; 11128 } 11129 11130 // Delete package data from internal structures and also remove data if flag is set 11131 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11132 11133 // Delete application code and resources 11134 if (deleteCodeAndResources && (outInfo != null)) { 11135 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11136 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11137 getAppDexInstructionSets(ps)); 11138 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11139 } 11140 return true; 11141 } 11142 11143 @Override 11144 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11145 int userId) { 11146 mContext.enforceCallingOrSelfPermission( 11147 android.Manifest.permission.DELETE_PACKAGES, null); 11148 synchronized (mPackages) { 11149 PackageSetting ps = mSettings.mPackages.get(packageName); 11150 if (ps == null) { 11151 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11152 return false; 11153 } 11154 if (!ps.getInstalled(userId)) { 11155 // Can't block uninstall for an app that is not installed or enabled. 11156 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11157 return false; 11158 } 11159 ps.setBlockUninstall(blockUninstall, userId); 11160 mSettings.writePackageRestrictionsLPr(userId); 11161 } 11162 return true; 11163 } 11164 11165 @Override 11166 public boolean getBlockUninstallForUser(String packageName, int userId) { 11167 synchronized (mPackages) { 11168 PackageSetting ps = mSettings.mPackages.get(packageName); 11169 if (ps == null) { 11170 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11171 return false; 11172 } 11173 return ps.getBlockUninstall(userId); 11174 } 11175 } 11176 11177 /* 11178 * This method handles package deletion in general 11179 */ 11180 private boolean deletePackageLI(String packageName, UserHandle user, 11181 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11182 int flags, PackageRemovedInfo outInfo, 11183 boolean writeSettings) { 11184 if (packageName == null) { 11185 Slog.w(TAG, "Attempt to delete null packageName."); 11186 return false; 11187 } 11188 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11189 PackageSetting ps; 11190 boolean dataOnly = false; 11191 int removeUser = -1; 11192 int appId = -1; 11193 synchronized (mPackages) { 11194 ps = mSettings.mPackages.get(packageName); 11195 if (ps == null) { 11196 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11197 return false; 11198 } 11199 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11200 && user.getIdentifier() != UserHandle.USER_ALL) { 11201 // The caller is asking that the package only be deleted for a single 11202 // user. To do this, we just mark its uninstalled state and delete 11203 // its data. If this is a system app, we only allow this to happen if 11204 // they have set the special DELETE_SYSTEM_APP which requests different 11205 // semantics than normal for uninstalling system apps. 11206 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11207 ps.setUserState(user.getIdentifier(), 11208 COMPONENT_ENABLED_STATE_DEFAULT, 11209 false, //installed 11210 true, //stopped 11211 true, //notLaunched 11212 false, //hidden 11213 null, null, null, 11214 false // blockUninstall 11215 ); 11216 if (!isSystemApp(ps)) { 11217 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11218 // Other user still have this package installed, so all 11219 // we need to do is clear this user's data and save that 11220 // it is uninstalled. 11221 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11222 removeUser = user.getIdentifier(); 11223 appId = ps.appId; 11224 mSettings.writePackageRestrictionsLPr(removeUser); 11225 } else { 11226 // We need to set it back to 'installed' so the uninstall 11227 // broadcasts will be sent correctly. 11228 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11229 ps.setInstalled(true, user.getIdentifier()); 11230 } 11231 } else { 11232 // This is a system app, so we assume that the 11233 // other users still have this package installed, so all 11234 // we need to do is clear this user's data and save that 11235 // it is uninstalled. 11236 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11237 removeUser = user.getIdentifier(); 11238 appId = ps.appId; 11239 mSettings.writePackageRestrictionsLPr(removeUser); 11240 } 11241 } 11242 } 11243 11244 if (removeUser >= 0) { 11245 // From above, we determined that we are deleting this only 11246 // for a single user. Continue the work here. 11247 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11248 if (outInfo != null) { 11249 outInfo.removedPackage = packageName; 11250 outInfo.removedAppId = appId; 11251 outInfo.removedUsers = new int[] {removeUser}; 11252 } 11253 mInstaller.clearUserData(packageName, removeUser); 11254 removeKeystoreDataIfNeeded(removeUser, appId); 11255 schedulePackageCleaning(packageName, removeUser, false); 11256 return true; 11257 } 11258 11259 if (dataOnly) { 11260 // Delete application data first 11261 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11262 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11263 return true; 11264 } 11265 11266 boolean ret = false; 11267 if (isSystemApp(ps)) { 11268 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11269 // When an updated system application is deleted we delete the existing resources as well and 11270 // fall back to existing code in system partition 11271 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11272 flags, outInfo, writeSettings); 11273 } else { 11274 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11275 // Kill application pre-emptively especially for apps on sd. 11276 killApplication(packageName, ps.appId, "uninstall pkg"); 11277 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11278 allUserHandles, perUserInstalled, 11279 outInfo, writeSettings); 11280 } 11281 11282 return ret; 11283 } 11284 11285 private final class ClearStorageConnection implements ServiceConnection { 11286 IMediaContainerService mContainerService; 11287 11288 @Override 11289 public void onServiceConnected(ComponentName name, IBinder service) { 11290 synchronized (this) { 11291 mContainerService = IMediaContainerService.Stub.asInterface(service); 11292 notifyAll(); 11293 } 11294 } 11295 11296 @Override 11297 public void onServiceDisconnected(ComponentName name) { 11298 } 11299 } 11300 11301 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11302 final boolean mounted; 11303 if (Environment.isExternalStorageEmulated()) { 11304 mounted = true; 11305 } else { 11306 final String status = Environment.getExternalStorageState(); 11307 11308 mounted = status.equals(Environment.MEDIA_MOUNTED) 11309 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11310 } 11311 11312 if (!mounted) { 11313 return; 11314 } 11315 11316 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11317 int[] users; 11318 if (userId == UserHandle.USER_ALL) { 11319 users = sUserManager.getUserIds(); 11320 } else { 11321 users = new int[] { userId }; 11322 } 11323 final ClearStorageConnection conn = new ClearStorageConnection(); 11324 if (mContext.bindServiceAsUser( 11325 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11326 try { 11327 for (int curUser : users) { 11328 long timeout = SystemClock.uptimeMillis() + 5000; 11329 synchronized (conn) { 11330 long now = SystemClock.uptimeMillis(); 11331 while (conn.mContainerService == null && now < timeout) { 11332 try { 11333 conn.wait(timeout - now); 11334 } catch (InterruptedException e) { 11335 } 11336 } 11337 } 11338 if (conn.mContainerService == null) { 11339 return; 11340 } 11341 11342 final UserEnvironment userEnv = new UserEnvironment(curUser); 11343 clearDirectory(conn.mContainerService, 11344 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11345 if (allData) { 11346 clearDirectory(conn.mContainerService, 11347 userEnv.buildExternalStorageAppDataDirs(packageName)); 11348 clearDirectory(conn.mContainerService, 11349 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11350 } 11351 } 11352 } finally { 11353 mContext.unbindService(conn); 11354 } 11355 } 11356 } 11357 11358 @Override 11359 public void clearApplicationUserData(final String packageName, 11360 final IPackageDataObserver observer, final int userId) { 11361 mContext.enforceCallingOrSelfPermission( 11362 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11363 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11364 // Queue up an async operation since the package deletion may take a little while. 11365 mHandler.post(new Runnable() { 11366 public void run() { 11367 mHandler.removeCallbacks(this); 11368 final boolean succeeded; 11369 synchronized (mInstallLock) { 11370 succeeded = clearApplicationUserDataLI(packageName, userId); 11371 } 11372 clearExternalStorageDataSync(packageName, userId, true); 11373 if (succeeded) { 11374 // invoke DeviceStorageMonitor's update method to clear any notifications 11375 DeviceStorageMonitorInternal 11376 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11377 if (dsm != null) { 11378 dsm.checkMemory(); 11379 } 11380 } 11381 if(observer != null) { 11382 try { 11383 observer.onRemoveCompleted(packageName, succeeded); 11384 } catch (RemoteException e) { 11385 Log.i(TAG, "Observer no longer exists."); 11386 } 11387 } //end if observer 11388 } //end run 11389 }); 11390 } 11391 11392 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11393 if (packageName == null) { 11394 Slog.w(TAG, "Attempt to delete null packageName."); 11395 return false; 11396 } 11397 11398 // Try finding details about the requested package 11399 PackageParser.Package pkg; 11400 synchronized (mPackages) { 11401 pkg = mPackages.get(packageName); 11402 if (pkg == null) { 11403 final PackageSetting ps = mSettings.mPackages.get(packageName); 11404 if (ps != null) { 11405 pkg = ps.pkg; 11406 } 11407 } 11408 } 11409 11410 if (pkg == null) { 11411 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11412 } 11413 11414 // Always delete data directories for package, even if we found no other 11415 // record of app. This helps users recover from UID mismatches without 11416 // resorting to a full data wipe. 11417 int retCode = mInstaller.clearUserData(packageName, userId); 11418 if (retCode < 0) { 11419 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11420 return false; 11421 } 11422 11423 if (pkg == null) { 11424 return false; 11425 } 11426 11427 if (pkg != null && pkg.applicationInfo != null) { 11428 final int appId = pkg.applicationInfo.uid; 11429 removeKeystoreDataIfNeeded(userId, appId); 11430 } 11431 11432 // Create a native library symlink only if we have native libraries 11433 // and if the native libraries are 32 bit libraries. We do not provide 11434 // this symlink for 64 bit libraries. 11435 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11436 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11437 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11438 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11439 Slog.w(TAG, "Failed linking native library dir"); 11440 return false; 11441 } 11442 } 11443 11444 return true; 11445 } 11446 11447 /** 11448 * Remove entries from the keystore daemon. Will only remove it if the 11449 * {@code appId} is valid. 11450 */ 11451 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11452 if (appId < 0) { 11453 return; 11454 } 11455 11456 final KeyStore keyStore = KeyStore.getInstance(); 11457 if (keyStore != null) { 11458 if (userId == UserHandle.USER_ALL) { 11459 for (final int individual : sUserManager.getUserIds()) { 11460 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11461 } 11462 } else { 11463 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11464 } 11465 } else { 11466 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11467 } 11468 } 11469 11470 @Override 11471 public void deleteApplicationCacheFiles(final String packageName, 11472 final IPackageDataObserver observer) { 11473 mContext.enforceCallingOrSelfPermission( 11474 android.Manifest.permission.DELETE_CACHE_FILES, null); 11475 // Queue up an async operation since the package deletion may take a little while. 11476 final int userId = UserHandle.getCallingUserId(); 11477 mHandler.post(new Runnable() { 11478 public void run() { 11479 mHandler.removeCallbacks(this); 11480 final boolean succeded; 11481 synchronized (mInstallLock) { 11482 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11483 } 11484 clearExternalStorageDataSync(packageName, userId, false); 11485 if(observer != null) { 11486 try { 11487 observer.onRemoveCompleted(packageName, succeded); 11488 } catch (RemoteException e) { 11489 Log.i(TAG, "Observer no longer exists."); 11490 } 11491 } //end if observer 11492 } //end run 11493 }); 11494 } 11495 11496 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11497 if (packageName == null) { 11498 Slog.w(TAG, "Attempt to delete null packageName."); 11499 return false; 11500 } 11501 PackageParser.Package p; 11502 synchronized (mPackages) { 11503 p = mPackages.get(packageName); 11504 } 11505 if (p == null) { 11506 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11507 return false; 11508 } 11509 final ApplicationInfo applicationInfo = p.applicationInfo; 11510 if (applicationInfo == null) { 11511 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11512 return false; 11513 } 11514 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11515 if (retCode < 0) { 11516 Slog.w(TAG, "Couldn't remove cache files for package: " 11517 + packageName + " u" + userId); 11518 return false; 11519 } 11520 return true; 11521 } 11522 11523 @Override 11524 public void getPackageSizeInfo(final String packageName, int userHandle, 11525 final IPackageStatsObserver observer) { 11526 mContext.enforceCallingOrSelfPermission( 11527 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11528 if (packageName == null) { 11529 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11530 } 11531 11532 PackageStats stats = new PackageStats(packageName, userHandle); 11533 11534 /* 11535 * Queue up an async operation since the package measurement may take a 11536 * little while. 11537 */ 11538 Message msg = mHandler.obtainMessage(INIT_COPY); 11539 msg.obj = new MeasureParams(stats, observer); 11540 mHandler.sendMessage(msg); 11541 } 11542 11543 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11544 PackageStats pStats) { 11545 if (packageName == null) { 11546 Slog.w(TAG, "Attempt to get size of null packageName."); 11547 return false; 11548 } 11549 PackageParser.Package p; 11550 boolean dataOnly = false; 11551 String libDirRoot = null; 11552 String asecPath = null; 11553 PackageSetting ps = null; 11554 synchronized (mPackages) { 11555 p = mPackages.get(packageName); 11556 ps = mSettings.mPackages.get(packageName); 11557 if(p == null) { 11558 dataOnly = true; 11559 if((ps == null) || (ps.pkg == null)) { 11560 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11561 return false; 11562 } 11563 p = ps.pkg; 11564 } 11565 if (ps != null) { 11566 libDirRoot = ps.legacyNativeLibraryPathString; 11567 } 11568 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11569 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11570 if (secureContainerId != null) { 11571 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11572 } 11573 } 11574 } 11575 String publicSrcDir = null; 11576 if(!dataOnly) { 11577 final ApplicationInfo applicationInfo = p.applicationInfo; 11578 if (applicationInfo == null) { 11579 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11580 return false; 11581 } 11582 if (p.isForwardLocked()) { 11583 publicSrcDir = applicationInfo.getBaseResourcePath(); 11584 } 11585 } 11586 // TODO: extend to measure size of split APKs 11587 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11588 // not just the first level. 11589 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11590 // just the primary. 11591 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11592 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11593 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11594 if (res < 0) { 11595 return false; 11596 } 11597 11598 // Fix-up for forward-locked applications in ASEC containers. 11599 if (!isExternal(p)) { 11600 pStats.codeSize += pStats.externalCodeSize; 11601 pStats.externalCodeSize = 0L; 11602 } 11603 11604 return true; 11605 } 11606 11607 11608 @Override 11609 public void addPackageToPreferred(String packageName) { 11610 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11611 } 11612 11613 @Override 11614 public void removePackageFromPreferred(String packageName) { 11615 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11616 } 11617 11618 @Override 11619 public List<PackageInfo> getPreferredPackages(int flags) { 11620 return new ArrayList<PackageInfo>(); 11621 } 11622 11623 private int getUidTargetSdkVersionLockedLPr(int uid) { 11624 Object obj = mSettings.getUserIdLPr(uid); 11625 if (obj instanceof SharedUserSetting) { 11626 final SharedUserSetting sus = (SharedUserSetting) obj; 11627 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11628 final Iterator<PackageSetting> it = sus.packages.iterator(); 11629 while (it.hasNext()) { 11630 final PackageSetting ps = it.next(); 11631 if (ps.pkg != null) { 11632 int v = ps.pkg.applicationInfo.targetSdkVersion; 11633 if (v < vers) vers = v; 11634 } 11635 } 11636 return vers; 11637 } else if (obj instanceof PackageSetting) { 11638 final PackageSetting ps = (PackageSetting) obj; 11639 if (ps.pkg != null) { 11640 return ps.pkg.applicationInfo.targetSdkVersion; 11641 } 11642 } 11643 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11644 } 11645 11646 @Override 11647 public void addPreferredActivity(IntentFilter filter, int match, 11648 ComponentName[] set, ComponentName activity, int userId) { 11649 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11650 "Adding preferred"); 11651 } 11652 11653 private void addPreferredActivityInternal(IntentFilter filter, int match, 11654 ComponentName[] set, ComponentName activity, boolean always, int userId, 11655 String opname) { 11656 // writer 11657 int callingUid = Binder.getCallingUid(); 11658 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11659 if (filter.countActions() == 0) { 11660 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11661 return; 11662 } 11663 synchronized (mPackages) { 11664 if (mContext.checkCallingOrSelfPermission( 11665 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11666 != PackageManager.PERMISSION_GRANTED) { 11667 if (getUidTargetSdkVersionLockedLPr(callingUid) 11668 < Build.VERSION_CODES.FROYO) { 11669 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11670 + callingUid); 11671 return; 11672 } 11673 mContext.enforceCallingOrSelfPermission( 11674 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11675 } 11676 11677 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11678 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11679 + userId + ":"); 11680 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11681 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11682 scheduleWritePackageRestrictionsLocked(userId); 11683 } 11684 } 11685 11686 @Override 11687 public void replacePreferredActivity(IntentFilter filter, int match, 11688 ComponentName[] set, ComponentName activity, int userId) { 11689 if (filter.countActions() != 1) { 11690 throw new IllegalArgumentException( 11691 "replacePreferredActivity expects filter to have only 1 action."); 11692 } 11693 if (filter.countDataAuthorities() != 0 11694 || filter.countDataPaths() != 0 11695 || filter.countDataSchemes() > 1 11696 || filter.countDataTypes() != 0) { 11697 throw new IllegalArgumentException( 11698 "replacePreferredActivity expects filter to have no data authorities, " + 11699 "paths, or types; and at most one scheme."); 11700 } 11701 11702 final int callingUid = Binder.getCallingUid(); 11703 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11704 synchronized (mPackages) { 11705 if (mContext.checkCallingOrSelfPermission( 11706 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11707 != PackageManager.PERMISSION_GRANTED) { 11708 if (getUidTargetSdkVersionLockedLPr(callingUid) 11709 < Build.VERSION_CODES.FROYO) { 11710 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11711 + Binder.getCallingUid()); 11712 return; 11713 } 11714 mContext.enforceCallingOrSelfPermission( 11715 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11716 } 11717 11718 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11719 if (pir != null) { 11720 // Get all of the existing entries that exactly match this filter. 11721 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11722 if (existing != null && existing.size() == 1) { 11723 PreferredActivity cur = existing.get(0); 11724 if (DEBUG_PREFERRED) { 11725 Slog.i(TAG, "Checking replace of preferred:"); 11726 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11727 if (!cur.mPref.mAlways) { 11728 Slog.i(TAG, " -- CUR; not mAlways!"); 11729 } else { 11730 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11731 Slog.i(TAG, " -- CUR: mSet=" 11732 + Arrays.toString(cur.mPref.mSetComponents)); 11733 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11734 Slog.i(TAG, " -- NEW: mMatch=" 11735 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11736 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11737 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11738 } 11739 } 11740 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11741 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11742 && cur.mPref.sameSet(set)) { 11743 // Setting the preferred activity to what it happens to be already 11744 if (DEBUG_PREFERRED) { 11745 Slog.i(TAG, "Replacing with same preferred activity " 11746 + cur.mPref.mShortComponent + " for user " 11747 + userId + ":"); 11748 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11749 } 11750 return; 11751 } 11752 } 11753 11754 if (existing != null) { 11755 if (DEBUG_PREFERRED) { 11756 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11757 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11758 } 11759 for (int i = 0; i < existing.size(); i++) { 11760 PreferredActivity pa = existing.get(i); 11761 if (DEBUG_PREFERRED) { 11762 Slog.i(TAG, "Removing existing preferred activity " 11763 + pa.mPref.mComponent + ":"); 11764 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11765 } 11766 pir.removeFilter(pa); 11767 } 11768 } 11769 } 11770 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11771 "Replacing preferred"); 11772 } 11773 } 11774 11775 @Override 11776 public void clearPackagePreferredActivities(String packageName) { 11777 final int uid = Binder.getCallingUid(); 11778 // writer 11779 synchronized (mPackages) { 11780 PackageParser.Package pkg = mPackages.get(packageName); 11781 if (pkg == null || pkg.applicationInfo.uid != uid) { 11782 if (mContext.checkCallingOrSelfPermission( 11783 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11784 != PackageManager.PERMISSION_GRANTED) { 11785 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11786 < Build.VERSION_CODES.FROYO) { 11787 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11788 + Binder.getCallingUid()); 11789 return; 11790 } 11791 mContext.enforceCallingOrSelfPermission( 11792 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11793 } 11794 } 11795 11796 int user = UserHandle.getCallingUserId(); 11797 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11798 scheduleWritePackageRestrictionsLocked(user); 11799 } 11800 } 11801 } 11802 11803 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11804 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11805 ArrayList<PreferredActivity> removed = null; 11806 boolean changed = false; 11807 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11808 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11809 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11810 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11811 continue; 11812 } 11813 Iterator<PreferredActivity> it = pir.filterIterator(); 11814 while (it.hasNext()) { 11815 PreferredActivity pa = it.next(); 11816 // Mark entry for removal only if it matches the package name 11817 // and the entry is of type "always". 11818 if (packageName == null || 11819 (pa.mPref.mComponent.getPackageName().equals(packageName) 11820 && pa.mPref.mAlways)) { 11821 if (removed == null) { 11822 removed = new ArrayList<PreferredActivity>(); 11823 } 11824 removed.add(pa); 11825 } 11826 } 11827 if (removed != null) { 11828 for (int j=0; j<removed.size(); j++) { 11829 PreferredActivity pa = removed.get(j); 11830 pir.removeFilter(pa); 11831 } 11832 changed = true; 11833 } 11834 } 11835 return changed; 11836 } 11837 11838 @Override 11839 public void resetPreferredActivities(int userId) { 11840 /* TODO: Actually use userId. Why is it being passed in? */ 11841 mContext.enforceCallingOrSelfPermission( 11842 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11843 // writer 11844 synchronized (mPackages) { 11845 int user = UserHandle.getCallingUserId(); 11846 clearPackagePreferredActivitiesLPw(null, user); 11847 mSettings.readDefaultPreferredAppsLPw(this, user); 11848 scheduleWritePackageRestrictionsLocked(user); 11849 } 11850 } 11851 11852 @Override 11853 public int getPreferredActivities(List<IntentFilter> outFilters, 11854 List<ComponentName> outActivities, String packageName) { 11855 11856 int num = 0; 11857 final int userId = UserHandle.getCallingUserId(); 11858 // reader 11859 synchronized (mPackages) { 11860 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11861 if (pir != null) { 11862 final Iterator<PreferredActivity> it = pir.filterIterator(); 11863 while (it.hasNext()) { 11864 final PreferredActivity pa = it.next(); 11865 if (packageName == null 11866 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11867 && pa.mPref.mAlways)) { 11868 if (outFilters != null) { 11869 outFilters.add(new IntentFilter(pa)); 11870 } 11871 if (outActivities != null) { 11872 outActivities.add(pa.mPref.mComponent); 11873 } 11874 } 11875 } 11876 } 11877 } 11878 11879 return num; 11880 } 11881 11882 @Override 11883 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11884 int userId) { 11885 int callingUid = Binder.getCallingUid(); 11886 if (callingUid != Process.SYSTEM_UID) { 11887 throw new SecurityException( 11888 "addPersistentPreferredActivity can only be run by the system"); 11889 } 11890 if (filter.countActions() == 0) { 11891 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11892 return; 11893 } 11894 synchronized (mPackages) { 11895 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11896 " :"); 11897 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11898 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11899 new PersistentPreferredActivity(filter, activity)); 11900 scheduleWritePackageRestrictionsLocked(userId); 11901 } 11902 } 11903 11904 @Override 11905 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11906 int callingUid = Binder.getCallingUid(); 11907 if (callingUid != Process.SYSTEM_UID) { 11908 throw new SecurityException( 11909 "clearPackagePersistentPreferredActivities can only be run by the system"); 11910 } 11911 ArrayList<PersistentPreferredActivity> removed = null; 11912 boolean changed = false; 11913 synchronized (mPackages) { 11914 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11915 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11916 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11917 .valueAt(i); 11918 if (userId != thisUserId) { 11919 continue; 11920 } 11921 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11922 while (it.hasNext()) { 11923 PersistentPreferredActivity ppa = it.next(); 11924 // Mark entry for removal only if it matches the package name. 11925 if (ppa.mComponent.getPackageName().equals(packageName)) { 11926 if (removed == null) { 11927 removed = new ArrayList<PersistentPreferredActivity>(); 11928 } 11929 removed.add(ppa); 11930 } 11931 } 11932 if (removed != null) { 11933 for (int j=0; j<removed.size(); j++) { 11934 PersistentPreferredActivity ppa = removed.get(j); 11935 ppir.removeFilter(ppa); 11936 } 11937 changed = true; 11938 } 11939 } 11940 11941 if (changed) { 11942 scheduleWritePackageRestrictionsLocked(userId); 11943 } 11944 } 11945 } 11946 11947 @Override 11948 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11949 int sourceUserId, int targetUserId, int flags) { 11950 mContext.enforceCallingOrSelfPermission( 11951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11952 int callingUid = Binder.getCallingUid(); 11953 enforceOwnerRights(ownerPackage, callingUid); 11954 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11955 if (intentFilter.countActions() == 0) { 11956 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11957 return; 11958 } 11959 synchronized (mPackages) { 11960 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11961 ownerPackage, targetUserId, flags); 11962 CrossProfileIntentResolver resolver = 11963 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11964 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11965 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11966 if (existing != null) { 11967 int size = existing.size(); 11968 for (int i = 0; i < size; i++) { 11969 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11970 return; 11971 } 11972 } 11973 } 11974 resolver.addFilter(newFilter); 11975 scheduleWritePackageRestrictionsLocked(sourceUserId); 11976 } 11977 } 11978 11979 @Override 11980 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 11981 mContext.enforceCallingOrSelfPermission( 11982 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11983 int callingUid = Binder.getCallingUid(); 11984 enforceOwnerRights(ownerPackage, callingUid); 11985 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11986 synchronized (mPackages) { 11987 CrossProfileIntentResolver resolver = 11988 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11989 ArraySet<CrossProfileIntentFilter> set = 11990 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11991 for (CrossProfileIntentFilter filter : set) { 11992 if (filter.getOwnerPackage().equals(ownerPackage)) { 11993 resolver.removeFilter(filter); 11994 } 11995 } 11996 scheduleWritePackageRestrictionsLocked(sourceUserId); 11997 } 11998 } 11999 12000 // Enforcing that callingUid is owning pkg on userId 12001 private void enforceOwnerRights(String pkg, int callingUid) { 12002 // The system owns everything. 12003 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12004 return; 12005 } 12006 int callingUserId = UserHandle.getUserId(callingUid); 12007 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12008 if (pi == null) { 12009 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12010 + callingUserId); 12011 } 12012 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12013 throw new SecurityException("Calling uid " + callingUid 12014 + " does not own package " + pkg); 12015 } 12016 } 12017 12018 @Override 12019 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12020 Intent intent = new Intent(Intent.ACTION_MAIN); 12021 intent.addCategory(Intent.CATEGORY_HOME); 12022 12023 final int callingUserId = UserHandle.getCallingUserId(); 12024 List<ResolveInfo> list = queryIntentActivities(intent, null, 12025 PackageManager.GET_META_DATA, callingUserId); 12026 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12027 true, false, false, callingUserId); 12028 12029 allHomeCandidates.clear(); 12030 if (list != null) { 12031 for (ResolveInfo ri : list) { 12032 allHomeCandidates.add(ri); 12033 } 12034 } 12035 return (preferred == null || preferred.activityInfo == null) 12036 ? null 12037 : new ComponentName(preferred.activityInfo.packageName, 12038 preferred.activityInfo.name); 12039 } 12040 12041 @Override 12042 public void setApplicationEnabledSetting(String appPackageName, 12043 int newState, int flags, int userId, String callingPackage) { 12044 if (!sUserManager.exists(userId)) return; 12045 if (callingPackage == null) { 12046 callingPackage = Integer.toString(Binder.getCallingUid()); 12047 } 12048 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12049 } 12050 12051 @Override 12052 public void setComponentEnabledSetting(ComponentName componentName, 12053 int newState, int flags, int userId) { 12054 if (!sUserManager.exists(userId)) return; 12055 setEnabledSetting(componentName.getPackageName(), 12056 componentName.getClassName(), newState, flags, userId, null); 12057 } 12058 12059 private void setEnabledSetting(final String packageName, String className, int newState, 12060 final int flags, int userId, String callingPackage) { 12061 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12062 || newState == COMPONENT_ENABLED_STATE_ENABLED 12063 || newState == COMPONENT_ENABLED_STATE_DISABLED 12064 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12065 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12066 throw new IllegalArgumentException("Invalid new component state: " 12067 + newState); 12068 } 12069 PackageSetting pkgSetting; 12070 final int uid = Binder.getCallingUid(); 12071 final int permission = mContext.checkCallingOrSelfPermission( 12072 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12073 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12074 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12075 boolean sendNow = false; 12076 boolean isApp = (className == null); 12077 String componentName = isApp ? packageName : className; 12078 int packageUid = -1; 12079 ArrayList<String> components; 12080 12081 // writer 12082 synchronized (mPackages) { 12083 pkgSetting = mSettings.mPackages.get(packageName); 12084 if (pkgSetting == null) { 12085 if (className == null) { 12086 throw new IllegalArgumentException( 12087 "Unknown package: " + packageName); 12088 } 12089 throw new IllegalArgumentException( 12090 "Unknown component: " + packageName 12091 + "/" + className); 12092 } 12093 // Allow root and verify that userId is not being specified by a different user 12094 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12095 throw new SecurityException( 12096 "Permission Denial: attempt to change component state from pid=" 12097 + Binder.getCallingPid() 12098 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12099 } 12100 if (className == null) { 12101 // We're dealing with an application/package level state change 12102 if (pkgSetting.getEnabled(userId) == newState) { 12103 // Nothing to do 12104 return; 12105 } 12106 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12107 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12108 // Don't care about who enables an app. 12109 callingPackage = null; 12110 } 12111 pkgSetting.setEnabled(newState, userId, callingPackage); 12112 // pkgSetting.pkg.mSetEnabled = newState; 12113 } else { 12114 // We're dealing with a component level state change 12115 // First, verify that this is a valid class name. 12116 PackageParser.Package pkg = pkgSetting.pkg; 12117 if (pkg == null || !pkg.hasComponentClassName(className)) { 12118 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12119 throw new IllegalArgumentException("Component class " + className 12120 + " does not exist in " + packageName); 12121 } else { 12122 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12123 + className + " does not exist in " + packageName); 12124 } 12125 } 12126 switch (newState) { 12127 case COMPONENT_ENABLED_STATE_ENABLED: 12128 if (!pkgSetting.enableComponentLPw(className, userId)) { 12129 return; 12130 } 12131 break; 12132 case COMPONENT_ENABLED_STATE_DISABLED: 12133 if (!pkgSetting.disableComponentLPw(className, userId)) { 12134 return; 12135 } 12136 break; 12137 case COMPONENT_ENABLED_STATE_DEFAULT: 12138 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12139 return; 12140 } 12141 break; 12142 default: 12143 Slog.e(TAG, "Invalid new component state: " + newState); 12144 return; 12145 } 12146 } 12147 scheduleWritePackageRestrictionsLocked(userId); 12148 components = mPendingBroadcasts.get(userId, packageName); 12149 final boolean newPackage = components == null; 12150 if (newPackage) { 12151 components = new ArrayList<String>(); 12152 } 12153 if (!components.contains(componentName)) { 12154 components.add(componentName); 12155 } 12156 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12157 sendNow = true; 12158 // Purge entry from pending broadcast list if another one exists already 12159 // since we are sending one right away. 12160 mPendingBroadcasts.remove(userId, packageName); 12161 } else { 12162 if (newPackage) { 12163 mPendingBroadcasts.put(userId, packageName, components); 12164 } 12165 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12166 // Schedule a message 12167 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12168 } 12169 } 12170 } 12171 12172 long callingId = Binder.clearCallingIdentity(); 12173 try { 12174 if (sendNow) { 12175 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12176 sendPackageChangedBroadcast(packageName, 12177 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12178 } 12179 } finally { 12180 Binder.restoreCallingIdentity(callingId); 12181 } 12182 } 12183 12184 private void sendPackageChangedBroadcast(String packageName, 12185 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12186 if (DEBUG_INSTALL) 12187 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12188 + componentNames); 12189 Bundle extras = new Bundle(4); 12190 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12191 String nameList[] = new String[componentNames.size()]; 12192 componentNames.toArray(nameList); 12193 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12194 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12195 extras.putInt(Intent.EXTRA_UID, packageUid); 12196 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12197 new int[] {UserHandle.getUserId(packageUid)}); 12198 } 12199 12200 @Override 12201 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12202 if (!sUserManager.exists(userId)) return; 12203 final int uid = Binder.getCallingUid(); 12204 final int permission = mContext.checkCallingOrSelfPermission( 12205 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12206 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12207 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12208 // writer 12209 synchronized (mPackages) { 12210 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12211 uid, userId)) { 12212 scheduleWritePackageRestrictionsLocked(userId); 12213 } 12214 } 12215 } 12216 12217 @Override 12218 public String getInstallerPackageName(String packageName) { 12219 // reader 12220 synchronized (mPackages) { 12221 return mSettings.getInstallerPackageNameLPr(packageName); 12222 } 12223 } 12224 12225 @Override 12226 public int getApplicationEnabledSetting(String packageName, int userId) { 12227 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12228 int uid = Binder.getCallingUid(); 12229 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12230 // reader 12231 synchronized (mPackages) { 12232 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12233 } 12234 } 12235 12236 @Override 12237 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12238 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12239 int uid = Binder.getCallingUid(); 12240 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12241 // reader 12242 synchronized (mPackages) { 12243 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12244 } 12245 } 12246 12247 @Override 12248 public void enterSafeMode() { 12249 enforceSystemOrRoot("Only the system can request entering safe mode"); 12250 12251 if (!mSystemReady) { 12252 mSafeMode = true; 12253 } 12254 } 12255 12256 @Override 12257 public void systemReady() { 12258 mSystemReady = true; 12259 12260 // Read the compatibilty setting when the system is ready. 12261 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12262 mContext.getContentResolver(), 12263 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12264 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12265 if (DEBUG_SETTINGS) { 12266 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12267 } 12268 12269 synchronized (mPackages) { 12270 // Verify that all of the preferred activity components actually 12271 // exist. It is possible for applications to be updated and at 12272 // that point remove a previously declared activity component that 12273 // had been set as a preferred activity. We try to clean this up 12274 // the next time we encounter that preferred activity, but it is 12275 // possible for the user flow to never be able to return to that 12276 // situation so here we do a sanity check to make sure we haven't 12277 // left any junk around. 12278 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12279 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12280 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12281 removed.clear(); 12282 for (PreferredActivity pa : pir.filterSet()) { 12283 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12284 removed.add(pa); 12285 } 12286 } 12287 if (removed.size() > 0) { 12288 for (int r=0; r<removed.size(); r++) { 12289 PreferredActivity pa = removed.get(r); 12290 Slog.w(TAG, "Removing dangling preferred activity: " 12291 + pa.mPref.mComponent); 12292 pir.removeFilter(pa); 12293 } 12294 mSettings.writePackageRestrictionsLPr( 12295 mSettings.mPreferredActivities.keyAt(i)); 12296 } 12297 } 12298 } 12299 sUserManager.systemReady(); 12300 12301 // Kick off any messages waiting for system ready 12302 if (mPostSystemReadyMessages != null) { 12303 for (Message msg : mPostSystemReadyMessages) { 12304 msg.sendToTarget(); 12305 } 12306 mPostSystemReadyMessages = null; 12307 } 12308 } 12309 12310 @Override 12311 public boolean isSafeMode() { 12312 return mSafeMode; 12313 } 12314 12315 @Override 12316 public boolean hasSystemUidErrors() { 12317 return mHasSystemUidErrors; 12318 } 12319 12320 static String arrayToString(int[] array) { 12321 StringBuffer buf = new StringBuffer(128); 12322 buf.append('['); 12323 if (array != null) { 12324 for (int i=0; i<array.length; i++) { 12325 if (i > 0) buf.append(", "); 12326 buf.append(array[i]); 12327 } 12328 } 12329 buf.append(']'); 12330 return buf.toString(); 12331 } 12332 12333 static class DumpState { 12334 public static final int DUMP_LIBS = 1 << 0; 12335 public static final int DUMP_FEATURES = 1 << 1; 12336 public static final int DUMP_RESOLVERS = 1 << 2; 12337 public static final int DUMP_PERMISSIONS = 1 << 3; 12338 public static final int DUMP_PACKAGES = 1 << 4; 12339 public static final int DUMP_SHARED_USERS = 1 << 5; 12340 public static final int DUMP_MESSAGES = 1 << 6; 12341 public static final int DUMP_PROVIDERS = 1 << 7; 12342 public static final int DUMP_VERIFIERS = 1 << 8; 12343 public static final int DUMP_PREFERRED = 1 << 9; 12344 public static final int DUMP_PREFERRED_XML = 1 << 10; 12345 public static final int DUMP_KEYSETS = 1 << 11; 12346 public static final int DUMP_VERSION = 1 << 12; 12347 public static final int DUMP_INSTALLS = 1 << 13; 12348 12349 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12350 12351 private int mTypes; 12352 12353 private int mOptions; 12354 12355 private boolean mTitlePrinted; 12356 12357 private SharedUserSetting mSharedUser; 12358 12359 public boolean isDumping(int type) { 12360 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12361 return true; 12362 } 12363 12364 return (mTypes & type) != 0; 12365 } 12366 12367 public void setDump(int type) { 12368 mTypes |= type; 12369 } 12370 12371 public boolean isOptionEnabled(int option) { 12372 return (mOptions & option) != 0; 12373 } 12374 12375 public void setOptionEnabled(int option) { 12376 mOptions |= option; 12377 } 12378 12379 public boolean onTitlePrinted() { 12380 final boolean printed = mTitlePrinted; 12381 mTitlePrinted = true; 12382 return printed; 12383 } 12384 12385 public boolean getTitlePrinted() { 12386 return mTitlePrinted; 12387 } 12388 12389 public void setTitlePrinted(boolean enabled) { 12390 mTitlePrinted = enabled; 12391 } 12392 12393 public SharedUserSetting getSharedUser() { 12394 return mSharedUser; 12395 } 12396 12397 public void setSharedUser(SharedUserSetting user) { 12398 mSharedUser = user; 12399 } 12400 } 12401 12402 @Override 12403 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12404 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12405 != PackageManager.PERMISSION_GRANTED) { 12406 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12407 + Binder.getCallingPid() 12408 + ", uid=" + Binder.getCallingUid() 12409 + " without permission " 12410 + android.Manifest.permission.DUMP); 12411 return; 12412 } 12413 12414 DumpState dumpState = new DumpState(); 12415 boolean fullPreferred = false; 12416 boolean checkin = false; 12417 12418 String packageName = null; 12419 12420 int opti = 0; 12421 while (opti < args.length) { 12422 String opt = args[opti]; 12423 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12424 break; 12425 } 12426 opti++; 12427 12428 if ("-a".equals(opt)) { 12429 // Right now we only know how to print all. 12430 } else if ("-h".equals(opt)) { 12431 pw.println("Package manager dump options:"); 12432 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12433 pw.println(" --checkin: dump for a checkin"); 12434 pw.println(" -f: print details of intent filters"); 12435 pw.println(" -h: print this help"); 12436 pw.println(" cmd may be one of:"); 12437 pw.println(" l[ibraries]: list known shared libraries"); 12438 pw.println(" f[ibraries]: list device features"); 12439 pw.println(" k[eysets]: print known keysets"); 12440 pw.println(" r[esolvers]: dump intent resolvers"); 12441 pw.println(" perm[issions]: dump permissions"); 12442 pw.println(" pref[erred]: print preferred package settings"); 12443 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12444 pw.println(" prov[iders]: dump content providers"); 12445 pw.println(" p[ackages]: dump installed packages"); 12446 pw.println(" s[hared-users]: dump shared user IDs"); 12447 pw.println(" m[essages]: print collected runtime messages"); 12448 pw.println(" v[erifiers]: print package verifier info"); 12449 pw.println(" version: print database version info"); 12450 pw.println(" write: write current settings now"); 12451 pw.println(" <package.name>: info about given package"); 12452 pw.println(" installs: details about install sessions"); 12453 return; 12454 } else if ("--checkin".equals(opt)) { 12455 checkin = true; 12456 } else if ("-f".equals(opt)) { 12457 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12458 } else { 12459 pw.println("Unknown argument: " + opt + "; use -h for help"); 12460 } 12461 } 12462 12463 // Is the caller requesting to dump a particular piece of data? 12464 if (opti < args.length) { 12465 String cmd = args[opti]; 12466 opti++; 12467 // Is this a package name? 12468 if ("android".equals(cmd) || cmd.contains(".")) { 12469 packageName = cmd; 12470 // When dumping a single package, we always dump all of its 12471 // filter information since the amount of data will be reasonable. 12472 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12473 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12474 dumpState.setDump(DumpState.DUMP_LIBS); 12475 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12476 dumpState.setDump(DumpState.DUMP_FEATURES); 12477 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12478 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12479 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12480 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12481 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12482 dumpState.setDump(DumpState.DUMP_PREFERRED); 12483 } else if ("preferred-xml".equals(cmd)) { 12484 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12485 if (opti < args.length && "--full".equals(args[opti])) { 12486 fullPreferred = true; 12487 opti++; 12488 } 12489 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12490 dumpState.setDump(DumpState.DUMP_PACKAGES); 12491 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12492 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12493 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12494 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12495 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12496 dumpState.setDump(DumpState.DUMP_MESSAGES); 12497 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12498 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12499 } else if ("version".equals(cmd)) { 12500 dumpState.setDump(DumpState.DUMP_VERSION); 12501 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12502 dumpState.setDump(DumpState.DUMP_KEYSETS); 12503 } else if ("installs".equals(cmd)) { 12504 dumpState.setDump(DumpState.DUMP_INSTALLS); 12505 } else if ("write".equals(cmd)) { 12506 synchronized (mPackages) { 12507 mSettings.writeLPr(); 12508 pw.println("Settings written."); 12509 return; 12510 } 12511 } 12512 } 12513 12514 if (checkin) { 12515 pw.println("vers,1"); 12516 } 12517 12518 // reader 12519 synchronized (mPackages) { 12520 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12521 if (!checkin) { 12522 if (dumpState.onTitlePrinted()) 12523 pw.println(); 12524 pw.println("Database versions:"); 12525 pw.print(" SDK Version:"); 12526 pw.print(" internal="); 12527 pw.print(mSettings.mInternalSdkPlatform); 12528 pw.print(" external="); 12529 pw.println(mSettings.mExternalSdkPlatform); 12530 pw.print(" DB Version:"); 12531 pw.print(" internal="); 12532 pw.print(mSettings.mInternalDatabaseVersion); 12533 pw.print(" external="); 12534 pw.println(mSettings.mExternalDatabaseVersion); 12535 } 12536 } 12537 12538 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12539 if (!checkin) { 12540 if (dumpState.onTitlePrinted()) 12541 pw.println(); 12542 pw.println("Verifiers:"); 12543 pw.print(" Required: "); 12544 pw.print(mRequiredVerifierPackage); 12545 pw.print(" (uid="); 12546 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12547 pw.println(")"); 12548 } else if (mRequiredVerifierPackage != null) { 12549 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12550 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12551 } 12552 } 12553 12554 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12555 boolean printedHeader = false; 12556 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12557 while (it.hasNext()) { 12558 String name = it.next(); 12559 SharedLibraryEntry ent = mSharedLibraries.get(name); 12560 if (!checkin) { 12561 if (!printedHeader) { 12562 if (dumpState.onTitlePrinted()) 12563 pw.println(); 12564 pw.println("Libraries:"); 12565 printedHeader = true; 12566 } 12567 pw.print(" "); 12568 } else { 12569 pw.print("lib,"); 12570 } 12571 pw.print(name); 12572 if (!checkin) { 12573 pw.print(" -> "); 12574 } 12575 if (ent.path != null) { 12576 if (!checkin) { 12577 pw.print("(jar) "); 12578 pw.print(ent.path); 12579 } else { 12580 pw.print(",jar,"); 12581 pw.print(ent.path); 12582 } 12583 } else { 12584 if (!checkin) { 12585 pw.print("(apk) "); 12586 pw.print(ent.apk); 12587 } else { 12588 pw.print(",apk,"); 12589 pw.print(ent.apk); 12590 } 12591 } 12592 pw.println(); 12593 } 12594 } 12595 12596 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12597 if (dumpState.onTitlePrinted()) 12598 pw.println(); 12599 if (!checkin) { 12600 pw.println("Features:"); 12601 } 12602 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12603 while (it.hasNext()) { 12604 String name = it.next(); 12605 if (!checkin) { 12606 pw.print(" "); 12607 } else { 12608 pw.print("feat,"); 12609 } 12610 pw.println(name); 12611 } 12612 } 12613 12614 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12615 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12616 : "Activity Resolver Table:", " ", packageName, 12617 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12618 dumpState.setTitlePrinted(true); 12619 } 12620 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12621 : "Receiver Resolver Table:", " ", packageName, 12622 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12623 dumpState.setTitlePrinted(true); 12624 } 12625 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12626 : "Service Resolver Table:", " ", packageName, 12627 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12628 dumpState.setTitlePrinted(true); 12629 } 12630 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12631 : "Provider Resolver Table:", " ", packageName, 12632 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12633 dumpState.setTitlePrinted(true); 12634 } 12635 } 12636 12637 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12638 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12639 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12640 int user = mSettings.mPreferredActivities.keyAt(i); 12641 if (pir.dump(pw, 12642 dumpState.getTitlePrinted() 12643 ? "\nPreferred Activities User " + user + ":" 12644 : "Preferred Activities User " + user + ":", " ", 12645 packageName, true, false)) { 12646 dumpState.setTitlePrinted(true); 12647 } 12648 } 12649 } 12650 12651 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12652 pw.flush(); 12653 FileOutputStream fout = new FileOutputStream(fd); 12654 BufferedOutputStream str = new BufferedOutputStream(fout); 12655 XmlSerializer serializer = new FastXmlSerializer(); 12656 try { 12657 serializer.setOutput(str, "utf-8"); 12658 serializer.startDocument(null, true); 12659 serializer.setFeature( 12660 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12661 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12662 serializer.endDocument(); 12663 serializer.flush(); 12664 } catch (IllegalArgumentException e) { 12665 pw.println("Failed writing: " + e); 12666 } catch (IllegalStateException e) { 12667 pw.println("Failed writing: " + e); 12668 } catch (IOException e) { 12669 pw.println("Failed writing: " + e); 12670 } 12671 } 12672 12673 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12674 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12675 if (packageName == null) { 12676 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12677 if (iperm == 0) { 12678 if (dumpState.onTitlePrinted()) 12679 pw.println(); 12680 pw.println("AppOp Permissions:"); 12681 } 12682 pw.print(" AppOp Permission "); 12683 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12684 pw.println(":"); 12685 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12686 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12687 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12688 } 12689 } 12690 } 12691 } 12692 12693 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12694 boolean printedSomething = false; 12695 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12696 if (packageName != null && !packageName.equals(p.info.packageName)) { 12697 continue; 12698 } 12699 if (!printedSomething) { 12700 if (dumpState.onTitlePrinted()) 12701 pw.println(); 12702 pw.println("Registered ContentProviders:"); 12703 printedSomething = true; 12704 } 12705 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12706 pw.print(" "); pw.println(p.toString()); 12707 } 12708 printedSomething = false; 12709 for (Map.Entry<String, PackageParser.Provider> entry : 12710 mProvidersByAuthority.entrySet()) { 12711 PackageParser.Provider p = entry.getValue(); 12712 if (packageName != null && !packageName.equals(p.info.packageName)) { 12713 continue; 12714 } 12715 if (!printedSomething) { 12716 if (dumpState.onTitlePrinted()) 12717 pw.println(); 12718 pw.println("ContentProvider Authorities:"); 12719 printedSomething = true; 12720 } 12721 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12722 pw.print(" "); pw.println(p.toString()); 12723 if (p.info != null && p.info.applicationInfo != null) { 12724 final String appInfo = p.info.applicationInfo.toString(); 12725 pw.print(" applicationInfo="); pw.println(appInfo); 12726 } 12727 } 12728 } 12729 12730 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12731 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12732 } 12733 12734 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12735 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12736 } 12737 12738 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12739 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12740 } 12741 12742 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12743 // XXX should handle packageName != null by dumping only install data that 12744 // the given package is involved with. 12745 if (dumpState.onTitlePrinted()) pw.println(); 12746 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12747 } 12748 12749 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12750 if (dumpState.onTitlePrinted()) pw.println(); 12751 mSettings.dumpReadMessagesLPr(pw, dumpState); 12752 12753 pw.println(); 12754 pw.println("Package warning messages:"); 12755 BufferedReader in = null; 12756 String line = null; 12757 try { 12758 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12759 while ((line = in.readLine()) != null) { 12760 if (line.contains("ignored: updated version")) continue; 12761 pw.println(line); 12762 } 12763 } catch (IOException ignored) { 12764 } finally { 12765 IoUtils.closeQuietly(in); 12766 } 12767 } 12768 12769 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12770 BufferedReader in = null; 12771 String line = null; 12772 try { 12773 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12774 while ((line = in.readLine()) != null) { 12775 if (line.contains("ignored: updated version")) continue; 12776 pw.print("msg,"); 12777 pw.println(line); 12778 } 12779 } catch (IOException ignored) { 12780 } finally { 12781 IoUtils.closeQuietly(in); 12782 } 12783 } 12784 } 12785 } 12786 12787 // ------- apps on sdcard specific code ------- 12788 static final boolean DEBUG_SD_INSTALL = false; 12789 12790 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12791 12792 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12793 12794 private boolean mMediaMounted = false; 12795 12796 static String getEncryptKey() { 12797 try { 12798 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12799 SD_ENCRYPTION_KEYSTORE_NAME); 12800 if (sdEncKey == null) { 12801 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12802 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12803 if (sdEncKey == null) { 12804 Slog.e(TAG, "Failed to create encryption keys"); 12805 return null; 12806 } 12807 } 12808 return sdEncKey; 12809 } catch (NoSuchAlgorithmException nsae) { 12810 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12811 return null; 12812 } catch (IOException ioe) { 12813 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12814 return null; 12815 } 12816 } 12817 12818 /* 12819 * Update media status on PackageManager. 12820 */ 12821 @Override 12822 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12823 int callingUid = Binder.getCallingUid(); 12824 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12825 throw new SecurityException("Media status can only be updated by the system"); 12826 } 12827 // reader; this apparently protects mMediaMounted, but should probably 12828 // be a different lock in that case. 12829 synchronized (mPackages) { 12830 Log.i(TAG, "Updating external media status from " 12831 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12832 + (mediaStatus ? "mounted" : "unmounted")); 12833 if (DEBUG_SD_INSTALL) 12834 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12835 + ", mMediaMounted=" + mMediaMounted); 12836 if (mediaStatus == mMediaMounted) { 12837 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12838 : 0, -1); 12839 mHandler.sendMessage(msg); 12840 return; 12841 } 12842 mMediaMounted = mediaStatus; 12843 } 12844 // Queue up an async operation since the package installation may take a 12845 // little while. 12846 mHandler.post(new Runnable() { 12847 public void run() { 12848 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12849 } 12850 }); 12851 } 12852 12853 /** 12854 * Called by MountService when the initial ASECs to scan are available. 12855 * Should block until all the ASEC containers are finished being scanned. 12856 */ 12857 public void scanAvailableAsecs() { 12858 updateExternalMediaStatusInner(true, false, false); 12859 if (mShouldRestoreconData) { 12860 SELinuxMMAC.setRestoreconDone(); 12861 mShouldRestoreconData = false; 12862 } 12863 } 12864 12865 /* 12866 * Collect information of applications on external media, map them against 12867 * existing containers and update information based on current mount status. 12868 * Please note that we always have to report status if reportStatus has been 12869 * set to true especially when unloading packages. 12870 */ 12871 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12872 boolean externalStorage) { 12873 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12874 int[] uidArr = EmptyArray.INT; 12875 12876 final String[] list = PackageHelper.getSecureContainerList(); 12877 if (ArrayUtils.isEmpty(list)) { 12878 Log.i(TAG, "No secure containers found"); 12879 } else { 12880 // Process list of secure containers and categorize them 12881 // as active or stale based on their package internal state. 12882 12883 // reader 12884 synchronized (mPackages) { 12885 for (String cid : list) { 12886 // Leave stages untouched for now; installer service owns them 12887 if (PackageInstallerService.isStageName(cid)) continue; 12888 12889 if (DEBUG_SD_INSTALL) 12890 Log.i(TAG, "Processing container " + cid); 12891 String pkgName = getAsecPackageName(cid); 12892 if (pkgName == null) { 12893 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12894 continue; 12895 } 12896 if (DEBUG_SD_INSTALL) 12897 Log.i(TAG, "Looking for pkg : " + pkgName); 12898 12899 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12900 if (ps == null) { 12901 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12902 continue; 12903 } 12904 12905 /* 12906 * Skip packages that are not external if we're unmounting 12907 * external storage. 12908 */ 12909 if (externalStorage && !isMounted && !isExternal(ps)) { 12910 continue; 12911 } 12912 12913 final AsecInstallArgs args = new AsecInstallArgs(cid, 12914 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12915 // The package status is changed only if the code path 12916 // matches between settings and the container id. 12917 if (ps.codePathString != null 12918 && ps.codePathString.startsWith(args.getCodePath())) { 12919 if (DEBUG_SD_INSTALL) { 12920 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12921 + " at code path: " + ps.codePathString); 12922 } 12923 12924 // We do have a valid package installed on sdcard 12925 processCids.put(args, ps.codePathString); 12926 final int uid = ps.appId; 12927 if (uid != -1) { 12928 uidArr = ArrayUtils.appendInt(uidArr, uid); 12929 } 12930 } else { 12931 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12932 + ps.codePathString); 12933 } 12934 } 12935 } 12936 12937 Arrays.sort(uidArr); 12938 } 12939 12940 // Process packages with valid entries. 12941 if (isMounted) { 12942 if (DEBUG_SD_INSTALL) 12943 Log.i(TAG, "Loading packages"); 12944 loadMediaPackages(processCids, uidArr); 12945 startCleaningPackages(); 12946 mInstallerService.onSecureContainersAvailable(); 12947 } else { 12948 if (DEBUG_SD_INSTALL) 12949 Log.i(TAG, "Unloading packages"); 12950 unloadMediaPackages(processCids, uidArr, reportStatus); 12951 } 12952 } 12953 12954 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12955 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12956 int size = pkgList.size(); 12957 if (size > 0) { 12958 // Send broadcasts here 12959 Bundle extras = new Bundle(); 12960 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12961 .toArray(new String[size])); 12962 if (uidArr != null) { 12963 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12964 } 12965 if (replacing) { 12966 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12967 } 12968 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12969 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12970 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12971 } 12972 } 12973 12974 /* 12975 * Look at potentially valid container ids from processCids If package 12976 * information doesn't match the one on record or package scanning fails, 12977 * the cid is added to list of removeCids. We currently don't delete stale 12978 * containers. 12979 */ 12980 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12981 ArrayList<String> pkgList = new ArrayList<String>(); 12982 Set<AsecInstallArgs> keys = processCids.keySet(); 12983 12984 for (AsecInstallArgs args : keys) { 12985 String codePath = processCids.get(args); 12986 if (DEBUG_SD_INSTALL) 12987 Log.i(TAG, "Loading container : " + args.cid); 12988 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12989 try { 12990 // Make sure there are no container errors first. 12991 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12992 Slog.e(TAG, "Failed to mount cid : " + args.cid 12993 + " when installing from sdcard"); 12994 continue; 12995 } 12996 // Check code path here. 12997 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12998 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12999 + " does not match one in settings " + codePath); 13000 continue; 13001 } 13002 // Parse package 13003 int parseFlags = mDefParseFlags; 13004 if (args.isExternal()) { 13005 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13006 } 13007 if (args.isFwdLocked()) { 13008 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13009 } 13010 13011 synchronized (mInstallLock) { 13012 PackageParser.Package pkg = null; 13013 try { 13014 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13015 } catch (PackageManagerException e) { 13016 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13017 } 13018 // Scan the package 13019 if (pkg != null) { 13020 /* 13021 * TODO why is the lock being held? doPostInstall is 13022 * called in other places without the lock. This needs 13023 * to be straightened out. 13024 */ 13025 // writer 13026 synchronized (mPackages) { 13027 retCode = PackageManager.INSTALL_SUCCEEDED; 13028 pkgList.add(pkg.packageName); 13029 // Post process args 13030 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13031 pkg.applicationInfo.uid); 13032 } 13033 } else { 13034 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13035 } 13036 } 13037 13038 } finally { 13039 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13040 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13041 } 13042 } 13043 } 13044 // writer 13045 synchronized (mPackages) { 13046 // If the platform SDK has changed since the last time we booted, 13047 // we need to re-grant app permission to catch any new ones that 13048 // appear. This is really a hack, and means that apps can in some 13049 // cases get permissions that the user didn't initially explicitly 13050 // allow... it would be nice to have some better way to handle 13051 // this situation. 13052 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13053 if (regrantPermissions) 13054 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13055 + mSdkVersion + "; regranting permissions for external storage"); 13056 mSettings.mExternalSdkPlatform = mSdkVersion; 13057 13058 // Make sure group IDs have been assigned, and any permission 13059 // changes in other apps are accounted for 13060 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13061 | (regrantPermissions 13062 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13063 : 0)); 13064 13065 mSettings.updateExternalDatabaseVersion(); 13066 13067 // can downgrade to reader 13068 // Persist settings 13069 mSettings.writeLPr(); 13070 } 13071 // Send a broadcast to let everyone know we are done processing 13072 if (pkgList.size() > 0) { 13073 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13074 } 13075 } 13076 13077 /* 13078 * Utility method to unload a list of specified containers 13079 */ 13080 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13081 // Just unmount all valid containers. 13082 for (AsecInstallArgs arg : cidArgs) { 13083 synchronized (mInstallLock) { 13084 arg.doPostDeleteLI(false); 13085 } 13086 } 13087 } 13088 13089 /* 13090 * Unload packages mounted on external media. This involves deleting package 13091 * data from internal structures, sending broadcasts about diabled packages, 13092 * gc'ing to free up references, unmounting all secure containers 13093 * corresponding to packages on external media, and posting a 13094 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13095 * that we always have to post this message if status has been requested no 13096 * matter what. 13097 */ 13098 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13099 final boolean reportStatus) { 13100 if (DEBUG_SD_INSTALL) 13101 Log.i(TAG, "unloading media packages"); 13102 ArrayList<String> pkgList = new ArrayList<String>(); 13103 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13104 final Set<AsecInstallArgs> keys = processCids.keySet(); 13105 for (AsecInstallArgs args : keys) { 13106 String pkgName = args.getPackageName(); 13107 if (DEBUG_SD_INSTALL) 13108 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13109 // Delete package internally 13110 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13111 synchronized (mInstallLock) { 13112 boolean res = deletePackageLI(pkgName, null, false, null, null, 13113 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13114 if (res) { 13115 pkgList.add(pkgName); 13116 } else { 13117 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13118 failedList.add(args); 13119 } 13120 } 13121 } 13122 13123 // reader 13124 synchronized (mPackages) { 13125 // We didn't update the settings after removing each package; 13126 // write them now for all packages. 13127 mSettings.writeLPr(); 13128 } 13129 13130 // We have to absolutely send UPDATED_MEDIA_STATUS only 13131 // after confirming that all the receivers processed the ordered 13132 // broadcast when packages get disabled, force a gc to clean things up. 13133 // and unload all the containers. 13134 if (pkgList.size() > 0) { 13135 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13136 new IIntentReceiver.Stub() { 13137 public void performReceive(Intent intent, int resultCode, String data, 13138 Bundle extras, boolean ordered, boolean sticky, 13139 int sendingUser) throws RemoteException { 13140 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13141 reportStatus ? 1 : 0, 1, keys); 13142 mHandler.sendMessage(msg); 13143 } 13144 }); 13145 } else { 13146 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13147 keys); 13148 mHandler.sendMessage(msg); 13149 } 13150 } 13151 13152 /** Binder call */ 13153 @Override 13154 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13155 final int flags) { 13156 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13157 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13158 int returnCode = PackageManager.MOVE_SUCCEEDED; 13159 int currInstallFlags = 0; 13160 int newInstallFlags = 0; 13161 13162 File codeFile = null; 13163 String installerPackageName = null; 13164 String packageAbiOverride = null; 13165 13166 // reader 13167 synchronized (mPackages) { 13168 final PackageParser.Package pkg = mPackages.get(packageName); 13169 final PackageSetting ps = mSettings.mPackages.get(packageName); 13170 if (pkg == null || ps == null) { 13171 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13172 } else { 13173 // Disable moving fwd locked apps and system packages 13174 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13175 Slog.w(TAG, "Cannot move system application"); 13176 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13177 } else if (pkg.mOperationPending) { 13178 Slog.w(TAG, "Attempt to move package which has pending operations"); 13179 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13180 } else { 13181 // Find install location first 13182 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13183 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13184 Slog.w(TAG, "Ambigous flags specified for move location."); 13185 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13186 } else { 13187 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13188 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13189 currInstallFlags = isExternal(pkg) 13190 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13191 13192 if (newInstallFlags == currInstallFlags) { 13193 Slog.w(TAG, "No move required. Trying to move to same location"); 13194 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13195 } else { 13196 if (pkg.isForwardLocked()) { 13197 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13198 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13199 } 13200 } 13201 } 13202 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13203 pkg.mOperationPending = true; 13204 } 13205 } 13206 13207 codeFile = new File(pkg.codePath); 13208 installerPackageName = ps.installerPackageName; 13209 packageAbiOverride = ps.cpuAbiOverrideString; 13210 } 13211 } 13212 13213 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13214 try { 13215 observer.packageMoved(packageName, returnCode); 13216 } catch (RemoteException ignored) { 13217 } 13218 return; 13219 } 13220 13221 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13222 @Override 13223 public void onUserActionRequired(Intent intent) throws RemoteException { 13224 throw new IllegalStateException(); 13225 } 13226 13227 @Override 13228 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13229 Bundle extras) throws RemoteException { 13230 Slog.d(TAG, "Install result for move: " 13231 + PackageManager.installStatusToString(returnCode, msg)); 13232 13233 // We usually have a new package now after the install, but if 13234 // we failed we need to clear the pending flag on the original 13235 // package object. 13236 synchronized (mPackages) { 13237 final PackageParser.Package pkg = mPackages.get(packageName); 13238 if (pkg != null) { 13239 pkg.mOperationPending = false; 13240 } 13241 } 13242 13243 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13244 switch (status) { 13245 case PackageInstaller.STATUS_SUCCESS: 13246 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13247 break; 13248 case PackageInstaller.STATUS_FAILURE_STORAGE: 13249 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13250 break; 13251 default: 13252 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13253 break; 13254 } 13255 } 13256 }; 13257 13258 // Treat a move like reinstalling an existing app, which ensures that we 13259 // process everythign uniformly, like unpacking native libraries. 13260 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13261 13262 final Message msg = mHandler.obtainMessage(INIT_COPY); 13263 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13264 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13265 installerPackageName, null, user, packageAbiOverride); 13266 mHandler.sendMessage(msg); 13267 } 13268 13269 @Override 13270 public boolean setInstallLocation(int loc) { 13271 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13272 null); 13273 if (getInstallLocation() == loc) { 13274 return true; 13275 } 13276 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13277 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13278 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13279 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13280 return true; 13281 } 13282 return false; 13283 } 13284 13285 @Override 13286 public int getInstallLocation() { 13287 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13288 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13289 PackageHelper.APP_INSTALL_AUTO); 13290 } 13291 13292 /** Called by UserManagerService */ 13293 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13294 mDirtyUsers.remove(userHandle); 13295 mSettings.removeUserLPw(userHandle); 13296 mPendingBroadcasts.remove(userHandle); 13297 if (mInstaller != null) { 13298 // Technically, we shouldn't be doing this with the package lock 13299 // held. However, this is very rare, and there is already so much 13300 // other disk I/O going on, that we'll let it slide for now. 13301 mInstaller.removeUserDataDirs(userHandle); 13302 } 13303 mUserNeedsBadging.delete(userHandle); 13304 removeUnusedPackagesLILPw(userManager, userHandle); 13305 } 13306 13307 /** 13308 * We're removing userHandle and would like to remove any downloaded packages 13309 * that are no longer in use by any other user. 13310 * @param userHandle the user being removed 13311 */ 13312 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13313 final boolean DEBUG_CLEAN_APKS = false; 13314 int [] users = userManager.getUserIdsLPr(); 13315 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13316 while (psit.hasNext()) { 13317 PackageSetting ps = psit.next(); 13318 if (ps.pkg == null) { 13319 continue; 13320 } 13321 final String packageName = ps.pkg.packageName; 13322 // Skip over if system app 13323 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13324 continue; 13325 } 13326 if (DEBUG_CLEAN_APKS) { 13327 Slog.i(TAG, "Checking package " + packageName); 13328 } 13329 boolean keep = false; 13330 for (int i = 0; i < users.length; i++) { 13331 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13332 keep = true; 13333 if (DEBUG_CLEAN_APKS) { 13334 Slog.i(TAG, " Keeping package " + packageName + " for user " 13335 + users[i]); 13336 } 13337 break; 13338 } 13339 } 13340 if (!keep) { 13341 if (DEBUG_CLEAN_APKS) { 13342 Slog.i(TAG, " Removing package " + packageName); 13343 } 13344 mHandler.post(new Runnable() { 13345 public void run() { 13346 deletePackageX(packageName, userHandle, 0); 13347 } //end run 13348 }); 13349 } 13350 } 13351 } 13352 13353 /** Called by UserManagerService */ 13354 void createNewUserLILPw(int userHandle, File path) { 13355 if (mInstaller != null) { 13356 mInstaller.createUserConfig(userHandle); 13357 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13358 } 13359 } 13360 13361 @Override 13362 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13363 mContext.enforceCallingOrSelfPermission( 13364 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13365 "Only package verification agents can read the verifier device identity"); 13366 13367 synchronized (mPackages) { 13368 return mSettings.getVerifierDeviceIdentityLPw(); 13369 } 13370 } 13371 13372 @Override 13373 public void setPermissionEnforced(String permission, boolean enforced) { 13374 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13375 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13376 synchronized (mPackages) { 13377 if (mSettings.mReadExternalStorageEnforced == null 13378 || mSettings.mReadExternalStorageEnforced != enforced) { 13379 mSettings.mReadExternalStorageEnforced = enforced; 13380 mSettings.writeLPr(); 13381 } 13382 } 13383 // kill any non-foreground processes so we restart them and 13384 // grant/revoke the GID. 13385 final IActivityManager am = ActivityManagerNative.getDefault(); 13386 if (am != null) { 13387 final long token = Binder.clearCallingIdentity(); 13388 try { 13389 am.killProcessesBelowForeground("setPermissionEnforcement"); 13390 } catch (RemoteException e) { 13391 } finally { 13392 Binder.restoreCallingIdentity(token); 13393 } 13394 } 13395 } else { 13396 throw new IllegalArgumentException("No selective enforcement for " + permission); 13397 } 13398 } 13399 13400 @Override 13401 @Deprecated 13402 public boolean isPermissionEnforced(String permission) { 13403 return true; 13404 } 13405 13406 @Override 13407 public boolean isStorageLow() { 13408 final long token = Binder.clearCallingIdentity(); 13409 try { 13410 final DeviceStorageMonitorInternal 13411 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13412 if (dsm != null) { 13413 return dsm.isMemoryLow(); 13414 } else { 13415 return false; 13416 } 13417 } finally { 13418 Binder.restoreCallingIdentity(token); 13419 } 13420 } 13421 13422 @Override 13423 public IPackageInstaller getPackageInstaller() { 13424 return mInstallerService; 13425 } 13426 13427 private boolean userNeedsBadging(int userId) { 13428 int index = mUserNeedsBadging.indexOfKey(userId); 13429 if (index < 0) { 13430 final UserInfo userInfo; 13431 final long token = Binder.clearCallingIdentity(); 13432 try { 13433 userInfo = sUserManager.getUserInfo(userId); 13434 } finally { 13435 Binder.restoreCallingIdentity(token); 13436 } 13437 final boolean b; 13438 if (userInfo != null && userInfo.isManagedProfile()) { 13439 b = true; 13440 } else { 13441 b = false; 13442 } 13443 mUserNeedsBadging.put(userId, b); 13444 return b; 13445 } 13446 return mUserNeedsBadging.valueAt(index); 13447 } 13448 13449 @Override 13450 public KeySet getKeySetByAlias(String packageName, String alias) { 13451 if (packageName == null || alias == null) { 13452 return null; 13453 } 13454 synchronized(mPackages) { 13455 final PackageParser.Package pkg = mPackages.get(packageName); 13456 if (pkg == null) { 13457 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13458 throw new IllegalArgumentException("Unknown package: " + packageName); 13459 } 13460 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13461 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13462 } 13463 } 13464 13465 @Override 13466 public KeySet getSigningKeySet(String packageName) { 13467 if (packageName == null) { 13468 return null; 13469 } 13470 synchronized(mPackages) { 13471 final PackageParser.Package pkg = mPackages.get(packageName); 13472 if (pkg == null) { 13473 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13474 throw new IllegalArgumentException("Unknown package: " + packageName); 13475 } 13476 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13477 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13478 throw new SecurityException("May not access signing KeySet of other apps."); 13479 } 13480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13481 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13482 } 13483 } 13484 13485 @Override 13486 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13487 if (packageName == null || ks == null) { 13488 return false; 13489 } 13490 synchronized(mPackages) { 13491 final PackageParser.Package pkg = mPackages.get(packageName); 13492 if (pkg == null) { 13493 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13494 throw new IllegalArgumentException("Unknown package: " + packageName); 13495 } 13496 IBinder ksh = ks.getToken(); 13497 if (ksh instanceof KeySetHandle) { 13498 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13499 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13500 } 13501 return false; 13502 } 13503 } 13504 13505 @Override 13506 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13507 if (packageName == null || ks == null) { 13508 return false; 13509 } 13510 synchronized(mPackages) { 13511 final PackageParser.Package pkg = mPackages.get(packageName); 13512 if (pkg == null) { 13513 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13514 throw new IllegalArgumentException("Unknown package: " + packageName); 13515 } 13516 IBinder ksh = ks.getToken(); 13517 if (ksh instanceof KeySetHandle) { 13518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13519 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13520 } 13521 return false; 13522 } 13523 } 13524 13525 public void getUsageStatsIfNoPackageUsageInfo() { 13526 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13527 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13528 if (usm == null) { 13529 throw new IllegalStateException("UsageStatsManager must be initialized"); 13530 } 13531 long now = System.currentTimeMillis(); 13532 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13533 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13534 String packageName = entry.getKey(); 13535 PackageParser.Package pkg = mPackages.get(packageName); 13536 if (pkg == null) { 13537 continue; 13538 } 13539 UsageStats usage = entry.getValue(); 13540 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13541 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13542 } 13543 } 13544 } 13545 13546 /** 13547 * Check and throw if the given before/after packages would be considered a 13548 * downgrade. 13549 */ 13550 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13551 throws PackageManagerException { 13552 if (after.versionCode < before.mVersionCode) { 13553 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13554 "Update version code " + after.versionCode + " is older than current " 13555 + before.mVersionCode); 13556 } else if (after.versionCode == before.mVersionCode) { 13557 if (after.baseRevisionCode < before.baseRevisionCode) { 13558 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13559 "Update base revision code " + after.baseRevisionCode 13560 + " is older than current " + before.baseRevisionCode); 13561 } 13562 13563 if (!ArrayUtils.isEmpty(after.splitNames)) { 13564 for (int i = 0; i < after.splitNames.length; i++) { 13565 final String splitName = after.splitNames[i]; 13566 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13567 if (j != -1) { 13568 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13569 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13570 "Update split " + splitName + " revision code " 13571 + after.splitRevisionCodes[i] + " is older than current " 13572 + before.splitRevisionCodes[j]); 13573 } 13574 } 13575 } 13576 } 13577 } 13578 } 13579} 13580