PackageManagerService.java revision 7265abe77a76f848a316640b5da106e882bdbc8a
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_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.AppGlobals; 84import android.app.IActivityManager; 85import android.app.admin.IDevicePolicyManager; 86import android.app.backup.IBackupManager; 87import android.content.BroadcastReceiver; 88import android.content.ComponentName; 89import android.content.Context; 90import android.content.IIntentReceiver; 91import android.content.Intent; 92import android.content.IntentFilter; 93import android.content.IntentSender; 94import android.content.IntentSender.SendIntentException; 95import android.content.ServiceConnection; 96import android.content.pm.ActivityInfo; 97import android.content.pm.ApplicationInfo; 98import android.content.pm.FeatureInfo; 99import android.content.pm.IPackageDataObserver; 100import android.content.pm.IPackageDeleteObserver; 101import android.content.pm.IPackageDeleteObserver2; 102import android.content.pm.IPackageInstallObserver2; 103import android.content.pm.IPackageInstaller; 104import android.content.pm.IPackageManager; 105import android.content.pm.IPackageMoveObserver; 106import android.content.pm.IPackageStatsObserver; 107import android.content.pm.InstrumentationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.storage.IMountService; 142import android.os.storage.StorageManager; 143import android.os.Debug; 144import android.os.FileUtils; 145import android.os.Handler; 146import android.os.IBinder; 147import android.os.Looper; 148import android.os.Message; 149import android.os.Parcel; 150import android.os.ParcelFileDescriptor; 151import android.os.Process; 152import android.os.RemoteException; 153import android.os.SELinux; 154import android.os.ServiceManager; 155import android.os.SystemClock; 156import android.os.SystemProperties; 157import android.os.UserHandle; 158import android.os.UserManager; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.view.Display; 178 179import java.io.BufferedInputStream; 180import java.io.BufferedOutputStream; 181import java.io.BufferedReader; 182import java.io.File; 183import java.io.FileDescriptor; 184import java.io.FileInputStream; 185import java.io.FileNotFoundException; 186import java.io.FileOutputStream; 187import java.io.FileReader; 188import java.io.FilenameFilter; 189import java.io.IOException; 190import java.io.InputStream; 191import java.io.PrintWriter; 192import java.nio.charset.StandardCharsets; 193import java.security.NoSuchAlgorithmException; 194import java.security.PublicKey; 195import java.security.cert.CertificateEncodingException; 196import java.security.cert.CertificateException; 197import java.text.SimpleDateFormat; 198import java.util.ArrayList; 199import java.util.Arrays; 200import java.util.Collection; 201import java.util.Collections; 202import java.util.Comparator; 203import java.util.Date; 204import java.util.HashMap; 205import java.util.HashSet; 206import java.util.Iterator; 207import java.util.List; 208import java.util.Map; 209import java.util.Objects; 210import java.util.Set; 211import java.util.concurrent.atomic.AtomicBoolean; 212import java.util.concurrent.atomic.AtomicLong; 213 214import dalvik.system.DexFile; 215import dalvik.system.StaleDexCacheError; 216import dalvik.system.VMRuntime; 217 218import libcore.io.IoUtils; 219import libcore.util.EmptyArray; 220 221/** 222 * Keep track of all those .apks everywhere. 223 * 224 * This is very central to the platform's security; please run the unit 225 * tests whenever making modifications here: 226 * 227mmm frameworks/base/tests/AndroidTests 228adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 229adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 230 * 231 * {@hide} 232 */ 233public class PackageManagerService extends IPackageManager.Stub { 234 static final String TAG = "PackageManager"; 235 static final boolean DEBUG_SETTINGS = false; 236 static final boolean DEBUG_PREFERRED = false; 237 static final boolean DEBUG_UPGRADE = false; 238 private static final boolean DEBUG_INSTALL = false; 239 private static final boolean DEBUG_REMOVE = false; 240 private static final boolean DEBUG_BROADCASTS = false; 241 private static final boolean DEBUG_SHOW_INFO = false; 242 private static final boolean DEBUG_PACKAGE_INFO = false; 243 private static final boolean DEBUG_INTENT_MATCHING = false; 244 private static final boolean DEBUG_PACKAGE_SCANNING = false; 245 private static final boolean DEBUG_VERIFY = false; 246 private static final boolean DEBUG_DEXOPT = false; 247 private static final boolean DEBUG_ABI_SELECTION = false; 248 249 private static final int RADIO_UID = Process.PHONE_UID; 250 private static final int LOG_UID = Process.LOG_UID; 251 private static final int NFC_UID = Process.NFC_UID; 252 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 253 private static final int SHELL_UID = Process.SHELL_UID; 254 255 // Cap the size of permission trees that 3rd party apps can define 256 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 257 258 // Suffix used during package installation when copying/moving 259 // package apks to install directory. 260 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 261 262 static final int SCAN_NO_DEX = 1<<1; 263 static final int SCAN_FORCE_DEX = 1<<2; 264 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 265 static final int SCAN_NEW_INSTALL = 1<<4; 266 static final int SCAN_NO_PATHS = 1<<5; 267 static final int SCAN_UPDATE_TIME = 1<<6; 268 static final int SCAN_DEFER_DEX = 1<<7; 269 static final int SCAN_BOOTING = 1<<8; 270 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 271 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 272 static final int SCAN_REPLACING = 1<<11; 273 274 static final int REMOVE_CHATTY = 1<<16; 275 276 /** 277 * Timeout (in milliseconds) after which the watchdog should declare that 278 * our handler thread is wedged. The usual default for such things is one 279 * minute but we sometimes do very lengthy I/O operations on this thread, 280 * such as installing multi-gigabyte applications, so ours needs to be longer. 281 */ 282 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 283 284 /** 285 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 286 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 287 * settings entry if available, otherwise we use the hardcoded default. If it's been 288 * more than this long since the last fstrim, we force one during the boot sequence. 289 * 290 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 291 * one gets run at the next available charging+idle time. This final mandatory 292 * no-fstrim check kicks in only of the other scheduling criteria is never met. 293 */ 294 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 295 296 /** 297 * Whether verification is enabled by default. 298 */ 299 private static final boolean DEFAULT_VERIFY_ENABLE = true; 300 301 /** 302 * The default maximum time to wait for the verification agent to return in 303 * milliseconds. 304 */ 305 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 306 307 /** 308 * The default response for package verification timeout. 309 * 310 * This can be either PackageManager.VERIFICATION_ALLOW or 311 * PackageManager.VERIFICATION_REJECT. 312 */ 313 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 314 315 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 316 317 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 318 DEFAULT_CONTAINER_PACKAGE, 319 "com.android.defcontainer.DefaultContainerService"); 320 321 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 322 323 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 324 325 private static String sPreferredInstructionSet; 326 327 final ServiceThread mHandlerThread; 328 329 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 330 private static final String IDMAP_SUFFIX = "@idmap"; 331 332 final PackageHandler mHandler; 333 334 /** 335 * Messages for {@link #mHandler} that need to wait for system ready before 336 * being dispatched. 337 */ 338 private ArrayList<Message> mPostSystemReadyMessages; 339 340 final int mSdkVersion = Build.VERSION.SDK_INT; 341 342 final Context mContext; 343 final boolean mFactoryTest; 344 final boolean mOnlyCore; 345 final boolean mLazyDexOpt; 346 final DisplayMetrics mMetrics; 347 final int mDefParseFlags; 348 final String[] mSeparateProcesses; 349 350 // This is where all application persistent data goes. 351 final File mAppDataDir; 352 353 // This is where all application persistent data goes for secondary users. 354 final File mUserAppDataDir; 355 356 /** The location for ASEC container files on internal storage. */ 357 final String mAsecInternalPath; 358 359 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 360 // LOCK HELD. Can be called with mInstallLock held. 361 final Installer mInstaller; 362 363 /** Directory where installed third-party apps stored */ 364 final File mAppInstallDir; 365 366 /** 367 * Directory to which applications installed internally have their 368 * 32 bit native libraries copied. 369 */ 370 private File mAppLib32InstallDir; 371 372 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 373 // apps. 374 final File mDrmAppPrivateInstallDir; 375 376 // ---------------------------------------------------------------- 377 378 // Lock for state used when installing and doing other long running 379 // operations. Methods that must be called with this lock held have 380 // the suffix "LI". 381 final Object mInstallLock = new Object(); 382 383 // ---------------------------------------------------------------- 384 385 // Keys are String (package name), values are Package. This also serves 386 // as the lock for the global state. Methods that must be called with 387 // this lock held have the prefix "LP". 388 final HashMap<String, PackageParser.Package> mPackages = 389 new HashMap<String, PackageParser.Package>(); 390 391 // Tracks available target package names -> overlay package paths. 392 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 393 new HashMap<String, HashMap<String, PackageParser.Package>>(); 394 395 final Settings mSettings; 396 boolean mRestoredSettings; 397 398 // System configuration read by SystemConfig. 399 final int[] mGlobalGids; 400 final SparseArray<HashSet<String>> mSystemPermissions; 401 final HashMap<String, FeatureInfo> mAvailableFeatures; 402 403 // If mac_permissions.xml was found for seinfo labeling. 404 boolean mFoundPolicyFile; 405 406 // If a recursive restorecon of /data/data/<pkg> is needed. 407 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 408 409 public static final class SharedLibraryEntry { 410 public final String path; 411 public final String apk; 412 413 SharedLibraryEntry(String _path, String _apk) { 414 path = _path; 415 apk = _apk; 416 } 417 } 418 419 // Currently known shared libraries. 420 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 421 new HashMap<String, SharedLibraryEntry>(); 422 423 // All available activities, for your resolving pleasure. 424 final ActivityIntentResolver mActivities = 425 new ActivityIntentResolver(); 426 427 // All available receivers, for your resolving pleasure. 428 final ActivityIntentResolver mReceivers = 429 new ActivityIntentResolver(); 430 431 // All available services, for your resolving pleasure. 432 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 433 434 // All available providers, for your resolving pleasure. 435 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 436 437 // Mapping from provider base names (first directory in content URI codePath) 438 // to the provider information. 439 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 440 new HashMap<String, PackageParser.Provider>(); 441 442 // Mapping from instrumentation class names to info about them. 443 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 444 new HashMap<ComponentName, PackageParser.Instrumentation>(); 445 446 // Mapping from permission names to info about them. 447 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 448 new HashMap<String, PackageParser.PermissionGroup>(); 449 450 // Packages whose data we have transfered into another package, thus 451 // should no longer exist. 452 final HashSet<String> mTransferedPackages = new HashSet<String>(); 453 454 // Broadcast actions that are only available to the system. 455 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 456 457 /** List of packages waiting for verification. */ 458 final SparseArray<PackageVerificationState> mPendingVerification 459 = new SparseArray<PackageVerificationState>(); 460 461 /** Set of packages associated with each app op permission. */ 462 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 463 464 final PackageInstallerService mInstallerService; 465 466 HashSet<PackageParser.Package> mDeferredDexOpt = null; 467 468 // Cache of users who need badging. 469 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 470 471 /** Token for keys in mPendingVerification. */ 472 private int mPendingVerificationToken = 0; 473 474 volatile boolean mSystemReady; 475 volatile boolean mSafeMode; 476 volatile boolean mHasSystemUidErrors; 477 478 ApplicationInfo mAndroidApplication; 479 final ActivityInfo mResolveActivity = new ActivityInfo(); 480 final ResolveInfo mResolveInfo = new ResolveInfo(); 481 ComponentName mResolveComponentName; 482 PackageParser.Package mPlatformPackage; 483 ComponentName mCustomResolverComponentName; 484 485 boolean mResolverReplaced = false; 486 487 // Set of pending broadcasts for aggregating enable/disable of components. 488 static class PendingPackageBroadcasts { 489 // for each user id, a map of <package name -> components within that package> 490 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 491 492 public PendingPackageBroadcasts() { 493 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 494 } 495 496 public ArrayList<String> get(int userId, String packageName) { 497 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 498 return packages.get(packageName); 499 } 500 501 public void put(int userId, String packageName, ArrayList<String> components) { 502 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 503 packages.put(packageName, components); 504 } 505 506 public void remove(int userId, String packageName) { 507 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 508 if (packages != null) { 509 packages.remove(packageName); 510 } 511 } 512 513 public void remove(int userId) { 514 mUidMap.remove(userId); 515 } 516 517 public int userIdCount() { 518 return mUidMap.size(); 519 } 520 521 public int userIdAt(int n) { 522 return mUidMap.keyAt(n); 523 } 524 525 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 526 return mUidMap.get(userId); 527 } 528 529 public int size() { 530 // total number of pending broadcast entries across all userIds 531 int num = 0; 532 for (int i = 0; i< mUidMap.size(); i++) { 533 num += mUidMap.valueAt(i).size(); 534 } 535 return num; 536 } 537 538 public void clear() { 539 mUidMap.clear(); 540 } 541 542 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 543 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 544 if (map == null) { 545 map = new HashMap<String, ArrayList<String>>(); 546 mUidMap.put(userId, map); 547 } 548 return map; 549 } 550 } 551 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 552 553 // Service Connection to remote media container service to copy 554 // package uri's from external media onto secure containers 555 // or internal storage. 556 private IMediaContainerService mContainerService = null; 557 558 static final int SEND_PENDING_BROADCAST = 1; 559 static final int MCS_BOUND = 3; 560 static final int END_COPY = 4; 561 static final int INIT_COPY = 5; 562 static final int MCS_UNBIND = 6; 563 static final int START_CLEANING_PACKAGE = 7; 564 static final int FIND_INSTALL_LOC = 8; 565 static final int POST_INSTALL = 9; 566 static final int MCS_RECONNECT = 10; 567 static final int MCS_GIVE_UP = 11; 568 static final int UPDATED_MEDIA_STATUS = 12; 569 static final int WRITE_SETTINGS = 13; 570 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 571 static final int PACKAGE_VERIFIED = 15; 572 static final int CHECK_PENDING_VERIFICATION = 16; 573 574 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 575 576 // Delay time in millisecs 577 static final int BROADCAST_DELAY = 10 * 1000; 578 579 static UserManagerService sUserManager; 580 581 // Stores a list of users whose package restrictions file needs to be updated 582 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 583 584 final private DefaultContainerConnection mDefContainerConn = 585 new DefaultContainerConnection(); 586 class DefaultContainerConnection implements ServiceConnection { 587 public void onServiceConnected(ComponentName name, IBinder service) { 588 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 589 IMediaContainerService imcs = 590 IMediaContainerService.Stub.asInterface(service); 591 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 592 } 593 594 public void onServiceDisconnected(ComponentName name) { 595 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 596 } 597 }; 598 599 // Recordkeeping of restore-after-install operations that are currently in flight 600 // between the Package Manager and the Backup Manager 601 class PostInstallData { 602 public InstallArgs args; 603 public PackageInstalledInfo res; 604 605 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 606 args = _a; 607 res = _r; 608 } 609 }; 610 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 611 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 612 613 private final String mRequiredVerifierPackage; 614 615 private final PackageUsage mPackageUsage = new PackageUsage(); 616 617 private class PackageUsage { 618 private static final int WRITE_INTERVAL 619 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 620 621 private final Object mFileLock = new Object(); 622 private final AtomicLong mLastWritten = new AtomicLong(0); 623 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 624 625 private boolean mIsHistoricalPackageUsageAvailable = true; 626 627 boolean isHistoricalPackageUsageAvailable() { 628 return mIsHistoricalPackageUsageAvailable; 629 } 630 631 void write(boolean force) { 632 if (force) { 633 writeInternal(); 634 return; 635 } 636 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 637 && !DEBUG_DEXOPT) { 638 return; 639 } 640 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 641 new Thread("PackageUsage_DiskWriter") { 642 @Override 643 public void run() { 644 try { 645 writeInternal(); 646 } finally { 647 mBackgroundWriteRunning.set(false); 648 } 649 } 650 }.start(); 651 } 652 } 653 654 private void writeInternal() { 655 synchronized (mPackages) { 656 synchronized (mFileLock) { 657 AtomicFile file = getFile(); 658 FileOutputStream f = null; 659 try { 660 f = file.startWrite(); 661 BufferedOutputStream out = new BufferedOutputStream(f); 662 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 663 StringBuilder sb = new StringBuilder(); 664 for (PackageParser.Package pkg : mPackages.values()) { 665 if (pkg.mLastPackageUsageTimeInMills == 0) { 666 continue; 667 } 668 sb.setLength(0); 669 sb.append(pkg.packageName); 670 sb.append(' '); 671 sb.append((long)pkg.mLastPackageUsageTimeInMills); 672 sb.append('\n'); 673 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 674 } 675 out.flush(); 676 file.finishWrite(f); 677 } catch (IOException e) { 678 if (f != null) { 679 file.failWrite(f); 680 } 681 Log.e(TAG, "Failed to write package usage times", e); 682 } 683 } 684 } 685 mLastWritten.set(SystemClock.elapsedRealtime()); 686 } 687 688 void readLP() { 689 synchronized (mFileLock) { 690 AtomicFile file = getFile(); 691 BufferedInputStream in = null; 692 try { 693 in = new BufferedInputStream(file.openRead()); 694 StringBuffer sb = new StringBuffer(); 695 while (true) { 696 String packageName = readToken(in, sb, ' '); 697 if (packageName == null) { 698 break; 699 } 700 String timeInMillisString = readToken(in, sb, '\n'); 701 if (timeInMillisString == null) { 702 throw new IOException("Failed to find last usage time for package " 703 + packageName); 704 } 705 PackageParser.Package pkg = mPackages.get(packageName); 706 if (pkg == null) { 707 continue; 708 } 709 long timeInMillis; 710 try { 711 timeInMillis = Long.parseLong(timeInMillisString.toString()); 712 } catch (NumberFormatException e) { 713 throw new IOException("Failed to parse " + timeInMillisString 714 + " as a long.", e); 715 } 716 pkg.mLastPackageUsageTimeInMills = timeInMillis; 717 } 718 } catch (FileNotFoundException expected) { 719 mIsHistoricalPackageUsageAvailable = false; 720 } catch (IOException e) { 721 Log.w(TAG, "Failed to read package usage times", e); 722 } finally { 723 IoUtils.closeQuietly(in); 724 } 725 } 726 mLastWritten.set(SystemClock.elapsedRealtime()); 727 } 728 729 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 730 throws IOException { 731 sb.setLength(0); 732 while (true) { 733 int ch = in.read(); 734 if (ch == -1) { 735 if (sb.length() == 0) { 736 return null; 737 } 738 throw new IOException("Unexpected EOF"); 739 } 740 if (ch == endOfToken) { 741 return sb.toString(); 742 } 743 sb.append((char)ch); 744 } 745 } 746 747 private AtomicFile getFile() { 748 File dataDir = Environment.getDataDirectory(); 749 File systemDir = new File(dataDir, "system"); 750 File fname = new File(systemDir, "package-usage.list"); 751 return new AtomicFile(fname); 752 } 753 } 754 755 class PackageHandler extends Handler { 756 private boolean mBound = false; 757 final ArrayList<HandlerParams> mPendingInstalls = 758 new ArrayList<HandlerParams>(); 759 760 private boolean connectToService() { 761 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 762 " DefaultContainerService"); 763 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 if (mContext.bindServiceAsUser(service, mDefContainerConn, 766 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 767 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 768 mBound = true; 769 return true; 770 } 771 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 772 return false; 773 } 774 775 private void disconnectService() { 776 mContainerService = null; 777 mBound = false; 778 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 779 mContext.unbindService(mDefContainerConn); 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 } 782 783 PackageHandler(Looper looper) { 784 super(looper); 785 } 786 787 public void handleMessage(Message msg) { 788 try { 789 doHandleMessage(msg); 790 } finally { 791 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 792 } 793 } 794 795 void doHandleMessage(Message msg) { 796 switch (msg.what) { 797 case INIT_COPY: { 798 HandlerParams params = (HandlerParams) msg.obj; 799 int idx = mPendingInstalls.size(); 800 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 801 // If a bind was already initiated we dont really 802 // need to do anything. The pending install 803 // will be processed later on. 804 if (!mBound) { 805 // If this is the only one pending we might 806 // have to bind to the service again. 807 if (!connectToService()) { 808 Slog.e(TAG, "Failed to bind to media container service"); 809 params.serviceError(); 810 return; 811 } else { 812 // Once we bind to the service, the first 813 // pending request will be processed. 814 mPendingInstalls.add(idx, params); 815 } 816 } else { 817 mPendingInstalls.add(idx, params); 818 // Already bound to the service. Just make 819 // sure we trigger off processing the first request. 820 if (idx == 0) { 821 mHandler.sendEmptyMessage(MCS_BOUND); 822 } 823 } 824 break; 825 } 826 case MCS_BOUND: { 827 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 828 if (msg.obj != null) { 829 mContainerService = (IMediaContainerService) msg.obj; 830 } 831 if (mContainerService == null) { 832 // Something seriously wrong. Bail out 833 Slog.e(TAG, "Cannot bind to media container service"); 834 for (HandlerParams params : mPendingInstalls) { 835 // Indicate service bind error 836 params.serviceError(); 837 } 838 mPendingInstalls.clear(); 839 } else if (mPendingInstalls.size() > 0) { 840 HandlerParams params = mPendingInstalls.get(0); 841 if (params != null) { 842 if (params.startCopy()) { 843 // We are done... look for more work or to 844 // go idle. 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Checking for more work or unbind..."); 847 // Delete pending install 848 if (mPendingInstalls.size() > 0) { 849 mPendingInstalls.remove(0); 850 } 851 if (mPendingInstalls.size() == 0) { 852 if (mBound) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, 854 "Posting delayed MCS_UNBIND"); 855 removeMessages(MCS_UNBIND); 856 Message ubmsg = obtainMessage(MCS_UNBIND); 857 // Unbind after a little delay, to avoid 858 // continual thrashing. 859 sendMessageDelayed(ubmsg, 10000); 860 } 861 } else { 862 // There are more pending requests in queue. 863 // Just post MCS_BOUND message to trigger processing 864 // of next pending install. 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Posting MCS_BOUND for next work"); 867 mHandler.sendEmptyMessage(MCS_BOUND); 868 } 869 } 870 } 871 } else { 872 // Should never happen ideally. 873 Slog.w(TAG, "Empty queue"); 874 } 875 break; 876 } 877 case MCS_RECONNECT: { 878 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 879 if (mPendingInstalls.size() > 0) { 880 if (mBound) { 881 disconnectService(); 882 } 883 if (!connectToService()) { 884 Slog.e(TAG, "Failed to bind to media container service"); 885 for (HandlerParams params : mPendingInstalls) { 886 // Indicate service bind error 887 params.serviceError(); 888 } 889 mPendingInstalls.clear(); 890 } 891 } 892 break; 893 } 894 case MCS_UNBIND: { 895 // If there is no actual work left, then time to unbind. 896 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 897 898 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 899 if (mBound) { 900 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 901 902 disconnectService(); 903 } 904 } else if (mPendingInstalls.size() > 0) { 905 // There are more pending requests in queue. 906 // Just post MCS_BOUND message to trigger processing 907 // of next pending install. 908 mHandler.sendEmptyMessage(MCS_BOUND); 909 } 910 911 break; 912 } 913 case MCS_GIVE_UP: { 914 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 915 mPendingInstalls.remove(0); 916 break; 917 } 918 case SEND_PENDING_BROADCAST: { 919 String packages[]; 920 ArrayList<String> components[]; 921 int size = 0; 922 int uids[]; 923 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 924 synchronized (mPackages) { 925 if (mPendingBroadcasts == null) { 926 return; 927 } 928 size = mPendingBroadcasts.size(); 929 if (size <= 0) { 930 // Nothing to be done. Just return 931 return; 932 } 933 packages = new String[size]; 934 components = new ArrayList[size]; 935 uids = new int[size]; 936 int i = 0; // filling out the above arrays 937 938 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 939 int packageUserId = mPendingBroadcasts.userIdAt(n); 940 Iterator<Map.Entry<String, ArrayList<String>>> it 941 = mPendingBroadcasts.packagesForUserId(packageUserId) 942 .entrySet().iterator(); 943 while (it.hasNext() && i < size) { 944 Map.Entry<String, ArrayList<String>> ent = it.next(); 945 packages[i] = ent.getKey(); 946 components[i] = ent.getValue(); 947 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 948 uids[i] = (ps != null) 949 ? UserHandle.getUid(packageUserId, ps.appId) 950 : -1; 951 i++; 952 } 953 } 954 size = i; 955 mPendingBroadcasts.clear(); 956 } 957 // Send broadcasts 958 for (int i = 0; i < size; i++) { 959 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 960 } 961 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 962 break; 963 } 964 case START_CLEANING_PACKAGE: { 965 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 966 final String packageName = (String)msg.obj; 967 final int userId = msg.arg1; 968 final boolean andCode = msg.arg2 != 0; 969 synchronized (mPackages) { 970 if (userId == UserHandle.USER_ALL) { 971 int[] users = sUserManager.getUserIds(); 972 for (int user : users) { 973 mSettings.addPackageToCleanLPw( 974 new PackageCleanItem(user, packageName, andCode)); 975 } 976 } else { 977 mSettings.addPackageToCleanLPw( 978 new PackageCleanItem(userId, packageName, andCode)); 979 } 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 startCleaningPackages(); 983 } break; 984 case POST_INSTALL: { 985 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 986 PostInstallData data = mRunningInstalls.get(msg.arg1); 987 mRunningInstalls.delete(msg.arg1); 988 boolean deleteOld = false; 989 990 if (data != null) { 991 InstallArgs args = data.args; 992 PackageInstalledInfo res = data.res; 993 994 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 995 res.removedInfo.sendBroadcast(false, true, false); 996 Bundle extras = new Bundle(1); 997 extras.putInt(Intent.EXTRA_UID, res.uid); 998 // Determine the set of users who are adding this 999 // package for the first time vs. those who are seeing 1000 // an update. 1001 int[] firstUsers; 1002 int[] updateUsers = new int[0]; 1003 if (res.origUsers == null || res.origUsers.length == 0) { 1004 firstUsers = res.newUsers; 1005 } else { 1006 firstUsers = new int[0]; 1007 for (int i=0; i<res.newUsers.length; i++) { 1008 int user = res.newUsers[i]; 1009 boolean isNew = true; 1010 for (int j=0; j<res.origUsers.length; j++) { 1011 if (res.origUsers[j] == user) { 1012 isNew = false; 1013 break; 1014 } 1015 } 1016 if (isNew) { 1017 int[] newFirst = new int[firstUsers.length+1]; 1018 System.arraycopy(firstUsers, 0, newFirst, 0, 1019 firstUsers.length); 1020 newFirst[firstUsers.length] = user; 1021 firstUsers = newFirst; 1022 } else { 1023 int[] newUpdate = new int[updateUsers.length+1]; 1024 System.arraycopy(updateUsers, 0, newUpdate, 0, 1025 updateUsers.length); 1026 newUpdate[updateUsers.length] = user; 1027 updateUsers = newUpdate; 1028 } 1029 } 1030 } 1031 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1032 res.pkg.applicationInfo.packageName, 1033 extras, null, null, firstUsers); 1034 final boolean update = res.removedInfo.removedPackage != null; 1035 if (update) { 1036 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1037 } 1038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1039 res.pkg.applicationInfo.packageName, 1040 extras, null, null, updateUsers); 1041 if (update) { 1042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1043 res.pkg.applicationInfo.packageName, 1044 extras, null, null, updateUsers); 1045 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1046 null, null, 1047 res.pkg.applicationInfo.packageName, null, updateUsers); 1048 1049 // treat asec-hosted packages like removable media on upgrade 1050 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1051 if (DEBUG_INSTALL) { 1052 Slog.i(TAG, "upgrading pkg " + res.pkg 1053 + " is ASEC-hosted -> AVAILABLE"); 1054 } 1055 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1056 ArrayList<String> pkgList = new ArrayList<String>(1); 1057 pkgList.add(res.pkg.applicationInfo.packageName); 1058 sendResourcesChangedBroadcast(true, true, 1059 pkgList,uidArray, null); 1060 } 1061 } 1062 if (res.removedInfo.args != null) { 1063 // Remove the replaced package's older resources safely now 1064 deleteOld = true; 1065 } 1066 1067 // Log current value of "unknown sources" setting 1068 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1069 getUnknownSourcesSettings()); 1070 } 1071 // Force a gc to clear up things 1072 Runtime.getRuntime().gc(); 1073 // We delete after a gc for applications on sdcard. 1074 if (deleteOld) { 1075 synchronized (mInstallLock) { 1076 res.removedInfo.args.doPostDeleteLI(true); 1077 } 1078 } 1079 if (args.observer != null) { 1080 try { 1081 Bundle extras = extrasForInstallResult(res); 1082 args.observer.onPackageInstalled(res.name, res.returnCode, 1083 res.returnMsg, extras); 1084 } catch (RemoteException e) { 1085 Slog.i(TAG, "Observer no longer exists."); 1086 } 1087 } 1088 } else { 1089 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1090 } 1091 } break; 1092 case UPDATED_MEDIA_STATUS: { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1094 boolean reportStatus = msg.arg1 == 1; 1095 boolean doGc = msg.arg2 == 1; 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1097 if (doGc) { 1098 // Force a gc to clear up stale containers. 1099 Runtime.getRuntime().gc(); 1100 } 1101 if (msg.obj != null) { 1102 @SuppressWarnings("unchecked") 1103 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1105 // Unload containers 1106 unloadAllContainers(args); 1107 } 1108 if (reportStatus) { 1109 try { 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1111 PackageHelper.getMountService().finishMediaUpdate(); 1112 } catch (RemoteException e) { 1113 Log.e(TAG, "MountService not running?"); 1114 } 1115 } 1116 } break; 1117 case WRITE_SETTINGS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_SETTINGS); 1121 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1122 mSettings.writeLPr(); 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case WRITE_PACKAGE_RESTRICTIONS: { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1129 synchronized (mPackages) { 1130 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1131 for (int userId : mDirtyUsers) { 1132 mSettings.writePackageRestrictionsLPr(userId); 1133 } 1134 mDirtyUsers.clear(); 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } break; 1138 case CHECK_PENDING_VERIFICATION: { 1139 final int verificationId = msg.arg1; 1140 final PackageVerificationState state = mPendingVerification.get(verificationId); 1141 1142 if ((state != null) && !state.timeoutExtended()) { 1143 final InstallArgs args = state.getInstallArgs(); 1144 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1145 1146 Slog.i(TAG, "Verification timed out for " + originUri); 1147 mPendingVerification.remove(verificationId); 1148 1149 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1150 1151 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1152 Slog.i(TAG, "Continuing with installation of " + originUri); 1153 state.setVerifierResponse(Binder.getCallingUid(), 1154 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1155 broadcastPackageVerified(verificationId, originUri, 1156 PackageManager.VERIFICATION_ALLOW, 1157 state.getInstallArgs().getUser()); 1158 try { 1159 ret = args.copyApk(mContainerService, true); 1160 } catch (RemoteException e) { 1161 Slog.e(TAG, "Could not contact the ContainerService"); 1162 } 1163 } else { 1164 broadcastPackageVerified(verificationId, originUri, 1165 PackageManager.VERIFICATION_REJECT, 1166 state.getInstallArgs().getUser()); 1167 } 1168 1169 processPendingInstall(args, ret); 1170 mHandler.sendEmptyMessage(MCS_UNBIND); 1171 } 1172 break; 1173 } 1174 case PACKAGE_VERIFIED: { 1175 final int verificationId = msg.arg1; 1176 1177 final PackageVerificationState state = mPendingVerification.get(verificationId); 1178 if (state == null) { 1179 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1180 break; 1181 } 1182 1183 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1184 1185 state.setVerifierResponse(response.callerUid, response.code); 1186 1187 if (state.isVerificationComplete()) { 1188 mPendingVerification.remove(verificationId); 1189 1190 final InstallArgs args = state.getInstallArgs(); 1191 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1192 1193 int ret; 1194 if (state.isInstallAllowed()) { 1195 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1196 broadcastPackageVerified(verificationId, originUri, 1197 response.code, state.getInstallArgs().getUser()); 1198 try { 1199 ret = args.copyApk(mContainerService, true); 1200 } catch (RemoteException e) { 1201 Slog.e(TAG, "Could not contact the ContainerService"); 1202 } 1203 } else { 1204 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1205 } 1206 1207 processPendingInstall(args, ret); 1208 1209 mHandler.sendEmptyMessage(MCS_UNBIND); 1210 } 1211 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1219 Bundle extras = null; 1220 switch (res.returnCode) { 1221 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1222 extras = new Bundle(); 1223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1224 res.origPermission); 1225 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1226 res.origPackage); 1227 break; 1228 } 1229 } 1230 return extras; 1231 } 1232 1233 void scheduleWriteSettingsLocked() { 1234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1236 } 1237 } 1238 1239 void scheduleWritePackageRestrictionsLocked(int userId) { 1240 if (!sUserManager.exists(userId)) return; 1241 mDirtyUsers.add(userId); 1242 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1243 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1244 } 1245 } 1246 1247 public static final PackageManagerService main(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 PackageManagerService m = new PackageManagerService(context, installer, 1250 factoryTest, onlyCore); 1251 ServiceManager.addService("package", m); 1252 return m; 1253 } 1254 1255 static String[] splitString(String str, char sep) { 1256 int count = 1; 1257 int i = 0; 1258 while ((i=str.indexOf(sep, i)) >= 0) { 1259 count++; 1260 i++; 1261 } 1262 1263 String[] res = new String[count]; 1264 i=0; 1265 count = 0; 1266 int lastI=0; 1267 while ((i=str.indexOf(sep, i)) >= 0) { 1268 res[count] = str.substring(lastI, i); 1269 count++; 1270 i++; 1271 lastI = i; 1272 } 1273 res[count] = str.substring(lastI, str.length()); 1274 return res; 1275 } 1276 1277 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1278 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1279 Context.DISPLAY_SERVICE); 1280 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1281 } 1282 1283 public PackageManagerService(Context context, Installer installer, 1284 boolean factoryTest, boolean onlyCore) { 1285 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1286 SystemClock.uptimeMillis()); 1287 1288 if (mSdkVersion <= 0) { 1289 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1290 } 1291 1292 mContext = context; 1293 mFactoryTest = factoryTest; 1294 mOnlyCore = onlyCore; 1295 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1296 mMetrics = new DisplayMetrics(); 1297 mSettings = new Settings(context); 1298 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1299 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1300 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1301 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1302 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1303 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1304 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1305 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1307 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1309 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1310 1311 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1312 if (separateProcesses != null && separateProcesses.length() > 0) { 1313 if ("*".equals(separateProcesses)) { 1314 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1315 mSeparateProcesses = null; 1316 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1317 } else { 1318 mDefParseFlags = 0; 1319 mSeparateProcesses = separateProcesses.split(","); 1320 Slog.w(TAG, "Running with debug.separate_processes: " 1321 + separateProcesses); 1322 } 1323 } else { 1324 mDefParseFlags = 0; 1325 mSeparateProcesses = null; 1326 } 1327 1328 mInstaller = installer; 1329 1330 getDefaultDisplayMetrics(context, mMetrics); 1331 1332 SystemConfig systemConfig = SystemConfig.getInstance(); 1333 mGlobalGids = systemConfig.getGlobalGids(); 1334 mSystemPermissions = systemConfig.getSystemPermissions(); 1335 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1336 1337 synchronized (mInstallLock) { 1338 // writer 1339 synchronized (mPackages) { 1340 mHandlerThread = new ServiceThread(TAG, 1341 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1342 mHandlerThread.start(); 1343 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1344 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1345 1346 File dataDir = Environment.getDataDirectory(); 1347 mAppDataDir = new File(dataDir, "data"); 1348 mAppInstallDir = new File(dataDir, "app"); 1349 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1350 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1351 mUserAppDataDir = new File(dataDir, "user"); 1352 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1353 1354 sUserManager = new UserManagerService(context, this, 1355 mInstallLock, mPackages); 1356 1357 // Propagate permission configuration in to package manager. 1358 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1359 = systemConfig.getPermissions(); 1360 for (int i=0; i<permConfig.size(); i++) { 1361 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1362 BasePermission bp = mSettings.mPermissions.get(perm.name); 1363 if (bp == null) { 1364 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1365 mSettings.mPermissions.put(perm.name, bp); 1366 } 1367 if (perm.gids != null) { 1368 bp.gids = appendInts(bp.gids, perm.gids); 1369 } 1370 } 1371 1372 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1373 for (int i=0; i<libConfig.size(); i++) { 1374 mSharedLibraries.put(libConfig.keyAt(i), 1375 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1376 } 1377 1378 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1379 1380 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1381 mSdkVersion, mOnlyCore); 1382 1383 String customResolverActivity = Resources.getSystem().getString( 1384 R.string.config_customResolverActivity); 1385 if (TextUtils.isEmpty(customResolverActivity)) { 1386 customResolverActivity = null; 1387 } else { 1388 mCustomResolverComponentName = ComponentName.unflattenFromString( 1389 customResolverActivity); 1390 } 1391 1392 long startTime = SystemClock.uptimeMillis(); 1393 1394 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1395 startTime); 1396 1397 // Set flag to monitor and not change apk file paths when 1398 // scanning install directories. 1399 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1400 1401 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1402 1403 /** 1404 * Add everything in the in the boot class path to the 1405 * list of process files because dexopt will have been run 1406 * if necessary during zygote startup. 1407 */ 1408 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1409 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1410 1411 if (bootClassPath != null) { 1412 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1413 for (String element : bootClassPathElements) { 1414 alreadyDexOpted.add(element); 1415 } 1416 } else { 1417 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1418 } 1419 1420 if (systemServerClassPath != null) { 1421 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1422 for (String element : systemServerClassPathElements) { 1423 alreadyDexOpted.add(element); 1424 } 1425 } else { 1426 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1427 } 1428 1429 boolean didDexOptLibraryOrTool = false; 1430 1431 final List<String> allInstructionSets = getAllInstructionSets(); 1432 final String[] dexCodeInstructionSets = 1433 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1434 1435 /** 1436 * Ensure all external libraries have had dexopt run on them. 1437 */ 1438 if (mSharedLibraries.size() > 0) { 1439 // NOTE: For now, we're compiling these system "shared libraries" 1440 // (and framework jars) into all available architectures. It's possible 1441 // to compile them only when we come across an app that uses them (there's 1442 // already logic for that in scanPackageLI) but that adds some complexity. 1443 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1444 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1445 final String lib = libEntry.path; 1446 if (lib == null) { 1447 continue; 1448 } 1449 1450 try { 1451 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1452 dexCodeInstructionSet, 1453 false); 1454 if (dexoptRequired != DexFile.UP_TO_DATE) { 1455 alreadyDexOpted.add(lib); 1456 1457 // The list of "shared libraries" we have at this point is 1458 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1459 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1460 } else { 1461 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1462 } 1463 didDexOptLibraryOrTool = true; 1464 } 1465 } catch (FileNotFoundException e) { 1466 Slog.w(TAG, "Library not found: " + lib); 1467 } catch (IOException e) { 1468 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1469 + e.getMessage()); 1470 } 1471 } 1472 } 1473 } 1474 1475 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1476 1477 // Gross hack for now: we know this file doesn't contain any 1478 // code, so don't dexopt it to avoid the resulting log spew. 1479 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1480 1481 // Gross hack for now: we know this file is only part of 1482 // the boot class path for art, so don't dexopt it to 1483 // avoid the resulting log spew. 1484 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1485 1486 /** 1487 * And there are a number of commands implemented in Java, which 1488 * we currently need to do the dexopt on so that they can be 1489 * run from a non-root shell. 1490 */ 1491 String[] frameworkFiles = frameworkDir.list(); 1492 if (frameworkFiles != null) { 1493 // TODO: We could compile these only for the most preferred ABI. We should 1494 // first double check that the dex files for these commands are not referenced 1495 // by other system apps. 1496 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1497 for (int i=0; i<frameworkFiles.length; i++) { 1498 File libPath = new File(frameworkDir, frameworkFiles[i]); 1499 String path = libPath.getPath(); 1500 // Skip the file if we already did it. 1501 if (alreadyDexOpted.contains(path)) { 1502 continue; 1503 } 1504 // Skip the file if it is not a type we want to dexopt. 1505 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1506 continue; 1507 } 1508 try { 1509 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1510 dexCodeInstructionSet, 1511 false); 1512 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1513 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1514 didDexOptLibraryOrTool = true; 1515 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1516 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1517 didDexOptLibraryOrTool = true; 1518 } 1519 } catch (FileNotFoundException e) { 1520 Slog.w(TAG, "Jar not found: " + path); 1521 } catch (IOException e) { 1522 Slog.w(TAG, "Exception reading jar: " + path, e); 1523 } 1524 } 1525 } 1526 } 1527 1528 // Collect vendor overlay packages. 1529 // (Do this before scanning any apps.) 1530 // For security and version matching reason, only consider 1531 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1532 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1533 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1534 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1535 1536 // Find base frameworks (resource packages without code). 1537 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1538 | PackageParser.PARSE_IS_SYSTEM_DIR 1539 | PackageParser.PARSE_IS_PRIVILEGED, 1540 scanFlags | SCAN_NO_DEX, 0); 1541 1542 // Collected privileged system packages. 1543 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1544 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR 1546 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1547 1548 // Collect ordinary system packages. 1549 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1550 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1551 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1552 1553 // Collect all vendor packages. 1554 File vendorAppDir = new File("/vendor/app"); 1555 try { 1556 vendorAppDir = vendorAppDir.getCanonicalFile(); 1557 } catch (IOException e) { 1558 // failed to look up canonical path, continue with original one 1559 } 1560 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1561 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1562 1563 // Collect all OEM packages. 1564 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1565 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1566 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1567 1568 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1569 mInstaller.moveFiles(); 1570 1571 // Prune any system packages that no longer exist. 1572 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1573 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1574 if (!mOnlyCore) { 1575 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1576 while (psit.hasNext()) { 1577 PackageSetting ps = psit.next(); 1578 1579 /* 1580 * If this is not a system app, it can't be a 1581 * disable system app. 1582 */ 1583 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1584 continue; 1585 } 1586 1587 /* 1588 * If the package is scanned, it's not erased. 1589 */ 1590 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1591 if (scannedPkg != null) { 1592 /* 1593 * If the system app is both scanned and in the 1594 * disabled packages list, then it must have been 1595 * added via OTA. Remove it from the currently 1596 * scanned package so the previously user-installed 1597 * application can be scanned. 1598 */ 1599 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1600 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1601 + ps.name + "; removing system app. Last known codePath=" 1602 + ps.codePathString + ", installStatus=" + ps.installStatus 1603 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1604 + scannedPkg.mVersionCode); 1605 removePackageLI(ps, true); 1606 expectingBetter.put(ps.name, ps.codePath); 1607 } 1608 1609 continue; 1610 } 1611 1612 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1613 psit.remove(); 1614 logCriticalInfo(Log.WARN, "System package " + ps.name 1615 + " no longer exists; wiping its data"); 1616 removeDataDirsLI(ps.name); 1617 } else { 1618 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1619 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1620 possiblyDeletedUpdatedSystemApps.add(ps.name); 1621 } 1622 } 1623 } 1624 } 1625 1626 //look for any incomplete package installations 1627 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1628 //clean up list 1629 for(int i = 0; i < deletePkgsList.size(); i++) { 1630 //clean up here 1631 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1632 } 1633 //delete tmp files 1634 deleteTempPackageFiles(); 1635 1636 // Remove any shared userIDs that have no associated packages 1637 mSettings.pruneSharedUsersLPw(); 1638 1639 if (!mOnlyCore) { 1640 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1641 SystemClock.uptimeMillis()); 1642 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1643 1644 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1645 scanFlags, 0); 1646 1647 /** 1648 * Remove disable package settings for any updated system 1649 * apps that were removed via an OTA. If they're not a 1650 * previously-updated app, remove them completely. 1651 * Otherwise, just revoke their system-level permissions. 1652 */ 1653 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1654 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1655 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1656 1657 String msg; 1658 if (deletedPkg == null) { 1659 msg = "Updated system package " + deletedAppName 1660 + " no longer exists; wiping its data"; 1661 removeDataDirsLI(deletedAppName); 1662 } else { 1663 msg = "Updated system app + " + deletedAppName 1664 + " no longer present; removing system privileges for " 1665 + deletedAppName; 1666 1667 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1668 1669 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1670 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1671 } 1672 logCriticalInfo(Log.WARN, msg); 1673 } 1674 1675 /** 1676 * Make sure all system apps that we expected to appear on 1677 * the userdata partition actually showed up. If they never 1678 * appeared, crawl back and revive the system version. 1679 */ 1680 for (int i = 0; i < expectingBetter.size(); i++) { 1681 final String packageName = expectingBetter.keyAt(i); 1682 if (!mPackages.containsKey(packageName)) { 1683 final File scanFile = expectingBetter.valueAt(i); 1684 1685 logCriticalInfo(Log.WARN, "Expected better " + packageName 1686 + " but never showed up; reverting to system"); 1687 1688 final int reparseFlags; 1689 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1690 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1691 | PackageParser.PARSE_IS_SYSTEM_DIR 1692 | PackageParser.PARSE_IS_PRIVILEGED; 1693 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1694 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1695 | PackageParser.PARSE_IS_SYSTEM_DIR; 1696 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1697 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1698 | PackageParser.PARSE_IS_SYSTEM_DIR; 1699 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1700 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1701 | PackageParser.PARSE_IS_SYSTEM_DIR; 1702 } else { 1703 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1704 continue; 1705 } 1706 1707 mSettings.enableSystemPackageLPw(packageName); 1708 1709 try { 1710 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1711 } catch (PackageManagerException e) { 1712 Slog.e(TAG, "Failed to parse original system package: " 1713 + e.getMessage()); 1714 } 1715 } 1716 } 1717 } 1718 1719 // Now that we know all of the shared libraries, update all clients to have 1720 // the correct library paths. 1721 updateAllSharedLibrariesLPw(); 1722 1723 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1724 // NOTE: We ignore potential failures here during a system scan (like 1725 // the rest of the commands above) because there's precious little we 1726 // can do about it. A settings error is reported, though. 1727 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1728 false /* force dexopt */, false /* defer dexopt */); 1729 } 1730 1731 // Now that we know all the packages we are keeping, 1732 // read and update their last usage times. 1733 mPackageUsage.readLP(); 1734 1735 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1736 SystemClock.uptimeMillis()); 1737 Slog.i(TAG, "Time to scan packages: " 1738 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1739 + " seconds"); 1740 1741 // If the platform SDK has changed since the last time we booted, 1742 // we need to re-grant app permission to catch any new ones that 1743 // appear. This is really a hack, and means that apps can in some 1744 // cases get permissions that the user didn't initially explicitly 1745 // allow... it would be nice to have some better way to handle 1746 // this situation. 1747 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1748 != mSdkVersion; 1749 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1750 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1751 + "; regranting permissions for internal storage"); 1752 mSettings.mInternalSdkPlatform = mSdkVersion; 1753 1754 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1755 | (regrantPermissions 1756 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1757 : 0)); 1758 1759 // If this is the first boot, and it is a normal boot, then 1760 // we need to initialize the default preferred apps. 1761 if (!mRestoredSettings && !onlyCore) { 1762 mSettings.readDefaultPreferredAppsLPw(this, 0); 1763 } 1764 1765 // If this is first boot after an OTA, and a normal boot, then 1766 // we need to clear code cache directories. 1767 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1768 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1769 for (String pkgName : mSettings.mPackages.keySet()) { 1770 deleteCodeCacheDirsLI(pkgName); 1771 } 1772 mSettings.mFingerprint = Build.FINGERPRINT; 1773 } 1774 1775 // All the changes are done during package scanning. 1776 mSettings.updateInternalDatabaseVersion(); 1777 1778 // can downgrade to reader 1779 mSettings.writeLPr(); 1780 1781 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1782 SystemClock.uptimeMillis()); 1783 1784 1785 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1786 } // synchronized (mPackages) 1787 } // synchronized (mInstallLock) 1788 1789 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1790 1791 // Now after opening every single application zip, make sure they 1792 // are all flushed. Not really needed, but keeps things nice and 1793 // tidy. 1794 Runtime.getRuntime().gc(); 1795 } 1796 1797 @Override 1798 public boolean isFirstBoot() { 1799 return !mRestoredSettings; 1800 } 1801 1802 @Override 1803 public boolean isOnlyCoreApps() { 1804 return mOnlyCore; 1805 } 1806 1807 private String getRequiredVerifierLPr() { 1808 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1809 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1810 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1811 1812 String requiredVerifier = null; 1813 1814 final int N = receivers.size(); 1815 for (int i = 0; i < N; i++) { 1816 final ResolveInfo info = receivers.get(i); 1817 1818 if (info.activityInfo == null) { 1819 continue; 1820 } 1821 1822 final String packageName = info.activityInfo.packageName; 1823 1824 final PackageSetting ps = mSettings.mPackages.get(packageName); 1825 if (ps == null) { 1826 continue; 1827 } 1828 1829 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1830 if (!gp.grantedPermissions 1831 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1832 continue; 1833 } 1834 1835 if (requiredVerifier != null) { 1836 throw new RuntimeException("There can be only one required verifier"); 1837 } 1838 1839 requiredVerifier = packageName; 1840 } 1841 1842 return requiredVerifier; 1843 } 1844 1845 @Override 1846 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1847 throws RemoteException { 1848 try { 1849 return super.onTransact(code, data, reply, flags); 1850 } catch (RuntimeException e) { 1851 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1852 Slog.wtf(TAG, "Package Manager Crash", e); 1853 } 1854 throw e; 1855 } 1856 } 1857 1858 void cleanupInstallFailedPackage(PackageSetting ps) { 1859 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1860 1861 removeDataDirsLI(ps.name); 1862 if (ps.codePath != null) { 1863 if (ps.codePath.isDirectory()) { 1864 FileUtils.deleteContents(ps.codePath); 1865 } 1866 ps.codePath.delete(); 1867 } 1868 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1869 if (ps.resourcePath.isDirectory()) { 1870 FileUtils.deleteContents(ps.resourcePath); 1871 } 1872 ps.resourcePath.delete(); 1873 } 1874 mSettings.removePackageLPw(ps.name); 1875 } 1876 1877 static int[] appendInts(int[] cur, int[] add) { 1878 if (add == null) return cur; 1879 if (cur == null) return add; 1880 final int N = add.length; 1881 for (int i=0; i<N; i++) { 1882 cur = appendInt(cur, add[i]); 1883 } 1884 return cur; 1885 } 1886 1887 static int[] removeInts(int[] cur, int[] rem) { 1888 if (rem == null) return cur; 1889 if (cur == null) return cur; 1890 final int N = rem.length; 1891 for (int i=0; i<N; i++) { 1892 cur = removeInt(cur, rem[i]); 1893 } 1894 return cur; 1895 } 1896 1897 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1898 if (!sUserManager.exists(userId)) return null; 1899 final PackageSetting ps = (PackageSetting) p.mExtras; 1900 if (ps == null) { 1901 return null; 1902 } 1903 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1904 final PackageUserState state = ps.readUserState(userId); 1905 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1906 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1907 state, userId); 1908 } 1909 1910 @Override 1911 public boolean isPackageAvailable(String packageName, int userId) { 1912 if (!sUserManager.exists(userId)) return false; 1913 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1914 synchronized (mPackages) { 1915 PackageParser.Package p = mPackages.get(packageName); 1916 if (p != null) { 1917 final PackageSetting ps = (PackageSetting) p.mExtras; 1918 if (ps != null) { 1919 final PackageUserState state = ps.readUserState(userId); 1920 if (state != null) { 1921 return PackageParser.isAvailable(state); 1922 } 1923 } 1924 } 1925 } 1926 return false; 1927 } 1928 1929 @Override 1930 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1931 if (!sUserManager.exists(userId)) return null; 1932 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1933 // reader 1934 synchronized (mPackages) { 1935 PackageParser.Package p = mPackages.get(packageName); 1936 if (DEBUG_PACKAGE_INFO) 1937 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1938 if (p != null) { 1939 return generatePackageInfo(p, flags, userId); 1940 } 1941 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1942 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1943 } 1944 } 1945 return null; 1946 } 1947 1948 @Override 1949 public String[] currentToCanonicalPackageNames(String[] names) { 1950 String[] out = new String[names.length]; 1951 // reader 1952 synchronized (mPackages) { 1953 for (int i=names.length-1; i>=0; i--) { 1954 PackageSetting ps = mSettings.mPackages.get(names[i]); 1955 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1956 } 1957 } 1958 return out; 1959 } 1960 1961 @Override 1962 public String[] canonicalToCurrentPackageNames(String[] names) { 1963 String[] out = new String[names.length]; 1964 // reader 1965 synchronized (mPackages) { 1966 for (int i=names.length-1; i>=0; i--) { 1967 String cur = mSettings.mRenamedPackages.get(names[i]); 1968 out[i] = cur != null ? cur : names[i]; 1969 } 1970 } 1971 return out; 1972 } 1973 1974 @Override 1975 public int getPackageUid(String packageName, int userId) { 1976 if (!sUserManager.exists(userId)) return -1; 1977 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1978 // reader 1979 synchronized (mPackages) { 1980 PackageParser.Package p = mPackages.get(packageName); 1981 if(p != null) { 1982 return UserHandle.getUid(userId, p.applicationInfo.uid); 1983 } 1984 PackageSetting ps = mSettings.mPackages.get(packageName); 1985 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1986 return -1; 1987 } 1988 p = ps.pkg; 1989 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1990 } 1991 } 1992 1993 @Override 1994 public int[] getPackageGids(String packageName) { 1995 // reader 1996 synchronized (mPackages) { 1997 PackageParser.Package p = mPackages.get(packageName); 1998 if (DEBUG_PACKAGE_INFO) 1999 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2000 if (p != null) { 2001 final PackageSetting ps = (PackageSetting)p.mExtras; 2002 return ps.getGids(); 2003 } 2004 } 2005 // stupid thing to indicate an error. 2006 return new int[0]; 2007 } 2008 2009 static final PermissionInfo generatePermissionInfo( 2010 BasePermission bp, int flags) { 2011 if (bp.perm != null) { 2012 return PackageParser.generatePermissionInfo(bp.perm, flags); 2013 } 2014 PermissionInfo pi = new PermissionInfo(); 2015 pi.name = bp.name; 2016 pi.packageName = bp.sourcePackage; 2017 pi.nonLocalizedLabel = bp.name; 2018 pi.protectionLevel = bp.protectionLevel; 2019 return pi; 2020 } 2021 2022 @Override 2023 public PermissionInfo getPermissionInfo(String name, int flags) { 2024 // reader 2025 synchronized (mPackages) { 2026 final BasePermission p = mSettings.mPermissions.get(name); 2027 if (p != null) { 2028 return generatePermissionInfo(p, flags); 2029 } 2030 return null; 2031 } 2032 } 2033 2034 @Override 2035 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2036 // reader 2037 synchronized (mPackages) { 2038 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2039 for (BasePermission p : mSettings.mPermissions.values()) { 2040 if (group == null) { 2041 if (p.perm == null || p.perm.info.group == null) { 2042 out.add(generatePermissionInfo(p, flags)); 2043 } 2044 } else { 2045 if (p.perm != null && group.equals(p.perm.info.group)) { 2046 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2047 } 2048 } 2049 } 2050 2051 if (out.size() > 0) { 2052 return out; 2053 } 2054 return mPermissionGroups.containsKey(group) ? out : null; 2055 } 2056 } 2057 2058 @Override 2059 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2060 // reader 2061 synchronized (mPackages) { 2062 return PackageParser.generatePermissionGroupInfo( 2063 mPermissionGroups.get(name), flags); 2064 } 2065 } 2066 2067 @Override 2068 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2069 // reader 2070 synchronized (mPackages) { 2071 final int N = mPermissionGroups.size(); 2072 ArrayList<PermissionGroupInfo> out 2073 = new ArrayList<PermissionGroupInfo>(N); 2074 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2075 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2076 } 2077 return out; 2078 } 2079 } 2080 2081 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2082 int userId) { 2083 if (!sUserManager.exists(userId)) return null; 2084 PackageSetting ps = mSettings.mPackages.get(packageName); 2085 if (ps != null) { 2086 if (ps.pkg == null) { 2087 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2088 flags, userId); 2089 if (pInfo != null) { 2090 return pInfo.applicationInfo; 2091 } 2092 return null; 2093 } 2094 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2095 ps.readUserState(userId), userId); 2096 } 2097 return null; 2098 } 2099 2100 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2101 int userId) { 2102 if (!sUserManager.exists(userId)) return null; 2103 PackageSetting ps = mSettings.mPackages.get(packageName); 2104 if (ps != null) { 2105 PackageParser.Package pkg = ps.pkg; 2106 if (pkg == null) { 2107 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2108 return null; 2109 } 2110 // Only data remains, so we aren't worried about code paths 2111 pkg = new PackageParser.Package(packageName); 2112 pkg.applicationInfo.packageName = packageName; 2113 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2114 pkg.applicationInfo.dataDir = 2115 getDataPathForPackage(packageName, 0).getPath(); 2116 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2117 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2118 } 2119 return generatePackageInfo(pkg, flags, userId); 2120 } 2121 return null; 2122 } 2123 2124 @Override 2125 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2126 if (!sUserManager.exists(userId)) return null; 2127 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2128 // writer 2129 synchronized (mPackages) { 2130 PackageParser.Package p = mPackages.get(packageName); 2131 if (DEBUG_PACKAGE_INFO) Log.v( 2132 TAG, "getApplicationInfo " + packageName 2133 + ": " + p); 2134 if (p != null) { 2135 PackageSetting ps = mSettings.mPackages.get(packageName); 2136 if (ps == null) return null; 2137 // Note: isEnabledLP() does not apply here - always return info 2138 return PackageParser.generateApplicationInfo( 2139 p, flags, ps.readUserState(userId), userId); 2140 } 2141 if ("android".equals(packageName)||"system".equals(packageName)) { 2142 return mAndroidApplication; 2143 } 2144 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2145 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2146 } 2147 } 2148 return null; 2149 } 2150 2151 2152 @Override 2153 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2154 mContext.enforceCallingOrSelfPermission( 2155 android.Manifest.permission.CLEAR_APP_CACHE, null); 2156 // Queue up an async operation since clearing cache may take a little while. 2157 mHandler.post(new Runnable() { 2158 public void run() { 2159 mHandler.removeCallbacks(this); 2160 int retCode = -1; 2161 synchronized (mInstallLock) { 2162 retCode = mInstaller.freeCache(freeStorageSize); 2163 if (retCode < 0) { 2164 Slog.w(TAG, "Couldn't clear application caches"); 2165 } 2166 } 2167 if (observer != null) { 2168 try { 2169 observer.onRemoveCompleted(null, (retCode >= 0)); 2170 } catch (RemoteException e) { 2171 Slog.w(TAG, "RemoveException when invoking call back"); 2172 } 2173 } 2174 } 2175 }); 2176 } 2177 2178 @Override 2179 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2180 mContext.enforceCallingOrSelfPermission( 2181 android.Manifest.permission.CLEAR_APP_CACHE, null); 2182 // Queue up an async operation since clearing cache may take a little while. 2183 mHandler.post(new Runnable() { 2184 public void run() { 2185 mHandler.removeCallbacks(this); 2186 int retCode = -1; 2187 synchronized (mInstallLock) { 2188 retCode = mInstaller.freeCache(freeStorageSize); 2189 if (retCode < 0) { 2190 Slog.w(TAG, "Couldn't clear application caches"); 2191 } 2192 } 2193 if(pi != null) { 2194 try { 2195 // Callback via pending intent 2196 int code = (retCode >= 0) ? 1 : 0; 2197 pi.sendIntent(null, code, null, 2198 null, null); 2199 } catch (SendIntentException e1) { 2200 Slog.i(TAG, "Failed to send pending intent"); 2201 } 2202 } 2203 } 2204 }); 2205 } 2206 2207 void freeStorage(long freeStorageSize) throws IOException { 2208 synchronized (mInstallLock) { 2209 if (mInstaller.freeCache(freeStorageSize) < 0) { 2210 throw new IOException("Failed to free enough space"); 2211 } 2212 } 2213 } 2214 2215 @Override 2216 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2217 if (!sUserManager.exists(userId)) return null; 2218 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2219 synchronized (mPackages) { 2220 PackageParser.Activity a = mActivities.mActivities.get(component); 2221 2222 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2223 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2224 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2225 if (ps == null) return null; 2226 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2227 userId); 2228 } 2229 if (mResolveComponentName.equals(component)) { 2230 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2231 new PackageUserState(), userId); 2232 } 2233 } 2234 return null; 2235 } 2236 2237 @Override 2238 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2239 String resolvedType) { 2240 synchronized (mPackages) { 2241 PackageParser.Activity a = mActivities.mActivities.get(component); 2242 if (a == null) { 2243 return false; 2244 } 2245 for (int i=0; i<a.intents.size(); i++) { 2246 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2247 intent.getData(), intent.getCategories(), TAG) >= 0) { 2248 return true; 2249 } 2250 } 2251 return false; 2252 } 2253 } 2254 2255 @Override 2256 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2257 if (!sUserManager.exists(userId)) return null; 2258 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2259 synchronized (mPackages) { 2260 PackageParser.Activity a = mReceivers.mActivities.get(component); 2261 if (DEBUG_PACKAGE_INFO) Log.v( 2262 TAG, "getReceiverInfo " + component + ": " + a); 2263 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2264 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2265 if (ps == null) return null; 2266 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2267 userId); 2268 } 2269 } 2270 return null; 2271 } 2272 2273 @Override 2274 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2275 if (!sUserManager.exists(userId)) return null; 2276 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2277 synchronized (mPackages) { 2278 PackageParser.Service s = mServices.mServices.get(component); 2279 if (DEBUG_PACKAGE_INFO) Log.v( 2280 TAG, "getServiceInfo " + component + ": " + s); 2281 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2282 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2283 if (ps == null) return null; 2284 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2285 userId); 2286 } 2287 } 2288 return null; 2289 } 2290 2291 @Override 2292 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2293 if (!sUserManager.exists(userId)) return null; 2294 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2295 synchronized (mPackages) { 2296 PackageParser.Provider p = mProviders.mProviders.get(component); 2297 if (DEBUG_PACKAGE_INFO) Log.v( 2298 TAG, "getProviderInfo " + component + ": " + p); 2299 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2300 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2301 if (ps == null) return null; 2302 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2303 userId); 2304 } 2305 } 2306 return null; 2307 } 2308 2309 @Override 2310 public String[] getSystemSharedLibraryNames() { 2311 Set<String> libSet; 2312 synchronized (mPackages) { 2313 libSet = mSharedLibraries.keySet(); 2314 int size = libSet.size(); 2315 if (size > 0) { 2316 String[] libs = new String[size]; 2317 libSet.toArray(libs); 2318 return libs; 2319 } 2320 } 2321 return null; 2322 } 2323 2324 @Override 2325 public FeatureInfo[] getSystemAvailableFeatures() { 2326 Collection<FeatureInfo> featSet; 2327 synchronized (mPackages) { 2328 featSet = mAvailableFeatures.values(); 2329 int size = featSet.size(); 2330 if (size > 0) { 2331 FeatureInfo[] features = new FeatureInfo[size+1]; 2332 featSet.toArray(features); 2333 FeatureInfo fi = new FeatureInfo(); 2334 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2335 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2336 features[size] = fi; 2337 return features; 2338 } 2339 } 2340 return null; 2341 } 2342 2343 @Override 2344 public boolean hasSystemFeature(String name) { 2345 synchronized (mPackages) { 2346 return mAvailableFeatures.containsKey(name); 2347 } 2348 } 2349 2350 private void checkValidCaller(int uid, int userId) { 2351 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2352 return; 2353 2354 throw new SecurityException("Caller uid=" + uid 2355 + " is not privileged to communicate with user=" + userId); 2356 } 2357 2358 @Override 2359 public int checkPermission(String permName, String pkgName) { 2360 synchronized (mPackages) { 2361 PackageParser.Package p = mPackages.get(pkgName); 2362 if (p != null && p.mExtras != null) { 2363 PackageSetting ps = (PackageSetting)p.mExtras; 2364 if (ps.sharedUser != null) { 2365 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2366 return PackageManager.PERMISSION_GRANTED; 2367 } 2368 } else if (ps.grantedPermissions.contains(permName)) { 2369 return PackageManager.PERMISSION_GRANTED; 2370 } 2371 } 2372 } 2373 return PackageManager.PERMISSION_DENIED; 2374 } 2375 2376 @Override 2377 public int checkUidPermission(String permName, int uid) { 2378 synchronized (mPackages) { 2379 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2380 if (obj != null) { 2381 GrantedPermissions gp = (GrantedPermissions)obj; 2382 if (gp.grantedPermissions.contains(permName)) { 2383 return PackageManager.PERMISSION_GRANTED; 2384 } 2385 } else { 2386 HashSet<String> perms = mSystemPermissions.get(uid); 2387 if (perms != null && perms.contains(permName)) { 2388 return PackageManager.PERMISSION_GRANTED; 2389 } 2390 } 2391 } 2392 return PackageManager.PERMISSION_DENIED; 2393 } 2394 2395 /** 2396 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2397 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2398 * @param checkShell TODO(yamasani): 2399 * @param message the message to log on security exception 2400 */ 2401 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2402 boolean checkShell, String message) { 2403 if (userId < 0) { 2404 throw new IllegalArgumentException("Invalid userId " + userId); 2405 } 2406 if (checkShell) { 2407 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2408 } 2409 if (userId == UserHandle.getUserId(callingUid)) return; 2410 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2411 if (requireFullPermission) { 2412 mContext.enforceCallingOrSelfPermission( 2413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2414 } else { 2415 try { 2416 mContext.enforceCallingOrSelfPermission( 2417 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2418 } catch (SecurityException se) { 2419 mContext.enforceCallingOrSelfPermission( 2420 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2421 } 2422 } 2423 } 2424 } 2425 2426 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2427 if (callingUid == Process.SHELL_UID) { 2428 if (userHandle >= 0 2429 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2430 throw new SecurityException("Shell does not have permission to access user " 2431 + userHandle); 2432 } else if (userHandle < 0) { 2433 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2434 + Debug.getCallers(3)); 2435 } 2436 } 2437 } 2438 2439 private BasePermission findPermissionTreeLP(String permName) { 2440 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2441 if (permName.startsWith(bp.name) && 2442 permName.length() > bp.name.length() && 2443 permName.charAt(bp.name.length()) == '.') { 2444 return bp; 2445 } 2446 } 2447 return null; 2448 } 2449 2450 private BasePermission checkPermissionTreeLP(String permName) { 2451 if (permName != null) { 2452 BasePermission bp = findPermissionTreeLP(permName); 2453 if (bp != null) { 2454 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2455 return bp; 2456 } 2457 throw new SecurityException("Calling uid " 2458 + Binder.getCallingUid() 2459 + " is not allowed to add to permission tree " 2460 + bp.name + " owned by uid " + bp.uid); 2461 } 2462 } 2463 throw new SecurityException("No permission tree found for " + permName); 2464 } 2465 2466 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2467 if (s1 == null) { 2468 return s2 == null; 2469 } 2470 if (s2 == null) { 2471 return false; 2472 } 2473 if (s1.getClass() != s2.getClass()) { 2474 return false; 2475 } 2476 return s1.equals(s2); 2477 } 2478 2479 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2480 if (pi1.icon != pi2.icon) return false; 2481 if (pi1.logo != pi2.logo) return false; 2482 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2483 if (!compareStrings(pi1.name, pi2.name)) return false; 2484 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2485 // We'll take care of setting this one. 2486 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2487 // These are not currently stored in settings. 2488 //if (!compareStrings(pi1.group, pi2.group)) return false; 2489 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2490 //if (pi1.labelRes != pi2.labelRes) return false; 2491 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2492 return true; 2493 } 2494 2495 int permissionInfoFootprint(PermissionInfo info) { 2496 int size = info.name.length(); 2497 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2498 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2499 return size; 2500 } 2501 2502 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2503 int size = 0; 2504 for (BasePermission perm : mSettings.mPermissions.values()) { 2505 if (perm.uid == tree.uid) { 2506 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2507 } 2508 } 2509 return size; 2510 } 2511 2512 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2513 // We calculate the max size of permissions defined by this uid and throw 2514 // if that plus the size of 'info' would exceed our stated maximum. 2515 if (tree.uid != Process.SYSTEM_UID) { 2516 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2517 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2518 throw new SecurityException("Permission tree size cap exceeded"); 2519 } 2520 } 2521 } 2522 2523 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2524 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2525 throw new SecurityException("Label must be specified in permission"); 2526 } 2527 BasePermission tree = checkPermissionTreeLP(info.name); 2528 BasePermission bp = mSettings.mPermissions.get(info.name); 2529 boolean added = bp == null; 2530 boolean changed = true; 2531 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2532 if (added) { 2533 enforcePermissionCapLocked(info, tree); 2534 bp = new BasePermission(info.name, tree.sourcePackage, 2535 BasePermission.TYPE_DYNAMIC); 2536 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2537 throw new SecurityException( 2538 "Not allowed to modify non-dynamic permission " 2539 + info.name); 2540 } else { 2541 if (bp.protectionLevel == fixedLevel 2542 && bp.perm.owner.equals(tree.perm.owner) 2543 && bp.uid == tree.uid 2544 && comparePermissionInfos(bp.perm.info, info)) { 2545 changed = false; 2546 } 2547 } 2548 bp.protectionLevel = fixedLevel; 2549 info = new PermissionInfo(info); 2550 info.protectionLevel = fixedLevel; 2551 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2552 bp.perm.info.packageName = tree.perm.info.packageName; 2553 bp.uid = tree.uid; 2554 if (added) { 2555 mSettings.mPermissions.put(info.name, bp); 2556 } 2557 if (changed) { 2558 if (!async) { 2559 mSettings.writeLPr(); 2560 } else { 2561 scheduleWriteSettingsLocked(); 2562 } 2563 } 2564 return added; 2565 } 2566 2567 @Override 2568 public boolean addPermission(PermissionInfo info) { 2569 synchronized (mPackages) { 2570 return addPermissionLocked(info, false); 2571 } 2572 } 2573 2574 @Override 2575 public boolean addPermissionAsync(PermissionInfo info) { 2576 synchronized (mPackages) { 2577 return addPermissionLocked(info, true); 2578 } 2579 } 2580 2581 @Override 2582 public void removePermission(String name) { 2583 synchronized (mPackages) { 2584 checkPermissionTreeLP(name); 2585 BasePermission bp = mSettings.mPermissions.get(name); 2586 if (bp != null) { 2587 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2588 throw new SecurityException( 2589 "Not allowed to modify non-dynamic permission " 2590 + name); 2591 } 2592 mSettings.mPermissions.remove(name); 2593 mSettings.writeLPr(); 2594 } 2595 } 2596 } 2597 2598 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2599 int index = pkg.requestedPermissions.indexOf(bp.name); 2600 if (index == -1) { 2601 throw new SecurityException("Package " + pkg.packageName 2602 + " has not requested permission " + bp.name); 2603 } 2604 boolean isNormal = 2605 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2606 == PermissionInfo.PROTECTION_NORMAL); 2607 boolean isDangerous = 2608 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2609 == PermissionInfo.PROTECTION_DANGEROUS); 2610 boolean isDevelopment = 2611 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2612 2613 if (!isNormal && !isDangerous && !isDevelopment) { 2614 throw new SecurityException("Permission " + bp.name 2615 + " is not a changeable permission type"); 2616 } 2617 2618 if (isNormal || isDangerous) { 2619 if (pkg.requestedPermissionsRequired.get(index)) { 2620 throw new SecurityException("Can't change " + bp.name 2621 + ". It is required by the application"); 2622 } 2623 } 2624 } 2625 2626 @Override 2627 public void grantPermission(String packageName, String permissionName) { 2628 mContext.enforceCallingOrSelfPermission( 2629 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2630 synchronized (mPackages) { 2631 final PackageParser.Package pkg = mPackages.get(packageName); 2632 if (pkg == null) { 2633 throw new IllegalArgumentException("Unknown package: " + packageName); 2634 } 2635 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2636 if (bp == null) { 2637 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2638 } 2639 2640 checkGrantRevokePermissions(pkg, bp); 2641 2642 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2643 if (ps == null) { 2644 return; 2645 } 2646 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2647 if (gp.grantedPermissions.add(permissionName)) { 2648 if (ps.haveGids) { 2649 gp.gids = appendInts(gp.gids, bp.gids); 2650 } 2651 mSettings.writeLPr(); 2652 } 2653 } 2654 } 2655 2656 @Override 2657 public void revokePermission(String packageName, String permissionName) { 2658 int changedAppId = -1; 2659 2660 synchronized (mPackages) { 2661 final PackageParser.Package pkg = mPackages.get(packageName); 2662 if (pkg == null) { 2663 throw new IllegalArgumentException("Unknown package: " + packageName); 2664 } 2665 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2666 mContext.enforceCallingOrSelfPermission( 2667 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2668 } 2669 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2670 if (bp == null) { 2671 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2672 } 2673 2674 checkGrantRevokePermissions(pkg, bp); 2675 2676 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2677 if (ps == null) { 2678 return; 2679 } 2680 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2681 if (gp.grantedPermissions.remove(permissionName)) { 2682 gp.grantedPermissions.remove(permissionName); 2683 if (ps.haveGids) { 2684 gp.gids = removeInts(gp.gids, bp.gids); 2685 } 2686 mSettings.writeLPr(); 2687 changedAppId = ps.appId; 2688 } 2689 } 2690 2691 if (changedAppId >= 0) { 2692 // We changed the perm on someone, kill its processes. 2693 IActivityManager am = ActivityManagerNative.getDefault(); 2694 if (am != null) { 2695 final int callingUserId = UserHandle.getCallingUserId(); 2696 final long ident = Binder.clearCallingIdentity(); 2697 try { 2698 //XXX we should only revoke for the calling user's app permissions, 2699 // but for now we impact all users. 2700 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2701 // "revoke " + permissionName); 2702 int[] users = sUserManager.getUserIds(); 2703 for (int user : users) { 2704 am.killUid(UserHandle.getUid(user, changedAppId), 2705 "revoke " + permissionName); 2706 } 2707 } catch (RemoteException e) { 2708 } finally { 2709 Binder.restoreCallingIdentity(ident); 2710 } 2711 } 2712 } 2713 } 2714 2715 @Override 2716 public boolean isProtectedBroadcast(String actionName) { 2717 synchronized (mPackages) { 2718 return mProtectedBroadcasts.contains(actionName); 2719 } 2720 } 2721 2722 @Override 2723 public int checkSignatures(String pkg1, String pkg2) { 2724 synchronized (mPackages) { 2725 final PackageParser.Package p1 = mPackages.get(pkg1); 2726 final PackageParser.Package p2 = mPackages.get(pkg2); 2727 if (p1 == null || p1.mExtras == null 2728 || p2 == null || p2.mExtras == null) { 2729 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2730 } 2731 return compareSignatures(p1.mSignatures, p2.mSignatures); 2732 } 2733 } 2734 2735 @Override 2736 public int checkUidSignatures(int uid1, int uid2) { 2737 // Map to base uids. 2738 uid1 = UserHandle.getAppId(uid1); 2739 uid2 = UserHandle.getAppId(uid2); 2740 // reader 2741 synchronized (mPackages) { 2742 Signature[] s1; 2743 Signature[] s2; 2744 Object obj = mSettings.getUserIdLPr(uid1); 2745 if (obj != null) { 2746 if (obj instanceof SharedUserSetting) { 2747 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2748 } else if (obj instanceof PackageSetting) { 2749 s1 = ((PackageSetting)obj).signatures.mSignatures; 2750 } else { 2751 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2752 } 2753 } else { 2754 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2755 } 2756 obj = mSettings.getUserIdLPr(uid2); 2757 if (obj != null) { 2758 if (obj instanceof SharedUserSetting) { 2759 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2760 } else if (obj instanceof PackageSetting) { 2761 s2 = ((PackageSetting)obj).signatures.mSignatures; 2762 } else { 2763 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2764 } 2765 } else { 2766 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2767 } 2768 return compareSignatures(s1, s2); 2769 } 2770 } 2771 2772 /** 2773 * Compares two sets of signatures. Returns: 2774 * <br /> 2775 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2776 * <br /> 2777 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2778 * <br /> 2779 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2780 * <br /> 2781 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2782 * <br /> 2783 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2784 */ 2785 static int compareSignatures(Signature[] s1, Signature[] s2) { 2786 if (s1 == null) { 2787 return s2 == null 2788 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2789 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2790 } 2791 2792 if (s2 == null) { 2793 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2794 } 2795 2796 if (s1.length != s2.length) { 2797 return PackageManager.SIGNATURE_NO_MATCH; 2798 } 2799 2800 // Since both signature sets are of size 1, we can compare without HashSets. 2801 if (s1.length == 1) { 2802 return s1[0].equals(s2[0]) ? 2803 PackageManager.SIGNATURE_MATCH : 2804 PackageManager.SIGNATURE_NO_MATCH; 2805 } 2806 2807 HashSet<Signature> set1 = new HashSet<Signature>(); 2808 for (Signature sig : s1) { 2809 set1.add(sig); 2810 } 2811 HashSet<Signature> set2 = new HashSet<Signature>(); 2812 for (Signature sig : s2) { 2813 set2.add(sig); 2814 } 2815 // Make sure s2 contains all signatures in s1. 2816 if (set1.equals(set2)) { 2817 return PackageManager.SIGNATURE_MATCH; 2818 } 2819 return PackageManager.SIGNATURE_NO_MATCH; 2820 } 2821 2822 /** 2823 * If the database version for this type of package (internal storage or 2824 * external storage) is less than the version where package signatures 2825 * were updated, return true. 2826 */ 2827 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2828 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2829 DatabaseVersion.SIGNATURE_END_ENTITY)) 2830 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2831 DatabaseVersion.SIGNATURE_END_ENTITY)); 2832 } 2833 2834 /** 2835 * Used for backward compatibility to make sure any packages with 2836 * certificate chains get upgraded to the new style. {@code existingSigs} 2837 * will be in the old format (since they were stored on disk from before the 2838 * system upgrade) and {@code scannedSigs} will be in the newer format. 2839 */ 2840 private int compareSignaturesCompat(PackageSignatures existingSigs, 2841 PackageParser.Package scannedPkg) { 2842 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2843 return PackageManager.SIGNATURE_NO_MATCH; 2844 } 2845 2846 HashSet<Signature> existingSet = new HashSet<Signature>(); 2847 for (Signature sig : existingSigs.mSignatures) { 2848 existingSet.add(sig); 2849 } 2850 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2851 for (Signature sig : scannedPkg.mSignatures) { 2852 try { 2853 Signature[] chainSignatures = sig.getChainSignatures(); 2854 for (Signature chainSig : chainSignatures) { 2855 scannedCompatSet.add(chainSig); 2856 } 2857 } catch (CertificateEncodingException e) { 2858 scannedCompatSet.add(sig); 2859 } 2860 } 2861 /* 2862 * Make sure the expanded scanned set contains all signatures in the 2863 * existing one. 2864 */ 2865 if (scannedCompatSet.equals(existingSet)) { 2866 // Migrate the old signatures to the new scheme. 2867 existingSigs.assignSignatures(scannedPkg.mSignatures); 2868 // The new KeySets will be re-added later in the scanning process. 2869 synchronized (mPackages) { 2870 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2871 } 2872 return PackageManager.SIGNATURE_MATCH; 2873 } 2874 return PackageManager.SIGNATURE_NO_MATCH; 2875 } 2876 2877 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2878 if (isExternal(scannedPkg)) { 2879 return mSettings.isExternalDatabaseVersionOlderThan( 2880 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2881 } else { 2882 return mSettings.isInternalDatabaseVersionOlderThan( 2883 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2884 } 2885 } 2886 2887 private int compareSignaturesRecover(PackageSignatures existingSigs, 2888 PackageParser.Package scannedPkg) { 2889 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2890 return PackageManager.SIGNATURE_NO_MATCH; 2891 } 2892 2893 String msg = null; 2894 try { 2895 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2896 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2897 + scannedPkg.packageName); 2898 return PackageManager.SIGNATURE_MATCH; 2899 } 2900 } catch (CertificateException e) { 2901 msg = e.getMessage(); 2902 } 2903 2904 logCriticalInfo(Log.INFO, 2905 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2906 return PackageManager.SIGNATURE_NO_MATCH; 2907 } 2908 2909 @Override 2910 public String[] getPackagesForUid(int uid) { 2911 uid = UserHandle.getAppId(uid); 2912 // reader 2913 synchronized (mPackages) { 2914 Object obj = mSettings.getUserIdLPr(uid); 2915 if (obj instanceof SharedUserSetting) { 2916 final SharedUserSetting sus = (SharedUserSetting) obj; 2917 final int N = sus.packages.size(); 2918 final String[] res = new String[N]; 2919 final Iterator<PackageSetting> it = sus.packages.iterator(); 2920 int i = 0; 2921 while (it.hasNext()) { 2922 res[i++] = it.next().name; 2923 } 2924 return res; 2925 } else if (obj instanceof PackageSetting) { 2926 final PackageSetting ps = (PackageSetting) obj; 2927 return new String[] { ps.name }; 2928 } 2929 } 2930 return null; 2931 } 2932 2933 @Override 2934 public String getNameForUid(int uid) { 2935 // reader 2936 synchronized (mPackages) { 2937 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2938 if (obj instanceof SharedUserSetting) { 2939 final SharedUserSetting sus = (SharedUserSetting) obj; 2940 return sus.name + ":" + sus.userId; 2941 } else if (obj instanceof PackageSetting) { 2942 final PackageSetting ps = (PackageSetting) obj; 2943 return ps.name; 2944 } 2945 } 2946 return null; 2947 } 2948 2949 @Override 2950 public int getUidForSharedUser(String sharedUserName) { 2951 if(sharedUserName == null) { 2952 return -1; 2953 } 2954 // reader 2955 synchronized (mPackages) { 2956 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2957 if (suid == null) { 2958 return -1; 2959 } 2960 return suid.userId; 2961 } 2962 } 2963 2964 @Override 2965 public int getFlagsForUid(int uid) { 2966 synchronized (mPackages) { 2967 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2968 if (obj instanceof SharedUserSetting) { 2969 final SharedUserSetting sus = (SharedUserSetting) obj; 2970 return sus.pkgFlags; 2971 } else if (obj instanceof PackageSetting) { 2972 final PackageSetting ps = (PackageSetting) obj; 2973 return ps.pkgFlags; 2974 } 2975 } 2976 return 0; 2977 } 2978 2979 @Override 2980 public boolean isUidPrivileged(int uid) { 2981 uid = UserHandle.getAppId(uid); 2982 // reader 2983 synchronized (mPackages) { 2984 Object obj = mSettings.getUserIdLPr(uid); 2985 if (obj instanceof SharedUserSetting) { 2986 final SharedUserSetting sus = (SharedUserSetting) obj; 2987 final Iterator<PackageSetting> it = sus.packages.iterator(); 2988 while (it.hasNext()) { 2989 if (it.next().isPrivileged()) { 2990 return true; 2991 } 2992 } 2993 } else if (obj instanceof PackageSetting) { 2994 final PackageSetting ps = (PackageSetting) obj; 2995 return ps.isPrivileged(); 2996 } 2997 } 2998 return false; 2999 } 3000 3001 @Override 3002 public String[] getAppOpPermissionPackages(String permissionName) { 3003 synchronized (mPackages) { 3004 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3005 if (pkgs == null) { 3006 return null; 3007 } 3008 return pkgs.toArray(new String[pkgs.size()]); 3009 } 3010 } 3011 3012 @Override 3013 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3014 int flags, int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3017 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3018 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3019 } 3020 3021 @Override 3022 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3023 IntentFilter filter, int match, ComponentName activity) { 3024 final int userId = UserHandle.getCallingUserId(); 3025 if (DEBUG_PREFERRED) { 3026 Log.v(TAG, "setLastChosenActivity intent=" + intent 3027 + " resolvedType=" + resolvedType 3028 + " flags=" + flags 3029 + " filter=" + filter 3030 + " match=" + match 3031 + " activity=" + activity); 3032 filter.dump(new PrintStreamPrinter(System.out), " "); 3033 } 3034 intent.setComponent(null); 3035 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3036 // Find any earlier preferred or last chosen entries and nuke them 3037 findPreferredActivity(intent, resolvedType, 3038 flags, query, 0, false, true, false, userId); 3039 // Add the new activity as the last chosen for this filter 3040 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3041 "Setting last chosen"); 3042 } 3043 3044 @Override 3045 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3046 final int userId = UserHandle.getCallingUserId(); 3047 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3048 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3049 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3050 false, false, false, userId); 3051 } 3052 3053 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3054 int flags, List<ResolveInfo> query, int userId) { 3055 if (query != null) { 3056 final int N = query.size(); 3057 if (N == 1) { 3058 return query.get(0); 3059 } else if (N > 1) { 3060 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3061 // If there is more than one activity with the same priority, 3062 // then let the user decide between them. 3063 ResolveInfo r0 = query.get(0); 3064 ResolveInfo r1 = query.get(1); 3065 if (DEBUG_INTENT_MATCHING || debug) { 3066 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3067 + r1.activityInfo.name + "=" + r1.priority); 3068 } 3069 // If the first activity has a higher priority, or a different 3070 // default, then it is always desireable to pick it. 3071 if (r0.priority != r1.priority 3072 || r0.preferredOrder != r1.preferredOrder 3073 || r0.isDefault != r1.isDefault) { 3074 return query.get(0); 3075 } 3076 // If we have saved a preference for a preferred activity for 3077 // this Intent, use that. 3078 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3079 flags, query, r0.priority, true, false, debug, userId); 3080 if (ri != null) { 3081 return ri; 3082 } 3083 if (userId != 0) { 3084 ri = new ResolveInfo(mResolveInfo); 3085 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3086 ri.activityInfo.applicationInfo = new ApplicationInfo( 3087 ri.activityInfo.applicationInfo); 3088 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3089 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3090 return ri; 3091 } 3092 return mResolveInfo; 3093 } 3094 } 3095 return null; 3096 } 3097 3098 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3099 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3100 final int N = query.size(); 3101 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3102 .get(userId); 3103 // Get the list of persistent preferred activities that handle the intent 3104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3105 List<PersistentPreferredActivity> pprefs = ppir != null 3106 ? ppir.queryIntent(intent, resolvedType, 3107 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3108 : null; 3109 if (pprefs != null && pprefs.size() > 0) { 3110 final int M = pprefs.size(); 3111 for (int i=0; i<M; i++) { 3112 final PersistentPreferredActivity ppa = pprefs.get(i); 3113 if (DEBUG_PREFERRED || debug) { 3114 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3115 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3116 + "\n component=" + ppa.mComponent); 3117 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3118 } 3119 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3120 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3121 if (DEBUG_PREFERRED || debug) { 3122 Slog.v(TAG, "Found persistent preferred activity:"); 3123 if (ai != null) { 3124 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3125 } else { 3126 Slog.v(TAG, " null"); 3127 } 3128 } 3129 if (ai == null) { 3130 // This previously registered persistent preferred activity 3131 // component is no longer known. Ignore it and do NOT remove it. 3132 continue; 3133 } 3134 for (int j=0; j<N; j++) { 3135 final ResolveInfo ri = query.get(j); 3136 if (!ri.activityInfo.applicationInfo.packageName 3137 .equals(ai.applicationInfo.packageName)) { 3138 continue; 3139 } 3140 if (!ri.activityInfo.name.equals(ai.name)) { 3141 continue; 3142 } 3143 // Found a persistent preference that can handle the intent. 3144 if (DEBUG_PREFERRED || debug) { 3145 Slog.v(TAG, "Returning persistent preferred activity: " + 3146 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3147 } 3148 return ri; 3149 } 3150 } 3151 } 3152 return null; 3153 } 3154 3155 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3156 List<ResolveInfo> query, int priority, boolean always, 3157 boolean removeMatches, boolean debug, int userId) { 3158 if (!sUserManager.exists(userId)) return null; 3159 // writer 3160 synchronized (mPackages) { 3161 if (intent.getSelector() != null) { 3162 intent = intent.getSelector(); 3163 } 3164 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3165 3166 // Try to find a matching persistent preferred activity. 3167 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3168 debug, userId); 3169 3170 // If a persistent preferred activity matched, use it. 3171 if (pri != null) { 3172 return pri; 3173 } 3174 3175 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3176 // Get the list of preferred activities that handle the intent 3177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3178 List<PreferredActivity> prefs = pir != null 3179 ? pir.queryIntent(intent, resolvedType, 3180 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3181 : null; 3182 if (prefs != null && prefs.size() > 0) { 3183 boolean changed = false; 3184 try { 3185 // First figure out how good the original match set is. 3186 // We will only allow preferred activities that came 3187 // from the same match quality. 3188 int match = 0; 3189 3190 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3191 3192 final int N = query.size(); 3193 for (int j=0; j<N; j++) { 3194 final ResolveInfo ri = query.get(j); 3195 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3196 + ": 0x" + Integer.toHexString(match)); 3197 if (ri.match > match) { 3198 match = ri.match; 3199 } 3200 } 3201 3202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3203 + Integer.toHexString(match)); 3204 3205 match &= IntentFilter.MATCH_CATEGORY_MASK; 3206 final int M = prefs.size(); 3207 for (int i=0; i<M; i++) { 3208 final PreferredActivity pa = prefs.get(i); 3209 if (DEBUG_PREFERRED || debug) { 3210 Slog.v(TAG, "Checking PreferredActivity ds=" 3211 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3212 + "\n component=" + pa.mPref.mComponent); 3213 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3214 } 3215 if (pa.mPref.mMatch != match) { 3216 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3217 + Integer.toHexString(pa.mPref.mMatch)); 3218 continue; 3219 } 3220 // If it's not an "always" type preferred activity and that's what we're 3221 // looking for, skip it. 3222 if (always && !pa.mPref.mAlways) { 3223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3224 continue; 3225 } 3226 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3227 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3228 if (DEBUG_PREFERRED || debug) { 3229 Slog.v(TAG, "Found preferred activity:"); 3230 if (ai != null) { 3231 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3232 } else { 3233 Slog.v(TAG, " null"); 3234 } 3235 } 3236 if (ai == null) { 3237 // This previously registered preferred activity 3238 // component is no longer known. Most likely an update 3239 // to the app was installed and in the new version this 3240 // component no longer exists. Clean it up by removing 3241 // it from the preferred activities list, and skip it. 3242 Slog.w(TAG, "Removing dangling preferred activity: " 3243 + pa.mPref.mComponent); 3244 pir.removeFilter(pa); 3245 changed = true; 3246 continue; 3247 } 3248 for (int j=0; j<N; j++) { 3249 final ResolveInfo ri = query.get(j); 3250 if (!ri.activityInfo.applicationInfo.packageName 3251 .equals(ai.applicationInfo.packageName)) { 3252 continue; 3253 } 3254 if (!ri.activityInfo.name.equals(ai.name)) { 3255 continue; 3256 } 3257 3258 if (removeMatches) { 3259 pir.removeFilter(pa); 3260 changed = true; 3261 if (DEBUG_PREFERRED) { 3262 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3263 } 3264 break; 3265 } 3266 3267 // Okay we found a previously set preferred or last chosen app. 3268 // If the result set is different from when this 3269 // was created, we need to clear it and re-ask the 3270 // user their preference, if we're looking for an "always" type entry. 3271 if (always && !pa.mPref.sameSet(query, priority)) { 3272 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3273 + intent + " type " + resolvedType); 3274 if (DEBUG_PREFERRED) { 3275 Slog.v(TAG, "Removing preferred activity since set changed " 3276 + pa.mPref.mComponent); 3277 } 3278 pir.removeFilter(pa); 3279 // Re-add the filter as a "last chosen" entry (!always) 3280 PreferredActivity lastChosen = new PreferredActivity( 3281 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3282 pir.addFilter(lastChosen); 3283 changed = true; 3284 return null; 3285 } 3286 3287 // Yay! Either the set matched or we're looking for the last chosen 3288 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3289 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3290 return ri; 3291 } 3292 } 3293 } finally { 3294 if (changed) { 3295 if (DEBUG_PREFERRED) { 3296 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3297 } 3298 mSettings.writePackageRestrictionsLPr(userId); 3299 } 3300 } 3301 } 3302 } 3303 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3304 return null; 3305 } 3306 3307 /* 3308 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3309 */ 3310 @Override 3311 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3312 int targetUserId) { 3313 mContext.enforceCallingOrSelfPermission( 3314 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3315 List<CrossProfileIntentFilter> matches = 3316 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3317 if (matches != null) { 3318 int size = matches.size(); 3319 for (int i = 0; i < size; i++) { 3320 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3321 } 3322 } 3323 return false; 3324 } 3325 3326 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3327 String resolvedType, int userId) { 3328 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3329 if (resolver != null) { 3330 return resolver.queryIntent(intent, resolvedType, false, userId); 3331 } 3332 return null; 3333 } 3334 3335 @Override 3336 public List<ResolveInfo> queryIntentActivities(Intent intent, 3337 String resolvedType, int flags, int userId) { 3338 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3339 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3340 ComponentName comp = intent.getComponent(); 3341 if (comp == null) { 3342 if (intent.getSelector() != null) { 3343 intent = intent.getSelector(); 3344 comp = intent.getComponent(); 3345 } 3346 } 3347 3348 if (comp != null) { 3349 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3350 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3351 if (ai != null) { 3352 final ResolveInfo ri = new ResolveInfo(); 3353 ri.activityInfo = ai; 3354 list.add(ri); 3355 } 3356 return list; 3357 } 3358 3359 // reader 3360 synchronized (mPackages) { 3361 final String pkgName = intent.getPackage(); 3362 if (pkgName == null) { 3363 List<CrossProfileIntentFilter> matchingFilters = 3364 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3365 // Check for results that need to skip the current profile. 3366 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3367 resolvedType, flags, userId); 3368 if (resolveInfo != null) { 3369 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3370 result.add(resolveInfo); 3371 return result; 3372 } 3373 // Check for cross profile results. 3374 resolveInfo = queryCrossProfileIntents( 3375 matchingFilters, intent, resolvedType, flags, userId); 3376 3377 // Check for results in the current profile. 3378 List<ResolveInfo> result = mActivities.queryIntent( 3379 intent, resolvedType, flags, userId); 3380 if (resolveInfo != null) { 3381 result.add(resolveInfo); 3382 Collections.sort(result, mResolvePrioritySorter); 3383 } 3384 return result; 3385 } 3386 final PackageParser.Package pkg = mPackages.get(pkgName); 3387 if (pkg != null) { 3388 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3389 pkg.activities, userId); 3390 } 3391 return new ArrayList<ResolveInfo>(); 3392 } 3393 } 3394 3395 private ResolveInfo querySkipCurrentProfileIntents( 3396 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3397 int flags, int sourceUserId) { 3398 if (matchingFilters != null) { 3399 int size = matchingFilters.size(); 3400 for (int i = 0; i < size; i ++) { 3401 CrossProfileIntentFilter filter = matchingFilters.get(i); 3402 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3403 // Checking if there are activities in the target user that can handle the 3404 // intent. 3405 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3406 flags, sourceUserId); 3407 if (resolveInfo != null) { 3408 return resolveInfo; 3409 } 3410 } 3411 } 3412 } 3413 return null; 3414 } 3415 3416 // Return matching ResolveInfo if any for skip current profile intent filters. 3417 private ResolveInfo queryCrossProfileIntents( 3418 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3419 int flags, int sourceUserId) { 3420 if (matchingFilters != null) { 3421 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3422 // match the same intent. For performance reasons, it is better not to 3423 // run queryIntent twice for the same userId 3424 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3425 int size = matchingFilters.size(); 3426 for (int i = 0; i < size; i++) { 3427 CrossProfileIntentFilter filter = matchingFilters.get(i); 3428 int targetUserId = filter.getTargetUserId(); 3429 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3430 && !alreadyTriedUserIds.get(targetUserId)) { 3431 // Checking if there are activities in the target user that can handle the 3432 // intent. 3433 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3434 flags, sourceUserId); 3435 if (resolveInfo != null) return resolveInfo; 3436 alreadyTriedUserIds.put(targetUserId, true); 3437 } 3438 } 3439 } 3440 return null; 3441 } 3442 3443 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3444 String resolvedType, int flags, int sourceUserId) { 3445 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3446 resolvedType, flags, filter.getTargetUserId()); 3447 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3448 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3449 } 3450 return null; 3451 } 3452 3453 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3454 int sourceUserId, int targetUserId) { 3455 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3456 String className; 3457 if (targetUserId == UserHandle.USER_OWNER) { 3458 className = FORWARD_INTENT_TO_USER_OWNER; 3459 } else { 3460 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3461 } 3462 ComponentName forwardingActivityComponentName = new ComponentName( 3463 mAndroidApplication.packageName, className); 3464 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3465 sourceUserId); 3466 if (targetUserId == UserHandle.USER_OWNER) { 3467 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3468 forwardingResolveInfo.noResourceId = true; 3469 } 3470 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3471 forwardingResolveInfo.priority = 0; 3472 forwardingResolveInfo.preferredOrder = 0; 3473 forwardingResolveInfo.match = 0; 3474 forwardingResolveInfo.isDefault = true; 3475 forwardingResolveInfo.filter = filter; 3476 forwardingResolveInfo.targetUserId = targetUserId; 3477 return forwardingResolveInfo; 3478 } 3479 3480 @Override 3481 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3482 Intent[] specifics, String[] specificTypes, Intent intent, 3483 String resolvedType, int flags, int userId) { 3484 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3485 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3486 false, "query intent activity options"); 3487 final String resultsAction = intent.getAction(); 3488 3489 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3490 | PackageManager.GET_RESOLVED_FILTER, userId); 3491 3492 if (DEBUG_INTENT_MATCHING) { 3493 Log.v(TAG, "Query " + intent + ": " + results); 3494 } 3495 3496 int specificsPos = 0; 3497 int N; 3498 3499 // todo: note that the algorithm used here is O(N^2). This 3500 // isn't a problem in our current environment, but if we start running 3501 // into situations where we have more than 5 or 10 matches then this 3502 // should probably be changed to something smarter... 3503 3504 // First we go through and resolve each of the specific items 3505 // that were supplied, taking care of removing any corresponding 3506 // duplicate items in the generic resolve list. 3507 if (specifics != null) { 3508 for (int i=0; i<specifics.length; i++) { 3509 final Intent sintent = specifics[i]; 3510 if (sintent == null) { 3511 continue; 3512 } 3513 3514 if (DEBUG_INTENT_MATCHING) { 3515 Log.v(TAG, "Specific #" + i + ": " + sintent); 3516 } 3517 3518 String action = sintent.getAction(); 3519 if (resultsAction != null && resultsAction.equals(action)) { 3520 // If this action was explicitly requested, then don't 3521 // remove things that have it. 3522 action = null; 3523 } 3524 3525 ResolveInfo ri = null; 3526 ActivityInfo ai = null; 3527 3528 ComponentName comp = sintent.getComponent(); 3529 if (comp == null) { 3530 ri = resolveIntent( 3531 sintent, 3532 specificTypes != null ? specificTypes[i] : null, 3533 flags, userId); 3534 if (ri == null) { 3535 continue; 3536 } 3537 if (ri == mResolveInfo) { 3538 // ACK! Must do something better with this. 3539 } 3540 ai = ri.activityInfo; 3541 comp = new ComponentName(ai.applicationInfo.packageName, 3542 ai.name); 3543 } else { 3544 ai = getActivityInfo(comp, flags, userId); 3545 if (ai == null) { 3546 continue; 3547 } 3548 } 3549 3550 // Look for any generic query activities that are duplicates 3551 // of this specific one, and remove them from the results. 3552 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3553 N = results.size(); 3554 int j; 3555 for (j=specificsPos; j<N; j++) { 3556 ResolveInfo sri = results.get(j); 3557 if ((sri.activityInfo.name.equals(comp.getClassName()) 3558 && sri.activityInfo.applicationInfo.packageName.equals( 3559 comp.getPackageName())) 3560 || (action != null && sri.filter.matchAction(action))) { 3561 results.remove(j); 3562 if (DEBUG_INTENT_MATCHING) Log.v( 3563 TAG, "Removing duplicate item from " + j 3564 + " due to specific " + specificsPos); 3565 if (ri == null) { 3566 ri = sri; 3567 } 3568 j--; 3569 N--; 3570 } 3571 } 3572 3573 // Add this specific item to its proper place. 3574 if (ri == null) { 3575 ri = new ResolveInfo(); 3576 ri.activityInfo = ai; 3577 } 3578 results.add(specificsPos, ri); 3579 ri.specificIndex = i; 3580 specificsPos++; 3581 } 3582 } 3583 3584 // Now we go through the remaining generic results and remove any 3585 // duplicate actions that are found here. 3586 N = results.size(); 3587 for (int i=specificsPos; i<N-1; i++) { 3588 final ResolveInfo rii = results.get(i); 3589 if (rii.filter == null) { 3590 continue; 3591 } 3592 3593 // Iterate over all of the actions of this result's intent 3594 // filter... typically this should be just one. 3595 final Iterator<String> it = rii.filter.actionsIterator(); 3596 if (it == null) { 3597 continue; 3598 } 3599 while (it.hasNext()) { 3600 final String action = it.next(); 3601 if (resultsAction != null && resultsAction.equals(action)) { 3602 // If this action was explicitly requested, then don't 3603 // remove things that have it. 3604 continue; 3605 } 3606 for (int j=i+1; j<N; j++) { 3607 final ResolveInfo rij = results.get(j); 3608 if (rij.filter != null && rij.filter.hasAction(action)) { 3609 results.remove(j); 3610 if (DEBUG_INTENT_MATCHING) Log.v( 3611 TAG, "Removing duplicate item from " + j 3612 + " due to action " + action + " at " + i); 3613 j--; 3614 N--; 3615 } 3616 } 3617 } 3618 3619 // If the caller didn't request filter information, drop it now 3620 // so we don't have to marshall/unmarshall it. 3621 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3622 rii.filter = null; 3623 } 3624 } 3625 3626 // Filter out the caller activity if so requested. 3627 if (caller != null) { 3628 N = results.size(); 3629 for (int i=0; i<N; i++) { 3630 ActivityInfo ainfo = results.get(i).activityInfo; 3631 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3632 && caller.getClassName().equals(ainfo.name)) { 3633 results.remove(i); 3634 break; 3635 } 3636 } 3637 } 3638 3639 // If the caller didn't request filter information, 3640 // drop them now so we don't have to 3641 // marshall/unmarshall it. 3642 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3643 N = results.size(); 3644 for (int i=0; i<N; i++) { 3645 results.get(i).filter = null; 3646 } 3647 } 3648 3649 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3650 return results; 3651 } 3652 3653 @Override 3654 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3655 int userId) { 3656 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3657 ComponentName comp = intent.getComponent(); 3658 if (comp == null) { 3659 if (intent.getSelector() != null) { 3660 intent = intent.getSelector(); 3661 comp = intent.getComponent(); 3662 } 3663 } 3664 if (comp != null) { 3665 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3666 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3667 if (ai != null) { 3668 ResolveInfo ri = new ResolveInfo(); 3669 ri.activityInfo = ai; 3670 list.add(ri); 3671 } 3672 return list; 3673 } 3674 3675 // reader 3676 synchronized (mPackages) { 3677 String pkgName = intent.getPackage(); 3678 if (pkgName == null) { 3679 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3680 } 3681 final PackageParser.Package pkg = mPackages.get(pkgName); 3682 if (pkg != null) { 3683 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3684 userId); 3685 } 3686 return null; 3687 } 3688 } 3689 3690 @Override 3691 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3692 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3693 if (!sUserManager.exists(userId)) return null; 3694 if (query != null) { 3695 if (query.size() >= 1) { 3696 // If there is more than one service with the same priority, 3697 // just arbitrarily pick the first one. 3698 return query.get(0); 3699 } 3700 } 3701 return null; 3702 } 3703 3704 @Override 3705 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3706 int userId) { 3707 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3708 ComponentName comp = intent.getComponent(); 3709 if (comp == null) { 3710 if (intent.getSelector() != null) { 3711 intent = intent.getSelector(); 3712 comp = intent.getComponent(); 3713 } 3714 } 3715 if (comp != null) { 3716 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3717 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3718 if (si != null) { 3719 final ResolveInfo ri = new ResolveInfo(); 3720 ri.serviceInfo = si; 3721 list.add(ri); 3722 } 3723 return list; 3724 } 3725 3726 // reader 3727 synchronized (mPackages) { 3728 String pkgName = intent.getPackage(); 3729 if (pkgName == null) { 3730 return mServices.queryIntent(intent, resolvedType, flags, userId); 3731 } 3732 final PackageParser.Package pkg = mPackages.get(pkgName); 3733 if (pkg != null) { 3734 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3735 userId); 3736 } 3737 return null; 3738 } 3739 } 3740 3741 @Override 3742 public List<ResolveInfo> queryIntentContentProviders( 3743 Intent intent, String resolvedType, int flags, int userId) { 3744 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3745 ComponentName comp = intent.getComponent(); 3746 if (comp == null) { 3747 if (intent.getSelector() != null) { 3748 intent = intent.getSelector(); 3749 comp = intent.getComponent(); 3750 } 3751 } 3752 if (comp != null) { 3753 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3754 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3755 if (pi != null) { 3756 final ResolveInfo ri = new ResolveInfo(); 3757 ri.providerInfo = pi; 3758 list.add(ri); 3759 } 3760 return list; 3761 } 3762 3763 // reader 3764 synchronized (mPackages) { 3765 String pkgName = intent.getPackage(); 3766 if (pkgName == null) { 3767 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3768 } 3769 final PackageParser.Package pkg = mPackages.get(pkgName); 3770 if (pkg != null) { 3771 return mProviders.queryIntentForPackage( 3772 intent, resolvedType, flags, pkg.providers, userId); 3773 } 3774 return null; 3775 } 3776 } 3777 3778 @Override 3779 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3780 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3781 3782 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3783 3784 // writer 3785 synchronized (mPackages) { 3786 ArrayList<PackageInfo> list; 3787 if (listUninstalled) { 3788 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3789 for (PackageSetting ps : mSettings.mPackages.values()) { 3790 PackageInfo pi; 3791 if (ps.pkg != null) { 3792 pi = generatePackageInfo(ps.pkg, flags, userId); 3793 } else { 3794 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3795 } 3796 if (pi != null) { 3797 list.add(pi); 3798 } 3799 } 3800 } else { 3801 list = new ArrayList<PackageInfo>(mPackages.size()); 3802 for (PackageParser.Package p : mPackages.values()) { 3803 PackageInfo pi = generatePackageInfo(p, flags, userId); 3804 if (pi != null) { 3805 list.add(pi); 3806 } 3807 } 3808 } 3809 3810 return new ParceledListSlice<PackageInfo>(list); 3811 } 3812 } 3813 3814 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3815 String[] permissions, boolean[] tmp, int flags, int userId) { 3816 int numMatch = 0; 3817 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3818 for (int i=0; i<permissions.length; i++) { 3819 if (gp.grantedPermissions.contains(permissions[i])) { 3820 tmp[i] = true; 3821 numMatch++; 3822 } else { 3823 tmp[i] = false; 3824 } 3825 } 3826 if (numMatch == 0) { 3827 return; 3828 } 3829 PackageInfo pi; 3830 if (ps.pkg != null) { 3831 pi = generatePackageInfo(ps.pkg, flags, userId); 3832 } else { 3833 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3834 } 3835 // The above might return null in cases of uninstalled apps or install-state 3836 // skew across users/profiles. 3837 if (pi != null) { 3838 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3839 if (numMatch == permissions.length) { 3840 pi.requestedPermissions = permissions; 3841 } else { 3842 pi.requestedPermissions = new String[numMatch]; 3843 numMatch = 0; 3844 for (int i=0; i<permissions.length; i++) { 3845 if (tmp[i]) { 3846 pi.requestedPermissions[numMatch] = permissions[i]; 3847 numMatch++; 3848 } 3849 } 3850 } 3851 } 3852 list.add(pi); 3853 } 3854 } 3855 3856 @Override 3857 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3858 String[] permissions, int flags, int userId) { 3859 if (!sUserManager.exists(userId)) return null; 3860 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3861 3862 // writer 3863 synchronized (mPackages) { 3864 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3865 boolean[] tmpBools = new boolean[permissions.length]; 3866 if (listUninstalled) { 3867 for (PackageSetting ps : mSettings.mPackages.values()) { 3868 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3869 } 3870 } else { 3871 for (PackageParser.Package pkg : mPackages.values()) { 3872 PackageSetting ps = (PackageSetting)pkg.mExtras; 3873 if (ps != null) { 3874 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3875 userId); 3876 } 3877 } 3878 } 3879 3880 return new ParceledListSlice<PackageInfo>(list); 3881 } 3882 } 3883 3884 @Override 3885 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3886 if (!sUserManager.exists(userId)) return null; 3887 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3888 3889 // writer 3890 synchronized (mPackages) { 3891 ArrayList<ApplicationInfo> list; 3892 if (listUninstalled) { 3893 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3894 for (PackageSetting ps : mSettings.mPackages.values()) { 3895 ApplicationInfo ai; 3896 if (ps.pkg != null) { 3897 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3898 ps.readUserState(userId), userId); 3899 } else { 3900 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3901 } 3902 if (ai != null) { 3903 list.add(ai); 3904 } 3905 } 3906 } else { 3907 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3908 for (PackageParser.Package p : mPackages.values()) { 3909 if (p.mExtras != null) { 3910 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3911 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3912 if (ai != null) { 3913 list.add(ai); 3914 } 3915 } 3916 } 3917 } 3918 3919 return new ParceledListSlice<ApplicationInfo>(list); 3920 } 3921 } 3922 3923 public List<ApplicationInfo> getPersistentApplications(int flags) { 3924 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3925 3926 // reader 3927 synchronized (mPackages) { 3928 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3929 final int userId = UserHandle.getCallingUserId(); 3930 while (i.hasNext()) { 3931 final PackageParser.Package p = i.next(); 3932 if (p.applicationInfo != null 3933 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3934 && (!mSafeMode || isSystemApp(p))) { 3935 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3936 if (ps != null) { 3937 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3938 ps.readUserState(userId), userId); 3939 if (ai != null) { 3940 finalList.add(ai); 3941 } 3942 } 3943 } 3944 } 3945 } 3946 3947 return finalList; 3948 } 3949 3950 @Override 3951 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3952 if (!sUserManager.exists(userId)) return null; 3953 // reader 3954 synchronized (mPackages) { 3955 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3956 PackageSetting ps = provider != null 3957 ? mSettings.mPackages.get(provider.owner.packageName) 3958 : null; 3959 return ps != null 3960 && mSettings.isEnabledLPr(provider.info, flags, userId) 3961 && (!mSafeMode || (provider.info.applicationInfo.flags 3962 &ApplicationInfo.FLAG_SYSTEM) != 0) 3963 ? PackageParser.generateProviderInfo(provider, flags, 3964 ps.readUserState(userId), userId) 3965 : null; 3966 } 3967 } 3968 3969 /** 3970 * @deprecated 3971 */ 3972 @Deprecated 3973 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3974 // reader 3975 synchronized (mPackages) { 3976 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3977 .entrySet().iterator(); 3978 final int userId = UserHandle.getCallingUserId(); 3979 while (i.hasNext()) { 3980 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3981 PackageParser.Provider p = entry.getValue(); 3982 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3983 3984 if (ps != null && p.syncable 3985 && (!mSafeMode || (p.info.applicationInfo.flags 3986 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3987 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3988 ps.readUserState(userId), userId); 3989 if (info != null) { 3990 outNames.add(entry.getKey()); 3991 outInfo.add(info); 3992 } 3993 } 3994 } 3995 } 3996 } 3997 3998 @Override 3999 public List<ProviderInfo> queryContentProviders(String processName, 4000 int uid, int flags) { 4001 ArrayList<ProviderInfo> finalList = null; 4002 // reader 4003 synchronized (mPackages) { 4004 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4005 final int userId = processName != null ? 4006 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4007 while (i.hasNext()) { 4008 final PackageParser.Provider p = i.next(); 4009 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4010 if (ps != null && p.info.authority != null 4011 && (processName == null 4012 || (p.info.processName.equals(processName) 4013 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4014 && mSettings.isEnabledLPr(p.info, flags, userId) 4015 && (!mSafeMode 4016 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4017 if (finalList == null) { 4018 finalList = new ArrayList<ProviderInfo>(3); 4019 } 4020 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4021 ps.readUserState(userId), userId); 4022 if (info != null) { 4023 finalList.add(info); 4024 } 4025 } 4026 } 4027 } 4028 4029 if (finalList != null) { 4030 Collections.sort(finalList, mProviderInitOrderSorter); 4031 } 4032 4033 return finalList; 4034 } 4035 4036 @Override 4037 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4038 int flags) { 4039 // reader 4040 synchronized (mPackages) { 4041 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4042 return PackageParser.generateInstrumentationInfo(i, flags); 4043 } 4044 } 4045 4046 @Override 4047 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4048 int flags) { 4049 ArrayList<InstrumentationInfo> finalList = 4050 new ArrayList<InstrumentationInfo>(); 4051 4052 // reader 4053 synchronized (mPackages) { 4054 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4055 while (i.hasNext()) { 4056 final PackageParser.Instrumentation p = i.next(); 4057 if (targetPackage == null 4058 || targetPackage.equals(p.info.targetPackage)) { 4059 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4060 flags); 4061 if (ii != null) { 4062 finalList.add(ii); 4063 } 4064 } 4065 } 4066 } 4067 4068 return finalList; 4069 } 4070 4071 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4072 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4073 if (overlays == null) { 4074 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4075 return; 4076 } 4077 for (PackageParser.Package opkg : overlays.values()) { 4078 // Not much to do if idmap fails: we already logged the error 4079 // and we certainly don't want to abort installation of pkg simply 4080 // because an overlay didn't fit properly. For these reasons, 4081 // ignore the return value of createIdmapForPackagePairLI. 4082 createIdmapForPackagePairLI(pkg, opkg); 4083 } 4084 } 4085 4086 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4087 PackageParser.Package opkg) { 4088 if (!opkg.mTrustedOverlay) { 4089 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4090 opkg.baseCodePath + ": overlay not trusted"); 4091 return false; 4092 } 4093 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4094 if (overlaySet == null) { 4095 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4096 opkg.baseCodePath + " but target package has no known overlays"); 4097 return false; 4098 } 4099 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4100 // TODO: generate idmap for split APKs 4101 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4102 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4103 + opkg.baseCodePath); 4104 return false; 4105 } 4106 PackageParser.Package[] overlayArray = 4107 overlaySet.values().toArray(new PackageParser.Package[0]); 4108 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4109 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4110 return p1.mOverlayPriority - p2.mOverlayPriority; 4111 } 4112 }; 4113 Arrays.sort(overlayArray, cmp); 4114 4115 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4116 int i = 0; 4117 for (PackageParser.Package p : overlayArray) { 4118 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4119 } 4120 return true; 4121 } 4122 4123 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4124 final File[] files = dir.listFiles(); 4125 if (ArrayUtils.isEmpty(files)) { 4126 Log.d(TAG, "No files in app dir " + dir); 4127 return; 4128 } 4129 4130 if (DEBUG_PACKAGE_SCANNING) { 4131 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4132 + " flags=0x" + Integer.toHexString(parseFlags)); 4133 } 4134 4135 for (File file : files) { 4136 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4137 && !PackageInstallerService.isStageName(file.getName()); 4138 if (!isPackage) { 4139 // Ignore entries which are not packages 4140 continue; 4141 } 4142 try { 4143 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4144 scanFlags, currentTime, null); 4145 } catch (PackageManagerException e) { 4146 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4147 4148 // Delete invalid userdata apps 4149 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4150 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4151 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4152 if (file.isDirectory()) { 4153 FileUtils.deleteContents(file); 4154 } 4155 file.delete(); 4156 } 4157 } 4158 } 4159 } 4160 4161 private static File getSettingsProblemFile() { 4162 File dataDir = Environment.getDataDirectory(); 4163 File systemDir = new File(dataDir, "system"); 4164 File fname = new File(systemDir, "uiderrors.txt"); 4165 return fname; 4166 } 4167 4168 static void reportSettingsProblem(int priority, String msg) { 4169 logCriticalInfo(priority, msg); 4170 } 4171 4172 static void logCriticalInfo(int priority, String msg) { 4173 Slog.println(priority, TAG, msg); 4174 EventLogTags.writePmCriticalInfo(msg); 4175 try { 4176 File fname = getSettingsProblemFile(); 4177 FileOutputStream out = new FileOutputStream(fname, true); 4178 PrintWriter pw = new FastPrintWriter(out); 4179 SimpleDateFormat formatter = new SimpleDateFormat(); 4180 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4181 pw.println(dateString + ": " + msg); 4182 pw.close(); 4183 FileUtils.setPermissions( 4184 fname.toString(), 4185 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4186 -1, -1); 4187 } catch (java.io.IOException e) { 4188 } 4189 } 4190 4191 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4192 PackageParser.Package pkg, File srcFile, int parseFlags) 4193 throws PackageManagerException { 4194 if (ps != null 4195 && ps.codePath.equals(srcFile) 4196 && ps.timeStamp == srcFile.lastModified() 4197 && !isCompatSignatureUpdateNeeded(pkg) 4198 && !isRecoverSignatureUpdateNeeded(pkg)) { 4199 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4200 if (ps.signatures.mSignatures != null 4201 && ps.signatures.mSignatures.length != 0 4202 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4203 // Optimization: reuse the existing cached certificates 4204 // if the package appears to be unchanged. 4205 pkg.mSignatures = ps.signatures.mSignatures; 4206 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4207 synchronized (mPackages) { 4208 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4209 } 4210 return; 4211 } 4212 4213 Slog.w(TAG, "PackageSetting for " + ps.name 4214 + " is missing signatures. Collecting certs again to recover them."); 4215 } else { 4216 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4217 } 4218 4219 try { 4220 pp.collectCertificates(pkg, parseFlags); 4221 pp.collectManifestDigest(pkg); 4222 } catch (PackageParserException e) { 4223 throw PackageManagerException.from(e); 4224 } 4225 } 4226 4227 /* 4228 * Scan a package and return the newly parsed package. 4229 * Returns null in case of errors and the error code is stored in mLastScanError 4230 */ 4231 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4232 long currentTime, UserHandle user) throws PackageManagerException { 4233 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4234 parseFlags |= mDefParseFlags; 4235 PackageParser pp = new PackageParser(); 4236 pp.setSeparateProcesses(mSeparateProcesses); 4237 pp.setOnlyCoreApps(mOnlyCore); 4238 pp.setDisplayMetrics(mMetrics); 4239 4240 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4241 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4242 } 4243 4244 final PackageParser.Package pkg; 4245 try { 4246 pkg = pp.parsePackage(scanFile, parseFlags); 4247 } catch (PackageParserException e) { 4248 throw PackageManagerException.from(e); 4249 } 4250 4251 PackageSetting ps = null; 4252 PackageSetting updatedPkg; 4253 // reader 4254 synchronized (mPackages) { 4255 // Look to see if we already know about this package. 4256 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4257 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4258 // This package has been renamed to its original name. Let's 4259 // use that. 4260 ps = mSettings.peekPackageLPr(oldName); 4261 } 4262 // If there was no original package, see one for the real package name. 4263 if (ps == null) { 4264 ps = mSettings.peekPackageLPr(pkg.packageName); 4265 } 4266 // Check to see if this package could be hiding/updating a system 4267 // package. Must look for it either under the original or real 4268 // package name depending on our state. 4269 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4270 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4271 } 4272 boolean updatedPkgBetter = false; 4273 // First check if this is a system package that may involve an update 4274 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4275 if (ps != null && !ps.codePath.equals(scanFile)) { 4276 // The path has changed from what was last scanned... check the 4277 // version of the new path against what we have stored to determine 4278 // what to do. 4279 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4280 if (pkg.mVersionCode < ps.versionCode) { 4281 // The system package has been updated and the code path does not match 4282 // Ignore entry. Skip it. 4283 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4284 + " ignored: updated version " + ps.versionCode 4285 + " better than this " + pkg.mVersionCode); 4286 if (!updatedPkg.codePath.equals(scanFile)) { 4287 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4288 + ps.name + " changing from " + updatedPkg.codePathString 4289 + " to " + scanFile); 4290 updatedPkg.codePath = scanFile; 4291 updatedPkg.codePathString = scanFile.toString(); 4292 // This is the point at which we know that the system-disk APK 4293 // for this package has moved during a reboot (e.g. due to an OTA), 4294 // so we need to reevaluate it for privilege policy. 4295 if (locationIsPrivileged(scanFile)) { 4296 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4297 } 4298 } 4299 updatedPkg.pkg = pkg; 4300 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4301 } else { 4302 // The current app on the system partition is better than 4303 // what we have updated to on the data partition; switch 4304 // back to the system partition version. 4305 // At this point, its safely assumed that package installation for 4306 // apps in system partition will go through. If not there won't be a working 4307 // version of the app 4308 // writer 4309 synchronized (mPackages) { 4310 // Just remove the loaded entries from package lists. 4311 mPackages.remove(ps.name); 4312 } 4313 4314 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4315 + " reverting from " + ps.codePathString 4316 + ": new version " + pkg.mVersionCode 4317 + " better than installed " + ps.versionCode); 4318 4319 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4320 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4321 getAppDexInstructionSets(ps)); 4322 synchronized (mInstallLock) { 4323 args.cleanUpResourcesLI(); 4324 } 4325 synchronized (mPackages) { 4326 mSettings.enableSystemPackageLPw(ps.name); 4327 } 4328 updatedPkgBetter = true; 4329 } 4330 } 4331 } 4332 4333 if (updatedPkg != null) { 4334 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4335 // initially 4336 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4337 4338 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4339 // flag set initially 4340 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4341 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4342 } 4343 } 4344 4345 // Verify certificates against what was last scanned 4346 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4347 4348 /* 4349 * A new system app appeared, but we already had a non-system one of the 4350 * same name installed earlier. 4351 */ 4352 boolean shouldHideSystemApp = false; 4353 if (updatedPkg == null && ps != null 4354 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4355 /* 4356 * Check to make sure the signatures match first. If they don't, 4357 * wipe the installed application and its data. 4358 */ 4359 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4360 != PackageManager.SIGNATURE_MATCH) { 4361 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4362 + " signatures don't match existing userdata copy; removing"); 4363 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4364 ps = null; 4365 } else { 4366 /* 4367 * If the newly-added system app is an older version than the 4368 * already installed version, hide it. It will be scanned later 4369 * and re-added like an update. 4370 */ 4371 if (pkg.mVersionCode < ps.versionCode) { 4372 shouldHideSystemApp = true; 4373 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4374 + " but new version " + pkg.mVersionCode + " better than installed " 4375 + ps.versionCode + "; hiding system"); 4376 } else { 4377 /* 4378 * The newly found system app is a newer version that the 4379 * one previously installed. Simply remove the 4380 * already-installed application and replace it with our own 4381 * while keeping the application data. 4382 */ 4383 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4384 + " reverting from " + ps.codePathString + ": new version " 4385 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4386 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4387 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4388 getAppDexInstructionSets(ps)); 4389 synchronized (mInstallLock) { 4390 args.cleanUpResourcesLI(); 4391 } 4392 } 4393 } 4394 } 4395 4396 // The apk is forward locked (not public) if its code and resources 4397 // are kept in different files. (except for app in either system or 4398 // vendor path). 4399 // TODO grab this value from PackageSettings 4400 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4401 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4402 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4403 } 4404 } 4405 4406 // TODO: extend to support forward-locked splits 4407 String resourcePath = null; 4408 String baseResourcePath = null; 4409 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4410 if (ps != null && ps.resourcePathString != null) { 4411 resourcePath = ps.resourcePathString; 4412 baseResourcePath = ps.resourcePathString; 4413 } else { 4414 // Should not happen at all. Just log an error. 4415 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4416 } 4417 } else { 4418 resourcePath = pkg.codePath; 4419 baseResourcePath = pkg.baseCodePath; 4420 } 4421 4422 // Set application objects path explicitly. 4423 pkg.applicationInfo.setCodePath(pkg.codePath); 4424 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4425 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4426 pkg.applicationInfo.setResourcePath(resourcePath); 4427 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4428 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4429 4430 // Note that we invoke the following method only if we are about to unpack an application 4431 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4432 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4433 4434 /* 4435 * If the system app should be overridden by a previously installed 4436 * data, hide the system app now and let the /data/app scan pick it up 4437 * again. 4438 */ 4439 if (shouldHideSystemApp) { 4440 synchronized (mPackages) { 4441 /* 4442 * We have to grant systems permissions before we hide, because 4443 * grantPermissions will assume the package update is trying to 4444 * expand its permissions. 4445 */ 4446 grantPermissionsLPw(pkg, true, pkg.packageName); 4447 mSettings.disableSystemPackageLPw(pkg.packageName); 4448 } 4449 } 4450 4451 return scannedPkg; 4452 } 4453 4454 private static String fixProcessName(String defProcessName, 4455 String processName, int uid) { 4456 if (processName == null) { 4457 return defProcessName; 4458 } 4459 return processName; 4460 } 4461 4462 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4463 throws PackageManagerException { 4464 if (pkgSetting.signatures.mSignatures != null) { 4465 // Already existing package. Make sure signatures match 4466 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4467 == PackageManager.SIGNATURE_MATCH; 4468 if (!match) { 4469 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4470 == PackageManager.SIGNATURE_MATCH; 4471 } 4472 if (!match) { 4473 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4474 == PackageManager.SIGNATURE_MATCH; 4475 } 4476 if (!match) { 4477 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4478 + pkg.packageName + " signatures do not match the " 4479 + "previously installed version; ignoring!"); 4480 } 4481 } 4482 4483 // Check for shared user signatures 4484 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4485 // Already existing package. Make sure signatures match 4486 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4487 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4488 if (!match) { 4489 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4490 == PackageManager.SIGNATURE_MATCH; 4491 } 4492 if (!match) { 4493 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4494 == PackageManager.SIGNATURE_MATCH; 4495 } 4496 if (!match) { 4497 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4498 "Package " + pkg.packageName 4499 + " has no signatures that match those in shared user " 4500 + pkgSetting.sharedUser.name + "; ignoring!"); 4501 } 4502 } 4503 } 4504 4505 /** 4506 * Enforces that only the system UID or root's UID can call a method exposed 4507 * via Binder. 4508 * 4509 * @param message used as message if SecurityException is thrown 4510 * @throws SecurityException if the caller is not system or root 4511 */ 4512 private static final void enforceSystemOrRoot(String message) { 4513 final int uid = Binder.getCallingUid(); 4514 if (uid != Process.SYSTEM_UID && uid != 0) { 4515 throw new SecurityException(message); 4516 } 4517 } 4518 4519 @Override 4520 public void performBootDexOpt() { 4521 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4522 4523 // Before everything else, see whether we need to fstrim. 4524 try { 4525 IMountService ms = PackageHelper.getMountService(); 4526 if (ms != null) { 4527 final long interval = android.provider.Settings.Global.getLong( 4528 mContext.getContentResolver(), 4529 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4530 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4531 if (interval > 0) { 4532 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4533 if (timeSinceLast > interval) { 4534 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4535 + "; running immediately"); 4536 if (!isFirstBoot()) { 4537 try { 4538 ActivityManagerNative.getDefault().showBootMessage( 4539 mContext.getResources().getString( 4540 R.string.android_upgrading_fstrim), true); 4541 } catch (RemoteException e) { 4542 } 4543 } 4544 ms.runMaintenance(); 4545 } 4546 } 4547 } else { 4548 Slog.e(TAG, "Mount service unavailable!"); 4549 } 4550 } catch (RemoteException e) { 4551 // Can't happen; MountService is local 4552 } 4553 4554 final HashSet<PackageParser.Package> pkgs; 4555 synchronized (mPackages) { 4556 pkgs = mDeferredDexOpt; 4557 mDeferredDexOpt = null; 4558 } 4559 4560 if (pkgs != null) { 4561 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4562 // in case the device runs out of space. 4563 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4564 // Give priority to core apps. 4565 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4566 PackageParser.Package pkg = it.next(); 4567 if (pkg.coreApp) { 4568 if (DEBUG_DEXOPT) { 4569 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4570 } 4571 sortedPkgs.add(pkg); 4572 it.remove(); 4573 } 4574 } 4575 // Give priority to system apps that listen for pre boot complete. 4576 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4577 HashSet<String> pkgNames = getPackageNamesForIntent(intent); 4578 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4579 PackageParser.Package pkg = it.next(); 4580 if (pkgNames.contains(pkg.packageName)) { 4581 if (DEBUG_DEXOPT) { 4582 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4583 } 4584 sortedPkgs.add(pkg); 4585 it.remove(); 4586 } 4587 } 4588 // Give priority to system apps. 4589 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4590 PackageParser.Package pkg = it.next(); 4591 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4592 if (DEBUG_DEXOPT) { 4593 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4594 } 4595 sortedPkgs.add(pkg); 4596 it.remove(); 4597 } 4598 } 4599 // Give priority to updated system apps. 4600 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4601 PackageParser.Package pkg = it.next(); 4602 if (isUpdatedSystemApp(pkg)) { 4603 if (DEBUG_DEXOPT) { 4604 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4605 } 4606 sortedPkgs.add(pkg); 4607 it.remove(); 4608 } 4609 } 4610 // Give priority to apps that listen for boot complete. 4611 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4612 pkgNames = getPackageNamesForIntent(intent); 4613 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4614 PackageParser.Package pkg = it.next(); 4615 if (pkgNames.contains(pkg.packageName)) { 4616 if (DEBUG_DEXOPT) { 4617 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4618 } 4619 sortedPkgs.add(pkg); 4620 it.remove(); 4621 } 4622 } 4623 // Filter out packages that aren't recently used. 4624 filterRecentlyUsedApps(pkgs); 4625 // Add all remaining apps. 4626 for (PackageParser.Package pkg : pkgs) { 4627 if (DEBUG_DEXOPT) { 4628 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4629 } 4630 sortedPkgs.add(pkg); 4631 } 4632 4633 int i = 0; 4634 int total = sortedPkgs.size(); 4635 File dataDir = Environment.getDataDirectory(); 4636 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4637 if (lowThreshold == 0) { 4638 throw new IllegalStateException("Invalid low memory threshold"); 4639 } 4640 for (PackageParser.Package pkg : sortedPkgs) { 4641 long usableSpace = dataDir.getUsableSpace(); 4642 if (usableSpace < lowThreshold) { 4643 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4644 break; 4645 } 4646 performBootDexOpt(pkg, ++i, total); 4647 } 4648 } 4649 } 4650 4651 private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) { 4652 // Filter out packages that aren't recently used. 4653 // 4654 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4655 // should do a full dexopt. 4656 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4657 // TODO: add a property to control this? 4658 long dexOptLRUThresholdInMinutes; 4659 if (mLazyDexOpt) { 4660 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4661 } else { 4662 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4663 } 4664 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4665 4666 int total = pkgs.size(); 4667 int skipped = 0; 4668 long now = System.currentTimeMillis(); 4669 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4670 PackageParser.Package pkg = i.next(); 4671 long then = pkg.mLastPackageUsageTimeInMills; 4672 if (then + dexOptLRUThresholdInMills < now) { 4673 if (DEBUG_DEXOPT) { 4674 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4675 ((then == 0) ? "never" : new Date(then))); 4676 } 4677 i.remove(); 4678 skipped++; 4679 } 4680 } 4681 if (DEBUG_DEXOPT) { 4682 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4683 } 4684 } 4685 } 4686 4687 private HashSet<String> getPackageNamesForIntent(Intent intent) { 4688 List<ResolveInfo> ris = null; 4689 try { 4690 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4691 intent, null, 0, UserHandle.USER_OWNER); 4692 } catch (RemoteException e) { 4693 } 4694 HashSet<String> pkgNames = new HashSet<String>(); 4695 if (ris != null) { 4696 for (ResolveInfo ri : ris) { 4697 pkgNames.add(ri.activityInfo.packageName); 4698 } 4699 } 4700 return pkgNames; 4701 } 4702 4703 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4704 if (DEBUG_DEXOPT) { 4705 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4706 } 4707 if (!isFirstBoot()) { 4708 try { 4709 ActivityManagerNative.getDefault().showBootMessage( 4710 mContext.getResources().getString(R.string.android_upgrading_apk, 4711 curr, total), true); 4712 } catch (RemoteException e) { 4713 } 4714 } 4715 PackageParser.Package p = pkg; 4716 synchronized (mInstallLock) { 4717 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4718 false /* defer */, true /* include dependencies */); 4719 } 4720 } 4721 4722 @Override 4723 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4724 return performDexOpt(packageName, instructionSet, false); 4725 } 4726 4727 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4728 if (info.primaryCpuAbi == null) { 4729 return getPreferredInstructionSet(); 4730 } 4731 4732 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4733 } 4734 4735 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4736 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4737 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4738 if (!dexopt && !updateUsage) { 4739 // We aren't going to dexopt or update usage, so bail early. 4740 return false; 4741 } 4742 PackageParser.Package p; 4743 final String targetInstructionSet; 4744 synchronized (mPackages) { 4745 p = mPackages.get(packageName); 4746 if (p == null) { 4747 return false; 4748 } 4749 if (updateUsage) { 4750 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4751 } 4752 mPackageUsage.write(false); 4753 if (!dexopt) { 4754 // We aren't going to dexopt, so bail early. 4755 return false; 4756 } 4757 4758 targetInstructionSet = instructionSet != null ? instructionSet : 4759 getPrimaryInstructionSet(p.applicationInfo); 4760 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4761 return false; 4762 } 4763 } 4764 4765 synchronized (mInstallLock) { 4766 final String[] instructionSets = new String[] { targetInstructionSet }; 4767 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4768 true /* include dependencies */) == DEX_OPT_PERFORMED; 4769 } 4770 } 4771 4772 public HashSet<String> getPackagesThatNeedDexOpt() { 4773 HashSet<String> pkgs = null; 4774 synchronized (mPackages) { 4775 for (PackageParser.Package p : mPackages.values()) { 4776 if (DEBUG_DEXOPT) { 4777 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4778 } 4779 if (!p.mDexOptPerformed.isEmpty()) { 4780 continue; 4781 } 4782 if (pkgs == null) { 4783 pkgs = new HashSet<String>(); 4784 } 4785 pkgs.add(p.packageName); 4786 } 4787 } 4788 return pkgs; 4789 } 4790 4791 public void shutdown() { 4792 mPackageUsage.write(true); 4793 } 4794 4795 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4796 boolean forceDex, boolean defer, HashSet<String> done) { 4797 for (int i=0; i<libs.size(); i++) { 4798 PackageParser.Package libPkg; 4799 String libName; 4800 synchronized (mPackages) { 4801 libName = libs.get(i); 4802 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4803 if (lib != null && lib.apk != null) { 4804 libPkg = mPackages.get(lib.apk); 4805 } else { 4806 libPkg = null; 4807 } 4808 } 4809 if (libPkg != null && !done.contains(libName)) { 4810 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4811 } 4812 } 4813 } 4814 4815 static final int DEX_OPT_SKIPPED = 0; 4816 static final int DEX_OPT_PERFORMED = 1; 4817 static final int DEX_OPT_DEFERRED = 2; 4818 static final int DEX_OPT_FAILED = -1; 4819 4820 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4821 boolean forceDex, boolean defer, HashSet<String> done) { 4822 final String[] instructionSets = targetInstructionSets != null ? 4823 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4824 4825 if (done != null) { 4826 done.add(pkg.packageName); 4827 if (pkg.usesLibraries != null) { 4828 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4829 } 4830 if (pkg.usesOptionalLibraries != null) { 4831 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4832 } 4833 } 4834 4835 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4836 return DEX_OPT_SKIPPED; 4837 } 4838 4839 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4840 4841 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4842 boolean performedDexOpt = false; 4843 // There are three basic cases here: 4844 // 1.) we need to dexopt, either because we are forced or it is needed 4845 // 2.) we are defering a needed dexopt 4846 // 3.) we are skipping an unneeded dexopt 4847 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4848 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4849 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4850 continue; 4851 } 4852 4853 for (String path : paths) { 4854 try { 4855 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4856 // patckage or the one we find does not match the image checksum (i.e. it was 4857 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4858 // odex file and it matches the checksum of the image but not its base address, 4859 // meaning we need to move it. 4860 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4861 pkg.packageName, dexCodeInstructionSet, defer); 4862 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4863 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4864 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4865 + " vmSafeMode=" + vmSafeMode); 4866 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4867 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4868 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4869 4870 if (ret < 0) { 4871 // Don't bother running dexopt again if we failed, it will probably 4872 // just result in an error again. Also, don't bother dexopting for other 4873 // paths & ISAs. 4874 return DEX_OPT_FAILED; 4875 } 4876 4877 performedDexOpt = true; 4878 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4879 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4880 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4881 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4882 pkg.packageName, dexCodeInstructionSet); 4883 4884 if (ret < 0) { 4885 // Don't bother running patchoat again if we failed, it will probably 4886 // just result in an error again. Also, don't bother dexopting for other 4887 // paths & ISAs. 4888 return DEX_OPT_FAILED; 4889 } 4890 4891 performedDexOpt = true; 4892 } 4893 4894 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4895 // paths and instruction sets. We'll deal with them all together when we process 4896 // our list of deferred dexopts. 4897 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4898 if (mDeferredDexOpt == null) { 4899 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4900 } 4901 mDeferredDexOpt.add(pkg); 4902 return DEX_OPT_DEFERRED; 4903 } 4904 } catch (FileNotFoundException e) { 4905 Slog.w(TAG, "Apk not found for dexopt: " + path); 4906 return DEX_OPT_FAILED; 4907 } catch (IOException e) { 4908 Slog.w(TAG, "IOException reading apk: " + path, e); 4909 return DEX_OPT_FAILED; 4910 } catch (StaleDexCacheError e) { 4911 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4912 return DEX_OPT_FAILED; 4913 } catch (Exception e) { 4914 Slog.w(TAG, "Exception when doing dexopt : ", e); 4915 return DEX_OPT_FAILED; 4916 } 4917 } 4918 4919 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4920 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4921 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4922 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4923 // it. 4924 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4925 } 4926 4927 // If we've gotten here, we're sure that no error occurred and that we haven't 4928 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4929 // we've skipped all of them because they are up to date. In both cases this 4930 // package doesn't need dexopt any longer. 4931 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4932 } 4933 4934 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4935 if (info.primaryCpuAbi != null) { 4936 if (info.secondaryCpuAbi != null) { 4937 return new String[] { 4938 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4939 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4940 } else { 4941 return new String[] { 4942 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4943 } 4944 } 4945 4946 return new String[] { getPreferredInstructionSet() }; 4947 } 4948 4949 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4950 if (ps.primaryCpuAbiString != null) { 4951 if (ps.secondaryCpuAbiString != null) { 4952 return new String[] { 4953 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4954 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4955 } else { 4956 return new String[] { 4957 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4958 } 4959 } 4960 4961 return new String[] { getPreferredInstructionSet() }; 4962 } 4963 4964 private static String getPreferredInstructionSet() { 4965 if (sPreferredInstructionSet == null) { 4966 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4967 } 4968 4969 return sPreferredInstructionSet; 4970 } 4971 4972 private static List<String> getAllInstructionSets() { 4973 final String[] allAbis = Build.SUPPORTED_ABIS; 4974 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4975 4976 for (String abi : allAbis) { 4977 final String instructionSet = VMRuntime.getInstructionSet(abi); 4978 if (!allInstructionSets.contains(instructionSet)) { 4979 allInstructionSets.add(instructionSet); 4980 } 4981 } 4982 4983 return allInstructionSets; 4984 } 4985 4986 /** 4987 * Returns the instruction set that should be used to compile dex code. In the presence of 4988 * a native bridge this might be different than the one shared libraries use. 4989 */ 4990 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4991 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4992 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4993 } 4994 4995 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4996 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4997 for (String instructionSet : instructionSets) { 4998 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4999 } 5000 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 5001 } 5002 5003 /** 5004 * Returns deduplicated list of supported instructions for dex code. 5005 */ 5006 public static String[] getAllDexCodeInstructionSets() { 5007 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 5008 for (int i = 0; i < supportedInstructionSets.length; i++) { 5009 String abi = Build.SUPPORTED_ABIS[i]; 5010 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 5011 } 5012 return getDexCodeInstructionSets(supportedInstructionSets); 5013 } 5014 5015 @Override 5016 public void forceDexOpt(String packageName) { 5017 enforceSystemOrRoot("forceDexOpt"); 5018 5019 PackageParser.Package pkg; 5020 synchronized (mPackages) { 5021 pkg = mPackages.get(packageName); 5022 if (pkg == null) { 5023 throw new IllegalArgumentException("Missing package: " + packageName); 5024 } 5025 } 5026 5027 synchronized (mInstallLock) { 5028 final String[] instructionSets = new String[] { 5029 getPrimaryInstructionSet(pkg.applicationInfo) }; 5030 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 5031 if (res != DEX_OPT_PERFORMED) { 5032 throw new IllegalStateException("Failed to dexopt: " + res); 5033 } 5034 } 5035 } 5036 5037 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 5038 boolean forceDex, boolean defer, boolean inclDependencies) { 5039 HashSet<String> done; 5040 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 5041 done = new HashSet<String>(); 5042 done.add(pkg.packageName); 5043 } else { 5044 done = null; 5045 } 5046 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 5047 } 5048 5049 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5050 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5051 Slog.w(TAG, "Unable to update from " + oldPkg.name 5052 + " to " + newPkg.packageName 5053 + ": old package not in system partition"); 5054 return false; 5055 } else if (mPackages.get(oldPkg.name) != null) { 5056 Slog.w(TAG, "Unable to update from " + oldPkg.name 5057 + " to " + newPkg.packageName 5058 + ": old package still exists"); 5059 return false; 5060 } 5061 return true; 5062 } 5063 5064 File getDataPathForUser(int userId) { 5065 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5066 } 5067 5068 private File getDataPathForPackage(String packageName, int userId) { 5069 /* 5070 * Until we fully support multiple users, return the directory we 5071 * previously would have. The PackageManagerTests will need to be 5072 * revised when this is changed back.. 5073 */ 5074 if (userId == 0) { 5075 return new File(mAppDataDir, packageName); 5076 } else { 5077 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5078 + File.separator + packageName); 5079 } 5080 } 5081 5082 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5083 int[] users = sUserManager.getUserIds(); 5084 int res = mInstaller.install(packageName, uid, uid, seinfo); 5085 if (res < 0) { 5086 return res; 5087 } 5088 for (int user : users) { 5089 if (user != 0) { 5090 res = mInstaller.createUserData(packageName, 5091 UserHandle.getUid(user, uid), user, seinfo); 5092 if (res < 0) { 5093 return res; 5094 } 5095 } 5096 } 5097 return res; 5098 } 5099 5100 private int removeDataDirsLI(String packageName) { 5101 int[] users = sUserManager.getUserIds(); 5102 int res = 0; 5103 for (int user : users) { 5104 int resInner = mInstaller.remove(packageName, user); 5105 if (resInner < 0) { 5106 res = resInner; 5107 } 5108 } 5109 5110 return res; 5111 } 5112 5113 private int deleteCodeCacheDirsLI(String packageName) { 5114 int[] users = sUserManager.getUserIds(); 5115 int res = 0; 5116 for (int user : users) { 5117 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5118 if (resInner < 0) { 5119 res = resInner; 5120 } 5121 } 5122 return res; 5123 } 5124 5125 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5126 PackageParser.Package changingLib) { 5127 if (file.path != null) { 5128 usesLibraryFiles.add(file.path); 5129 return; 5130 } 5131 PackageParser.Package p = mPackages.get(file.apk); 5132 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5133 // If we are doing this while in the middle of updating a library apk, 5134 // then we need to make sure to use that new apk for determining the 5135 // dependencies here. (We haven't yet finished committing the new apk 5136 // to the package manager state.) 5137 if (p == null || p.packageName.equals(changingLib.packageName)) { 5138 p = changingLib; 5139 } 5140 } 5141 if (p != null) { 5142 usesLibraryFiles.addAll(p.getAllCodePaths()); 5143 } 5144 } 5145 5146 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5147 PackageParser.Package changingLib) throws PackageManagerException { 5148 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5149 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5150 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5151 for (int i=0; i<N; i++) { 5152 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5153 if (file == null) { 5154 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5155 "Package " + pkg.packageName + " requires unavailable shared library " 5156 + pkg.usesLibraries.get(i) + "; failing!"); 5157 } 5158 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5159 } 5160 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5161 for (int i=0; i<N; i++) { 5162 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5163 if (file == null) { 5164 Slog.w(TAG, "Package " + pkg.packageName 5165 + " desires unavailable shared library " 5166 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5167 } else { 5168 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5169 } 5170 } 5171 N = usesLibraryFiles.size(); 5172 if (N > 0) { 5173 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5174 } else { 5175 pkg.usesLibraryFiles = null; 5176 } 5177 } 5178 } 5179 5180 private static boolean hasString(List<String> list, List<String> which) { 5181 if (list == null) { 5182 return false; 5183 } 5184 for (int i=list.size()-1; i>=0; i--) { 5185 for (int j=which.size()-1; j>=0; j--) { 5186 if (which.get(j).equals(list.get(i))) { 5187 return true; 5188 } 5189 } 5190 } 5191 return false; 5192 } 5193 5194 private void updateAllSharedLibrariesLPw() { 5195 for (PackageParser.Package pkg : mPackages.values()) { 5196 try { 5197 updateSharedLibrariesLPw(pkg, null); 5198 } catch (PackageManagerException e) { 5199 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5200 } 5201 } 5202 } 5203 5204 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5205 PackageParser.Package changingPkg) { 5206 ArrayList<PackageParser.Package> res = null; 5207 for (PackageParser.Package pkg : mPackages.values()) { 5208 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5209 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5210 if (res == null) { 5211 res = new ArrayList<PackageParser.Package>(); 5212 } 5213 res.add(pkg); 5214 try { 5215 updateSharedLibrariesLPw(pkg, changingPkg); 5216 } catch (PackageManagerException e) { 5217 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5218 } 5219 } 5220 } 5221 return res; 5222 } 5223 5224 /** 5225 * Derive the value of the {@code cpuAbiOverride} based on the provided 5226 * value and an optional stored value from the package settings. 5227 */ 5228 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5229 String cpuAbiOverride = null; 5230 5231 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5232 cpuAbiOverride = null; 5233 } else if (abiOverride != null) { 5234 cpuAbiOverride = abiOverride; 5235 } else if (settings != null) { 5236 cpuAbiOverride = settings.cpuAbiOverrideString; 5237 } 5238 5239 return cpuAbiOverride; 5240 } 5241 5242 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5243 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5244 boolean success = false; 5245 try { 5246 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5247 currentTime, user); 5248 success = true; 5249 return res; 5250 } finally { 5251 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5252 removeDataDirsLI(pkg.packageName); 5253 } 5254 } 5255 } 5256 5257 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5258 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5259 final File scanFile = new File(pkg.codePath); 5260 if (pkg.applicationInfo.getCodePath() == null || 5261 pkg.applicationInfo.getResourcePath() == null) { 5262 // Bail out. The resource and code paths haven't been set. 5263 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5264 "Code and resource paths haven't been set correctly"); 5265 } 5266 5267 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5268 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5269 } else { 5270 // Only allow system apps to be flagged as core apps. 5271 pkg.coreApp = false; 5272 } 5273 5274 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5275 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5276 } 5277 5278 if (mCustomResolverComponentName != null && 5279 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5280 setUpCustomResolverActivity(pkg); 5281 } 5282 5283 if (pkg.packageName.equals("android")) { 5284 synchronized (mPackages) { 5285 if (mAndroidApplication != null) { 5286 Slog.w(TAG, "*************************************************"); 5287 Slog.w(TAG, "Core android package being redefined. Skipping."); 5288 Slog.w(TAG, " file=" + scanFile); 5289 Slog.w(TAG, "*************************************************"); 5290 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5291 "Core android package being redefined. Skipping."); 5292 } 5293 5294 // Set up information for our fall-back user intent resolution activity. 5295 mPlatformPackage = pkg; 5296 pkg.mVersionCode = mSdkVersion; 5297 mAndroidApplication = pkg.applicationInfo; 5298 5299 if (!mResolverReplaced) { 5300 mResolveActivity.applicationInfo = mAndroidApplication; 5301 mResolveActivity.name = ResolverActivity.class.getName(); 5302 mResolveActivity.packageName = mAndroidApplication.packageName; 5303 mResolveActivity.processName = "system:ui"; 5304 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5305 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5306 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5307 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5308 mResolveActivity.exported = true; 5309 mResolveActivity.enabled = true; 5310 mResolveInfo.activityInfo = mResolveActivity; 5311 mResolveInfo.priority = 0; 5312 mResolveInfo.preferredOrder = 0; 5313 mResolveInfo.match = 0; 5314 mResolveComponentName = new ComponentName( 5315 mAndroidApplication.packageName, mResolveActivity.name); 5316 } 5317 } 5318 } 5319 5320 if (DEBUG_PACKAGE_SCANNING) { 5321 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5322 Log.d(TAG, "Scanning package " + pkg.packageName); 5323 } 5324 5325 if (mPackages.containsKey(pkg.packageName) 5326 || mSharedLibraries.containsKey(pkg.packageName)) { 5327 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5328 "Application package " + pkg.packageName 5329 + " already installed. Skipping duplicate."); 5330 } 5331 5332 // Initialize package source and resource directories 5333 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5334 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5335 5336 SharedUserSetting suid = null; 5337 PackageSetting pkgSetting = null; 5338 5339 if (!isSystemApp(pkg)) { 5340 // Only system apps can use these features. 5341 pkg.mOriginalPackages = null; 5342 pkg.mRealPackage = null; 5343 pkg.mAdoptPermissions = null; 5344 } 5345 5346 // writer 5347 synchronized (mPackages) { 5348 if (pkg.mSharedUserId != null) { 5349 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5350 if (suid == null) { 5351 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5352 "Creating application package " + pkg.packageName 5353 + " for shared user failed"); 5354 } 5355 if (DEBUG_PACKAGE_SCANNING) { 5356 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5357 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5358 + "): packages=" + suid.packages); 5359 } 5360 } 5361 5362 // Check if we are renaming from an original package name. 5363 PackageSetting origPackage = null; 5364 String realName = null; 5365 if (pkg.mOriginalPackages != null) { 5366 // This package may need to be renamed to a previously 5367 // installed name. Let's check on that... 5368 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5369 if (pkg.mOriginalPackages.contains(renamed)) { 5370 // This package had originally been installed as the 5371 // original name, and we have already taken care of 5372 // transitioning to the new one. Just update the new 5373 // one to continue using the old name. 5374 realName = pkg.mRealPackage; 5375 if (!pkg.packageName.equals(renamed)) { 5376 // Callers into this function may have already taken 5377 // care of renaming the package; only do it here if 5378 // it is not already done. 5379 pkg.setPackageName(renamed); 5380 } 5381 5382 } else { 5383 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5384 if ((origPackage = mSettings.peekPackageLPr( 5385 pkg.mOriginalPackages.get(i))) != null) { 5386 // We do have the package already installed under its 5387 // original name... should we use it? 5388 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5389 // New package is not compatible with original. 5390 origPackage = null; 5391 continue; 5392 } else if (origPackage.sharedUser != null) { 5393 // Make sure uid is compatible between packages. 5394 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5395 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5396 + " to " + pkg.packageName + ": old uid " 5397 + origPackage.sharedUser.name 5398 + " differs from " + pkg.mSharedUserId); 5399 origPackage = null; 5400 continue; 5401 } 5402 } else { 5403 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5404 + pkg.packageName + " to old name " + origPackage.name); 5405 } 5406 break; 5407 } 5408 } 5409 } 5410 } 5411 5412 if (mTransferedPackages.contains(pkg.packageName)) { 5413 Slog.w(TAG, "Package " + pkg.packageName 5414 + " was transferred to another, but its .apk remains"); 5415 } 5416 5417 // Just create the setting, don't add it yet. For already existing packages 5418 // the PkgSetting exists already and doesn't have to be created. 5419 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5420 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5421 pkg.applicationInfo.primaryCpuAbi, 5422 pkg.applicationInfo.secondaryCpuAbi, 5423 pkg.applicationInfo.flags, user, false); 5424 if (pkgSetting == null) { 5425 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5426 "Creating application package " + pkg.packageName + " failed"); 5427 } 5428 5429 if (pkgSetting.origPackage != null) { 5430 // If we are first transitioning from an original package, 5431 // fix up the new package's name now. We need to do this after 5432 // looking up the package under its new name, so getPackageLP 5433 // can take care of fiddling things correctly. 5434 pkg.setPackageName(origPackage.name); 5435 5436 // File a report about this. 5437 String msg = "New package " + pkgSetting.realName 5438 + " renamed to replace old package " + pkgSetting.name; 5439 reportSettingsProblem(Log.WARN, msg); 5440 5441 // Make a note of it. 5442 mTransferedPackages.add(origPackage.name); 5443 5444 // No longer need to retain this. 5445 pkgSetting.origPackage = null; 5446 } 5447 5448 if (realName != null) { 5449 // Make a note of it. 5450 mTransferedPackages.add(pkg.packageName); 5451 } 5452 5453 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5454 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5455 } 5456 5457 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5458 // Check all shared libraries and map to their actual file path. 5459 // We only do this here for apps not on a system dir, because those 5460 // are the only ones that can fail an install due to this. We 5461 // will take care of the system apps by updating all of their 5462 // library paths after the scan is done. 5463 updateSharedLibrariesLPw(pkg, null); 5464 } 5465 5466 if (mFoundPolicyFile) { 5467 SELinuxMMAC.assignSeinfoValue(pkg); 5468 } 5469 5470 pkg.applicationInfo.uid = pkgSetting.appId; 5471 pkg.mExtras = pkgSetting; 5472 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5473 try { 5474 verifySignaturesLP(pkgSetting, pkg); 5475 // We just determined the app is signed correctly, so bring 5476 // over the latest parsed certs. 5477 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5478 } catch (PackageManagerException e) { 5479 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5480 throw e; 5481 } 5482 // The signature has changed, but this package is in the system 5483 // image... let's recover! 5484 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5485 // However... if this package is part of a shared user, but it 5486 // doesn't match the signature of the shared user, let's fail. 5487 // What this means is that you can't change the signatures 5488 // associated with an overall shared user, which doesn't seem all 5489 // that unreasonable. 5490 if (pkgSetting.sharedUser != null) { 5491 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5492 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5493 throw new PackageManagerException( 5494 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5495 "Signature mismatch for shared user : " 5496 + pkgSetting.sharedUser); 5497 } 5498 } 5499 // File a report about this. 5500 String msg = "System package " + pkg.packageName 5501 + " signature changed; retaining data."; 5502 reportSettingsProblem(Log.WARN, msg); 5503 } 5504 } else { 5505 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5506 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5507 + pkg.packageName + " upgrade keys do not match the " 5508 + "previously installed version"); 5509 } else { 5510 // We just determined the app is signed correctly, so bring 5511 // over the latest parsed certs. 5512 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5513 } 5514 } 5515 // Verify that this new package doesn't have any content providers 5516 // that conflict with existing packages. Only do this if the 5517 // package isn't already installed, since we don't want to break 5518 // things that are installed. 5519 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5520 final int N = pkg.providers.size(); 5521 int i; 5522 for (i=0; i<N; i++) { 5523 PackageParser.Provider p = pkg.providers.get(i); 5524 if (p.info.authority != null) { 5525 String names[] = p.info.authority.split(";"); 5526 for (int j = 0; j < names.length; j++) { 5527 if (mProvidersByAuthority.containsKey(names[j])) { 5528 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5529 final String otherPackageName = 5530 ((other != null && other.getComponentName() != null) ? 5531 other.getComponentName().getPackageName() : "?"); 5532 throw new PackageManagerException( 5533 INSTALL_FAILED_CONFLICTING_PROVIDER, 5534 "Can't install because provider name " + names[j] 5535 + " (in package " + pkg.applicationInfo.packageName 5536 + ") is already used by " + otherPackageName); 5537 } 5538 } 5539 } 5540 } 5541 } 5542 5543 if (pkg.mAdoptPermissions != null) { 5544 // This package wants to adopt ownership of permissions from 5545 // another package. 5546 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5547 final String origName = pkg.mAdoptPermissions.get(i); 5548 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5549 if (orig != null) { 5550 if (verifyPackageUpdateLPr(orig, pkg)) { 5551 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5552 + pkg.packageName); 5553 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5554 } 5555 } 5556 } 5557 } 5558 } 5559 5560 final String pkgName = pkg.packageName; 5561 5562 final long scanFileTime = scanFile.lastModified(); 5563 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5564 pkg.applicationInfo.processName = fixProcessName( 5565 pkg.applicationInfo.packageName, 5566 pkg.applicationInfo.processName, 5567 pkg.applicationInfo.uid); 5568 5569 File dataPath; 5570 if (mPlatformPackage == pkg) { 5571 // The system package is special. 5572 dataPath = new File(Environment.getDataDirectory(), "system"); 5573 5574 pkg.applicationInfo.dataDir = dataPath.getPath(); 5575 5576 } else { 5577 // This is a normal package, need to make its data directory. 5578 dataPath = getDataPathForPackage(pkg.packageName, 0); 5579 5580 boolean uidError = false; 5581 if (dataPath.exists()) { 5582 int currentUid = 0; 5583 try { 5584 StructStat stat = Os.stat(dataPath.getPath()); 5585 currentUid = stat.st_uid; 5586 } catch (ErrnoException e) { 5587 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5588 } 5589 5590 // If we have mismatched owners for the data path, we have a problem. 5591 if (currentUid != pkg.applicationInfo.uid) { 5592 boolean recovered = false; 5593 if (currentUid == 0) { 5594 // The directory somehow became owned by root. Wow. 5595 // This is probably because the system was stopped while 5596 // installd was in the middle of messing with its libs 5597 // directory. Ask installd to fix that. 5598 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5599 pkg.applicationInfo.uid); 5600 if (ret >= 0) { 5601 recovered = true; 5602 String msg = "Package " + pkg.packageName 5603 + " unexpectedly changed to uid 0; recovered to " + 5604 + pkg.applicationInfo.uid; 5605 reportSettingsProblem(Log.WARN, msg); 5606 } 5607 } 5608 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5609 || (scanFlags&SCAN_BOOTING) != 0)) { 5610 // If this is a system app, we can at least delete its 5611 // current data so the application will still work. 5612 int ret = removeDataDirsLI(pkgName); 5613 if (ret >= 0) { 5614 // TODO: Kill the processes first 5615 // Old data gone! 5616 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5617 ? "System package " : "Third party package "; 5618 String msg = prefix + pkg.packageName 5619 + " has changed from uid: " 5620 + currentUid + " to " 5621 + pkg.applicationInfo.uid + "; old data erased"; 5622 reportSettingsProblem(Log.WARN, msg); 5623 recovered = true; 5624 5625 // And now re-install the app. 5626 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5627 pkg.applicationInfo.seinfo); 5628 if (ret == -1) { 5629 // Ack should not happen! 5630 msg = prefix + pkg.packageName 5631 + " could not have data directory re-created after delete."; 5632 reportSettingsProblem(Log.WARN, msg); 5633 throw new PackageManagerException( 5634 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5635 } 5636 } 5637 if (!recovered) { 5638 mHasSystemUidErrors = true; 5639 } 5640 } else if (!recovered) { 5641 // If we allow this install to proceed, we will be broken. 5642 // Abort, abort! 5643 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5644 "scanPackageLI"); 5645 } 5646 if (!recovered) { 5647 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5648 + pkg.applicationInfo.uid + "/fs_" 5649 + currentUid; 5650 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5651 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5652 String msg = "Package " + pkg.packageName 5653 + " has mismatched uid: " 5654 + currentUid + " on disk, " 5655 + pkg.applicationInfo.uid + " in settings"; 5656 // writer 5657 synchronized (mPackages) { 5658 mSettings.mReadMessages.append(msg); 5659 mSettings.mReadMessages.append('\n'); 5660 uidError = true; 5661 if (!pkgSetting.uidError) { 5662 reportSettingsProblem(Log.ERROR, msg); 5663 } 5664 } 5665 } 5666 } 5667 pkg.applicationInfo.dataDir = dataPath.getPath(); 5668 if (mShouldRestoreconData) { 5669 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5670 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5671 pkg.applicationInfo.uid); 5672 } 5673 } else { 5674 if (DEBUG_PACKAGE_SCANNING) { 5675 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5676 Log.v(TAG, "Want this data dir: " + dataPath); 5677 } 5678 //invoke installer to do the actual installation 5679 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5680 pkg.applicationInfo.seinfo); 5681 if (ret < 0) { 5682 // Error from installer 5683 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5684 "Unable to create data dirs [errorCode=" + ret + "]"); 5685 } 5686 5687 if (dataPath.exists()) { 5688 pkg.applicationInfo.dataDir = dataPath.getPath(); 5689 } else { 5690 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5691 pkg.applicationInfo.dataDir = null; 5692 } 5693 } 5694 5695 pkgSetting.uidError = uidError; 5696 } 5697 5698 final String path = scanFile.getPath(); 5699 final String codePath = pkg.applicationInfo.getCodePath(); 5700 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5701 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5702 setBundledAppAbisAndRoots(pkg, pkgSetting); 5703 5704 // If we haven't found any native libraries for the app, check if it has 5705 // renderscript code. We'll need to force the app to 32 bit if it has 5706 // renderscript bitcode. 5707 if (pkg.applicationInfo.primaryCpuAbi == null 5708 && pkg.applicationInfo.secondaryCpuAbi == null 5709 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5710 NativeLibraryHelper.Handle handle = null; 5711 try { 5712 handle = NativeLibraryHelper.Handle.create(scanFile); 5713 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5714 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5715 } 5716 } catch (IOException ioe) { 5717 Slog.w(TAG, "Error scanning system app : " + ioe); 5718 } finally { 5719 IoUtils.closeQuietly(handle); 5720 } 5721 } 5722 5723 setNativeLibraryPaths(pkg); 5724 } else { 5725 // TODO: We can probably be smarter about this stuff. For installed apps, 5726 // we can calculate this information at install time once and for all. For 5727 // system apps, we can probably assume that this information doesn't change 5728 // after the first boot scan. As things stand, we do lots of unnecessary work. 5729 5730 // Give ourselves some initial paths; we'll come back for another 5731 // pass once we've determined ABI below. 5732 setNativeLibraryPaths(pkg); 5733 5734 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5735 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5736 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5737 5738 NativeLibraryHelper.Handle handle = null; 5739 try { 5740 handle = NativeLibraryHelper.Handle.create(scanFile); 5741 // TODO(multiArch): This can be null for apps that didn't go through the 5742 // usual installation process. We can calculate it again, like we 5743 // do during install time. 5744 // 5745 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5746 // unnecessary. 5747 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5748 5749 // Null out the abis so that they can be recalculated. 5750 pkg.applicationInfo.primaryCpuAbi = null; 5751 pkg.applicationInfo.secondaryCpuAbi = null; 5752 if (isMultiArch(pkg.applicationInfo)) { 5753 // Warn if we've set an abiOverride for multi-lib packages.. 5754 // By definition, we need to copy both 32 and 64 bit libraries for 5755 // such packages. 5756 if (pkg.cpuAbiOverride != null 5757 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5758 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5759 } 5760 5761 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5762 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5763 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5764 if (isAsec) { 5765 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5766 } else { 5767 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5768 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5769 useIsaSpecificSubdirs); 5770 } 5771 } 5772 5773 maybeThrowExceptionForMultiArchCopy( 5774 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5775 5776 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5777 if (isAsec) { 5778 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5779 } else { 5780 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5781 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5782 useIsaSpecificSubdirs); 5783 } 5784 } 5785 5786 maybeThrowExceptionForMultiArchCopy( 5787 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5788 5789 if (abi64 >= 0) { 5790 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5791 } 5792 5793 if (abi32 >= 0) { 5794 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5795 if (abi64 >= 0) { 5796 pkg.applicationInfo.secondaryCpuAbi = abi; 5797 } else { 5798 pkg.applicationInfo.primaryCpuAbi = abi; 5799 } 5800 } 5801 } else { 5802 String[] abiList = (cpuAbiOverride != null) ? 5803 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5804 5805 // Enable gross and lame hacks for apps that are built with old 5806 // SDK tools. We must scan their APKs for renderscript bitcode and 5807 // not launch them if it's present. Don't bother checking on devices 5808 // that don't have 64 bit support. 5809 boolean needsRenderScriptOverride = false; 5810 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5811 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5812 abiList = Build.SUPPORTED_32_BIT_ABIS; 5813 needsRenderScriptOverride = true; 5814 } 5815 5816 final int copyRet; 5817 if (isAsec) { 5818 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5819 } else { 5820 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5821 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5822 } 5823 5824 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5825 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5826 "Error unpackaging native libs for app, errorCode=" + copyRet); 5827 } 5828 5829 if (copyRet >= 0) { 5830 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5831 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5832 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5833 } else if (needsRenderScriptOverride) { 5834 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5835 } 5836 } 5837 } catch (IOException ioe) { 5838 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5839 } finally { 5840 IoUtils.closeQuietly(handle); 5841 } 5842 5843 // Now that we've calculated the ABIs and determined if it's an internal app, 5844 // we will go ahead and populate the nativeLibraryPath. 5845 setNativeLibraryPaths(pkg); 5846 5847 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5848 final int[] userIds = sUserManager.getUserIds(); 5849 synchronized (mInstallLock) { 5850 // Create a native library symlink only if we have native libraries 5851 // and if the native libraries are 32 bit libraries. We do not provide 5852 // this symlink for 64 bit libraries. 5853 if (pkg.applicationInfo.primaryCpuAbi != null && 5854 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5855 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5856 for (int userId : userIds) { 5857 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5858 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5859 "Failed linking native library dir (user=" + userId + ")"); 5860 } 5861 } 5862 } 5863 } 5864 } 5865 5866 // This is a special case for the "system" package, where the ABI is 5867 // dictated by the zygote configuration (and init.rc). We should keep track 5868 // of this ABI so that we can deal with "normal" applications that run under 5869 // the same UID correctly. 5870 if (mPlatformPackage == pkg) { 5871 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5872 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5873 } 5874 5875 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5876 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5877 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5878 // Copy the derived override back to the parsed package, so that we can 5879 // update the package settings accordingly. 5880 pkg.cpuAbiOverride = cpuAbiOverride; 5881 5882 if (DEBUG_ABI_SELECTION) { 5883 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5884 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5885 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5886 } 5887 5888 // Push the derived path down into PackageSettings so we know what to 5889 // clean up at uninstall time. 5890 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5891 5892 if (DEBUG_ABI_SELECTION) { 5893 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5894 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5895 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5896 } 5897 5898 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5899 // We don't do this here during boot because we can do it all 5900 // at once after scanning all existing packages. 5901 // 5902 // We also do this *before* we perform dexopt on this package, so that 5903 // we can avoid redundant dexopts, and also to make sure we've got the 5904 // code and package path correct. 5905 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5906 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5907 } 5908 5909 if ((scanFlags & SCAN_NO_DEX) == 0) { 5910 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5911 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5912 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5913 } 5914 } 5915 5916 if (mFactoryTest && pkg.requestedPermissions.contains( 5917 android.Manifest.permission.FACTORY_TEST)) { 5918 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5919 } 5920 5921 ArrayList<PackageParser.Package> clientLibPkgs = null; 5922 5923 // writer 5924 synchronized (mPackages) { 5925 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5926 // Only system apps can add new shared libraries. 5927 if (pkg.libraryNames != null) { 5928 for (int i=0; i<pkg.libraryNames.size(); i++) { 5929 String name = pkg.libraryNames.get(i); 5930 boolean allowed = false; 5931 if (isUpdatedSystemApp(pkg)) { 5932 // New library entries can only be added through the 5933 // system image. This is important to get rid of a lot 5934 // of nasty edge cases: for example if we allowed a non- 5935 // system update of the app to add a library, then uninstalling 5936 // the update would make the library go away, and assumptions 5937 // we made such as through app install filtering would now 5938 // have allowed apps on the device which aren't compatible 5939 // with it. Better to just have the restriction here, be 5940 // conservative, and create many fewer cases that can negatively 5941 // impact the user experience. 5942 final PackageSetting sysPs = mSettings 5943 .getDisabledSystemPkgLPr(pkg.packageName); 5944 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5945 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5946 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5947 allowed = true; 5948 allowed = true; 5949 break; 5950 } 5951 } 5952 } 5953 } else { 5954 allowed = true; 5955 } 5956 if (allowed) { 5957 if (!mSharedLibraries.containsKey(name)) { 5958 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5959 } else if (!name.equals(pkg.packageName)) { 5960 Slog.w(TAG, "Package " + pkg.packageName + " library " 5961 + name + " already exists; skipping"); 5962 } 5963 } else { 5964 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5965 + name + " that is not declared on system image; skipping"); 5966 } 5967 } 5968 if ((scanFlags&SCAN_BOOTING) == 0) { 5969 // If we are not booting, we need to update any applications 5970 // that are clients of our shared library. If we are booting, 5971 // this will all be done once the scan is complete. 5972 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5973 } 5974 } 5975 } 5976 } 5977 5978 // We also need to dexopt any apps that are dependent on this library. Note that 5979 // if these fail, we should abort the install since installing the library will 5980 // result in some apps being broken. 5981 if (clientLibPkgs != null) { 5982 if ((scanFlags & SCAN_NO_DEX) == 0) { 5983 for (int i = 0; i < clientLibPkgs.size(); i++) { 5984 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5985 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5986 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5987 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5988 "scanPackageLI failed to dexopt clientLibPkgs"); 5989 } 5990 } 5991 } 5992 } 5993 5994 // Request the ActivityManager to kill the process(only for existing packages) 5995 // so that we do not end up in a confused state while the user is still using the older 5996 // version of the application while the new one gets installed. 5997 if ((scanFlags & SCAN_REPLACING) != 0) { 5998 killApplication(pkg.applicationInfo.packageName, 5999 pkg.applicationInfo.uid, "update pkg"); 6000 } 6001 6002 // Also need to kill any apps that are dependent on the library. 6003 if (clientLibPkgs != null) { 6004 for (int i=0; i<clientLibPkgs.size(); i++) { 6005 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6006 killApplication(clientPkg.applicationInfo.packageName, 6007 clientPkg.applicationInfo.uid, "update lib"); 6008 } 6009 } 6010 6011 // writer 6012 synchronized (mPackages) { 6013 // We don't expect installation to fail beyond this point 6014 6015 // Add the new setting to mSettings 6016 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6017 // Add the new setting to mPackages 6018 mPackages.put(pkg.applicationInfo.packageName, pkg); 6019 // Make sure we don't accidentally delete its data. 6020 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6021 while (iter.hasNext()) { 6022 PackageCleanItem item = iter.next(); 6023 if (pkgName.equals(item.packageName)) { 6024 iter.remove(); 6025 } 6026 } 6027 6028 // Take care of first install / last update times. 6029 if (currentTime != 0) { 6030 if (pkgSetting.firstInstallTime == 0) { 6031 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6032 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6033 pkgSetting.lastUpdateTime = currentTime; 6034 } 6035 } else if (pkgSetting.firstInstallTime == 0) { 6036 // We need *something*. Take time time stamp of the file. 6037 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6038 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6039 if (scanFileTime != pkgSetting.timeStamp) { 6040 // A package on the system image has changed; consider this 6041 // to be an update. 6042 pkgSetting.lastUpdateTime = scanFileTime; 6043 } 6044 } 6045 6046 // Add the package's KeySets to the global KeySetManagerService 6047 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6048 try { 6049 // Old KeySetData no longer valid. 6050 ksms.removeAppKeySetDataLPw(pkg.packageName); 6051 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6052 if (pkg.mKeySetMapping != null) { 6053 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6054 pkg.mKeySetMapping.entrySet()) { 6055 if (entry.getValue() != null) { 6056 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6057 entry.getValue(), entry.getKey()); 6058 } 6059 } 6060 if (pkg.mUpgradeKeySets != null) { 6061 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6062 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6063 } 6064 } 6065 } 6066 } catch (NullPointerException e) { 6067 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6068 } catch (IllegalArgumentException e) { 6069 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6070 } 6071 6072 int N = pkg.providers.size(); 6073 StringBuilder r = null; 6074 int i; 6075 for (i=0; i<N; i++) { 6076 PackageParser.Provider p = pkg.providers.get(i); 6077 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6078 p.info.processName, pkg.applicationInfo.uid); 6079 mProviders.addProvider(p); 6080 p.syncable = p.info.isSyncable; 6081 if (p.info.authority != null) { 6082 String names[] = p.info.authority.split(";"); 6083 p.info.authority = null; 6084 for (int j = 0; j < names.length; j++) { 6085 if (j == 1 && p.syncable) { 6086 // We only want the first authority for a provider to possibly be 6087 // syncable, so if we already added this provider using a different 6088 // authority clear the syncable flag. We copy the provider before 6089 // changing it because the mProviders object contains a reference 6090 // to a provider that we don't want to change. 6091 // Only do this for the second authority since the resulting provider 6092 // object can be the same for all future authorities for this provider. 6093 p = new PackageParser.Provider(p); 6094 p.syncable = false; 6095 } 6096 if (!mProvidersByAuthority.containsKey(names[j])) { 6097 mProvidersByAuthority.put(names[j], p); 6098 if (p.info.authority == null) { 6099 p.info.authority = names[j]; 6100 } else { 6101 p.info.authority = p.info.authority + ";" + names[j]; 6102 } 6103 if (DEBUG_PACKAGE_SCANNING) { 6104 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6105 Log.d(TAG, "Registered content provider: " + names[j] 6106 + ", className = " + p.info.name + ", isSyncable = " 6107 + p.info.isSyncable); 6108 } 6109 } else { 6110 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6111 Slog.w(TAG, "Skipping provider name " + names[j] + 6112 " (in package " + pkg.applicationInfo.packageName + 6113 "): name already used by " 6114 + ((other != null && other.getComponentName() != null) 6115 ? other.getComponentName().getPackageName() : "?")); 6116 } 6117 } 6118 } 6119 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6120 if (r == null) { 6121 r = new StringBuilder(256); 6122 } else { 6123 r.append(' '); 6124 } 6125 r.append(p.info.name); 6126 } 6127 } 6128 if (r != null) { 6129 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6130 } 6131 6132 N = pkg.services.size(); 6133 r = null; 6134 for (i=0; i<N; i++) { 6135 PackageParser.Service s = pkg.services.get(i); 6136 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6137 s.info.processName, pkg.applicationInfo.uid); 6138 mServices.addService(s); 6139 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6140 if (r == null) { 6141 r = new StringBuilder(256); 6142 } else { 6143 r.append(' '); 6144 } 6145 r.append(s.info.name); 6146 } 6147 } 6148 if (r != null) { 6149 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6150 } 6151 6152 N = pkg.receivers.size(); 6153 r = null; 6154 for (i=0; i<N; i++) { 6155 PackageParser.Activity a = pkg.receivers.get(i); 6156 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6157 a.info.processName, pkg.applicationInfo.uid); 6158 mReceivers.addActivity(a, "receiver"); 6159 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6160 if (r == null) { 6161 r = new StringBuilder(256); 6162 } else { 6163 r.append(' '); 6164 } 6165 r.append(a.info.name); 6166 } 6167 } 6168 if (r != null) { 6169 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6170 } 6171 6172 N = pkg.activities.size(); 6173 r = null; 6174 for (i=0; i<N; i++) { 6175 PackageParser.Activity a = pkg.activities.get(i); 6176 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6177 a.info.processName, pkg.applicationInfo.uid); 6178 mActivities.addActivity(a, "activity"); 6179 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6180 if (r == null) { 6181 r = new StringBuilder(256); 6182 } else { 6183 r.append(' '); 6184 } 6185 r.append(a.info.name); 6186 } 6187 } 6188 if (r != null) { 6189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6190 } 6191 6192 N = pkg.permissionGroups.size(); 6193 r = null; 6194 for (i=0; i<N; i++) { 6195 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6196 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6197 if (cur == null) { 6198 mPermissionGroups.put(pg.info.name, pg); 6199 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6200 if (r == null) { 6201 r = new StringBuilder(256); 6202 } else { 6203 r.append(' '); 6204 } 6205 r.append(pg.info.name); 6206 } 6207 } else { 6208 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6209 + pg.info.packageName + " ignored: original from " 6210 + cur.info.packageName); 6211 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6212 if (r == null) { 6213 r = new StringBuilder(256); 6214 } else { 6215 r.append(' '); 6216 } 6217 r.append("DUP:"); 6218 r.append(pg.info.name); 6219 } 6220 } 6221 } 6222 if (r != null) { 6223 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6224 } 6225 6226 N = pkg.permissions.size(); 6227 r = null; 6228 for (i=0; i<N; i++) { 6229 PackageParser.Permission p = pkg.permissions.get(i); 6230 HashMap<String, BasePermission> permissionMap = 6231 p.tree ? mSettings.mPermissionTrees 6232 : mSettings.mPermissions; 6233 p.group = mPermissionGroups.get(p.info.group); 6234 if (p.info.group == null || p.group != null) { 6235 BasePermission bp = permissionMap.get(p.info.name); 6236 6237 // Allow system apps to redefine non-system permissions 6238 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6239 final boolean currentOwnerIsSystem = (bp.perm != null 6240 && isSystemApp(bp.perm.owner)); 6241 if (isSystemApp(p.owner)) { 6242 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6243 // It's a built-in permission and no owner, take ownership now 6244 bp.packageSetting = pkgSetting; 6245 bp.perm = p; 6246 bp.uid = pkg.applicationInfo.uid; 6247 bp.sourcePackage = p.info.packageName; 6248 } else if (!currentOwnerIsSystem) { 6249 String msg = "New decl " + p.owner + " of permission " 6250 + p.info.name + " is system; overriding " + bp.sourcePackage; 6251 reportSettingsProblem(Log.WARN, msg); 6252 bp = null; 6253 } 6254 } 6255 } 6256 6257 if (bp == null) { 6258 bp = new BasePermission(p.info.name, p.info.packageName, 6259 BasePermission.TYPE_NORMAL); 6260 permissionMap.put(p.info.name, bp); 6261 } 6262 6263 if (bp.perm == null) { 6264 if (bp.sourcePackage == null 6265 || bp.sourcePackage.equals(p.info.packageName)) { 6266 BasePermission tree = findPermissionTreeLP(p.info.name); 6267 if (tree == null 6268 || tree.sourcePackage.equals(p.info.packageName)) { 6269 bp.packageSetting = pkgSetting; 6270 bp.perm = p; 6271 bp.uid = pkg.applicationInfo.uid; 6272 bp.sourcePackage = p.info.packageName; 6273 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6274 if (r == null) { 6275 r = new StringBuilder(256); 6276 } else { 6277 r.append(' '); 6278 } 6279 r.append(p.info.name); 6280 } 6281 } else { 6282 Slog.w(TAG, "Permission " + p.info.name + " from package " 6283 + p.info.packageName + " ignored: base tree " 6284 + tree.name + " is from package " 6285 + tree.sourcePackage); 6286 } 6287 } else { 6288 Slog.w(TAG, "Permission " + p.info.name + " from package " 6289 + p.info.packageName + " ignored: original from " 6290 + bp.sourcePackage); 6291 } 6292 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6293 if (r == null) { 6294 r = new StringBuilder(256); 6295 } else { 6296 r.append(' '); 6297 } 6298 r.append("DUP:"); 6299 r.append(p.info.name); 6300 } 6301 if (bp.perm == p) { 6302 bp.protectionLevel = p.info.protectionLevel; 6303 } 6304 } else { 6305 Slog.w(TAG, "Permission " + p.info.name + " from package " 6306 + p.info.packageName + " ignored: no group " 6307 + p.group); 6308 } 6309 } 6310 if (r != null) { 6311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6312 } 6313 6314 N = pkg.instrumentation.size(); 6315 r = null; 6316 for (i=0; i<N; i++) { 6317 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6318 a.info.packageName = pkg.applicationInfo.packageName; 6319 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6320 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6321 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6322 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6323 a.info.dataDir = pkg.applicationInfo.dataDir; 6324 6325 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6326 // need other information about the application, like the ABI and what not ? 6327 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6328 mInstrumentation.put(a.getComponentName(), a); 6329 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6330 if (r == null) { 6331 r = new StringBuilder(256); 6332 } else { 6333 r.append(' '); 6334 } 6335 r.append(a.info.name); 6336 } 6337 } 6338 if (r != null) { 6339 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6340 } 6341 6342 if (pkg.protectedBroadcasts != null) { 6343 N = pkg.protectedBroadcasts.size(); 6344 for (i=0; i<N; i++) { 6345 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6346 } 6347 } 6348 6349 pkgSetting.setTimeStamp(scanFileTime); 6350 6351 // Create idmap files for pairs of (packages, overlay packages). 6352 // Note: "android", ie framework-res.apk, is handled by native layers. 6353 if (pkg.mOverlayTarget != null) { 6354 // This is an overlay package. 6355 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6356 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6357 mOverlays.put(pkg.mOverlayTarget, 6358 new HashMap<String, PackageParser.Package>()); 6359 } 6360 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6361 map.put(pkg.packageName, pkg); 6362 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6363 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6364 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6365 "scanPackageLI failed to createIdmap"); 6366 } 6367 } 6368 } else if (mOverlays.containsKey(pkg.packageName) && 6369 !pkg.packageName.equals("android")) { 6370 // This is a regular package, with one or more known overlay packages. 6371 createIdmapsForPackageLI(pkg); 6372 } 6373 } 6374 6375 return pkg; 6376 } 6377 6378 /** 6379 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6380 * i.e, so that all packages can be run inside a single process if required. 6381 * 6382 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6383 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6384 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6385 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6386 * updating a package that belongs to a shared user. 6387 * 6388 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6389 * adds unnecessary complexity. 6390 */ 6391 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6392 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6393 String requiredInstructionSet = null; 6394 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6395 requiredInstructionSet = VMRuntime.getInstructionSet( 6396 scannedPackage.applicationInfo.primaryCpuAbi); 6397 } 6398 6399 PackageSetting requirer = null; 6400 for (PackageSetting ps : packagesForUser) { 6401 // If packagesForUser contains scannedPackage, we skip it. This will happen 6402 // when scannedPackage is an update of an existing package. Without this check, 6403 // we will never be able to change the ABI of any package belonging to a shared 6404 // user, even if it's compatible with other packages. 6405 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6406 if (ps.primaryCpuAbiString == null) { 6407 continue; 6408 } 6409 6410 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6411 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6412 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6413 // this but there's not much we can do. 6414 String errorMessage = "Instruction set mismatch, " 6415 + ((requirer == null) ? "[caller]" : requirer) 6416 + " requires " + requiredInstructionSet + " whereas " + ps 6417 + " requires " + instructionSet; 6418 Slog.w(TAG, errorMessage); 6419 } 6420 6421 if (requiredInstructionSet == null) { 6422 requiredInstructionSet = instructionSet; 6423 requirer = ps; 6424 } 6425 } 6426 } 6427 6428 if (requiredInstructionSet != null) { 6429 String adjustedAbi; 6430 if (requirer != null) { 6431 // requirer != null implies that either scannedPackage was null or that scannedPackage 6432 // did not require an ABI, in which case we have to adjust scannedPackage to match 6433 // the ABI of the set (which is the same as requirer's ABI) 6434 adjustedAbi = requirer.primaryCpuAbiString; 6435 if (scannedPackage != null) { 6436 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6437 } 6438 } else { 6439 // requirer == null implies that we're updating all ABIs in the set to 6440 // match scannedPackage. 6441 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6442 } 6443 6444 for (PackageSetting ps : packagesForUser) { 6445 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6446 if (ps.primaryCpuAbiString != null) { 6447 continue; 6448 } 6449 6450 ps.primaryCpuAbiString = adjustedAbi; 6451 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6452 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6453 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6454 6455 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6456 deferDexOpt, true) == DEX_OPT_FAILED) { 6457 ps.primaryCpuAbiString = null; 6458 ps.pkg.applicationInfo.primaryCpuAbi = null; 6459 return; 6460 } else { 6461 mInstaller.rmdex(ps.codePathString, 6462 getDexCodeInstructionSet(getPreferredInstructionSet())); 6463 } 6464 } 6465 } 6466 } 6467 } 6468 } 6469 6470 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6471 synchronized (mPackages) { 6472 mResolverReplaced = true; 6473 // Set up information for custom user intent resolution activity. 6474 mResolveActivity.applicationInfo = pkg.applicationInfo; 6475 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6476 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6477 mResolveActivity.processName = null; 6478 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6479 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6480 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6481 mResolveActivity.theme = 0; 6482 mResolveActivity.exported = true; 6483 mResolveActivity.enabled = true; 6484 mResolveInfo.activityInfo = mResolveActivity; 6485 mResolveInfo.priority = 0; 6486 mResolveInfo.preferredOrder = 0; 6487 mResolveInfo.match = 0; 6488 mResolveComponentName = mCustomResolverComponentName; 6489 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6490 mResolveComponentName); 6491 } 6492 } 6493 6494 private static String calculateBundledApkRoot(final String codePathString) { 6495 final File codePath = new File(codePathString); 6496 final File codeRoot; 6497 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6498 codeRoot = Environment.getRootDirectory(); 6499 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6500 codeRoot = Environment.getOemDirectory(); 6501 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6502 codeRoot = Environment.getVendorDirectory(); 6503 } else { 6504 // Unrecognized code path; take its top real segment as the apk root: 6505 // e.g. /something/app/blah.apk => /something 6506 try { 6507 File f = codePath.getCanonicalFile(); 6508 File parent = f.getParentFile(); // non-null because codePath is a file 6509 File tmp; 6510 while ((tmp = parent.getParentFile()) != null) { 6511 f = parent; 6512 parent = tmp; 6513 } 6514 codeRoot = f; 6515 Slog.w(TAG, "Unrecognized code path " 6516 + codePath + " - using " + codeRoot); 6517 } catch (IOException e) { 6518 // Can't canonicalize the code path -- shenanigans? 6519 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6520 return Environment.getRootDirectory().getPath(); 6521 } 6522 } 6523 return codeRoot.getPath(); 6524 } 6525 6526 /** 6527 * Derive and set the location of native libraries for the given package, 6528 * which varies depending on where and how the package was installed. 6529 */ 6530 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6531 final ApplicationInfo info = pkg.applicationInfo; 6532 final String codePath = pkg.codePath; 6533 final File codeFile = new File(codePath); 6534 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6535 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6536 6537 info.nativeLibraryRootDir = null; 6538 info.nativeLibraryRootRequiresIsa = false; 6539 info.nativeLibraryDir = null; 6540 info.secondaryNativeLibraryDir = null; 6541 6542 if (isApkFile(codeFile)) { 6543 // Monolithic install 6544 if (bundledApp) { 6545 // If "/system/lib64/apkname" exists, assume that is the per-package 6546 // native library directory to use; otherwise use "/system/lib/apkname". 6547 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6548 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6549 getPrimaryInstructionSet(info)); 6550 6551 // This is a bundled system app so choose the path based on the ABI. 6552 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6553 // is just the default path. 6554 final String apkName = deriveCodePathName(codePath); 6555 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6556 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6557 apkName).getAbsolutePath(); 6558 6559 if (info.secondaryCpuAbi != null) { 6560 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6561 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6562 secondaryLibDir, apkName).getAbsolutePath(); 6563 } 6564 } else if (asecApp) { 6565 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6566 .getAbsolutePath(); 6567 } else { 6568 final String apkName = deriveCodePathName(codePath); 6569 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6570 .getAbsolutePath(); 6571 } 6572 6573 info.nativeLibraryRootRequiresIsa = false; 6574 info.nativeLibraryDir = info.nativeLibraryRootDir; 6575 } else { 6576 // Cluster install 6577 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6578 info.nativeLibraryRootRequiresIsa = true; 6579 6580 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6581 getPrimaryInstructionSet(info)).getAbsolutePath(); 6582 6583 if (info.secondaryCpuAbi != null) { 6584 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6585 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6586 } 6587 } 6588 } 6589 6590 /** 6591 * Calculate the abis and roots for a bundled app. These can uniquely 6592 * be determined from the contents of the system partition, i.e whether 6593 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6594 * of this information, and instead assume that the system was built 6595 * sensibly. 6596 */ 6597 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6598 PackageSetting pkgSetting) { 6599 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6600 6601 // If "/system/lib64/apkname" exists, assume that is the per-package 6602 // native library directory to use; otherwise use "/system/lib/apkname". 6603 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6604 setBundledAppAbi(pkg, apkRoot, apkName); 6605 // pkgSetting might be null during rescan following uninstall of updates 6606 // to a bundled app, so accommodate that possibility. The settings in 6607 // that case will be established later from the parsed package. 6608 // 6609 // If the settings aren't null, sync them up with what we've just derived. 6610 // note that apkRoot isn't stored in the package settings. 6611 if (pkgSetting != null) { 6612 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6613 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6614 } 6615 } 6616 6617 /** 6618 * Deduces the ABI of a bundled app and sets the relevant fields on the 6619 * parsed pkg object. 6620 * 6621 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6622 * under which system libraries are installed. 6623 * @param apkName the name of the installed package. 6624 */ 6625 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6626 final File codeFile = new File(pkg.codePath); 6627 6628 final boolean has64BitLibs; 6629 final boolean has32BitLibs; 6630 if (isApkFile(codeFile)) { 6631 // Monolithic install 6632 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6633 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6634 } else { 6635 // Cluster install 6636 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6637 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6638 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6639 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6640 has64BitLibs = (new File(rootDir, isa)).exists(); 6641 } else { 6642 has64BitLibs = false; 6643 } 6644 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6645 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6646 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6647 has32BitLibs = (new File(rootDir, isa)).exists(); 6648 } else { 6649 has32BitLibs = false; 6650 } 6651 } 6652 6653 if (has64BitLibs && !has32BitLibs) { 6654 // The package has 64 bit libs, but not 32 bit libs. Its primary 6655 // ABI should be 64 bit. We can safely assume here that the bundled 6656 // native libraries correspond to the most preferred ABI in the list. 6657 6658 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6659 pkg.applicationInfo.secondaryCpuAbi = null; 6660 } else if (has32BitLibs && !has64BitLibs) { 6661 // The package has 32 bit libs but not 64 bit libs. Its primary 6662 // ABI should be 32 bit. 6663 6664 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6665 pkg.applicationInfo.secondaryCpuAbi = null; 6666 } else if (has32BitLibs && has64BitLibs) { 6667 // The application has both 64 and 32 bit bundled libraries. We check 6668 // here that the app declares multiArch support, and warn if it doesn't. 6669 // 6670 // We will be lenient here and record both ABIs. The primary will be the 6671 // ABI that's higher on the list, i.e, a device that's configured to prefer 6672 // 64 bit apps will see a 64 bit primary ABI, 6673 6674 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6675 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6676 } 6677 6678 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6679 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6680 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6681 } else { 6682 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6683 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6684 } 6685 } else { 6686 pkg.applicationInfo.primaryCpuAbi = null; 6687 pkg.applicationInfo.secondaryCpuAbi = null; 6688 } 6689 } 6690 6691 private void killApplication(String pkgName, int appId, String reason) { 6692 // Request the ActivityManager to kill the process(only for existing packages) 6693 // so that we do not end up in a confused state while the user is still using the older 6694 // version of the application while the new one gets installed. 6695 IActivityManager am = ActivityManagerNative.getDefault(); 6696 if (am != null) { 6697 try { 6698 am.killApplicationWithAppId(pkgName, appId, reason); 6699 } catch (RemoteException e) { 6700 } 6701 } 6702 } 6703 6704 void removePackageLI(PackageSetting ps, boolean chatty) { 6705 if (DEBUG_INSTALL) { 6706 if (chatty) 6707 Log.d(TAG, "Removing package " + ps.name); 6708 } 6709 6710 // writer 6711 synchronized (mPackages) { 6712 mPackages.remove(ps.name); 6713 final PackageParser.Package pkg = ps.pkg; 6714 if (pkg != null) { 6715 cleanPackageDataStructuresLILPw(pkg, chatty); 6716 } 6717 } 6718 } 6719 6720 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6721 if (DEBUG_INSTALL) { 6722 if (chatty) 6723 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6724 } 6725 6726 // writer 6727 synchronized (mPackages) { 6728 mPackages.remove(pkg.applicationInfo.packageName); 6729 cleanPackageDataStructuresLILPw(pkg, chatty); 6730 } 6731 } 6732 6733 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6734 int N = pkg.providers.size(); 6735 StringBuilder r = null; 6736 int i; 6737 for (i=0; i<N; i++) { 6738 PackageParser.Provider p = pkg.providers.get(i); 6739 mProviders.removeProvider(p); 6740 if (p.info.authority == null) { 6741 6742 /* There was another ContentProvider with this authority when 6743 * this app was installed so this authority is null, 6744 * Ignore it as we don't have to unregister the provider. 6745 */ 6746 continue; 6747 } 6748 String names[] = p.info.authority.split(";"); 6749 for (int j = 0; j < names.length; j++) { 6750 if (mProvidersByAuthority.get(names[j]) == p) { 6751 mProvidersByAuthority.remove(names[j]); 6752 if (DEBUG_REMOVE) { 6753 if (chatty) 6754 Log.d(TAG, "Unregistered content provider: " + names[j] 6755 + ", className = " + p.info.name + ", isSyncable = " 6756 + p.info.isSyncable); 6757 } 6758 } 6759 } 6760 if (DEBUG_REMOVE && chatty) { 6761 if (r == null) { 6762 r = new StringBuilder(256); 6763 } else { 6764 r.append(' '); 6765 } 6766 r.append(p.info.name); 6767 } 6768 } 6769 if (r != null) { 6770 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6771 } 6772 6773 N = pkg.services.size(); 6774 r = null; 6775 for (i=0; i<N; i++) { 6776 PackageParser.Service s = pkg.services.get(i); 6777 mServices.removeService(s); 6778 if (chatty) { 6779 if (r == null) { 6780 r = new StringBuilder(256); 6781 } else { 6782 r.append(' '); 6783 } 6784 r.append(s.info.name); 6785 } 6786 } 6787 if (r != null) { 6788 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6789 } 6790 6791 N = pkg.receivers.size(); 6792 r = null; 6793 for (i=0; i<N; i++) { 6794 PackageParser.Activity a = pkg.receivers.get(i); 6795 mReceivers.removeActivity(a, "receiver"); 6796 if (DEBUG_REMOVE && chatty) { 6797 if (r == null) { 6798 r = new StringBuilder(256); 6799 } else { 6800 r.append(' '); 6801 } 6802 r.append(a.info.name); 6803 } 6804 } 6805 if (r != null) { 6806 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6807 } 6808 6809 N = pkg.activities.size(); 6810 r = null; 6811 for (i=0; i<N; i++) { 6812 PackageParser.Activity a = pkg.activities.get(i); 6813 mActivities.removeActivity(a, "activity"); 6814 if (DEBUG_REMOVE && chatty) { 6815 if (r == null) { 6816 r = new StringBuilder(256); 6817 } else { 6818 r.append(' '); 6819 } 6820 r.append(a.info.name); 6821 } 6822 } 6823 if (r != null) { 6824 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6825 } 6826 6827 N = pkg.permissions.size(); 6828 r = null; 6829 for (i=0; i<N; i++) { 6830 PackageParser.Permission p = pkg.permissions.get(i); 6831 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6832 if (bp == null) { 6833 bp = mSettings.mPermissionTrees.get(p.info.name); 6834 } 6835 if (bp != null && bp.perm == p) { 6836 bp.perm = null; 6837 if (DEBUG_REMOVE && chatty) { 6838 if (r == null) { 6839 r = new StringBuilder(256); 6840 } else { 6841 r.append(' '); 6842 } 6843 r.append(p.info.name); 6844 } 6845 } 6846 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6847 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6848 if (appOpPerms != null) { 6849 appOpPerms.remove(pkg.packageName); 6850 } 6851 } 6852 } 6853 if (r != null) { 6854 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6855 } 6856 6857 N = pkg.requestedPermissions.size(); 6858 r = null; 6859 for (i=0; i<N; i++) { 6860 String perm = pkg.requestedPermissions.get(i); 6861 BasePermission bp = mSettings.mPermissions.get(perm); 6862 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6863 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6864 if (appOpPerms != null) { 6865 appOpPerms.remove(pkg.packageName); 6866 if (appOpPerms.isEmpty()) { 6867 mAppOpPermissionPackages.remove(perm); 6868 } 6869 } 6870 } 6871 } 6872 if (r != null) { 6873 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6874 } 6875 6876 N = pkg.instrumentation.size(); 6877 r = null; 6878 for (i=0; i<N; i++) { 6879 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6880 mInstrumentation.remove(a.getComponentName()); 6881 if (DEBUG_REMOVE && chatty) { 6882 if (r == null) { 6883 r = new StringBuilder(256); 6884 } else { 6885 r.append(' '); 6886 } 6887 r.append(a.info.name); 6888 } 6889 } 6890 if (r != null) { 6891 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6892 } 6893 6894 r = null; 6895 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6896 // Only system apps can hold shared libraries. 6897 if (pkg.libraryNames != null) { 6898 for (i=0; i<pkg.libraryNames.size(); i++) { 6899 String name = pkg.libraryNames.get(i); 6900 SharedLibraryEntry cur = mSharedLibraries.get(name); 6901 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6902 mSharedLibraries.remove(name); 6903 if (DEBUG_REMOVE && chatty) { 6904 if (r == null) { 6905 r = new StringBuilder(256); 6906 } else { 6907 r.append(' '); 6908 } 6909 r.append(name); 6910 } 6911 } 6912 } 6913 } 6914 } 6915 if (r != null) { 6916 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6917 } 6918 } 6919 6920 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6921 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6922 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6923 return true; 6924 } 6925 } 6926 return false; 6927 } 6928 6929 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6930 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6931 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6932 6933 private void updatePermissionsLPw(String changingPkg, 6934 PackageParser.Package pkgInfo, int flags) { 6935 // Make sure there are no dangling permission trees. 6936 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6937 while (it.hasNext()) { 6938 final BasePermission bp = it.next(); 6939 if (bp.packageSetting == null) { 6940 // We may not yet have parsed the package, so just see if 6941 // we still know about its settings. 6942 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6943 } 6944 if (bp.packageSetting == null) { 6945 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6946 + " from package " + bp.sourcePackage); 6947 it.remove(); 6948 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6949 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6950 Slog.i(TAG, "Removing old permission tree: " + bp.name 6951 + " from package " + bp.sourcePackage); 6952 flags |= UPDATE_PERMISSIONS_ALL; 6953 it.remove(); 6954 } 6955 } 6956 } 6957 6958 // Make sure all dynamic permissions have been assigned to a package, 6959 // and make sure there are no dangling permissions. 6960 it = mSettings.mPermissions.values().iterator(); 6961 while (it.hasNext()) { 6962 final BasePermission bp = it.next(); 6963 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6964 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6965 + bp.name + " pkg=" + bp.sourcePackage 6966 + " info=" + bp.pendingInfo); 6967 if (bp.packageSetting == null && bp.pendingInfo != null) { 6968 final BasePermission tree = findPermissionTreeLP(bp.name); 6969 if (tree != null && tree.perm != null) { 6970 bp.packageSetting = tree.packageSetting; 6971 bp.perm = new PackageParser.Permission(tree.perm.owner, 6972 new PermissionInfo(bp.pendingInfo)); 6973 bp.perm.info.packageName = tree.perm.info.packageName; 6974 bp.perm.info.name = bp.name; 6975 bp.uid = tree.uid; 6976 } 6977 } 6978 } 6979 if (bp.packageSetting == null) { 6980 // We may not yet have parsed the package, so just see if 6981 // we still know about its settings. 6982 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6983 } 6984 if (bp.packageSetting == null) { 6985 Slog.w(TAG, "Removing dangling permission: " + bp.name 6986 + " from package " + bp.sourcePackage); 6987 it.remove(); 6988 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6989 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6990 Slog.i(TAG, "Removing old permission: " + bp.name 6991 + " from package " + bp.sourcePackage); 6992 flags |= UPDATE_PERMISSIONS_ALL; 6993 it.remove(); 6994 } 6995 } 6996 } 6997 6998 // Now update the permissions for all packages, in particular 6999 // replace the granted permissions of the system packages. 7000 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7001 for (PackageParser.Package pkg : mPackages.values()) { 7002 if (pkg != pkgInfo) { 7003 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7004 changingPkg); 7005 } 7006 } 7007 } 7008 7009 if (pkgInfo != null) { 7010 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7011 } 7012 } 7013 7014 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7015 String packageOfInterest) { 7016 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7017 if (ps == null) { 7018 return; 7019 } 7020 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 7021 HashSet<String> origPermissions = gp.grantedPermissions; 7022 boolean changedPermission = false; 7023 7024 if (replace) { 7025 ps.permissionsFixed = false; 7026 if (gp == ps) { 7027 origPermissions = new HashSet<String>(gp.grantedPermissions); 7028 gp.grantedPermissions.clear(); 7029 gp.gids = mGlobalGids; 7030 } 7031 } 7032 7033 if (gp.gids == null) { 7034 gp.gids = mGlobalGids; 7035 } 7036 7037 final int N = pkg.requestedPermissions.size(); 7038 for (int i=0; i<N; i++) { 7039 final String name = pkg.requestedPermissions.get(i); 7040 final boolean required = pkg.requestedPermissionsRequired.get(i); 7041 final BasePermission bp = mSettings.mPermissions.get(name); 7042 if (DEBUG_INSTALL) { 7043 if (gp != ps) { 7044 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7045 } 7046 } 7047 7048 if (bp == null || bp.packageSetting == null) { 7049 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7050 Slog.w(TAG, "Unknown permission " + name 7051 + " in package " + pkg.packageName); 7052 } 7053 continue; 7054 } 7055 7056 final String perm = bp.name; 7057 boolean allowed; 7058 boolean allowedSig = false; 7059 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7060 // Keep track of app op permissions. 7061 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7062 if (pkgs == null) { 7063 pkgs = new ArraySet<>(); 7064 mAppOpPermissionPackages.put(bp.name, pkgs); 7065 } 7066 pkgs.add(pkg.packageName); 7067 } 7068 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7069 if (level == PermissionInfo.PROTECTION_NORMAL 7070 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7071 // We grant a normal or dangerous permission if any of the following 7072 // are true: 7073 // 1) The permission is required 7074 // 2) The permission is optional, but was granted in the past 7075 // 3) The permission is optional, but was requested by an 7076 // app in /system (not /data) 7077 // 7078 // Otherwise, reject the permission. 7079 allowed = (required || origPermissions.contains(perm) 7080 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7081 } else if (bp.packageSetting == null) { 7082 // This permission is invalid; skip it. 7083 allowed = false; 7084 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7085 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7086 if (allowed) { 7087 allowedSig = true; 7088 } 7089 } else { 7090 allowed = false; 7091 } 7092 if (DEBUG_INSTALL) { 7093 if (gp != ps) { 7094 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7095 } 7096 } 7097 if (allowed) { 7098 if (!isSystemApp(ps) && ps.permissionsFixed) { 7099 // If this is an existing, non-system package, then 7100 // we can't add any new permissions to it. 7101 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7102 // Except... if this is a permission that was added 7103 // to the platform (note: need to only do this when 7104 // updating the platform). 7105 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7106 } 7107 } 7108 if (allowed) { 7109 if (!gp.grantedPermissions.contains(perm)) { 7110 changedPermission = true; 7111 gp.grantedPermissions.add(perm); 7112 gp.gids = appendInts(gp.gids, bp.gids); 7113 } else if (!ps.haveGids) { 7114 gp.gids = appendInts(gp.gids, bp.gids); 7115 } 7116 } else { 7117 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7118 Slog.w(TAG, "Not granting permission " + perm 7119 + " to package " + pkg.packageName 7120 + " because it was previously installed without"); 7121 } 7122 } 7123 } else { 7124 if (gp.grantedPermissions.remove(perm)) { 7125 changedPermission = true; 7126 gp.gids = removeInts(gp.gids, bp.gids); 7127 Slog.i(TAG, "Un-granting permission " + perm 7128 + " from package " + pkg.packageName 7129 + " (protectionLevel=" + bp.protectionLevel 7130 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7131 + ")"); 7132 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7133 // Don't print warning for app op permissions, since it is fine for them 7134 // not to be granted, there is a UI for the user to decide. 7135 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7136 Slog.w(TAG, "Not granting permission " + perm 7137 + " to package " + pkg.packageName 7138 + " (protectionLevel=" + bp.protectionLevel 7139 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7140 + ")"); 7141 } 7142 } 7143 } 7144 } 7145 7146 if ((changedPermission || replace) && !ps.permissionsFixed && 7147 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7148 // This is the first that we have heard about this package, so the 7149 // permissions we have now selected are fixed until explicitly 7150 // changed. 7151 ps.permissionsFixed = true; 7152 } 7153 ps.haveGids = true; 7154 } 7155 7156 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7157 boolean allowed = false; 7158 final int NP = PackageParser.NEW_PERMISSIONS.length; 7159 for (int ip=0; ip<NP; ip++) { 7160 final PackageParser.NewPermissionInfo npi 7161 = PackageParser.NEW_PERMISSIONS[ip]; 7162 if (npi.name.equals(perm) 7163 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7164 allowed = true; 7165 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7166 + pkg.packageName); 7167 break; 7168 } 7169 } 7170 return allowed; 7171 } 7172 7173 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7174 BasePermission bp, HashSet<String> origPermissions) { 7175 boolean allowed; 7176 allowed = (compareSignatures( 7177 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7178 == PackageManager.SIGNATURE_MATCH) 7179 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7180 == PackageManager.SIGNATURE_MATCH); 7181 if (!allowed && (bp.protectionLevel 7182 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7183 if (isSystemApp(pkg)) { 7184 // For updated system applications, a system permission 7185 // is granted only if it had been defined by the original application. 7186 if (isUpdatedSystemApp(pkg)) { 7187 final PackageSetting sysPs = mSettings 7188 .getDisabledSystemPkgLPr(pkg.packageName); 7189 final GrantedPermissions origGp = sysPs.sharedUser != null 7190 ? sysPs.sharedUser : sysPs; 7191 7192 if (origGp.grantedPermissions.contains(perm)) { 7193 // If the original was granted this permission, we take 7194 // that grant decision as read and propagate it to the 7195 // update. 7196 allowed = true; 7197 } else { 7198 // The system apk may have been updated with an older 7199 // version of the one on the data partition, but which 7200 // granted a new system permission that it didn't have 7201 // before. In this case we do want to allow the app to 7202 // now get the new permission if the ancestral apk is 7203 // privileged to get it. 7204 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7205 for (int j=0; 7206 j<sysPs.pkg.requestedPermissions.size(); j++) { 7207 if (perm.equals( 7208 sysPs.pkg.requestedPermissions.get(j))) { 7209 allowed = true; 7210 break; 7211 } 7212 } 7213 } 7214 } 7215 } else { 7216 allowed = isPrivilegedApp(pkg); 7217 } 7218 } 7219 } 7220 if (!allowed && (bp.protectionLevel 7221 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7222 // For development permissions, a development permission 7223 // is granted only if it was already granted. 7224 allowed = origPermissions.contains(perm); 7225 } 7226 return allowed; 7227 } 7228 7229 final class ActivityIntentResolver 7230 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7231 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7232 boolean defaultOnly, int userId) { 7233 if (!sUserManager.exists(userId)) return null; 7234 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7235 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7236 } 7237 7238 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7239 int userId) { 7240 if (!sUserManager.exists(userId)) return null; 7241 mFlags = flags; 7242 return super.queryIntent(intent, resolvedType, 7243 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7244 } 7245 7246 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7247 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7248 if (!sUserManager.exists(userId)) return null; 7249 if (packageActivities == null) { 7250 return null; 7251 } 7252 mFlags = flags; 7253 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7254 final int N = packageActivities.size(); 7255 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7256 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7257 7258 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7259 for (int i = 0; i < N; ++i) { 7260 intentFilters = packageActivities.get(i).intents; 7261 if (intentFilters != null && intentFilters.size() > 0) { 7262 PackageParser.ActivityIntentInfo[] array = 7263 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7264 intentFilters.toArray(array); 7265 listCut.add(array); 7266 } 7267 } 7268 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7269 } 7270 7271 public final void addActivity(PackageParser.Activity a, String type) { 7272 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7273 mActivities.put(a.getComponentName(), a); 7274 if (DEBUG_SHOW_INFO) 7275 Log.v( 7276 TAG, " " + type + " " + 7277 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7278 if (DEBUG_SHOW_INFO) 7279 Log.v(TAG, " Class=" + a.info.name); 7280 final int NI = a.intents.size(); 7281 for (int j=0; j<NI; j++) { 7282 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7283 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7284 intent.setPriority(0); 7285 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7286 + a.className + " with priority > 0, forcing to 0"); 7287 } 7288 if (DEBUG_SHOW_INFO) { 7289 Log.v(TAG, " IntentFilter:"); 7290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7291 } 7292 if (!intent.debugCheck()) { 7293 Log.w(TAG, "==> For Activity " + a.info.name); 7294 } 7295 addFilter(intent); 7296 } 7297 } 7298 7299 public final void removeActivity(PackageParser.Activity a, String type) { 7300 mActivities.remove(a.getComponentName()); 7301 if (DEBUG_SHOW_INFO) { 7302 Log.v(TAG, " " + type + " " 7303 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7304 : a.info.name) + ":"); 7305 Log.v(TAG, " Class=" + a.info.name); 7306 } 7307 final int NI = a.intents.size(); 7308 for (int j=0; j<NI; j++) { 7309 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7310 if (DEBUG_SHOW_INFO) { 7311 Log.v(TAG, " IntentFilter:"); 7312 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7313 } 7314 removeFilter(intent); 7315 } 7316 } 7317 7318 @Override 7319 protected boolean allowFilterResult( 7320 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7321 ActivityInfo filterAi = filter.activity.info; 7322 for (int i=dest.size()-1; i>=0; i--) { 7323 ActivityInfo destAi = dest.get(i).activityInfo; 7324 if (destAi.name == filterAi.name 7325 && destAi.packageName == filterAi.packageName) { 7326 return false; 7327 } 7328 } 7329 return true; 7330 } 7331 7332 @Override 7333 protected ActivityIntentInfo[] newArray(int size) { 7334 return new ActivityIntentInfo[size]; 7335 } 7336 7337 @Override 7338 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7339 if (!sUserManager.exists(userId)) return true; 7340 PackageParser.Package p = filter.activity.owner; 7341 if (p != null) { 7342 PackageSetting ps = (PackageSetting)p.mExtras; 7343 if (ps != null) { 7344 // System apps are never considered stopped for purposes of 7345 // filtering, because there may be no way for the user to 7346 // actually re-launch them. 7347 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7348 && ps.getStopped(userId); 7349 } 7350 } 7351 return false; 7352 } 7353 7354 @Override 7355 protected boolean isPackageForFilter(String packageName, 7356 PackageParser.ActivityIntentInfo info) { 7357 return packageName.equals(info.activity.owner.packageName); 7358 } 7359 7360 @Override 7361 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7362 int match, int userId) { 7363 if (!sUserManager.exists(userId)) return null; 7364 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7365 return null; 7366 } 7367 final PackageParser.Activity activity = info.activity; 7368 if (mSafeMode && (activity.info.applicationInfo.flags 7369 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7370 return null; 7371 } 7372 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7373 if (ps == null) { 7374 return null; 7375 } 7376 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7377 ps.readUserState(userId), userId); 7378 if (ai == null) { 7379 return null; 7380 } 7381 final ResolveInfo res = new ResolveInfo(); 7382 res.activityInfo = ai; 7383 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7384 res.filter = info; 7385 } 7386 res.priority = info.getPriority(); 7387 res.preferredOrder = activity.owner.mPreferredOrder; 7388 //System.out.println("Result: " + res.activityInfo.className + 7389 // " = " + res.priority); 7390 res.match = match; 7391 res.isDefault = info.hasDefault; 7392 res.labelRes = info.labelRes; 7393 res.nonLocalizedLabel = info.nonLocalizedLabel; 7394 if (userNeedsBadging(userId)) { 7395 res.noResourceId = true; 7396 } else { 7397 res.icon = info.icon; 7398 } 7399 res.system = isSystemApp(res.activityInfo.applicationInfo); 7400 return res; 7401 } 7402 7403 @Override 7404 protected void sortResults(List<ResolveInfo> results) { 7405 Collections.sort(results, mResolvePrioritySorter); 7406 } 7407 7408 @Override 7409 protected void dumpFilter(PrintWriter out, String prefix, 7410 PackageParser.ActivityIntentInfo filter) { 7411 out.print(prefix); out.print( 7412 Integer.toHexString(System.identityHashCode(filter.activity))); 7413 out.print(' '); 7414 filter.activity.printComponentShortName(out); 7415 out.print(" filter "); 7416 out.println(Integer.toHexString(System.identityHashCode(filter))); 7417 } 7418 7419// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7420// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7421// final List<ResolveInfo> retList = Lists.newArrayList(); 7422// while (i.hasNext()) { 7423// final ResolveInfo resolveInfo = i.next(); 7424// if (isEnabledLP(resolveInfo.activityInfo)) { 7425// retList.add(resolveInfo); 7426// } 7427// } 7428// return retList; 7429// } 7430 7431 // Keys are String (activity class name), values are Activity. 7432 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7433 = new HashMap<ComponentName, PackageParser.Activity>(); 7434 private int mFlags; 7435 } 7436 7437 private final class ServiceIntentResolver 7438 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7439 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7440 boolean defaultOnly, int userId) { 7441 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7442 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7443 } 7444 7445 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7446 int userId) { 7447 if (!sUserManager.exists(userId)) return null; 7448 mFlags = flags; 7449 return super.queryIntent(intent, resolvedType, 7450 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7451 } 7452 7453 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7454 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7455 if (!sUserManager.exists(userId)) return null; 7456 if (packageServices == null) { 7457 return null; 7458 } 7459 mFlags = flags; 7460 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7461 final int N = packageServices.size(); 7462 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7463 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7464 7465 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7466 for (int i = 0; i < N; ++i) { 7467 intentFilters = packageServices.get(i).intents; 7468 if (intentFilters != null && intentFilters.size() > 0) { 7469 PackageParser.ServiceIntentInfo[] array = 7470 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7471 intentFilters.toArray(array); 7472 listCut.add(array); 7473 } 7474 } 7475 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7476 } 7477 7478 public final void addService(PackageParser.Service s) { 7479 mServices.put(s.getComponentName(), s); 7480 if (DEBUG_SHOW_INFO) { 7481 Log.v(TAG, " " 7482 + (s.info.nonLocalizedLabel != null 7483 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7484 Log.v(TAG, " Class=" + s.info.name); 7485 } 7486 final int NI = s.intents.size(); 7487 int j; 7488 for (j=0; j<NI; j++) { 7489 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7490 if (DEBUG_SHOW_INFO) { 7491 Log.v(TAG, " IntentFilter:"); 7492 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7493 } 7494 if (!intent.debugCheck()) { 7495 Log.w(TAG, "==> For Service " + s.info.name); 7496 } 7497 addFilter(intent); 7498 } 7499 } 7500 7501 public final void removeService(PackageParser.Service s) { 7502 mServices.remove(s.getComponentName()); 7503 if (DEBUG_SHOW_INFO) { 7504 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7505 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7506 Log.v(TAG, " Class=" + s.info.name); 7507 } 7508 final int NI = s.intents.size(); 7509 int j; 7510 for (j=0; j<NI; j++) { 7511 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7512 if (DEBUG_SHOW_INFO) { 7513 Log.v(TAG, " IntentFilter:"); 7514 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7515 } 7516 removeFilter(intent); 7517 } 7518 } 7519 7520 @Override 7521 protected boolean allowFilterResult( 7522 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7523 ServiceInfo filterSi = filter.service.info; 7524 for (int i=dest.size()-1; i>=0; i--) { 7525 ServiceInfo destAi = dest.get(i).serviceInfo; 7526 if (destAi.name == filterSi.name 7527 && destAi.packageName == filterSi.packageName) { 7528 return false; 7529 } 7530 } 7531 return true; 7532 } 7533 7534 @Override 7535 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7536 return new PackageParser.ServiceIntentInfo[size]; 7537 } 7538 7539 @Override 7540 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7541 if (!sUserManager.exists(userId)) return true; 7542 PackageParser.Package p = filter.service.owner; 7543 if (p != null) { 7544 PackageSetting ps = (PackageSetting)p.mExtras; 7545 if (ps != null) { 7546 // System apps are never considered stopped for purposes of 7547 // filtering, because there may be no way for the user to 7548 // actually re-launch them. 7549 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7550 && ps.getStopped(userId); 7551 } 7552 } 7553 return false; 7554 } 7555 7556 @Override 7557 protected boolean isPackageForFilter(String packageName, 7558 PackageParser.ServiceIntentInfo info) { 7559 return packageName.equals(info.service.owner.packageName); 7560 } 7561 7562 @Override 7563 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7564 int match, int userId) { 7565 if (!sUserManager.exists(userId)) return null; 7566 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7567 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7568 return null; 7569 } 7570 final PackageParser.Service service = info.service; 7571 if (mSafeMode && (service.info.applicationInfo.flags 7572 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7573 return null; 7574 } 7575 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7576 if (ps == null) { 7577 return null; 7578 } 7579 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7580 ps.readUserState(userId), userId); 7581 if (si == null) { 7582 return null; 7583 } 7584 final ResolveInfo res = new ResolveInfo(); 7585 res.serviceInfo = si; 7586 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7587 res.filter = filter; 7588 } 7589 res.priority = info.getPriority(); 7590 res.preferredOrder = service.owner.mPreferredOrder; 7591 //System.out.println("Result: " + res.activityInfo.className + 7592 // " = " + res.priority); 7593 res.match = match; 7594 res.isDefault = info.hasDefault; 7595 res.labelRes = info.labelRes; 7596 res.nonLocalizedLabel = info.nonLocalizedLabel; 7597 res.icon = info.icon; 7598 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7599 return res; 7600 } 7601 7602 @Override 7603 protected void sortResults(List<ResolveInfo> results) { 7604 Collections.sort(results, mResolvePrioritySorter); 7605 } 7606 7607 @Override 7608 protected void dumpFilter(PrintWriter out, String prefix, 7609 PackageParser.ServiceIntentInfo filter) { 7610 out.print(prefix); out.print( 7611 Integer.toHexString(System.identityHashCode(filter.service))); 7612 out.print(' '); 7613 filter.service.printComponentShortName(out); 7614 out.print(" filter "); 7615 out.println(Integer.toHexString(System.identityHashCode(filter))); 7616 } 7617 7618// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7619// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7620// final List<ResolveInfo> retList = Lists.newArrayList(); 7621// while (i.hasNext()) { 7622// final ResolveInfo resolveInfo = (ResolveInfo) i; 7623// if (isEnabledLP(resolveInfo.serviceInfo)) { 7624// retList.add(resolveInfo); 7625// } 7626// } 7627// return retList; 7628// } 7629 7630 // Keys are String (activity class name), values are Activity. 7631 private final HashMap<ComponentName, PackageParser.Service> mServices 7632 = new HashMap<ComponentName, PackageParser.Service>(); 7633 private int mFlags; 7634 }; 7635 7636 private final class ProviderIntentResolver 7637 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7639 boolean defaultOnly, int userId) { 7640 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7641 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7642 } 7643 7644 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7645 int userId) { 7646 if (!sUserManager.exists(userId)) 7647 return null; 7648 mFlags = flags; 7649 return super.queryIntent(intent, resolvedType, 7650 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7651 } 7652 7653 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7654 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7655 if (!sUserManager.exists(userId)) 7656 return null; 7657 if (packageProviders == null) { 7658 return null; 7659 } 7660 mFlags = flags; 7661 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7662 final int N = packageProviders.size(); 7663 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7664 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7665 7666 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7667 for (int i = 0; i < N; ++i) { 7668 intentFilters = packageProviders.get(i).intents; 7669 if (intentFilters != null && intentFilters.size() > 0) { 7670 PackageParser.ProviderIntentInfo[] array = 7671 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7672 intentFilters.toArray(array); 7673 listCut.add(array); 7674 } 7675 } 7676 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7677 } 7678 7679 public final void addProvider(PackageParser.Provider p) { 7680 if (mProviders.containsKey(p.getComponentName())) { 7681 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7682 return; 7683 } 7684 7685 mProviders.put(p.getComponentName(), p); 7686 if (DEBUG_SHOW_INFO) { 7687 Log.v(TAG, " " 7688 + (p.info.nonLocalizedLabel != null 7689 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7690 Log.v(TAG, " Class=" + p.info.name); 7691 } 7692 final int NI = p.intents.size(); 7693 int j; 7694 for (j = 0; j < NI; j++) { 7695 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7696 if (DEBUG_SHOW_INFO) { 7697 Log.v(TAG, " IntentFilter:"); 7698 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7699 } 7700 if (!intent.debugCheck()) { 7701 Log.w(TAG, "==> For Provider " + p.info.name); 7702 } 7703 addFilter(intent); 7704 } 7705 } 7706 7707 public final void removeProvider(PackageParser.Provider p) { 7708 mProviders.remove(p.getComponentName()); 7709 if (DEBUG_SHOW_INFO) { 7710 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7711 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7712 Log.v(TAG, " Class=" + p.info.name); 7713 } 7714 final int NI = p.intents.size(); 7715 int j; 7716 for (j = 0; j < NI; j++) { 7717 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7718 if (DEBUG_SHOW_INFO) { 7719 Log.v(TAG, " IntentFilter:"); 7720 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7721 } 7722 removeFilter(intent); 7723 } 7724 } 7725 7726 @Override 7727 protected boolean allowFilterResult( 7728 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7729 ProviderInfo filterPi = filter.provider.info; 7730 for (int i = dest.size() - 1; i >= 0; i--) { 7731 ProviderInfo destPi = dest.get(i).providerInfo; 7732 if (destPi.name == filterPi.name 7733 && destPi.packageName == filterPi.packageName) { 7734 return false; 7735 } 7736 } 7737 return true; 7738 } 7739 7740 @Override 7741 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7742 return new PackageParser.ProviderIntentInfo[size]; 7743 } 7744 7745 @Override 7746 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7747 if (!sUserManager.exists(userId)) 7748 return true; 7749 PackageParser.Package p = filter.provider.owner; 7750 if (p != null) { 7751 PackageSetting ps = (PackageSetting) p.mExtras; 7752 if (ps != null) { 7753 // System apps are never considered stopped for purposes of 7754 // filtering, because there may be no way for the user to 7755 // actually re-launch them. 7756 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7757 && ps.getStopped(userId); 7758 } 7759 } 7760 return false; 7761 } 7762 7763 @Override 7764 protected boolean isPackageForFilter(String packageName, 7765 PackageParser.ProviderIntentInfo info) { 7766 return packageName.equals(info.provider.owner.packageName); 7767 } 7768 7769 @Override 7770 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7771 int match, int userId) { 7772 if (!sUserManager.exists(userId)) 7773 return null; 7774 final PackageParser.ProviderIntentInfo info = filter; 7775 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7776 return null; 7777 } 7778 final PackageParser.Provider provider = info.provider; 7779 if (mSafeMode && (provider.info.applicationInfo.flags 7780 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7781 return null; 7782 } 7783 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7784 if (ps == null) { 7785 return null; 7786 } 7787 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7788 ps.readUserState(userId), userId); 7789 if (pi == null) { 7790 return null; 7791 } 7792 final ResolveInfo res = new ResolveInfo(); 7793 res.providerInfo = pi; 7794 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7795 res.filter = filter; 7796 } 7797 res.priority = info.getPriority(); 7798 res.preferredOrder = provider.owner.mPreferredOrder; 7799 res.match = match; 7800 res.isDefault = info.hasDefault; 7801 res.labelRes = info.labelRes; 7802 res.nonLocalizedLabel = info.nonLocalizedLabel; 7803 res.icon = info.icon; 7804 res.system = isSystemApp(res.providerInfo.applicationInfo); 7805 return res; 7806 } 7807 7808 @Override 7809 protected void sortResults(List<ResolveInfo> results) { 7810 Collections.sort(results, mResolvePrioritySorter); 7811 } 7812 7813 @Override 7814 protected void dumpFilter(PrintWriter out, String prefix, 7815 PackageParser.ProviderIntentInfo filter) { 7816 out.print(prefix); 7817 out.print( 7818 Integer.toHexString(System.identityHashCode(filter.provider))); 7819 out.print(' '); 7820 filter.provider.printComponentShortName(out); 7821 out.print(" filter "); 7822 out.println(Integer.toHexString(System.identityHashCode(filter))); 7823 } 7824 7825 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7826 = new HashMap<ComponentName, PackageParser.Provider>(); 7827 private int mFlags; 7828 }; 7829 7830 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7831 new Comparator<ResolveInfo>() { 7832 public int compare(ResolveInfo r1, ResolveInfo r2) { 7833 int v1 = r1.priority; 7834 int v2 = r2.priority; 7835 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7836 if (v1 != v2) { 7837 return (v1 > v2) ? -1 : 1; 7838 } 7839 v1 = r1.preferredOrder; 7840 v2 = r2.preferredOrder; 7841 if (v1 != v2) { 7842 return (v1 > v2) ? -1 : 1; 7843 } 7844 if (r1.isDefault != r2.isDefault) { 7845 return r1.isDefault ? -1 : 1; 7846 } 7847 v1 = r1.match; 7848 v2 = r2.match; 7849 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7850 if (v1 != v2) { 7851 return (v1 > v2) ? -1 : 1; 7852 } 7853 if (r1.system != r2.system) { 7854 return r1.system ? -1 : 1; 7855 } 7856 return 0; 7857 } 7858 }; 7859 7860 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7861 new Comparator<ProviderInfo>() { 7862 public int compare(ProviderInfo p1, ProviderInfo p2) { 7863 final int v1 = p1.initOrder; 7864 final int v2 = p2.initOrder; 7865 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7866 } 7867 }; 7868 7869 static final void sendPackageBroadcast(String action, String pkg, 7870 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7871 int[] userIds) { 7872 IActivityManager am = ActivityManagerNative.getDefault(); 7873 if (am != null) { 7874 try { 7875 if (userIds == null) { 7876 userIds = am.getRunningUserIds(); 7877 } 7878 for (int id : userIds) { 7879 final Intent intent = new Intent(action, 7880 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7881 if (extras != null) { 7882 intent.putExtras(extras); 7883 } 7884 if (targetPkg != null) { 7885 intent.setPackage(targetPkg); 7886 } 7887 // Modify the UID when posting to other users 7888 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7889 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7890 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7891 intent.putExtra(Intent.EXTRA_UID, uid); 7892 } 7893 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7894 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7895 if (DEBUG_BROADCASTS) { 7896 RuntimeException here = new RuntimeException("here"); 7897 here.fillInStackTrace(); 7898 Slog.d(TAG, "Sending to user " + id + ": " 7899 + intent.toShortString(false, true, false, false) 7900 + " " + intent.getExtras(), here); 7901 } 7902 am.broadcastIntent(null, intent, null, finishedReceiver, 7903 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7904 finishedReceiver != null, false, id); 7905 } 7906 } catch (RemoteException ex) { 7907 } 7908 } 7909 } 7910 7911 /** 7912 * Check if the external storage media is available. This is true if there 7913 * is a mounted external storage medium or if the external storage is 7914 * emulated. 7915 */ 7916 private boolean isExternalMediaAvailable() { 7917 return mMediaMounted || Environment.isExternalStorageEmulated(); 7918 } 7919 7920 @Override 7921 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7922 // writer 7923 synchronized (mPackages) { 7924 if (!isExternalMediaAvailable()) { 7925 // If the external storage is no longer mounted at this point, 7926 // the caller may not have been able to delete all of this 7927 // packages files and can not delete any more. Bail. 7928 return null; 7929 } 7930 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7931 if (lastPackage != null) { 7932 pkgs.remove(lastPackage); 7933 } 7934 if (pkgs.size() > 0) { 7935 return pkgs.get(0); 7936 } 7937 } 7938 return null; 7939 } 7940 7941 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7942 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7943 userId, andCode ? 1 : 0, packageName); 7944 if (mSystemReady) { 7945 msg.sendToTarget(); 7946 } else { 7947 if (mPostSystemReadyMessages == null) { 7948 mPostSystemReadyMessages = new ArrayList<>(); 7949 } 7950 mPostSystemReadyMessages.add(msg); 7951 } 7952 } 7953 7954 void startCleaningPackages() { 7955 // reader 7956 synchronized (mPackages) { 7957 if (!isExternalMediaAvailable()) { 7958 return; 7959 } 7960 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7961 return; 7962 } 7963 } 7964 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7965 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7966 IActivityManager am = ActivityManagerNative.getDefault(); 7967 if (am != null) { 7968 try { 7969 am.startService(null, intent, null, UserHandle.USER_OWNER); 7970 } catch (RemoteException e) { 7971 } 7972 } 7973 } 7974 7975 @Override 7976 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7977 int installFlags, String installerPackageName, VerificationParams verificationParams, 7978 String packageAbiOverride) { 7979 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7980 packageAbiOverride, UserHandle.getCallingUserId()); 7981 } 7982 7983 @Override 7984 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7985 int installFlags, String installerPackageName, VerificationParams verificationParams, 7986 String packageAbiOverride, int userId) { 7987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7988 7989 final int callingUid = Binder.getCallingUid(); 7990 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7991 7992 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7993 try { 7994 if (observer != null) { 7995 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7996 } 7997 } catch (RemoteException re) { 7998 } 7999 return; 8000 } 8001 8002 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8003 installFlags |= PackageManager.INSTALL_FROM_ADB; 8004 8005 } else { 8006 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8007 // about installerPackageName. 8008 8009 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8010 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8011 } 8012 8013 UserHandle user; 8014 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8015 user = UserHandle.ALL; 8016 } else { 8017 user = new UserHandle(userId); 8018 } 8019 8020 verificationParams.setInstallerUid(callingUid); 8021 8022 final File originFile = new File(originPath); 8023 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8024 8025 final Message msg = mHandler.obtainMessage(INIT_COPY); 8026 msg.obj = new InstallParams(origin, observer, installFlags, 8027 installerPackageName, verificationParams, user, packageAbiOverride); 8028 mHandler.sendMessage(msg); 8029 } 8030 8031 void installStage(String packageName, File stagedDir, String stagedCid, 8032 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8033 String installerPackageName, int installerUid, UserHandle user) { 8034 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8035 params.referrerUri, installerUid, null); 8036 8037 final OriginInfo origin; 8038 if (stagedDir != null) { 8039 origin = OriginInfo.fromStagedFile(stagedDir); 8040 } else { 8041 origin = OriginInfo.fromStagedContainer(stagedCid); 8042 } 8043 8044 final Message msg = mHandler.obtainMessage(INIT_COPY); 8045 msg.obj = new InstallParams(origin, observer, params.installFlags, 8046 installerPackageName, verifParams, user, params.abiOverride); 8047 mHandler.sendMessage(msg); 8048 } 8049 8050 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8051 Bundle extras = new Bundle(1); 8052 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8053 8054 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8055 packageName, extras, null, null, new int[] {userId}); 8056 try { 8057 IActivityManager am = ActivityManagerNative.getDefault(); 8058 final boolean isSystem = 8059 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8060 if (isSystem && am.isUserRunning(userId, false)) { 8061 // The just-installed/enabled app is bundled on the system, so presumed 8062 // to be able to run automatically without needing an explicit launch. 8063 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8064 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8065 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8066 .setPackage(packageName); 8067 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8068 android.app.AppOpsManager.OP_NONE, false, false, userId); 8069 } 8070 } catch (RemoteException e) { 8071 // shouldn't happen 8072 Slog.w(TAG, "Unable to bootstrap installed package", e); 8073 } 8074 } 8075 8076 @Override 8077 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8078 int userId) { 8079 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8080 PackageSetting pkgSetting; 8081 final int uid = Binder.getCallingUid(); 8082 enforceCrossUserPermission(uid, userId, true, true, 8083 "setApplicationHiddenSetting for user " + userId); 8084 8085 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8086 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8087 return false; 8088 } 8089 8090 long callingId = Binder.clearCallingIdentity(); 8091 try { 8092 boolean sendAdded = false; 8093 boolean sendRemoved = false; 8094 // writer 8095 synchronized (mPackages) { 8096 pkgSetting = mSettings.mPackages.get(packageName); 8097 if (pkgSetting == null) { 8098 return false; 8099 } 8100 if (pkgSetting.getHidden(userId) != hidden) { 8101 pkgSetting.setHidden(hidden, userId); 8102 mSettings.writePackageRestrictionsLPr(userId); 8103 if (hidden) { 8104 sendRemoved = true; 8105 } else { 8106 sendAdded = true; 8107 } 8108 } 8109 } 8110 if (sendAdded) { 8111 sendPackageAddedForUser(packageName, pkgSetting, userId); 8112 return true; 8113 } 8114 if (sendRemoved) { 8115 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8116 "hiding pkg"); 8117 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8118 } 8119 } finally { 8120 Binder.restoreCallingIdentity(callingId); 8121 } 8122 return false; 8123 } 8124 8125 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8126 int userId) { 8127 final PackageRemovedInfo info = new PackageRemovedInfo(); 8128 info.removedPackage = packageName; 8129 info.removedUsers = new int[] {userId}; 8130 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8131 info.sendBroadcast(false, false, false); 8132 } 8133 8134 /** 8135 * Returns true if application is not found or there was an error. Otherwise it returns 8136 * the hidden state of the package for the given user. 8137 */ 8138 @Override 8139 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8141 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8142 false, "getApplicationHidden for user " + userId); 8143 PackageSetting pkgSetting; 8144 long callingId = Binder.clearCallingIdentity(); 8145 try { 8146 // writer 8147 synchronized (mPackages) { 8148 pkgSetting = mSettings.mPackages.get(packageName); 8149 if (pkgSetting == null) { 8150 return true; 8151 } 8152 return pkgSetting.getHidden(userId); 8153 } 8154 } finally { 8155 Binder.restoreCallingIdentity(callingId); 8156 } 8157 } 8158 8159 /** 8160 * @hide 8161 */ 8162 @Override 8163 public int installExistingPackageAsUser(String packageName, int userId) { 8164 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8165 null); 8166 PackageSetting pkgSetting; 8167 final int uid = Binder.getCallingUid(); 8168 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8169 + userId); 8170 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8171 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8172 } 8173 8174 long callingId = Binder.clearCallingIdentity(); 8175 try { 8176 boolean sendAdded = false; 8177 Bundle extras = new Bundle(1); 8178 8179 // writer 8180 synchronized (mPackages) { 8181 pkgSetting = mSettings.mPackages.get(packageName); 8182 if (pkgSetting == null) { 8183 return PackageManager.INSTALL_FAILED_INVALID_URI; 8184 } 8185 if (!pkgSetting.getInstalled(userId)) { 8186 pkgSetting.setInstalled(true, userId); 8187 pkgSetting.setHidden(false, userId); 8188 mSettings.writePackageRestrictionsLPr(userId); 8189 sendAdded = true; 8190 } 8191 } 8192 8193 if (sendAdded) { 8194 sendPackageAddedForUser(packageName, pkgSetting, userId); 8195 } 8196 } finally { 8197 Binder.restoreCallingIdentity(callingId); 8198 } 8199 8200 return PackageManager.INSTALL_SUCCEEDED; 8201 } 8202 8203 boolean isUserRestricted(int userId, String restrictionKey) { 8204 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8205 if (restrictions.getBoolean(restrictionKey, false)) { 8206 Log.w(TAG, "User is restricted: " + restrictionKey); 8207 return true; 8208 } 8209 return false; 8210 } 8211 8212 @Override 8213 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8214 mContext.enforceCallingOrSelfPermission( 8215 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8216 "Only package verification agents can verify applications"); 8217 8218 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8219 final PackageVerificationResponse response = new PackageVerificationResponse( 8220 verificationCode, Binder.getCallingUid()); 8221 msg.arg1 = id; 8222 msg.obj = response; 8223 mHandler.sendMessage(msg); 8224 } 8225 8226 @Override 8227 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8228 long millisecondsToDelay) { 8229 mContext.enforceCallingOrSelfPermission( 8230 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8231 "Only package verification agents can extend verification timeouts"); 8232 8233 final PackageVerificationState state = mPendingVerification.get(id); 8234 final PackageVerificationResponse response = new PackageVerificationResponse( 8235 verificationCodeAtTimeout, Binder.getCallingUid()); 8236 8237 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8238 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8239 } 8240 if (millisecondsToDelay < 0) { 8241 millisecondsToDelay = 0; 8242 } 8243 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8244 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8245 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8246 } 8247 8248 if ((state != null) && !state.timeoutExtended()) { 8249 state.extendTimeout(); 8250 8251 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8252 msg.arg1 = id; 8253 msg.obj = response; 8254 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8255 } 8256 } 8257 8258 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8259 int verificationCode, UserHandle user) { 8260 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8261 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8262 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8263 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8264 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8265 8266 mContext.sendBroadcastAsUser(intent, user, 8267 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8268 } 8269 8270 private ComponentName matchComponentForVerifier(String packageName, 8271 List<ResolveInfo> receivers) { 8272 ActivityInfo targetReceiver = null; 8273 8274 final int NR = receivers.size(); 8275 for (int i = 0; i < NR; i++) { 8276 final ResolveInfo info = receivers.get(i); 8277 if (info.activityInfo == null) { 8278 continue; 8279 } 8280 8281 if (packageName.equals(info.activityInfo.packageName)) { 8282 targetReceiver = info.activityInfo; 8283 break; 8284 } 8285 } 8286 8287 if (targetReceiver == null) { 8288 return null; 8289 } 8290 8291 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8292 } 8293 8294 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8295 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8296 if (pkgInfo.verifiers.length == 0) { 8297 return null; 8298 } 8299 8300 final int N = pkgInfo.verifiers.length; 8301 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8302 for (int i = 0; i < N; i++) { 8303 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8304 8305 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8306 receivers); 8307 if (comp == null) { 8308 continue; 8309 } 8310 8311 final int verifierUid = getUidForVerifier(verifierInfo); 8312 if (verifierUid == -1) { 8313 continue; 8314 } 8315 8316 if (DEBUG_VERIFY) { 8317 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8318 + " with the correct signature"); 8319 } 8320 sufficientVerifiers.add(comp); 8321 verificationState.addSufficientVerifier(verifierUid); 8322 } 8323 8324 return sufficientVerifiers; 8325 } 8326 8327 private int getUidForVerifier(VerifierInfo verifierInfo) { 8328 synchronized (mPackages) { 8329 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8330 if (pkg == null) { 8331 return -1; 8332 } else if (pkg.mSignatures.length != 1) { 8333 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8334 + " has more than one signature; ignoring"); 8335 return -1; 8336 } 8337 8338 /* 8339 * If the public key of the package's signature does not match 8340 * our expected public key, then this is a different package and 8341 * we should skip. 8342 */ 8343 8344 final byte[] expectedPublicKey; 8345 try { 8346 final Signature verifierSig = pkg.mSignatures[0]; 8347 final PublicKey publicKey = verifierSig.getPublicKey(); 8348 expectedPublicKey = publicKey.getEncoded(); 8349 } catch (CertificateException e) { 8350 return -1; 8351 } 8352 8353 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8354 8355 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8356 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8357 + " does not have the expected public key; ignoring"); 8358 return -1; 8359 } 8360 8361 return pkg.applicationInfo.uid; 8362 } 8363 } 8364 8365 @Override 8366 public void finishPackageInstall(int token) { 8367 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8368 8369 if (DEBUG_INSTALL) { 8370 Slog.v(TAG, "BM finishing package install for " + token); 8371 } 8372 8373 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8374 mHandler.sendMessage(msg); 8375 } 8376 8377 /** 8378 * Get the verification agent timeout. 8379 * 8380 * @return verification timeout in milliseconds 8381 */ 8382 private long getVerificationTimeout() { 8383 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8384 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8385 DEFAULT_VERIFICATION_TIMEOUT); 8386 } 8387 8388 /** 8389 * Get the default verification agent response code. 8390 * 8391 * @return default verification response code 8392 */ 8393 private int getDefaultVerificationResponse() { 8394 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8395 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8396 DEFAULT_VERIFICATION_RESPONSE); 8397 } 8398 8399 /** 8400 * Check whether or not package verification has been enabled. 8401 * 8402 * @return true if verification should be performed 8403 */ 8404 private boolean isVerificationEnabled(int userId, int installFlags) { 8405 if (!DEFAULT_VERIFY_ENABLE) { 8406 return false; 8407 } 8408 8409 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8410 8411 // Check if installing from ADB 8412 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8413 // Do not run verification in a test harness environment 8414 if (ActivityManager.isRunningInTestHarness()) { 8415 return false; 8416 } 8417 if (ensureVerifyAppsEnabled) { 8418 return true; 8419 } 8420 // Check if the developer does not want package verification for ADB installs 8421 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8422 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8423 return false; 8424 } 8425 } 8426 8427 if (ensureVerifyAppsEnabled) { 8428 return true; 8429 } 8430 8431 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8432 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8433 } 8434 8435 /** 8436 * Get the "allow unknown sources" setting. 8437 * 8438 * @return the current "allow unknown sources" setting 8439 */ 8440 private int getUnknownSourcesSettings() { 8441 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8442 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8443 -1); 8444 } 8445 8446 @Override 8447 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8448 final int uid = Binder.getCallingUid(); 8449 // writer 8450 synchronized (mPackages) { 8451 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8452 if (targetPackageSetting == null) { 8453 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8454 } 8455 8456 PackageSetting installerPackageSetting; 8457 if (installerPackageName != null) { 8458 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8459 if (installerPackageSetting == null) { 8460 throw new IllegalArgumentException("Unknown installer package: " 8461 + installerPackageName); 8462 } 8463 } else { 8464 installerPackageSetting = null; 8465 } 8466 8467 Signature[] callerSignature; 8468 Object obj = mSettings.getUserIdLPr(uid); 8469 if (obj != null) { 8470 if (obj instanceof SharedUserSetting) { 8471 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8472 } else if (obj instanceof PackageSetting) { 8473 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8474 } else { 8475 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8476 } 8477 } else { 8478 throw new SecurityException("Unknown calling uid " + uid); 8479 } 8480 8481 // Verify: can't set installerPackageName to a package that is 8482 // not signed with the same cert as the caller. 8483 if (installerPackageSetting != null) { 8484 if (compareSignatures(callerSignature, 8485 installerPackageSetting.signatures.mSignatures) 8486 != PackageManager.SIGNATURE_MATCH) { 8487 throw new SecurityException( 8488 "Caller does not have same cert as new installer package " 8489 + installerPackageName); 8490 } 8491 } 8492 8493 // Verify: if target already has an installer package, it must 8494 // be signed with the same cert as the caller. 8495 if (targetPackageSetting.installerPackageName != null) { 8496 PackageSetting setting = mSettings.mPackages.get( 8497 targetPackageSetting.installerPackageName); 8498 // If the currently set package isn't valid, then it's always 8499 // okay to change it. 8500 if (setting != null) { 8501 if (compareSignatures(callerSignature, 8502 setting.signatures.mSignatures) 8503 != PackageManager.SIGNATURE_MATCH) { 8504 throw new SecurityException( 8505 "Caller does not have same cert as old installer package " 8506 + targetPackageSetting.installerPackageName); 8507 } 8508 } 8509 } 8510 8511 // Okay! 8512 targetPackageSetting.installerPackageName = installerPackageName; 8513 scheduleWriteSettingsLocked(); 8514 } 8515 } 8516 8517 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8518 // Queue up an async operation since the package installation may take a little while. 8519 mHandler.post(new Runnable() { 8520 public void run() { 8521 mHandler.removeCallbacks(this); 8522 // Result object to be returned 8523 PackageInstalledInfo res = new PackageInstalledInfo(); 8524 res.returnCode = currentStatus; 8525 res.uid = -1; 8526 res.pkg = null; 8527 res.removedInfo = new PackageRemovedInfo(); 8528 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8529 args.doPreInstall(res.returnCode); 8530 synchronized (mInstallLock) { 8531 installPackageLI(args, res); 8532 } 8533 args.doPostInstall(res.returnCode, res.uid); 8534 } 8535 8536 // A restore should be performed at this point if (a) the install 8537 // succeeded, (b) the operation is not an update, and (c) the new 8538 // package has not opted out of backup participation. 8539 final boolean update = res.removedInfo.removedPackage != null; 8540 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8541 boolean doRestore = !update 8542 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8543 8544 // Set up the post-install work request bookkeeping. This will be used 8545 // and cleaned up by the post-install event handling regardless of whether 8546 // there's a restore pass performed. Token values are >= 1. 8547 int token; 8548 if (mNextInstallToken < 0) mNextInstallToken = 1; 8549 token = mNextInstallToken++; 8550 8551 PostInstallData data = new PostInstallData(args, res); 8552 mRunningInstalls.put(token, data); 8553 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8554 8555 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8556 // Pass responsibility to the Backup Manager. It will perform a 8557 // restore if appropriate, then pass responsibility back to the 8558 // Package Manager to run the post-install observer callbacks 8559 // and broadcasts. 8560 IBackupManager bm = IBackupManager.Stub.asInterface( 8561 ServiceManager.getService(Context.BACKUP_SERVICE)); 8562 if (bm != null) { 8563 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8564 + " to BM for possible restore"); 8565 try { 8566 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8567 } catch (RemoteException e) { 8568 // can't happen; the backup manager is local 8569 } catch (Exception e) { 8570 Slog.e(TAG, "Exception trying to enqueue restore", e); 8571 doRestore = false; 8572 } 8573 } else { 8574 Slog.e(TAG, "Backup Manager not found!"); 8575 doRestore = false; 8576 } 8577 } 8578 8579 if (!doRestore) { 8580 // No restore possible, or the Backup Manager was mysteriously not 8581 // available -- just fire the post-install work request directly. 8582 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8583 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8584 mHandler.sendMessage(msg); 8585 } 8586 } 8587 }); 8588 } 8589 8590 private abstract class HandlerParams { 8591 private static final int MAX_RETRIES = 4; 8592 8593 /** 8594 * Number of times startCopy() has been attempted and had a non-fatal 8595 * error. 8596 */ 8597 private int mRetries = 0; 8598 8599 /** User handle for the user requesting the information or installation. */ 8600 private final UserHandle mUser; 8601 8602 HandlerParams(UserHandle user) { 8603 mUser = user; 8604 } 8605 8606 UserHandle getUser() { 8607 return mUser; 8608 } 8609 8610 final boolean startCopy() { 8611 boolean res; 8612 try { 8613 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8614 8615 if (++mRetries > MAX_RETRIES) { 8616 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8617 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8618 handleServiceError(); 8619 return false; 8620 } else { 8621 handleStartCopy(); 8622 res = true; 8623 } 8624 } catch (RemoteException e) { 8625 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8626 mHandler.sendEmptyMessage(MCS_RECONNECT); 8627 res = false; 8628 } 8629 handleReturnCode(); 8630 return res; 8631 } 8632 8633 final void serviceError() { 8634 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8635 handleServiceError(); 8636 handleReturnCode(); 8637 } 8638 8639 abstract void handleStartCopy() throws RemoteException; 8640 abstract void handleServiceError(); 8641 abstract void handleReturnCode(); 8642 } 8643 8644 class MeasureParams extends HandlerParams { 8645 private final PackageStats mStats; 8646 private boolean mSuccess; 8647 8648 private final IPackageStatsObserver mObserver; 8649 8650 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8651 super(new UserHandle(stats.userHandle)); 8652 mObserver = observer; 8653 mStats = stats; 8654 } 8655 8656 @Override 8657 public String toString() { 8658 return "MeasureParams{" 8659 + Integer.toHexString(System.identityHashCode(this)) 8660 + " " + mStats.packageName + "}"; 8661 } 8662 8663 @Override 8664 void handleStartCopy() throws RemoteException { 8665 synchronized (mInstallLock) { 8666 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8667 } 8668 8669 if (mSuccess) { 8670 final boolean mounted; 8671 if (Environment.isExternalStorageEmulated()) { 8672 mounted = true; 8673 } else { 8674 final String status = Environment.getExternalStorageState(); 8675 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8676 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8677 } 8678 8679 if (mounted) { 8680 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8681 8682 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8683 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8684 8685 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8686 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8687 8688 // Always subtract cache size, since it's a subdirectory 8689 mStats.externalDataSize -= mStats.externalCacheSize; 8690 8691 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8692 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8693 8694 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8695 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8696 } 8697 } 8698 } 8699 8700 @Override 8701 void handleReturnCode() { 8702 if (mObserver != null) { 8703 try { 8704 mObserver.onGetStatsCompleted(mStats, mSuccess); 8705 } catch (RemoteException e) { 8706 Slog.i(TAG, "Observer no longer exists."); 8707 } 8708 } 8709 } 8710 8711 @Override 8712 void handleServiceError() { 8713 Slog.e(TAG, "Could not measure application " + mStats.packageName 8714 + " external storage"); 8715 } 8716 } 8717 8718 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8719 throws RemoteException { 8720 long result = 0; 8721 for (File path : paths) { 8722 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8723 } 8724 return result; 8725 } 8726 8727 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8728 for (File path : paths) { 8729 try { 8730 mcs.clearDirectory(path.getAbsolutePath()); 8731 } catch (RemoteException e) { 8732 } 8733 } 8734 } 8735 8736 static class OriginInfo { 8737 /** 8738 * Location where install is coming from, before it has been 8739 * copied/renamed into place. This could be a single monolithic APK 8740 * file, or a cluster directory. This location may be untrusted. 8741 */ 8742 final File file; 8743 final String cid; 8744 8745 /** 8746 * Flag indicating that {@link #file} or {@link #cid} has already been 8747 * staged, meaning downstream users don't need to defensively copy the 8748 * contents. 8749 */ 8750 final boolean staged; 8751 8752 /** 8753 * Flag indicating that {@link #file} or {@link #cid} is an already 8754 * installed app that is being moved. 8755 */ 8756 final boolean existing; 8757 8758 final String resolvedPath; 8759 final File resolvedFile; 8760 8761 static OriginInfo fromNothing() { 8762 return new OriginInfo(null, null, false, false); 8763 } 8764 8765 static OriginInfo fromUntrustedFile(File file) { 8766 return new OriginInfo(file, null, false, false); 8767 } 8768 8769 static OriginInfo fromExistingFile(File file) { 8770 return new OriginInfo(file, null, false, true); 8771 } 8772 8773 static OriginInfo fromStagedFile(File file) { 8774 return new OriginInfo(file, null, true, false); 8775 } 8776 8777 static OriginInfo fromStagedContainer(String cid) { 8778 return new OriginInfo(null, cid, true, false); 8779 } 8780 8781 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8782 this.file = file; 8783 this.cid = cid; 8784 this.staged = staged; 8785 this.existing = existing; 8786 8787 if (cid != null) { 8788 resolvedPath = PackageHelper.getSdDir(cid); 8789 resolvedFile = new File(resolvedPath); 8790 } else if (file != null) { 8791 resolvedPath = file.getAbsolutePath(); 8792 resolvedFile = file; 8793 } else { 8794 resolvedPath = null; 8795 resolvedFile = null; 8796 } 8797 } 8798 } 8799 8800 class InstallParams extends HandlerParams { 8801 final OriginInfo origin; 8802 final IPackageInstallObserver2 observer; 8803 int installFlags; 8804 final String installerPackageName; 8805 final VerificationParams verificationParams; 8806 private InstallArgs mArgs; 8807 private int mRet; 8808 final String packageAbiOverride; 8809 8810 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8811 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8812 String packageAbiOverride) { 8813 super(user); 8814 this.origin = origin; 8815 this.observer = observer; 8816 this.installFlags = installFlags; 8817 this.installerPackageName = installerPackageName; 8818 this.verificationParams = verificationParams; 8819 this.packageAbiOverride = packageAbiOverride; 8820 } 8821 8822 @Override 8823 public String toString() { 8824 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8825 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8826 } 8827 8828 public ManifestDigest getManifestDigest() { 8829 if (verificationParams == null) { 8830 return null; 8831 } 8832 return verificationParams.getManifestDigest(); 8833 } 8834 8835 private int installLocationPolicy(PackageInfoLite pkgLite) { 8836 String packageName = pkgLite.packageName; 8837 int installLocation = pkgLite.installLocation; 8838 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8839 // reader 8840 synchronized (mPackages) { 8841 PackageParser.Package pkg = mPackages.get(packageName); 8842 if (pkg != null) { 8843 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8844 // Check for downgrading. 8845 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8846 if (pkgLite.versionCode < pkg.mVersionCode) { 8847 Slog.w(TAG, "Can't install update of " + packageName 8848 + " update version " + pkgLite.versionCode 8849 + " is older than installed version " 8850 + pkg.mVersionCode); 8851 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8852 } 8853 } 8854 // Check for updated system application. 8855 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8856 if (onSd) { 8857 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8858 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8859 } 8860 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8861 } else { 8862 if (onSd) { 8863 // Install flag overrides everything. 8864 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8865 } 8866 // If current upgrade specifies particular preference 8867 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8868 // Application explicitly specified internal. 8869 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8870 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8871 // App explictly prefers external. Let policy decide 8872 } else { 8873 // Prefer previous location 8874 if (isExternal(pkg)) { 8875 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8876 } 8877 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8878 } 8879 } 8880 } else { 8881 // Invalid install. Return error code 8882 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8883 } 8884 } 8885 } 8886 // All the special cases have been taken care of. 8887 // Return result based on recommended install location. 8888 if (onSd) { 8889 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8890 } 8891 return pkgLite.recommendedInstallLocation; 8892 } 8893 8894 /* 8895 * Invoke remote method to get package information and install 8896 * location values. Override install location based on default 8897 * policy if needed and then create install arguments based 8898 * on the install location. 8899 */ 8900 public void handleStartCopy() throws RemoteException { 8901 int ret = PackageManager.INSTALL_SUCCEEDED; 8902 8903 // If we're already staged, we've firmly committed to an install location 8904 if (origin.staged) { 8905 if (origin.file != null) { 8906 installFlags |= PackageManager.INSTALL_INTERNAL; 8907 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8908 } else if (origin.cid != null) { 8909 installFlags |= PackageManager.INSTALL_EXTERNAL; 8910 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8911 } else { 8912 throw new IllegalStateException("Invalid stage location"); 8913 } 8914 } 8915 8916 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8917 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8918 8919 PackageInfoLite pkgLite = null; 8920 8921 if (onInt && onSd) { 8922 // Check if both bits are set. 8923 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8924 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8925 } else { 8926 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8927 packageAbiOverride); 8928 8929 /* 8930 * If we have too little free space, try to free cache 8931 * before giving up. 8932 */ 8933 if (!origin.staged && pkgLite.recommendedInstallLocation 8934 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8935 // TODO: focus freeing disk space on the target device 8936 final StorageManager storage = StorageManager.from(mContext); 8937 final long lowThreshold = storage.getStorageLowBytes( 8938 Environment.getDataDirectory()); 8939 8940 final long sizeBytes = mContainerService.calculateInstalledSize( 8941 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8942 8943 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8944 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8945 installFlags, packageAbiOverride); 8946 } 8947 8948 /* 8949 * The cache free must have deleted the file we 8950 * downloaded to install. 8951 * 8952 * TODO: fix the "freeCache" call to not delete 8953 * the file we care about. 8954 */ 8955 if (pkgLite.recommendedInstallLocation 8956 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8957 pkgLite.recommendedInstallLocation 8958 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8959 } 8960 } 8961 } 8962 8963 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8964 int loc = pkgLite.recommendedInstallLocation; 8965 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8966 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8967 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8968 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8969 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8970 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8971 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8972 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8973 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8974 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8975 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8976 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8977 } else { 8978 // Override with defaults if needed. 8979 loc = installLocationPolicy(pkgLite); 8980 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8981 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8982 } else if (!onSd && !onInt) { 8983 // Override install location with flags 8984 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8985 // Set the flag to install on external media. 8986 installFlags |= PackageManager.INSTALL_EXTERNAL; 8987 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8988 } else { 8989 // Make sure the flag for installing on external 8990 // media is unset 8991 installFlags |= PackageManager.INSTALL_INTERNAL; 8992 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8993 } 8994 } 8995 } 8996 } 8997 8998 final InstallArgs args = createInstallArgs(this); 8999 mArgs = args; 9000 9001 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9002 /* 9003 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9004 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9005 */ 9006 int userIdentifier = getUser().getIdentifier(); 9007 if (userIdentifier == UserHandle.USER_ALL 9008 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9009 userIdentifier = UserHandle.USER_OWNER; 9010 } 9011 9012 /* 9013 * Determine if we have any installed package verifiers. If we 9014 * do, then we'll defer to them to verify the packages. 9015 */ 9016 final int requiredUid = mRequiredVerifierPackage == null ? -1 9017 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9018 if (!origin.existing && requiredUid != -1 9019 && isVerificationEnabled(userIdentifier, installFlags)) { 9020 final Intent verification = new Intent( 9021 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9022 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9023 PACKAGE_MIME_TYPE); 9024 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9025 9026 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9027 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9028 0 /* TODO: Which userId? */); 9029 9030 if (DEBUG_VERIFY) { 9031 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9032 + verification.toString() + " with " + pkgLite.verifiers.length 9033 + " optional verifiers"); 9034 } 9035 9036 final int verificationId = mPendingVerificationToken++; 9037 9038 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9039 9040 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9041 installerPackageName); 9042 9043 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9044 installFlags); 9045 9046 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9047 pkgLite.packageName); 9048 9049 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9050 pkgLite.versionCode); 9051 9052 if (verificationParams != null) { 9053 if (verificationParams.getVerificationURI() != null) { 9054 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9055 verificationParams.getVerificationURI()); 9056 } 9057 if (verificationParams.getOriginatingURI() != null) { 9058 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9059 verificationParams.getOriginatingURI()); 9060 } 9061 if (verificationParams.getReferrer() != null) { 9062 verification.putExtra(Intent.EXTRA_REFERRER, 9063 verificationParams.getReferrer()); 9064 } 9065 if (verificationParams.getOriginatingUid() >= 0) { 9066 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9067 verificationParams.getOriginatingUid()); 9068 } 9069 if (verificationParams.getInstallerUid() >= 0) { 9070 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9071 verificationParams.getInstallerUid()); 9072 } 9073 } 9074 9075 final PackageVerificationState verificationState = new PackageVerificationState( 9076 requiredUid, args); 9077 9078 mPendingVerification.append(verificationId, verificationState); 9079 9080 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9081 receivers, verificationState); 9082 9083 /* 9084 * If any sufficient verifiers were listed in the package 9085 * manifest, attempt to ask them. 9086 */ 9087 if (sufficientVerifiers != null) { 9088 final int N = sufficientVerifiers.size(); 9089 if (N == 0) { 9090 Slog.i(TAG, "Additional verifiers required, but none installed."); 9091 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9092 } else { 9093 for (int i = 0; i < N; i++) { 9094 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9095 9096 final Intent sufficientIntent = new Intent(verification); 9097 sufficientIntent.setComponent(verifierComponent); 9098 9099 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9100 } 9101 } 9102 } 9103 9104 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9105 mRequiredVerifierPackage, receivers); 9106 if (ret == PackageManager.INSTALL_SUCCEEDED 9107 && mRequiredVerifierPackage != null) { 9108 /* 9109 * Send the intent to the required verification agent, 9110 * but only start the verification timeout after the 9111 * target BroadcastReceivers have run. 9112 */ 9113 verification.setComponent(requiredVerifierComponent); 9114 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9115 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9116 new BroadcastReceiver() { 9117 @Override 9118 public void onReceive(Context context, Intent intent) { 9119 final Message msg = mHandler 9120 .obtainMessage(CHECK_PENDING_VERIFICATION); 9121 msg.arg1 = verificationId; 9122 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9123 } 9124 }, null, 0, null, null); 9125 9126 /* 9127 * We don't want the copy to proceed until verification 9128 * succeeds, so null out this field. 9129 */ 9130 mArgs = null; 9131 } 9132 } else { 9133 /* 9134 * No package verification is enabled, so immediately start 9135 * the remote call to initiate copy using temporary file. 9136 */ 9137 ret = args.copyApk(mContainerService, true); 9138 } 9139 } 9140 9141 mRet = ret; 9142 } 9143 9144 @Override 9145 void handleReturnCode() { 9146 // If mArgs is null, then MCS couldn't be reached. When it 9147 // reconnects, it will try again to install. At that point, this 9148 // will succeed. 9149 if (mArgs != null) { 9150 processPendingInstall(mArgs, mRet); 9151 } 9152 } 9153 9154 @Override 9155 void handleServiceError() { 9156 mArgs = createInstallArgs(this); 9157 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9158 } 9159 9160 public boolean isForwardLocked() { 9161 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9162 } 9163 } 9164 9165 /** 9166 * Used during creation of InstallArgs 9167 * 9168 * @param installFlags package installation flags 9169 * @return true if should be installed on external storage 9170 */ 9171 private static boolean installOnSd(int installFlags) { 9172 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9173 return false; 9174 } 9175 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9176 return true; 9177 } 9178 return false; 9179 } 9180 9181 /** 9182 * Used during creation of InstallArgs 9183 * 9184 * @param installFlags package installation flags 9185 * @return true if should be installed as forward locked 9186 */ 9187 private static boolean installForwardLocked(int installFlags) { 9188 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9189 } 9190 9191 private InstallArgs createInstallArgs(InstallParams params) { 9192 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9193 return new AsecInstallArgs(params); 9194 } else { 9195 return new FileInstallArgs(params); 9196 } 9197 } 9198 9199 /** 9200 * Create args that describe an existing installed package. Typically used 9201 * when cleaning up old installs, or used as a move source. 9202 */ 9203 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9204 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9205 final boolean isInAsec; 9206 if (installOnSd(installFlags)) { 9207 /* Apps on SD card are always in ASEC containers. */ 9208 isInAsec = true; 9209 } else if (installForwardLocked(installFlags) 9210 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9211 /* 9212 * Forward-locked apps are only in ASEC containers if they're the 9213 * new style 9214 */ 9215 isInAsec = true; 9216 } else { 9217 isInAsec = false; 9218 } 9219 9220 if (isInAsec) { 9221 return new AsecInstallArgs(codePath, instructionSets, 9222 installOnSd(installFlags), installForwardLocked(installFlags)); 9223 } else { 9224 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9225 instructionSets); 9226 } 9227 } 9228 9229 static abstract class InstallArgs { 9230 /** @see InstallParams#origin */ 9231 final OriginInfo origin; 9232 9233 final IPackageInstallObserver2 observer; 9234 // Always refers to PackageManager flags only 9235 final int installFlags; 9236 final String installerPackageName; 9237 final ManifestDigest manifestDigest; 9238 final UserHandle user; 9239 final String abiOverride; 9240 9241 // The list of instruction sets supported by this app. This is currently 9242 // only used during the rmdex() phase to clean up resources. We can get rid of this 9243 // if we move dex files under the common app path. 9244 /* nullable */ String[] instructionSets; 9245 9246 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9247 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9248 String[] instructionSets, String abiOverride) { 9249 this.origin = origin; 9250 this.installFlags = installFlags; 9251 this.observer = observer; 9252 this.installerPackageName = installerPackageName; 9253 this.manifestDigest = manifestDigest; 9254 this.user = user; 9255 this.instructionSets = instructionSets; 9256 this.abiOverride = abiOverride; 9257 } 9258 9259 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9260 abstract int doPreInstall(int status); 9261 9262 /** 9263 * Rename package into final resting place. All paths on the given 9264 * scanned package should be updated to reflect the rename. 9265 */ 9266 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9267 abstract int doPostInstall(int status, int uid); 9268 9269 /** @see PackageSettingBase#codePathString */ 9270 abstract String getCodePath(); 9271 /** @see PackageSettingBase#resourcePathString */ 9272 abstract String getResourcePath(); 9273 abstract String getLegacyNativeLibraryPath(); 9274 9275 // Need installer lock especially for dex file removal. 9276 abstract void cleanUpResourcesLI(); 9277 abstract boolean doPostDeleteLI(boolean delete); 9278 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9279 9280 /** 9281 * Called before the source arguments are copied. This is used mostly 9282 * for MoveParams when it needs to read the source file to put it in the 9283 * destination. 9284 */ 9285 int doPreCopy() { 9286 return PackageManager.INSTALL_SUCCEEDED; 9287 } 9288 9289 /** 9290 * Called after the source arguments are copied. This is used mostly for 9291 * MoveParams when it needs to read the source file to put it in the 9292 * destination. 9293 * 9294 * @return 9295 */ 9296 int doPostCopy(int uid) { 9297 return PackageManager.INSTALL_SUCCEEDED; 9298 } 9299 9300 protected boolean isFwdLocked() { 9301 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9302 } 9303 9304 protected boolean isExternal() { 9305 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9306 } 9307 9308 UserHandle getUser() { 9309 return user; 9310 } 9311 } 9312 9313 /** 9314 * Logic to handle installation of non-ASEC applications, including copying 9315 * and renaming logic. 9316 */ 9317 class FileInstallArgs extends InstallArgs { 9318 private File codeFile; 9319 private File resourceFile; 9320 private File legacyNativeLibraryPath; 9321 9322 // Example topology: 9323 // /data/app/com.example/base.apk 9324 // /data/app/com.example/split_foo.apk 9325 // /data/app/com.example/lib/arm/libfoo.so 9326 // /data/app/com.example/lib/arm64/libfoo.so 9327 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9328 9329 /** New install */ 9330 FileInstallArgs(InstallParams params) { 9331 super(params.origin, params.observer, params.installFlags, 9332 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9333 null /* instruction sets */, params.packageAbiOverride); 9334 if (isFwdLocked()) { 9335 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9336 } 9337 } 9338 9339 /** Existing install */ 9340 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9341 String[] instructionSets) { 9342 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9343 this.codeFile = (codePath != null) ? new File(codePath) : null; 9344 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9345 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9346 new File(legacyNativeLibraryPath) : null; 9347 } 9348 9349 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9350 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9351 isFwdLocked(), abiOverride); 9352 9353 final StorageManager storage = StorageManager.from(mContext); 9354 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9355 } 9356 9357 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9358 if (origin.staged) { 9359 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9360 codeFile = origin.file; 9361 resourceFile = origin.file; 9362 return PackageManager.INSTALL_SUCCEEDED; 9363 } 9364 9365 try { 9366 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9367 codeFile = tempDir; 9368 resourceFile = tempDir; 9369 } catch (IOException e) { 9370 Slog.w(TAG, "Failed to create copy file: " + e); 9371 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9372 } 9373 9374 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9375 @Override 9376 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9377 if (!FileUtils.isValidExtFilename(name)) { 9378 throw new IllegalArgumentException("Invalid filename: " + name); 9379 } 9380 try { 9381 final File file = new File(codeFile, name); 9382 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9383 O_RDWR | O_CREAT, 0644); 9384 Os.chmod(file.getAbsolutePath(), 0644); 9385 return new ParcelFileDescriptor(fd); 9386 } catch (ErrnoException e) { 9387 throw new RemoteException("Failed to open: " + e.getMessage()); 9388 } 9389 } 9390 }; 9391 9392 int ret = PackageManager.INSTALL_SUCCEEDED; 9393 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9394 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9395 Slog.e(TAG, "Failed to copy package"); 9396 return ret; 9397 } 9398 9399 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9400 NativeLibraryHelper.Handle handle = null; 9401 try { 9402 handle = NativeLibraryHelper.Handle.create(codeFile); 9403 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9404 abiOverride); 9405 } catch (IOException e) { 9406 Slog.e(TAG, "Copying native libraries failed", e); 9407 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9408 } finally { 9409 IoUtils.closeQuietly(handle); 9410 } 9411 9412 return ret; 9413 } 9414 9415 int doPreInstall(int status) { 9416 if (status != PackageManager.INSTALL_SUCCEEDED) { 9417 cleanUp(); 9418 } 9419 return status; 9420 } 9421 9422 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9423 if (status != PackageManager.INSTALL_SUCCEEDED) { 9424 cleanUp(); 9425 return false; 9426 } else { 9427 final File beforeCodeFile = codeFile; 9428 final File afterCodeFile = getNextCodePath(pkg.packageName); 9429 9430 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9431 try { 9432 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9433 } catch (ErrnoException e) { 9434 Slog.d(TAG, "Failed to rename", e); 9435 return false; 9436 } 9437 9438 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9439 Slog.d(TAG, "Failed to restorecon"); 9440 return false; 9441 } 9442 9443 // Reflect the rename internally 9444 codeFile = afterCodeFile; 9445 resourceFile = afterCodeFile; 9446 9447 // Reflect the rename in scanned details 9448 pkg.codePath = afterCodeFile.getAbsolutePath(); 9449 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9450 pkg.baseCodePath); 9451 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9452 pkg.splitCodePaths); 9453 9454 // Reflect the rename in app info 9455 pkg.applicationInfo.setCodePath(pkg.codePath); 9456 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9457 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9458 pkg.applicationInfo.setResourcePath(pkg.codePath); 9459 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9460 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9461 9462 return true; 9463 } 9464 } 9465 9466 int doPostInstall(int status, int uid) { 9467 if (status != PackageManager.INSTALL_SUCCEEDED) { 9468 cleanUp(); 9469 } 9470 return status; 9471 } 9472 9473 @Override 9474 String getCodePath() { 9475 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9476 } 9477 9478 @Override 9479 String getResourcePath() { 9480 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9481 } 9482 9483 @Override 9484 String getLegacyNativeLibraryPath() { 9485 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9486 } 9487 9488 private boolean cleanUp() { 9489 if (codeFile == null || !codeFile.exists()) { 9490 return false; 9491 } 9492 9493 if (codeFile.isDirectory()) { 9494 FileUtils.deleteContents(codeFile); 9495 } 9496 codeFile.delete(); 9497 9498 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9499 resourceFile.delete(); 9500 } 9501 9502 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9503 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9504 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9505 } 9506 legacyNativeLibraryPath.delete(); 9507 } 9508 9509 return true; 9510 } 9511 9512 void cleanUpResourcesLI() { 9513 // Try enumerating all code paths before deleting 9514 List<String> allCodePaths = Collections.EMPTY_LIST; 9515 if (codeFile != null && codeFile.exists()) { 9516 try { 9517 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9518 allCodePaths = pkg.getAllCodePaths(); 9519 } catch (PackageParserException e) { 9520 // Ignored; we tried our best 9521 } 9522 } 9523 9524 cleanUp(); 9525 9526 if (!allCodePaths.isEmpty()) { 9527 if (instructionSets == null) { 9528 throw new IllegalStateException("instructionSet == null"); 9529 } 9530 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9531 for (String codePath : allCodePaths) { 9532 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9533 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9534 if (retCode < 0) { 9535 Slog.w(TAG, "Couldn't remove dex file for package: " 9536 + " at location " + codePath + ", retcode=" + retCode); 9537 // we don't consider this to be a failure of the core package deletion 9538 } 9539 } 9540 } 9541 } 9542 } 9543 9544 boolean doPostDeleteLI(boolean delete) { 9545 // XXX err, shouldn't we respect the delete flag? 9546 cleanUpResourcesLI(); 9547 return true; 9548 } 9549 } 9550 9551 private boolean isAsecExternal(String cid) { 9552 final String asecPath = PackageHelper.getSdFilesystem(cid); 9553 return !asecPath.startsWith(mAsecInternalPath); 9554 } 9555 9556 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9557 PackageManagerException { 9558 if (copyRet < 0) { 9559 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9560 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9561 throw new PackageManagerException(copyRet, message); 9562 } 9563 } 9564 } 9565 9566 /** 9567 * Extract the MountService "container ID" from the full code path of an 9568 * .apk. 9569 */ 9570 static String cidFromCodePath(String fullCodePath) { 9571 int eidx = fullCodePath.lastIndexOf("/"); 9572 String subStr1 = fullCodePath.substring(0, eidx); 9573 int sidx = subStr1.lastIndexOf("/"); 9574 return subStr1.substring(sidx+1, eidx); 9575 } 9576 9577 /** 9578 * Logic to handle installation of ASEC applications, including copying and 9579 * renaming logic. 9580 */ 9581 class AsecInstallArgs extends InstallArgs { 9582 static final String RES_FILE_NAME = "pkg.apk"; 9583 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9584 9585 String cid; 9586 String packagePath; 9587 String resourcePath; 9588 String legacyNativeLibraryDir; 9589 9590 /** New install */ 9591 AsecInstallArgs(InstallParams params) { 9592 super(params.origin, params.observer, params.installFlags, 9593 params.installerPackageName, params.getManifestDigest(), 9594 params.getUser(), null /* instruction sets */, 9595 params.packageAbiOverride); 9596 } 9597 9598 /** Existing install */ 9599 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9600 boolean isExternal, boolean isForwardLocked) { 9601 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9602 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9603 instructionSets, null); 9604 // Hackily pretend we're still looking at a full code path 9605 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9606 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9607 } 9608 9609 // Extract cid from fullCodePath 9610 int eidx = fullCodePath.lastIndexOf("/"); 9611 String subStr1 = fullCodePath.substring(0, eidx); 9612 int sidx = subStr1.lastIndexOf("/"); 9613 cid = subStr1.substring(sidx+1, eidx); 9614 setMountPath(subStr1); 9615 } 9616 9617 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9618 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9619 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9620 instructionSets, null); 9621 this.cid = cid; 9622 setMountPath(PackageHelper.getSdDir(cid)); 9623 } 9624 9625 void createCopyFile() { 9626 cid = mInstallerService.allocateExternalStageCidLegacy(); 9627 } 9628 9629 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9630 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9631 abiOverride); 9632 9633 final File target; 9634 if (isExternal()) { 9635 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9636 } else { 9637 target = Environment.getDataDirectory(); 9638 } 9639 9640 final StorageManager storage = StorageManager.from(mContext); 9641 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9642 } 9643 9644 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9645 if (origin.staged) { 9646 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9647 cid = origin.cid; 9648 setMountPath(PackageHelper.getSdDir(cid)); 9649 return PackageManager.INSTALL_SUCCEEDED; 9650 } 9651 9652 if (temp) { 9653 createCopyFile(); 9654 } else { 9655 /* 9656 * Pre-emptively destroy the container since it's destroyed if 9657 * copying fails due to it existing anyway. 9658 */ 9659 PackageHelper.destroySdDir(cid); 9660 } 9661 9662 final String newMountPath = imcs.copyPackageToContainer( 9663 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9664 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9665 9666 if (newMountPath != null) { 9667 setMountPath(newMountPath); 9668 return PackageManager.INSTALL_SUCCEEDED; 9669 } else { 9670 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9671 } 9672 } 9673 9674 @Override 9675 String getCodePath() { 9676 return packagePath; 9677 } 9678 9679 @Override 9680 String getResourcePath() { 9681 return resourcePath; 9682 } 9683 9684 @Override 9685 String getLegacyNativeLibraryPath() { 9686 return legacyNativeLibraryDir; 9687 } 9688 9689 int doPreInstall(int status) { 9690 if (status != PackageManager.INSTALL_SUCCEEDED) { 9691 // Destroy container 9692 PackageHelper.destroySdDir(cid); 9693 } else { 9694 boolean mounted = PackageHelper.isContainerMounted(cid); 9695 if (!mounted) { 9696 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9697 Process.SYSTEM_UID); 9698 if (newMountPath != null) { 9699 setMountPath(newMountPath); 9700 } else { 9701 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9702 } 9703 } 9704 } 9705 return status; 9706 } 9707 9708 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9709 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9710 String newMountPath = null; 9711 if (PackageHelper.isContainerMounted(cid)) { 9712 // Unmount the container 9713 if (!PackageHelper.unMountSdDir(cid)) { 9714 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9715 return false; 9716 } 9717 } 9718 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9719 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9720 " which might be stale. Will try to clean up."); 9721 // Clean up the stale container and proceed to recreate. 9722 if (!PackageHelper.destroySdDir(newCacheId)) { 9723 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9724 return false; 9725 } 9726 // Successfully cleaned up stale container. Try to rename again. 9727 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9728 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9729 + " inspite of cleaning it up."); 9730 return false; 9731 } 9732 } 9733 if (!PackageHelper.isContainerMounted(newCacheId)) { 9734 Slog.w(TAG, "Mounting container " + newCacheId); 9735 newMountPath = PackageHelper.mountSdDir(newCacheId, 9736 getEncryptKey(), Process.SYSTEM_UID); 9737 } else { 9738 newMountPath = PackageHelper.getSdDir(newCacheId); 9739 } 9740 if (newMountPath == null) { 9741 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9742 return false; 9743 } 9744 Log.i(TAG, "Succesfully renamed " + cid + 9745 " to " + newCacheId + 9746 " at new path: " + newMountPath); 9747 cid = newCacheId; 9748 9749 final File beforeCodeFile = new File(packagePath); 9750 setMountPath(newMountPath); 9751 final File afterCodeFile = new File(packagePath); 9752 9753 // Reflect the rename in scanned details 9754 pkg.codePath = afterCodeFile.getAbsolutePath(); 9755 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9756 pkg.baseCodePath); 9757 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9758 pkg.splitCodePaths); 9759 9760 // Reflect the rename in app info 9761 pkg.applicationInfo.setCodePath(pkg.codePath); 9762 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9763 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9764 pkg.applicationInfo.setResourcePath(pkg.codePath); 9765 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9766 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9767 9768 return true; 9769 } 9770 9771 private void setMountPath(String mountPath) { 9772 final File mountFile = new File(mountPath); 9773 9774 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9775 if (monolithicFile.exists()) { 9776 packagePath = monolithicFile.getAbsolutePath(); 9777 if (isFwdLocked()) { 9778 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9779 } else { 9780 resourcePath = packagePath; 9781 } 9782 } else { 9783 packagePath = mountFile.getAbsolutePath(); 9784 resourcePath = packagePath; 9785 } 9786 9787 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9788 } 9789 9790 int doPostInstall(int status, int uid) { 9791 if (status != PackageManager.INSTALL_SUCCEEDED) { 9792 cleanUp(); 9793 } else { 9794 final int groupOwner; 9795 final String protectedFile; 9796 if (isFwdLocked()) { 9797 groupOwner = UserHandle.getSharedAppGid(uid); 9798 protectedFile = RES_FILE_NAME; 9799 } else { 9800 groupOwner = -1; 9801 protectedFile = null; 9802 } 9803 9804 if (uid < Process.FIRST_APPLICATION_UID 9805 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9806 Slog.e(TAG, "Failed to finalize " + cid); 9807 PackageHelper.destroySdDir(cid); 9808 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9809 } 9810 9811 boolean mounted = PackageHelper.isContainerMounted(cid); 9812 if (!mounted) { 9813 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9814 } 9815 } 9816 return status; 9817 } 9818 9819 private void cleanUp() { 9820 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9821 9822 // Destroy secure container 9823 PackageHelper.destroySdDir(cid); 9824 } 9825 9826 private List<String> getAllCodePaths() { 9827 final File codeFile = new File(getCodePath()); 9828 if (codeFile != null && codeFile.exists()) { 9829 try { 9830 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9831 return pkg.getAllCodePaths(); 9832 } catch (PackageParserException e) { 9833 // Ignored; we tried our best 9834 } 9835 } 9836 return Collections.EMPTY_LIST; 9837 } 9838 9839 void cleanUpResourcesLI() { 9840 // Enumerate all code paths before deleting 9841 cleanUpResourcesLI(getAllCodePaths()); 9842 } 9843 9844 private void cleanUpResourcesLI(List<String> allCodePaths) { 9845 cleanUp(); 9846 9847 if (!allCodePaths.isEmpty()) { 9848 if (instructionSets == null) { 9849 throw new IllegalStateException("instructionSet == null"); 9850 } 9851 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9852 for (String codePath : allCodePaths) { 9853 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9854 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9855 if (retCode < 0) { 9856 Slog.w(TAG, "Couldn't remove dex file for package: " 9857 + " at location " + codePath + ", retcode=" + retCode); 9858 // we don't consider this to be a failure of the core package deletion 9859 } 9860 } 9861 } 9862 } 9863 } 9864 9865 boolean matchContainer(String app) { 9866 if (cid.startsWith(app)) { 9867 return true; 9868 } 9869 return false; 9870 } 9871 9872 String getPackageName() { 9873 return getAsecPackageName(cid); 9874 } 9875 9876 boolean doPostDeleteLI(boolean delete) { 9877 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9878 final List<String> allCodePaths = getAllCodePaths(); 9879 boolean mounted = PackageHelper.isContainerMounted(cid); 9880 if (mounted) { 9881 // Unmount first 9882 if (PackageHelper.unMountSdDir(cid)) { 9883 mounted = false; 9884 } 9885 } 9886 if (!mounted && delete) { 9887 cleanUpResourcesLI(allCodePaths); 9888 } 9889 return !mounted; 9890 } 9891 9892 @Override 9893 int doPreCopy() { 9894 if (isFwdLocked()) { 9895 if (!PackageHelper.fixSdPermissions(cid, 9896 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9897 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9898 } 9899 } 9900 9901 return PackageManager.INSTALL_SUCCEEDED; 9902 } 9903 9904 @Override 9905 int doPostCopy(int uid) { 9906 if (isFwdLocked()) { 9907 if (uid < Process.FIRST_APPLICATION_UID 9908 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9909 RES_FILE_NAME)) { 9910 Slog.e(TAG, "Failed to finalize " + cid); 9911 PackageHelper.destroySdDir(cid); 9912 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9913 } 9914 } 9915 9916 return PackageManager.INSTALL_SUCCEEDED; 9917 } 9918 } 9919 9920 static String getAsecPackageName(String packageCid) { 9921 int idx = packageCid.lastIndexOf("-"); 9922 if (idx == -1) { 9923 return packageCid; 9924 } 9925 return packageCid.substring(0, idx); 9926 } 9927 9928 // Utility method used to create code paths based on package name and available index. 9929 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9930 String idxStr = ""; 9931 int idx = 1; 9932 // Fall back to default value of idx=1 if prefix is not 9933 // part of oldCodePath 9934 if (oldCodePath != null) { 9935 String subStr = oldCodePath; 9936 // Drop the suffix right away 9937 if (suffix != null && subStr.endsWith(suffix)) { 9938 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9939 } 9940 // If oldCodePath already contains prefix find out the 9941 // ending index to either increment or decrement. 9942 int sidx = subStr.lastIndexOf(prefix); 9943 if (sidx != -1) { 9944 subStr = subStr.substring(sidx + prefix.length()); 9945 if (subStr != null) { 9946 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9947 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9948 } 9949 try { 9950 idx = Integer.parseInt(subStr); 9951 if (idx <= 1) { 9952 idx++; 9953 } else { 9954 idx--; 9955 } 9956 } catch(NumberFormatException e) { 9957 } 9958 } 9959 } 9960 } 9961 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9962 return prefix + idxStr; 9963 } 9964 9965 private File getNextCodePath(String packageName) { 9966 int suffix = 1; 9967 File result; 9968 do { 9969 result = new File(mAppInstallDir, packageName + "-" + suffix); 9970 suffix++; 9971 } while (result.exists()); 9972 return result; 9973 } 9974 9975 // Utility method used to ignore ADD/REMOVE events 9976 // by directory observer. 9977 private static boolean ignoreCodePath(String fullPathStr) { 9978 String apkName = deriveCodePathName(fullPathStr); 9979 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9980 if (idx != -1 && ((idx+1) < apkName.length())) { 9981 // Make sure the package ends with a numeral 9982 String version = apkName.substring(idx+1); 9983 try { 9984 Integer.parseInt(version); 9985 return true; 9986 } catch (NumberFormatException e) {} 9987 } 9988 return false; 9989 } 9990 9991 // Utility method that returns the relative package path with respect 9992 // to the installation directory. Like say for /data/data/com.test-1.apk 9993 // string com.test-1 is returned. 9994 static String deriveCodePathName(String codePath) { 9995 if (codePath == null) { 9996 return null; 9997 } 9998 final File codeFile = new File(codePath); 9999 final String name = codeFile.getName(); 10000 if (codeFile.isDirectory()) { 10001 return name; 10002 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10003 final int lastDot = name.lastIndexOf('.'); 10004 return name.substring(0, lastDot); 10005 } else { 10006 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10007 return null; 10008 } 10009 } 10010 10011 class PackageInstalledInfo { 10012 String name; 10013 int uid; 10014 // The set of users that originally had this package installed. 10015 int[] origUsers; 10016 // The set of users that now have this package installed. 10017 int[] newUsers; 10018 PackageParser.Package pkg; 10019 int returnCode; 10020 String returnMsg; 10021 PackageRemovedInfo removedInfo; 10022 10023 public void setError(int code, String msg) { 10024 returnCode = code; 10025 returnMsg = msg; 10026 Slog.w(TAG, msg); 10027 } 10028 10029 public void setError(String msg, PackageParserException e) { 10030 returnCode = e.error; 10031 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10032 Slog.w(TAG, msg, e); 10033 } 10034 10035 public void setError(String msg, PackageManagerException e) { 10036 returnCode = e.error; 10037 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10038 Slog.w(TAG, msg, e); 10039 } 10040 10041 // In some error cases we want to convey more info back to the observer 10042 String origPackage; 10043 String origPermission; 10044 } 10045 10046 /* 10047 * Install a non-existing package. 10048 */ 10049 private void installNewPackageLI(PackageParser.Package pkg, 10050 int parseFlags, int scanFlags, UserHandle user, 10051 String installerPackageName, PackageInstalledInfo res) { 10052 // Remember this for later, in case we need to rollback this install 10053 String pkgName = pkg.packageName; 10054 10055 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10056 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10057 synchronized(mPackages) { 10058 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10059 // A package with the same name is already installed, though 10060 // it has been renamed to an older name. The package we 10061 // are trying to install should be installed as an update to 10062 // the existing one, but that has not been requested, so bail. 10063 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10064 + " without first uninstalling package running as " 10065 + mSettings.mRenamedPackages.get(pkgName)); 10066 return; 10067 } 10068 if (mPackages.containsKey(pkgName)) { 10069 // Don't allow installation over an existing package with the same name. 10070 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10071 + " without first uninstalling."); 10072 return; 10073 } 10074 } 10075 10076 try { 10077 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10078 System.currentTimeMillis(), user); 10079 10080 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10081 // delete the partially installed application. the data directory will have to be 10082 // restored if it was already existing 10083 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10084 // remove package from internal structures. Note that we want deletePackageX to 10085 // delete the package data and cache directories that it created in 10086 // scanPackageLocked, unless those directories existed before we even tried to 10087 // install. 10088 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10089 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10090 res.removedInfo, true); 10091 } 10092 10093 } catch (PackageManagerException e) { 10094 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10095 } 10096 } 10097 10098 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10099 // Upgrade keysets are being used. Determine if new package has a superset of the 10100 // required keys. 10101 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10102 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10103 for (int i = 0; i < upgradeKeySets.length; i++) { 10104 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10105 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10106 return true; 10107 } 10108 } 10109 return false; 10110 } 10111 10112 private void replacePackageLI(PackageParser.Package pkg, 10113 int parseFlags, int scanFlags, UserHandle user, 10114 String installerPackageName, PackageInstalledInfo res) { 10115 PackageParser.Package oldPackage; 10116 String pkgName = pkg.packageName; 10117 int[] allUsers; 10118 boolean[] perUserInstalled; 10119 10120 // First find the old package info and check signatures 10121 synchronized(mPackages) { 10122 oldPackage = mPackages.get(pkgName); 10123 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10124 PackageSetting ps = mSettings.mPackages.get(pkgName); 10125 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10126 // default to original signature matching 10127 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10128 != PackageManager.SIGNATURE_MATCH) { 10129 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10130 "New package has a different signature: " + pkgName); 10131 return; 10132 } 10133 } else { 10134 if(!checkUpgradeKeySetLP(ps, pkg)) { 10135 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10136 "New package not signed by keys specified by upgrade-keysets: " 10137 + pkgName); 10138 return; 10139 } 10140 } 10141 10142 // In case of rollback, remember per-user/profile install state 10143 allUsers = sUserManager.getUserIds(); 10144 perUserInstalled = new boolean[allUsers.length]; 10145 for (int i = 0; i < allUsers.length; i++) { 10146 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10147 } 10148 } 10149 10150 boolean sysPkg = (isSystemApp(oldPackage)); 10151 if (sysPkg) { 10152 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10153 user, allUsers, perUserInstalled, installerPackageName, res); 10154 } else { 10155 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10156 user, allUsers, perUserInstalled, installerPackageName, res); 10157 } 10158 } 10159 10160 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10161 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10162 int[] allUsers, boolean[] perUserInstalled, 10163 String installerPackageName, PackageInstalledInfo res) { 10164 String pkgName = deletedPackage.packageName; 10165 boolean deletedPkg = true; 10166 boolean updatedSettings = false; 10167 10168 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10169 + deletedPackage); 10170 long origUpdateTime; 10171 if (pkg.mExtras != null) { 10172 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10173 } else { 10174 origUpdateTime = 0; 10175 } 10176 10177 // First delete the existing package while retaining the data directory 10178 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10179 res.removedInfo, true)) { 10180 // If the existing package wasn't successfully deleted 10181 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10182 deletedPkg = false; 10183 } else { 10184 // Successfully deleted the old package; proceed with replace. 10185 10186 // If deleted package lived in a container, give users a chance to 10187 // relinquish resources before killing. 10188 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10189 if (DEBUG_INSTALL) { 10190 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10191 } 10192 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10193 final ArrayList<String> pkgList = new ArrayList<String>(1); 10194 pkgList.add(deletedPackage.applicationInfo.packageName); 10195 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10196 } 10197 10198 deleteCodeCacheDirsLI(pkgName); 10199 try { 10200 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10201 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10202 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10203 updatedSettings = true; 10204 } catch (PackageManagerException e) { 10205 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10206 } 10207 } 10208 10209 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10210 // remove package from internal structures. Note that we want deletePackageX to 10211 // delete the package data and cache directories that it created in 10212 // scanPackageLocked, unless those directories existed before we even tried to 10213 // install. 10214 if(updatedSettings) { 10215 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10216 deletePackageLI( 10217 pkgName, null, true, allUsers, perUserInstalled, 10218 PackageManager.DELETE_KEEP_DATA, 10219 res.removedInfo, true); 10220 } 10221 // Since we failed to install the new package we need to restore the old 10222 // package that we deleted. 10223 if (deletedPkg) { 10224 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10225 File restoreFile = new File(deletedPackage.codePath); 10226 // Parse old package 10227 boolean oldOnSd = isExternal(deletedPackage); 10228 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10229 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10230 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10231 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10232 try { 10233 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10234 } catch (PackageManagerException e) { 10235 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10236 + e.getMessage()); 10237 return; 10238 } 10239 // Restore of old package succeeded. Update permissions. 10240 // writer 10241 synchronized (mPackages) { 10242 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10243 UPDATE_PERMISSIONS_ALL); 10244 // can downgrade to reader 10245 mSettings.writeLPr(); 10246 } 10247 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10248 } 10249 } 10250 } 10251 10252 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10253 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10254 int[] allUsers, boolean[] perUserInstalled, 10255 String installerPackageName, PackageInstalledInfo res) { 10256 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10257 + ", old=" + deletedPackage); 10258 boolean disabledSystem = false; 10259 boolean updatedSettings = false; 10260 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10261 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10262 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10263 } 10264 String packageName = deletedPackage.packageName; 10265 if (packageName == null) { 10266 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10267 "Attempt to delete null packageName."); 10268 return; 10269 } 10270 PackageParser.Package oldPkg; 10271 PackageSetting oldPkgSetting; 10272 // reader 10273 synchronized (mPackages) { 10274 oldPkg = mPackages.get(packageName); 10275 oldPkgSetting = mSettings.mPackages.get(packageName); 10276 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10277 (oldPkgSetting == null)) { 10278 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10279 "Couldn't find package:" + packageName + " information"); 10280 return; 10281 } 10282 } 10283 10284 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10285 10286 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10287 res.removedInfo.removedPackage = packageName; 10288 // Remove existing system package 10289 removePackageLI(oldPkgSetting, true); 10290 // writer 10291 synchronized (mPackages) { 10292 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10293 if (!disabledSystem && deletedPackage != null) { 10294 // We didn't need to disable the .apk as a current system package, 10295 // which means we are replacing another update that is already 10296 // installed. We need to make sure to delete the older one's .apk. 10297 res.removedInfo.args = createInstallArgsForExisting(0, 10298 deletedPackage.applicationInfo.getCodePath(), 10299 deletedPackage.applicationInfo.getResourcePath(), 10300 deletedPackage.applicationInfo.nativeLibraryRootDir, 10301 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10302 } else { 10303 res.removedInfo.args = null; 10304 } 10305 } 10306 10307 // Successfully disabled the old package. Now proceed with re-installation 10308 deleteCodeCacheDirsLI(packageName); 10309 10310 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10311 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10312 10313 PackageParser.Package newPackage = null; 10314 try { 10315 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10316 if (newPackage.mExtras != null) { 10317 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10318 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10319 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10320 10321 // is the update attempting to change shared user? that isn't going to work... 10322 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10323 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10324 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10325 + " to " + newPkgSetting.sharedUser); 10326 updatedSettings = true; 10327 } 10328 } 10329 10330 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10331 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10332 updatedSettings = true; 10333 } 10334 10335 } catch (PackageManagerException e) { 10336 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10337 } 10338 10339 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10340 // Re installation failed. Restore old information 10341 // Remove new pkg information 10342 if (newPackage != null) { 10343 removeInstalledPackageLI(newPackage, true); 10344 } 10345 // Add back the old system package 10346 try { 10347 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10348 } catch (PackageManagerException e) { 10349 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10350 } 10351 // Restore the old system information in Settings 10352 synchronized (mPackages) { 10353 if (disabledSystem) { 10354 mSettings.enableSystemPackageLPw(packageName); 10355 } 10356 if (updatedSettings) { 10357 mSettings.setInstallerPackageName(packageName, 10358 oldPkgSetting.installerPackageName); 10359 } 10360 mSettings.writeLPr(); 10361 } 10362 } 10363 } 10364 10365 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10366 int[] allUsers, boolean[] perUserInstalled, 10367 PackageInstalledInfo res) { 10368 String pkgName = newPackage.packageName; 10369 synchronized (mPackages) { 10370 //write settings. the installStatus will be incomplete at this stage. 10371 //note that the new package setting would have already been 10372 //added to mPackages. It hasn't been persisted yet. 10373 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10374 mSettings.writeLPr(); 10375 } 10376 10377 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10378 10379 synchronized (mPackages) { 10380 updatePermissionsLPw(newPackage.packageName, newPackage, 10381 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10382 ? UPDATE_PERMISSIONS_ALL : 0)); 10383 // For system-bundled packages, we assume that installing an upgraded version 10384 // of the package implies that the user actually wants to run that new code, 10385 // so we enable the package. 10386 if (isSystemApp(newPackage)) { 10387 // NB: implicit assumption that system package upgrades apply to all users 10388 if (DEBUG_INSTALL) { 10389 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10390 } 10391 PackageSetting ps = mSettings.mPackages.get(pkgName); 10392 if (ps != null) { 10393 if (res.origUsers != null) { 10394 for (int userHandle : res.origUsers) { 10395 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10396 userHandle, installerPackageName); 10397 } 10398 } 10399 // Also convey the prior install/uninstall state 10400 if (allUsers != null && perUserInstalled != null) { 10401 for (int i = 0; i < allUsers.length; i++) { 10402 if (DEBUG_INSTALL) { 10403 Slog.d(TAG, " user " + allUsers[i] 10404 + " => " + perUserInstalled[i]); 10405 } 10406 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10407 } 10408 // these install state changes will be persisted in the 10409 // upcoming call to mSettings.writeLPr(). 10410 } 10411 } 10412 } 10413 res.name = pkgName; 10414 res.uid = newPackage.applicationInfo.uid; 10415 res.pkg = newPackage; 10416 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10417 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10418 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10419 //to update install status 10420 mSettings.writeLPr(); 10421 } 10422 } 10423 10424 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10425 final int installFlags = args.installFlags; 10426 String installerPackageName = args.installerPackageName; 10427 File tmpPackageFile = new File(args.getCodePath()); 10428 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10429 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10430 boolean replace = false; 10431 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10432 // Result object to be returned 10433 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10434 10435 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10436 // Retrieve PackageSettings and parse package 10437 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10438 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10439 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10440 PackageParser pp = new PackageParser(); 10441 pp.setSeparateProcesses(mSeparateProcesses); 10442 pp.setDisplayMetrics(mMetrics); 10443 10444 final PackageParser.Package pkg; 10445 try { 10446 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10447 } catch (PackageParserException e) { 10448 res.setError("Failed parse during installPackageLI", e); 10449 return; 10450 } 10451 10452 // Mark that we have an install time CPU ABI override. 10453 pkg.cpuAbiOverride = args.abiOverride; 10454 10455 String pkgName = res.name = pkg.packageName; 10456 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10457 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10458 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10459 return; 10460 } 10461 } 10462 10463 try { 10464 pp.collectCertificates(pkg, parseFlags); 10465 pp.collectManifestDigest(pkg); 10466 } catch (PackageParserException e) { 10467 res.setError("Failed collect during installPackageLI", e); 10468 return; 10469 } 10470 10471 /* If the installer passed in a manifest digest, compare it now. */ 10472 if (args.manifestDigest != null) { 10473 if (DEBUG_INSTALL) { 10474 final String parsedManifest = pkg.manifestDigest == null ? "null" 10475 : pkg.manifestDigest.toString(); 10476 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10477 + parsedManifest); 10478 } 10479 10480 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10481 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10482 return; 10483 } 10484 } else if (DEBUG_INSTALL) { 10485 final String parsedManifest = pkg.manifestDigest == null 10486 ? "null" : pkg.manifestDigest.toString(); 10487 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10488 } 10489 10490 // Get rid of all references to package scan path via parser. 10491 pp = null; 10492 String oldCodePath = null; 10493 boolean systemApp = false; 10494 synchronized (mPackages) { 10495 // Check whether the newly-scanned package wants to define an already-defined perm 10496 int N = pkg.permissions.size(); 10497 for (int i = N-1; i >= 0; i--) { 10498 PackageParser.Permission perm = pkg.permissions.get(i); 10499 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10500 if (bp != null) { 10501 // If the defining package is signed with our cert, it's okay. This 10502 // also includes the "updating the same package" case, of course. 10503 // "updating same package" could also involve key-rotation. 10504 final boolean sigsOk; 10505 if (!bp.sourcePackage.equals(pkg.packageName) 10506 || !(bp.packageSetting instanceof PackageSetting) 10507 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10508 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10509 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10510 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10511 } else { 10512 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10513 } 10514 if (!sigsOk) { 10515 // If the owning package is the system itself, we log but allow 10516 // install to proceed; we fail the install on all other permission 10517 // redefinitions. 10518 if (!bp.sourcePackage.equals("android")) { 10519 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10520 + pkg.packageName + " attempting to redeclare permission " 10521 + perm.info.name + " already owned by " + bp.sourcePackage); 10522 res.origPermission = perm.info.name; 10523 res.origPackage = bp.sourcePackage; 10524 return; 10525 } else { 10526 Slog.w(TAG, "Package " + pkg.packageName 10527 + " attempting to redeclare system permission " 10528 + perm.info.name + "; ignoring new declaration"); 10529 pkg.permissions.remove(i); 10530 } 10531 } 10532 } 10533 } 10534 10535 // Check if installing already existing package 10536 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10537 String oldName = mSettings.mRenamedPackages.get(pkgName); 10538 if (pkg.mOriginalPackages != null 10539 && pkg.mOriginalPackages.contains(oldName) 10540 && mPackages.containsKey(oldName)) { 10541 // This package is derived from an original package, 10542 // and this device has been updating from that original 10543 // name. We must continue using the original name, so 10544 // rename the new package here. 10545 pkg.setPackageName(oldName); 10546 pkgName = pkg.packageName; 10547 replace = true; 10548 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10549 + oldName + " pkgName=" + pkgName); 10550 } else if (mPackages.containsKey(pkgName)) { 10551 // This package, under its official name, already exists 10552 // on the device; we should replace it. 10553 replace = true; 10554 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10555 } 10556 } 10557 PackageSetting ps = mSettings.mPackages.get(pkgName); 10558 if (ps != null) { 10559 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10560 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10561 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10562 systemApp = (ps.pkg.applicationInfo.flags & 10563 ApplicationInfo.FLAG_SYSTEM) != 0; 10564 } 10565 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10566 } 10567 } 10568 10569 if (systemApp && onSd) { 10570 // Disable updates to system apps on sdcard 10571 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10572 "Cannot install updates to system apps on sdcard"); 10573 return; 10574 } 10575 10576 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10577 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10578 return; 10579 } 10580 10581 if (replace) { 10582 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10583 installerPackageName, res); 10584 } else { 10585 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10586 args.user, installerPackageName, res); 10587 } 10588 synchronized (mPackages) { 10589 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10590 if (ps != null) { 10591 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10592 } 10593 } 10594 } 10595 10596 private static boolean isForwardLocked(PackageParser.Package pkg) { 10597 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10598 } 10599 10600 private static boolean isForwardLocked(ApplicationInfo info) { 10601 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10602 } 10603 10604 private boolean isForwardLocked(PackageSetting ps) { 10605 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10606 } 10607 10608 private static boolean isMultiArch(PackageSetting ps) { 10609 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10610 } 10611 10612 private static boolean isMultiArch(ApplicationInfo info) { 10613 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10614 } 10615 10616 private static boolean isExternal(PackageParser.Package pkg) { 10617 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10618 } 10619 10620 private static boolean isExternal(PackageSetting ps) { 10621 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10622 } 10623 10624 private static boolean isExternal(ApplicationInfo info) { 10625 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10626 } 10627 10628 private static boolean isSystemApp(PackageParser.Package pkg) { 10629 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10630 } 10631 10632 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10633 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10634 } 10635 10636 private static boolean isSystemApp(ApplicationInfo info) { 10637 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10638 } 10639 10640 private static boolean isSystemApp(PackageSetting ps) { 10641 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10642 } 10643 10644 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10645 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10646 } 10647 10648 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10649 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10650 } 10651 10652 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10653 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10654 } 10655 10656 private int packageFlagsToInstallFlags(PackageSetting ps) { 10657 int installFlags = 0; 10658 if (isExternal(ps)) { 10659 installFlags |= PackageManager.INSTALL_EXTERNAL; 10660 } 10661 if (isForwardLocked(ps)) { 10662 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10663 } 10664 return installFlags; 10665 } 10666 10667 private void deleteTempPackageFiles() { 10668 final FilenameFilter filter = new FilenameFilter() { 10669 public boolean accept(File dir, String name) { 10670 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10671 } 10672 }; 10673 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10674 file.delete(); 10675 } 10676 } 10677 10678 @Override 10679 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10680 int flags) { 10681 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10682 flags); 10683 } 10684 10685 @Override 10686 public void deletePackage(final String packageName, 10687 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10688 mContext.enforceCallingOrSelfPermission( 10689 android.Manifest.permission.DELETE_PACKAGES, null); 10690 final int uid = Binder.getCallingUid(); 10691 if (UserHandle.getUserId(uid) != userId) { 10692 mContext.enforceCallingPermission( 10693 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10694 "deletePackage for user " + userId); 10695 } 10696 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10697 try { 10698 observer.onPackageDeleted(packageName, 10699 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10700 } catch (RemoteException re) { 10701 } 10702 return; 10703 } 10704 10705 boolean uninstallBlocked = false; 10706 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10707 int[] users = sUserManager.getUserIds(); 10708 for (int i = 0; i < users.length; ++i) { 10709 if (getBlockUninstallForUser(packageName, users[i])) { 10710 uninstallBlocked = true; 10711 break; 10712 } 10713 } 10714 } else { 10715 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10716 } 10717 if (uninstallBlocked) { 10718 try { 10719 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10720 null); 10721 } catch (RemoteException re) { 10722 } 10723 return; 10724 } 10725 10726 if (DEBUG_REMOVE) { 10727 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10728 } 10729 // Queue up an async operation since the package deletion may take a little while. 10730 mHandler.post(new Runnable() { 10731 public void run() { 10732 mHandler.removeCallbacks(this); 10733 final int returnCode = deletePackageX(packageName, userId, flags); 10734 if (observer != null) { 10735 try { 10736 observer.onPackageDeleted(packageName, returnCode, null); 10737 } catch (RemoteException e) { 10738 Log.i(TAG, "Observer no longer exists."); 10739 } //end catch 10740 } //end if 10741 } //end run 10742 }); 10743 } 10744 10745 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10746 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10747 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10748 try { 10749 if (dpm != null) { 10750 if (dpm.isDeviceOwner(packageName)) { 10751 return true; 10752 } 10753 int[] users; 10754 if (userId == UserHandle.USER_ALL) { 10755 users = sUserManager.getUserIds(); 10756 } else { 10757 users = new int[]{userId}; 10758 } 10759 for (int i = 0; i < users.length; ++i) { 10760 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10761 return true; 10762 } 10763 } 10764 } 10765 } catch (RemoteException e) { 10766 } 10767 return false; 10768 } 10769 10770 /** 10771 * This method is an internal method that could be get invoked either 10772 * to delete an installed package or to clean up a failed installation. 10773 * After deleting an installed package, a broadcast is sent to notify any 10774 * listeners that the package has been installed. For cleaning up a failed 10775 * installation, the broadcast is not necessary since the package's 10776 * installation wouldn't have sent the initial broadcast either 10777 * The key steps in deleting a package are 10778 * deleting the package information in internal structures like mPackages, 10779 * deleting the packages base directories through installd 10780 * updating mSettings to reflect current status 10781 * persisting settings for later use 10782 * sending a broadcast if necessary 10783 */ 10784 private int deletePackageX(String packageName, int userId, int flags) { 10785 final PackageRemovedInfo info = new PackageRemovedInfo(); 10786 final boolean res; 10787 10788 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10789 ? UserHandle.ALL : new UserHandle(userId); 10790 10791 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10792 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10793 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10794 } 10795 10796 boolean removedForAllUsers = false; 10797 boolean systemUpdate = false; 10798 10799 // for the uninstall-updates case and restricted profiles, remember the per- 10800 // userhandle installed state 10801 int[] allUsers; 10802 boolean[] perUserInstalled; 10803 synchronized (mPackages) { 10804 PackageSetting ps = mSettings.mPackages.get(packageName); 10805 allUsers = sUserManager.getUserIds(); 10806 perUserInstalled = new boolean[allUsers.length]; 10807 for (int i = 0; i < allUsers.length; i++) { 10808 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10809 } 10810 } 10811 10812 synchronized (mInstallLock) { 10813 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10814 res = deletePackageLI(packageName, removeForUser, 10815 true, allUsers, perUserInstalled, 10816 flags | REMOVE_CHATTY, info, true); 10817 systemUpdate = info.isRemovedPackageSystemUpdate; 10818 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10819 removedForAllUsers = true; 10820 } 10821 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10822 + " removedForAllUsers=" + removedForAllUsers); 10823 } 10824 10825 if (res) { 10826 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10827 10828 // If the removed package was a system update, the old system package 10829 // was re-enabled; we need to broadcast this information 10830 if (systemUpdate) { 10831 Bundle extras = new Bundle(1); 10832 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10833 ? info.removedAppId : info.uid); 10834 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10835 10836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10837 extras, null, null, null); 10838 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10839 extras, null, null, null); 10840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10841 null, packageName, null, null); 10842 } 10843 } 10844 // Force a gc here. 10845 Runtime.getRuntime().gc(); 10846 // Delete the resources here after sending the broadcast to let 10847 // other processes clean up before deleting resources. 10848 if (info.args != null) { 10849 synchronized (mInstallLock) { 10850 info.args.doPostDeleteLI(true); 10851 } 10852 } 10853 10854 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10855 } 10856 10857 static class PackageRemovedInfo { 10858 String removedPackage; 10859 int uid = -1; 10860 int removedAppId = -1; 10861 int[] removedUsers = null; 10862 boolean isRemovedPackageSystemUpdate = false; 10863 // Clean up resources deleted packages. 10864 InstallArgs args = null; 10865 10866 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10867 Bundle extras = new Bundle(1); 10868 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10869 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10870 if (replacing) { 10871 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10872 } 10873 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10874 if (removedPackage != null) { 10875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10876 extras, null, null, removedUsers); 10877 if (fullRemove && !replacing) { 10878 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10879 extras, null, null, removedUsers); 10880 } 10881 } 10882 if (removedAppId >= 0) { 10883 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10884 removedUsers); 10885 } 10886 } 10887 } 10888 10889 /* 10890 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10891 * flag is not set, the data directory is removed as well. 10892 * make sure this flag is set for partially installed apps. If not its meaningless to 10893 * delete a partially installed application. 10894 */ 10895 private void removePackageDataLI(PackageSetting ps, 10896 int[] allUserHandles, boolean[] perUserInstalled, 10897 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10898 String packageName = ps.name; 10899 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10900 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10901 // Retrieve object to delete permissions for shared user later on 10902 final PackageSetting deletedPs; 10903 // reader 10904 synchronized (mPackages) { 10905 deletedPs = mSettings.mPackages.get(packageName); 10906 if (outInfo != null) { 10907 outInfo.removedPackage = packageName; 10908 outInfo.removedUsers = deletedPs != null 10909 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10910 : null; 10911 } 10912 } 10913 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10914 removeDataDirsLI(packageName); 10915 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10916 } 10917 // writer 10918 synchronized (mPackages) { 10919 if (deletedPs != null) { 10920 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10921 if (outInfo != null) { 10922 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10923 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10924 } 10925 if (deletedPs != null) { 10926 updatePermissionsLPw(deletedPs.name, null, 0); 10927 if (deletedPs.sharedUser != null) { 10928 // remove permissions associated with package 10929 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10930 } 10931 } 10932 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10933 } 10934 // make sure to preserve per-user disabled state if this removal was just 10935 // a downgrade of a system app to the factory package 10936 if (allUserHandles != null && perUserInstalled != null) { 10937 if (DEBUG_REMOVE) { 10938 Slog.d(TAG, "Propagating install state across downgrade"); 10939 } 10940 for (int i = 0; i < allUserHandles.length; i++) { 10941 if (DEBUG_REMOVE) { 10942 Slog.d(TAG, " user " + allUserHandles[i] 10943 + " => " + perUserInstalled[i]); 10944 } 10945 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10946 } 10947 } 10948 } 10949 // can downgrade to reader 10950 if (writeSettings) { 10951 // Save settings now 10952 mSettings.writeLPr(); 10953 } 10954 } 10955 if (outInfo != null) { 10956 // A user ID was deleted here. Go through all users and remove it 10957 // from KeyStore. 10958 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10959 } 10960 } 10961 10962 static boolean locationIsPrivileged(File path) { 10963 try { 10964 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10965 .getCanonicalPath(); 10966 return path.getCanonicalPath().startsWith(privilegedAppDir); 10967 } catch (IOException e) { 10968 Slog.e(TAG, "Unable to access code path " + path); 10969 } 10970 return false; 10971 } 10972 10973 /* 10974 * Tries to delete system package. 10975 */ 10976 private boolean deleteSystemPackageLI(PackageSetting newPs, 10977 int[] allUserHandles, boolean[] perUserInstalled, 10978 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10979 final boolean applyUserRestrictions 10980 = (allUserHandles != null) && (perUserInstalled != null); 10981 PackageSetting disabledPs = null; 10982 // Confirm if the system package has been updated 10983 // An updated system app can be deleted. This will also have to restore 10984 // the system pkg from system partition 10985 // reader 10986 synchronized (mPackages) { 10987 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10988 } 10989 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10990 + " disabledPs=" + disabledPs); 10991 if (disabledPs == null) { 10992 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10993 return false; 10994 } else if (DEBUG_REMOVE) { 10995 Slog.d(TAG, "Deleting system pkg from data partition"); 10996 } 10997 if (DEBUG_REMOVE) { 10998 if (applyUserRestrictions) { 10999 Slog.d(TAG, "Remembering install states:"); 11000 for (int i = 0; i < allUserHandles.length; i++) { 11001 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11002 } 11003 } 11004 } 11005 // Delete the updated package 11006 outInfo.isRemovedPackageSystemUpdate = true; 11007 if (disabledPs.versionCode < newPs.versionCode) { 11008 // Delete data for downgrades 11009 flags &= ~PackageManager.DELETE_KEEP_DATA; 11010 } else { 11011 // Preserve data by setting flag 11012 flags |= PackageManager.DELETE_KEEP_DATA; 11013 } 11014 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11015 allUserHandles, perUserInstalled, outInfo, writeSettings); 11016 if (!ret) { 11017 return false; 11018 } 11019 // writer 11020 synchronized (mPackages) { 11021 // Reinstate the old system package 11022 mSettings.enableSystemPackageLPw(newPs.name); 11023 // Remove any native libraries from the upgraded package. 11024 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11025 } 11026 // Install the system package 11027 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11028 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11029 if (locationIsPrivileged(disabledPs.codePath)) { 11030 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11031 } 11032 11033 final PackageParser.Package newPkg; 11034 try { 11035 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11036 } catch (PackageManagerException e) { 11037 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11038 return false; 11039 } 11040 11041 // writer 11042 synchronized (mPackages) { 11043 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11044 updatePermissionsLPw(newPkg.packageName, newPkg, 11045 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11046 if (applyUserRestrictions) { 11047 if (DEBUG_REMOVE) { 11048 Slog.d(TAG, "Propagating install state across reinstall"); 11049 } 11050 for (int i = 0; i < allUserHandles.length; i++) { 11051 if (DEBUG_REMOVE) { 11052 Slog.d(TAG, " user " + allUserHandles[i] 11053 + " => " + perUserInstalled[i]); 11054 } 11055 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11056 } 11057 // Regardless of writeSettings we need to ensure that this restriction 11058 // state propagation is persisted 11059 mSettings.writeAllUsersPackageRestrictionsLPr(); 11060 } 11061 // can downgrade to reader here 11062 if (writeSettings) { 11063 mSettings.writeLPr(); 11064 } 11065 } 11066 return true; 11067 } 11068 11069 private boolean deleteInstalledPackageLI(PackageSetting ps, 11070 boolean deleteCodeAndResources, int flags, 11071 int[] allUserHandles, boolean[] perUserInstalled, 11072 PackageRemovedInfo outInfo, boolean writeSettings) { 11073 if (outInfo != null) { 11074 outInfo.uid = ps.appId; 11075 } 11076 11077 // Delete package data from internal structures and also remove data if flag is set 11078 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11079 11080 // Delete application code and resources 11081 if (deleteCodeAndResources && (outInfo != null)) { 11082 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11083 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11084 getAppDexInstructionSets(ps)); 11085 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11086 } 11087 return true; 11088 } 11089 11090 @Override 11091 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11092 int userId) { 11093 mContext.enforceCallingOrSelfPermission( 11094 android.Manifest.permission.DELETE_PACKAGES, null); 11095 synchronized (mPackages) { 11096 PackageSetting ps = mSettings.mPackages.get(packageName); 11097 if (ps == null) { 11098 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11099 return false; 11100 } 11101 if (!ps.getInstalled(userId)) { 11102 // Can't block uninstall for an app that is not installed or enabled. 11103 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11104 return false; 11105 } 11106 ps.setBlockUninstall(blockUninstall, userId); 11107 mSettings.writePackageRestrictionsLPr(userId); 11108 } 11109 return true; 11110 } 11111 11112 @Override 11113 public boolean getBlockUninstallForUser(String packageName, int userId) { 11114 synchronized (mPackages) { 11115 PackageSetting ps = mSettings.mPackages.get(packageName); 11116 if (ps == null) { 11117 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11118 return false; 11119 } 11120 return ps.getBlockUninstall(userId); 11121 } 11122 } 11123 11124 /* 11125 * This method handles package deletion in general 11126 */ 11127 private boolean deletePackageLI(String packageName, UserHandle user, 11128 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11129 int flags, PackageRemovedInfo outInfo, 11130 boolean writeSettings) { 11131 if (packageName == null) { 11132 Slog.w(TAG, "Attempt to delete null packageName."); 11133 return false; 11134 } 11135 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11136 PackageSetting ps; 11137 boolean dataOnly = false; 11138 int removeUser = -1; 11139 int appId = -1; 11140 synchronized (mPackages) { 11141 ps = mSettings.mPackages.get(packageName); 11142 if (ps == null) { 11143 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11144 return false; 11145 } 11146 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11147 && user.getIdentifier() != UserHandle.USER_ALL) { 11148 // The caller is asking that the package only be deleted for a single 11149 // user. To do this, we just mark its uninstalled state and delete 11150 // its data. If this is a system app, we only allow this to happen if 11151 // they have set the special DELETE_SYSTEM_APP which requests different 11152 // semantics than normal for uninstalling system apps. 11153 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11154 ps.setUserState(user.getIdentifier(), 11155 COMPONENT_ENABLED_STATE_DEFAULT, 11156 false, //installed 11157 true, //stopped 11158 true, //notLaunched 11159 false, //hidden 11160 null, null, null, 11161 false // blockUninstall 11162 ); 11163 if (!isSystemApp(ps)) { 11164 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11165 // Other user still have this package installed, so all 11166 // we need to do is clear this user's data and save that 11167 // it is uninstalled. 11168 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11169 removeUser = user.getIdentifier(); 11170 appId = ps.appId; 11171 mSettings.writePackageRestrictionsLPr(removeUser); 11172 } else { 11173 // We need to set it back to 'installed' so the uninstall 11174 // broadcasts will be sent correctly. 11175 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11176 ps.setInstalled(true, user.getIdentifier()); 11177 } 11178 } else { 11179 // This is a system app, so we assume that the 11180 // other users still have this package installed, so all 11181 // we need to do is clear this user's data and save that 11182 // it is uninstalled. 11183 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11184 removeUser = user.getIdentifier(); 11185 appId = ps.appId; 11186 mSettings.writePackageRestrictionsLPr(removeUser); 11187 } 11188 } 11189 } 11190 11191 if (removeUser >= 0) { 11192 // From above, we determined that we are deleting this only 11193 // for a single user. Continue the work here. 11194 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11195 if (outInfo != null) { 11196 outInfo.removedPackage = packageName; 11197 outInfo.removedAppId = appId; 11198 outInfo.removedUsers = new int[] {removeUser}; 11199 } 11200 mInstaller.clearUserData(packageName, removeUser); 11201 removeKeystoreDataIfNeeded(removeUser, appId); 11202 schedulePackageCleaning(packageName, removeUser, false); 11203 return true; 11204 } 11205 11206 if (dataOnly) { 11207 // Delete application data first 11208 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11209 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11210 return true; 11211 } 11212 11213 boolean ret = false; 11214 if (isSystemApp(ps)) { 11215 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11216 // When an updated system application is deleted we delete the existing resources as well and 11217 // fall back to existing code in system partition 11218 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11219 flags, outInfo, writeSettings); 11220 } else { 11221 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11222 // Kill application pre-emptively especially for apps on sd. 11223 killApplication(packageName, ps.appId, "uninstall pkg"); 11224 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11225 allUserHandles, perUserInstalled, 11226 outInfo, writeSettings); 11227 } 11228 11229 return ret; 11230 } 11231 11232 private final class ClearStorageConnection implements ServiceConnection { 11233 IMediaContainerService mContainerService; 11234 11235 @Override 11236 public void onServiceConnected(ComponentName name, IBinder service) { 11237 synchronized (this) { 11238 mContainerService = IMediaContainerService.Stub.asInterface(service); 11239 notifyAll(); 11240 } 11241 } 11242 11243 @Override 11244 public void onServiceDisconnected(ComponentName name) { 11245 } 11246 } 11247 11248 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11249 final boolean mounted; 11250 if (Environment.isExternalStorageEmulated()) { 11251 mounted = true; 11252 } else { 11253 final String status = Environment.getExternalStorageState(); 11254 11255 mounted = status.equals(Environment.MEDIA_MOUNTED) 11256 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11257 } 11258 11259 if (!mounted) { 11260 return; 11261 } 11262 11263 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11264 int[] users; 11265 if (userId == UserHandle.USER_ALL) { 11266 users = sUserManager.getUserIds(); 11267 } else { 11268 users = new int[] { userId }; 11269 } 11270 final ClearStorageConnection conn = new ClearStorageConnection(); 11271 if (mContext.bindServiceAsUser( 11272 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11273 try { 11274 for (int curUser : users) { 11275 long timeout = SystemClock.uptimeMillis() + 5000; 11276 synchronized (conn) { 11277 long now = SystemClock.uptimeMillis(); 11278 while (conn.mContainerService == null && now < timeout) { 11279 try { 11280 conn.wait(timeout - now); 11281 } catch (InterruptedException e) { 11282 } 11283 } 11284 } 11285 if (conn.mContainerService == null) { 11286 return; 11287 } 11288 11289 final UserEnvironment userEnv = new UserEnvironment(curUser); 11290 clearDirectory(conn.mContainerService, 11291 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11292 if (allData) { 11293 clearDirectory(conn.mContainerService, 11294 userEnv.buildExternalStorageAppDataDirs(packageName)); 11295 clearDirectory(conn.mContainerService, 11296 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11297 } 11298 } 11299 } finally { 11300 mContext.unbindService(conn); 11301 } 11302 } 11303 } 11304 11305 @Override 11306 public void clearApplicationUserData(final String packageName, 11307 final IPackageDataObserver observer, final int userId) { 11308 mContext.enforceCallingOrSelfPermission( 11309 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11310 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11311 // Queue up an async operation since the package deletion may take a little while. 11312 mHandler.post(new Runnable() { 11313 public void run() { 11314 mHandler.removeCallbacks(this); 11315 final boolean succeeded; 11316 synchronized (mInstallLock) { 11317 succeeded = clearApplicationUserDataLI(packageName, userId); 11318 } 11319 clearExternalStorageDataSync(packageName, userId, true); 11320 if (succeeded) { 11321 // invoke DeviceStorageMonitor's update method to clear any notifications 11322 DeviceStorageMonitorInternal 11323 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11324 if (dsm != null) { 11325 dsm.checkMemory(); 11326 } 11327 } 11328 if(observer != null) { 11329 try { 11330 observer.onRemoveCompleted(packageName, succeeded); 11331 } catch (RemoteException e) { 11332 Log.i(TAG, "Observer no longer exists."); 11333 } 11334 } //end if observer 11335 } //end run 11336 }); 11337 } 11338 11339 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11340 if (packageName == null) { 11341 Slog.w(TAG, "Attempt to delete null packageName."); 11342 return false; 11343 } 11344 11345 // Try finding details about the requested package 11346 PackageParser.Package pkg; 11347 synchronized (mPackages) { 11348 pkg = mPackages.get(packageName); 11349 if (pkg == null) { 11350 final PackageSetting ps = mSettings.mPackages.get(packageName); 11351 if (ps != null) { 11352 pkg = ps.pkg; 11353 } 11354 } 11355 } 11356 11357 if (pkg == null) { 11358 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11359 } 11360 11361 // Always delete data directories for package, even if we found no other 11362 // record of app. This helps users recover from UID mismatches without 11363 // resorting to a full data wipe. 11364 int retCode = mInstaller.clearUserData(packageName, userId); 11365 if (retCode < 0) { 11366 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11367 return false; 11368 } 11369 11370 if (pkg == null) { 11371 return false; 11372 } 11373 11374 if (pkg != null && pkg.applicationInfo != null) { 11375 final int appId = pkg.applicationInfo.uid; 11376 removeKeystoreDataIfNeeded(userId, appId); 11377 } 11378 11379 // Create a native library symlink only if we have native libraries 11380 // and if the native libraries are 32 bit libraries. We do not provide 11381 // this symlink for 64 bit libraries. 11382 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11383 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11384 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11385 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11386 Slog.w(TAG, "Failed linking native library dir"); 11387 return false; 11388 } 11389 } 11390 11391 return true; 11392 } 11393 11394 /** 11395 * Remove entries from the keystore daemon. Will only remove it if the 11396 * {@code appId} is valid. 11397 */ 11398 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11399 if (appId < 0) { 11400 return; 11401 } 11402 11403 final KeyStore keyStore = KeyStore.getInstance(); 11404 if (keyStore != null) { 11405 if (userId == UserHandle.USER_ALL) { 11406 for (final int individual : sUserManager.getUserIds()) { 11407 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11408 } 11409 } else { 11410 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11411 } 11412 } else { 11413 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11414 } 11415 } 11416 11417 @Override 11418 public void deleteApplicationCacheFiles(final String packageName, 11419 final IPackageDataObserver observer) { 11420 mContext.enforceCallingOrSelfPermission( 11421 android.Manifest.permission.DELETE_CACHE_FILES, null); 11422 // Queue up an async operation since the package deletion may take a little while. 11423 final int userId = UserHandle.getCallingUserId(); 11424 mHandler.post(new Runnable() { 11425 public void run() { 11426 mHandler.removeCallbacks(this); 11427 final boolean succeded; 11428 synchronized (mInstallLock) { 11429 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11430 } 11431 clearExternalStorageDataSync(packageName, userId, false); 11432 if(observer != null) { 11433 try { 11434 observer.onRemoveCompleted(packageName, succeded); 11435 } catch (RemoteException e) { 11436 Log.i(TAG, "Observer no longer exists."); 11437 } 11438 } //end if observer 11439 } //end run 11440 }); 11441 } 11442 11443 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11444 if (packageName == null) { 11445 Slog.w(TAG, "Attempt to delete null packageName."); 11446 return false; 11447 } 11448 PackageParser.Package p; 11449 synchronized (mPackages) { 11450 p = mPackages.get(packageName); 11451 } 11452 if (p == null) { 11453 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11454 return false; 11455 } 11456 final ApplicationInfo applicationInfo = p.applicationInfo; 11457 if (applicationInfo == null) { 11458 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11459 return false; 11460 } 11461 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11462 if (retCode < 0) { 11463 Slog.w(TAG, "Couldn't remove cache files for package: " 11464 + packageName + " u" + userId); 11465 return false; 11466 } 11467 return true; 11468 } 11469 11470 @Override 11471 public void getPackageSizeInfo(final String packageName, int userHandle, 11472 final IPackageStatsObserver observer) { 11473 mContext.enforceCallingOrSelfPermission( 11474 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11475 if (packageName == null) { 11476 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11477 } 11478 11479 PackageStats stats = new PackageStats(packageName, userHandle); 11480 11481 /* 11482 * Queue up an async operation since the package measurement may take a 11483 * little while. 11484 */ 11485 Message msg = mHandler.obtainMessage(INIT_COPY); 11486 msg.obj = new MeasureParams(stats, observer); 11487 mHandler.sendMessage(msg); 11488 } 11489 11490 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11491 PackageStats pStats) { 11492 if (packageName == null) { 11493 Slog.w(TAG, "Attempt to get size of null packageName."); 11494 return false; 11495 } 11496 PackageParser.Package p; 11497 boolean dataOnly = false; 11498 String libDirRoot = null; 11499 String asecPath = null; 11500 PackageSetting ps = null; 11501 synchronized (mPackages) { 11502 p = mPackages.get(packageName); 11503 ps = mSettings.mPackages.get(packageName); 11504 if(p == null) { 11505 dataOnly = true; 11506 if((ps == null) || (ps.pkg == null)) { 11507 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11508 return false; 11509 } 11510 p = ps.pkg; 11511 } 11512 if (ps != null) { 11513 libDirRoot = ps.legacyNativeLibraryPathString; 11514 } 11515 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11516 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11517 if (secureContainerId != null) { 11518 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11519 } 11520 } 11521 } 11522 String publicSrcDir = null; 11523 if(!dataOnly) { 11524 final ApplicationInfo applicationInfo = p.applicationInfo; 11525 if (applicationInfo == null) { 11526 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11527 return false; 11528 } 11529 if (isForwardLocked(p)) { 11530 publicSrcDir = applicationInfo.getBaseResourcePath(); 11531 } 11532 } 11533 // TODO: extend to measure size of split APKs 11534 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11535 // not just the first level. 11536 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11537 // just the primary. 11538 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11539 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11540 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11541 if (res < 0) { 11542 return false; 11543 } 11544 11545 // Fix-up for forward-locked applications in ASEC containers. 11546 if (!isExternal(p)) { 11547 pStats.codeSize += pStats.externalCodeSize; 11548 pStats.externalCodeSize = 0L; 11549 } 11550 11551 return true; 11552 } 11553 11554 11555 @Override 11556 public void addPackageToPreferred(String packageName) { 11557 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11558 } 11559 11560 @Override 11561 public void removePackageFromPreferred(String packageName) { 11562 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11563 } 11564 11565 @Override 11566 public List<PackageInfo> getPreferredPackages(int flags) { 11567 return new ArrayList<PackageInfo>(); 11568 } 11569 11570 private int getUidTargetSdkVersionLockedLPr(int uid) { 11571 Object obj = mSettings.getUserIdLPr(uid); 11572 if (obj instanceof SharedUserSetting) { 11573 final SharedUserSetting sus = (SharedUserSetting) obj; 11574 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11575 final Iterator<PackageSetting> it = sus.packages.iterator(); 11576 while (it.hasNext()) { 11577 final PackageSetting ps = it.next(); 11578 if (ps.pkg != null) { 11579 int v = ps.pkg.applicationInfo.targetSdkVersion; 11580 if (v < vers) vers = v; 11581 } 11582 } 11583 return vers; 11584 } else if (obj instanceof PackageSetting) { 11585 final PackageSetting ps = (PackageSetting) obj; 11586 if (ps.pkg != null) { 11587 return ps.pkg.applicationInfo.targetSdkVersion; 11588 } 11589 } 11590 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11591 } 11592 11593 @Override 11594 public void addPreferredActivity(IntentFilter filter, int match, 11595 ComponentName[] set, ComponentName activity, int userId) { 11596 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11597 "Adding preferred"); 11598 } 11599 11600 private void addPreferredActivityInternal(IntentFilter filter, int match, 11601 ComponentName[] set, ComponentName activity, boolean always, int userId, 11602 String opname) { 11603 // writer 11604 int callingUid = Binder.getCallingUid(); 11605 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11606 if (filter.countActions() == 0) { 11607 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11608 return; 11609 } 11610 synchronized (mPackages) { 11611 if (mContext.checkCallingOrSelfPermission( 11612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11613 != PackageManager.PERMISSION_GRANTED) { 11614 if (getUidTargetSdkVersionLockedLPr(callingUid) 11615 < Build.VERSION_CODES.FROYO) { 11616 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11617 + callingUid); 11618 return; 11619 } 11620 mContext.enforceCallingOrSelfPermission( 11621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11622 } 11623 11624 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11625 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11626 + userId + ":"); 11627 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11628 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11629 mSettings.writePackageRestrictionsLPr(userId); 11630 } 11631 } 11632 11633 @Override 11634 public void replacePreferredActivity(IntentFilter filter, int match, 11635 ComponentName[] set, ComponentName activity, int userId) { 11636 if (filter.countActions() != 1) { 11637 throw new IllegalArgumentException( 11638 "replacePreferredActivity expects filter to have only 1 action."); 11639 } 11640 if (filter.countDataAuthorities() != 0 11641 || filter.countDataPaths() != 0 11642 || filter.countDataSchemes() > 1 11643 || filter.countDataTypes() != 0) { 11644 throw new IllegalArgumentException( 11645 "replacePreferredActivity expects filter to have no data authorities, " + 11646 "paths, or types; and at most one scheme."); 11647 } 11648 11649 final int callingUid = Binder.getCallingUid(); 11650 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11651 synchronized (mPackages) { 11652 if (mContext.checkCallingOrSelfPermission( 11653 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11654 != PackageManager.PERMISSION_GRANTED) { 11655 if (getUidTargetSdkVersionLockedLPr(callingUid) 11656 < Build.VERSION_CODES.FROYO) { 11657 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11658 + Binder.getCallingUid()); 11659 return; 11660 } 11661 mContext.enforceCallingOrSelfPermission( 11662 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11663 } 11664 11665 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11666 if (pir != null) { 11667 // Get all of the existing entries that exactly match this filter. 11668 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11669 if (existing != null && existing.size() == 1) { 11670 PreferredActivity cur = existing.get(0); 11671 if (DEBUG_PREFERRED) { 11672 Slog.i(TAG, "Checking replace of preferred:"); 11673 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11674 if (!cur.mPref.mAlways) { 11675 Slog.i(TAG, " -- CUR; not mAlways!"); 11676 } else { 11677 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11678 Slog.i(TAG, " -- CUR: mSet=" 11679 + Arrays.toString(cur.mPref.mSetComponents)); 11680 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11681 Slog.i(TAG, " -- NEW: mMatch=" 11682 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11683 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11684 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11685 } 11686 } 11687 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11688 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11689 && cur.mPref.sameSet(set)) { 11690 // Setting the preferred activity to what it happens to be already 11691 if (DEBUG_PREFERRED) { 11692 Slog.i(TAG, "Replacing with same preferred activity " 11693 + cur.mPref.mShortComponent + " for user " 11694 + userId + ":"); 11695 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11696 } 11697 return; 11698 } 11699 } 11700 11701 if (existing != null) { 11702 if (DEBUG_PREFERRED) { 11703 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11704 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11705 } 11706 for (int i = 0; i < existing.size(); i++) { 11707 PreferredActivity pa = existing.get(i); 11708 if (DEBUG_PREFERRED) { 11709 Slog.i(TAG, "Removing existing preferred activity " 11710 + pa.mPref.mComponent + ":"); 11711 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11712 } 11713 pir.removeFilter(pa); 11714 } 11715 } 11716 } 11717 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11718 "Replacing preferred"); 11719 } 11720 } 11721 11722 @Override 11723 public void clearPackagePreferredActivities(String packageName) { 11724 final int uid = Binder.getCallingUid(); 11725 // writer 11726 synchronized (mPackages) { 11727 PackageParser.Package pkg = mPackages.get(packageName); 11728 if (pkg == null || pkg.applicationInfo.uid != uid) { 11729 if (mContext.checkCallingOrSelfPermission( 11730 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11731 != PackageManager.PERMISSION_GRANTED) { 11732 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11733 < Build.VERSION_CODES.FROYO) { 11734 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11735 + Binder.getCallingUid()); 11736 return; 11737 } 11738 mContext.enforceCallingOrSelfPermission( 11739 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11740 } 11741 } 11742 11743 int user = UserHandle.getCallingUserId(); 11744 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11745 mSettings.writePackageRestrictionsLPr(user); 11746 scheduleWriteSettingsLocked(); 11747 } 11748 } 11749 } 11750 11751 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11752 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11753 ArrayList<PreferredActivity> removed = null; 11754 boolean changed = false; 11755 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11756 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11757 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11758 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11759 continue; 11760 } 11761 Iterator<PreferredActivity> it = pir.filterIterator(); 11762 while (it.hasNext()) { 11763 PreferredActivity pa = it.next(); 11764 // Mark entry for removal only if it matches the package name 11765 // and the entry is of type "always". 11766 if (packageName == null || 11767 (pa.mPref.mComponent.getPackageName().equals(packageName) 11768 && pa.mPref.mAlways)) { 11769 if (removed == null) { 11770 removed = new ArrayList<PreferredActivity>(); 11771 } 11772 removed.add(pa); 11773 } 11774 } 11775 if (removed != null) { 11776 for (int j=0; j<removed.size(); j++) { 11777 PreferredActivity pa = removed.get(j); 11778 pir.removeFilter(pa); 11779 } 11780 changed = true; 11781 } 11782 } 11783 return changed; 11784 } 11785 11786 @Override 11787 public void resetPreferredActivities(int userId) { 11788 /* TODO: Actually use userId. Why is it being passed in? */ 11789 mContext.enforceCallingOrSelfPermission( 11790 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11791 // writer 11792 synchronized (mPackages) { 11793 int user = UserHandle.getCallingUserId(); 11794 clearPackagePreferredActivitiesLPw(null, user); 11795 mSettings.readDefaultPreferredAppsLPw(this, user); 11796 mSettings.writePackageRestrictionsLPr(user); 11797 scheduleWriteSettingsLocked(); 11798 } 11799 } 11800 11801 @Override 11802 public int getPreferredActivities(List<IntentFilter> outFilters, 11803 List<ComponentName> outActivities, String packageName) { 11804 11805 int num = 0; 11806 final int userId = UserHandle.getCallingUserId(); 11807 // reader 11808 synchronized (mPackages) { 11809 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11810 if (pir != null) { 11811 final Iterator<PreferredActivity> it = pir.filterIterator(); 11812 while (it.hasNext()) { 11813 final PreferredActivity pa = it.next(); 11814 if (packageName == null 11815 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11816 && pa.mPref.mAlways)) { 11817 if (outFilters != null) { 11818 outFilters.add(new IntentFilter(pa)); 11819 } 11820 if (outActivities != null) { 11821 outActivities.add(pa.mPref.mComponent); 11822 } 11823 } 11824 } 11825 } 11826 } 11827 11828 return num; 11829 } 11830 11831 @Override 11832 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11833 int userId) { 11834 int callingUid = Binder.getCallingUid(); 11835 if (callingUid != Process.SYSTEM_UID) { 11836 throw new SecurityException( 11837 "addPersistentPreferredActivity can only be run by the system"); 11838 } 11839 if (filter.countActions() == 0) { 11840 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11841 return; 11842 } 11843 synchronized (mPackages) { 11844 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11845 " :"); 11846 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11847 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11848 new PersistentPreferredActivity(filter, activity)); 11849 mSettings.writePackageRestrictionsLPr(userId); 11850 } 11851 } 11852 11853 @Override 11854 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11855 int callingUid = Binder.getCallingUid(); 11856 if (callingUid != Process.SYSTEM_UID) { 11857 throw new SecurityException( 11858 "clearPackagePersistentPreferredActivities can only be run by the system"); 11859 } 11860 ArrayList<PersistentPreferredActivity> removed = null; 11861 boolean changed = false; 11862 synchronized (mPackages) { 11863 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11864 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11865 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11866 .valueAt(i); 11867 if (userId != thisUserId) { 11868 continue; 11869 } 11870 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11871 while (it.hasNext()) { 11872 PersistentPreferredActivity ppa = it.next(); 11873 // Mark entry for removal only if it matches the package name. 11874 if (ppa.mComponent.getPackageName().equals(packageName)) { 11875 if (removed == null) { 11876 removed = new ArrayList<PersistentPreferredActivity>(); 11877 } 11878 removed.add(ppa); 11879 } 11880 } 11881 if (removed != null) { 11882 for (int j=0; j<removed.size(); j++) { 11883 PersistentPreferredActivity ppa = removed.get(j); 11884 ppir.removeFilter(ppa); 11885 } 11886 changed = true; 11887 } 11888 } 11889 11890 if (changed) { 11891 mSettings.writePackageRestrictionsLPr(userId); 11892 } 11893 } 11894 } 11895 11896 @Override 11897 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11898 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11899 mContext.enforceCallingOrSelfPermission( 11900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11901 int callingUid = Binder.getCallingUid(); 11902 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11903 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11904 if (intentFilter.countActions() == 0) { 11905 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11906 return; 11907 } 11908 synchronized (mPackages) { 11909 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11910 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11911 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11912 mSettings.writePackageRestrictionsLPr(sourceUserId); 11913 } 11914 } 11915 11916 @Override 11917 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11918 int ownerUserId) { 11919 mContext.enforceCallingOrSelfPermission( 11920 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11921 int callingUid = Binder.getCallingUid(); 11922 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11923 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11924 int callingUserId = UserHandle.getUserId(callingUid); 11925 synchronized (mPackages) { 11926 CrossProfileIntentResolver resolver = 11927 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11928 HashSet<CrossProfileIntentFilter> set = 11929 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11930 for (CrossProfileIntentFilter filter : set) { 11931 if (filter.getOwnerPackage().equals(ownerPackage) 11932 && filter.getOwnerUserId() == callingUserId) { 11933 resolver.removeFilter(filter); 11934 } 11935 } 11936 mSettings.writePackageRestrictionsLPr(sourceUserId); 11937 } 11938 } 11939 11940 // Enforcing that callingUid is owning pkg on userId 11941 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11942 // The system owns everything. 11943 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11944 return; 11945 } 11946 int callingUserId = UserHandle.getUserId(callingUid); 11947 if (callingUserId != userId) { 11948 throw new SecurityException("calling uid " + callingUid 11949 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11950 + callingUserId); 11951 } 11952 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11953 if (pi == null) { 11954 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11955 + callingUserId); 11956 } 11957 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11958 throw new SecurityException("Calling uid " + callingUid 11959 + " does not own package " + pkg); 11960 } 11961 } 11962 11963 @Override 11964 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11965 Intent intent = new Intent(Intent.ACTION_MAIN); 11966 intent.addCategory(Intent.CATEGORY_HOME); 11967 11968 final int callingUserId = UserHandle.getCallingUserId(); 11969 List<ResolveInfo> list = queryIntentActivities(intent, null, 11970 PackageManager.GET_META_DATA, callingUserId); 11971 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11972 true, false, false, callingUserId); 11973 11974 allHomeCandidates.clear(); 11975 if (list != null) { 11976 for (ResolveInfo ri : list) { 11977 allHomeCandidates.add(ri); 11978 } 11979 } 11980 return (preferred == null || preferred.activityInfo == null) 11981 ? null 11982 : new ComponentName(preferred.activityInfo.packageName, 11983 preferred.activityInfo.name); 11984 } 11985 11986 @Override 11987 public void setApplicationEnabledSetting(String appPackageName, 11988 int newState, int flags, int userId, String callingPackage) { 11989 if (!sUserManager.exists(userId)) return; 11990 if (callingPackage == null) { 11991 callingPackage = Integer.toString(Binder.getCallingUid()); 11992 } 11993 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11994 } 11995 11996 @Override 11997 public void setComponentEnabledSetting(ComponentName componentName, 11998 int newState, int flags, int userId) { 11999 if (!sUserManager.exists(userId)) return; 12000 setEnabledSetting(componentName.getPackageName(), 12001 componentName.getClassName(), newState, flags, userId, null); 12002 } 12003 12004 private void setEnabledSetting(final String packageName, String className, int newState, 12005 final int flags, int userId, String callingPackage) { 12006 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12007 || newState == COMPONENT_ENABLED_STATE_ENABLED 12008 || newState == COMPONENT_ENABLED_STATE_DISABLED 12009 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12010 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12011 throw new IllegalArgumentException("Invalid new component state: " 12012 + newState); 12013 } 12014 PackageSetting pkgSetting; 12015 final int uid = Binder.getCallingUid(); 12016 final int permission = mContext.checkCallingOrSelfPermission( 12017 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12018 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12019 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12020 boolean sendNow = false; 12021 boolean isApp = (className == null); 12022 String componentName = isApp ? packageName : className; 12023 int packageUid = -1; 12024 ArrayList<String> components; 12025 12026 // writer 12027 synchronized (mPackages) { 12028 pkgSetting = mSettings.mPackages.get(packageName); 12029 if (pkgSetting == null) { 12030 if (className == null) { 12031 throw new IllegalArgumentException( 12032 "Unknown package: " + packageName); 12033 } 12034 throw new IllegalArgumentException( 12035 "Unknown component: " + packageName 12036 + "/" + className); 12037 } 12038 // Allow root and verify that userId is not being specified by a different user 12039 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12040 throw new SecurityException( 12041 "Permission Denial: attempt to change component state from pid=" 12042 + Binder.getCallingPid() 12043 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12044 } 12045 if (className == null) { 12046 // We're dealing with an application/package level state change 12047 if (pkgSetting.getEnabled(userId) == newState) { 12048 // Nothing to do 12049 return; 12050 } 12051 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12052 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12053 // Don't care about who enables an app. 12054 callingPackage = null; 12055 } 12056 pkgSetting.setEnabled(newState, userId, callingPackage); 12057 // pkgSetting.pkg.mSetEnabled = newState; 12058 } else { 12059 // We're dealing with a component level state change 12060 // First, verify that this is a valid class name. 12061 PackageParser.Package pkg = pkgSetting.pkg; 12062 if (pkg == null || !pkg.hasComponentClassName(className)) { 12063 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12064 throw new IllegalArgumentException("Component class " + className 12065 + " does not exist in " + packageName); 12066 } else { 12067 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12068 + className + " does not exist in " + packageName); 12069 } 12070 } 12071 switch (newState) { 12072 case COMPONENT_ENABLED_STATE_ENABLED: 12073 if (!pkgSetting.enableComponentLPw(className, userId)) { 12074 return; 12075 } 12076 break; 12077 case COMPONENT_ENABLED_STATE_DISABLED: 12078 if (!pkgSetting.disableComponentLPw(className, userId)) { 12079 return; 12080 } 12081 break; 12082 case COMPONENT_ENABLED_STATE_DEFAULT: 12083 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12084 return; 12085 } 12086 break; 12087 default: 12088 Slog.e(TAG, "Invalid new component state: " + newState); 12089 return; 12090 } 12091 } 12092 mSettings.writePackageRestrictionsLPr(userId); 12093 components = mPendingBroadcasts.get(userId, packageName); 12094 final boolean newPackage = components == null; 12095 if (newPackage) { 12096 components = new ArrayList<String>(); 12097 } 12098 if (!components.contains(componentName)) { 12099 components.add(componentName); 12100 } 12101 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12102 sendNow = true; 12103 // Purge entry from pending broadcast list if another one exists already 12104 // since we are sending one right away. 12105 mPendingBroadcasts.remove(userId, packageName); 12106 } else { 12107 if (newPackage) { 12108 mPendingBroadcasts.put(userId, packageName, components); 12109 } 12110 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12111 // Schedule a message 12112 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12113 } 12114 } 12115 } 12116 12117 long callingId = Binder.clearCallingIdentity(); 12118 try { 12119 if (sendNow) { 12120 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12121 sendPackageChangedBroadcast(packageName, 12122 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12123 } 12124 } finally { 12125 Binder.restoreCallingIdentity(callingId); 12126 } 12127 } 12128 12129 private void sendPackageChangedBroadcast(String packageName, 12130 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12131 if (DEBUG_INSTALL) 12132 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12133 + componentNames); 12134 Bundle extras = new Bundle(4); 12135 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12136 String nameList[] = new String[componentNames.size()]; 12137 componentNames.toArray(nameList); 12138 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12139 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12140 extras.putInt(Intent.EXTRA_UID, packageUid); 12141 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12142 new int[] {UserHandle.getUserId(packageUid)}); 12143 } 12144 12145 @Override 12146 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12147 if (!sUserManager.exists(userId)) return; 12148 final int uid = Binder.getCallingUid(); 12149 final int permission = mContext.checkCallingOrSelfPermission( 12150 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12151 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12152 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12153 // writer 12154 synchronized (mPackages) { 12155 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12156 uid, userId)) { 12157 scheduleWritePackageRestrictionsLocked(userId); 12158 } 12159 } 12160 } 12161 12162 @Override 12163 public String getInstallerPackageName(String packageName) { 12164 // reader 12165 synchronized (mPackages) { 12166 return mSettings.getInstallerPackageNameLPr(packageName); 12167 } 12168 } 12169 12170 @Override 12171 public int getApplicationEnabledSetting(String packageName, int userId) { 12172 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12173 int uid = Binder.getCallingUid(); 12174 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12175 // reader 12176 synchronized (mPackages) { 12177 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12178 } 12179 } 12180 12181 @Override 12182 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12183 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12184 int uid = Binder.getCallingUid(); 12185 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12186 // reader 12187 synchronized (mPackages) { 12188 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12189 } 12190 } 12191 12192 @Override 12193 public void enterSafeMode() { 12194 enforceSystemOrRoot("Only the system can request entering safe mode"); 12195 12196 if (!mSystemReady) { 12197 mSafeMode = true; 12198 } 12199 } 12200 12201 @Override 12202 public void systemReady() { 12203 mSystemReady = true; 12204 12205 // Read the compatibilty setting when the system is ready. 12206 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12207 mContext.getContentResolver(), 12208 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12209 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12210 if (DEBUG_SETTINGS) { 12211 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12212 } 12213 12214 synchronized (mPackages) { 12215 // Verify that all of the preferred activity components actually 12216 // exist. It is possible for applications to be updated and at 12217 // that point remove a previously declared activity component that 12218 // had been set as a preferred activity. We try to clean this up 12219 // the next time we encounter that preferred activity, but it is 12220 // possible for the user flow to never be able to return to that 12221 // situation so here we do a sanity check to make sure we haven't 12222 // left any junk around. 12223 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12224 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12225 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12226 removed.clear(); 12227 for (PreferredActivity pa : pir.filterSet()) { 12228 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12229 removed.add(pa); 12230 } 12231 } 12232 if (removed.size() > 0) { 12233 for (int r=0; r<removed.size(); r++) { 12234 PreferredActivity pa = removed.get(r); 12235 Slog.w(TAG, "Removing dangling preferred activity: " 12236 + pa.mPref.mComponent); 12237 pir.removeFilter(pa); 12238 } 12239 mSettings.writePackageRestrictionsLPr( 12240 mSettings.mPreferredActivities.keyAt(i)); 12241 } 12242 } 12243 } 12244 sUserManager.systemReady(); 12245 12246 // Kick off any messages waiting for system ready 12247 if (mPostSystemReadyMessages != null) { 12248 for (Message msg : mPostSystemReadyMessages) { 12249 msg.sendToTarget(); 12250 } 12251 mPostSystemReadyMessages = null; 12252 } 12253 } 12254 12255 @Override 12256 public boolean isSafeMode() { 12257 return mSafeMode; 12258 } 12259 12260 @Override 12261 public boolean hasSystemUidErrors() { 12262 return mHasSystemUidErrors; 12263 } 12264 12265 static String arrayToString(int[] array) { 12266 StringBuffer buf = new StringBuffer(128); 12267 buf.append('['); 12268 if (array != null) { 12269 for (int i=0; i<array.length; i++) { 12270 if (i > 0) buf.append(", "); 12271 buf.append(array[i]); 12272 } 12273 } 12274 buf.append(']'); 12275 return buf.toString(); 12276 } 12277 12278 static class DumpState { 12279 public static final int DUMP_LIBS = 1 << 0; 12280 public static final int DUMP_FEATURES = 1 << 1; 12281 public static final int DUMP_RESOLVERS = 1 << 2; 12282 public static final int DUMP_PERMISSIONS = 1 << 3; 12283 public static final int DUMP_PACKAGES = 1 << 4; 12284 public static final int DUMP_SHARED_USERS = 1 << 5; 12285 public static final int DUMP_MESSAGES = 1 << 6; 12286 public static final int DUMP_PROVIDERS = 1 << 7; 12287 public static final int DUMP_VERIFIERS = 1 << 8; 12288 public static final int DUMP_PREFERRED = 1 << 9; 12289 public static final int DUMP_PREFERRED_XML = 1 << 10; 12290 public static final int DUMP_KEYSETS = 1 << 11; 12291 public static final int DUMP_VERSION = 1 << 12; 12292 public static final int DUMP_INSTALLS = 1 << 13; 12293 12294 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12295 12296 private int mTypes; 12297 12298 private int mOptions; 12299 12300 private boolean mTitlePrinted; 12301 12302 private SharedUserSetting mSharedUser; 12303 12304 public boolean isDumping(int type) { 12305 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12306 return true; 12307 } 12308 12309 return (mTypes & type) != 0; 12310 } 12311 12312 public void setDump(int type) { 12313 mTypes |= type; 12314 } 12315 12316 public boolean isOptionEnabled(int option) { 12317 return (mOptions & option) != 0; 12318 } 12319 12320 public void setOptionEnabled(int option) { 12321 mOptions |= option; 12322 } 12323 12324 public boolean onTitlePrinted() { 12325 final boolean printed = mTitlePrinted; 12326 mTitlePrinted = true; 12327 return printed; 12328 } 12329 12330 public boolean getTitlePrinted() { 12331 return mTitlePrinted; 12332 } 12333 12334 public void setTitlePrinted(boolean enabled) { 12335 mTitlePrinted = enabled; 12336 } 12337 12338 public SharedUserSetting getSharedUser() { 12339 return mSharedUser; 12340 } 12341 12342 public void setSharedUser(SharedUserSetting user) { 12343 mSharedUser = user; 12344 } 12345 } 12346 12347 @Override 12348 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12349 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12350 != PackageManager.PERMISSION_GRANTED) { 12351 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12352 + Binder.getCallingPid() 12353 + ", uid=" + Binder.getCallingUid() 12354 + " without permission " 12355 + android.Manifest.permission.DUMP); 12356 return; 12357 } 12358 12359 DumpState dumpState = new DumpState(); 12360 boolean fullPreferred = false; 12361 boolean checkin = false; 12362 12363 String packageName = null; 12364 12365 int opti = 0; 12366 while (opti < args.length) { 12367 String opt = args[opti]; 12368 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12369 break; 12370 } 12371 opti++; 12372 12373 if ("-a".equals(opt)) { 12374 // Right now we only know how to print all. 12375 } else if ("-h".equals(opt)) { 12376 pw.println("Package manager dump options:"); 12377 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12378 pw.println(" --checkin: dump for a checkin"); 12379 pw.println(" -f: print details of intent filters"); 12380 pw.println(" -h: print this help"); 12381 pw.println(" cmd may be one of:"); 12382 pw.println(" l[ibraries]: list known shared libraries"); 12383 pw.println(" f[ibraries]: list device features"); 12384 pw.println(" k[eysets]: print known keysets"); 12385 pw.println(" r[esolvers]: dump intent resolvers"); 12386 pw.println(" perm[issions]: dump permissions"); 12387 pw.println(" pref[erred]: print preferred package settings"); 12388 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12389 pw.println(" prov[iders]: dump content providers"); 12390 pw.println(" p[ackages]: dump installed packages"); 12391 pw.println(" s[hared-users]: dump shared user IDs"); 12392 pw.println(" m[essages]: print collected runtime messages"); 12393 pw.println(" v[erifiers]: print package verifier info"); 12394 pw.println(" version: print database version info"); 12395 pw.println(" write: write current settings now"); 12396 pw.println(" <package.name>: info about given package"); 12397 pw.println(" installs: details about install sessions"); 12398 return; 12399 } else if ("--checkin".equals(opt)) { 12400 checkin = true; 12401 } else if ("-f".equals(opt)) { 12402 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12403 } else { 12404 pw.println("Unknown argument: " + opt + "; use -h for help"); 12405 } 12406 } 12407 12408 // Is the caller requesting to dump a particular piece of data? 12409 if (opti < args.length) { 12410 String cmd = args[opti]; 12411 opti++; 12412 // Is this a package name? 12413 if ("android".equals(cmd) || cmd.contains(".")) { 12414 packageName = cmd; 12415 // When dumping a single package, we always dump all of its 12416 // filter information since the amount of data will be reasonable. 12417 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12418 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12419 dumpState.setDump(DumpState.DUMP_LIBS); 12420 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12421 dumpState.setDump(DumpState.DUMP_FEATURES); 12422 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12423 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12424 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12425 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12426 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12427 dumpState.setDump(DumpState.DUMP_PREFERRED); 12428 } else if ("preferred-xml".equals(cmd)) { 12429 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12430 if (opti < args.length && "--full".equals(args[opti])) { 12431 fullPreferred = true; 12432 opti++; 12433 } 12434 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12435 dumpState.setDump(DumpState.DUMP_PACKAGES); 12436 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12437 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12438 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12439 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12440 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12441 dumpState.setDump(DumpState.DUMP_MESSAGES); 12442 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12443 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12444 } else if ("version".equals(cmd)) { 12445 dumpState.setDump(DumpState.DUMP_VERSION); 12446 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12447 dumpState.setDump(DumpState.DUMP_KEYSETS); 12448 } else if ("installs".equals(cmd)) { 12449 dumpState.setDump(DumpState.DUMP_INSTALLS); 12450 } else if ("write".equals(cmd)) { 12451 synchronized (mPackages) { 12452 mSettings.writeLPr(); 12453 pw.println("Settings written."); 12454 return; 12455 } 12456 } 12457 } 12458 12459 if (checkin) { 12460 pw.println("vers,1"); 12461 } 12462 12463 // reader 12464 synchronized (mPackages) { 12465 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12466 if (!checkin) { 12467 if (dumpState.onTitlePrinted()) 12468 pw.println(); 12469 pw.println("Database versions:"); 12470 pw.print(" SDK Version:"); 12471 pw.print(" internal="); 12472 pw.print(mSettings.mInternalSdkPlatform); 12473 pw.print(" external="); 12474 pw.println(mSettings.mExternalSdkPlatform); 12475 pw.print(" DB Version:"); 12476 pw.print(" internal="); 12477 pw.print(mSettings.mInternalDatabaseVersion); 12478 pw.print(" external="); 12479 pw.println(mSettings.mExternalDatabaseVersion); 12480 } 12481 } 12482 12483 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12484 if (!checkin) { 12485 if (dumpState.onTitlePrinted()) 12486 pw.println(); 12487 pw.println("Verifiers:"); 12488 pw.print(" Required: "); 12489 pw.print(mRequiredVerifierPackage); 12490 pw.print(" (uid="); 12491 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12492 pw.println(")"); 12493 } else if (mRequiredVerifierPackage != null) { 12494 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12495 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12496 } 12497 } 12498 12499 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12500 boolean printedHeader = false; 12501 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12502 while (it.hasNext()) { 12503 String name = it.next(); 12504 SharedLibraryEntry ent = mSharedLibraries.get(name); 12505 if (!checkin) { 12506 if (!printedHeader) { 12507 if (dumpState.onTitlePrinted()) 12508 pw.println(); 12509 pw.println("Libraries:"); 12510 printedHeader = true; 12511 } 12512 pw.print(" "); 12513 } else { 12514 pw.print("lib,"); 12515 } 12516 pw.print(name); 12517 if (!checkin) { 12518 pw.print(" -> "); 12519 } 12520 if (ent.path != null) { 12521 if (!checkin) { 12522 pw.print("(jar) "); 12523 pw.print(ent.path); 12524 } else { 12525 pw.print(",jar,"); 12526 pw.print(ent.path); 12527 } 12528 } else { 12529 if (!checkin) { 12530 pw.print("(apk) "); 12531 pw.print(ent.apk); 12532 } else { 12533 pw.print(",apk,"); 12534 pw.print(ent.apk); 12535 } 12536 } 12537 pw.println(); 12538 } 12539 } 12540 12541 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12542 if (dumpState.onTitlePrinted()) 12543 pw.println(); 12544 if (!checkin) { 12545 pw.println("Features:"); 12546 } 12547 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12548 while (it.hasNext()) { 12549 String name = it.next(); 12550 if (!checkin) { 12551 pw.print(" "); 12552 } else { 12553 pw.print("feat,"); 12554 } 12555 pw.println(name); 12556 } 12557 } 12558 12559 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12560 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12561 : "Activity Resolver Table:", " ", packageName, 12562 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12563 dumpState.setTitlePrinted(true); 12564 } 12565 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12566 : "Receiver Resolver Table:", " ", packageName, 12567 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12568 dumpState.setTitlePrinted(true); 12569 } 12570 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12571 : "Service Resolver Table:", " ", packageName, 12572 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12573 dumpState.setTitlePrinted(true); 12574 } 12575 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12576 : "Provider Resolver Table:", " ", packageName, 12577 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12578 dumpState.setTitlePrinted(true); 12579 } 12580 } 12581 12582 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12583 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12584 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12585 int user = mSettings.mPreferredActivities.keyAt(i); 12586 if (pir.dump(pw, 12587 dumpState.getTitlePrinted() 12588 ? "\nPreferred Activities User " + user + ":" 12589 : "Preferred Activities User " + user + ":", " ", 12590 packageName, true)) { 12591 dumpState.setTitlePrinted(true); 12592 } 12593 } 12594 } 12595 12596 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12597 pw.flush(); 12598 FileOutputStream fout = new FileOutputStream(fd); 12599 BufferedOutputStream str = new BufferedOutputStream(fout); 12600 XmlSerializer serializer = new FastXmlSerializer(); 12601 try { 12602 serializer.setOutput(str, "utf-8"); 12603 serializer.startDocument(null, true); 12604 serializer.setFeature( 12605 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12606 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12607 serializer.endDocument(); 12608 serializer.flush(); 12609 } catch (IllegalArgumentException e) { 12610 pw.println("Failed writing: " + e); 12611 } catch (IllegalStateException e) { 12612 pw.println("Failed writing: " + e); 12613 } catch (IOException e) { 12614 pw.println("Failed writing: " + e); 12615 } 12616 } 12617 12618 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12619 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12620 if (packageName == null) { 12621 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12622 if (iperm == 0) { 12623 if (dumpState.onTitlePrinted()) 12624 pw.println(); 12625 pw.println("AppOp Permissions:"); 12626 } 12627 pw.print(" AppOp Permission "); 12628 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12629 pw.println(":"); 12630 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12631 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12632 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12633 } 12634 } 12635 } 12636 } 12637 12638 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12639 boolean printedSomething = false; 12640 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12641 if (packageName != null && !packageName.equals(p.info.packageName)) { 12642 continue; 12643 } 12644 if (!printedSomething) { 12645 if (dumpState.onTitlePrinted()) 12646 pw.println(); 12647 pw.println("Registered ContentProviders:"); 12648 printedSomething = true; 12649 } 12650 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12651 pw.print(" "); pw.println(p.toString()); 12652 } 12653 printedSomething = false; 12654 for (Map.Entry<String, PackageParser.Provider> entry : 12655 mProvidersByAuthority.entrySet()) { 12656 PackageParser.Provider p = entry.getValue(); 12657 if (packageName != null && !packageName.equals(p.info.packageName)) { 12658 continue; 12659 } 12660 if (!printedSomething) { 12661 if (dumpState.onTitlePrinted()) 12662 pw.println(); 12663 pw.println("ContentProvider Authorities:"); 12664 printedSomething = true; 12665 } 12666 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12667 pw.print(" "); pw.println(p.toString()); 12668 if (p.info != null && p.info.applicationInfo != null) { 12669 final String appInfo = p.info.applicationInfo.toString(); 12670 pw.print(" applicationInfo="); pw.println(appInfo); 12671 } 12672 } 12673 } 12674 12675 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12676 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12677 } 12678 12679 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12680 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12681 } 12682 12683 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12684 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12685 } 12686 12687 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12688 // XXX should handle packageName != null by dumping only install data that 12689 // the given package is involved with. 12690 if (dumpState.onTitlePrinted()) pw.println(); 12691 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12692 } 12693 12694 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12695 if (dumpState.onTitlePrinted()) pw.println(); 12696 mSettings.dumpReadMessagesLPr(pw, dumpState); 12697 12698 pw.println(); 12699 pw.println("Package warning messages:"); 12700 final File fname = getSettingsProblemFile(); 12701 FileInputStream in = null; 12702 try { 12703 in = new FileInputStream(fname); 12704 final int avail = in.available(); 12705 final byte[] data = new byte[avail]; 12706 in.read(data); 12707 pw.print(new String(data)); 12708 } catch (FileNotFoundException e) { 12709 } catch (IOException e) { 12710 } finally { 12711 if (in != null) { 12712 try { 12713 in.close(); 12714 } catch (IOException e) { 12715 } 12716 } 12717 } 12718 } 12719 12720 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12721 BufferedReader in = null; 12722 String line = null; 12723 try { 12724 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12725 while ((line = in.readLine()) != null) { 12726 pw.print("msg,"); 12727 pw.println(line); 12728 } 12729 } catch (IOException ignored) { 12730 } finally { 12731 IoUtils.closeQuietly(in); 12732 } 12733 } 12734 } 12735 } 12736 12737 // ------- apps on sdcard specific code ------- 12738 static final boolean DEBUG_SD_INSTALL = false; 12739 12740 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12741 12742 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12743 12744 private boolean mMediaMounted = false; 12745 12746 static String getEncryptKey() { 12747 try { 12748 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12749 SD_ENCRYPTION_KEYSTORE_NAME); 12750 if (sdEncKey == null) { 12751 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12752 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12753 if (sdEncKey == null) { 12754 Slog.e(TAG, "Failed to create encryption keys"); 12755 return null; 12756 } 12757 } 12758 return sdEncKey; 12759 } catch (NoSuchAlgorithmException nsae) { 12760 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12761 return null; 12762 } catch (IOException ioe) { 12763 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12764 return null; 12765 } 12766 } 12767 12768 /* 12769 * Update media status on PackageManager. 12770 */ 12771 @Override 12772 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12773 int callingUid = Binder.getCallingUid(); 12774 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12775 throw new SecurityException("Media status can only be updated by the system"); 12776 } 12777 // reader; this apparently protects mMediaMounted, but should probably 12778 // be a different lock in that case. 12779 synchronized (mPackages) { 12780 Log.i(TAG, "Updating external media status from " 12781 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12782 + (mediaStatus ? "mounted" : "unmounted")); 12783 if (DEBUG_SD_INSTALL) 12784 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12785 + ", mMediaMounted=" + mMediaMounted); 12786 if (mediaStatus == mMediaMounted) { 12787 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12788 : 0, -1); 12789 mHandler.sendMessage(msg); 12790 return; 12791 } 12792 mMediaMounted = mediaStatus; 12793 } 12794 // Queue up an async operation since the package installation may take a 12795 // little while. 12796 mHandler.post(new Runnable() { 12797 public void run() { 12798 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12799 } 12800 }); 12801 } 12802 12803 /** 12804 * Called by MountService when the initial ASECs to scan are available. 12805 * Should block until all the ASEC containers are finished being scanned. 12806 */ 12807 public void scanAvailableAsecs() { 12808 updateExternalMediaStatusInner(true, false, false); 12809 if (mShouldRestoreconData) { 12810 SELinuxMMAC.setRestoreconDone(); 12811 mShouldRestoreconData = false; 12812 } 12813 } 12814 12815 /* 12816 * Collect information of applications on external media, map them against 12817 * existing containers and update information based on current mount status. 12818 * Please note that we always have to report status if reportStatus has been 12819 * set to true especially when unloading packages. 12820 */ 12821 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12822 boolean externalStorage) { 12823 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12824 int[] uidArr = EmptyArray.INT; 12825 12826 final String[] list = PackageHelper.getSecureContainerList(); 12827 if (ArrayUtils.isEmpty(list)) { 12828 Log.i(TAG, "No secure containers found"); 12829 } else { 12830 // Process list of secure containers and categorize them 12831 // as active or stale based on their package internal state. 12832 12833 // reader 12834 synchronized (mPackages) { 12835 for (String cid : list) { 12836 // Leave stages untouched for now; installer service owns them 12837 if (PackageInstallerService.isStageName(cid)) continue; 12838 12839 if (DEBUG_SD_INSTALL) 12840 Log.i(TAG, "Processing container " + cid); 12841 String pkgName = getAsecPackageName(cid); 12842 if (pkgName == null) { 12843 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12844 continue; 12845 } 12846 if (DEBUG_SD_INSTALL) 12847 Log.i(TAG, "Looking for pkg : " + pkgName); 12848 12849 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12850 if (ps == null) { 12851 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12852 continue; 12853 } 12854 12855 /* 12856 * Skip packages that are not external if we're unmounting 12857 * external storage. 12858 */ 12859 if (externalStorage && !isMounted && !isExternal(ps)) { 12860 continue; 12861 } 12862 12863 final AsecInstallArgs args = new AsecInstallArgs(cid, 12864 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12865 // The package status is changed only if the code path 12866 // matches between settings and the container id. 12867 if (ps.codePathString != null 12868 && ps.codePathString.startsWith(args.getCodePath())) { 12869 if (DEBUG_SD_INSTALL) { 12870 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12871 + " at code path: " + ps.codePathString); 12872 } 12873 12874 // We do have a valid package installed on sdcard 12875 processCids.put(args, ps.codePathString); 12876 final int uid = ps.appId; 12877 if (uid != -1) { 12878 uidArr = ArrayUtils.appendInt(uidArr, uid); 12879 } 12880 } else { 12881 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12882 + ps.codePathString); 12883 } 12884 } 12885 } 12886 12887 Arrays.sort(uidArr); 12888 } 12889 12890 // Process packages with valid entries. 12891 if (isMounted) { 12892 if (DEBUG_SD_INSTALL) 12893 Log.i(TAG, "Loading packages"); 12894 loadMediaPackages(processCids, uidArr); 12895 startCleaningPackages(); 12896 mInstallerService.onSecureContainersAvailable(); 12897 } else { 12898 if (DEBUG_SD_INSTALL) 12899 Log.i(TAG, "Unloading packages"); 12900 unloadMediaPackages(processCids, uidArr, reportStatus); 12901 } 12902 } 12903 12904 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12905 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12906 int size = pkgList.size(); 12907 if (size > 0) { 12908 // Send broadcasts here 12909 Bundle extras = new Bundle(); 12910 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12911 .toArray(new String[size])); 12912 if (uidArr != null) { 12913 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12914 } 12915 if (replacing) { 12916 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12917 } 12918 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12919 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12920 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12921 } 12922 } 12923 12924 /* 12925 * Look at potentially valid container ids from processCids If package 12926 * information doesn't match the one on record or package scanning fails, 12927 * the cid is added to list of removeCids. We currently don't delete stale 12928 * containers. 12929 */ 12930 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12931 ArrayList<String> pkgList = new ArrayList<String>(); 12932 Set<AsecInstallArgs> keys = processCids.keySet(); 12933 12934 for (AsecInstallArgs args : keys) { 12935 String codePath = processCids.get(args); 12936 if (DEBUG_SD_INSTALL) 12937 Log.i(TAG, "Loading container : " + args.cid); 12938 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12939 try { 12940 // Make sure there are no container errors first. 12941 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12942 Slog.e(TAG, "Failed to mount cid : " + args.cid 12943 + " when installing from sdcard"); 12944 continue; 12945 } 12946 // Check code path here. 12947 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12948 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12949 + " does not match one in settings " + codePath); 12950 continue; 12951 } 12952 // Parse package 12953 int parseFlags = mDefParseFlags; 12954 if (args.isExternal()) { 12955 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12956 } 12957 if (args.isFwdLocked()) { 12958 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12959 } 12960 12961 synchronized (mInstallLock) { 12962 PackageParser.Package pkg = null; 12963 try { 12964 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12965 } catch (PackageManagerException e) { 12966 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12967 } 12968 // Scan the package 12969 if (pkg != null) { 12970 /* 12971 * TODO why is the lock being held? doPostInstall is 12972 * called in other places without the lock. This needs 12973 * to be straightened out. 12974 */ 12975 // writer 12976 synchronized (mPackages) { 12977 retCode = PackageManager.INSTALL_SUCCEEDED; 12978 pkgList.add(pkg.packageName); 12979 // Post process args 12980 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12981 pkg.applicationInfo.uid); 12982 } 12983 } else { 12984 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12985 } 12986 } 12987 12988 } finally { 12989 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12990 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12991 } 12992 } 12993 } 12994 // writer 12995 synchronized (mPackages) { 12996 // If the platform SDK has changed since the last time we booted, 12997 // we need to re-grant app permission to catch any new ones that 12998 // appear. This is really a hack, and means that apps can in some 12999 // cases get permissions that the user didn't initially explicitly 13000 // allow... it would be nice to have some better way to handle 13001 // this situation. 13002 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13003 if (regrantPermissions) 13004 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13005 + mSdkVersion + "; regranting permissions for external storage"); 13006 mSettings.mExternalSdkPlatform = mSdkVersion; 13007 13008 // Make sure group IDs have been assigned, and any permission 13009 // changes in other apps are accounted for 13010 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13011 | (regrantPermissions 13012 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13013 : 0)); 13014 13015 mSettings.updateExternalDatabaseVersion(); 13016 13017 // can downgrade to reader 13018 // Persist settings 13019 mSettings.writeLPr(); 13020 } 13021 // Send a broadcast to let everyone know we are done processing 13022 if (pkgList.size() > 0) { 13023 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13024 } 13025 } 13026 13027 /* 13028 * Utility method to unload a list of specified containers 13029 */ 13030 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13031 // Just unmount all valid containers. 13032 for (AsecInstallArgs arg : cidArgs) { 13033 synchronized (mInstallLock) { 13034 arg.doPostDeleteLI(false); 13035 } 13036 } 13037 } 13038 13039 /* 13040 * Unload packages mounted on external media. This involves deleting package 13041 * data from internal structures, sending broadcasts about diabled packages, 13042 * gc'ing to free up references, unmounting all secure containers 13043 * corresponding to packages on external media, and posting a 13044 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13045 * that we always have to post this message if status has been requested no 13046 * matter what. 13047 */ 13048 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13049 final boolean reportStatus) { 13050 if (DEBUG_SD_INSTALL) 13051 Log.i(TAG, "unloading media packages"); 13052 ArrayList<String> pkgList = new ArrayList<String>(); 13053 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13054 final Set<AsecInstallArgs> keys = processCids.keySet(); 13055 for (AsecInstallArgs args : keys) { 13056 String pkgName = args.getPackageName(); 13057 if (DEBUG_SD_INSTALL) 13058 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13059 // Delete package internally 13060 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13061 synchronized (mInstallLock) { 13062 boolean res = deletePackageLI(pkgName, null, false, null, null, 13063 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13064 if (res) { 13065 pkgList.add(pkgName); 13066 } else { 13067 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13068 failedList.add(args); 13069 } 13070 } 13071 } 13072 13073 // reader 13074 synchronized (mPackages) { 13075 // We didn't update the settings after removing each package; 13076 // write them now for all packages. 13077 mSettings.writeLPr(); 13078 } 13079 13080 // We have to absolutely send UPDATED_MEDIA_STATUS only 13081 // after confirming that all the receivers processed the ordered 13082 // broadcast when packages get disabled, force a gc to clean things up. 13083 // and unload all the containers. 13084 if (pkgList.size() > 0) { 13085 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13086 new IIntentReceiver.Stub() { 13087 public void performReceive(Intent intent, int resultCode, String data, 13088 Bundle extras, boolean ordered, boolean sticky, 13089 int sendingUser) throws RemoteException { 13090 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13091 reportStatus ? 1 : 0, 1, keys); 13092 mHandler.sendMessage(msg); 13093 } 13094 }); 13095 } else { 13096 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13097 keys); 13098 mHandler.sendMessage(msg); 13099 } 13100 } 13101 13102 /** Binder call */ 13103 @Override 13104 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13105 final int flags) { 13106 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13107 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13108 int returnCode = PackageManager.MOVE_SUCCEEDED; 13109 int currInstallFlags = 0; 13110 int newInstallFlags = 0; 13111 13112 File codeFile = null; 13113 String installerPackageName = null; 13114 String packageAbiOverride = null; 13115 13116 // reader 13117 synchronized (mPackages) { 13118 final PackageParser.Package pkg = mPackages.get(packageName); 13119 final PackageSetting ps = mSettings.mPackages.get(packageName); 13120 if (pkg == null || ps == null) { 13121 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13122 } else { 13123 // Disable moving fwd locked apps and system packages 13124 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13125 Slog.w(TAG, "Cannot move system application"); 13126 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13127 } else if (pkg.mOperationPending) { 13128 Slog.w(TAG, "Attempt to move package which has pending operations"); 13129 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13130 } else { 13131 // Find install location first 13132 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13133 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13134 Slog.w(TAG, "Ambigous flags specified for move location."); 13135 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13136 } else { 13137 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13138 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13139 currInstallFlags = isExternal(pkg) 13140 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13141 13142 if (newInstallFlags == currInstallFlags) { 13143 Slog.w(TAG, "No move required. Trying to move to same location"); 13144 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13145 } else { 13146 if (isForwardLocked(pkg)) { 13147 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13148 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13149 } 13150 } 13151 } 13152 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13153 pkg.mOperationPending = true; 13154 } 13155 } 13156 13157 codeFile = new File(pkg.codePath); 13158 installerPackageName = ps.installerPackageName; 13159 packageAbiOverride = ps.cpuAbiOverrideString; 13160 } 13161 } 13162 13163 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13164 try { 13165 observer.packageMoved(packageName, returnCode); 13166 } catch (RemoteException ignored) { 13167 } 13168 return; 13169 } 13170 13171 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13172 @Override 13173 public void onUserActionRequired(Intent intent) throws RemoteException { 13174 throw new IllegalStateException(); 13175 } 13176 13177 @Override 13178 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13179 Bundle extras) throws RemoteException { 13180 Slog.d(TAG, "Install result for move: " 13181 + PackageManager.installStatusToString(returnCode, msg)); 13182 13183 // We usually have a new package now after the install, but if 13184 // we failed we need to clear the pending flag on the original 13185 // package object. 13186 synchronized (mPackages) { 13187 final PackageParser.Package pkg = mPackages.get(packageName); 13188 if (pkg != null) { 13189 pkg.mOperationPending = false; 13190 } 13191 } 13192 13193 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13194 switch (status) { 13195 case PackageInstaller.STATUS_SUCCESS: 13196 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13197 break; 13198 case PackageInstaller.STATUS_FAILURE_STORAGE: 13199 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13200 break; 13201 default: 13202 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13203 break; 13204 } 13205 } 13206 }; 13207 13208 // Treat a move like reinstalling an existing app, which ensures that we 13209 // process everythign uniformly, like unpacking native libraries. 13210 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13211 13212 final Message msg = mHandler.obtainMessage(INIT_COPY); 13213 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13214 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13215 installerPackageName, null, user, packageAbiOverride); 13216 mHandler.sendMessage(msg); 13217 } 13218 13219 @Override 13220 public boolean setInstallLocation(int loc) { 13221 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13222 null); 13223 if (getInstallLocation() == loc) { 13224 return true; 13225 } 13226 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13227 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13228 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13229 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13230 return true; 13231 } 13232 return false; 13233 } 13234 13235 @Override 13236 public int getInstallLocation() { 13237 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13238 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13239 PackageHelper.APP_INSTALL_AUTO); 13240 } 13241 13242 /** Called by UserManagerService */ 13243 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13244 mDirtyUsers.remove(userHandle); 13245 mSettings.removeUserLPw(userHandle); 13246 mPendingBroadcasts.remove(userHandle); 13247 if (mInstaller != null) { 13248 // Technically, we shouldn't be doing this with the package lock 13249 // held. However, this is very rare, and there is already so much 13250 // other disk I/O going on, that we'll let it slide for now. 13251 mInstaller.removeUserDataDirs(userHandle); 13252 } 13253 mUserNeedsBadging.delete(userHandle); 13254 removeUnusedPackagesLILPw(userManager, userHandle); 13255 } 13256 13257 /** 13258 * We're removing userHandle and would like to remove any downloaded packages 13259 * that are no longer in use by any other user. 13260 * @param userHandle the user being removed 13261 */ 13262 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13263 final boolean DEBUG_CLEAN_APKS = false; 13264 int [] users = userManager.getUserIdsLPr(); 13265 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13266 while (psit.hasNext()) { 13267 PackageSetting ps = psit.next(); 13268 if (ps.pkg == null) { 13269 continue; 13270 } 13271 final String packageName = ps.pkg.packageName; 13272 // Skip over if system app 13273 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13274 continue; 13275 } 13276 if (DEBUG_CLEAN_APKS) { 13277 Slog.i(TAG, "Checking package " + packageName); 13278 } 13279 boolean keep = false; 13280 for (int i = 0; i < users.length; i++) { 13281 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13282 keep = true; 13283 if (DEBUG_CLEAN_APKS) { 13284 Slog.i(TAG, " Keeping package " + packageName + " for user " 13285 + users[i]); 13286 } 13287 break; 13288 } 13289 } 13290 if (!keep) { 13291 if (DEBUG_CLEAN_APKS) { 13292 Slog.i(TAG, " Removing package " + packageName); 13293 } 13294 mHandler.post(new Runnable() { 13295 public void run() { 13296 deletePackageX(packageName, userHandle, 0); 13297 } //end run 13298 }); 13299 } 13300 } 13301 } 13302 13303 /** Called by UserManagerService */ 13304 void createNewUserLILPw(int userHandle, File path) { 13305 if (mInstaller != null) { 13306 mInstaller.createUserConfig(userHandle); 13307 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13308 } 13309 } 13310 13311 @Override 13312 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13313 mContext.enforceCallingOrSelfPermission( 13314 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13315 "Only package verification agents can read the verifier device identity"); 13316 13317 synchronized (mPackages) { 13318 return mSettings.getVerifierDeviceIdentityLPw(); 13319 } 13320 } 13321 13322 @Override 13323 public void setPermissionEnforced(String permission, boolean enforced) { 13324 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13325 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13326 synchronized (mPackages) { 13327 if (mSettings.mReadExternalStorageEnforced == null 13328 || mSettings.mReadExternalStorageEnforced != enforced) { 13329 mSettings.mReadExternalStorageEnforced = enforced; 13330 mSettings.writeLPr(); 13331 } 13332 } 13333 // kill any non-foreground processes so we restart them and 13334 // grant/revoke the GID. 13335 final IActivityManager am = ActivityManagerNative.getDefault(); 13336 if (am != null) { 13337 final long token = Binder.clearCallingIdentity(); 13338 try { 13339 am.killProcessesBelowForeground("setPermissionEnforcement"); 13340 } catch (RemoteException e) { 13341 } finally { 13342 Binder.restoreCallingIdentity(token); 13343 } 13344 } 13345 } else { 13346 throw new IllegalArgumentException("No selective enforcement for " + permission); 13347 } 13348 } 13349 13350 @Override 13351 @Deprecated 13352 public boolean isPermissionEnforced(String permission) { 13353 return true; 13354 } 13355 13356 @Override 13357 public boolean isStorageLow() { 13358 final long token = Binder.clearCallingIdentity(); 13359 try { 13360 final DeviceStorageMonitorInternal 13361 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13362 if (dsm != null) { 13363 return dsm.isMemoryLow(); 13364 } else { 13365 return false; 13366 } 13367 } finally { 13368 Binder.restoreCallingIdentity(token); 13369 } 13370 } 13371 13372 @Override 13373 public IPackageInstaller getPackageInstaller() { 13374 return mInstallerService; 13375 } 13376 13377 private boolean userNeedsBadging(int userId) { 13378 int index = mUserNeedsBadging.indexOfKey(userId); 13379 if (index < 0) { 13380 final UserInfo userInfo; 13381 final long token = Binder.clearCallingIdentity(); 13382 try { 13383 userInfo = sUserManager.getUserInfo(userId); 13384 } finally { 13385 Binder.restoreCallingIdentity(token); 13386 } 13387 final boolean b; 13388 if (userInfo != null && userInfo.isManagedProfile()) { 13389 b = true; 13390 } else { 13391 b = false; 13392 } 13393 mUserNeedsBadging.put(userId, b); 13394 return b; 13395 } 13396 return mUserNeedsBadging.valueAt(index); 13397 } 13398 13399 @Override 13400 public KeySet getKeySetByAlias(String packageName, String alias) { 13401 if (packageName == null || alias == null) { 13402 return null; 13403 } 13404 synchronized(mPackages) { 13405 final PackageParser.Package pkg = mPackages.get(packageName); 13406 if (pkg == null) { 13407 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13408 throw new IllegalArgumentException("Unknown package: " + packageName); 13409 } 13410 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13411 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13412 } 13413 } 13414 13415 @Override 13416 public KeySet getSigningKeySet(String packageName) { 13417 if (packageName == null) { 13418 return null; 13419 } 13420 synchronized(mPackages) { 13421 final PackageParser.Package pkg = mPackages.get(packageName); 13422 if (pkg == null) { 13423 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13424 throw new IllegalArgumentException("Unknown package: " + packageName); 13425 } 13426 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13427 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13428 throw new SecurityException("May not access signing KeySet of other apps."); 13429 } 13430 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13431 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13432 } 13433 } 13434 13435 @Override 13436 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13437 if (packageName == null || ks == null) { 13438 return false; 13439 } 13440 synchronized(mPackages) { 13441 final PackageParser.Package pkg = mPackages.get(packageName); 13442 if (pkg == null) { 13443 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13444 throw new IllegalArgumentException("Unknown package: " + packageName); 13445 } 13446 IBinder ksh = ks.getToken(); 13447 if (ksh instanceof KeySetHandle) { 13448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13449 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13450 } 13451 return false; 13452 } 13453 } 13454 13455 @Override 13456 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13457 if (packageName == null || ks == null) { 13458 return false; 13459 } 13460 synchronized(mPackages) { 13461 final PackageParser.Package pkg = mPackages.get(packageName); 13462 if (pkg == null) { 13463 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13464 throw new IllegalArgumentException("Unknown package: " + packageName); 13465 } 13466 IBinder ksh = ks.getToken(); 13467 if (ksh instanceof KeySetHandle) { 13468 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13469 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13470 } 13471 return false; 13472 } 13473 } 13474} 13475