PackageManagerService.java revision e79553355b10815be2cd44f7b84ae39c91a12bb1
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.app.usage.UsageStats; 88import android.app.usage.UsageStatsManager; 89import android.content.BroadcastReceiver; 90import android.content.ComponentName; 91import android.content.Context; 92import android.content.IIntentReceiver; 93import android.content.Intent; 94import android.content.IntentFilter; 95import android.content.IntentSender; 96import android.content.IntentSender.SendIntentException; 97import android.content.ServiceConnection; 98import android.content.pm.ActivityInfo; 99import android.content.pm.ApplicationInfo; 100import android.content.pm.FeatureInfo; 101import android.content.pm.IPackageDataObserver; 102import android.content.pm.IPackageDeleteObserver; 103import android.content.pm.IPackageDeleteObserver2; 104import android.content.pm.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstrumentationInfo; 110import android.content.pm.KeySet; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageInstaller; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.storage.StorageManager; 144import android.os.Debug; 145import android.os.FileUtils; 146import android.os.Handler; 147import android.os.IBinder; 148import android.os.Looper; 149import android.os.Message; 150import android.os.Parcel; 151import android.os.ParcelFileDescriptor; 152import android.os.Process; 153import android.os.RemoteException; 154import android.os.SELinux; 155import android.os.ServiceManager; 156import android.os.SystemClock; 157import android.os.SystemProperties; 158import android.os.UserHandle; 159import android.os.UserManager; 160import android.security.KeyStore; 161import android.security.SystemKeyStore; 162import android.system.ErrnoException; 163import android.system.Os; 164import android.system.StructStat; 165import android.text.TextUtils; 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.Iterator; 205import java.util.List; 206import java.util.Map; 207import java.util.Objects; 208import java.util.Set; 209import java.util.concurrent.atomic.AtomicBoolean; 210import java.util.concurrent.atomic.AtomicLong; 211 212import dalvik.system.DexFile; 213import dalvik.system.StaleDexCacheError; 214import dalvik.system.VMRuntime; 215 216import libcore.io.IoUtils; 217import libcore.util.EmptyArray; 218 219/** 220 * Keep track of all those .apks everywhere. 221 * 222 * This is very central to the platform's security; please run the unit 223 * tests whenever making modifications here: 224 * 225mmm frameworks/base/tests/AndroidTests 226adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 227adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 228 * 229 * {@hide} 230 */ 231public class PackageManagerService extends IPackageManager.Stub { 232 static final String TAG = "PackageManager"; 233 static final boolean DEBUG_SETTINGS = false; 234 static final boolean DEBUG_PREFERRED = false; 235 static final boolean DEBUG_UPGRADE = false; 236 private static final boolean DEBUG_INSTALL = false; 237 private static final boolean DEBUG_REMOVE = false; 238 private static final boolean DEBUG_BROADCASTS = false; 239 private static final boolean DEBUG_SHOW_INFO = false; 240 private static final boolean DEBUG_PACKAGE_INFO = false; 241 private static final boolean DEBUG_INTENT_MATCHING = false; 242 private static final boolean DEBUG_PACKAGE_SCANNING = false; 243 private static final boolean DEBUG_VERIFY = false; 244 private static final boolean DEBUG_DEXOPT = false; 245 private static final boolean DEBUG_ABI_SELECTION = false; 246 247 private static final int RADIO_UID = Process.PHONE_UID; 248 private static final int LOG_UID = Process.LOG_UID; 249 private static final int NFC_UID = Process.NFC_UID; 250 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 251 private static final int SHELL_UID = Process.SHELL_UID; 252 253 // Cap the size of permission trees that 3rd party apps can define 254 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 255 256 // Suffix used during package installation when copying/moving 257 // package apks to install directory. 258 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 259 260 static final int SCAN_NO_DEX = 1<<1; 261 static final int SCAN_FORCE_DEX = 1<<2; 262 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 263 static final int SCAN_NEW_INSTALL = 1<<4; 264 static final int SCAN_NO_PATHS = 1<<5; 265 static final int SCAN_UPDATE_TIME = 1<<6; 266 static final int SCAN_DEFER_DEX = 1<<7; 267 static final int SCAN_BOOTING = 1<<8; 268 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 269 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 270 static final int SCAN_REPLACING = 1<<11; 271 272 static final int REMOVE_CHATTY = 1<<16; 273 274 /** 275 * Timeout (in milliseconds) after which the watchdog should declare that 276 * our handler thread is wedged. The usual default for such things is one 277 * minute but we sometimes do very lengthy I/O operations on this thread, 278 * such as installing multi-gigabyte applications, so ours needs to be longer. 279 */ 280 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 281 282 /** 283 * Whether verification is enabled by default. 284 */ 285 private static final boolean DEFAULT_VERIFY_ENABLE = true; 286 287 /** 288 * The default maximum time to wait for the verification agent to return in 289 * milliseconds. 290 */ 291 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 292 293 /** 294 * The default response for package verification timeout. 295 * 296 * This can be either PackageManager.VERIFICATION_ALLOW or 297 * PackageManager.VERIFICATION_REJECT. 298 */ 299 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 300 301 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 302 303 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 304 DEFAULT_CONTAINER_PACKAGE, 305 "com.android.defcontainer.DefaultContainerService"); 306 307 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 308 309 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 310 311 private static String sPreferredInstructionSet; 312 313 final ServiceThread mHandlerThread; 314 315 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 316 private static final String IDMAP_SUFFIX = "@idmap"; 317 318 final PackageHandler mHandler; 319 320 /** 321 * Messages for {@link #mHandler} that need to wait for system ready before 322 * being dispatched. 323 */ 324 private ArrayList<Message> mPostSystemReadyMessages; 325 326 final int mSdkVersion = Build.VERSION.SDK_INT; 327 328 final Context mContext; 329 final boolean mFactoryTest; 330 final boolean mOnlyCore; 331 final boolean mLazyDexOpt; 332 final long mDexOptLRUThresholdInMills; 333 final DisplayMetrics mMetrics; 334 final int mDefParseFlags; 335 final String[] mSeparateProcesses; 336 337 // This is where all application persistent data goes. 338 final File mAppDataDir; 339 340 // This is where all application persistent data goes for secondary users. 341 final File mUserAppDataDir; 342 343 /** The location for ASEC container files on internal storage. */ 344 final String mAsecInternalPath; 345 346 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 347 // LOCK HELD. Can be called with mInstallLock held. 348 final Installer mInstaller; 349 350 /** Directory where installed third-party apps stored */ 351 final File mAppInstallDir; 352 353 /** 354 * Directory to which applications installed internally have their 355 * 32 bit native libraries copied. 356 */ 357 private File mAppLib32InstallDir; 358 359 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 360 // apps. 361 final File mDrmAppPrivateInstallDir; 362 363 // ---------------------------------------------------------------- 364 365 // Lock for state used when installing and doing other long running 366 // operations. Methods that must be called with this lock held have 367 // the suffix "LI". 368 final Object mInstallLock = new Object(); 369 370 // ---------------------------------------------------------------- 371 372 // Keys are String (package name), values are Package. This also serves 373 // as the lock for the global state. Methods that must be called with 374 // this lock held have the prefix "LP". 375 final ArrayMap<String, PackageParser.Package> mPackages = 376 new ArrayMap<String, PackageParser.Package>(); 377 378 // Tracks available target package names -> overlay package paths. 379 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 380 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 381 382 final Settings mSettings; 383 boolean mRestoredSettings; 384 385 // System configuration read by SystemConfig. 386 final int[] mGlobalGids; 387 final SparseArray<ArraySet<String>> mSystemPermissions; 388 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 389 390 // If mac_permissions.xml was found for seinfo labeling. 391 boolean mFoundPolicyFile; 392 393 // If a recursive restorecon of /data/data/<pkg> is needed. 394 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 395 396 public static final class SharedLibraryEntry { 397 public final String path; 398 public final String apk; 399 400 SharedLibraryEntry(String _path, String _apk) { 401 path = _path; 402 apk = _apk; 403 } 404 } 405 406 // Currently known shared libraries. 407 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 408 new ArrayMap<String, SharedLibraryEntry>(); 409 410 // All available activities, for your resolving pleasure. 411 final ActivityIntentResolver mActivities = 412 new ActivityIntentResolver(); 413 414 // All available receivers, for your resolving pleasure. 415 final ActivityIntentResolver mReceivers = 416 new ActivityIntentResolver(); 417 418 // All available services, for your resolving pleasure. 419 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 420 421 // All available providers, for your resolving pleasure. 422 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 423 424 // Mapping from provider base names (first directory in content URI codePath) 425 // to the provider information. 426 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 427 new ArrayMap<String, PackageParser.Provider>(); 428 429 // Mapping from instrumentation class names to info about them. 430 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 431 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 432 433 // Mapping from permission names to info about them. 434 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 435 new ArrayMap<String, PackageParser.PermissionGroup>(); 436 437 // Packages whose data we have transfered into another package, thus 438 // should no longer exist. 439 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 440 441 // Broadcast actions that are only available to the system. 442 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 443 444 /** List of packages waiting for verification. */ 445 final SparseArray<PackageVerificationState> mPendingVerification 446 = new SparseArray<PackageVerificationState>(); 447 448 /** Set of packages associated with each app op permission. */ 449 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 450 451 final PackageInstallerService mInstallerService; 452 453 ArraySet<PackageParser.Package> mDeferredDexOpt = null; 454 455 // Cache of users who need badging. 456 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 457 458 /** Token for keys in mPendingVerification. */ 459 private int mPendingVerificationToken = 0; 460 461 volatile boolean mSystemReady; 462 volatile boolean mSafeMode; 463 volatile boolean mHasSystemUidErrors; 464 465 ApplicationInfo mAndroidApplication; 466 final ActivityInfo mResolveActivity = new ActivityInfo(); 467 final ResolveInfo mResolveInfo = new ResolveInfo(); 468 ComponentName mResolveComponentName; 469 PackageParser.Package mPlatformPackage; 470 ComponentName mCustomResolverComponentName; 471 472 boolean mResolverReplaced = false; 473 474 // Set of pending broadcasts for aggregating enable/disable of components. 475 static class PendingPackageBroadcasts { 476 // for each user id, a map of <package name -> components within that package> 477 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 478 479 public PendingPackageBroadcasts() { 480 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 481 } 482 483 public ArrayList<String> get(int userId, String packageName) { 484 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 485 return packages.get(packageName); 486 } 487 488 public void put(int userId, String packageName, ArrayList<String> components) { 489 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 490 packages.put(packageName, components); 491 } 492 493 public void remove(int userId, String packageName) { 494 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 495 if (packages != null) { 496 packages.remove(packageName); 497 } 498 } 499 500 public void remove(int userId) { 501 mUidMap.remove(userId); 502 } 503 504 public int userIdCount() { 505 return mUidMap.size(); 506 } 507 508 public int userIdAt(int n) { 509 return mUidMap.keyAt(n); 510 } 511 512 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 513 return mUidMap.get(userId); 514 } 515 516 public int size() { 517 // total number of pending broadcast entries across all userIds 518 int num = 0; 519 for (int i = 0; i< mUidMap.size(); i++) { 520 num += mUidMap.valueAt(i).size(); 521 } 522 return num; 523 } 524 525 public void clear() { 526 mUidMap.clear(); 527 } 528 529 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 530 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 531 if (map == null) { 532 map = new ArrayMap<String, ArrayList<String>>(); 533 mUidMap.put(userId, map); 534 } 535 return map; 536 } 537 } 538 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 539 540 // Service Connection to remote media container service to copy 541 // package uri's from external media onto secure containers 542 // or internal storage. 543 private IMediaContainerService mContainerService = null; 544 545 static final int SEND_PENDING_BROADCAST = 1; 546 static final int MCS_BOUND = 3; 547 static final int END_COPY = 4; 548 static final int INIT_COPY = 5; 549 static final int MCS_UNBIND = 6; 550 static final int START_CLEANING_PACKAGE = 7; 551 static final int FIND_INSTALL_LOC = 8; 552 static final int POST_INSTALL = 9; 553 static final int MCS_RECONNECT = 10; 554 static final int MCS_GIVE_UP = 11; 555 static final int UPDATED_MEDIA_STATUS = 12; 556 static final int WRITE_SETTINGS = 13; 557 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 558 static final int PACKAGE_VERIFIED = 15; 559 static final int CHECK_PENDING_VERIFICATION = 16; 560 561 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 562 563 // Delay time in millisecs 564 static final int BROADCAST_DELAY = 10 * 1000; 565 566 static UserManagerService sUserManager; 567 568 // Stores a list of users whose package restrictions file needs to be updated 569 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 570 571 final private DefaultContainerConnection mDefContainerConn = 572 new DefaultContainerConnection(); 573 class DefaultContainerConnection implements ServiceConnection { 574 public void onServiceConnected(ComponentName name, IBinder service) { 575 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 576 IMediaContainerService imcs = 577 IMediaContainerService.Stub.asInterface(service); 578 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 579 } 580 581 public void onServiceDisconnected(ComponentName name) { 582 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 583 } 584 }; 585 586 // Recordkeeping of restore-after-install operations that are currently in flight 587 // between the Package Manager and the Backup Manager 588 class PostInstallData { 589 public InstallArgs args; 590 public PackageInstalledInfo res; 591 592 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 593 args = _a; 594 res = _r; 595 } 596 }; 597 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 598 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 599 600 private final String mRequiredVerifierPackage; 601 602 private final PackageUsage mPackageUsage = new PackageUsage(); 603 604 private class PackageUsage { 605 private static final int WRITE_INTERVAL 606 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 607 608 private final Object mFileLock = new Object(); 609 private final AtomicLong mLastWritten = new AtomicLong(0); 610 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 611 612 private boolean mIsHistoricalPackageUsageAvailable = true; 613 614 boolean isHistoricalPackageUsageAvailable() { 615 return mIsHistoricalPackageUsageAvailable; 616 } 617 618 void write(boolean force) { 619 if (force) { 620 writeInternal(); 621 return; 622 } 623 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 624 && !DEBUG_DEXOPT) { 625 return; 626 } 627 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 628 new Thread("PackageUsage_DiskWriter") { 629 @Override 630 public void run() { 631 try { 632 writeInternal(); 633 } finally { 634 mBackgroundWriteRunning.set(false); 635 } 636 } 637 }.start(); 638 } 639 } 640 641 private void writeInternal() { 642 synchronized (mPackages) { 643 synchronized (mFileLock) { 644 AtomicFile file = getFile(); 645 FileOutputStream f = null; 646 try { 647 f = file.startWrite(); 648 BufferedOutputStream out = new BufferedOutputStream(f); 649 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 650 StringBuilder sb = new StringBuilder(); 651 for (PackageParser.Package pkg : mPackages.values()) { 652 if (pkg.mLastPackageUsageTimeInMills == 0) { 653 continue; 654 } 655 sb.setLength(0); 656 sb.append(pkg.packageName); 657 sb.append(' '); 658 sb.append((long)pkg.mLastPackageUsageTimeInMills); 659 sb.append('\n'); 660 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 661 } 662 out.flush(); 663 file.finishWrite(f); 664 } catch (IOException e) { 665 if (f != null) { 666 file.failWrite(f); 667 } 668 Log.e(TAG, "Failed to write package usage times", e); 669 } 670 } 671 } 672 mLastWritten.set(SystemClock.elapsedRealtime()); 673 } 674 675 void readLP() { 676 synchronized (mFileLock) { 677 AtomicFile file = getFile(); 678 BufferedInputStream in = null; 679 try { 680 in = new BufferedInputStream(file.openRead()); 681 StringBuffer sb = new StringBuffer(); 682 while (true) { 683 String packageName = readToken(in, sb, ' '); 684 if (packageName == null) { 685 break; 686 } 687 String timeInMillisString = readToken(in, sb, '\n'); 688 if (timeInMillisString == null) { 689 throw new IOException("Failed to find last usage time for package " 690 + packageName); 691 } 692 PackageParser.Package pkg = mPackages.get(packageName); 693 if (pkg == null) { 694 continue; 695 } 696 long timeInMillis; 697 try { 698 timeInMillis = Long.parseLong(timeInMillisString.toString()); 699 } catch (NumberFormatException e) { 700 throw new IOException("Failed to parse " + timeInMillisString 701 + " as a long.", e); 702 } 703 pkg.mLastPackageUsageTimeInMills = timeInMillis; 704 } 705 } catch (FileNotFoundException expected) { 706 mIsHistoricalPackageUsageAvailable = false; 707 } catch (IOException e) { 708 Log.w(TAG, "Failed to read package usage times", e); 709 } finally { 710 IoUtils.closeQuietly(in); 711 } 712 } 713 mLastWritten.set(SystemClock.elapsedRealtime()); 714 } 715 716 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 717 throws IOException { 718 sb.setLength(0); 719 while (true) { 720 int ch = in.read(); 721 if (ch == -1) { 722 if (sb.length() == 0) { 723 return null; 724 } 725 throw new IOException("Unexpected EOF"); 726 } 727 if (ch == endOfToken) { 728 return sb.toString(); 729 } 730 sb.append((char)ch); 731 } 732 } 733 734 private AtomicFile getFile() { 735 File dataDir = Environment.getDataDirectory(); 736 File systemDir = new File(dataDir, "system"); 737 File fname = new File(systemDir, "package-usage.list"); 738 return new AtomicFile(fname); 739 } 740 } 741 742 class PackageHandler extends Handler { 743 private boolean mBound = false; 744 final ArrayList<HandlerParams> mPendingInstalls = 745 new ArrayList<HandlerParams>(); 746 747 private boolean connectToService() { 748 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 749 " DefaultContainerService"); 750 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 751 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 752 if (mContext.bindServiceAsUser(service, mDefContainerConn, 753 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 754 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 755 mBound = true; 756 return true; 757 } 758 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 759 return false; 760 } 761 762 private void disconnectService() { 763 mContainerService = null; 764 mBound = false; 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 mContext.unbindService(mDefContainerConn); 767 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 768 } 769 770 PackageHandler(Looper looper) { 771 super(looper); 772 } 773 774 public void handleMessage(Message msg) { 775 try { 776 doHandleMessage(msg); 777 } finally { 778 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 779 } 780 } 781 782 void doHandleMessage(Message msg) { 783 switch (msg.what) { 784 case INIT_COPY: { 785 HandlerParams params = (HandlerParams) msg.obj; 786 int idx = mPendingInstalls.size(); 787 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 788 // If a bind was already initiated we dont really 789 // need to do anything. The pending install 790 // will be processed later on. 791 if (!mBound) { 792 // If this is the only one pending we might 793 // have to bind to the service again. 794 if (!connectToService()) { 795 Slog.e(TAG, "Failed to bind to media container service"); 796 params.serviceError(); 797 return; 798 } else { 799 // Once we bind to the service, the first 800 // pending request will be processed. 801 mPendingInstalls.add(idx, params); 802 } 803 } else { 804 mPendingInstalls.add(idx, params); 805 // Already bound to the service. Just make 806 // sure we trigger off processing the first request. 807 if (idx == 0) { 808 mHandler.sendEmptyMessage(MCS_BOUND); 809 } 810 } 811 break; 812 } 813 case MCS_BOUND: { 814 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 815 if (msg.obj != null) { 816 mContainerService = (IMediaContainerService) msg.obj; 817 } 818 if (mContainerService == null) { 819 // Something seriously wrong. Bail out 820 Slog.e(TAG, "Cannot bind to media container service"); 821 for (HandlerParams params : mPendingInstalls) { 822 // Indicate service bind error 823 params.serviceError(); 824 } 825 mPendingInstalls.clear(); 826 } else if (mPendingInstalls.size() > 0) { 827 HandlerParams params = mPendingInstalls.get(0); 828 if (params != null) { 829 if (params.startCopy()) { 830 // We are done... look for more work or to 831 // go idle. 832 if (DEBUG_SD_INSTALL) Log.i(TAG, 833 "Checking for more work or unbind..."); 834 // Delete pending install 835 if (mPendingInstalls.size() > 0) { 836 mPendingInstalls.remove(0); 837 } 838 if (mPendingInstalls.size() == 0) { 839 if (mBound) { 840 if (DEBUG_SD_INSTALL) Log.i(TAG, 841 "Posting delayed MCS_UNBIND"); 842 removeMessages(MCS_UNBIND); 843 Message ubmsg = obtainMessage(MCS_UNBIND); 844 // Unbind after a little delay, to avoid 845 // continual thrashing. 846 sendMessageDelayed(ubmsg, 10000); 847 } 848 } else { 849 // There are more pending requests in queue. 850 // Just post MCS_BOUND message to trigger processing 851 // of next pending install. 852 if (DEBUG_SD_INSTALL) Log.i(TAG, 853 "Posting MCS_BOUND for next work"); 854 mHandler.sendEmptyMessage(MCS_BOUND); 855 } 856 } 857 } 858 } else { 859 // Should never happen ideally. 860 Slog.w(TAG, "Empty queue"); 861 } 862 break; 863 } 864 case MCS_RECONNECT: { 865 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 866 if (mPendingInstalls.size() > 0) { 867 if (mBound) { 868 disconnectService(); 869 } 870 if (!connectToService()) { 871 Slog.e(TAG, "Failed to bind to media container service"); 872 for (HandlerParams params : mPendingInstalls) { 873 // Indicate service bind error 874 params.serviceError(); 875 } 876 mPendingInstalls.clear(); 877 } 878 } 879 break; 880 } 881 case MCS_UNBIND: { 882 // If there is no actual work left, then time to unbind. 883 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 884 885 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 886 if (mBound) { 887 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 888 889 disconnectService(); 890 } 891 } else if (mPendingInstalls.size() > 0) { 892 // There are more pending requests in queue. 893 // Just post MCS_BOUND message to trigger processing 894 // of next pending install. 895 mHandler.sendEmptyMessage(MCS_BOUND); 896 } 897 898 break; 899 } 900 case MCS_GIVE_UP: { 901 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 902 mPendingInstalls.remove(0); 903 break; 904 } 905 case SEND_PENDING_BROADCAST: { 906 String packages[]; 907 ArrayList<String> components[]; 908 int size = 0; 909 int uids[]; 910 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 911 synchronized (mPackages) { 912 if (mPendingBroadcasts == null) { 913 return; 914 } 915 size = mPendingBroadcasts.size(); 916 if (size <= 0) { 917 // Nothing to be done. Just return 918 return; 919 } 920 packages = new String[size]; 921 components = new ArrayList[size]; 922 uids = new int[size]; 923 int i = 0; // filling out the above arrays 924 925 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 926 int packageUserId = mPendingBroadcasts.userIdAt(n); 927 Iterator<Map.Entry<String, ArrayList<String>>> it 928 = mPendingBroadcasts.packagesForUserId(packageUserId) 929 .entrySet().iterator(); 930 while (it.hasNext() && i < size) { 931 Map.Entry<String, ArrayList<String>> ent = it.next(); 932 packages[i] = ent.getKey(); 933 components[i] = ent.getValue(); 934 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 935 uids[i] = (ps != null) 936 ? UserHandle.getUid(packageUserId, ps.appId) 937 : -1; 938 i++; 939 } 940 } 941 size = i; 942 mPendingBroadcasts.clear(); 943 } 944 // Send broadcasts 945 for (int i = 0; i < size; i++) { 946 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 947 } 948 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 949 break; 950 } 951 case START_CLEANING_PACKAGE: { 952 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 953 final String packageName = (String)msg.obj; 954 final int userId = msg.arg1; 955 final boolean andCode = msg.arg2 != 0; 956 synchronized (mPackages) { 957 if (userId == UserHandle.USER_ALL) { 958 int[] users = sUserManager.getUserIds(); 959 for (int user : users) { 960 mSettings.addPackageToCleanLPw( 961 new PackageCleanItem(user, packageName, andCode)); 962 } 963 } else { 964 mSettings.addPackageToCleanLPw( 965 new PackageCleanItem(userId, packageName, andCode)); 966 } 967 } 968 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 969 startCleaningPackages(); 970 } break; 971 case POST_INSTALL: { 972 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 973 PostInstallData data = mRunningInstalls.get(msg.arg1); 974 mRunningInstalls.delete(msg.arg1); 975 boolean deleteOld = false; 976 977 if (data != null) { 978 InstallArgs args = data.args; 979 PackageInstalledInfo res = data.res; 980 981 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 982 res.removedInfo.sendBroadcast(false, true, false); 983 Bundle extras = new Bundle(1); 984 extras.putInt(Intent.EXTRA_UID, res.uid); 985 // Determine the set of users who are adding this 986 // package for the first time vs. those who are seeing 987 // an update. 988 int[] firstUsers; 989 int[] updateUsers = new int[0]; 990 if (res.origUsers == null || res.origUsers.length == 0) { 991 firstUsers = res.newUsers; 992 } else { 993 firstUsers = new int[0]; 994 for (int i=0; i<res.newUsers.length; i++) { 995 int user = res.newUsers[i]; 996 boolean isNew = true; 997 for (int j=0; j<res.origUsers.length; j++) { 998 if (res.origUsers[j] == user) { 999 isNew = false; 1000 break; 1001 } 1002 } 1003 if (isNew) { 1004 int[] newFirst = new int[firstUsers.length+1]; 1005 System.arraycopy(firstUsers, 0, newFirst, 0, 1006 firstUsers.length); 1007 newFirst[firstUsers.length] = user; 1008 firstUsers = newFirst; 1009 } else { 1010 int[] newUpdate = new int[updateUsers.length+1]; 1011 System.arraycopy(updateUsers, 0, newUpdate, 0, 1012 updateUsers.length); 1013 newUpdate[updateUsers.length] = user; 1014 updateUsers = newUpdate; 1015 } 1016 } 1017 } 1018 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1019 res.pkg.applicationInfo.packageName, 1020 extras, null, null, firstUsers); 1021 final boolean update = res.removedInfo.removedPackage != null; 1022 if (update) { 1023 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1024 } 1025 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1026 res.pkg.applicationInfo.packageName, 1027 extras, null, null, updateUsers); 1028 if (update) { 1029 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1030 res.pkg.applicationInfo.packageName, 1031 extras, null, null, updateUsers); 1032 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1033 null, null, 1034 res.pkg.applicationInfo.packageName, null, updateUsers); 1035 1036 // treat asec-hosted packages like removable media on upgrade 1037 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1038 if (DEBUG_INSTALL) { 1039 Slog.i(TAG, "upgrading pkg " + res.pkg 1040 + " is ASEC-hosted -> AVAILABLE"); 1041 } 1042 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1043 ArrayList<String> pkgList = new ArrayList<String>(1); 1044 pkgList.add(res.pkg.applicationInfo.packageName); 1045 sendResourcesChangedBroadcast(true, true, 1046 pkgList,uidArray, null); 1047 } 1048 } 1049 if (res.removedInfo.args != null) { 1050 // Remove the replaced package's older resources safely now 1051 deleteOld = true; 1052 } 1053 1054 // Log current value of "unknown sources" setting 1055 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1056 getUnknownSourcesSettings()); 1057 } 1058 // Force a gc to clear up things 1059 Runtime.getRuntime().gc(); 1060 // We delete after a gc for applications on sdcard. 1061 if (deleteOld) { 1062 synchronized (mInstallLock) { 1063 res.removedInfo.args.doPostDeleteLI(true); 1064 } 1065 } 1066 if (args.observer != null) { 1067 try { 1068 Bundle extras = extrasForInstallResult(res); 1069 args.observer.onPackageInstalled(res.name, res.returnCode, 1070 res.returnMsg, extras); 1071 } catch (RemoteException e) { 1072 Slog.i(TAG, "Observer no longer exists."); 1073 } 1074 } 1075 } else { 1076 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1077 } 1078 } break; 1079 case UPDATED_MEDIA_STATUS: { 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1081 boolean reportStatus = msg.arg1 == 1; 1082 boolean doGc = msg.arg2 == 1; 1083 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1084 if (doGc) { 1085 // Force a gc to clear up stale containers. 1086 Runtime.getRuntime().gc(); 1087 } 1088 if (msg.obj != null) { 1089 @SuppressWarnings("unchecked") 1090 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1092 // Unload containers 1093 unloadAllContainers(args); 1094 } 1095 if (reportStatus) { 1096 try { 1097 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1098 PackageHelper.getMountService().finishMediaUpdate(); 1099 } catch (RemoteException e) { 1100 Log.e(TAG, "MountService not running?"); 1101 } 1102 } 1103 } break; 1104 case WRITE_SETTINGS: { 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1106 synchronized (mPackages) { 1107 removeMessages(WRITE_SETTINGS); 1108 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1109 mSettings.writeLPr(); 1110 mDirtyUsers.clear(); 1111 } 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 } break; 1114 case WRITE_PACKAGE_RESTRICTIONS: { 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1116 synchronized (mPackages) { 1117 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1118 for (int userId : mDirtyUsers) { 1119 mSettings.writePackageRestrictionsLPr(userId); 1120 } 1121 mDirtyUsers.clear(); 1122 } 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } break; 1125 case CHECK_PENDING_VERIFICATION: { 1126 final int verificationId = msg.arg1; 1127 final PackageVerificationState state = mPendingVerification.get(verificationId); 1128 1129 if ((state != null) && !state.timeoutExtended()) { 1130 final InstallArgs args = state.getInstallArgs(); 1131 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1132 1133 Slog.i(TAG, "Verification timed out for " + originUri); 1134 mPendingVerification.remove(verificationId); 1135 1136 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1137 1138 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1139 Slog.i(TAG, "Continuing with installation of " + originUri); 1140 state.setVerifierResponse(Binder.getCallingUid(), 1141 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1142 broadcastPackageVerified(verificationId, originUri, 1143 PackageManager.VERIFICATION_ALLOW, 1144 state.getInstallArgs().getUser()); 1145 try { 1146 ret = args.copyApk(mContainerService, true); 1147 } catch (RemoteException e) { 1148 Slog.e(TAG, "Could not contact the ContainerService"); 1149 } 1150 } else { 1151 broadcastPackageVerified(verificationId, originUri, 1152 PackageManager.VERIFICATION_REJECT, 1153 state.getInstallArgs().getUser()); 1154 } 1155 1156 processPendingInstall(args, ret); 1157 mHandler.sendEmptyMessage(MCS_UNBIND); 1158 } 1159 break; 1160 } 1161 case PACKAGE_VERIFIED: { 1162 final int verificationId = msg.arg1; 1163 1164 final PackageVerificationState state = mPendingVerification.get(verificationId); 1165 if (state == null) { 1166 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1167 break; 1168 } 1169 1170 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1171 1172 state.setVerifierResponse(response.callerUid, response.code); 1173 1174 if (state.isVerificationComplete()) { 1175 mPendingVerification.remove(verificationId); 1176 1177 final InstallArgs args = state.getInstallArgs(); 1178 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1179 1180 int ret; 1181 if (state.isInstallAllowed()) { 1182 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1183 broadcastPackageVerified(verificationId, originUri, 1184 response.code, state.getInstallArgs().getUser()); 1185 try { 1186 ret = args.copyApk(mContainerService, true); 1187 } catch (RemoteException e) { 1188 Slog.e(TAG, "Could not contact the ContainerService"); 1189 } 1190 } else { 1191 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1192 } 1193 1194 processPendingInstall(args, ret); 1195 1196 mHandler.sendEmptyMessage(MCS_UNBIND); 1197 } 1198 1199 break; 1200 } 1201 } 1202 } 1203 } 1204 1205 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1206 Bundle extras = null; 1207 switch (res.returnCode) { 1208 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1209 extras = new Bundle(); 1210 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1211 res.origPermission); 1212 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1213 res.origPackage); 1214 break; 1215 } 1216 } 1217 return extras; 1218 } 1219 1220 void scheduleWriteSettingsLocked() { 1221 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1222 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1223 } 1224 } 1225 1226 void scheduleWritePackageRestrictionsLocked(int userId) { 1227 if (!sUserManager.exists(userId)) return; 1228 mDirtyUsers.add(userId); 1229 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1230 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1231 } 1232 } 1233 1234 public static final PackageManagerService main(Context context, Installer installer, 1235 boolean factoryTest, boolean onlyCore) { 1236 PackageManagerService m = new PackageManagerService(context, installer, 1237 factoryTest, onlyCore); 1238 ServiceManager.addService("package", m); 1239 return m; 1240 } 1241 1242 static String[] splitString(String str, char sep) { 1243 int count = 1; 1244 int i = 0; 1245 while ((i=str.indexOf(sep, i)) >= 0) { 1246 count++; 1247 i++; 1248 } 1249 1250 String[] res = new String[count]; 1251 i=0; 1252 count = 0; 1253 int lastI=0; 1254 while ((i=str.indexOf(sep, i)) >= 0) { 1255 res[count] = str.substring(lastI, i); 1256 count++; 1257 i++; 1258 lastI = i; 1259 } 1260 res[count] = str.substring(lastI, str.length()); 1261 return res; 1262 } 1263 1264 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1265 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1266 Context.DISPLAY_SERVICE); 1267 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1268 } 1269 1270 public PackageManagerService(Context context, Installer installer, 1271 boolean factoryTest, boolean onlyCore) { 1272 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1273 SystemClock.uptimeMillis()); 1274 1275 if (mSdkVersion <= 0) { 1276 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1277 } 1278 1279 mContext = context; 1280 mFactoryTest = factoryTest; 1281 mOnlyCore = onlyCore; 1282 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1283 mMetrics = new DisplayMetrics(); 1284 mSettings = new Settings(context); 1285 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 1298 // TODO: add a property to control this? 1299 long dexOptLRUThresholdInMinutes; 1300 if (mLazyDexOpt) { 1301 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1302 } else { 1303 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1304 } 1305 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1306 1307 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1308 if (separateProcesses != null && separateProcesses.length() > 0) { 1309 if ("*".equals(separateProcesses)) { 1310 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1311 mSeparateProcesses = null; 1312 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1313 } else { 1314 mDefParseFlags = 0; 1315 mSeparateProcesses = separateProcesses.split(","); 1316 Slog.w(TAG, "Running with debug.separate_processes: " 1317 + separateProcesses); 1318 } 1319 } else { 1320 mDefParseFlags = 0; 1321 mSeparateProcesses = null; 1322 } 1323 1324 mInstaller = installer; 1325 1326 getDefaultDisplayMetrics(context, mMetrics); 1327 1328 SystemConfig systemConfig = SystemConfig.getInstance(); 1329 mGlobalGids = systemConfig.getGlobalGids(); 1330 mSystemPermissions = systemConfig.getSystemPermissions(); 1331 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1332 1333 synchronized (mInstallLock) { 1334 // writer 1335 synchronized (mPackages) { 1336 mHandlerThread = new ServiceThread(TAG, 1337 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1338 mHandlerThread.start(); 1339 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1340 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1341 1342 File dataDir = Environment.getDataDirectory(); 1343 mAppDataDir = new File(dataDir, "data"); 1344 mAppInstallDir = new File(dataDir, "app"); 1345 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1346 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1347 mUserAppDataDir = new File(dataDir, "user"); 1348 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1349 1350 sUserManager = new UserManagerService(context, this, 1351 mInstallLock, mPackages); 1352 1353 // Propagate permission configuration in to package manager. 1354 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1355 = systemConfig.getPermissions(); 1356 for (int i=0; i<permConfig.size(); i++) { 1357 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1358 BasePermission bp = mSettings.mPermissions.get(perm.name); 1359 if (bp == null) { 1360 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1361 mSettings.mPermissions.put(perm.name, bp); 1362 } 1363 if (perm.gids != null) { 1364 bp.gids = appendInts(bp.gids, perm.gids); 1365 } 1366 } 1367 1368 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1369 for (int i=0; i<libConfig.size(); i++) { 1370 mSharedLibraries.put(libConfig.keyAt(i), 1371 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1372 } 1373 1374 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1375 1376 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1377 mSdkVersion, mOnlyCore); 1378 1379 String customResolverActivity = Resources.getSystem().getString( 1380 R.string.config_customResolverActivity); 1381 if (TextUtils.isEmpty(customResolverActivity)) { 1382 customResolverActivity = null; 1383 } else { 1384 mCustomResolverComponentName = ComponentName.unflattenFromString( 1385 customResolverActivity); 1386 } 1387 1388 long startTime = SystemClock.uptimeMillis(); 1389 1390 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1391 startTime); 1392 1393 // Set flag to monitor and not change apk file paths when 1394 // scanning install directories. 1395 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1396 1397 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1398 1399 /** 1400 * Add everything in the in the boot class path to the 1401 * list of process files because dexopt will have been run 1402 * if necessary during zygote startup. 1403 */ 1404 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1405 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1406 1407 if (bootClassPath != null) { 1408 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1409 for (String element : bootClassPathElements) { 1410 alreadyDexOpted.add(element); 1411 } 1412 } else { 1413 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1414 } 1415 1416 if (systemServerClassPath != null) { 1417 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1418 for (String element : systemServerClassPathElements) { 1419 alreadyDexOpted.add(element); 1420 } 1421 } else { 1422 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1423 } 1424 1425 boolean didDexOptLibraryOrTool = false; 1426 1427 final List<String> allInstructionSets = getAllInstructionSets(); 1428 final String[] dexCodeInstructionSets = 1429 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1430 1431 /** 1432 * Ensure all external libraries have had dexopt run on them. 1433 */ 1434 if (mSharedLibraries.size() > 0) { 1435 // NOTE: For now, we're compiling these system "shared libraries" 1436 // (and framework jars) into all available architectures. It's possible 1437 // to compile them only when we come across an app that uses them (there's 1438 // already logic for that in scanPackageLI) but that adds some complexity. 1439 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1440 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1441 final String lib = libEntry.path; 1442 if (lib == null) { 1443 continue; 1444 } 1445 1446 try { 1447 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1448 dexCodeInstructionSet, 1449 false); 1450 if (dexoptRequired != DexFile.UP_TO_DATE) { 1451 alreadyDexOpted.add(lib); 1452 1453 // The list of "shared libraries" we have at this point is 1454 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1455 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1456 } else { 1457 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1458 } 1459 didDexOptLibraryOrTool = true; 1460 } 1461 } catch (FileNotFoundException e) { 1462 Slog.w(TAG, "Library not found: " + lib); 1463 } catch (IOException e) { 1464 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1465 + e.getMessage()); 1466 } 1467 } 1468 } 1469 } 1470 1471 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1472 1473 // Gross hack for now: we know this file doesn't contain any 1474 // code, so don't dexopt it to avoid the resulting log spew. 1475 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1476 1477 // Gross hack for now: we know this file is only part of 1478 // the boot class path for art, so don't dexopt it to 1479 // avoid the resulting log spew. 1480 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1481 1482 /** 1483 * And there are a number of commands implemented in Java, which 1484 * we currently need to do the dexopt on so that they can be 1485 * run from a non-root shell. 1486 */ 1487 String[] frameworkFiles = frameworkDir.list(); 1488 if (frameworkFiles != null) { 1489 // TODO: We could compile these only for the most preferred ABI. We should 1490 // first double check that the dex files for these commands are not referenced 1491 // by other system apps. 1492 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1493 for (int i=0; i<frameworkFiles.length; i++) { 1494 File libPath = new File(frameworkDir, frameworkFiles[i]); 1495 String path = libPath.getPath(); 1496 // Skip the file if we already did it. 1497 if (alreadyDexOpted.contains(path)) { 1498 continue; 1499 } 1500 // Skip the file if it is not a type we want to dexopt. 1501 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1502 continue; 1503 } 1504 try { 1505 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1506 dexCodeInstructionSet, 1507 false); 1508 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1509 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1510 didDexOptLibraryOrTool = true; 1511 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1512 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1513 didDexOptLibraryOrTool = true; 1514 } 1515 } catch (FileNotFoundException e) { 1516 Slog.w(TAG, "Jar not found: " + path); 1517 } catch (IOException e) { 1518 Slog.w(TAG, "Exception reading jar: " + path, e); 1519 } 1520 } 1521 } 1522 } 1523 1524 // Collect vendor overlay packages. 1525 // (Do this before scanning any apps.) 1526 // For security and version matching reason, only consider 1527 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1528 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1529 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1530 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1531 1532 // Find base frameworks (resource packages without code). 1533 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1534 | PackageParser.PARSE_IS_SYSTEM_DIR 1535 | PackageParser.PARSE_IS_PRIVILEGED, 1536 scanFlags | SCAN_NO_DEX, 0); 1537 1538 // Collected privileged system packages. 1539 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1540 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR 1542 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1543 1544 // Collect ordinary system packages. 1545 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1546 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1548 1549 // Collect all vendor packages. 1550 File vendorAppDir = new File("/vendor/app"); 1551 try { 1552 vendorAppDir = vendorAppDir.getCanonicalFile(); 1553 } catch (IOException e) { 1554 // failed to look up canonical path, continue with original one 1555 } 1556 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1557 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1558 1559 // Collect all OEM packages. 1560 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1561 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1562 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1563 1564 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1565 mInstaller.moveFiles(); 1566 1567 // Prune any system packages that no longer exist. 1568 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1569 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1570 if (!mOnlyCore) { 1571 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1572 while (psit.hasNext()) { 1573 PackageSetting ps = psit.next(); 1574 1575 /* 1576 * If this is not a system app, it can't be a 1577 * disable system app. 1578 */ 1579 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1580 continue; 1581 } 1582 1583 /* 1584 * If the package is scanned, it's not erased. 1585 */ 1586 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1587 if (scannedPkg != null) { 1588 /* 1589 * If the system app is both scanned and in the 1590 * disabled packages list, then it must have been 1591 * added via OTA. Remove it from the currently 1592 * scanned package so the previously user-installed 1593 * application can be scanned. 1594 */ 1595 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1596 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1597 + ps.name + "; removing system app. Last known codePath=" 1598 + ps.codePathString + ", installStatus=" + ps.installStatus 1599 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1600 + scannedPkg.mVersionCode); 1601 removePackageLI(ps, true); 1602 expectingBetter.put(ps.name, ps.codePath); 1603 } 1604 1605 continue; 1606 } 1607 1608 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1609 psit.remove(); 1610 logCriticalInfo(Log.WARN, "System package " + ps.name 1611 + " no longer exists; wiping its data"); 1612 removeDataDirsLI(ps.name); 1613 } else { 1614 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1615 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1616 possiblyDeletedUpdatedSystemApps.add(ps.name); 1617 } 1618 } 1619 } 1620 } 1621 1622 //look for any incomplete package installations 1623 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1624 //clean up list 1625 for(int i = 0; i < deletePkgsList.size(); i++) { 1626 //clean up here 1627 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1628 } 1629 //delete tmp files 1630 deleteTempPackageFiles(); 1631 1632 // Remove any shared userIDs that have no associated packages 1633 mSettings.pruneSharedUsersLPw(); 1634 1635 if (!mOnlyCore) { 1636 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1637 SystemClock.uptimeMillis()); 1638 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1639 1640 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1641 scanFlags, 0); 1642 1643 /** 1644 * Remove disable package settings for any updated system 1645 * apps that were removed via an OTA. If they're not a 1646 * previously-updated app, remove them completely. 1647 * Otherwise, just revoke their system-level permissions. 1648 */ 1649 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1650 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1651 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1652 1653 String msg; 1654 if (deletedPkg == null) { 1655 msg = "Updated system package " + deletedAppName 1656 + " no longer exists; wiping its data"; 1657 removeDataDirsLI(deletedAppName); 1658 } else { 1659 msg = "Updated system app + " + deletedAppName 1660 + " no longer present; removing system privileges for " 1661 + deletedAppName; 1662 1663 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1664 1665 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1666 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1667 } 1668 logCriticalInfo(Log.WARN, msg); 1669 } 1670 1671 /** 1672 * Make sure all system apps that we expected to appear on 1673 * the userdata partition actually showed up. If they never 1674 * appeared, crawl back and revive the system version. 1675 */ 1676 for (int i = 0; i < expectingBetter.size(); i++) { 1677 final String packageName = expectingBetter.keyAt(i); 1678 if (!mPackages.containsKey(packageName)) { 1679 final File scanFile = expectingBetter.valueAt(i); 1680 1681 logCriticalInfo(Log.WARN, "Expected better " + packageName 1682 + " but never showed up; reverting to system"); 1683 1684 final int reparseFlags; 1685 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1686 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1687 | PackageParser.PARSE_IS_SYSTEM_DIR 1688 | PackageParser.PARSE_IS_PRIVILEGED; 1689 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1690 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1691 | PackageParser.PARSE_IS_SYSTEM_DIR; 1692 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1693 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1694 | PackageParser.PARSE_IS_SYSTEM_DIR; 1695 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1696 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1697 | PackageParser.PARSE_IS_SYSTEM_DIR; 1698 } else { 1699 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1700 continue; 1701 } 1702 1703 mSettings.enableSystemPackageLPw(packageName); 1704 1705 try { 1706 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1707 } catch (PackageManagerException e) { 1708 Slog.e(TAG, "Failed to parse original system package: " 1709 + e.getMessage()); 1710 } 1711 } 1712 } 1713 } 1714 1715 // Now that we know all of the shared libraries, update all clients to have 1716 // the correct library paths. 1717 updateAllSharedLibrariesLPw(); 1718 1719 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1720 // NOTE: We ignore potential failures here during a system scan (like 1721 // the rest of the commands above) because there's precious little we 1722 // can do about it. A settings error is reported, though. 1723 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1724 false /* force dexopt */, false /* defer dexopt */); 1725 } 1726 1727 // Now that we know all the packages we are keeping, 1728 // read and update their last usage times. 1729 mPackageUsage.readLP(); 1730 1731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1732 SystemClock.uptimeMillis()); 1733 Slog.i(TAG, "Time to scan packages: " 1734 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1735 + " seconds"); 1736 1737 // If the platform SDK has changed since the last time we booted, 1738 // we need to re-grant app permission to catch any new ones that 1739 // appear. This is really a hack, and means that apps can in some 1740 // cases get permissions that the user didn't initially explicitly 1741 // allow... it would be nice to have some better way to handle 1742 // this situation. 1743 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1744 != mSdkVersion; 1745 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1746 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1747 + "; regranting permissions for internal storage"); 1748 mSettings.mInternalSdkPlatform = mSdkVersion; 1749 1750 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1751 | (regrantPermissions 1752 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1753 : 0)); 1754 1755 // If this is the first boot, and it is a normal boot, then 1756 // we need to initialize the default preferred apps. 1757 if (!mRestoredSettings && !onlyCore) { 1758 mSettings.readDefaultPreferredAppsLPw(this, 0); 1759 } 1760 1761 // If this is first boot after an OTA, and a normal boot, then 1762 // we need to clear code cache directories. 1763 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1764 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1765 for (String pkgName : mSettings.mPackages.keySet()) { 1766 deleteCodeCacheDirsLI(pkgName); 1767 } 1768 mSettings.mFingerprint = Build.FINGERPRINT; 1769 } 1770 1771 // All the changes are done during package scanning. 1772 mSettings.updateInternalDatabaseVersion(); 1773 1774 // can downgrade to reader 1775 mSettings.writeLPr(); 1776 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1778 SystemClock.uptimeMillis()); 1779 1780 1781 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1782 } // synchronized (mPackages) 1783 } // synchronized (mInstallLock) 1784 1785 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1786 1787 // Now after opening every single application zip, make sure they 1788 // are all flushed. Not really needed, but keeps things nice and 1789 // tidy. 1790 Runtime.getRuntime().gc(); 1791 } 1792 1793 @Override 1794 public boolean isFirstBoot() { 1795 return !mRestoredSettings; 1796 } 1797 1798 @Override 1799 public boolean isOnlyCoreApps() { 1800 return mOnlyCore; 1801 } 1802 1803 private String getRequiredVerifierLPr() { 1804 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1805 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1806 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1807 1808 String requiredVerifier = null; 1809 1810 final int N = receivers.size(); 1811 for (int i = 0; i < N; i++) { 1812 final ResolveInfo info = receivers.get(i); 1813 1814 if (info.activityInfo == null) { 1815 continue; 1816 } 1817 1818 final String packageName = info.activityInfo.packageName; 1819 1820 final PackageSetting ps = mSettings.mPackages.get(packageName); 1821 if (ps == null) { 1822 continue; 1823 } 1824 1825 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1826 if (!gp.grantedPermissions 1827 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1828 continue; 1829 } 1830 1831 if (requiredVerifier != null) { 1832 throw new RuntimeException("There can be only one required verifier"); 1833 } 1834 1835 requiredVerifier = packageName; 1836 } 1837 1838 return requiredVerifier; 1839 } 1840 1841 @Override 1842 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1843 throws RemoteException { 1844 try { 1845 return super.onTransact(code, data, reply, flags); 1846 } catch (RuntimeException e) { 1847 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1848 Slog.wtf(TAG, "Package Manager Crash", e); 1849 } 1850 throw e; 1851 } 1852 } 1853 1854 void cleanupInstallFailedPackage(PackageSetting ps) { 1855 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1856 1857 removeDataDirsLI(ps.name); 1858 if (ps.codePath != null) { 1859 if (ps.codePath.isDirectory()) { 1860 FileUtils.deleteContents(ps.codePath); 1861 } 1862 ps.codePath.delete(); 1863 } 1864 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1865 if (ps.resourcePath.isDirectory()) { 1866 FileUtils.deleteContents(ps.resourcePath); 1867 } 1868 ps.resourcePath.delete(); 1869 } 1870 mSettings.removePackageLPw(ps.name); 1871 } 1872 1873 static int[] appendInts(int[] cur, int[] add) { 1874 if (add == null) return cur; 1875 if (cur == null) return add; 1876 final int N = add.length; 1877 for (int i=0; i<N; i++) { 1878 cur = appendInt(cur, add[i]); 1879 } 1880 return cur; 1881 } 1882 1883 static int[] removeInts(int[] cur, int[] rem) { 1884 if (rem == null) return cur; 1885 if (cur == null) return cur; 1886 final int N = rem.length; 1887 for (int i=0; i<N; i++) { 1888 cur = removeInt(cur, rem[i]); 1889 } 1890 return cur; 1891 } 1892 1893 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1894 if (!sUserManager.exists(userId)) return null; 1895 final PackageSetting ps = (PackageSetting) p.mExtras; 1896 if (ps == null) { 1897 return null; 1898 } 1899 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1900 final PackageUserState state = ps.readUserState(userId); 1901 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1902 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1903 state, userId); 1904 } 1905 1906 @Override 1907 public boolean isPackageAvailable(String packageName, int userId) { 1908 if (!sUserManager.exists(userId)) return false; 1909 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1910 synchronized (mPackages) { 1911 PackageParser.Package p = mPackages.get(packageName); 1912 if (p != null) { 1913 final PackageSetting ps = (PackageSetting) p.mExtras; 1914 if (ps != null) { 1915 final PackageUserState state = ps.readUserState(userId); 1916 if (state != null) { 1917 return PackageParser.isAvailable(state); 1918 } 1919 } 1920 } 1921 } 1922 return false; 1923 } 1924 1925 @Override 1926 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1927 if (!sUserManager.exists(userId)) return null; 1928 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1929 // reader 1930 synchronized (mPackages) { 1931 PackageParser.Package p = mPackages.get(packageName); 1932 if (DEBUG_PACKAGE_INFO) 1933 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1934 if (p != null) { 1935 return generatePackageInfo(p, flags, userId); 1936 } 1937 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1938 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1939 } 1940 } 1941 return null; 1942 } 1943 1944 @Override 1945 public String[] currentToCanonicalPackageNames(String[] names) { 1946 String[] out = new String[names.length]; 1947 // reader 1948 synchronized (mPackages) { 1949 for (int i=names.length-1; i>=0; i--) { 1950 PackageSetting ps = mSettings.mPackages.get(names[i]); 1951 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1952 } 1953 } 1954 return out; 1955 } 1956 1957 @Override 1958 public String[] canonicalToCurrentPackageNames(String[] names) { 1959 String[] out = new String[names.length]; 1960 // reader 1961 synchronized (mPackages) { 1962 for (int i=names.length-1; i>=0; i--) { 1963 String cur = mSettings.mRenamedPackages.get(names[i]); 1964 out[i] = cur != null ? cur : names[i]; 1965 } 1966 } 1967 return out; 1968 } 1969 1970 @Override 1971 public int getPackageUid(String packageName, int userId) { 1972 if (!sUserManager.exists(userId)) return -1; 1973 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1974 // reader 1975 synchronized (mPackages) { 1976 PackageParser.Package p = mPackages.get(packageName); 1977 if(p != null) { 1978 return UserHandle.getUid(userId, p.applicationInfo.uid); 1979 } 1980 PackageSetting ps = mSettings.mPackages.get(packageName); 1981 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1982 return -1; 1983 } 1984 p = ps.pkg; 1985 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1986 } 1987 } 1988 1989 @Override 1990 public int[] getPackageGids(String packageName) { 1991 // reader 1992 synchronized (mPackages) { 1993 PackageParser.Package p = mPackages.get(packageName); 1994 if (DEBUG_PACKAGE_INFO) 1995 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1996 if (p != null) { 1997 final PackageSetting ps = (PackageSetting)p.mExtras; 1998 return ps.getGids(); 1999 } 2000 } 2001 // stupid thing to indicate an error. 2002 return new int[0]; 2003 } 2004 2005 static final PermissionInfo generatePermissionInfo( 2006 BasePermission bp, int flags) { 2007 if (bp.perm != null) { 2008 return PackageParser.generatePermissionInfo(bp.perm, flags); 2009 } 2010 PermissionInfo pi = new PermissionInfo(); 2011 pi.name = bp.name; 2012 pi.packageName = bp.sourcePackage; 2013 pi.nonLocalizedLabel = bp.name; 2014 pi.protectionLevel = bp.protectionLevel; 2015 return pi; 2016 } 2017 2018 @Override 2019 public PermissionInfo getPermissionInfo(String name, int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 final BasePermission p = mSettings.mPermissions.get(name); 2023 if (p != null) { 2024 return generatePermissionInfo(p, flags); 2025 } 2026 return null; 2027 } 2028 } 2029 2030 @Override 2031 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2032 // reader 2033 synchronized (mPackages) { 2034 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2035 for (BasePermission p : mSettings.mPermissions.values()) { 2036 if (group == null) { 2037 if (p.perm == null || p.perm.info.group == null) { 2038 out.add(generatePermissionInfo(p, flags)); 2039 } 2040 } else { 2041 if (p.perm != null && group.equals(p.perm.info.group)) { 2042 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2043 } 2044 } 2045 } 2046 2047 if (out.size() > 0) { 2048 return out; 2049 } 2050 return mPermissionGroups.containsKey(group) ? out : null; 2051 } 2052 } 2053 2054 @Override 2055 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2056 // reader 2057 synchronized (mPackages) { 2058 return PackageParser.generatePermissionGroupInfo( 2059 mPermissionGroups.get(name), flags); 2060 } 2061 } 2062 2063 @Override 2064 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2065 // reader 2066 synchronized (mPackages) { 2067 final int N = mPermissionGroups.size(); 2068 ArrayList<PermissionGroupInfo> out 2069 = new ArrayList<PermissionGroupInfo>(N); 2070 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2071 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2072 } 2073 return out; 2074 } 2075 } 2076 2077 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2078 int userId) { 2079 if (!sUserManager.exists(userId)) return null; 2080 PackageSetting ps = mSettings.mPackages.get(packageName); 2081 if (ps != null) { 2082 if (ps.pkg == null) { 2083 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2084 flags, userId); 2085 if (pInfo != null) { 2086 return pInfo.applicationInfo; 2087 } 2088 return null; 2089 } 2090 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2091 ps.readUserState(userId), userId); 2092 } 2093 return null; 2094 } 2095 2096 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2097 int userId) { 2098 if (!sUserManager.exists(userId)) return null; 2099 PackageSetting ps = mSettings.mPackages.get(packageName); 2100 if (ps != null) { 2101 PackageParser.Package pkg = ps.pkg; 2102 if (pkg == null) { 2103 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2104 return null; 2105 } 2106 // Only data remains, so we aren't worried about code paths 2107 pkg = new PackageParser.Package(packageName); 2108 pkg.applicationInfo.packageName = packageName; 2109 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2110 pkg.applicationInfo.dataDir = 2111 getDataPathForPackage(packageName, 0).getPath(); 2112 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2113 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2114 } 2115 return generatePackageInfo(pkg, flags, userId); 2116 } 2117 return null; 2118 } 2119 2120 @Override 2121 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2122 if (!sUserManager.exists(userId)) return null; 2123 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2124 // writer 2125 synchronized (mPackages) { 2126 PackageParser.Package p = mPackages.get(packageName); 2127 if (DEBUG_PACKAGE_INFO) Log.v( 2128 TAG, "getApplicationInfo " + packageName 2129 + ": " + p); 2130 if (p != null) { 2131 PackageSetting ps = mSettings.mPackages.get(packageName); 2132 if (ps == null) return null; 2133 // Note: isEnabledLP() does not apply here - always return info 2134 return PackageParser.generateApplicationInfo( 2135 p, flags, ps.readUserState(userId), userId); 2136 } 2137 if ("android".equals(packageName)||"system".equals(packageName)) { 2138 return mAndroidApplication; 2139 } 2140 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2141 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2142 } 2143 } 2144 return null; 2145 } 2146 2147 2148 @Override 2149 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2150 mContext.enforceCallingOrSelfPermission( 2151 android.Manifest.permission.CLEAR_APP_CACHE, null); 2152 // Queue up an async operation since clearing cache may take a little while. 2153 mHandler.post(new Runnable() { 2154 public void run() { 2155 mHandler.removeCallbacks(this); 2156 int retCode = -1; 2157 synchronized (mInstallLock) { 2158 retCode = mInstaller.freeCache(freeStorageSize); 2159 if (retCode < 0) { 2160 Slog.w(TAG, "Couldn't clear application caches"); 2161 } 2162 } 2163 if (observer != null) { 2164 try { 2165 observer.onRemoveCompleted(null, (retCode >= 0)); 2166 } catch (RemoteException e) { 2167 Slog.w(TAG, "RemoveException when invoking call back"); 2168 } 2169 } 2170 } 2171 }); 2172 } 2173 2174 @Override 2175 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2176 mContext.enforceCallingOrSelfPermission( 2177 android.Manifest.permission.CLEAR_APP_CACHE, null); 2178 // Queue up an async operation since clearing cache may take a little while. 2179 mHandler.post(new Runnable() { 2180 public void run() { 2181 mHandler.removeCallbacks(this); 2182 int retCode = -1; 2183 synchronized (mInstallLock) { 2184 retCode = mInstaller.freeCache(freeStorageSize); 2185 if (retCode < 0) { 2186 Slog.w(TAG, "Couldn't clear application caches"); 2187 } 2188 } 2189 if(pi != null) { 2190 try { 2191 // Callback via pending intent 2192 int code = (retCode >= 0) ? 1 : 0; 2193 pi.sendIntent(null, code, null, 2194 null, null); 2195 } catch (SendIntentException e1) { 2196 Slog.i(TAG, "Failed to send pending intent"); 2197 } 2198 } 2199 } 2200 }); 2201 } 2202 2203 void freeStorage(long freeStorageSize) throws IOException { 2204 synchronized (mInstallLock) { 2205 if (mInstaller.freeCache(freeStorageSize) < 0) { 2206 throw new IOException("Failed to free enough space"); 2207 } 2208 } 2209 } 2210 2211 @Override 2212 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2213 if (!sUserManager.exists(userId)) return null; 2214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2215 synchronized (mPackages) { 2216 PackageParser.Activity a = mActivities.mActivities.get(component); 2217 2218 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2219 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2220 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2221 if (ps == null) return null; 2222 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2223 userId); 2224 } 2225 if (mResolveComponentName.equals(component)) { 2226 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2227 new PackageUserState(), userId); 2228 } 2229 } 2230 return null; 2231 } 2232 2233 @Override 2234 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2235 String resolvedType) { 2236 synchronized (mPackages) { 2237 PackageParser.Activity a = mActivities.mActivities.get(component); 2238 if (a == null) { 2239 return false; 2240 } 2241 for (int i=0; i<a.intents.size(); i++) { 2242 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2243 intent.getData(), intent.getCategories(), TAG) >= 0) { 2244 return true; 2245 } 2246 } 2247 return false; 2248 } 2249 } 2250 2251 @Override 2252 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2253 if (!sUserManager.exists(userId)) return null; 2254 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2255 synchronized (mPackages) { 2256 PackageParser.Activity a = mReceivers.mActivities.get(component); 2257 if (DEBUG_PACKAGE_INFO) Log.v( 2258 TAG, "getReceiverInfo " + component + ": " + a); 2259 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2260 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2261 if (ps == null) return null; 2262 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2263 userId); 2264 } 2265 } 2266 return null; 2267 } 2268 2269 @Override 2270 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2271 if (!sUserManager.exists(userId)) return null; 2272 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2273 synchronized (mPackages) { 2274 PackageParser.Service s = mServices.mServices.get(component); 2275 if (DEBUG_PACKAGE_INFO) Log.v( 2276 TAG, "getServiceInfo " + component + ": " + s); 2277 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2278 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2279 if (ps == null) return null; 2280 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2281 userId); 2282 } 2283 } 2284 return null; 2285 } 2286 2287 @Override 2288 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2289 if (!sUserManager.exists(userId)) return null; 2290 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2291 synchronized (mPackages) { 2292 PackageParser.Provider p = mProviders.mProviders.get(component); 2293 if (DEBUG_PACKAGE_INFO) Log.v( 2294 TAG, "getProviderInfo " + component + ": " + p); 2295 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2296 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2297 if (ps == null) return null; 2298 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2299 userId); 2300 } 2301 } 2302 return null; 2303 } 2304 2305 @Override 2306 public String[] getSystemSharedLibraryNames() { 2307 Set<String> libSet; 2308 synchronized (mPackages) { 2309 libSet = mSharedLibraries.keySet(); 2310 int size = libSet.size(); 2311 if (size > 0) { 2312 String[] libs = new String[size]; 2313 libSet.toArray(libs); 2314 return libs; 2315 } 2316 } 2317 return null; 2318 } 2319 2320 @Override 2321 public FeatureInfo[] getSystemAvailableFeatures() { 2322 Collection<FeatureInfo> featSet; 2323 synchronized (mPackages) { 2324 featSet = mAvailableFeatures.values(); 2325 int size = featSet.size(); 2326 if (size > 0) { 2327 FeatureInfo[] features = new FeatureInfo[size+1]; 2328 featSet.toArray(features); 2329 FeatureInfo fi = new FeatureInfo(); 2330 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2331 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2332 features[size] = fi; 2333 return features; 2334 } 2335 } 2336 return null; 2337 } 2338 2339 @Override 2340 public boolean hasSystemFeature(String name) { 2341 synchronized (mPackages) { 2342 return mAvailableFeatures.containsKey(name); 2343 } 2344 } 2345 2346 private void checkValidCaller(int uid, int userId) { 2347 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2348 return; 2349 2350 throw new SecurityException("Caller uid=" + uid 2351 + " is not privileged to communicate with user=" + userId); 2352 } 2353 2354 @Override 2355 public int checkPermission(String permName, String pkgName) { 2356 synchronized (mPackages) { 2357 PackageParser.Package p = mPackages.get(pkgName); 2358 if (p != null && p.mExtras != null) { 2359 PackageSetting ps = (PackageSetting)p.mExtras; 2360 if (ps.sharedUser != null) { 2361 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2362 return PackageManager.PERMISSION_GRANTED; 2363 } 2364 } else if (ps.grantedPermissions.contains(permName)) { 2365 return PackageManager.PERMISSION_GRANTED; 2366 } 2367 } 2368 } 2369 return PackageManager.PERMISSION_DENIED; 2370 } 2371 2372 @Override 2373 public int checkUidPermission(String permName, int uid) { 2374 synchronized (mPackages) { 2375 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2376 if (obj != null) { 2377 GrantedPermissions gp = (GrantedPermissions)obj; 2378 if (gp.grantedPermissions.contains(permName)) { 2379 return PackageManager.PERMISSION_GRANTED; 2380 } 2381 } else { 2382 ArraySet<String> perms = mSystemPermissions.get(uid); 2383 if (perms != null && perms.contains(permName)) { 2384 return PackageManager.PERMISSION_GRANTED; 2385 } 2386 } 2387 } 2388 return PackageManager.PERMISSION_DENIED; 2389 } 2390 2391 /** 2392 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2393 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2394 * @param checkShell TODO(yamasani): 2395 * @param message the message to log on security exception 2396 */ 2397 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2398 boolean checkShell, String message) { 2399 if (userId < 0) { 2400 throw new IllegalArgumentException("Invalid userId " + userId); 2401 } 2402 if (checkShell) { 2403 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2404 } 2405 if (userId == UserHandle.getUserId(callingUid)) return; 2406 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2407 if (requireFullPermission) { 2408 mContext.enforceCallingOrSelfPermission( 2409 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2410 } else { 2411 try { 2412 mContext.enforceCallingOrSelfPermission( 2413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2414 } catch (SecurityException se) { 2415 mContext.enforceCallingOrSelfPermission( 2416 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2417 } 2418 } 2419 } 2420 } 2421 2422 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2423 if (callingUid == Process.SHELL_UID) { 2424 if (userHandle >= 0 2425 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2426 throw new SecurityException("Shell does not have permission to access user " 2427 + userHandle); 2428 } else if (userHandle < 0) { 2429 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2430 + Debug.getCallers(3)); 2431 } 2432 } 2433 } 2434 2435 private BasePermission findPermissionTreeLP(String permName) { 2436 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2437 if (permName.startsWith(bp.name) && 2438 permName.length() > bp.name.length() && 2439 permName.charAt(bp.name.length()) == '.') { 2440 return bp; 2441 } 2442 } 2443 return null; 2444 } 2445 2446 private BasePermission checkPermissionTreeLP(String permName) { 2447 if (permName != null) { 2448 BasePermission bp = findPermissionTreeLP(permName); 2449 if (bp != null) { 2450 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2451 return bp; 2452 } 2453 throw new SecurityException("Calling uid " 2454 + Binder.getCallingUid() 2455 + " is not allowed to add to permission tree " 2456 + bp.name + " owned by uid " + bp.uid); 2457 } 2458 } 2459 throw new SecurityException("No permission tree found for " + permName); 2460 } 2461 2462 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2463 if (s1 == null) { 2464 return s2 == null; 2465 } 2466 if (s2 == null) { 2467 return false; 2468 } 2469 if (s1.getClass() != s2.getClass()) { 2470 return false; 2471 } 2472 return s1.equals(s2); 2473 } 2474 2475 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2476 if (pi1.icon != pi2.icon) return false; 2477 if (pi1.logo != pi2.logo) return false; 2478 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2479 if (!compareStrings(pi1.name, pi2.name)) return false; 2480 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2481 // We'll take care of setting this one. 2482 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2483 // These are not currently stored in settings. 2484 //if (!compareStrings(pi1.group, pi2.group)) return false; 2485 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2486 //if (pi1.labelRes != pi2.labelRes) return false; 2487 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2488 return true; 2489 } 2490 2491 int permissionInfoFootprint(PermissionInfo info) { 2492 int size = info.name.length(); 2493 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2494 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2495 return size; 2496 } 2497 2498 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2499 int size = 0; 2500 for (BasePermission perm : mSettings.mPermissions.values()) { 2501 if (perm.uid == tree.uid) { 2502 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2503 } 2504 } 2505 return size; 2506 } 2507 2508 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2509 // We calculate the max size of permissions defined by this uid and throw 2510 // if that plus the size of 'info' would exceed our stated maximum. 2511 if (tree.uid != Process.SYSTEM_UID) { 2512 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2513 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2514 throw new SecurityException("Permission tree size cap exceeded"); 2515 } 2516 } 2517 } 2518 2519 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2520 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2521 throw new SecurityException("Label must be specified in permission"); 2522 } 2523 BasePermission tree = checkPermissionTreeLP(info.name); 2524 BasePermission bp = mSettings.mPermissions.get(info.name); 2525 boolean added = bp == null; 2526 boolean changed = true; 2527 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2528 if (added) { 2529 enforcePermissionCapLocked(info, tree); 2530 bp = new BasePermission(info.name, tree.sourcePackage, 2531 BasePermission.TYPE_DYNAMIC); 2532 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2533 throw new SecurityException( 2534 "Not allowed to modify non-dynamic permission " 2535 + info.name); 2536 } else { 2537 if (bp.protectionLevel == fixedLevel 2538 && bp.perm.owner.equals(tree.perm.owner) 2539 && bp.uid == tree.uid 2540 && comparePermissionInfos(bp.perm.info, info)) { 2541 changed = false; 2542 } 2543 } 2544 bp.protectionLevel = fixedLevel; 2545 info = new PermissionInfo(info); 2546 info.protectionLevel = fixedLevel; 2547 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2548 bp.perm.info.packageName = tree.perm.info.packageName; 2549 bp.uid = tree.uid; 2550 if (added) { 2551 mSettings.mPermissions.put(info.name, bp); 2552 } 2553 if (changed) { 2554 if (!async) { 2555 mSettings.writeLPr(); 2556 } else { 2557 scheduleWriteSettingsLocked(); 2558 } 2559 } 2560 return added; 2561 } 2562 2563 @Override 2564 public boolean addPermission(PermissionInfo info) { 2565 synchronized (mPackages) { 2566 return addPermissionLocked(info, false); 2567 } 2568 } 2569 2570 @Override 2571 public boolean addPermissionAsync(PermissionInfo info) { 2572 synchronized (mPackages) { 2573 return addPermissionLocked(info, true); 2574 } 2575 } 2576 2577 @Override 2578 public void removePermission(String name) { 2579 synchronized (mPackages) { 2580 checkPermissionTreeLP(name); 2581 BasePermission bp = mSettings.mPermissions.get(name); 2582 if (bp != null) { 2583 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2584 throw new SecurityException( 2585 "Not allowed to modify non-dynamic permission " 2586 + name); 2587 } 2588 mSettings.mPermissions.remove(name); 2589 mSettings.writeLPr(); 2590 } 2591 } 2592 } 2593 2594 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2595 int index = pkg.requestedPermissions.indexOf(bp.name); 2596 if (index == -1) { 2597 throw new SecurityException("Package " + pkg.packageName 2598 + " has not requested permission " + bp.name); 2599 } 2600 boolean isNormal = 2601 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2602 == PermissionInfo.PROTECTION_NORMAL); 2603 boolean isDangerous = 2604 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2605 == PermissionInfo.PROTECTION_DANGEROUS); 2606 boolean isDevelopment = 2607 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2608 2609 if (!isNormal && !isDangerous && !isDevelopment) { 2610 throw new SecurityException("Permission " + bp.name 2611 + " is not a changeable permission type"); 2612 } 2613 2614 if (isNormal || isDangerous) { 2615 if (pkg.requestedPermissionsRequired.get(index)) { 2616 throw new SecurityException("Can't change " + bp.name 2617 + ". It is required by the application"); 2618 } 2619 } 2620 } 2621 2622 @Override 2623 public void grantPermission(String packageName, String permissionName) { 2624 mContext.enforceCallingOrSelfPermission( 2625 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2626 synchronized (mPackages) { 2627 final PackageParser.Package pkg = mPackages.get(packageName); 2628 if (pkg == null) { 2629 throw new IllegalArgumentException("Unknown package: " + packageName); 2630 } 2631 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2632 if (bp == null) { 2633 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2634 } 2635 2636 checkGrantRevokePermissions(pkg, bp); 2637 2638 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2639 if (ps == null) { 2640 return; 2641 } 2642 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2643 if (gp.grantedPermissions.add(permissionName)) { 2644 if (ps.haveGids) { 2645 gp.gids = appendInts(gp.gids, bp.gids); 2646 } 2647 mSettings.writeLPr(); 2648 } 2649 } 2650 } 2651 2652 @Override 2653 public void revokePermission(String packageName, String permissionName) { 2654 int changedAppId = -1; 2655 2656 synchronized (mPackages) { 2657 final PackageParser.Package pkg = mPackages.get(packageName); 2658 if (pkg == null) { 2659 throw new IllegalArgumentException("Unknown package: " + packageName); 2660 } 2661 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2662 mContext.enforceCallingOrSelfPermission( 2663 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2664 } 2665 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2666 if (bp == null) { 2667 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2668 } 2669 2670 checkGrantRevokePermissions(pkg, bp); 2671 2672 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2673 if (ps == null) { 2674 return; 2675 } 2676 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2677 if (gp.grantedPermissions.remove(permissionName)) { 2678 gp.grantedPermissions.remove(permissionName); 2679 if (ps.haveGids) { 2680 gp.gids = removeInts(gp.gids, bp.gids); 2681 } 2682 mSettings.writeLPr(); 2683 changedAppId = ps.appId; 2684 } 2685 } 2686 2687 if (changedAppId >= 0) { 2688 // We changed the perm on someone, kill its processes. 2689 IActivityManager am = ActivityManagerNative.getDefault(); 2690 if (am != null) { 2691 final int callingUserId = UserHandle.getCallingUserId(); 2692 final long ident = Binder.clearCallingIdentity(); 2693 try { 2694 //XXX we should only revoke for the calling user's app permissions, 2695 // but for now we impact all users. 2696 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2697 // "revoke " + permissionName); 2698 int[] users = sUserManager.getUserIds(); 2699 for (int user : users) { 2700 am.killUid(UserHandle.getUid(user, changedAppId), 2701 "revoke " + permissionName); 2702 } 2703 } catch (RemoteException e) { 2704 } finally { 2705 Binder.restoreCallingIdentity(ident); 2706 } 2707 } 2708 } 2709 } 2710 2711 @Override 2712 public boolean isProtectedBroadcast(String actionName) { 2713 synchronized (mPackages) { 2714 return mProtectedBroadcasts.contains(actionName); 2715 } 2716 } 2717 2718 @Override 2719 public int checkSignatures(String pkg1, String pkg2) { 2720 synchronized (mPackages) { 2721 final PackageParser.Package p1 = mPackages.get(pkg1); 2722 final PackageParser.Package p2 = mPackages.get(pkg2); 2723 if (p1 == null || p1.mExtras == null 2724 || p2 == null || p2.mExtras == null) { 2725 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2726 } 2727 return compareSignatures(p1.mSignatures, p2.mSignatures); 2728 } 2729 } 2730 2731 @Override 2732 public int checkUidSignatures(int uid1, int uid2) { 2733 // Map to base uids. 2734 uid1 = UserHandle.getAppId(uid1); 2735 uid2 = UserHandle.getAppId(uid2); 2736 // reader 2737 synchronized (mPackages) { 2738 Signature[] s1; 2739 Signature[] s2; 2740 Object obj = mSettings.getUserIdLPr(uid1); 2741 if (obj != null) { 2742 if (obj instanceof SharedUserSetting) { 2743 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2744 } else if (obj instanceof PackageSetting) { 2745 s1 = ((PackageSetting)obj).signatures.mSignatures; 2746 } else { 2747 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2748 } 2749 } else { 2750 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2751 } 2752 obj = mSettings.getUserIdLPr(uid2); 2753 if (obj != null) { 2754 if (obj instanceof SharedUserSetting) { 2755 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2756 } else if (obj instanceof PackageSetting) { 2757 s2 = ((PackageSetting)obj).signatures.mSignatures; 2758 } else { 2759 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2760 } 2761 } else { 2762 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2763 } 2764 return compareSignatures(s1, s2); 2765 } 2766 } 2767 2768 /** 2769 * Compares two sets of signatures. Returns: 2770 * <br /> 2771 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2772 * <br /> 2773 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2774 * <br /> 2775 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2776 * <br /> 2777 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2778 * <br /> 2779 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2780 */ 2781 static int compareSignatures(Signature[] s1, Signature[] s2) { 2782 if (s1 == null) { 2783 return s2 == null 2784 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2785 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2786 } 2787 2788 if (s2 == null) { 2789 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2790 } 2791 2792 if (s1.length != s2.length) { 2793 return PackageManager.SIGNATURE_NO_MATCH; 2794 } 2795 2796 // Since both signature sets are of size 1, we can compare without HashSets. 2797 if (s1.length == 1) { 2798 return s1[0].equals(s2[0]) ? 2799 PackageManager.SIGNATURE_MATCH : 2800 PackageManager.SIGNATURE_NO_MATCH; 2801 } 2802 2803 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2804 for (Signature sig : s1) { 2805 set1.add(sig); 2806 } 2807 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2808 for (Signature sig : s2) { 2809 set2.add(sig); 2810 } 2811 // Make sure s2 contains all signatures in s1. 2812 if (set1.equals(set2)) { 2813 return PackageManager.SIGNATURE_MATCH; 2814 } 2815 return PackageManager.SIGNATURE_NO_MATCH; 2816 } 2817 2818 /** 2819 * If the database version for this type of package (internal storage or 2820 * external storage) is less than the version where package signatures 2821 * were updated, return true. 2822 */ 2823 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2824 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2825 DatabaseVersion.SIGNATURE_END_ENTITY)) 2826 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2827 DatabaseVersion.SIGNATURE_END_ENTITY)); 2828 } 2829 2830 /** 2831 * Used for backward compatibility to make sure any packages with 2832 * certificate chains get upgraded to the new style. {@code existingSigs} 2833 * will be in the old format (since they were stored on disk from before the 2834 * system upgrade) and {@code scannedSigs} will be in the newer format. 2835 */ 2836 private int compareSignaturesCompat(PackageSignatures existingSigs, 2837 PackageParser.Package scannedPkg) { 2838 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2839 return PackageManager.SIGNATURE_NO_MATCH; 2840 } 2841 2842 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2843 for (Signature sig : existingSigs.mSignatures) { 2844 existingSet.add(sig); 2845 } 2846 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2847 for (Signature sig : scannedPkg.mSignatures) { 2848 try { 2849 Signature[] chainSignatures = sig.getChainSignatures(); 2850 for (Signature chainSig : chainSignatures) { 2851 scannedCompatSet.add(chainSig); 2852 } 2853 } catch (CertificateEncodingException e) { 2854 scannedCompatSet.add(sig); 2855 } 2856 } 2857 /* 2858 * Make sure the expanded scanned set contains all signatures in the 2859 * existing one. 2860 */ 2861 if (scannedCompatSet.equals(existingSet)) { 2862 // Migrate the old signatures to the new scheme. 2863 existingSigs.assignSignatures(scannedPkg.mSignatures); 2864 // The new KeySets will be re-added later in the scanning process. 2865 synchronized (mPackages) { 2866 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2867 } 2868 return PackageManager.SIGNATURE_MATCH; 2869 } 2870 return PackageManager.SIGNATURE_NO_MATCH; 2871 } 2872 2873 @Override 2874 public String[] getPackagesForUid(int uid) { 2875 uid = UserHandle.getAppId(uid); 2876 // reader 2877 synchronized (mPackages) { 2878 Object obj = mSettings.getUserIdLPr(uid); 2879 if (obj instanceof SharedUserSetting) { 2880 final SharedUserSetting sus = (SharedUserSetting) obj; 2881 final int N = sus.packages.size(); 2882 final String[] res = new String[N]; 2883 final Iterator<PackageSetting> it = sus.packages.iterator(); 2884 int i = 0; 2885 while (it.hasNext()) { 2886 res[i++] = it.next().name; 2887 } 2888 return res; 2889 } else if (obj instanceof PackageSetting) { 2890 final PackageSetting ps = (PackageSetting) obj; 2891 return new String[] { ps.name }; 2892 } 2893 } 2894 return null; 2895 } 2896 2897 @Override 2898 public String getNameForUid(int uid) { 2899 // reader 2900 synchronized (mPackages) { 2901 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2902 if (obj instanceof SharedUserSetting) { 2903 final SharedUserSetting sus = (SharedUserSetting) obj; 2904 return sus.name + ":" + sus.userId; 2905 } else if (obj instanceof PackageSetting) { 2906 final PackageSetting ps = (PackageSetting) obj; 2907 return ps.name; 2908 } 2909 } 2910 return null; 2911 } 2912 2913 @Override 2914 public int getUidForSharedUser(String sharedUserName) { 2915 if(sharedUserName == null) { 2916 return -1; 2917 } 2918 // reader 2919 synchronized (mPackages) { 2920 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2921 if (suid == null) { 2922 return -1; 2923 } 2924 return suid.userId; 2925 } 2926 } 2927 2928 @Override 2929 public int getFlagsForUid(int uid) { 2930 synchronized (mPackages) { 2931 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2932 if (obj instanceof SharedUserSetting) { 2933 final SharedUserSetting sus = (SharedUserSetting) obj; 2934 return sus.pkgFlags; 2935 } else if (obj instanceof PackageSetting) { 2936 final PackageSetting ps = (PackageSetting) obj; 2937 return ps.pkgFlags; 2938 } 2939 } 2940 return 0; 2941 } 2942 2943 @Override 2944 public boolean isUidPrivileged(int uid) { 2945 uid = UserHandle.getAppId(uid); 2946 // reader 2947 synchronized (mPackages) { 2948 Object obj = mSettings.getUserIdLPr(uid); 2949 if (obj instanceof SharedUserSetting) { 2950 final SharedUserSetting sus = (SharedUserSetting) obj; 2951 final Iterator<PackageSetting> it = sus.packages.iterator(); 2952 while (it.hasNext()) { 2953 if (it.next().isPrivileged()) { 2954 return true; 2955 } 2956 } 2957 } else if (obj instanceof PackageSetting) { 2958 final PackageSetting ps = (PackageSetting) obj; 2959 return ps.isPrivileged(); 2960 } 2961 } 2962 return false; 2963 } 2964 2965 @Override 2966 public String[] getAppOpPermissionPackages(String permissionName) { 2967 synchronized (mPackages) { 2968 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2969 if (pkgs == null) { 2970 return null; 2971 } 2972 return pkgs.toArray(new String[pkgs.size()]); 2973 } 2974 } 2975 2976 @Override 2977 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2978 int flags, int userId) { 2979 if (!sUserManager.exists(userId)) return null; 2980 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2981 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2982 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2983 } 2984 2985 @Override 2986 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2987 IntentFilter filter, int match, ComponentName activity) { 2988 final int userId = UserHandle.getCallingUserId(); 2989 if (DEBUG_PREFERRED) { 2990 Log.v(TAG, "setLastChosenActivity intent=" + intent 2991 + " resolvedType=" + resolvedType 2992 + " flags=" + flags 2993 + " filter=" + filter 2994 + " match=" + match 2995 + " activity=" + activity); 2996 filter.dump(new PrintStreamPrinter(System.out), " "); 2997 } 2998 intent.setComponent(null); 2999 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3000 // Find any earlier preferred or last chosen entries and nuke them 3001 findPreferredActivity(intent, resolvedType, 3002 flags, query, 0, false, true, false, userId); 3003 // Add the new activity as the last chosen for this filter 3004 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3005 "Setting last chosen"); 3006 } 3007 3008 @Override 3009 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3010 final int userId = UserHandle.getCallingUserId(); 3011 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3012 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3013 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3014 false, false, false, userId); 3015 } 3016 3017 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3018 int flags, List<ResolveInfo> query, int userId) { 3019 if (query != null) { 3020 final int N = query.size(); 3021 if (N == 1) { 3022 return query.get(0); 3023 } else if (N > 1) { 3024 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3025 // If there is more than one activity with the same priority, 3026 // then let the user decide between them. 3027 ResolveInfo r0 = query.get(0); 3028 ResolveInfo r1 = query.get(1); 3029 if (DEBUG_INTENT_MATCHING || debug) { 3030 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3031 + r1.activityInfo.name + "=" + r1.priority); 3032 } 3033 // If the first activity has a higher priority, or a different 3034 // default, then it is always desireable to pick it. 3035 if (r0.priority != r1.priority 3036 || r0.preferredOrder != r1.preferredOrder 3037 || r0.isDefault != r1.isDefault) { 3038 return query.get(0); 3039 } 3040 // If we have saved a preference for a preferred activity for 3041 // this Intent, use that. 3042 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3043 flags, query, r0.priority, true, false, debug, userId); 3044 if (ri != null) { 3045 return ri; 3046 } 3047 if (userId != 0) { 3048 ri = new ResolveInfo(mResolveInfo); 3049 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3050 ri.activityInfo.applicationInfo = new ApplicationInfo( 3051 ri.activityInfo.applicationInfo); 3052 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3053 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3054 return ri; 3055 } 3056 return mResolveInfo; 3057 } 3058 } 3059 return null; 3060 } 3061 3062 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3063 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3064 final int N = query.size(); 3065 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3066 .get(userId); 3067 // Get the list of persistent preferred activities that handle the intent 3068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3069 List<PersistentPreferredActivity> pprefs = ppir != null 3070 ? ppir.queryIntent(intent, resolvedType, 3071 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3072 : null; 3073 if (pprefs != null && pprefs.size() > 0) { 3074 final int M = pprefs.size(); 3075 for (int i=0; i<M; i++) { 3076 final PersistentPreferredActivity ppa = pprefs.get(i); 3077 if (DEBUG_PREFERRED || debug) { 3078 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3079 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3080 + "\n component=" + ppa.mComponent); 3081 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3082 } 3083 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3084 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3085 if (DEBUG_PREFERRED || debug) { 3086 Slog.v(TAG, "Found persistent preferred activity:"); 3087 if (ai != null) { 3088 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3089 } else { 3090 Slog.v(TAG, " null"); 3091 } 3092 } 3093 if (ai == null) { 3094 // This previously registered persistent preferred activity 3095 // component is no longer known. Ignore it and do NOT remove it. 3096 continue; 3097 } 3098 for (int j=0; j<N; j++) { 3099 final ResolveInfo ri = query.get(j); 3100 if (!ri.activityInfo.applicationInfo.packageName 3101 .equals(ai.applicationInfo.packageName)) { 3102 continue; 3103 } 3104 if (!ri.activityInfo.name.equals(ai.name)) { 3105 continue; 3106 } 3107 // Found a persistent preference that can handle the intent. 3108 if (DEBUG_PREFERRED || debug) { 3109 Slog.v(TAG, "Returning persistent preferred activity: " + 3110 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3111 } 3112 return ri; 3113 } 3114 } 3115 } 3116 return null; 3117 } 3118 3119 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3120 List<ResolveInfo> query, int priority, boolean always, 3121 boolean removeMatches, boolean debug, int userId) { 3122 if (!sUserManager.exists(userId)) return null; 3123 // writer 3124 synchronized (mPackages) { 3125 if (intent.getSelector() != null) { 3126 intent = intent.getSelector(); 3127 } 3128 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3129 3130 // Try to find a matching persistent preferred activity. 3131 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3132 debug, userId); 3133 3134 // If a persistent preferred activity matched, use it. 3135 if (pri != null) { 3136 return pri; 3137 } 3138 3139 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3140 // Get the list of preferred activities that handle the intent 3141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3142 List<PreferredActivity> prefs = pir != null 3143 ? pir.queryIntent(intent, resolvedType, 3144 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3145 : null; 3146 if (prefs != null && prefs.size() > 0) { 3147 boolean changed = false; 3148 try { 3149 // First figure out how good the original match set is. 3150 // We will only allow preferred activities that came 3151 // from the same match quality. 3152 int match = 0; 3153 3154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3155 3156 final int N = query.size(); 3157 for (int j=0; j<N; j++) { 3158 final ResolveInfo ri = query.get(j); 3159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3160 + ": 0x" + Integer.toHexString(match)); 3161 if (ri.match > match) { 3162 match = ri.match; 3163 } 3164 } 3165 3166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3167 + Integer.toHexString(match)); 3168 3169 match &= IntentFilter.MATCH_CATEGORY_MASK; 3170 final int M = prefs.size(); 3171 for (int i=0; i<M; i++) { 3172 final PreferredActivity pa = prefs.get(i); 3173 if (DEBUG_PREFERRED || debug) { 3174 Slog.v(TAG, "Checking PreferredActivity ds=" 3175 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3176 + "\n component=" + pa.mPref.mComponent); 3177 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3178 } 3179 if (pa.mPref.mMatch != match) { 3180 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3181 + Integer.toHexString(pa.mPref.mMatch)); 3182 continue; 3183 } 3184 // If it's not an "always" type preferred activity and that's what we're 3185 // looking for, skip it. 3186 if (always && !pa.mPref.mAlways) { 3187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3188 continue; 3189 } 3190 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3191 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3192 if (DEBUG_PREFERRED || debug) { 3193 Slog.v(TAG, "Found preferred activity:"); 3194 if (ai != null) { 3195 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3196 } else { 3197 Slog.v(TAG, " null"); 3198 } 3199 } 3200 if (ai == null) { 3201 // This previously registered preferred activity 3202 // component is no longer known. Most likely an update 3203 // to the app was installed and in the new version this 3204 // component no longer exists. Clean it up by removing 3205 // it from the preferred activities list, and skip it. 3206 Slog.w(TAG, "Removing dangling preferred activity: " 3207 + pa.mPref.mComponent); 3208 pir.removeFilter(pa); 3209 changed = true; 3210 continue; 3211 } 3212 for (int j=0; j<N; j++) { 3213 final ResolveInfo ri = query.get(j); 3214 if (!ri.activityInfo.applicationInfo.packageName 3215 .equals(ai.applicationInfo.packageName)) { 3216 continue; 3217 } 3218 if (!ri.activityInfo.name.equals(ai.name)) { 3219 continue; 3220 } 3221 3222 if (removeMatches) { 3223 pir.removeFilter(pa); 3224 changed = true; 3225 if (DEBUG_PREFERRED) { 3226 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3227 } 3228 break; 3229 } 3230 3231 // Okay we found a previously set preferred or last chosen app. 3232 // If the result set is different from when this 3233 // was created, we need to clear it and re-ask the 3234 // user their preference, if we're looking for an "always" type entry. 3235 if (always && !pa.mPref.sameSet(query, priority)) { 3236 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3237 + intent + " type " + resolvedType); 3238 if (DEBUG_PREFERRED) { 3239 Slog.v(TAG, "Removing preferred activity since set changed " 3240 + pa.mPref.mComponent); 3241 } 3242 pir.removeFilter(pa); 3243 // Re-add the filter as a "last chosen" entry (!always) 3244 PreferredActivity lastChosen = new PreferredActivity( 3245 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3246 pir.addFilter(lastChosen); 3247 changed = true; 3248 return null; 3249 } 3250 3251 // Yay! Either the set matched or we're looking for the last chosen 3252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3253 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3254 return ri; 3255 } 3256 } 3257 } finally { 3258 if (changed) { 3259 if (DEBUG_PREFERRED) { 3260 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3261 } 3262 mSettings.writePackageRestrictionsLPr(userId); 3263 } 3264 } 3265 } 3266 } 3267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3268 return null; 3269 } 3270 3271 /* 3272 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3273 */ 3274 @Override 3275 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3276 int targetUserId) { 3277 mContext.enforceCallingOrSelfPermission( 3278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3279 List<CrossProfileIntentFilter> matches = 3280 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3281 if (matches != null) { 3282 int size = matches.size(); 3283 for (int i = 0; i < size; i++) { 3284 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3285 } 3286 } 3287 return false; 3288 } 3289 3290 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3291 String resolvedType, int userId) { 3292 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3293 if (resolver != null) { 3294 return resolver.queryIntent(intent, resolvedType, false, userId); 3295 } 3296 return null; 3297 } 3298 3299 @Override 3300 public List<ResolveInfo> queryIntentActivities(Intent intent, 3301 String resolvedType, int flags, int userId) { 3302 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3303 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3304 ComponentName comp = intent.getComponent(); 3305 if (comp == null) { 3306 if (intent.getSelector() != null) { 3307 intent = intent.getSelector(); 3308 comp = intent.getComponent(); 3309 } 3310 } 3311 3312 if (comp != null) { 3313 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3314 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3315 if (ai != null) { 3316 final ResolveInfo ri = new ResolveInfo(); 3317 ri.activityInfo = ai; 3318 list.add(ri); 3319 } 3320 return list; 3321 } 3322 3323 // reader 3324 synchronized (mPackages) { 3325 final String pkgName = intent.getPackage(); 3326 if (pkgName == null) { 3327 List<CrossProfileIntentFilter> matchingFilters = 3328 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3329 // Check for results that need to skip the current profile. 3330 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3331 resolvedType, flags, userId); 3332 if (resolveInfo != null) { 3333 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3334 result.add(resolveInfo); 3335 return result; 3336 } 3337 // Check for cross profile results. 3338 resolveInfo = queryCrossProfileIntents( 3339 matchingFilters, intent, resolvedType, flags, userId); 3340 3341 // Check for results in the current profile. 3342 List<ResolveInfo> result = mActivities.queryIntent( 3343 intent, resolvedType, flags, userId); 3344 if (resolveInfo != null) { 3345 result.add(resolveInfo); 3346 Collections.sort(result, mResolvePrioritySorter); 3347 } 3348 return result; 3349 } 3350 final PackageParser.Package pkg = mPackages.get(pkgName); 3351 if (pkg != null) { 3352 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3353 pkg.activities, userId); 3354 } 3355 return new ArrayList<ResolveInfo>(); 3356 } 3357 } 3358 3359 private ResolveInfo querySkipCurrentProfileIntents( 3360 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3361 int flags, int sourceUserId) { 3362 if (matchingFilters != null) { 3363 int size = matchingFilters.size(); 3364 for (int i = 0; i < size; i ++) { 3365 CrossProfileIntentFilter filter = matchingFilters.get(i); 3366 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3367 // Checking if there are activities in the target user that can handle the 3368 // intent. 3369 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3370 flags, sourceUserId); 3371 if (resolveInfo != null) { 3372 return resolveInfo; 3373 } 3374 } 3375 } 3376 } 3377 return null; 3378 } 3379 3380 // Return matching ResolveInfo if any for skip current profile intent filters. 3381 private ResolveInfo queryCrossProfileIntents( 3382 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3383 int flags, int sourceUserId) { 3384 if (matchingFilters != null) { 3385 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3386 // match the same intent. For performance reasons, it is better not to 3387 // run queryIntent twice for the same userId 3388 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3389 int size = matchingFilters.size(); 3390 for (int i = 0; i < size; i++) { 3391 CrossProfileIntentFilter filter = matchingFilters.get(i); 3392 int targetUserId = filter.getTargetUserId(); 3393 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3394 && !alreadyTriedUserIds.get(targetUserId)) { 3395 // Checking if there are activities in the target user that can handle the 3396 // intent. 3397 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3398 flags, sourceUserId); 3399 if (resolveInfo != null) return resolveInfo; 3400 alreadyTriedUserIds.put(targetUserId, true); 3401 } 3402 } 3403 } 3404 return null; 3405 } 3406 3407 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3408 String resolvedType, int flags, int sourceUserId) { 3409 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3410 resolvedType, flags, filter.getTargetUserId()); 3411 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3412 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3413 } 3414 return null; 3415 } 3416 3417 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3418 int sourceUserId, int targetUserId) { 3419 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3420 String className; 3421 if (targetUserId == UserHandle.USER_OWNER) { 3422 className = FORWARD_INTENT_TO_USER_OWNER; 3423 } else { 3424 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3425 } 3426 ComponentName forwardingActivityComponentName = new ComponentName( 3427 mAndroidApplication.packageName, className); 3428 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3429 sourceUserId); 3430 if (targetUserId == UserHandle.USER_OWNER) { 3431 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3432 forwardingResolveInfo.noResourceId = true; 3433 } 3434 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3435 forwardingResolveInfo.priority = 0; 3436 forwardingResolveInfo.preferredOrder = 0; 3437 forwardingResolveInfo.match = 0; 3438 forwardingResolveInfo.isDefault = true; 3439 forwardingResolveInfo.filter = filter; 3440 forwardingResolveInfo.targetUserId = targetUserId; 3441 return forwardingResolveInfo; 3442 } 3443 3444 @Override 3445 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3446 Intent[] specifics, String[] specificTypes, Intent intent, 3447 String resolvedType, int flags, int userId) { 3448 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3449 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3450 false, "query intent activity options"); 3451 final String resultsAction = intent.getAction(); 3452 3453 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3454 | PackageManager.GET_RESOLVED_FILTER, userId); 3455 3456 if (DEBUG_INTENT_MATCHING) { 3457 Log.v(TAG, "Query " + intent + ": " + results); 3458 } 3459 3460 int specificsPos = 0; 3461 int N; 3462 3463 // todo: note that the algorithm used here is O(N^2). This 3464 // isn't a problem in our current environment, but if we start running 3465 // into situations where we have more than 5 or 10 matches then this 3466 // should probably be changed to something smarter... 3467 3468 // First we go through and resolve each of the specific items 3469 // that were supplied, taking care of removing any corresponding 3470 // duplicate items in the generic resolve list. 3471 if (specifics != null) { 3472 for (int i=0; i<specifics.length; i++) { 3473 final Intent sintent = specifics[i]; 3474 if (sintent == null) { 3475 continue; 3476 } 3477 3478 if (DEBUG_INTENT_MATCHING) { 3479 Log.v(TAG, "Specific #" + i + ": " + sintent); 3480 } 3481 3482 String action = sintent.getAction(); 3483 if (resultsAction != null && resultsAction.equals(action)) { 3484 // If this action was explicitly requested, then don't 3485 // remove things that have it. 3486 action = null; 3487 } 3488 3489 ResolveInfo ri = null; 3490 ActivityInfo ai = null; 3491 3492 ComponentName comp = sintent.getComponent(); 3493 if (comp == null) { 3494 ri = resolveIntent( 3495 sintent, 3496 specificTypes != null ? specificTypes[i] : null, 3497 flags, userId); 3498 if (ri == null) { 3499 continue; 3500 } 3501 if (ri == mResolveInfo) { 3502 // ACK! Must do something better with this. 3503 } 3504 ai = ri.activityInfo; 3505 comp = new ComponentName(ai.applicationInfo.packageName, 3506 ai.name); 3507 } else { 3508 ai = getActivityInfo(comp, flags, userId); 3509 if (ai == null) { 3510 continue; 3511 } 3512 } 3513 3514 // Look for any generic query activities that are duplicates 3515 // of this specific one, and remove them from the results. 3516 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3517 N = results.size(); 3518 int j; 3519 for (j=specificsPos; j<N; j++) { 3520 ResolveInfo sri = results.get(j); 3521 if ((sri.activityInfo.name.equals(comp.getClassName()) 3522 && sri.activityInfo.applicationInfo.packageName.equals( 3523 comp.getPackageName())) 3524 || (action != null && sri.filter.matchAction(action))) { 3525 results.remove(j); 3526 if (DEBUG_INTENT_MATCHING) Log.v( 3527 TAG, "Removing duplicate item from " + j 3528 + " due to specific " + specificsPos); 3529 if (ri == null) { 3530 ri = sri; 3531 } 3532 j--; 3533 N--; 3534 } 3535 } 3536 3537 // Add this specific item to its proper place. 3538 if (ri == null) { 3539 ri = new ResolveInfo(); 3540 ri.activityInfo = ai; 3541 } 3542 results.add(specificsPos, ri); 3543 ri.specificIndex = i; 3544 specificsPos++; 3545 } 3546 } 3547 3548 // Now we go through the remaining generic results and remove any 3549 // duplicate actions that are found here. 3550 N = results.size(); 3551 for (int i=specificsPos; i<N-1; i++) { 3552 final ResolveInfo rii = results.get(i); 3553 if (rii.filter == null) { 3554 continue; 3555 } 3556 3557 // Iterate over all of the actions of this result's intent 3558 // filter... typically this should be just one. 3559 final Iterator<String> it = rii.filter.actionsIterator(); 3560 if (it == null) { 3561 continue; 3562 } 3563 while (it.hasNext()) { 3564 final String action = it.next(); 3565 if (resultsAction != null && resultsAction.equals(action)) { 3566 // If this action was explicitly requested, then don't 3567 // remove things that have it. 3568 continue; 3569 } 3570 for (int j=i+1; j<N; j++) { 3571 final ResolveInfo rij = results.get(j); 3572 if (rij.filter != null && rij.filter.hasAction(action)) { 3573 results.remove(j); 3574 if (DEBUG_INTENT_MATCHING) Log.v( 3575 TAG, "Removing duplicate item from " + j 3576 + " due to action " + action + " at " + i); 3577 j--; 3578 N--; 3579 } 3580 } 3581 } 3582 3583 // If the caller didn't request filter information, drop it now 3584 // so we don't have to marshall/unmarshall it. 3585 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3586 rii.filter = null; 3587 } 3588 } 3589 3590 // Filter out the caller activity if so requested. 3591 if (caller != null) { 3592 N = results.size(); 3593 for (int i=0; i<N; i++) { 3594 ActivityInfo ainfo = results.get(i).activityInfo; 3595 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3596 && caller.getClassName().equals(ainfo.name)) { 3597 results.remove(i); 3598 break; 3599 } 3600 } 3601 } 3602 3603 // If the caller didn't request filter information, 3604 // drop them now so we don't have to 3605 // marshall/unmarshall it. 3606 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3607 N = results.size(); 3608 for (int i=0; i<N; i++) { 3609 results.get(i).filter = null; 3610 } 3611 } 3612 3613 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3614 return results; 3615 } 3616 3617 @Override 3618 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3619 int userId) { 3620 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3621 ComponentName comp = intent.getComponent(); 3622 if (comp == null) { 3623 if (intent.getSelector() != null) { 3624 intent = intent.getSelector(); 3625 comp = intent.getComponent(); 3626 } 3627 } 3628 if (comp != null) { 3629 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3630 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3631 if (ai != null) { 3632 ResolveInfo ri = new ResolveInfo(); 3633 ri.activityInfo = ai; 3634 list.add(ri); 3635 } 3636 return list; 3637 } 3638 3639 // reader 3640 synchronized (mPackages) { 3641 String pkgName = intent.getPackage(); 3642 if (pkgName == null) { 3643 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3644 } 3645 final PackageParser.Package pkg = mPackages.get(pkgName); 3646 if (pkg != null) { 3647 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3648 userId); 3649 } 3650 return null; 3651 } 3652 } 3653 3654 @Override 3655 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3656 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3657 if (!sUserManager.exists(userId)) return null; 3658 if (query != null) { 3659 if (query.size() >= 1) { 3660 // If there is more than one service with the same priority, 3661 // just arbitrarily pick the first one. 3662 return query.get(0); 3663 } 3664 } 3665 return null; 3666 } 3667 3668 @Override 3669 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3670 int userId) { 3671 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3672 ComponentName comp = intent.getComponent(); 3673 if (comp == null) { 3674 if (intent.getSelector() != null) { 3675 intent = intent.getSelector(); 3676 comp = intent.getComponent(); 3677 } 3678 } 3679 if (comp != null) { 3680 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3681 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3682 if (si != null) { 3683 final ResolveInfo ri = new ResolveInfo(); 3684 ri.serviceInfo = si; 3685 list.add(ri); 3686 } 3687 return list; 3688 } 3689 3690 // reader 3691 synchronized (mPackages) { 3692 String pkgName = intent.getPackage(); 3693 if (pkgName == null) { 3694 return mServices.queryIntent(intent, resolvedType, flags, userId); 3695 } 3696 final PackageParser.Package pkg = mPackages.get(pkgName); 3697 if (pkg != null) { 3698 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3699 userId); 3700 } 3701 return null; 3702 } 3703 } 3704 3705 @Override 3706 public List<ResolveInfo> queryIntentContentProviders( 3707 Intent intent, String resolvedType, int flags, int userId) { 3708 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3709 ComponentName comp = intent.getComponent(); 3710 if (comp == null) { 3711 if (intent.getSelector() != null) { 3712 intent = intent.getSelector(); 3713 comp = intent.getComponent(); 3714 } 3715 } 3716 if (comp != null) { 3717 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3718 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3719 if (pi != null) { 3720 final ResolveInfo ri = new ResolveInfo(); 3721 ri.providerInfo = pi; 3722 list.add(ri); 3723 } 3724 return list; 3725 } 3726 3727 // reader 3728 synchronized (mPackages) { 3729 String pkgName = intent.getPackage(); 3730 if (pkgName == null) { 3731 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3732 } 3733 final PackageParser.Package pkg = mPackages.get(pkgName); 3734 if (pkg != null) { 3735 return mProviders.queryIntentForPackage( 3736 intent, resolvedType, flags, pkg.providers, userId); 3737 } 3738 return null; 3739 } 3740 } 3741 3742 @Override 3743 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3744 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3745 3746 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3747 3748 // writer 3749 synchronized (mPackages) { 3750 ArrayList<PackageInfo> list; 3751 if (listUninstalled) { 3752 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3753 for (PackageSetting ps : mSettings.mPackages.values()) { 3754 PackageInfo pi; 3755 if (ps.pkg != null) { 3756 pi = generatePackageInfo(ps.pkg, flags, userId); 3757 } else { 3758 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3759 } 3760 if (pi != null) { 3761 list.add(pi); 3762 } 3763 } 3764 } else { 3765 list = new ArrayList<PackageInfo>(mPackages.size()); 3766 for (PackageParser.Package p : mPackages.values()) { 3767 PackageInfo pi = generatePackageInfo(p, flags, userId); 3768 if (pi != null) { 3769 list.add(pi); 3770 } 3771 } 3772 } 3773 3774 return new ParceledListSlice<PackageInfo>(list); 3775 } 3776 } 3777 3778 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3779 String[] permissions, boolean[] tmp, int flags, int userId) { 3780 int numMatch = 0; 3781 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3782 for (int i=0; i<permissions.length; i++) { 3783 if (gp.grantedPermissions.contains(permissions[i])) { 3784 tmp[i] = true; 3785 numMatch++; 3786 } else { 3787 tmp[i] = false; 3788 } 3789 } 3790 if (numMatch == 0) { 3791 return; 3792 } 3793 PackageInfo pi; 3794 if (ps.pkg != null) { 3795 pi = generatePackageInfo(ps.pkg, flags, userId); 3796 } else { 3797 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3798 } 3799 // The above might return null in cases of uninstalled apps or install-state 3800 // skew across users/profiles. 3801 if (pi != null) { 3802 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3803 if (numMatch == permissions.length) { 3804 pi.requestedPermissions = permissions; 3805 } else { 3806 pi.requestedPermissions = new String[numMatch]; 3807 numMatch = 0; 3808 for (int i=0; i<permissions.length; i++) { 3809 if (tmp[i]) { 3810 pi.requestedPermissions[numMatch] = permissions[i]; 3811 numMatch++; 3812 } 3813 } 3814 } 3815 } 3816 list.add(pi); 3817 } 3818 } 3819 3820 @Override 3821 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3822 String[] permissions, int flags, int userId) { 3823 if (!sUserManager.exists(userId)) return null; 3824 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3825 3826 // writer 3827 synchronized (mPackages) { 3828 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3829 boolean[] tmpBools = new boolean[permissions.length]; 3830 if (listUninstalled) { 3831 for (PackageSetting ps : mSettings.mPackages.values()) { 3832 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3833 } 3834 } else { 3835 for (PackageParser.Package pkg : mPackages.values()) { 3836 PackageSetting ps = (PackageSetting)pkg.mExtras; 3837 if (ps != null) { 3838 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3839 userId); 3840 } 3841 } 3842 } 3843 3844 return new ParceledListSlice<PackageInfo>(list); 3845 } 3846 } 3847 3848 @Override 3849 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3850 if (!sUserManager.exists(userId)) return null; 3851 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3852 3853 // writer 3854 synchronized (mPackages) { 3855 ArrayList<ApplicationInfo> list; 3856 if (listUninstalled) { 3857 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3858 for (PackageSetting ps : mSettings.mPackages.values()) { 3859 ApplicationInfo ai; 3860 if (ps.pkg != null) { 3861 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3862 ps.readUserState(userId), userId); 3863 } else { 3864 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3865 } 3866 if (ai != null) { 3867 list.add(ai); 3868 } 3869 } 3870 } else { 3871 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3872 for (PackageParser.Package p : mPackages.values()) { 3873 if (p.mExtras != null) { 3874 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3875 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3876 if (ai != null) { 3877 list.add(ai); 3878 } 3879 } 3880 } 3881 } 3882 3883 return new ParceledListSlice<ApplicationInfo>(list); 3884 } 3885 } 3886 3887 public List<ApplicationInfo> getPersistentApplications(int flags) { 3888 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3889 3890 // reader 3891 synchronized (mPackages) { 3892 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3893 final int userId = UserHandle.getCallingUserId(); 3894 while (i.hasNext()) { 3895 final PackageParser.Package p = i.next(); 3896 if (p.applicationInfo != null 3897 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3898 && (!mSafeMode || isSystemApp(p))) { 3899 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3900 if (ps != null) { 3901 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3902 ps.readUserState(userId), userId); 3903 if (ai != null) { 3904 finalList.add(ai); 3905 } 3906 } 3907 } 3908 } 3909 } 3910 3911 return finalList; 3912 } 3913 3914 @Override 3915 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3916 if (!sUserManager.exists(userId)) return null; 3917 // reader 3918 synchronized (mPackages) { 3919 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3920 PackageSetting ps = provider != null 3921 ? mSettings.mPackages.get(provider.owner.packageName) 3922 : null; 3923 return ps != null 3924 && mSettings.isEnabledLPr(provider.info, flags, userId) 3925 && (!mSafeMode || (provider.info.applicationInfo.flags 3926 &ApplicationInfo.FLAG_SYSTEM) != 0) 3927 ? PackageParser.generateProviderInfo(provider, flags, 3928 ps.readUserState(userId), userId) 3929 : null; 3930 } 3931 } 3932 3933 /** 3934 * @deprecated 3935 */ 3936 @Deprecated 3937 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3938 // reader 3939 synchronized (mPackages) { 3940 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3941 .entrySet().iterator(); 3942 final int userId = UserHandle.getCallingUserId(); 3943 while (i.hasNext()) { 3944 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3945 PackageParser.Provider p = entry.getValue(); 3946 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3947 3948 if (ps != null && p.syncable 3949 && (!mSafeMode || (p.info.applicationInfo.flags 3950 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3951 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3952 ps.readUserState(userId), userId); 3953 if (info != null) { 3954 outNames.add(entry.getKey()); 3955 outInfo.add(info); 3956 } 3957 } 3958 } 3959 } 3960 } 3961 3962 @Override 3963 public List<ProviderInfo> queryContentProviders(String processName, 3964 int uid, int flags) { 3965 ArrayList<ProviderInfo> finalList = null; 3966 // reader 3967 synchronized (mPackages) { 3968 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3969 final int userId = processName != null ? 3970 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3971 while (i.hasNext()) { 3972 final PackageParser.Provider p = i.next(); 3973 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3974 if (ps != null && p.info.authority != null 3975 && (processName == null 3976 || (p.info.processName.equals(processName) 3977 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3978 && mSettings.isEnabledLPr(p.info, flags, userId) 3979 && (!mSafeMode 3980 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3981 if (finalList == null) { 3982 finalList = new ArrayList<ProviderInfo>(3); 3983 } 3984 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3985 ps.readUserState(userId), userId); 3986 if (info != null) { 3987 finalList.add(info); 3988 } 3989 } 3990 } 3991 } 3992 3993 if (finalList != null) { 3994 Collections.sort(finalList, mProviderInitOrderSorter); 3995 } 3996 3997 return finalList; 3998 } 3999 4000 @Override 4001 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4002 int flags) { 4003 // reader 4004 synchronized (mPackages) { 4005 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4006 return PackageParser.generateInstrumentationInfo(i, flags); 4007 } 4008 } 4009 4010 @Override 4011 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4012 int flags) { 4013 ArrayList<InstrumentationInfo> finalList = 4014 new ArrayList<InstrumentationInfo>(); 4015 4016 // reader 4017 synchronized (mPackages) { 4018 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4019 while (i.hasNext()) { 4020 final PackageParser.Instrumentation p = i.next(); 4021 if (targetPackage == null 4022 || targetPackage.equals(p.info.targetPackage)) { 4023 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4024 flags); 4025 if (ii != null) { 4026 finalList.add(ii); 4027 } 4028 } 4029 } 4030 } 4031 4032 return finalList; 4033 } 4034 4035 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4036 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4037 if (overlays == null) { 4038 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4039 return; 4040 } 4041 for (PackageParser.Package opkg : overlays.values()) { 4042 // Not much to do if idmap fails: we already logged the error 4043 // and we certainly don't want to abort installation of pkg simply 4044 // because an overlay didn't fit properly. For these reasons, 4045 // ignore the return value of createIdmapForPackagePairLI. 4046 createIdmapForPackagePairLI(pkg, opkg); 4047 } 4048 } 4049 4050 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4051 PackageParser.Package opkg) { 4052 if (!opkg.mTrustedOverlay) { 4053 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4054 opkg.baseCodePath + ": overlay not trusted"); 4055 return false; 4056 } 4057 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4058 if (overlaySet == null) { 4059 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4060 opkg.baseCodePath + " but target package has no known overlays"); 4061 return false; 4062 } 4063 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4064 // TODO: generate idmap for split APKs 4065 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4066 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4067 + opkg.baseCodePath); 4068 return false; 4069 } 4070 PackageParser.Package[] overlayArray = 4071 overlaySet.values().toArray(new PackageParser.Package[0]); 4072 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4073 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4074 return p1.mOverlayPriority - p2.mOverlayPriority; 4075 } 4076 }; 4077 Arrays.sort(overlayArray, cmp); 4078 4079 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4080 int i = 0; 4081 for (PackageParser.Package p : overlayArray) { 4082 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4083 } 4084 return true; 4085 } 4086 4087 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4088 final File[] files = dir.listFiles(); 4089 if (ArrayUtils.isEmpty(files)) { 4090 Log.d(TAG, "No files in app dir " + dir); 4091 return; 4092 } 4093 4094 if (DEBUG_PACKAGE_SCANNING) { 4095 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4096 + " flags=0x" + Integer.toHexString(parseFlags)); 4097 } 4098 4099 for (File file : files) { 4100 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4101 && !PackageInstallerService.isStageName(file.getName()); 4102 if (!isPackage) { 4103 // Ignore entries which are not packages 4104 continue; 4105 } 4106 try { 4107 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4108 scanFlags, currentTime, null); 4109 } catch (PackageManagerException e) { 4110 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4111 4112 // Delete invalid userdata apps 4113 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4114 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4115 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4116 if (file.isDirectory()) { 4117 FileUtils.deleteContents(file); 4118 } 4119 file.delete(); 4120 } 4121 } 4122 } 4123 } 4124 4125 private static File getSettingsProblemFile() { 4126 File dataDir = Environment.getDataDirectory(); 4127 File systemDir = new File(dataDir, "system"); 4128 File fname = new File(systemDir, "uiderrors.txt"); 4129 return fname; 4130 } 4131 4132 static void reportSettingsProblem(int priority, String msg) { 4133 logCriticalInfo(priority, msg); 4134 } 4135 4136 static void logCriticalInfo(int priority, String msg) { 4137 Slog.println(priority, TAG, msg); 4138 EventLogTags.writePmCriticalInfo(msg); 4139 try { 4140 File fname = getSettingsProblemFile(); 4141 FileOutputStream out = new FileOutputStream(fname, true); 4142 PrintWriter pw = new FastPrintWriter(out); 4143 SimpleDateFormat formatter = new SimpleDateFormat(); 4144 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4145 pw.println(dateString + ": " + msg); 4146 pw.close(); 4147 FileUtils.setPermissions( 4148 fname.toString(), 4149 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4150 -1, -1); 4151 } catch (java.io.IOException e) { 4152 } 4153 } 4154 4155 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4156 PackageParser.Package pkg, File srcFile, int parseFlags) 4157 throws PackageManagerException { 4158 if (ps != null 4159 && ps.codePath.equals(srcFile) 4160 && ps.timeStamp == srcFile.lastModified() 4161 && !isCompatSignatureUpdateNeeded(pkg)) { 4162 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4163 if (ps.signatures.mSignatures != null 4164 && ps.signatures.mSignatures.length != 0 4165 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4166 // Optimization: reuse the existing cached certificates 4167 // if the package appears to be unchanged. 4168 pkg.mSignatures = ps.signatures.mSignatures; 4169 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4170 synchronized (mPackages) { 4171 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4172 } 4173 return; 4174 } 4175 4176 Slog.w(TAG, "PackageSetting for " + ps.name 4177 + " is missing signatures. Collecting certs again to recover them."); 4178 } else { 4179 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4180 } 4181 4182 try { 4183 pp.collectCertificates(pkg, parseFlags); 4184 pp.collectManifestDigest(pkg); 4185 } catch (PackageParserException e) { 4186 throw PackageManagerException.from(e); 4187 } 4188 } 4189 4190 /* 4191 * Scan a package and return the newly parsed package. 4192 * Returns null in case of errors and the error code is stored in mLastScanError 4193 */ 4194 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4195 long currentTime, UserHandle user) throws PackageManagerException { 4196 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4197 parseFlags |= mDefParseFlags; 4198 PackageParser pp = new PackageParser(); 4199 pp.setSeparateProcesses(mSeparateProcesses); 4200 pp.setOnlyCoreApps(mOnlyCore); 4201 pp.setDisplayMetrics(mMetrics); 4202 4203 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4204 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4205 } 4206 4207 final PackageParser.Package pkg; 4208 try { 4209 pkg = pp.parsePackage(scanFile, parseFlags); 4210 } catch (PackageParserException e) { 4211 throw PackageManagerException.from(e); 4212 } 4213 4214 PackageSetting ps = null; 4215 PackageSetting updatedPkg; 4216 // reader 4217 synchronized (mPackages) { 4218 // Look to see if we already know about this package. 4219 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4220 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4221 // This package has been renamed to its original name. Let's 4222 // use that. 4223 ps = mSettings.peekPackageLPr(oldName); 4224 } 4225 // If there was no original package, see one for the real package name. 4226 if (ps == null) { 4227 ps = mSettings.peekPackageLPr(pkg.packageName); 4228 } 4229 // Check to see if this package could be hiding/updating a system 4230 // package. Must look for it either under the original or real 4231 // package name depending on our state. 4232 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4233 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4234 } 4235 boolean updatedPkgBetter = false; 4236 // First check if this is a system package that may involve an update 4237 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4238 if (ps != null && !ps.codePath.equals(scanFile)) { 4239 // The path has changed from what was last scanned... check the 4240 // version of the new path against what we have stored to determine 4241 // what to do. 4242 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4243 if (pkg.mVersionCode < ps.versionCode) { 4244 // The system package has been updated and the code path does not match 4245 // Ignore entry. Skip it. 4246 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4247 + " ignored: updated version " + ps.versionCode 4248 + " better than this " + pkg.mVersionCode); 4249 if (!updatedPkg.codePath.equals(scanFile)) { 4250 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4251 + ps.name + " changing from " + updatedPkg.codePathString 4252 + " to " + scanFile); 4253 updatedPkg.codePath = scanFile; 4254 updatedPkg.codePathString = scanFile.toString(); 4255 // This is the point at which we know that the system-disk APK 4256 // for this package has moved during a reboot (e.g. due to an OTA), 4257 // so we need to reevaluate it for privilege policy. 4258 if (locationIsPrivileged(scanFile)) { 4259 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4260 } 4261 } 4262 updatedPkg.pkg = pkg; 4263 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4264 } else { 4265 // The current app on the system partition is better than 4266 // what we have updated to on the data partition; switch 4267 // back to the system partition version. 4268 // At this point, its safely assumed that package installation for 4269 // apps in system partition will go through. If not there won't be a working 4270 // version of the app 4271 // writer 4272 synchronized (mPackages) { 4273 // Just remove the loaded entries from package lists. 4274 mPackages.remove(ps.name); 4275 } 4276 4277 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4278 + " reverting from " + ps.codePathString 4279 + ": new version " + pkg.mVersionCode 4280 + " better than installed " + ps.versionCode); 4281 4282 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4283 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4284 getAppDexInstructionSets(ps)); 4285 synchronized (mInstallLock) { 4286 args.cleanUpResourcesLI(); 4287 } 4288 synchronized (mPackages) { 4289 mSettings.enableSystemPackageLPw(ps.name); 4290 } 4291 updatedPkgBetter = true; 4292 } 4293 } 4294 } 4295 4296 if (updatedPkg != null) { 4297 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4298 // initially 4299 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4300 4301 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4302 // flag set initially 4303 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4304 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4305 } 4306 } 4307 4308 // Verify certificates against what was last scanned 4309 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4310 4311 /* 4312 * A new system app appeared, but we already had a non-system one of the 4313 * same name installed earlier. 4314 */ 4315 boolean shouldHideSystemApp = false; 4316 if (updatedPkg == null && ps != null 4317 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4318 /* 4319 * Check to make sure the signatures match first. If they don't, 4320 * wipe the installed application and its data. 4321 */ 4322 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4323 != PackageManager.SIGNATURE_MATCH) { 4324 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4325 + " signatures don't match existing userdata copy; removing"); 4326 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4327 ps = null; 4328 } else { 4329 /* 4330 * If the newly-added system app is an older version than the 4331 * already installed version, hide it. It will be scanned later 4332 * and re-added like an update. 4333 */ 4334 if (pkg.mVersionCode < ps.versionCode) { 4335 shouldHideSystemApp = true; 4336 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4337 + " but new version " + pkg.mVersionCode + " better than installed " 4338 + ps.versionCode + "; hiding system"); 4339 } else { 4340 /* 4341 * The newly found system app is a newer version that the 4342 * one previously installed. Simply remove the 4343 * already-installed application and replace it with our own 4344 * while keeping the application data. 4345 */ 4346 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4347 + " reverting from " + ps.codePathString + ": new version " 4348 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4349 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4350 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4351 getAppDexInstructionSets(ps)); 4352 synchronized (mInstallLock) { 4353 args.cleanUpResourcesLI(); 4354 } 4355 } 4356 } 4357 } 4358 4359 // The apk is forward locked (not public) if its code and resources 4360 // are kept in different files. (except for app in either system or 4361 // vendor path). 4362 // TODO grab this value from PackageSettings 4363 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4364 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4365 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4366 } 4367 } 4368 4369 // TODO: extend to support forward-locked splits 4370 String resourcePath = null; 4371 String baseResourcePath = null; 4372 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4373 if (ps != null && ps.resourcePathString != null) { 4374 resourcePath = ps.resourcePathString; 4375 baseResourcePath = ps.resourcePathString; 4376 } else { 4377 // Should not happen at all. Just log an error. 4378 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4379 } 4380 } else { 4381 resourcePath = pkg.codePath; 4382 baseResourcePath = pkg.baseCodePath; 4383 } 4384 4385 // Set application objects path explicitly. 4386 pkg.applicationInfo.setCodePath(pkg.codePath); 4387 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4388 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4389 pkg.applicationInfo.setResourcePath(resourcePath); 4390 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4391 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4392 4393 // Note that we invoke the following method only if we are about to unpack an application 4394 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4395 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4396 4397 /* 4398 * If the system app should be overridden by a previously installed 4399 * data, hide the system app now and let the /data/app scan pick it up 4400 * again. 4401 */ 4402 if (shouldHideSystemApp) { 4403 synchronized (mPackages) { 4404 /* 4405 * We have to grant systems permissions before we hide, because 4406 * grantPermissions will assume the package update is trying to 4407 * expand its permissions. 4408 */ 4409 grantPermissionsLPw(pkg, true, pkg.packageName); 4410 mSettings.disableSystemPackageLPw(pkg.packageName); 4411 } 4412 } 4413 4414 return scannedPkg; 4415 } 4416 4417 private static String fixProcessName(String defProcessName, 4418 String processName, int uid) { 4419 if (processName == null) { 4420 return defProcessName; 4421 } 4422 return processName; 4423 } 4424 4425 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4426 throws PackageManagerException { 4427 if (pkgSetting.signatures.mSignatures != null) { 4428 // Already existing package. Make sure signatures match 4429 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4430 == PackageManager.SIGNATURE_MATCH; 4431 if (!match) { 4432 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4433 == PackageManager.SIGNATURE_MATCH; 4434 } 4435 if (!match) { 4436 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4437 + pkg.packageName + " signatures do not match the " 4438 + "previously installed version; ignoring!"); 4439 } 4440 } 4441 4442 // Check for shared user signatures 4443 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4444 // Already existing package. Make sure signatures match 4445 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4446 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4447 if (!match) { 4448 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4449 == PackageManager.SIGNATURE_MATCH; 4450 } 4451 if (!match) { 4452 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4453 "Package " + pkg.packageName 4454 + " has no signatures that match those in shared user " 4455 + pkgSetting.sharedUser.name + "; ignoring!"); 4456 } 4457 } 4458 } 4459 4460 /** 4461 * Enforces that only the system UID or root's UID can call a method exposed 4462 * via Binder. 4463 * 4464 * @param message used as message if SecurityException is thrown 4465 * @throws SecurityException if the caller is not system or root 4466 */ 4467 private static final void enforceSystemOrRoot(String message) { 4468 final int uid = Binder.getCallingUid(); 4469 if (uid != Process.SYSTEM_UID && uid != 0) { 4470 throw new SecurityException(message); 4471 } 4472 } 4473 4474 @Override 4475 public void performBootDexOpt() { 4476 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4477 4478 final ArraySet<PackageParser.Package> pkgs; 4479 synchronized (mPackages) { 4480 pkgs = mDeferredDexOpt; 4481 mDeferredDexOpt = null; 4482 } 4483 4484 if (pkgs != null) { 4485 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4486 // in case the device runs out of space. 4487 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4488 // Give priority to core apps. 4489 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4490 PackageParser.Package pkg = it.next(); 4491 if (pkg.coreApp) { 4492 if (DEBUG_DEXOPT) { 4493 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4494 } 4495 sortedPkgs.add(pkg); 4496 it.remove(); 4497 } 4498 } 4499 // Give priority to system apps that listen for pre boot complete. 4500 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4501 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4502 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4503 PackageParser.Package pkg = it.next(); 4504 if (pkgNames.contains(pkg.packageName)) { 4505 if (DEBUG_DEXOPT) { 4506 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4507 } 4508 sortedPkgs.add(pkg); 4509 it.remove(); 4510 } 4511 } 4512 // Give priority to system apps. 4513 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4514 PackageParser.Package pkg = it.next(); 4515 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4516 if (DEBUG_DEXOPT) { 4517 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4518 } 4519 sortedPkgs.add(pkg); 4520 it.remove(); 4521 } 4522 } 4523 // Give priority to updated system apps. 4524 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4525 PackageParser.Package pkg = it.next(); 4526 if (isUpdatedSystemApp(pkg)) { 4527 if (DEBUG_DEXOPT) { 4528 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4529 } 4530 sortedPkgs.add(pkg); 4531 it.remove(); 4532 } 4533 } 4534 // Give priority to apps that listen for boot complete. 4535 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4536 pkgNames = getPackageNamesForIntent(intent); 4537 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4538 PackageParser.Package pkg = it.next(); 4539 if (pkgNames.contains(pkg.packageName)) { 4540 if (DEBUG_DEXOPT) { 4541 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4542 } 4543 sortedPkgs.add(pkg); 4544 it.remove(); 4545 } 4546 } 4547 // Filter out packages that aren't recently used. 4548 filterRecentlyUsedApps(pkgs); 4549 // Add all remaining apps. 4550 for (PackageParser.Package pkg : pkgs) { 4551 if (DEBUG_DEXOPT) { 4552 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4553 } 4554 sortedPkgs.add(pkg); 4555 } 4556 4557 int i = 0; 4558 int total = sortedPkgs.size(); 4559 File dataDir = Environment.getDataDirectory(); 4560 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4561 if (lowThreshold == 0) { 4562 throw new IllegalStateException("Invalid low memory threshold"); 4563 } 4564 for (PackageParser.Package pkg : sortedPkgs) { 4565 long usableSpace = dataDir.getUsableSpace(); 4566 if (usableSpace < lowThreshold) { 4567 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4568 break; 4569 } 4570 performBootDexOpt(pkg, ++i, total); 4571 } 4572 } 4573 } 4574 4575 private void filterRecentlyUsedApps(ArraySet<PackageParser.Package> pkgs) { 4576 // Filter out packages that aren't recently used. 4577 // 4578 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4579 // should do a full dexopt. 4580 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4581 int total = pkgs.size(); 4582 int skipped = 0; 4583 long now = System.currentTimeMillis(); 4584 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4585 PackageParser.Package pkg = i.next(); 4586 long then = pkg.mLastPackageUsageTimeInMills; 4587 if (then + mDexOptLRUThresholdInMills < now) { 4588 if (DEBUG_DEXOPT) { 4589 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4590 ((then == 0) ? "never" : new Date(then))); 4591 } 4592 i.remove(); 4593 skipped++; 4594 } 4595 } 4596 if (DEBUG_DEXOPT) { 4597 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4598 } 4599 } 4600 } 4601 4602 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4603 List<ResolveInfo> ris = null; 4604 try { 4605 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4606 intent, null, 0, UserHandle.USER_OWNER); 4607 } catch (RemoteException e) { 4608 } 4609 ArraySet<String> pkgNames = new ArraySet<String>(); 4610 if (ris != null) { 4611 for (ResolveInfo ri : ris) { 4612 pkgNames.add(ri.activityInfo.packageName); 4613 } 4614 } 4615 return pkgNames; 4616 } 4617 4618 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4619 if (DEBUG_DEXOPT) { 4620 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4621 } 4622 if (!isFirstBoot()) { 4623 try { 4624 ActivityManagerNative.getDefault().showBootMessage( 4625 mContext.getResources().getString(R.string.android_upgrading_apk, 4626 curr, total), true); 4627 } catch (RemoteException e) { 4628 } 4629 } 4630 PackageParser.Package p = pkg; 4631 synchronized (mInstallLock) { 4632 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4633 false /* defer */, true /* include dependencies */); 4634 } 4635 } 4636 4637 @Override 4638 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4639 return performDexOpt(packageName, instructionSet, false); 4640 } 4641 4642 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4643 if (info.primaryCpuAbi == null) { 4644 return getPreferredInstructionSet(); 4645 } 4646 4647 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4648 } 4649 4650 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4651 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4652 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4653 if (!dexopt && !updateUsage) { 4654 // We aren't going to dexopt or update usage, so bail early. 4655 return false; 4656 } 4657 PackageParser.Package p; 4658 final String targetInstructionSet; 4659 synchronized (mPackages) { 4660 p = mPackages.get(packageName); 4661 if (p == null) { 4662 return false; 4663 } 4664 if (updateUsage) { 4665 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4666 } 4667 mPackageUsage.write(false); 4668 if (!dexopt) { 4669 // We aren't going to dexopt, so bail early. 4670 return false; 4671 } 4672 4673 targetInstructionSet = instructionSet != null ? instructionSet : 4674 getPrimaryInstructionSet(p.applicationInfo); 4675 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4676 return false; 4677 } 4678 } 4679 4680 synchronized (mInstallLock) { 4681 final String[] instructionSets = new String[] { targetInstructionSet }; 4682 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4683 true /* include dependencies */) == DEX_OPT_PERFORMED; 4684 } 4685 } 4686 4687 public ArraySet<String> getPackagesThatNeedDexOpt() { 4688 ArraySet<String> pkgs = null; 4689 synchronized (mPackages) { 4690 for (PackageParser.Package p : mPackages.values()) { 4691 if (DEBUG_DEXOPT) { 4692 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4693 } 4694 if (!p.mDexOptPerformed.isEmpty()) { 4695 continue; 4696 } 4697 if (pkgs == null) { 4698 pkgs = new ArraySet<String>(); 4699 } 4700 pkgs.add(p.packageName); 4701 } 4702 } 4703 return pkgs; 4704 } 4705 4706 public void shutdown() { 4707 mPackageUsage.write(true); 4708 } 4709 4710 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4711 boolean forceDex, boolean defer, ArraySet<String> done) { 4712 for (int i=0; i<libs.size(); i++) { 4713 PackageParser.Package libPkg; 4714 String libName; 4715 synchronized (mPackages) { 4716 libName = libs.get(i); 4717 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4718 if (lib != null && lib.apk != null) { 4719 libPkg = mPackages.get(lib.apk); 4720 } else { 4721 libPkg = null; 4722 } 4723 } 4724 if (libPkg != null && !done.contains(libName)) { 4725 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4726 } 4727 } 4728 } 4729 4730 static final int DEX_OPT_SKIPPED = 0; 4731 static final int DEX_OPT_PERFORMED = 1; 4732 static final int DEX_OPT_DEFERRED = 2; 4733 static final int DEX_OPT_FAILED = -1; 4734 4735 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4736 boolean forceDex, boolean defer, ArraySet<String> done) { 4737 final String[] instructionSets = targetInstructionSets != null ? 4738 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4739 4740 if (done != null) { 4741 done.add(pkg.packageName); 4742 if (pkg.usesLibraries != null) { 4743 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4744 } 4745 if (pkg.usesOptionalLibraries != null) { 4746 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4747 } 4748 } 4749 4750 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4751 return DEX_OPT_SKIPPED; 4752 } 4753 4754 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4755 4756 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4757 boolean performedDexOpt = false; 4758 // There are three basic cases here: 4759 // 1.) we need to dexopt, either because we are forced or it is needed 4760 // 2.) we are defering a needed dexopt 4761 // 3.) we are skipping an unneeded dexopt 4762 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4763 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4764 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4765 continue; 4766 } 4767 4768 for (String path : paths) { 4769 try { 4770 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4771 // patckage or the one we find does not match the image checksum (i.e. it was 4772 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4773 // odex file and it matches the checksum of the image but not its base address, 4774 // meaning we need to move it. 4775 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4776 pkg.packageName, dexCodeInstructionSet, defer); 4777 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4778 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4779 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4780 + " vmSafeMode=" + vmSafeMode); 4781 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4782 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4783 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4784 4785 if (ret < 0) { 4786 // Don't bother running dexopt again if we failed, it will probably 4787 // just result in an error again. Also, don't bother dexopting for other 4788 // paths & ISAs. 4789 return DEX_OPT_FAILED; 4790 } 4791 4792 performedDexOpt = true; 4793 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4794 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4795 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4796 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4797 pkg.packageName, dexCodeInstructionSet); 4798 4799 if (ret < 0) { 4800 // Don't bother running patchoat again if we failed, it will probably 4801 // just result in an error again. Also, don't bother dexopting for other 4802 // paths & ISAs. 4803 return DEX_OPT_FAILED; 4804 } 4805 4806 performedDexOpt = true; 4807 } 4808 4809 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4810 // paths and instruction sets. We'll deal with them all together when we process 4811 // our list of deferred dexopts. 4812 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4813 if (mDeferredDexOpt == null) { 4814 mDeferredDexOpt = new ArraySet<PackageParser.Package>(); 4815 } 4816 mDeferredDexOpt.add(pkg); 4817 return DEX_OPT_DEFERRED; 4818 } 4819 } catch (FileNotFoundException e) { 4820 Slog.w(TAG, "Apk not found for dexopt: " + path); 4821 return DEX_OPT_FAILED; 4822 } catch (IOException e) { 4823 Slog.w(TAG, "IOException reading apk: " + path, e); 4824 return DEX_OPT_FAILED; 4825 } catch (StaleDexCacheError e) { 4826 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4827 return DEX_OPT_FAILED; 4828 } catch (Exception e) { 4829 Slog.w(TAG, "Exception when doing dexopt : ", e); 4830 return DEX_OPT_FAILED; 4831 } 4832 } 4833 4834 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4835 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4836 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4837 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4838 // it. 4839 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4840 } 4841 4842 // If we've gotten here, we're sure that no error occurred and that we haven't 4843 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4844 // we've skipped all of them because they are up to date. In both cases this 4845 // package doesn't need dexopt any longer. 4846 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4847 } 4848 4849 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4850 if (info.primaryCpuAbi != null) { 4851 if (info.secondaryCpuAbi != null) { 4852 return new String[] { 4853 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4854 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4855 } else { 4856 return new String[] { 4857 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4858 } 4859 } 4860 4861 return new String[] { getPreferredInstructionSet() }; 4862 } 4863 4864 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4865 if (ps.primaryCpuAbiString != null) { 4866 if (ps.secondaryCpuAbiString != null) { 4867 return new String[] { 4868 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4869 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4870 } else { 4871 return new String[] { 4872 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4873 } 4874 } 4875 4876 return new String[] { getPreferredInstructionSet() }; 4877 } 4878 4879 private static String getPreferredInstructionSet() { 4880 if (sPreferredInstructionSet == null) { 4881 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4882 } 4883 4884 return sPreferredInstructionSet; 4885 } 4886 4887 private static List<String> getAllInstructionSets() { 4888 final String[] allAbis = Build.SUPPORTED_ABIS; 4889 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4890 4891 for (String abi : allAbis) { 4892 final String instructionSet = VMRuntime.getInstructionSet(abi); 4893 if (!allInstructionSets.contains(instructionSet)) { 4894 allInstructionSets.add(instructionSet); 4895 } 4896 } 4897 4898 return allInstructionSets; 4899 } 4900 4901 /** 4902 * Returns the instruction set that should be used to compile dex code. In the presence of 4903 * a native bridge this might be different than the one shared libraries use. 4904 */ 4905 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4906 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4907 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4908 } 4909 4910 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4911 ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length); 4912 for (String instructionSet : instructionSets) { 4913 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4914 } 4915 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4916 } 4917 4918 /** 4919 * Returns deduplicated list of supported instructions for dex code. 4920 */ 4921 public static String[] getAllDexCodeInstructionSets() { 4922 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4923 for (int i = 0; i < supportedInstructionSets.length; i++) { 4924 String abi = Build.SUPPORTED_ABIS[i]; 4925 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4926 } 4927 return getDexCodeInstructionSets(supportedInstructionSets); 4928 } 4929 4930 @Override 4931 public void forceDexOpt(String packageName) { 4932 enforceSystemOrRoot("forceDexOpt"); 4933 4934 PackageParser.Package pkg; 4935 synchronized (mPackages) { 4936 pkg = mPackages.get(packageName); 4937 if (pkg == null) { 4938 throw new IllegalArgumentException("Missing package: " + packageName); 4939 } 4940 } 4941 4942 synchronized (mInstallLock) { 4943 final String[] instructionSets = new String[] { 4944 getPrimaryInstructionSet(pkg.applicationInfo) }; 4945 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4946 if (res != DEX_OPT_PERFORMED) { 4947 throw new IllegalStateException("Failed to dexopt: " + res); 4948 } 4949 } 4950 } 4951 4952 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4953 boolean forceDex, boolean defer, boolean inclDependencies) { 4954 ArraySet<String> done; 4955 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4956 done = new ArraySet<String>(); 4957 done.add(pkg.packageName); 4958 } else { 4959 done = null; 4960 } 4961 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4962 } 4963 4964 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4965 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4966 Slog.w(TAG, "Unable to update from " + oldPkg.name 4967 + " to " + newPkg.packageName 4968 + ": old package not in system partition"); 4969 return false; 4970 } else if (mPackages.get(oldPkg.name) != null) { 4971 Slog.w(TAG, "Unable to update from " + oldPkg.name 4972 + " to " + newPkg.packageName 4973 + ": old package still exists"); 4974 return false; 4975 } 4976 return true; 4977 } 4978 4979 File getDataPathForUser(int userId) { 4980 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4981 } 4982 4983 private File getDataPathForPackage(String packageName, int userId) { 4984 /* 4985 * Until we fully support multiple users, return the directory we 4986 * previously would have. The PackageManagerTests will need to be 4987 * revised when this is changed back.. 4988 */ 4989 if (userId == 0) { 4990 return new File(mAppDataDir, packageName); 4991 } else { 4992 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4993 + File.separator + packageName); 4994 } 4995 } 4996 4997 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4998 int[] users = sUserManager.getUserIds(); 4999 int res = mInstaller.install(packageName, uid, uid, seinfo); 5000 if (res < 0) { 5001 return res; 5002 } 5003 for (int user : users) { 5004 if (user != 0) { 5005 res = mInstaller.createUserData(packageName, 5006 UserHandle.getUid(user, uid), user, seinfo); 5007 if (res < 0) { 5008 return res; 5009 } 5010 } 5011 } 5012 return res; 5013 } 5014 5015 private int removeDataDirsLI(String packageName) { 5016 int[] users = sUserManager.getUserIds(); 5017 int res = 0; 5018 for (int user : users) { 5019 int resInner = mInstaller.remove(packageName, user); 5020 if (resInner < 0) { 5021 res = resInner; 5022 } 5023 } 5024 5025 return res; 5026 } 5027 5028 private int deleteCodeCacheDirsLI(String packageName) { 5029 int[] users = sUserManager.getUserIds(); 5030 int res = 0; 5031 for (int user : users) { 5032 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5033 if (resInner < 0) { 5034 res = resInner; 5035 } 5036 } 5037 return res; 5038 } 5039 5040 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5041 PackageParser.Package changingLib) { 5042 if (file.path != null) { 5043 usesLibraryFiles.add(file.path); 5044 return; 5045 } 5046 PackageParser.Package p = mPackages.get(file.apk); 5047 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5048 // If we are doing this while in the middle of updating a library apk, 5049 // then we need to make sure to use that new apk for determining the 5050 // dependencies here. (We haven't yet finished committing the new apk 5051 // to the package manager state.) 5052 if (p == null || p.packageName.equals(changingLib.packageName)) { 5053 p = changingLib; 5054 } 5055 } 5056 if (p != null) { 5057 usesLibraryFiles.addAll(p.getAllCodePaths()); 5058 } 5059 } 5060 5061 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5062 PackageParser.Package changingLib) throws PackageManagerException { 5063 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5064 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5065 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5066 for (int i=0; i<N; i++) { 5067 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5068 if (file == null) { 5069 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5070 "Package " + pkg.packageName + " requires unavailable shared library " 5071 + pkg.usesLibraries.get(i) + "; failing!"); 5072 } 5073 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5074 } 5075 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5076 for (int i=0; i<N; i++) { 5077 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5078 if (file == null) { 5079 Slog.w(TAG, "Package " + pkg.packageName 5080 + " desires unavailable shared library " 5081 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5082 } else { 5083 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5084 } 5085 } 5086 N = usesLibraryFiles.size(); 5087 if (N > 0) { 5088 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5089 } else { 5090 pkg.usesLibraryFiles = null; 5091 } 5092 } 5093 } 5094 5095 private static boolean hasString(List<String> list, List<String> which) { 5096 if (list == null) { 5097 return false; 5098 } 5099 for (int i=list.size()-1; i>=0; i--) { 5100 for (int j=which.size()-1; j>=0; j--) { 5101 if (which.get(j).equals(list.get(i))) { 5102 return true; 5103 } 5104 } 5105 } 5106 return false; 5107 } 5108 5109 private void updateAllSharedLibrariesLPw() { 5110 for (PackageParser.Package pkg : mPackages.values()) { 5111 try { 5112 updateSharedLibrariesLPw(pkg, null); 5113 } catch (PackageManagerException e) { 5114 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5115 } 5116 } 5117 } 5118 5119 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5120 PackageParser.Package changingPkg) { 5121 ArrayList<PackageParser.Package> res = null; 5122 for (PackageParser.Package pkg : mPackages.values()) { 5123 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5124 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5125 if (res == null) { 5126 res = new ArrayList<PackageParser.Package>(); 5127 } 5128 res.add(pkg); 5129 try { 5130 updateSharedLibrariesLPw(pkg, changingPkg); 5131 } catch (PackageManagerException e) { 5132 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5133 } 5134 } 5135 } 5136 return res; 5137 } 5138 5139 /** 5140 * Derive the value of the {@code cpuAbiOverride} based on the provided 5141 * value and an optional stored value from the package settings. 5142 */ 5143 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5144 String cpuAbiOverride = null; 5145 5146 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5147 cpuAbiOverride = null; 5148 } else if (abiOverride != null) { 5149 cpuAbiOverride = abiOverride; 5150 } else if (settings != null) { 5151 cpuAbiOverride = settings.cpuAbiOverrideString; 5152 } 5153 5154 return cpuAbiOverride; 5155 } 5156 5157 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5158 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5159 boolean success = false; 5160 try { 5161 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5162 currentTime, user); 5163 success = true; 5164 return res; 5165 } finally { 5166 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5167 removeDataDirsLI(pkg.packageName); 5168 } 5169 } 5170 } 5171 5172 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5173 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5174 final File scanFile = new File(pkg.codePath); 5175 if (pkg.applicationInfo.getCodePath() == null || 5176 pkg.applicationInfo.getResourcePath() == null) { 5177 // Bail out. The resource and code paths haven't been set. 5178 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5179 "Code and resource paths haven't been set correctly"); 5180 } 5181 5182 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5183 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5184 } else { 5185 // Only allow system apps to be flagged as core apps. 5186 pkg.coreApp = false; 5187 } 5188 5189 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5190 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5191 } 5192 5193 if (mCustomResolverComponentName != null && 5194 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5195 setUpCustomResolverActivity(pkg); 5196 } 5197 5198 if (pkg.packageName.equals("android")) { 5199 synchronized (mPackages) { 5200 if (mAndroidApplication != null) { 5201 Slog.w(TAG, "*************************************************"); 5202 Slog.w(TAG, "Core android package being redefined. Skipping."); 5203 Slog.w(TAG, " file=" + scanFile); 5204 Slog.w(TAG, "*************************************************"); 5205 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5206 "Core android package being redefined. Skipping."); 5207 } 5208 5209 // Set up information for our fall-back user intent resolution activity. 5210 mPlatformPackage = pkg; 5211 pkg.mVersionCode = mSdkVersion; 5212 mAndroidApplication = pkg.applicationInfo; 5213 5214 if (!mResolverReplaced) { 5215 mResolveActivity.applicationInfo = mAndroidApplication; 5216 mResolveActivity.name = ResolverActivity.class.getName(); 5217 mResolveActivity.packageName = mAndroidApplication.packageName; 5218 mResolveActivity.processName = "system:ui"; 5219 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5220 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5221 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5222 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5223 mResolveActivity.exported = true; 5224 mResolveActivity.enabled = true; 5225 mResolveInfo.activityInfo = mResolveActivity; 5226 mResolveInfo.priority = 0; 5227 mResolveInfo.preferredOrder = 0; 5228 mResolveInfo.match = 0; 5229 mResolveComponentName = new ComponentName( 5230 mAndroidApplication.packageName, mResolveActivity.name); 5231 } 5232 } 5233 } 5234 5235 if (DEBUG_PACKAGE_SCANNING) { 5236 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5237 Log.d(TAG, "Scanning package " + pkg.packageName); 5238 } 5239 5240 if (mPackages.containsKey(pkg.packageName) 5241 || mSharedLibraries.containsKey(pkg.packageName)) { 5242 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5243 "Application package " + pkg.packageName 5244 + " already installed. Skipping duplicate."); 5245 } 5246 5247 // Initialize package source and resource directories 5248 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5249 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5250 5251 SharedUserSetting suid = null; 5252 PackageSetting pkgSetting = null; 5253 5254 if (!isSystemApp(pkg)) { 5255 // Only system apps can use these features. 5256 pkg.mOriginalPackages = null; 5257 pkg.mRealPackage = null; 5258 pkg.mAdoptPermissions = null; 5259 } 5260 5261 // writer 5262 synchronized (mPackages) { 5263 if (pkg.mSharedUserId != null) { 5264 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5265 if (suid == null) { 5266 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5267 "Creating application package " + pkg.packageName 5268 + " for shared user failed"); 5269 } 5270 if (DEBUG_PACKAGE_SCANNING) { 5271 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5272 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5273 + "): packages=" + suid.packages); 5274 } 5275 } 5276 5277 // Check if we are renaming from an original package name. 5278 PackageSetting origPackage = null; 5279 String realName = null; 5280 if (pkg.mOriginalPackages != null) { 5281 // This package may need to be renamed to a previously 5282 // installed name. Let's check on that... 5283 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5284 if (pkg.mOriginalPackages.contains(renamed)) { 5285 // This package had originally been installed as the 5286 // original name, and we have already taken care of 5287 // transitioning to the new one. Just update the new 5288 // one to continue using the old name. 5289 realName = pkg.mRealPackage; 5290 if (!pkg.packageName.equals(renamed)) { 5291 // Callers into this function may have already taken 5292 // care of renaming the package; only do it here if 5293 // it is not already done. 5294 pkg.setPackageName(renamed); 5295 } 5296 5297 } else { 5298 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5299 if ((origPackage = mSettings.peekPackageLPr( 5300 pkg.mOriginalPackages.get(i))) != null) { 5301 // We do have the package already installed under its 5302 // original name... should we use it? 5303 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5304 // New package is not compatible with original. 5305 origPackage = null; 5306 continue; 5307 } else if (origPackage.sharedUser != null) { 5308 // Make sure uid is compatible between packages. 5309 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5310 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5311 + " to " + pkg.packageName + ": old uid " 5312 + origPackage.sharedUser.name 5313 + " differs from " + pkg.mSharedUserId); 5314 origPackage = null; 5315 continue; 5316 } 5317 } else { 5318 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5319 + pkg.packageName + " to old name " + origPackage.name); 5320 } 5321 break; 5322 } 5323 } 5324 } 5325 } 5326 5327 if (mTransferedPackages.contains(pkg.packageName)) { 5328 Slog.w(TAG, "Package " + pkg.packageName 5329 + " was transferred to another, but its .apk remains"); 5330 } 5331 5332 // Just create the setting, don't add it yet. For already existing packages 5333 // the PkgSetting exists already and doesn't have to be created. 5334 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5335 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5336 pkg.applicationInfo.primaryCpuAbi, 5337 pkg.applicationInfo.secondaryCpuAbi, 5338 pkg.applicationInfo.flags, user, false); 5339 if (pkgSetting == null) { 5340 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5341 "Creating application package " + pkg.packageName + " failed"); 5342 } 5343 5344 if (pkgSetting.origPackage != null) { 5345 // If we are first transitioning from an original package, 5346 // fix up the new package's name now. We need to do this after 5347 // looking up the package under its new name, so getPackageLP 5348 // can take care of fiddling things correctly. 5349 pkg.setPackageName(origPackage.name); 5350 5351 // File a report about this. 5352 String msg = "New package " + pkgSetting.realName 5353 + " renamed to replace old package " + pkgSetting.name; 5354 reportSettingsProblem(Log.WARN, msg); 5355 5356 // Make a note of it. 5357 mTransferedPackages.add(origPackage.name); 5358 5359 // No longer need to retain this. 5360 pkgSetting.origPackage = null; 5361 } 5362 5363 if (realName != null) { 5364 // Make a note of it. 5365 mTransferedPackages.add(pkg.packageName); 5366 } 5367 5368 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5369 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5370 } 5371 5372 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5373 // Check all shared libraries and map to their actual file path. 5374 // We only do this here for apps not on a system dir, because those 5375 // are the only ones that can fail an install due to this. We 5376 // will take care of the system apps by updating all of their 5377 // library paths after the scan is done. 5378 updateSharedLibrariesLPw(pkg, null); 5379 } 5380 5381 if (mFoundPolicyFile) { 5382 SELinuxMMAC.assignSeinfoValue(pkg); 5383 } 5384 5385 pkg.applicationInfo.uid = pkgSetting.appId; 5386 pkg.mExtras = pkgSetting; 5387 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5388 try { 5389 verifySignaturesLP(pkgSetting, pkg); 5390 } catch (PackageManagerException e) { 5391 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5392 throw e; 5393 } 5394 // The signature has changed, but this package is in the system 5395 // image... let's recover! 5396 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5397 // However... if this package is part of a shared user, but it 5398 // doesn't match the signature of the shared user, let's fail. 5399 // What this means is that you can't change the signatures 5400 // associated with an overall shared user, which doesn't seem all 5401 // that unreasonable. 5402 if (pkgSetting.sharedUser != null) { 5403 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5404 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5405 throw new PackageManagerException( 5406 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5407 "Signature mismatch for shared user : " 5408 + pkgSetting.sharedUser); 5409 } 5410 } 5411 // File a report about this. 5412 String msg = "System package " + pkg.packageName 5413 + " signature changed; retaining data."; 5414 reportSettingsProblem(Log.WARN, msg); 5415 } 5416 } else { 5417 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5418 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5419 + pkg.packageName + " upgrade keys do not match the " 5420 + "previously installed version"); 5421 } else { 5422 // signatures may have changed as result of upgrade 5423 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5424 } 5425 } 5426 // Verify that this new package doesn't have any content providers 5427 // that conflict with existing packages. Only do this if the 5428 // package isn't already installed, since we don't want to break 5429 // things that are installed. 5430 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5431 final int N = pkg.providers.size(); 5432 int i; 5433 for (i=0; i<N; i++) { 5434 PackageParser.Provider p = pkg.providers.get(i); 5435 if (p.info.authority != null) { 5436 String names[] = p.info.authority.split(";"); 5437 for (int j = 0; j < names.length; j++) { 5438 if (mProvidersByAuthority.containsKey(names[j])) { 5439 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5440 final String otherPackageName = 5441 ((other != null && other.getComponentName() != null) ? 5442 other.getComponentName().getPackageName() : "?"); 5443 throw new PackageManagerException( 5444 INSTALL_FAILED_CONFLICTING_PROVIDER, 5445 "Can't install because provider name " + names[j] 5446 + " (in package " + pkg.applicationInfo.packageName 5447 + ") is already used by " + otherPackageName); 5448 } 5449 } 5450 } 5451 } 5452 } 5453 5454 if (pkg.mAdoptPermissions != null) { 5455 // This package wants to adopt ownership of permissions from 5456 // another package. 5457 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5458 final String origName = pkg.mAdoptPermissions.get(i); 5459 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5460 if (orig != null) { 5461 if (verifyPackageUpdateLPr(orig, pkg)) { 5462 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5463 + pkg.packageName); 5464 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5465 } 5466 } 5467 } 5468 } 5469 } 5470 5471 final String pkgName = pkg.packageName; 5472 5473 final long scanFileTime = scanFile.lastModified(); 5474 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5475 pkg.applicationInfo.processName = fixProcessName( 5476 pkg.applicationInfo.packageName, 5477 pkg.applicationInfo.processName, 5478 pkg.applicationInfo.uid); 5479 5480 File dataPath; 5481 if (mPlatformPackage == pkg) { 5482 // The system package is special. 5483 dataPath = new File(Environment.getDataDirectory(), "system"); 5484 5485 pkg.applicationInfo.dataDir = dataPath.getPath(); 5486 5487 } else { 5488 // This is a normal package, need to make its data directory. 5489 dataPath = getDataPathForPackage(pkg.packageName, 0); 5490 5491 boolean uidError = false; 5492 if (dataPath.exists()) { 5493 int currentUid = 0; 5494 try { 5495 StructStat stat = Os.stat(dataPath.getPath()); 5496 currentUid = stat.st_uid; 5497 } catch (ErrnoException e) { 5498 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5499 } 5500 5501 // If we have mismatched owners for the data path, we have a problem. 5502 if (currentUid != pkg.applicationInfo.uid) { 5503 boolean recovered = false; 5504 if (currentUid == 0) { 5505 // The directory somehow became owned by root. Wow. 5506 // This is probably because the system was stopped while 5507 // installd was in the middle of messing with its libs 5508 // directory. Ask installd to fix that. 5509 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5510 pkg.applicationInfo.uid); 5511 if (ret >= 0) { 5512 recovered = true; 5513 String msg = "Package " + pkg.packageName 5514 + " unexpectedly changed to uid 0; recovered to " + 5515 + pkg.applicationInfo.uid; 5516 reportSettingsProblem(Log.WARN, msg); 5517 } 5518 } 5519 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5520 || (scanFlags&SCAN_BOOTING) != 0)) { 5521 // If this is a system app, we can at least delete its 5522 // current data so the application will still work. 5523 int ret = removeDataDirsLI(pkgName); 5524 if (ret >= 0) { 5525 // TODO: Kill the processes first 5526 // Old data gone! 5527 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5528 ? "System package " : "Third party package "; 5529 String msg = prefix + pkg.packageName 5530 + " has changed from uid: " 5531 + currentUid + " to " 5532 + pkg.applicationInfo.uid + "; old data erased"; 5533 reportSettingsProblem(Log.WARN, msg); 5534 recovered = true; 5535 5536 // And now re-install the app. 5537 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5538 pkg.applicationInfo.seinfo); 5539 if (ret == -1) { 5540 // Ack should not happen! 5541 msg = prefix + pkg.packageName 5542 + " could not have data directory re-created after delete."; 5543 reportSettingsProblem(Log.WARN, msg); 5544 throw new PackageManagerException( 5545 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5546 } 5547 } 5548 if (!recovered) { 5549 mHasSystemUidErrors = true; 5550 } 5551 } else if (!recovered) { 5552 // If we allow this install to proceed, we will be broken. 5553 // Abort, abort! 5554 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5555 "scanPackageLI"); 5556 } 5557 if (!recovered) { 5558 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5559 + pkg.applicationInfo.uid + "/fs_" 5560 + currentUid; 5561 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5562 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5563 String msg = "Package " + pkg.packageName 5564 + " has mismatched uid: " 5565 + currentUid + " on disk, " 5566 + pkg.applicationInfo.uid + " in settings"; 5567 // writer 5568 synchronized (mPackages) { 5569 mSettings.mReadMessages.append(msg); 5570 mSettings.mReadMessages.append('\n'); 5571 uidError = true; 5572 if (!pkgSetting.uidError) { 5573 reportSettingsProblem(Log.ERROR, msg); 5574 } 5575 } 5576 } 5577 } 5578 pkg.applicationInfo.dataDir = dataPath.getPath(); 5579 if (mShouldRestoreconData) { 5580 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5581 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5582 pkg.applicationInfo.uid); 5583 } 5584 } else { 5585 if (DEBUG_PACKAGE_SCANNING) { 5586 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5587 Log.v(TAG, "Want this data dir: " + dataPath); 5588 } 5589 //invoke installer to do the actual installation 5590 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5591 pkg.applicationInfo.seinfo); 5592 if (ret < 0) { 5593 // Error from installer 5594 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5595 "Unable to create data dirs [errorCode=" + ret + "]"); 5596 } 5597 5598 if (dataPath.exists()) { 5599 pkg.applicationInfo.dataDir = dataPath.getPath(); 5600 } else { 5601 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5602 pkg.applicationInfo.dataDir = null; 5603 } 5604 } 5605 5606 pkgSetting.uidError = uidError; 5607 } 5608 5609 final String path = scanFile.getPath(); 5610 final String codePath = pkg.applicationInfo.getCodePath(); 5611 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5612 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5613 setBundledAppAbisAndRoots(pkg, pkgSetting); 5614 5615 // If we haven't found any native libraries for the app, check if it has 5616 // renderscript code. We'll need to force the app to 32 bit if it has 5617 // renderscript bitcode. 5618 if (pkg.applicationInfo.primaryCpuAbi == null 5619 && pkg.applicationInfo.secondaryCpuAbi == null 5620 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5621 NativeLibraryHelper.Handle handle = null; 5622 try { 5623 handle = NativeLibraryHelper.Handle.create(scanFile); 5624 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5625 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5626 } 5627 } catch (IOException ioe) { 5628 Slog.w(TAG, "Error scanning system app : " + ioe); 5629 } finally { 5630 IoUtils.closeQuietly(handle); 5631 } 5632 } 5633 5634 setNativeLibraryPaths(pkg); 5635 } else { 5636 // TODO: We can probably be smarter about this stuff. For installed apps, 5637 // we can calculate this information at install time once and for all. For 5638 // system apps, we can probably assume that this information doesn't change 5639 // after the first boot scan. As things stand, we do lots of unnecessary work. 5640 5641 // Give ourselves some initial paths; we'll come back for another 5642 // pass once we've determined ABI below. 5643 setNativeLibraryPaths(pkg); 5644 5645 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5646 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5647 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5648 5649 NativeLibraryHelper.Handle handle = null; 5650 try { 5651 handle = NativeLibraryHelper.Handle.create(scanFile); 5652 // TODO(multiArch): This can be null for apps that didn't go through the 5653 // usual installation process. We can calculate it again, like we 5654 // do during install time. 5655 // 5656 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5657 // unnecessary. 5658 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5659 5660 // Null out the abis so that they can be recalculated. 5661 pkg.applicationInfo.primaryCpuAbi = null; 5662 pkg.applicationInfo.secondaryCpuAbi = null; 5663 if (isMultiArch(pkg.applicationInfo)) { 5664 // Warn if we've set an abiOverride for multi-lib packages.. 5665 // By definition, we need to copy both 32 and 64 bit libraries for 5666 // such packages. 5667 if (pkg.cpuAbiOverride != null 5668 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5669 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5670 } 5671 5672 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5673 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5674 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5675 if (isAsec) { 5676 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5677 } else { 5678 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5679 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5680 useIsaSpecificSubdirs); 5681 } 5682 } 5683 5684 maybeThrowExceptionForMultiArchCopy( 5685 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5686 5687 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5688 if (isAsec) { 5689 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5690 } else { 5691 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5692 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5693 useIsaSpecificSubdirs); 5694 } 5695 } 5696 5697 maybeThrowExceptionForMultiArchCopy( 5698 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5699 5700 if (abi64 >= 0) { 5701 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5702 } 5703 5704 if (abi32 >= 0) { 5705 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5706 if (abi64 >= 0) { 5707 pkg.applicationInfo.secondaryCpuAbi = abi; 5708 } else { 5709 pkg.applicationInfo.primaryCpuAbi = abi; 5710 } 5711 } 5712 } else { 5713 String[] abiList = (cpuAbiOverride != null) ? 5714 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5715 5716 // Enable gross and lame hacks for apps that are built with old 5717 // SDK tools. We must scan their APKs for renderscript bitcode and 5718 // not launch them if it's present. Don't bother checking on devices 5719 // that don't have 64 bit support. 5720 boolean needsRenderScriptOverride = false; 5721 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5722 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5723 abiList = Build.SUPPORTED_32_BIT_ABIS; 5724 needsRenderScriptOverride = true; 5725 } 5726 5727 final int copyRet; 5728 if (isAsec) { 5729 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5730 } else { 5731 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5732 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5733 } 5734 5735 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5736 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5737 "Error unpackaging native libs for app, errorCode=" + copyRet); 5738 } 5739 5740 if (copyRet >= 0) { 5741 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5742 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5743 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5744 } else if (needsRenderScriptOverride) { 5745 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5746 } 5747 } 5748 } catch (IOException ioe) { 5749 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5750 } finally { 5751 IoUtils.closeQuietly(handle); 5752 } 5753 5754 // Now that we've calculated the ABIs and determined if it's an internal app, 5755 // we will go ahead and populate the nativeLibraryPath. 5756 setNativeLibraryPaths(pkg); 5757 5758 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5759 final int[] userIds = sUserManager.getUserIds(); 5760 synchronized (mInstallLock) { 5761 // Create a native library symlink only if we have native libraries 5762 // and if the native libraries are 32 bit libraries. We do not provide 5763 // this symlink for 64 bit libraries. 5764 if (pkg.applicationInfo.primaryCpuAbi != null && 5765 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5766 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5767 for (int userId : userIds) { 5768 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5769 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5770 "Failed linking native library dir (user=" + userId + ")"); 5771 } 5772 } 5773 } 5774 } 5775 } 5776 5777 // This is a special case for the "system" package, where the ABI is 5778 // dictated by the zygote configuration (and init.rc). We should keep track 5779 // of this ABI so that we can deal with "normal" applications that run under 5780 // the same UID correctly. 5781 if (mPlatformPackage == pkg) { 5782 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5783 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5784 } 5785 5786 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5787 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5788 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5789 // Copy the derived override back to the parsed package, so that we can 5790 // update the package settings accordingly. 5791 pkg.cpuAbiOverride = cpuAbiOverride; 5792 5793 if (DEBUG_ABI_SELECTION) { 5794 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5795 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5796 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5797 } 5798 5799 // Push the derived path down into PackageSettings so we know what to 5800 // clean up at uninstall time. 5801 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5802 5803 if (DEBUG_ABI_SELECTION) { 5804 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5805 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5806 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5807 } 5808 5809 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5810 // We don't do this here during boot because we can do it all 5811 // at once after scanning all existing packages. 5812 // 5813 // We also do this *before* we perform dexopt on this package, so that 5814 // we can avoid redundant dexopts, and also to make sure we've got the 5815 // code and package path correct. 5816 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5817 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5818 } 5819 5820 if ((scanFlags & SCAN_NO_DEX) == 0) { 5821 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5822 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5823 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5824 } 5825 } 5826 5827 if (mFactoryTest && pkg.requestedPermissions.contains( 5828 android.Manifest.permission.FACTORY_TEST)) { 5829 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5830 } 5831 5832 ArrayList<PackageParser.Package> clientLibPkgs = null; 5833 5834 // writer 5835 synchronized (mPackages) { 5836 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5837 // Only system apps can add new shared libraries. 5838 if (pkg.libraryNames != null) { 5839 for (int i=0; i<pkg.libraryNames.size(); i++) { 5840 String name = pkg.libraryNames.get(i); 5841 boolean allowed = false; 5842 if (isUpdatedSystemApp(pkg)) { 5843 // New library entries can only be added through the 5844 // system image. This is important to get rid of a lot 5845 // of nasty edge cases: for example if we allowed a non- 5846 // system update of the app to add a library, then uninstalling 5847 // the update would make the library go away, and assumptions 5848 // we made such as through app install filtering would now 5849 // have allowed apps on the device which aren't compatible 5850 // with it. Better to just have the restriction here, be 5851 // conservative, and create many fewer cases that can negatively 5852 // impact the user experience. 5853 final PackageSetting sysPs = mSettings 5854 .getDisabledSystemPkgLPr(pkg.packageName); 5855 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5856 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5857 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5858 allowed = true; 5859 allowed = true; 5860 break; 5861 } 5862 } 5863 } 5864 } else { 5865 allowed = true; 5866 } 5867 if (allowed) { 5868 if (!mSharedLibraries.containsKey(name)) { 5869 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5870 } else if (!name.equals(pkg.packageName)) { 5871 Slog.w(TAG, "Package " + pkg.packageName + " library " 5872 + name + " already exists; skipping"); 5873 } 5874 } else { 5875 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5876 + name + " that is not declared on system image; skipping"); 5877 } 5878 } 5879 if ((scanFlags&SCAN_BOOTING) == 0) { 5880 // If we are not booting, we need to update any applications 5881 // that are clients of our shared library. If we are booting, 5882 // this will all be done once the scan is complete. 5883 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5884 } 5885 } 5886 } 5887 } 5888 5889 // We also need to dexopt any apps that are dependent on this library. Note that 5890 // if these fail, we should abort the install since installing the library will 5891 // result in some apps being broken. 5892 if (clientLibPkgs != null) { 5893 if ((scanFlags & SCAN_NO_DEX) == 0) { 5894 for (int i = 0; i < clientLibPkgs.size(); i++) { 5895 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5896 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5897 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5898 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5899 "scanPackageLI failed to dexopt clientLibPkgs"); 5900 } 5901 } 5902 } 5903 } 5904 5905 // Request the ActivityManager to kill the process(only for existing packages) 5906 // so that we do not end up in a confused state while the user is still using the older 5907 // version of the application while the new one gets installed. 5908 if ((scanFlags & SCAN_REPLACING) != 0) { 5909 killApplication(pkg.applicationInfo.packageName, 5910 pkg.applicationInfo.uid, "update pkg"); 5911 } 5912 5913 // Also need to kill any apps that are dependent on the library. 5914 if (clientLibPkgs != null) { 5915 for (int i=0; i<clientLibPkgs.size(); i++) { 5916 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5917 killApplication(clientPkg.applicationInfo.packageName, 5918 clientPkg.applicationInfo.uid, "update lib"); 5919 } 5920 } 5921 5922 // writer 5923 synchronized (mPackages) { 5924 // We don't expect installation to fail beyond this point 5925 5926 // Add the new setting to mSettings 5927 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5928 // Add the new setting to mPackages 5929 mPackages.put(pkg.applicationInfo.packageName, pkg); 5930 // Make sure we don't accidentally delete its data. 5931 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5932 while (iter.hasNext()) { 5933 PackageCleanItem item = iter.next(); 5934 if (pkgName.equals(item.packageName)) { 5935 iter.remove(); 5936 } 5937 } 5938 5939 // Take care of first install / last update times. 5940 if (currentTime != 0) { 5941 if (pkgSetting.firstInstallTime == 0) { 5942 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5943 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5944 pkgSetting.lastUpdateTime = currentTime; 5945 } 5946 } else if (pkgSetting.firstInstallTime == 0) { 5947 // We need *something*. Take time time stamp of the file. 5948 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5949 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5950 if (scanFileTime != pkgSetting.timeStamp) { 5951 // A package on the system image has changed; consider this 5952 // to be an update. 5953 pkgSetting.lastUpdateTime = scanFileTime; 5954 } 5955 } 5956 5957 // Add the package's KeySets to the global KeySetManagerService 5958 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5959 try { 5960 // Old KeySetData no longer valid. 5961 ksms.removeAppKeySetDataLPw(pkg.packageName); 5962 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5963 if (pkg.mKeySetMapping != null) { 5964 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5965 pkg.mKeySetMapping.entrySet()) { 5966 if (entry.getValue() != null) { 5967 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5968 entry.getValue(), entry.getKey()); 5969 } 5970 } 5971 if (pkg.mUpgradeKeySets != null) { 5972 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5973 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5974 } 5975 } 5976 } 5977 } catch (NullPointerException e) { 5978 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5979 } catch (IllegalArgumentException e) { 5980 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5981 } 5982 5983 int N = pkg.providers.size(); 5984 StringBuilder r = null; 5985 int i; 5986 for (i=0; i<N; i++) { 5987 PackageParser.Provider p = pkg.providers.get(i); 5988 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5989 p.info.processName, pkg.applicationInfo.uid); 5990 mProviders.addProvider(p); 5991 p.syncable = p.info.isSyncable; 5992 if (p.info.authority != null) { 5993 String names[] = p.info.authority.split(";"); 5994 p.info.authority = null; 5995 for (int j = 0; j < names.length; j++) { 5996 if (j == 1 && p.syncable) { 5997 // We only want the first authority for a provider to possibly be 5998 // syncable, so if we already added this provider using a different 5999 // authority clear the syncable flag. We copy the provider before 6000 // changing it because the mProviders object contains a reference 6001 // to a provider that we don't want to change. 6002 // Only do this for the second authority since the resulting provider 6003 // object can be the same for all future authorities for this provider. 6004 p = new PackageParser.Provider(p); 6005 p.syncable = false; 6006 } 6007 if (!mProvidersByAuthority.containsKey(names[j])) { 6008 mProvidersByAuthority.put(names[j], p); 6009 if (p.info.authority == null) { 6010 p.info.authority = names[j]; 6011 } else { 6012 p.info.authority = p.info.authority + ";" + names[j]; 6013 } 6014 if (DEBUG_PACKAGE_SCANNING) { 6015 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6016 Log.d(TAG, "Registered content provider: " + names[j] 6017 + ", className = " + p.info.name + ", isSyncable = " 6018 + p.info.isSyncable); 6019 } 6020 } else { 6021 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6022 Slog.w(TAG, "Skipping provider name " + names[j] + 6023 " (in package " + pkg.applicationInfo.packageName + 6024 "): name already used by " 6025 + ((other != null && other.getComponentName() != null) 6026 ? other.getComponentName().getPackageName() : "?")); 6027 } 6028 } 6029 } 6030 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6031 if (r == null) { 6032 r = new StringBuilder(256); 6033 } else { 6034 r.append(' '); 6035 } 6036 r.append(p.info.name); 6037 } 6038 } 6039 if (r != null) { 6040 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6041 } 6042 6043 N = pkg.services.size(); 6044 r = null; 6045 for (i=0; i<N; i++) { 6046 PackageParser.Service s = pkg.services.get(i); 6047 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6048 s.info.processName, pkg.applicationInfo.uid); 6049 mServices.addService(s); 6050 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6051 if (r == null) { 6052 r = new StringBuilder(256); 6053 } else { 6054 r.append(' '); 6055 } 6056 r.append(s.info.name); 6057 } 6058 } 6059 if (r != null) { 6060 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6061 } 6062 6063 N = pkg.receivers.size(); 6064 r = null; 6065 for (i=0; i<N; i++) { 6066 PackageParser.Activity a = pkg.receivers.get(i); 6067 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6068 a.info.processName, pkg.applicationInfo.uid); 6069 mReceivers.addActivity(a, "receiver"); 6070 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6071 if (r == null) { 6072 r = new StringBuilder(256); 6073 } else { 6074 r.append(' '); 6075 } 6076 r.append(a.info.name); 6077 } 6078 } 6079 if (r != null) { 6080 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6081 } 6082 6083 N = pkg.activities.size(); 6084 r = null; 6085 for (i=0; i<N; i++) { 6086 PackageParser.Activity a = pkg.activities.get(i); 6087 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6088 a.info.processName, pkg.applicationInfo.uid); 6089 mActivities.addActivity(a, "activity"); 6090 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6091 if (r == null) { 6092 r = new StringBuilder(256); 6093 } else { 6094 r.append(' '); 6095 } 6096 r.append(a.info.name); 6097 } 6098 } 6099 if (r != null) { 6100 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6101 } 6102 6103 N = pkg.permissionGroups.size(); 6104 r = null; 6105 for (i=0; i<N; i++) { 6106 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6107 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6108 if (cur == null) { 6109 mPermissionGroups.put(pg.info.name, pg); 6110 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6111 if (r == null) { 6112 r = new StringBuilder(256); 6113 } else { 6114 r.append(' '); 6115 } 6116 r.append(pg.info.name); 6117 } 6118 } else { 6119 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6120 + pg.info.packageName + " ignored: original from " 6121 + cur.info.packageName); 6122 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6123 if (r == null) { 6124 r = new StringBuilder(256); 6125 } else { 6126 r.append(' '); 6127 } 6128 r.append("DUP:"); 6129 r.append(pg.info.name); 6130 } 6131 } 6132 } 6133 if (r != null) { 6134 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6135 } 6136 6137 N = pkg.permissions.size(); 6138 r = null; 6139 for (i=0; i<N; i++) { 6140 PackageParser.Permission p = pkg.permissions.get(i); 6141 ArrayMap<String, BasePermission> permissionMap = 6142 p.tree ? mSettings.mPermissionTrees 6143 : mSettings.mPermissions; 6144 p.group = mPermissionGroups.get(p.info.group); 6145 if (p.info.group == null || p.group != null) { 6146 BasePermission bp = permissionMap.get(p.info.name); 6147 6148 // Allow system apps to redefine non-system permissions 6149 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6150 final boolean currentOwnerIsSystem = (bp.perm != null 6151 && isSystemApp(bp.perm.owner)); 6152 if (isSystemApp(p.owner)) { 6153 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6154 // It's a built-in permission and no owner, take ownership now 6155 bp.packageSetting = pkgSetting; 6156 bp.perm = p; 6157 bp.uid = pkg.applicationInfo.uid; 6158 bp.sourcePackage = p.info.packageName; 6159 } else if (!currentOwnerIsSystem) { 6160 String msg = "New decl " + p.owner + " of permission " 6161 + p.info.name + " is system; overriding " + bp.sourcePackage; 6162 reportSettingsProblem(Log.WARN, msg); 6163 bp = null; 6164 } 6165 } 6166 } 6167 6168 if (bp == null) { 6169 bp = new BasePermission(p.info.name, p.info.packageName, 6170 BasePermission.TYPE_NORMAL); 6171 permissionMap.put(p.info.name, bp); 6172 } 6173 6174 if (bp.perm == null) { 6175 if (bp.sourcePackage == null 6176 || bp.sourcePackage.equals(p.info.packageName)) { 6177 BasePermission tree = findPermissionTreeLP(p.info.name); 6178 if (tree == null 6179 || tree.sourcePackage.equals(p.info.packageName)) { 6180 bp.packageSetting = pkgSetting; 6181 bp.perm = p; 6182 bp.uid = pkg.applicationInfo.uid; 6183 bp.sourcePackage = p.info.packageName; 6184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6185 if (r == null) { 6186 r = new StringBuilder(256); 6187 } else { 6188 r.append(' '); 6189 } 6190 r.append(p.info.name); 6191 } 6192 } else { 6193 Slog.w(TAG, "Permission " + p.info.name + " from package " 6194 + p.info.packageName + " ignored: base tree " 6195 + tree.name + " is from package " 6196 + tree.sourcePackage); 6197 } 6198 } else { 6199 Slog.w(TAG, "Permission " + p.info.name + " from package " 6200 + p.info.packageName + " ignored: original from " 6201 + bp.sourcePackage); 6202 } 6203 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6204 if (r == null) { 6205 r = new StringBuilder(256); 6206 } else { 6207 r.append(' '); 6208 } 6209 r.append("DUP:"); 6210 r.append(p.info.name); 6211 } 6212 if (bp.perm == p) { 6213 bp.protectionLevel = p.info.protectionLevel; 6214 } 6215 } else { 6216 Slog.w(TAG, "Permission " + p.info.name + " from package " 6217 + p.info.packageName + " ignored: no group " 6218 + p.group); 6219 } 6220 } 6221 if (r != null) { 6222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6223 } 6224 6225 N = pkg.instrumentation.size(); 6226 r = null; 6227 for (i=0; i<N; i++) { 6228 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6229 a.info.packageName = pkg.applicationInfo.packageName; 6230 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6231 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6232 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6233 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6234 a.info.dataDir = pkg.applicationInfo.dataDir; 6235 6236 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6237 // need other information about the application, like the ABI and what not ? 6238 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6239 mInstrumentation.put(a.getComponentName(), a); 6240 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6241 if (r == null) { 6242 r = new StringBuilder(256); 6243 } else { 6244 r.append(' '); 6245 } 6246 r.append(a.info.name); 6247 } 6248 } 6249 if (r != null) { 6250 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6251 } 6252 6253 if (pkg.protectedBroadcasts != null) { 6254 N = pkg.protectedBroadcasts.size(); 6255 for (i=0; i<N; i++) { 6256 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6257 } 6258 } 6259 6260 pkgSetting.setTimeStamp(scanFileTime); 6261 6262 // Create idmap files for pairs of (packages, overlay packages). 6263 // Note: "android", ie framework-res.apk, is handled by native layers. 6264 if (pkg.mOverlayTarget != null) { 6265 // This is an overlay package. 6266 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6267 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6268 mOverlays.put(pkg.mOverlayTarget, 6269 new ArrayMap<String, PackageParser.Package>()); 6270 } 6271 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6272 map.put(pkg.packageName, pkg); 6273 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6274 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6275 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6276 "scanPackageLI failed to createIdmap"); 6277 } 6278 } 6279 } else if (mOverlays.containsKey(pkg.packageName) && 6280 !pkg.packageName.equals("android")) { 6281 // This is a regular package, with one or more known overlay packages. 6282 createIdmapsForPackageLI(pkg); 6283 } 6284 } 6285 6286 return pkg; 6287 } 6288 6289 /** 6290 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6291 * i.e, so that all packages can be run inside a single process if required. 6292 * 6293 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6294 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6295 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6296 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6297 * updating a package that belongs to a shared user. 6298 * 6299 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6300 * adds unnecessary complexity. 6301 */ 6302 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6303 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6304 String requiredInstructionSet = null; 6305 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6306 requiredInstructionSet = VMRuntime.getInstructionSet( 6307 scannedPackage.applicationInfo.primaryCpuAbi); 6308 } 6309 6310 PackageSetting requirer = null; 6311 for (PackageSetting ps : packagesForUser) { 6312 // If packagesForUser contains scannedPackage, we skip it. This will happen 6313 // when scannedPackage is an update of an existing package. Without this check, 6314 // we will never be able to change the ABI of any package belonging to a shared 6315 // user, even if it's compatible with other packages. 6316 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6317 if (ps.primaryCpuAbiString == null) { 6318 continue; 6319 } 6320 6321 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6322 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6323 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6324 // this but there's not much we can do. 6325 String errorMessage = "Instruction set mismatch, " 6326 + ((requirer == null) ? "[caller]" : requirer) 6327 + " requires " + requiredInstructionSet + " whereas " + ps 6328 + " requires " + instructionSet; 6329 Slog.w(TAG, errorMessage); 6330 } 6331 6332 if (requiredInstructionSet == null) { 6333 requiredInstructionSet = instructionSet; 6334 requirer = ps; 6335 } 6336 } 6337 } 6338 6339 if (requiredInstructionSet != null) { 6340 String adjustedAbi; 6341 if (requirer != null) { 6342 // requirer != null implies that either scannedPackage was null or that scannedPackage 6343 // did not require an ABI, in which case we have to adjust scannedPackage to match 6344 // the ABI of the set (which is the same as requirer's ABI) 6345 adjustedAbi = requirer.primaryCpuAbiString; 6346 if (scannedPackage != null) { 6347 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6348 } 6349 } else { 6350 // requirer == null implies that we're updating all ABIs in the set to 6351 // match scannedPackage. 6352 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6353 } 6354 6355 for (PackageSetting ps : packagesForUser) { 6356 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6357 if (ps.primaryCpuAbiString != null) { 6358 continue; 6359 } 6360 6361 ps.primaryCpuAbiString = adjustedAbi; 6362 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6363 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6364 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6365 6366 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6367 deferDexOpt, true) == DEX_OPT_FAILED) { 6368 ps.primaryCpuAbiString = null; 6369 ps.pkg.applicationInfo.primaryCpuAbi = null; 6370 return; 6371 } else { 6372 mInstaller.rmdex(ps.codePathString, 6373 getDexCodeInstructionSet(getPreferredInstructionSet())); 6374 } 6375 } 6376 } 6377 } 6378 } 6379 } 6380 6381 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6382 synchronized (mPackages) { 6383 mResolverReplaced = true; 6384 // Set up information for custom user intent resolution activity. 6385 mResolveActivity.applicationInfo = pkg.applicationInfo; 6386 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6387 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6388 mResolveActivity.processName = null; 6389 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6390 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6391 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6392 mResolveActivity.theme = 0; 6393 mResolveActivity.exported = true; 6394 mResolveActivity.enabled = true; 6395 mResolveInfo.activityInfo = mResolveActivity; 6396 mResolveInfo.priority = 0; 6397 mResolveInfo.preferredOrder = 0; 6398 mResolveInfo.match = 0; 6399 mResolveComponentName = mCustomResolverComponentName; 6400 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6401 mResolveComponentName); 6402 } 6403 } 6404 6405 private static String calculateBundledApkRoot(final String codePathString) { 6406 final File codePath = new File(codePathString); 6407 final File codeRoot; 6408 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6409 codeRoot = Environment.getRootDirectory(); 6410 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6411 codeRoot = Environment.getOemDirectory(); 6412 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6413 codeRoot = Environment.getVendorDirectory(); 6414 } else { 6415 // Unrecognized code path; take its top real segment as the apk root: 6416 // e.g. /something/app/blah.apk => /something 6417 try { 6418 File f = codePath.getCanonicalFile(); 6419 File parent = f.getParentFile(); // non-null because codePath is a file 6420 File tmp; 6421 while ((tmp = parent.getParentFile()) != null) { 6422 f = parent; 6423 parent = tmp; 6424 } 6425 codeRoot = f; 6426 Slog.w(TAG, "Unrecognized code path " 6427 + codePath + " - using " + codeRoot); 6428 } catch (IOException e) { 6429 // Can't canonicalize the code path -- shenanigans? 6430 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6431 return Environment.getRootDirectory().getPath(); 6432 } 6433 } 6434 return codeRoot.getPath(); 6435 } 6436 6437 /** 6438 * Derive and set the location of native libraries for the given package, 6439 * which varies depending on where and how the package was installed. 6440 */ 6441 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6442 final ApplicationInfo info = pkg.applicationInfo; 6443 final String codePath = pkg.codePath; 6444 final File codeFile = new File(codePath); 6445 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6446 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6447 6448 info.nativeLibraryRootDir = null; 6449 info.nativeLibraryRootRequiresIsa = false; 6450 info.nativeLibraryDir = null; 6451 info.secondaryNativeLibraryDir = null; 6452 6453 if (isApkFile(codeFile)) { 6454 // Monolithic install 6455 if (bundledApp) { 6456 // If "/system/lib64/apkname" exists, assume that is the per-package 6457 // native library directory to use; otherwise use "/system/lib/apkname". 6458 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6459 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6460 getPrimaryInstructionSet(info)); 6461 6462 // This is a bundled system app so choose the path based on the ABI. 6463 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6464 // is just the default path. 6465 final String apkName = deriveCodePathName(codePath); 6466 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6467 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6468 apkName).getAbsolutePath(); 6469 6470 if (info.secondaryCpuAbi != null) { 6471 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6472 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6473 secondaryLibDir, apkName).getAbsolutePath(); 6474 } 6475 } else if (asecApp) { 6476 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6477 .getAbsolutePath(); 6478 } else { 6479 final String apkName = deriveCodePathName(codePath); 6480 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6481 .getAbsolutePath(); 6482 } 6483 6484 info.nativeLibraryRootRequiresIsa = false; 6485 info.nativeLibraryDir = info.nativeLibraryRootDir; 6486 } else { 6487 // Cluster install 6488 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6489 info.nativeLibraryRootRequiresIsa = true; 6490 6491 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6492 getPrimaryInstructionSet(info)).getAbsolutePath(); 6493 6494 if (info.secondaryCpuAbi != null) { 6495 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6496 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6497 } 6498 } 6499 } 6500 6501 /** 6502 * Calculate the abis and roots for a bundled app. These can uniquely 6503 * be determined from the contents of the system partition, i.e whether 6504 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6505 * of this information, and instead assume that the system was built 6506 * sensibly. 6507 */ 6508 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6509 PackageSetting pkgSetting) { 6510 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6511 6512 // If "/system/lib64/apkname" exists, assume that is the per-package 6513 // native library directory to use; otherwise use "/system/lib/apkname". 6514 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6515 setBundledAppAbi(pkg, apkRoot, apkName); 6516 // pkgSetting might be null during rescan following uninstall of updates 6517 // to a bundled app, so accommodate that possibility. The settings in 6518 // that case will be established later from the parsed package. 6519 // 6520 // If the settings aren't null, sync them up with what we've just derived. 6521 // note that apkRoot isn't stored in the package settings. 6522 if (pkgSetting != null) { 6523 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6524 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6525 } 6526 } 6527 6528 /** 6529 * Deduces the ABI of a bundled app and sets the relevant fields on the 6530 * parsed pkg object. 6531 * 6532 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6533 * under which system libraries are installed. 6534 * @param apkName the name of the installed package. 6535 */ 6536 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6537 final File codeFile = new File(pkg.codePath); 6538 6539 final boolean has64BitLibs; 6540 final boolean has32BitLibs; 6541 if (isApkFile(codeFile)) { 6542 // Monolithic install 6543 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6544 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6545 } else { 6546 // Cluster install 6547 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6548 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6549 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6550 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6551 has64BitLibs = (new File(rootDir, isa)).exists(); 6552 } else { 6553 has64BitLibs = false; 6554 } 6555 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6556 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6557 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6558 has32BitLibs = (new File(rootDir, isa)).exists(); 6559 } else { 6560 has32BitLibs = false; 6561 } 6562 } 6563 6564 if (has64BitLibs && !has32BitLibs) { 6565 // The package has 64 bit libs, but not 32 bit libs. Its primary 6566 // ABI should be 64 bit. We can safely assume here that the bundled 6567 // native libraries correspond to the most preferred ABI in the list. 6568 6569 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6570 pkg.applicationInfo.secondaryCpuAbi = null; 6571 } else if (has32BitLibs && !has64BitLibs) { 6572 // The package has 32 bit libs but not 64 bit libs. Its primary 6573 // ABI should be 32 bit. 6574 6575 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6576 pkg.applicationInfo.secondaryCpuAbi = null; 6577 } else if (has32BitLibs && has64BitLibs) { 6578 // The application has both 64 and 32 bit bundled libraries. We check 6579 // here that the app declares multiArch support, and warn if it doesn't. 6580 // 6581 // We will be lenient here and record both ABIs. The primary will be the 6582 // ABI that's higher on the list, i.e, a device that's configured to prefer 6583 // 64 bit apps will see a 64 bit primary ABI, 6584 6585 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6586 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6587 } 6588 6589 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6590 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6591 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6592 } else { 6593 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6594 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6595 } 6596 } else { 6597 pkg.applicationInfo.primaryCpuAbi = null; 6598 pkg.applicationInfo.secondaryCpuAbi = null; 6599 } 6600 } 6601 6602 private void killApplication(String pkgName, int appId, String reason) { 6603 // Request the ActivityManager to kill the process(only for existing packages) 6604 // so that we do not end up in a confused state while the user is still using the older 6605 // version of the application while the new one gets installed. 6606 IActivityManager am = ActivityManagerNative.getDefault(); 6607 if (am != null) { 6608 try { 6609 am.killApplicationWithAppId(pkgName, appId, reason); 6610 } catch (RemoteException e) { 6611 } 6612 } 6613 } 6614 6615 void removePackageLI(PackageSetting ps, boolean chatty) { 6616 if (DEBUG_INSTALL) { 6617 if (chatty) 6618 Log.d(TAG, "Removing package " + ps.name); 6619 } 6620 6621 // writer 6622 synchronized (mPackages) { 6623 mPackages.remove(ps.name); 6624 final PackageParser.Package pkg = ps.pkg; 6625 if (pkg != null) { 6626 cleanPackageDataStructuresLILPw(pkg, chatty); 6627 } 6628 } 6629 } 6630 6631 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6632 if (DEBUG_INSTALL) { 6633 if (chatty) 6634 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6635 } 6636 6637 // writer 6638 synchronized (mPackages) { 6639 mPackages.remove(pkg.applicationInfo.packageName); 6640 cleanPackageDataStructuresLILPw(pkg, chatty); 6641 } 6642 } 6643 6644 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6645 int N = pkg.providers.size(); 6646 StringBuilder r = null; 6647 int i; 6648 for (i=0; i<N; i++) { 6649 PackageParser.Provider p = pkg.providers.get(i); 6650 mProviders.removeProvider(p); 6651 if (p.info.authority == null) { 6652 6653 /* There was another ContentProvider with this authority when 6654 * this app was installed so this authority is null, 6655 * Ignore it as we don't have to unregister the provider. 6656 */ 6657 continue; 6658 } 6659 String names[] = p.info.authority.split(";"); 6660 for (int j = 0; j < names.length; j++) { 6661 if (mProvidersByAuthority.get(names[j]) == p) { 6662 mProvidersByAuthority.remove(names[j]); 6663 if (DEBUG_REMOVE) { 6664 if (chatty) 6665 Log.d(TAG, "Unregistered content provider: " + names[j] 6666 + ", className = " + p.info.name + ", isSyncable = " 6667 + p.info.isSyncable); 6668 } 6669 } 6670 } 6671 if (DEBUG_REMOVE && chatty) { 6672 if (r == null) { 6673 r = new StringBuilder(256); 6674 } else { 6675 r.append(' '); 6676 } 6677 r.append(p.info.name); 6678 } 6679 } 6680 if (r != null) { 6681 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6682 } 6683 6684 N = pkg.services.size(); 6685 r = null; 6686 for (i=0; i<N; i++) { 6687 PackageParser.Service s = pkg.services.get(i); 6688 mServices.removeService(s); 6689 if (chatty) { 6690 if (r == null) { 6691 r = new StringBuilder(256); 6692 } else { 6693 r.append(' '); 6694 } 6695 r.append(s.info.name); 6696 } 6697 } 6698 if (r != null) { 6699 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6700 } 6701 6702 N = pkg.receivers.size(); 6703 r = null; 6704 for (i=0; i<N; i++) { 6705 PackageParser.Activity a = pkg.receivers.get(i); 6706 mReceivers.removeActivity(a, "receiver"); 6707 if (DEBUG_REMOVE && chatty) { 6708 if (r == null) { 6709 r = new StringBuilder(256); 6710 } else { 6711 r.append(' '); 6712 } 6713 r.append(a.info.name); 6714 } 6715 } 6716 if (r != null) { 6717 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6718 } 6719 6720 N = pkg.activities.size(); 6721 r = null; 6722 for (i=0; i<N; i++) { 6723 PackageParser.Activity a = pkg.activities.get(i); 6724 mActivities.removeActivity(a, "activity"); 6725 if (DEBUG_REMOVE && chatty) { 6726 if (r == null) { 6727 r = new StringBuilder(256); 6728 } else { 6729 r.append(' '); 6730 } 6731 r.append(a.info.name); 6732 } 6733 } 6734 if (r != null) { 6735 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6736 } 6737 6738 N = pkg.permissions.size(); 6739 r = null; 6740 for (i=0; i<N; i++) { 6741 PackageParser.Permission p = pkg.permissions.get(i); 6742 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6743 if (bp == null) { 6744 bp = mSettings.mPermissionTrees.get(p.info.name); 6745 } 6746 if (bp != null && bp.perm == p) { 6747 bp.perm = null; 6748 if (DEBUG_REMOVE && chatty) { 6749 if (r == null) { 6750 r = new StringBuilder(256); 6751 } else { 6752 r.append(' '); 6753 } 6754 r.append(p.info.name); 6755 } 6756 } 6757 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6758 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6759 if (appOpPerms != null) { 6760 appOpPerms.remove(pkg.packageName); 6761 } 6762 } 6763 } 6764 if (r != null) { 6765 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6766 } 6767 6768 N = pkg.requestedPermissions.size(); 6769 r = null; 6770 for (i=0; i<N; i++) { 6771 String perm = pkg.requestedPermissions.get(i); 6772 BasePermission bp = mSettings.mPermissions.get(perm); 6773 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6774 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6775 if (appOpPerms != null) { 6776 appOpPerms.remove(pkg.packageName); 6777 if (appOpPerms.isEmpty()) { 6778 mAppOpPermissionPackages.remove(perm); 6779 } 6780 } 6781 } 6782 } 6783 if (r != null) { 6784 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6785 } 6786 6787 N = pkg.instrumentation.size(); 6788 r = null; 6789 for (i=0; i<N; i++) { 6790 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6791 mInstrumentation.remove(a.getComponentName()); 6792 if (DEBUG_REMOVE && chatty) { 6793 if (r == null) { 6794 r = new StringBuilder(256); 6795 } else { 6796 r.append(' '); 6797 } 6798 r.append(a.info.name); 6799 } 6800 } 6801 if (r != null) { 6802 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6803 } 6804 6805 r = null; 6806 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6807 // Only system apps can hold shared libraries. 6808 if (pkg.libraryNames != null) { 6809 for (i=0; i<pkg.libraryNames.size(); i++) { 6810 String name = pkg.libraryNames.get(i); 6811 SharedLibraryEntry cur = mSharedLibraries.get(name); 6812 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6813 mSharedLibraries.remove(name); 6814 if (DEBUG_REMOVE && chatty) { 6815 if (r == null) { 6816 r = new StringBuilder(256); 6817 } else { 6818 r.append(' '); 6819 } 6820 r.append(name); 6821 } 6822 } 6823 } 6824 } 6825 } 6826 if (r != null) { 6827 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6828 } 6829 } 6830 6831 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6832 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6833 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6834 return true; 6835 } 6836 } 6837 return false; 6838 } 6839 6840 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6841 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6842 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6843 6844 private void updatePermissionsLPw(String changingPkg, 6845 PackageParser.Package pkgInfo, int flags) { 6846 // Make sure there are no dangling permission trees. 6847 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6848 while (it.hasNext()) { 6849 final BasePermission bp = it.next(); 6850 if (bp.packageSetting == null) { 6851 // We may not yet have parsed the package, so just see if 6852 // we still know about its settings. 6853 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6854 } 6855 if (bp.packageSetting == null) { 6856 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6857 + " from package " + bp.sourcePackage); 6858 it.remove(); 6859 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6860 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6861 Slog.i(TAG, "Removing old permission tree: " + bp.name 6862 + " from package " + bp.sourcePackage); 6863 flags |= UPDATE_PERMISSIONS_ALL; 6864 it.remove(); 6865 } 6866 } 6867 } 6868 6869 // Make sure all dynamic permissions have been assigned to a package, 6870 // and make sure there are no dangling permissions. 6871 it = mSettings.mPermissions.values().iterator(); 6872 while (it.hasNext()) { 6873 final BasePermission bp = it.next(); 6874 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6875 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6876 + bp.name + " pkg=" + bp.sourcePackage 6877 + " info=" + bp.pendingInfo); 6878 if (bp.packageSetting == null && bp.pendingInfo != null) { 6879 final BasePermission tree = findPermissionTreeLP(bp.name); 6880 if (tree != null && tree.perm != null) { 6881 bp.packageSetting = tree.packageSetting; 6882 bp.perm = new PackageParser.Permission(tree.perm.owner, 6883 new PermissionInfo(bp.pendingInfo)); 6884 bp.perm.info.packageName = tree.perm.info.packageName; 6885 bp.perm.info.name = bp.name; 6886 bp.uid = tree.uid; 6887 } 6888 } 6889 } 6890 if (bp.packageSetting == null) { 6891 // We may not yet have parsed the package, so just see if 6892 // we still know about its settings. 6893 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6894 } 6895 if (bp.packageSetting == null) { 6896 Slog.w(TAG, "Removing dangling permission: " + bp.name 6897 + " from package " + bp.sourcePackage); 6898 it.remove(); 6899 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6900 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6901 Slog.i(TAG, "Removing old permission: " + bp.name 6902 + " from package " + bp.sourcePackage); 6903 flags |= UPDATE_PERMISSIONS_ALL; 6904 it.remove(); 6905 } 6906 } 6907 } 6908 6909 // Now update the permissions for all packages, in particular 6910 // replace the granted permissions of the system packages. 6911 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6912 for (PackageParser.Package pkg : mPackages.values()) { 6913 if (pkg != pkgInfo) { 6914 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6915 changingPkg); 6916 } 6917 } 6918 } 6919 6920 if (pkgInfo != null) { 6921 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6922 } 6923 } 6924 6925 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6926 String packageOfInterest) { 6927 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6928 if (ps == null) { 6929 return; 6930 } 6931 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6932 ArraySet<String> origPermissions = gp.grantedPermissions; 6933 boolean changedPermission = false; 6934 6935 if (replace) { 6936 ps.permissionsFixed = false; 6937 if (gp == ps) { 6938 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6939 gp.grantedPermissions.clear(); 6940 gp.gids = mGlobalGids; 6941 } 6942 } 6943 6944 if (gp.gids == null) { 6945 gp.gids = mGlobalGids; 6946 } 6947 6948 final int N = pkg.requestedPermissions.size(); 6949 for (int i=0; i<N; i++) { 6950 final String name = pkg.requestedPermissions.get(i); 6951 final boolean required = pkg.requestedPermissionsRequired.get(i); 6952 final BasePermission bp = mSettings.mPermissions.get(name); 6953 if (DEBUG_INSTALL) { 6954 if (gp != ps) { 6955 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6956 } 6957 } 6958 6959 if (bp == null || bp.packageSetting == null) { 6960 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6961 Slog.w(TAG, "Unknown permission " + name 6962 + " in package " + pkg.packageName); 6963 } 6964 continue; 6965 } 6966 6967 final String perm = bp.name; 6968 boolean allowed; 6969 boolean allowedSig = false; 6970 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6971 // Keep track of app op permissions. 6972 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6973 if (pkgs == null) { 6974 pkgs = new ArraySet<>(); 6975 mAppOpPermissionPackages.put(bp.name, pkgs); 6976 } 6977 pkgs.add(pkg.packageName); 6978 } 6979 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6980 if (level == PermissionInfo.PROTECTION_NORMAL 6981 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6982 // We grant a normal or dangerous permission if any of the following 6983 // are true: 6984 // 1) The permission is required 6985 // 2) The permission is optional, but was granted in the past 6986 // 3) The permission is optional, but was requested by an 6987 // app in /system (not /data) 6988 // 6989 // Otherwise, reject the permission. 6990 allowed = (required || origPermissions.contains(perm) 6991 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6992 } else if (bp.packageSetting == null) { 6993 // This permission is invalid; skip it. 6994 allowed = false; 6995 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6996 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6997 if (allowed) { 6998 allowedSig = true; 6999 } 7000 } else { 7001 allowed = false; 7002 } 7003 if (DEBUG_INSTALL) { 7004 if (gp != ps) { 7005 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7006 } 7007 } 7008 if (allowed) { 7009 if (!isSystemApp(ps) && ps.permissionsFixed) { 7010 // If this is an existing, non-system package, then 7011 // we can't add any new permissions to it. 7012 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7013 // Except... if this is a permission that was added 7014 // to the platform (note: need to only do this when 7015 // updating the platform). 7016 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7017 } 7018 } 7019 if (allowed) { 7020 if (!gp.grantedPermissions.contains(perm)) { 7021 changedPermission = true; 7022 gp.grantedPermissions.add(perm); 7023 gp.gids = appendInts(gp.gids, bp.gids); 7024 } else if (!ps.haveGids) { 7025 gp.gids = appendInts(gp.gids, bp.gids); 7026 } 7027 } else { 7028 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7029 Slog.w(TAG, "Not granting permission " + perm 7030 + " to package " + pkg.packageName 7031 + " because it was previously installed without"); 7032 } 7033 } 7034 } else { 7035 if (gp.grantedPermissions.remove(perm)) { 7036 changedPermission = true; 7037 gp.gids = removeInts(gp.gids, bp.gids); 7038 Slog.i(TAG, "Un-granting permission " + perm 7039 + " from package " + pkg.packageName 7040 + " (protectionLevel=" + bp.protectionLevel 7041 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7042 + ")"); 7043 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7044 // Don't print warning for app op permissions, since it is fine for them 7045 // not to be granted, there is a UI for the user to decide. 7046 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7047 Slog.w(TAG, "Not granting permission " + perm 7048 + " to package " + pkg.packageName 7049 + " (protectionLevel=" + bp.protectionLevel 7050 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7051 + ")"); 7052 } 7053 } 7054 } 7055 } 7056 7057 if ((changedPermission || replace) && !ps.permissionsFixed && 7058 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7059 // This is the first that we have heard about this package, so the 7060 // permissions we have now selected are fixed until explicitly 7061 // changed. 7062 ps.permissionsFixed = true; 7063 } 7064 ps.haveGids = true; 7065 } 7066 7067 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7068 boolean allowed = false; 7069 final int NP = PackageParser.NEW_PERMISSIONS.length; 7070 for (int ip=0; ip<NP; ip++) { 7071 final PackageParser.NewPermissionInfo npi 7072 = PackageParser.NEW_PERMISSIONS[ip]; 7073 if (npi.name.equals(perm) 7074 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7075 allowed = true; 7076 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7077 + pkg.packageName); 7078 break; 7079 } 7080 } 7081 return allowed; 7082 } 7083 7084 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7085 BasePermission bp, ArraySet<String> origPermissions) { 7086 boolean allowed; 7087 allowed = (compareSignatures( 7088 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7089 == PackageManager.SIGNATURE_MATCH) 7090 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7091 == PackageManager.SIGNATURE_MATCH); 7092 if (!allowed && (bp.protectionLevel 7093 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7094 if (isSystemApp(pkg)) { 7095 // For updated system applications, a system permission 7096 // is granted only if it had been defined by the original application. 7097 if (isUpdatedSystemApp(pkg)) { 7098 final PackageSetting sysPs = mSettings 7099 .getDisabledSystemPkgLPr(pkg.packageName); 7100 final GrantedPermissions origGp = sysPs.sharedUser != null 7101 ? sysPs.sharedUser : sysPs; 7102 7103 if (origGp.grantedPermissions.contains(perm)) { 7104 // If the original was granted this permission, we take 7105 // that grant decision as read and propagate it to the 7106 // update. 7107 allowed = true; 7108 } else { 7109 // The system apk may have been updated with an older 7110 // version of the one on the data partition, but which 7111 // granted a new system permission that it didn't have 7112 // before. In this case we do want to allow the app to 7113 // now get the new permission if the ancestral apk is 7114 // privileged to get it. 7115 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7116 for (int j=0; 7117 j<sysPs.pkg.requestedPermissions.size(); j++) { 7118 if (perm.equals( 7119 sysPs.pkg.requestedPermissions.get(j))) { 7120 allowed = true; 7121 break; 7122 } 7123 } 7124 } 7125 } 7126 } else { 7127 allowed = isPrivilegedApp(pkg); 7128 } 7129 } 7130 } 7131 if (!allowed && (bp.protectionLevel 7132 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7133 // For development permissions, a development permission 7134 // is granted only if it was already granted. 7135 allowed = origPermissions.contains(perm); 7136 } 7137 return allowed; 7138 } 7139 7140 final class ActivityIntentResolver 7141 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7142 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7143 boolean defaultOnly, int userId) { 7144 if (!sUserManager.exists(userId)) return null; 7145 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7146 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7147 } 7148 7149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7150 int userId) { 7151 if (!sUserManager.exists(userId)) return null; 7152 mFlags = flags; 7153 return super.queryIntent(intent, resolvedType, 7154 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7155 } 7156 7157 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7158 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7159 if (!sUserManager.exists(userId)) return null; 7160 if (packageActivities == null) { 7161 return null; 7162 } 7163 mFlags = flags; 7164 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7165 final int N = packageActivities.size(); 7166 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7167 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7168 7169 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7170 for (int i = 0; i < N; ++i) { 7171 intentFilters = packageActivities.get(i).intents; 7172 if (intentFilters != null && intentFilters.size() > 0) { 7173 PackageParser.ActivityIntentInfo[] array = 7174 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7175 intentFilters.toArray(array); 7176 listCut.add(array); 7177 } 7178 } 7179 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7180 } 7181 7182 public final void addActivity(PackageParser.Activity a, String type) { 7183 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7184 mActivities.put(a.getComponentName(), a); 7185 if (DEBUG_SHOW_INFO) 7186 Log.v( 7187 TAG, " " + type + " " + 7188 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7189 if (DEBUG_SHOW_INFO) 7190 Log.v(TAG, " Class=" + a.info.name); 7191 final int NI = a.intents.size(); 7192 for (int j=0; j<NI; j++) { 7193 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7194 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7195 intent.setPriority(0); 7196 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7197 + a.className + " with priority > 0, forcing to 0"); 7198 } 7199 if (DEBUG_SHOW_INFO) { 7200 Log.v(TAG, " IntentFilter:"); 7201 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7202 } 7203 if (!intent.debugCheck()) { 7204 Log.w(TAG, "==> For Activity " + a.info.name); 7205 } 7206 addFilter(intent); 7207 } 7208 } 7209 7210 public final void removeActivity(PackageParser.Activity a, String type) { 7211 mActivities.remove(a.getComponentName()); 7212 if (DEBUG_SHOW_INFO) { 7213 Log.v(TAG, " " + type + " " 7214 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7215 : a.info.name) + ":"); 7216 Log.v(TAG, " Class=" + a.info.name); 7217 } 7218 final int NI = a.intents.size(); 7219 for (int j=0; j<NI; j++) { 7220 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7221 if (DEBUG_SHOW_INFO) { 7222 Log.v(TAG, " IntentFilter:"); 7223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7224 } 7225 removeFilter(intent); 7226 } 7227 } 7228 7229 @Override 7230 protected boolean allowFilterResult( 7231 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7232 ActivityInfo filterAi = filter.activity.info; 7233 for (int i=dest.size()-1; i>=0; i--) { 7234 ActivityInfo destAi = dest.get(i).activityInfo; 7235 if (destAi.name == filterAi.name 7236 && destAi.packageName == filterAi.packageName) { 7237 return false; 7238 } 7239 } 7240 return true; 7241 } 7242 7243 @Override 7244 protected ActivityIntentInfo[] newArray(int size) { 7245 return new ActivityIntentInfo[size]; 7246 } 7247 7248 @Override 7249 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7250 if (!sUserManager.exists(userId)) return true; 7251 PackageParser.Package p = filter.activity.owner; 7252 if (p != null) { 7253 PackageSetting ps = (PackageSetting)p.mExtras; 7254 if (ps != null) { 7255 // System apps are never considered stopped for purposes of 7256 // filtering, because there may be no way for the user to 7257 // actually re-launch them. 7258 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7259 && ps.getStopped(userId); 7260 } 7261 } 7262 return false; 7263 } 7264 7265 @Override 7266 protected boolean isPackageForFilter(String packageName, 7267 PackageParser.ActivityIntentInfo info) { 7268 return packageName.equals(info.activity.owner.packageName); 7269 } 7270 7271 @Override 7272 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7273 int match, int userId) { 7274 if (!sUserManager.exists(userId)) return null; 7275 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7276 return null; 7277 } 7278 final PackageParser.Activity activity = info.activity; 7279 if (mSafeMode && (activity.info.applicationInfo.flags 7280 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7281 return null; 7282 } 7283 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7284 if (ps == null) { 7285 return null; 7286 } 7287 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7288 ps.readUserState(userId), userId); 7289 if (ai == null) { 7290 return null; 7291 } 7292 final ResolveInfo res = new ResolveInfo(); 7293 res.activityInfo = ai; 7294 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7295 res.filter = info; 7296 } 7297 res.priority = info.getPriority(); 7298 res.preferredOrder = activity.owner.mPreferredOrder; 7299 //System.out.println("Result: " + res.activityInfo.className + 7300 // " = " + res.priority); 7301 res.match = match; 7302 res.isDefault = info.hasDefault; 7303 res.labelRes = info.labelRes; 7304 res.nonLocalizedLabel = info.nonLocalizedLabel; 7305 if (userNeedsBadging(userId)) { 7306 res.noResourceId = true; 7307 } else { 7308 res.icon = info.icon; 7309 } 7310 res.system = isSystemApp(res.activityInfo.applicationInfo); 7311 return res; 7312 } 7313 7314 @Override 7315 protected void sortResults(List<ResolveInfo> results) { 7316 Collections.sort(results, mResolvePrioritySorter); 7317 } 7318 7319 @Override 7320 protected void dumpFilter(PrintWriter out, String prefix, 7321 PackageParser.ActivityIntentInfo filter) { 7322 out.print(prefix); out.print( 7323 Integer.toHexString(System.identityHashCode(filter.activity))); 7324 out.print(' '); 7325 filter.activity.printComponentShortName(out); 7326 out.print(" filter "); 7327 out.println(Integer.toHexString(System.identityHashCode(filter))); 7328 } 7329 7330// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7331// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7332// final List<ResolveInfo> retList = Lists.newArrayList(); 7333// while (i.hasNext()) { 7334// final ResolveInfo resolveInfo = i.next(); 7335// if (isEnabledLP(resolveInfo.activityInfo)) { 7336// retList.add(resolveInfo); 7337// } 7338// } 7339// return retList; 7340// } 7341 7342 // Keys are String (activity class name), values are Activity. 7343 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7344 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7345 private int mFlags; 7346 } 7347 7348 private final class ServiceIntentResolver 7349 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7350 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7351 boolean defaultOnly, int userId) { 7352 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7353 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7354 } 7355 7356 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7357 int userId) { 7358 if (!sUserManager.exists(userId)) return null; 7359 mFlags = flags; 7360 return super.queryIntent(intent, resolvedType, 7361 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7362 } 7363 7364 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7365 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7366 if (!sUserManager.exists(userId)) return null; 7367 if (packageServices == null) { 7368 return null; 7369 } 7370 mFlags = flags; 7371 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7372 final int N = packageServices.size(); 7373 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7374 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7375 7376 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7377 for (int i = 0; i < N; ++i) { 7378 intentFilters = packageServices.get(i).intents; 7379 if (intentFilters != null && intentFilters.size() > 0) { 7380 PackageParser.ServiceIntentInfo[] array = 7381 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7382 intentFilters.toArray(array); 7383 listCut.add(array); 7384 } 7385 } 7386 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7387 } 7388 7389 public final void addService(PackageParser.Service s) { 7390 mServices.put(s.getComponentName(), s); 7391 if (DEBUG_SHOW_INFO) { 7392 Log.v(TAG, " " 7393 + (s.info.nonLocalizedLabel != null 7394 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7395 Log.v(TAG, " Class=" + s.info.name); 7396 } 7397 final int NI = s.intents.size(); 7398 int j; 7399 for (j=0; j<NI; j++) { 7400 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7401 if (DEBUG_SHOW_INFO) { 7402 Log.v(TAG, " IntentFilter:"); 7403 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7404 } 7405 if (!intent.debugCheck()) { 7406 Log.w(TAG, "==> For Service " + s.info.name); 7407 } 7408 addFilter(intent); 7409 } 7410 } 7411 7412 public final void removeService(PackageParser.Service s) { 7413 mServices.remove(s.getComponentName()); 7414 if (DEBUG_SHOW_INFO) { 7415 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7416 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7417 Log.v(TAG, " Class=" + s.info.name); 7418 } 7419 final int NI = s.intents.size(); 7420 int j; 7421 for (j=0; j<NI; j++) { 7422 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7423 if (DEBUG_SHOW_INFO) { 7424 Log.v(TAG, " IntentFilter:"); 7425 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7426 } 7427 removeFilter(intent); 7428 } 7429 } 7430 7431 @Override 7432 protected boolean allowFilterResult( 7433 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7434 ServiceInfo filterSi = filter.service.info; 7435 for (int i=dest.size()-1; i>=0; i--) { 7436 ServiceInfo destAi = dest.get(i).serviceInfo; 7437 if (destAi.name == filterSi.name 7438 && destAi.packageName == filterSi.packageName) { 7439 return false; 7440 } 7441 } 7442 return true; 7443 } 7444 7445 @Override 7446 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7447 return new PackageParser.ServiceIntentInfo[size]; 7448 } 7449 7450 @Override 7451 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7452 if (!sUserManager.exists(userId)) return true; 7453 PackageParser.Package p = filter.service.owner; 7454 if (p != null) { 7455 PackageSetting ps = (PackageSetting)p.mExtras; 7456 if (ps != null) { 7457 // System apps are never considered stopped for purposes of 7458 // filtering, because there may be no way for the user to 7459 // actually re-launch them. 7460 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7461 && ps.getStopped(userId); 7462 } 7463 } 7464 return false; 7465 } 7466 7467 @Override 7468 protected boolean isPackageForFilter(String packageName, 7469 PackageParser.ServiceIntentInfo info) { 7470 return packageName.equals(info.service.owner.packageName); 7471 } 7472 7473 @Override 7474 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7475 int match, int userId) { 7476 if (!sUserManager.exists(userId)) return null; 7477 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7478 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7479 return null; 7480 } 7481 final PackageParser.Service service = info.service; 7482 if (mSafeMode && (service.info.applicationInfo.flags 7483 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7484 return null; 7485 } 7486 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7487 if (ps == null) { 7488 return null; 7489 } 7490 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7491 ps.readUserState(userId), userId); 7492 if (si == null) { 7493 return null; 7494 } 7495 final ResolveInfo res = new ResolveInfo(); 7496 res.serviceInfo = si; 7497 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7498 res.filter = filter; 7499 } 7500 res.priority = info.getPriority(); 7501 res.preferredOrder = service.owner.mPreferredOrder; 7502 //System.out.println("Result: " + res.activityInfo.className + 7503 // " = " + res.priority); 7504 res.match = match; 7505 res.isDefault = info.hasDefault; 7506 res.labelRes = info.labelRes; 7507 res.nonLocalizedLabel = info.nonLocalizedLabel; 7508 res.icon = info.icon; 7509 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7510 return res; 7511 } 7512 7513 @Override 7514 protected void sortResults(List<ResolveInfo> results) { 7515 Collections.sort(results, mResolvePrioritySorter); 7516 } 7517 7518 @Override 7519 protected void dumpFilter(PrintWriter out, String prefix, 7520 PackageParser.ServiceIntentInfo filter) { 7521 out.print(prefix); out.print( 7522 Integer.toHexString(System.identityHashCode(filter.service))); 7523 out.print(' '); 7524 filter.service.printComponentShortName(out); 7525 out.print(" filter "); 7526 out.println(Integer.toHexString(System.identityHashCode(filter))); 7527 } 7528 7529// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7530// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7531// final List<ResolveInfo> retList = Lists.newArrayList(); 7532// while (i.hasNext()) { 7533// final ResolveInfo resolveInfo = (ResolveInfo) i; 7534// if (isEnabledLP(resolveInfo.serviceInfo)) { 7535// retList.add(resolveInfo); 7536// } 7537// } 7538// return retList; 7539// } 7540 7541 // Keys are String (activity class name), values are Activity. 7542 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7543 = new ArrayMap<ComponentName, PackageParser.Service>(); 7544 private int mFlags; 7545 }; 7546 7547 private final class ProviderIntentResolver 7548 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7549 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7550 boolean defaultOnly, int userId) { 7551 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7552 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7553 } 7554 7555 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7556 int userId) { 7557 if (!sUserManager.exists(userId)) 7558 return null; 7559 mFlags = flags; 7560 return super.queryIntent(intent, resolvedType, 7561 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7562 } 7563 7564 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7565 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7566 if (!sUserManager.exists(userId)) 7567 return null; 7568 if (packageProviders == null) { 7569 return null; 7570 } 7571 mFlags = flags; 7572 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7573 final int N = packageProviders.size(); 7574 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7575 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7576 7577 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7578 for (int i = 0; i < N; ++i) { 7579 intentFilters = packageProviders.get(i).intents; 7580 if (intentFilters != null && intentFilters.size() > 0) { 7581 PackageParser.ProviderIntentInfo[] array = 7582 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7583 intentFilters.toArray(array); 7584 listCut.add(array); 7585 } 7586 } 7587 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7588 } 7589 7590 public final void addProvider(PackageParser.Provider p) { 7591 if (mProviders.containsKey(p.getComponentName())) { 7592 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7593 return; 7594 } 7595 7596 mProviders.put(p.getComponentName(), p); 7597 if (DEBUG_SHOW_INFO) { 7598 Log.v(TAG, " " 7599 + (p.info.nonLocalizedLabel != null 7600 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7601 Log.v(TAG, " Class=" + p.info.name); 7602 } 7603 final int NI = p.intents.size(); 7604 int j; 7605 for (j = 0; j < NI; j++) { 7606 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7607 if (DEBUG_SHOW_INFO) { 7608 Log.v(TAG, " IntentFilter:"); 7609 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7610 } 7611 if (!intent.debugCheck()) { 7612 Log.w(TAG, "==> For Provider " + p.info.name); 7613 } 7614 addFilter(intent); 7615 } 7616 } 7617 7618 public final void removeProvider(PackageParser.Provider p) { 7619 mProviders.remove(p.getComponentName()); 7620 if (DEBUG_SHOW_INFO) { 7621 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7622 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7623 Log.v(TAG, " Class=" + p.info.name); 7624 } 7625 final int NI = p.intents.size(); 7626 int j; 7627 for (j = 0; j < NI; j++) { 7628 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7629 if (DEBUG_SHOW_INFO) { 7630 Log.v(TAG, " IntentFilter:"); 7631 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7632 } 7633 removeFilter(intent); 7634 } 7635 } 7636 7637 @Override 7638 protected boolean allowFilterResult( 7639 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7640 ProviderInfo filterPi = filter.provider.info; 7641 for (int i = dest.size() - 1; i >= 0; i--) { 7642 ProviderInfo destPi = dest.get(i).providerInfo; 7643 if (destPi.name == filterPi.name 7644 && destPi.packageName == filterPi.packageName) { 7645 return false; 7646 } 7647 } 7648 return true; 7649 } 7650 7651 @Override 7652 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7653 return new PackageParser.ProviderIntentInfo[size]; 7654 } 7655 7656 @Override 7657 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7658 if (!sUserManager.exists(userId)) 7659 return true; 7660 PackageParser.Package p = filter.provider.owner; 7661 if (p != null) { 7662 PackageSetting ps = (PackageSetting) p.mExtras; 7663 if (ps != null) { 7664 // System apps are never considered stopped for purposes of 7665 // filtering, because there may be no way for the user to 7666 // actually re-launch them. 7667 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7668 && ps.getStopped(userId); 7669 } 7670 } 7671 return false; 7672 } 7673 7674 @Override 7675 protected boolean isPackageForFilter(String packageName, 7676 PackageParser.ProviderIntentInfo info) { 7677 return packageName.equals(info.provider.owner.packageName); 7678 } 7679 7680 @Override 7681 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7682 int match, int userId) { 7683 if (!sUserManager.exists(userId)) 7684 return null; 7685 final PackageParser.ProviderIntentInfo info = filter; 7686 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7687 return null; 7688 } 7689 final PackageParser.Provider provider = info.provider; 7690 if (mSafeMode && (provider.info.applicationInfo.flags 7691 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7692 return null; 7693 } 7694 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7695 if (ps == null) { 7696 return null; 7697 } 7698 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7699 ps.readUserState(userId), userId); 7700 if (pi == null) { 7701 return null; 7702 } 7703 final ResolveInfo res = new ResolveInfo(); 7704 res.providerInfo = pi; 7705 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7706 res.filter = filter; 7707 } 7708 res.priority = info.getPriority(); 7709 res.preferredOrder = provider.owner.mPreferredOrder; 7710 res.match = match; 7711 res.isDefault = info.hasDefault; 7712 res.labelRes = info.labelRes; 7713 res.nonLocalizedLabel = info.nonLocalizedLabel; 7714 res.icon = info.icon; 7715 res.system = isSystemApp(res.providerInfo.applicationInfo); 7716 return res; 7717 } 7718 7719 @Override 7720 protected void sortResults(List<ResolveInfo> results) { 7721 Collections.sort(results, mResolvePrioritySorter); 7722 } 7723 7724 @Override 7725 protected void dumpFilter(PrintWriter out, String prefix, 7726 PackageParser.ProviderIntentInfo filter) { 7727 out.print(prefix); 7728 out.print( 7729 Integer.toHexString(System.identityHashCode(filter.provider))); 7730 out.print(' '); 7731 filter.provider.printComponentShortName(out); 7732 out.print(" filter "); 7733 out.println(Integer.toHexString(System.identityHashCode(filter))); 7734 } 7735 7736 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7737 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7738 private int mFlags; 7739 }; 7740 7741 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7742 new Comparator<ResolveInfo>() { 7743 public int compare(ResolveInfo r1, ResolveInfo r2) { 7744 int v1 = r1.priority; 7745 int v2 = r2.priority; 7746 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7747 if (v1 != v2) { 7748 return (v1 > v2) ? -1 : 1; 7749 } 7750 v1 = r1.preferredOrder; 7751 v2 = r2.preferredOrder; 7752 if (v1 != v2) { 7753 return (v1 > v2) ? -1 : 1; 7754 } 7755 if (r1.isDefault != r2.isDefault) { 7756 return r1.isDefault ? -1 : 1; 7757 } 7758 v1 = r1.match; 7759 v2 = r2.match; 7760 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7761 if (v1 != v2) { 7762 return (v1 > v2) ? -1 : 1; 7763 } 7764 if (r1.system != r2.system) { 7765 return r1.system ? -1 : 1; 7766 } 7767 return 0; 7768 } 7769 }; 7770 7771 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7772 new Comparator<ProviderInfo>() { 7773 public int compare(ProviderInfo p1, ProviderInfo p2) { 7774 final int v1 = p1.initOrder; 7775 final int v2 = p2.initOrder; 7776 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7777 } 7778 }; 7779 7780 static final void sendPackageBroadcast(String action, String pkg, 7781 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7782 int[] userIds) { 7783 IActivityManager am = ActivityManagerNative.getDefault(); 7784 if (am != null) { 7785 try { 7786 if (userIds == null) { 7787 userIds = am.getRunningUserIds(); 7788 } 7789 for (int id : userIds) { 7790 final Intent intent = new Intent(action, 7791 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7792 if (extras != null) { 7793 intent.putExtras(extras); 7794 } 7795 if (targetPkg != null) { 7796 intent.setPackage(targetPkg); 7797 } 7798 // Modify the UID when posting to other users 7799 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7800 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7801 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7802 intent.putExtra(Intent.EXTRA_UID, uid); 7803 } 7804 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7805 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7806 if (DEBUG_BROADCASTS) { 7807 RuntimeException here = new RuntimeException("here"); 7808 here.fillInStackTrace(); 7809 Slog.d(TAG, "Sending to user " + id + ": " 7810 + intent.toShortString(false, true, false, false) 7811 + " " + intent.getExtras(), here); 7812 } 7813 am.broadcastIntent(null, intent, null, finishedReceiver, 7814 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7815 finishedReceiver != null, false, id); 7816 } 7817 } catch (RemoteException ex) { 7818 } 7819 } 7820 } 7821 7822 /** 7823 * Check if the external storage media is available. This is true if there 7824 * is a mounted external storage medium or if the external storage is 7825 * emulated. 7826 */ 7827 private boolean isExternalMediaAvailable() { 7828 return mMediaMounted || Environment.isExternalStorageEmulated(); 7829 } 7830 7831 @Override 7832 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7833 // writer 7834 synchronized (mPackages) { 7835 if (!isExternalMediaAvailable()) { 7836 // If the external storage is no longer mounted at this point, 7837 // the caller may not have been able to delete all of this 7838 // packages files and can not delete any more. Bail. 7839 return null; 7840 } 7841 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7842 if (lastPackage != null) { 7843 pkgs.remove(lastPackage); 7844 } 7845 if (pkgs.size() > 0) { 7846 return pkgs.get(0); 7847 } 7848 } 7849 return null; 7850 } 7851 7852 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7853 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7854 userId, andCode ? 1 : 0, packageName); 7855 if (mSystemReady) { 7856 msg.sendToTarget(); 7857 } else { 7858 if (mPostSystemReadyMessages == null) { 7859 mPostSystemReadyMessages = new ArrayList<>(); 7860 } 7861 mPostSystemReadyMessages.add(msg); 7862 } 7863 } 7864 7865 void startCleaningPackages() { 7866 // reader 7867 synchronized (mPackages) { 7868 if (!isExternalMediaAvailable()) { 7869 return; 7870 } 7871 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7872 return; 7873 } 7874 } 7875 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7876 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7877 IActivityManager am = ActivityManagerNative.getDefault(); 7878 if (am != null) { 7879 try { 7880 am.startService(null, intent, null, UserHandle.USER_OWNER); 7881 } catch (RemoteException e) { 7882 } 7883 } 7884 } 7885 7886 @Override 7887 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7888 int installFlags, String installerPackageName, VerificationParams verificationParams, 7889 String packageAbiOverride) { 7890 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7891 packageAbiOverride, UserHandle.getCallingUserId()); 7892 } 7893 7894 @Override 7895 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7896 int installFlags, String installerPackageName, VerificationParams verificationParams, 7897 String packageAbiOverride, int userId) { 7898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7899 7900 final int callingUid = Binder.getCallingUid(); 7901 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7902 7903 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7904 try { 7905 if (observer != null) { 7906 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7907 } 7908 } catch (RemoteException re) { 7909 } 7910 return; 7911 } 7912 7913 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7914 installFlags |= PackageManager.INSTALL_FROM_ADB; 7915 7916 } else { 7917 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7918 // about installerPackageName. 7919 7920 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7921 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7922 } 7923 7924 UserHandle user; 7925 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7926 user = UserHandle.ALL; 7927 } else { 7928 user = new UserHandle(userId); 7929 } 7930 7931 verificationParams.setInstallerUid(callingUid); 7932 7933 final File originFile = new File(originPath); 7934 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7935 7936 final Message msg = mHandler.obtainMessage(INIT_COPY); 7937 msg.obj = new InstallParams(origin, observer, installFlags, 7938 installerPackageName, verificationParams, user, packageAbiOverride); 7939 mHandler.sendMessage(msg); 7940 } 7941 7942 void installStage(String packageName, File stagedDir, String stagedCid, 7943 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7944 String installerPackageName, int installerUid, UserHandle user) { 7945 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7946 params.referrerUri, installerUid, null); 7947 7948 final OriginInfo origin; 7949 if (stagedDir != null) { 7950 origin = OriginInfo.fromStagedFile(stagedDir); 7951 } else { 7952 origin = OriginInfo.fromStagedContainer(stagedCid); 7953 } 7954 7955 final Message msg = mHandler.obtainMessage(INIT_COPY); 7956 msg.obj = new InstallParams(origin, observer, params.installFlags, 7957 installerPackageName, verifParams, user, params.abiOverride); 7958 mHandler.sendMessage(msg); 7959 } 7960 7961 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7962 Bundle extras = new Bundle(1); 7963 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7964 7965 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7966 packageName, extras, null, null, new int[] {userId}); 7967 try { 7968 IActivityManager am = ActivityManagerNative.getDefault(); 7969 final boolean isSystem = 7970 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7971 if (isSystem && am.isUserRunning(userId, false)) { 7972 // The just-installed/enabled app is bundled on the system, so presumed 7973 // to be able to run automatically without needing an explicit launch. 7974 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7975 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7976 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7977 .setPackage(packageName); 7978 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7979 android.app.AppOpsManager.OP_NONE, false, false, userId); 7980 } 7981 } catch (RemoteException e) { 7982 // shouldn't happen 7983 Slog.w(TAG, "Unable to bootstrap installed package", e); 7984 } 7985 } 7986 7987 @Override 7988 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7989 int userId) { 7990 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7991 PackageSetting pkgSetting; 7992 final int uid = Binder.getCallingUid(); 7993 enforceCrossUserPermission(uid, userId, true, true, 7994 "setApplicationHiddenSetting for user " + userId); 7995 7996 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7997 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7998 return false; 7999 } 8000 8001 long callingId = Binder.clearCallingIdentity(); 8002 try { 8003 boolean sendAdded = false; 8004 boolean sendRemoved = false; 8005 // writer 8006 synchronized (mPackages) { 8007 pkgSetting = mSettings.mPackages.get(packageName); 8008 if (pkgSetting == null) { 8009 return false; 8010 } 8011 if (pkgSetting.getHidden(userId) != hidden) { 8012 pkgSetting.setHidden(hidden, userId); 8013 mSettings.writePackageRestrictionsLPr(userId); 8014 if (hidden) { 8015 sendRemoved = true; 8016 } else { 8017 sendAdded = true; 8018 } 8019 } 8020 } 8021 if (sendAdded) { 8022 sendPackageAddedForUser(packageName, pkgSetting, userId); 8023 return true; 8024 } 8025 if (sendRemoved) { 8026 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8027 "hiding pkg"); 8028 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8029 } 8030 } finally { 8031 Binder.restoreCallingIdentity(callingId); 8032 } 8033 return false; 8034 } 8035 8036 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8037 int userId) { 8038 final PackageRemovedInfo info = new PackageRemovedInfo(); 8039 info.removedPackage = packageName; 8040 info.removedUsers = new int[] {userId}; 8041 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8042 info.sendBroadcast(false, false, false); 8043 } 8044 8045 /** 8046 * Returns true if application is not found or there was an error. Otherwise it returns 8047 * the hidden state of the package for the given user. 8048 */ 8049 @Override 8050 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8052 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8053 false, "getApplicationHidden for user " + userId); 8054 PackageSetting pkgSetting; 8055 long callingId = Binder.clearCallingIdentity(); 8056 try { 8057 // writer 8058 synchronized (mPackages) { 8059 pkgSetting = mSettings.mPackages.get(packageName); 8060 if (pkgSetting == null) { 8061 return true; 8062 } 8063 return pkgSetting.getHidden(userId); 8064 } 8065 } finally { 8066 Binder.restoreCallingIdentity(callingId); 8067 } 8068 } 8069 8070 /** 8071 * @hide 8072 */ 8073 @Override 8074 public int installExistingPackageAsUser(String packageName, int userId) { 8075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8076 null); 8077 PackageSetting pkgSetting; 8078 final int uid = Binder.getCallingUid(); 8079 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8080 + userId); 8081 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8082 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8083 } 8084 8085 long callingId = Binder.clearCallingIdentity(); 8086 try { 8087 boolean sendAdded = false; 8088 Bundle extras = new Bundle(1); 8089 8090 // writer 8091 synchronized (mPackages) { 8092 pkgSetting = mSettings.mPackages.get(packageName); 8093 if (pkgSetting == null) { 8094 return PackageManager.INSTALL_FAILED_INVALID_URI; 8095 } 8096 if (!pkgSetting.getInstalled(userId)) { 8097 pkgSetting.setInstalled(true, userId); 8098 pkgSetting.setHidden(false, userId); 8099 mSettings.writePackageRestrictionsLPr(userId); 8100 sendAdded = true; 8101 } 8102 } 8103 8104 if (sendAdded) { 8105 sendPackageAddedForUser(packageName, pkgSetting, userId); 8106 } 8107 } finally { 8108 Binder.restoreCallingIdentity(callingId); 8109 } 8110 8111 return PackageManager.INSTALL_SUCCEEDED; 8112 } 8113 8114 boolean isUserRestricted(int userId, String restrictionKey) { 8115 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8116 if (restrictions.getBoolean(restrictionKey, false)) { 8117 Log.w(TAG, "User is restricted: " + restrictionKey); 8118 return true; 8119 } 8120 return false; 8121 } 8122 8123 @Override 8124 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8125 mContext.enforceCallingOrSelfPermission( 8126 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8127 "Only package verification agents can verify applications"); 8128 8129 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8130 final PackageVerificationResponse response = new PackageVerificationResponse( 8131 verificationCode, Binder.getCallingUid()); 8132 msg.arg1 = id; 8133 msg.obj = response; 8134 mHandler.sendMessage(msg); 8135 } 8136 8137 @Override 8138 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8139 long millisecondsToDelay) { 8140 mContext.enforceCallingOrSelfPermission( 8141 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8142 "Only package verification agents can extend verification timeouts"); 8143 8144 final PackageVerificationState state = mPendingVerification.get(id); 8145 final PackageVerificationResponse response = new PackageVerificationResponse( 8146 verificationCodeAtTimeout, Binder.getCallingUid()); 8147 8148 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8149 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8150 } 8151 if (millisecondsToDelay < 0) { 8152 millisecondsToDelay = 0; 8153 } 8154 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8155 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8156 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8157 } 8158 8159 if ((state != null) && !state.timeoutExtended()) { 8160 state.extendTimeout(); 8161 8162 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8163 msg.arg1 = id; 8164 msg.obj = response; 8165 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8166 } 8167 } 8168 8169 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8170 int verificationCode, UserHandle user) { 8171 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8172 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8173 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8174 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8175 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8176 8177 mContext.sendBroadcastAsUser(intent, user, 8178 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8179 } 8180 8181 private ComponentName matchComponentForVerifier(String packageName, 8182 List<ResolveInfo> receivers) { 8183 ActivityInfo targetReceiver = null; 8184 8185 final int NR = receivers.size(); 8186 for (int i = 0; i < NR; i++) { 8187 final ResolveInfo info = receivers.get(i); 8188 if (info.activityInfo == null) { 8189 continue; 8190 } 8191 8192 if (packageName.equals(info.activityInfo.packageName)) { 8193 targetReceiver = info.activityInfo; 8194 break; 8195 } 8196 } 8197 8198 if (targetReceiver == null) { 8199 return null; 8200 } 8201 8202 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8203 } 8204 8205 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8206 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8207 if (pkgInfo.verifiers.length == 0) { 8208 return null; 8209 } 8210 8211 final int N = pkgInfo.verifiers.length; 8212 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8213 for (int i = 0; i < N; i++) { 8214 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8215 8216 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8217 receivers); 8218 if (comp == null) { 8219 continue; 8220 } 8221 8222 final int verifierUid = getUidForVerifier(verifierInfo); 8223 if (verifierUid == -1) { 8224 continue; 8225 } 8226 8227 if (DEBUG_VERIFY) { 8228 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8229 + " with the correct signature"); 8230 } 8231 sufficientVerifiers.add(comp); 8232 verificationState.addSufficientVerifier(verifierUid); 8233 } 8234 8235 return sufficientVerifiers; 8236 } 8237 8238 private int getUidForVerifier(VerifierInfo verifierInfo) { 8239 synchronized (mPackages) { 8240 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8241 if (pkg == null) { 8242 return -1; 8243 } else if (pkg.mSignatures.length != 1) { 8244 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8245 + " has more than one signature; ignoring"); 8246 return -1; 8247 } 8248 8249 /* 8250 * If the public key of the package's signature does not match 8251 * our expected public key, then this is a different package and 8252 * we should skip. 8253 */ 8254 8255 final byte[] expectedPublicKey; 8256 try { 8257 final Signature verifierSig = pkg.mSignatures[0]; 8258 final PublicKey publicKey = verifierSig.getPublicKey(); 8259 expectedPublicKey = publicKey.getEncoded(); 8260 } catch (CertificateException e) { 8261 return -1; 8262 } 8263 8264 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8265 8266 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8267 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8268 + " does not have the expected public key; ignoring"); 8269 return -1; 8270 } 8271 8272 return pkg.applicationInfo.uid; 8273 } 8274 } 8275 8276 @Override 8277 public void finishPackageInstall(int token) { 8278 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8279 8280 if (DEBUG_INSTALL) { 8281 Slog.v(TAG, "BM finishing package install for " + token); 8282 } 8283 8284 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8285 mHandler.sendMessage(msg); 8286 } 8287 8288 /** 8289 * Get the verification agent timeout. 8290 * 8291 * @return verification timeout in milliseconds 8292 */ 8293 private long getVerificationTimeout() { 8294 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8295 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8296 DEFAULT_VERIFICATION_TIMEOUT); 8297 } 8298 8299 /** 8300 * Get the default verification agent response code. 8301 * 8302 * @return default verification response code 8303 */ 8304 private int getDefaultVerificationResponse() { 8305 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8306 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8307 DEFAULT_VERIFICATION_RESPONSE); 8308 } 8309 8310 /** 8311 * Check whether or not package verification has been enabled. 8312 * 8313 * @return true if verification should be performed 8314 */ 8315 private boolean isVerificationEnabled(int userId, int installFlags) { 8316 if (!DEFAULT_VERIFY_ENABLE) { 8317 return false; 8318 } 8319 8320 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8321 8322 // Check if installing from ADB 8323 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8324 // Do not run verification in a test harness environment 8325 if (ActivityManager.isRunningInTestHarness()) { 8326 return false; 8327 } 8328 if (ensureVerifyAppsEnabled) { 8329 return true; 8330 } 8331 // Check if the developer does not want package verification for ADB installs 8332 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8333 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8334 return false; 8335 } 8336 } 8337 8338 if (ensureVerifyAppsEnabled) { 8339 return true; 8340 } 8341 8342 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8343 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8344 } 8345 8346 /** 8347 * Get the "allow unknown sources" setting. 8348 * 8349 * @return the current "allow unknown sources" setting 8350 */ 8351 private int getUnknownSourcesSettings() { 8352 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8353 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8354 -1); 8355 } 8356 8357 @Override 8358 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8359 final int uid = Binder.getCallingUid(); 8360 // writer 8361 synchronized (mPackages) { 8362 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8363 if (targetPackageSetting == null) { 8364 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8365 } 8366 8367 PackageSetting installerPackageSetting; 8368 if (installerPackageName != null) { 8369 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8370 if (installerPackageSetting == null) { 8371 throw new IllegalArgumentException("Unknown installer package: " 8372 + installerPackageName); 8373 } 8374 } else { 8375 installerPackageSetting = null; 8376 } 8377 8378 Signature[] callerSignature; 8379 Object obj = mSettings.getUserIdLPr(uid); 8380 if (obj != null) { 8381 if (obj instanceof SharedUserSetting) { 8382 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8383 } else if (obj instanceof PackageSetting) { 8384 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8385 } else { 8386 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8387 } 8388 } else { 8389 throw new SecurityException("Unknown calling uid " + uid); 8390 } 8391 8392 // Verify: can't set installerPackageName to a package that is 8393 // not signed with the same cert as the caller. 8394 if (installerPackageSetting != null) { 8395 if (compareSignatures(callerSignature, 8396 installerPackageSetting.signatures.mSignatures) 8397 != PackageManager.SIGNATURE_MATCH) { 8398 throw new SecurityException( 8399 "Caller does not have same cert as new installer package " 8400 + installerPackageName); 8401 } 8402 } 8403 8404 // Verify: if target already has an installer package, it must 8405 // be signed with the same cert as the caller. 8406 if (targetPackageSetting.installerPackageName != null) { 8407 PackageSetting setting = mSettings.mPackages.get( 8408 targetPackageSetting.installerPackageName); 8409 // If the currently set package isn't valid, then it's always 8410 // okay to change it. 8411 if (setting != null) { 8412 if (compareSignatures(callerSignature, 8413 setting.signatures.mSignatures) 8414 != PackageManager.SIGNATURE_MATCH) { 8415 throw new SecurityException( 8416 "Caller does not have same cert as old installer package " 8417 + targetPackageSetting.installerPackageName); 8418 } 8419 } 8420 } 8421 8422 // Okay! 8423 targetPackageSetting.installerPackageName = installerPackageName; 8424 scheduleWriteSettingsLocked(); 8425 } 8426 } 8427 8428 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8429 // Queue up an async operation since the package installation may take a little while. 8430 mHandler.post(new Runnable() { 8431 public void run() { 8432 mHandler.removeCallbacks(this); 8433 // Result object to be returned 8434 PackageInstalledInfo res = new PackageInstalledInfo(); 8435 res.returnCode = currentStatus; 8436 res.uid = -1; 8437 res.pkg = null; 8438 res.removedInfo = new PackageRemovedInfo(); 8439 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8440 args.doPreInstall(res.returnCode); 8441 synchronized (mInstallLock) { 8442 installPackageLI(args, res); 8443 } 8444 args.doPostInstall(res.returnCode, res.uid); 8445 } 8446 8447 // A restore should be performed at this point if (a) the install 8448 // succeeded, (b) the operation is not an update, and (c) the new 8449 // package has not opted out of backup participation. 8450 final boolean update = res.removedInfo.removedPackage != null; 8451 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8452 boolean doRestore = !update 8453 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8454 8455 // Set up the post-install work request bookkeeping. This will be used 8456 // and cleaned up by the post-install event handling regardless of whether 8457 // there's a restore pass performed. Token values are >= 1. 8458 int token; 8459 if (mNextInstallToken < 0) mNextInstallToken = 1; 8460 token = mNextInstallToken++; 8461 8462 PostInstallData data = new PostInstallData(args, res); 8463 mRunningInstalls.put(token, data); 8464 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8465 8466 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8467 // Pass responsibility to the Backup Manager. It will perform a 8468 // restore if appropriate, then pass responsibility back to the 8469 // Package Manager to run the post-install observer callbacks 8470 // and broadcasts. 8471 IBackupManager bm = IBackupManager.Stub.asInterface( 8472 ServiceManager.getService(Context.BACKUP_SERVICE)); 8473 if (bm != null) { 8474 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8475 + " to BM for possible restore"); 8476 try { 8477 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8478 } catch (RemoteException e) { 8479 // can't happen; the backup manager is local 8480 } catch (Exception e) { 8481 Slog.e(TAG, "Exception trying to enqueue restore", e); 8482 doRestore = false; 8483 } 8484 } else { 8485 Slog.e(TAG, "Backup Manager not found!"); 8486 doRestore = false; 8487 } 8488 } 8489 8490 if (!doRestore) { 8491 // No restore possible, or the Backup Manager was mysteriously not 8492 // available -- just fire the post-install work request directly. 8493 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8494 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8495 mHandler.sendMessage(msg); 8496 } 8497 } 8498 }); 8499 } 8500 8501 private abstract class HandlerParams { 8502 private static final int MAX_RETRIES = 4; 8503 8504 /** 8505 * Number of times startCopy() has been attempted and had a non-fatal 8506 * error. 8507 */ 8508 private int mRetries = 0; 8509 8510 /** User handle for the user requesting the information or installation. */ 8511 private final UserHandle mUser; 8512 8513 HandlerParams(UserHandle user) { 8514 mUser = user; 8515 } 8516 8517 UserHandle getUser() { 8518 return mUser; 8519 } 8520 8521 final boolean startCopy() { 8522 boolean res; 8523 try { 8524 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8525 8526 if (++mRetries > MAX_RETRIES) { 8527 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8528 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8529 handleServiceError(); 8530 return false; 8531 } else { 8532 handleStartCopy(); 8533 res = true; 8534 } 8535 } catch (RemoteException e) { 8536 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8537 mHandler.sendEmptyMessage(MCS_RECONNECT); 8538 res = false; 8539 } 8540 handleReturnCode(); 8541 return res; 8542 } 8543 8544 final void serviceError() { 8545 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8546 handleServiceError(); 8547 handleReturnCode(); 8548 } 8549 8550 abstract void handleStartCopy() throws RemoteException; 8551 abstract void handleServiceError(); 8552 abstract void handleReturnCode(); 8553 } 8554 8555 class MeasureParams extends HandlerParams { 8556 private final PackageStats mStats; 8557 private boolean mSuccess; 8558 8559 private final IPackageStatsObserver mObserver; 8560 8561 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8562 super(new UserHandle(stats.userHandle)); 8563 mObserver = observer; 8564 mStats = stats; 8565 } 8566 8567 @Override 8568 public String toString() { 8569 return "MeasureParams{" 8570 + Integer.toHexString(System.identityHashCode(this)) 8571 + " " + mStats.packageName + "}"; 8572 } 8573 8574 @Override 8575 void handleStartCopy() throws RemoteException { 8576 synchronized (mInstallLock) { 8577 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8578 } 8579 8580 if (mSuccess) { 8581 final boolean mounted; 8582 if (Environment.isExternalStorageEmulated()) { 8583 mounted = true; 8584 } else { 8585 final String status = Environment.getExternalStorageState(); 8586 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8587 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8588 } 8589 8590 if (mounted) { 8591 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8592 8593 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8594 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8595 8596 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8597 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8598 8599 // Always subtract cache size, since it's a subdirectory 8600 mStats.externalDataSize -= mStats.externalCacheSize; 8601 8602 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8603 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8604 8605 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8606 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8607 } 8608 } 8609 } 8610 8611 @Override 8612 void handleReturnCode() { 8613 if (mObserver != null) { 8614 try { 8615 mObserver.onGetStatsCompleted(mStats, mSuccess); 8616 } catch (RemoteException e) { 8617 Slog.i(TAG, "Observer no longer exists."); 8618 } 8619 } 8620 } 8621 8622 @Override 8623 void handleServiceError() { 8624 Slog.e(TAG, "Could not measure application " + mStats.packageName 8625 + " external storage"); 8626 } 8627 } 8628 8629 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8630 throws RemoteException { 8631 long result = 0; 8632 for (File path : paths) { 8633 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8634 } 8635 return result; 8636 } 8637 8638 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8639 for (File path : paths) { 8640 try { 8641 mcs.clearDirectory(path.getAbsolutePath()); 8642 } catch (RemoteException e) { 8643 } 8644 } 8645 } 8646 8647 static class OriginInfo { 8648 /** 8649 * Location where install is coming from, before it has been 8650 * copied/renamed into place. This could be a single monolithic APK 8651 * file, or a cluster directory. This location may be untrusted. 8652 */ 8653 final File file; 8654 final String cid; 8655 8656 /** 8657 * Flag indicating that {@link #file} or {@link #cid} has already been 8658 * staged, meaning downstream users don't need to defensively copy the 8659 * contents. 8660 */ 8661 final boolean staged; 8662 8663 /** 8664 * Flag indicating that {@link #file} or {@link #cid} is an already 8665 * installed app that is being moved. 8666 */ 8667 final boolean existing; 8668 8669 final String resolvedPath; 8670 final File resolvedFile; 8671 8672 static OriginInfo fromNothing() { 8673 return new OriginInfo(null, null, false, false); 8674 } 8675 8676 static OriginInfo fromUntrustedFile(File file) { 8677 return new OriginInfo(file, null, false, false); 8678 } 8679 8680 static OriginInfo fromExistingFile(File file) { 8681 return new OriginInfo(file, null, false, true); 8682 } 8683 8684 static OriginInfo fromStagedFile(File file) { 8685 return new OriginInfo(file, null, true, false); 8686 } 8687 8688 static OriginInfo fromStagedContainer(String cid) { 8689 return new OriginInfo(null, cid, true, false); 8690 } 8691 8692 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8693 this.file = file; 8694 this.cid = cid; 8695 this.staged = staged; 8696 this.existing = existing; 8697 8698 if (cid != null) { 8699 resolvedPath = PackageHelper.getSdDir(cid); 8700 resolvedFile = new File(resolvedPath); 8701 } else if (file != null) { 8702 resolvedPath = file.getAbsolutePath(); 8703 resolvedFile = file; 8704 } else { 8705 resolvedPath = null; 8706 resolvedFile = null; 8707 } 8708 } 8709 } 8710 8711 class InstallParams extends HandlerParams { 8712 final OriginInfo origin; 8713 final IPackageInstallObserver2 observer; 8714 int installFlags; 8715 final String installerPackageName; 8716 final VerificationParams verificationParams; 8717 private InstallArgs mArgs; 8718 private int mRet; 8719 final String packageAbiOverride; 8720 8721 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8722 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8723 String packageAbiOverride) { 8724 super(user); 8725 this.origin = origin; 8726 this.observer = observer; 8727 this.installFlags = installFlags; 8728 this.installerPackageName = installerPackageName; 8729 this.verificationParams = verificationParams; 8730 this.packageAbiOverride = packageAbiOverride; 8731 } 8732 8733 @Override 8734 public String toString() { 8735 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8736 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8737 } 8738 8739 public ManifestDigest getManifestDigest() { 8740 if (verificationParams == null) { 8741 return null; 8742 } 8743 return verificationParams.getManifestDigest(); 8744 } 8745 8746 private int installLocationPolicy(PackageInfoLite pkgLite) { 8747 String packageName = pkgLite.packageName; 8748 int installLocation = pkgLite.installLocation; 8749 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8750 // reader 8751 synchronized (mPackages) { 8752 PackageParser.Package pkg = mPackages.get(packageName); 8753 if (pkg != null) { 8754 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8755 // Check for downgrading. 8756 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8757 if (pkgLite.versionCode < pkg.mVersionCode) { 8758 Slog.w(TAG, "Can't install update of " + packageName 8759 + " update version " + pkgLite.versionCode 8760 + " is older than installed version " 8761 + pkg.mVersionCode); 8762 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8763 } 8764 } 8765 // Check for updated system application. 8766 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8767 if (onSd) { 8768 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8769 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8770 } 8771 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8772 } else { 8773 if (onSd) { 8774 // Install flag overrides everything. 8775 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8776 } 8777 // If current upgrade specifies particular preference 8778 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8779 // Application explicitly specified internal. 8780 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8781 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8782 // App explictly prefers external. Let policy decide 8783 } else { 8784 // Prefer previous location 8785 if (isExternal(pkg)) { 8786 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8787 } 8788 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8789 } 8790 } 8791 } else { 8792 // Invalid install. Return error code 8793 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8794 } 8795 } 8796 } 8797 // All the special cases have been taken care of. 8798 // Return result based on recommended install location. 8799 if (onSd) { 8800 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8801 } 8802 return pkgLite.recommendedInstallLocation; 8803 } 8804 8805 /* 8806 * Invoke remote method to get package information and install 8807 * location values. Override install location based on default 8808 * policy if needed and then create install arguments based 8809 * on the install location. 8810 */ 8811 public void handleStartCopy() throws RemoteException { 8812 int ret = PackageManager.INSTALL_SUCCEEDED; 8813 8814 // If we're already staged, we've firmly committed to an install location 8815 if (origin.staged) { 8816 if (origin.file != null) { 8817 installFlags |= PackageManager.INSTALL_INTERNAL; 8818 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8819 } else if (origin.cid != null) { 8820 installFlags |= PackageManager.INSTALL_EXTERNAL; 8821 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8822 } else { 8823 throw new IllegalStateException("Invalid stage location"); 8824 } 8825 } 8826 8827 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8828 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8829 8830 PackageInfoLite pkgLite = null; 8831 8832 if (onInt && onSd) { 8833 // Check if both bits are set. 8834 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8835 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8836 } else { 8837 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8838 packageAbiOverride); 8839 8840 /* 8841 * If we have too little free space, try to free cache 8842 * before giving up. 8843 */ 8844 if (!origin.staged && pkgLite.recommendedInstallLocation 8845 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8846 // TODO: focus freeing disk space on the target device 8847 final StorageManager storage = StorageManager.from(mContext); 8848 final long lowThreshold = storage.getStorageLowBytes( 8849 Environment.getDataDirectory()); 8850 8851 final long sizeBytes = mContainerService.calculateInstalledSize( 8852 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8853 8854 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8855 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8856 installFlags, packageAbiOverride); 8857 } 8858 8859 /* 8860 * The cache free must have deleted the file we 8861 * downloaded to install. 8862 * 8863 * TODO: fix the "freeCache" call to not delete 8864 * the file we care about. 8865 */ 8866 if (pkgLite.recommendedInstallLocation 8867 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8868 pkgLite.recommendedInstallLocation 8869 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8870 } 8871 } 8872 } 8873 8874 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8875 int loc = pkgLite.recommendedInstallLocation; 8876 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8877 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8878 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8879 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8880 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8881 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8882 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8883 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8884 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8885 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8886 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8887 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8888 } else { 8889 // Override with defaults if needed. 8890 loc = installLocationPolicy(pkgLite); 8891 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8892 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8893 } else if (!onSd && !onInt) { 8894 // Override install location with flags 8895 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8896 // Set the flag to install on external media. 8897 installFlags |= PackageManager.INSTALL_EXTERNAL; 8898 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8899 } else { 8900 // Make sure the flag for installing on external 8901 // media is unset 8902 installFlags |= PackageManager.INSTALL_INTERNAL; 8903 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8904 } 8905 } 8906 } 8907 } 8908 8909 final InstallArgs args = createInstallArgs(this); 8910 mArgs = args; 8911 8912 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8913 /* 8914 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8915 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8916 */ 8917 int userIdentifier = getUser().getIdentifier(); 8918 if (userIdentifier == UserHandle.USER_ALL 8919 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8920 userIdentifier = UserHandle.USER_OWNER; 8921 } 8922 8923 /* 8924 * Determine if we have any installed package verifiers. If we 8925 * do, then we'll defer to them to verify the packages. 8926 */ 8927 final int requiredUid = mRequiredVerifierPackage == null ? -1 8928 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8929 if (!origin.existing && requiredUid != -1 8930 && isVerificationEnabled(userIdentifier, installFlags)) { 8931 final Intent verification = new Intent( 8932 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8933 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8934 PACKAGE_MIME_TYPE); 8935 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8936 8937 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8938 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8939 0 /* TODO: Which userId? */); 8940 8941 if (DEBUG_VERIFY) { 8942 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8943 + verification.toString() + " with " + pkgLite.verifiers.length 8944 + " optional verifiers"); 8945 } 8946 8947 final int verificationId = mPendingVerificationToken++; 8948 8949 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8950 8951 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8952 installerPackageName); 8953 8954 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8955 installFlags); 8956 8957 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8958 pkgLite.packageName); 8959 8960 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8961 pkgLite.versionCode); 8962 8963 if (verificationParams != null) { 8964 if (verificationParams.getVerificationURI() != null) { 8965 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8966 verificationParams.getVerificationURI()); 8967 } 8968 if (verificationParams.getOriginatingURI() != null) { 8969 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8970 verificationParams.getOriginatingURI()); 8971 } 8972 if (verificationParams.getReferrer() != null) { 8973 verification.putExtra(Intent.EXTRA_REFERRER, 8974 verificationParams.getReferrer()); 8975 } 8976 if (verificationParams.getOriginatingUid() >= 0) { 8977 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8978 verificationParams.getOriginatingUid()); 8979 } 8980 if (verificationParams.getInstallerUid() >= 0) { 8981 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8982 verificationParams.getInstallerUid()); 8983 } 8984 } 8985 8986 final PackageVerificationState verificationState = new PackageVerificationState( 8987 requiredUid, args); 8988 8989 mPendingVerification.append(verificationId, verificationState); 8990 8991 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8992 receivers, verificationState); 8993 8994 /* 8995 * If any sufficient verifiers were listed in the package 8996 * manifest, attempt to ask them. 8997 */ 8998 if (sufficientVerifiers != null) { 8999 final int N = sufficientVerifiers.size(); 9000 if (N == 0) { 9001 Slog.i(TAG, "Additional verifiers required, but none installed."); 9002 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9003 } else { 9004 for (int i = 0; i < N; i++) { 9005 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9006 9007 final Intent sufficientIntent = new Intent(verification); 9008 sufficientIntent.setComponent(verifierComponent); 9009 9010 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9011 } 9012 } 9013 } 9014 9015 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9016 mRequiredVerifierPackage, receivers); 9017 if (ret == PackageManager.INSTALL_SUCCEEDED 9018 && mRequiredVerifierPackage != null) { 9019 /* 9020 * Send the intent to the required verification agent, 9021 * but only start the verification timeout after the 9022 * target BroadcastReceivers have run. 9023 */ 9024 verification.setComponent(requiredVerifierComponent); 9025 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9026 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9027 new BroadcastReceiver() { 9028 @Override 9029 public void onReceive(Context context, Intent intent) { 9030 final Message msg = mHandler 9031 .obtainMessage(CHECK_PENDING_VERIFICATION); 9032 msg.arg1 = verificationId; 9033 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9034 } 9035 }, null, 0, null, null); 9036 9037 /* 9038 * We don't want the copy to proceed until verification 9039 * succeeds, so null out this field. 9040 */ 9041 mArgs = null; 9042 } 9043 } else { 9044 /* 9045 * No package verification is enabled, so immediately start 9046 * the remote call to initiate copy using temporary file. 9047 */ 9048 ret = args.copyApk(mContainerService, true); 9049 } 9050 } 9051 9052 mRet = ret; 9053 } 9054 9055 @Override 9056 void handleReturnCode() { 9057 // If mArgs is null, then MCS couldn't be reached. When it 9058 // reconnects, it will try again to install. At that point, this 9059 // will succeed. 9060 if (mArgs != null) { 9061 processPendingInstall(mArgs, mRet); 9062 } 9063 } 9064 9065 @Override 9066 void handleServiceError() { 9067 mArgs = createInstallArgs(this); 9068 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9069 } 9070 9071 public boolean isForwardLocked() { 9072 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9073 } 9074 } 9075 9076 /** 9077 * Used during creation of InstallArgs 9078 * 9079 * @param installFlags package installation flags 9080 * @return true if should be installed on external storage 9081 */ 9082 private static boolean installOnSd(int installFlags) { 9083 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9084 return false; 9085 } 9086 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9087 return true; 9088 } 9089 return false; 9090 } 9091 9092 /** 9093 * Used during creation of InstallArgs 9094 * 9095 * @param installFlags package installation flags 9096 * @return true if should be installed as forward locked 9097 */ 9098 private static boolean installForwardLocked(int installFlags) { 9099 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9100 } 9101 9102 private InstallArgs createInstallArgs(InstallParams params) { 9103 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9104 return new AsecInstallArgs(params); 9105 } else { 9106 return new FileInstallArgs(params); 9107 } 9108 } 9109 9110 /** 9111 * Create args that describe an existing installed package. Typically used 9112 * when cleaning up old installs, or used as a move source. 9113 */ 9114 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9115 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9116 final boolean isInAsec; 9117 if (installOnSd(installFlags)) { 9118 /* Apps on SD card are always in ASEC containers. */ 9119 isInAsec = true; 9120 } else if (installForwardLocked(installFlags) 9121 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9122 /* 9123 * Forward-locked apps are only in ASEC containers if they're the 9124 * new style 9125 */ 9126 isInAsec = true; 9127 } else { 9128 isInAsec = false; 9129 } 9130 9131 if (isInAsec) { 9132 return new AsecInstallArgs(codePath, instructionSets, 9133 installOnSd(installFlags), installForwardLocked(installFlags)); 9134 } else { 9135 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9136 instructionSets); 9137 } 9138 } 9139 9140 static abstract class InstallArgs { 9141 /** @see InstallParams#origin */ 9142 final OriginInfo origin; 9143 9144 final IPackageInstallObserver2 observer; 9145 // Always refers to PackageManager flags only 9146 final int installFlags; 9147 final String installerPackageName; 9148 final ManifestDigest manifestDigest; 9149 final UserHandle user; 9150 final String abiOverride; 9151 9152 // The list of instruction sets supported by this app. This is currently 9153 // only used during the rmdex() phase to clean up resources. We can get rid of this 9154 // if we move dex files under the common app path. 9155 /* nullable */ String[] instructionSets; 9156 9157 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9158 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9159 String[] instructionSets, String abiOverride) { 9160 this.origin = origin; 9161 this.installFlags = installFlags; 9162 this.observer = observer; 9163 this.installerPackageName = installerPackageName; 9164 this.manifestDigest = manifestDigest; 9165 this.user = user; 9166 this.instructionSets = instructionSets; 9167 this.abiOverride = abiOverride; 9168 } 9169 9170 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9171 abstract int doPreInstall(int status); 9172 9173 /** 9174 * Rename package into final resting place. All paths on the given 9175 * scanned package should be updated to reflect the rename. 9176 */ 9177 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9178 abstract int doPostInstall(int status, int uid); 9179 9180 /** @see PackageSettingBase#codePathString */ 9181 abstract String getCodePath(); 9182 /** @see PackageSettingBase#resourcePathString */ 9183 abstract String getResourcePath(); 9184 abstract String getLegacyNativeLibraryPath(); 9185 9186 // Need installer lock especially for dex file removal. 9187 abstract void cleanUpResourcesLI(); 9188 abstract boolean doPostDeleteLI(boolean delete); 9189 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9190 9191 /** 9192 * Called before the source arguments are copied. This is used mostly 9193 * for MoveParams when it needs to read the source file to put it in the 9194 * destination. 9195 */ 9196 int doPreCopy() { 9197 return PackageManager.INSTALL_SUCCEEDED; 9198 } 9199 9200 /** 9201 * Called after the source arguments are copied. This is used mostly for 9202 * MoveParams when it needs to read the source file to put it in the 9203 * destination. 9204 * 9205 * @return 9206 */ 9207 int doPostCopy(int uid) { 9208 return PackageManager.INSTALL_SUCCEEDED; 9209 } 9210 9211 protected boolean isFwdLocked() { 9212 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9213 } 9214 9215 protected boolean isExternal() { 9216 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9217 } 9218 9219 UserHandle getUser() { 9220 return user; 9221 } 9222 } 9223 9224 /** 9225 * Logic to handle installation of non-ASEC applications, including copying 9226 * and renaming logic. 9227 */ 9228 class FileInstallArgs extends InstallArgs { 9229 private File codeFile; 9230 private File resourceFile; 9231 private File legacyNativeLibraryPath; 9232 9233 // Example topology: 9234 // /data/app/com.example/base.apk 9235 // /data/app/com.example/split_foo.apk 9236 // /data/app/com.example/lib/arm/libfoo.so 9237 // /data/app/com.example/lib/arm64/libfoo.so 9238 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9239 9240 /** New install */ 9241 FileInstallArgs(InstallParams params) { 9242 super(params.origin, params.observer, params.installFlags, 9243 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9244 null /* instruction sets */, params.packageAbiOverride); 9245 if (isFwdLocked()) { 9246 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9247 } 9248 } 9249 9250 /** Existing install */ 9251 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9252 String[] instructionSets) { 9253 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9254 this.codeFile = (codePath != null) ? new File(codePath) : null; 9255 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9256 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9257 new File(legacyNativeLibraryPath) : null; 9258 } 9259 9260 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9261 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9262 isFwdLocked(), abiOverride); 9263 9264 final StorageManager storage = StorageManager.from(mContext); 9265 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9266 } 9267 9268 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9269 if (origin.staged) { 9270 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9271 codeFile = origin.file; 9272 resourceFile = origin.file; 9273 return PackageManager.INSTALL_SUCCEEDED; 9274 } 9275 9276 try { 9277 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9278 codeFile = tempDir; 9279 resourceFile = tempDir; 9280 } catch (IOException e) { 9281 Slog.w(TAG, "Failed to create copy file: " + e); 9282 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9283 } 9284 9285 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9286 @Override 9287 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9288 if (!FileUtils.isValidExtFilename(name)) { 9289 throw new IllegalArgumentException("Invalid filename: " + name); 9290 } 9291 try { 9292 final File file = new File(codeFile, name); 9293 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9294 O_RDWR | O_CREAT, 0644); 9295 Os.chmod(file.getAbsolutePath(), 0644); 9296 return new ParcelFileDescriptor(fd); 9297 } catch (ErrnoException e) { 9298 throw new RemoteException("Failed to open: " + e.getMessage()); 9299 } 9300 } 9301 }; 9302 9303 int ret = PackageManager.INSTALL_SUCCEEDED; 9304 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9305 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9306 Slog.e(TAG, "Failed to copy package"); 9307 return ret; 9308 } 9309 9310 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9311 NativeLibraryHelper.Handle handle = null; 9312 try { 9313 handle = NativeLibraryHelper.Handle.create(codeFile); 9314 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9315 abiOverride); 9316 } catch (IOException e) { 9317 Slog.e(TAG, "Copying native libraries failed", e); 9318 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9319 } finally { 9320 IoUtils.closeQuietly(handle); 9321 } 9322 9323 return ret; 9324 } 9325 9326 int doPreInstall(int status) { 9327 if (status != PackageManager.INSTALL_SUCCEEDED) { 9328 cleanUp(); 9329 } 9330 return status; 9331 } 9332 9333 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9334 if (status != PackageManager.INSTALL_SUCCEEDED) { 9335 cleanUp(); 9336 return false; 9337 } else { 9338 final File beforeCodeFile = codeFile; 9339 final File afterCodeFile = getNextCodePath(pkg.packageName); 9340 9341 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9342 try { 9343 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9344 } catch (ErrnoException e) { 9345 Slog.d(TAG, "Failed to rename", e); 9346 return false; 9347 } 9348 9349 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9350 Slog.d(TAG, "Failed to restorecon"); 9351 return false; 9352 } 9353 9354 // Reflect the rename internally 9355 codeFile = afterCodeFile; 9356 resourceFile = afterCodeFile; 9357 9358 // Reflect the rename in scanned details 9359 pkg.codePath = afterCodeFile.getAbsolutePath(); 9360 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9361 pkg.baseCodePath); 9362 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9363 pkg.splitCodePaths); 9364 9365 // Reflect the rename in app info 9366 pkg.applicationInfo.setCodePath(pkg.codePath); 9367 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9368 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9369 pkg.applicationInfo.setResourcePath(pkg.codePath); 9370 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9371 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9372 9373 return true; 9374 } 9375 } 9376 9377 int doPostInstall(int status, int uid) { 9378 if (status != PackageManager.INSTALL_SUCCEEDED) { 9379 cleanUp(); 9380 } 9381 return status; 9382 } 9383 9384 @Override 9385 String getCodePath() { 9386 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9387 } 9388 9389 @Override 9390 String getResourcePath() { 9391 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9392 } 9393 9394 @Override 9395 String getLegacyNativeLibraryPath() { 9396 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9397 } 9398 9399 private boolean cleanUp() { 9400 if (codeFile == null || !codeFile.exists()) { 9401 return false; 9402 } 9403 9404 if (codeFile.isDirectory()) { 9405 FileUtils.deleteContents(codeFile); 9406 } 9407 codeFile.delete(); 9408 9409 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9410 resourceFile.delete(); 9411 } 9412 9413 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9414 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9415 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9416 } 9417 legacyNativeLibraryPath.delete(); 9418 } 9419 9420 return true; 9421 } 9422 9423 void cleanUpResourcesLI() { 9424 // Try enumerating all code paths before deleting 9425 List<String> allCodePaths = Collections.EMPTY_LIST; 9426 if (codeFile != null && codeFile.exists()) { 9427 try { 9428 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9429 allCodePaths = pkg.getAllCodePaths(); 9430 } catch (PackageParserException e) { 9431 // Ignored; we tried our best 9432 } 9433 } 9434 9435 cleanUp(); 9436 9437 if (!allCodePaths.isEmpty()) { 9438 if (instructionSets == null) { 9439 throw new IllegalStateException("instructionSet == null"); 9440 } 9441 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9442 for (String codePath : allCodePaths) { 9443 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9444 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9445 if (retCode < 0) { 9446 Slog.w(TAG, "Couldn't remove dex file for package: " 9447 + " at location " + codePath + ", retcode=" + retCode); 9448 // we don't consider this to be a failure of the core package deletion 9449 } 9450 } 9451 } 9452 } 9453 } 9454 9455 boolean doPostDeleteLI(boolean delete) { 9456 // XXX err, shouldn't we respect the delete flag? 9457 cleanUpResourcesLI(); 9458 return true; 9459 } 9460 } 9461 9462 private boolean isAsecExternal(String cid) { 9463 final String asecPath = PackageHelper.getSdFilesystem(cid); 9464 return !asecPath.startsWith(mAsecInternalPath); 9465 } 9466 9467 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9468 PackageManagerException { 9469 if (copyRet < 0) { 9470 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9471 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9472 throw new PackageManagerException(copyRet, message); 9473 } 9474 } 9475 } 9476 9477 /** 9478 * Extract the MountService "container ID" from the full code path of an 9479 * .apk. 9480 */ 9481 static String cidFromCodePath(String fullCodePath) { 9482 int eidx = fullCodePath.lastIndexOf("/"); 9483 String subStr1 = fullCodePath.substring(0, eidx); 9484 int sidx = subStr1.lastIndexOf("/"); 9485 return subStr1.substring(sidx+1, eidx); 9486 } 9487 9488 /** 9489 * Logic to handle installation of ASEC applications, including copying and 9490 * renaming logic. 9491 */ 9492 class AsecInstallArgs extends InstallArgs { 9493 static final String RES_FILE_NAME = "pkg.apk"; 9494 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9495 9496 String cid; 9497 String packagePath; 9498 String resourcePath; 9499 String legacyNativeLibraryDir; 9500 9501 /** New install */ 9502 AsecInstallArgs(InstallParams params) { 9503 super(params.origin, params.observer, params.installFlags, 9504 params.installerPackageName, params.getManifestDigest(), 9505 params.getUser(), null /* instruction sets */, 9506 params.packageAbiOverride); 9507 } 9508 9509 /** Existing install */ 9510 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9511 boolean isExternal, boolean isForwardLocked) { 9512 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9513 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9514 instructionSets, null); 9515 // Hackily pretend we're still looking at a full code path 9516 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9517 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9518 } 9519 9520 // Extract cid from fullCodePath 9521 int eidx = fullCodePath.lastIndexOf("/"); 9522 String subStr1 = fullCodePath.substring(0, eidx); 9523 int sidx = subStr1.lastIndexOf("/"); 9524 cid = subStr1.substring(sidx+1, eidx); 9525 setMountPath(subStr1); 9526 } 9527 9528 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9529 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9530 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9531 instructionSets, null); 9532 this.cid = cid; 9533 setMountPath(PackageHelper.getSdDir(cid)); 9534 } 9535 9536 void createCopyFile() { 9537 cid = mInstallerService.allocateExternalStageCidLegacy(); 9538 } 9539 9540 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9541 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9542 abiOverride); 9543 9544 final File target; 9545 if (isExternal()) { 9546 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9547 } else { 9548 target = Environment.getDataDirectory(); 9549 } 9550 9551 final StorageManager storage = StorageManager.from(mContext); 9552 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9553 } 9554 9555 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9556 if (origin.staged) { 9557 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9558 cid = origin.cid; 9559 setMountPath(PackageHelper.getSdDir(cid)); 9560 return PackageManager.INSTALL_SUCCEEDED; 9561 } 9562 9563 if (temp) { 9564 createCopyFile(); 9565 } else { 9566 /* 9567 * Pre-emptively destroy the container since it's destroyed if 9568 * copying fails due to it existing anyway. 9569 */ 9570 PackageHelper.destroySdDir(cid); 9571 } 9572 9573 final String newMountPath = imcs.copyPackageToContainer( 9574 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9575 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9576 9577 if (newMountPath != null) { 9578 setMountPath(newMountPath); 9579 return PackageManager.INSTALL_SUCCEEDED; 9580 } else { 9581 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9582 } 9583 } 9584 9585 @Override 9586 String getCodePath() { 9587 return packagePath; 9588 } 9589 9590 @Override 9591 String getResourcePath() { 9592 return resourcePath; 9593 } 9594 9595 @Override 9596 String getLegacyNativeLibraryPath() { 9597 return legacyNativeLibraryDir; 9598 } 9599 9600 int doPreInstall(int status) { 9601 if (status != PackageManager.INSTALL_SUCCEEDED) { 9602 // Destroy container 9603 PackageHelper.destroySdDir(cid); 9604 } else { 9605 boolean mounted = PackageHelper.isContainerMounted(cid); 9606 if (!mounted) { 9607 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9608 Process.SYSTEM_UID); 9609 if (newMountPath != null) { 9610 setMountPath(newMountPath); 9611 } else { 9612 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9613 } 9614 } 9615 } 9616 return status; 9617 } 9618 9619 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9620 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9621 String newMountPath = null; 9622 if (PackageHelper.isContainerMounted(cid)) { 9623 // Unmount the container 9624 if (!PackageHelper.unMountSdDir(cid)) { 9625 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9626 return false; 9627 } 9628 } 9629 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9630 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9631 " which might be stale. Will try to clean up."); 9632 // Clean up the stale container and proceed to recreate. 9633 if (!PackageHelper.destroySdDir(newCacheId)) { 9634 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9635 return false; 9636 } 9637 // Successfully cleaned up stale container. Try to rename again. 9638 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9639 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9640 + " inspite of cleaning it up."); 9641 return false; 9642 } 9643 } 9644 if (!PackageHelper.isContainerMounted(newCacheId)) { 9645 Slog.w(TAG, "Mounting container " + newCacheId); 9646 newMountPath = PackageHelper.mountSdDir(newCacheId, 9647 getEncryptKey(), Process.SYSTEM_UID); 9648 } else { 9649 newMountPath = PackageHelper.getSdDir(newCacheId); 9650 } 9651 if (newMountPath == null) { 9652 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9653 return false; 9654 } 9655 Log.i(TAG, "Succesfully renamed " + cid + 9656 " to " + newCacheId + 9657 " at new path: " + newMountPath); 9658 cid = newCacheId; 9659 9660 final File beforeCodeFile = new File(packagePath); 9661 setMountPath(newMountPath); 9662 final File afterCodeFile = new File(packagePath); 9663 9664 // Reflect the rename in scanned details 9665 pkg.codePath = afterCodeFile.getAbsolutePath(); 9666 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9667 pkg.baseCodePath); 9668 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9669 pkg.splitCodePaths); 9670 9671 // Reflect the rename in app info 9672 pkg.applicationInfo.setCodePath(pkg.codePath); 9673 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9674 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9675 pkg.applicationInfo.setResourcePath(pkg.codePath); 9676 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9677 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9678 9679 return true; 9680 } 9681 9682 private void setMountPath(String mountPath) { 9683 final File mountFile = new File(mountPath); 9684 9685 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9686 if (monolithicFile.exists()) { 9687 packagePath = monolithicFile.getAbsolutePath(); 9688 if (isFwdLocked()) { 9689 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9690 } else { 9691 resourcePath = packagePath; 9692 } 9693 } else { 9694 packagePath = mountFile.getAbsolutePath(); 9695 resourcePath = packagePath; 9696 } 9697 9698 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9699 } 9700 9701 int doPostInstall(int status, int uid) { 9702 if (status != PackageManager.INSTALL_SUCCEEDED) { 9703 cleanUp(); 9704 } else { 9705 final int groupOwner; 9706 final String protectedFile; 9707 if (isFwdLocked()) { 9708 groupOwner = UserHandle.getSharedAppGid(uid); 9709 protectedFile = RES_FILE_NAME; 9710 } else { 9711 groupOwner = -1; 9712 protectedFile = null; 9713 } 9714 9715 if (uid < Process.FIRST_APPLICATION_UID 9716 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9717 Slog.e(TAG, "Failed to finalize " + cid); 9718 PackageHelper.destroySdDir(cid); 9719 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9720 } 9721 9722 boolean mounted = PackageHelper.isContainerMounted(cid); 9723 if (!mounted) { 9724 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9725 } 9726 } 9727 return status; 9728 } 9729 9730 private void cleanUp() { 9731 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9732 9733 // Destroy secure container 9734 PackageHelper.destroySdDir(cid); 9735 } 9736 9737 private List<String> getAllCodePaths() { 9738 final File codeFile = new File(getCodePath()); 9739 if (codeFile != null && codeFile.exists()) { 9740 try { 9741 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9742 return pkg.getAllCodePaths(); 9743 } catch (PackageParserException e) { 9744 // Ignored; we tried our best 9745 } 9746 } 9747 return Collections.EMPTY_LIST; 9748 } 9749 9750 void cleanUpResourcesLI() { 9751 // Enumerate all code paths before deleting 9752 cleanUpResourcesLI(getAllCodePaths()); 9753 } 9754 9755 private void cleanUpResourcesLI(List<String> allCodePaths) { 9756 cleanUp(); 9757 9758 if (!allCodePaths.isEmpty()) { 9759 if (instructionSets == null) { 9760 throw new IllegalStateException("instructionSet == null"); 9761 } 9762 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9763 for (String codePath : allCodePaths) { 9764 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9765 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9766 if (retCode < 0) { 9767 Slog.w(TAG, "Couldn't remove dex file for package: " 9768 + " at location " + codePath + ", retcode=" + retCode); 9769 // we don't consider this to be a failure of the core package deletion 9770 } 9771 } 9772 } 9773 } 9774 } 9775 9776 boolean matchContainer(String app) { 9777 if (cid.startsWith(app)) { 9778 return true; 9779 } 9780 return false; 9781 } 9782 9783 String getPackageName() { 9784 return getAsecPackageName(cid); 9785 } 9786 9787 boolean doPostDeleteLI(boolean delete) { 9788 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9789 final List<String> allCodePaths = getAllCodePaths(); 9790 boolean mounted = PackageHelper.isContainerMounted(cid); 9791 if (mounted) { 9792 // Unmount first 9793 if (PackageHelper.unMountSdDir(cid)) { 9794 mounted = false; 9795 } 9796 } 9797 if (!mounted && delete) { 9798 cleanUpResourcesLI(allCodePaths); 9799 } 9800 return !mounted; 9801 } 9802 9803 @Override 9804 int doPreCopy() { 9805 if (isFwdLocked()) { 9806 if (!PackageHelper.fixSdPermissions(cid, 9807 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9808 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9809 } 9810 } 9811 9812 return PackageManager.INSTALL_SUCCEEDED; 9813 } 9814 9815 @Override 9816 int doPostCopy(int uid) { 9817 if (isFwdLocked()) { 9818 if (uid < Process.FIRST_APPLICATION_UID 9819 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9820 RES_FILE_NAME)) { 9821 Slog.e(TAG, "Failed to finalize " + cid); 9822 PackageHelper.destroySdDir(cid); 9823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9824 } 9825 } 9826 9827 return PackageManager.INSTALL_SUCCEEDED; 9828 } 9829 } 9830 9831 static String getAsecPackageName(String packageCid) { 9832 int idx = packageCid.lastIndexOf("-"); 9833 if (idx == -1) { 9834 return packageCid; 9835 } 9836 return packageCid.substring(0, idx); 9837 } 9838 9839 // Utility method used to create code paths based on package name and available index. 9840 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9841 String idxStr = ""; 9842 int idx = 1; 9843 // Fall back to default value of idx=1 if prefix is not 9844 // part of oldCodePath 9845 if (oldCodePath != null) { 9846 String subStr = oldCodePath; 9847 // Drop the suffix right away 9848 if (suffix != null && subStr.endsWith(suffix)) { 9849 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9850 } 9851 // If oldCodePath already contains prefix find out the 9852 // ending index to either increment or decrement. 9853 int sidx = subStr.lastIndexOf(prefix); 9854 if (sidx != -1) { 9855 subStr = subStr.substring(sidx + prefix.length()); 9856 if (subStr != null) { 9857 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9858 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9859 } 9860 try { 9861 idx = Integer.parseInt(subStr); 9862 if (idx <= 1) { 9863 idx++; 9864 } else { 9865 idx--; 9866 } 9867 } catch(NumberFormatException e) { 9868 } 9869 } 9870 } 9871 } 9872 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9873 return prefix + idxStr; 9874 } 9875 9876 private File getNextCodePath(String packageName) { 9877 int suffix = 1; 9878 File result; 9879 do { 9880 result = new File(mAppInstallDir, packageName + "-" + suffix); 9881 suffix++; 9882 } while (result.exists()); 9883 return result; 9884 } 9885 9886 // Utility method used to ignore ADD/REMOVE events 9887 // by directory observer. 9888 private static boolean ignoreCodePath(String fullPathStr) { 9889 String apkName = deriveCodePathName(fullPathStr); 9890 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9891 if (idx != -1 && ((idx+1) < apkName.length())) { 9892 // Make sure the package ends with a numeral 9893 String version = apkName.substring(idx+1); 9894 try { 9895 Integer.parseInt(version); 9896 return true; 9897 } catch (NumberFormatException e) {} 9898 } 9899 return false; 9900 } 9901 9902 // Utility method that returns the relative package path with respect 9903 // to the installation directory. Like say for /data/data/com.test-1.apk 9904 // string com.test-1 is returned. 9905 static String deriveCodePathName(String codePath) { 9906 if (codePath == null) { 9907 return null; 9908 } 9909 final File codeFile = new File(codePath); 9910 final String name = codeFile.getName(); 9911 if (codeFile.isDirectory()) { 9912 return name; 9913 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9914 final int lastDot = name.lastIndexOf('.'); 9915 return name.substring(0, lastDot); 9916 } else { 9917 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9918 return null; 9919 } 9920 } 9921 9922 class PackageInstalledInfo { 9923 String name; 9924 int uid; 9925 // The set of users that originally had this package installed. 9926 int[] origUsers; 9927 // The set of users that now have this package installed. 9928 int[] newUsers; 9929 PackageParser.Package pkg; 9930 int returnCode; 9931 String returnMsg; 9932 PackageRemovedInfo removedInfo; 9933 9934 public void setError(int code, String msg) { 9935 returnCode = code; 9936 returnMsg = msg; 9937 Slog.w(TAG, msg); 9938 } 9939 9940 public void setError(String msg, PackageParserException e) { 9941 returnCode = e.error; 9942 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9943 Slog.w(TAG, msg, e); 9944 } 9945 9946 public void setError(String msg, PackageManagerException e) { 9947 returnCode = e.error; 9948 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9949 Slog.w(TAG, msg, e); 9950 } 9951 9952 // In some error cases we want to convey more info back to the observer 9953 String origPackage; 9954 String origPermission; 9955 } 9956 9957 /* 9958 * Install a non-existing package. 9959 */ 9960 private void installNewPackageLI(PackageParser.Package pkg, 9961 int parseFlags, int scanFlags, UserHandle user, 9962 String installerPackageName, PackageInstalledInfo res) { 9963 // Remember this for later, in case we need to rollback this install 9964 String pkgName = pkg.packageName; 9965 9966 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9967 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9968 synchronized(mPackages) { 9969 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9970 // A package with the same name is already installed, though 9971 // it has been renamed to an older name. The package we 9972 // are trying to install should be installed as an update to 9973 // the existing one, but that has not been requested, so bail. 9974 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9975 + " without first uninstalling package running as " 9976 + mSettings.mRenamedPackages.get(pkgName)); 9977 return; 9978 } 9979 if (mPackages.containsKey(pkgName)) { 9980 // Don't allow installation over an existing package with the same name. 9981 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9982 + " without first uninstalling."); 9983 return; 9984 } 9985 } 9986 9987 try { 9988 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9989 System.currentTimeMillis(), user); 9990 9991 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9992 // delete the partially installed application. the data directory will have to be 9993 // restored if it was already existing 9994 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9995 // remove package from internal structures. Note that we want deletePackageX to 9996 // delete the package data and cache directories that it created in 9997 // scanPackageLocked, unless those directories existed before we even tried to 9998 // install. 9999 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10000 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10001 res.removedInfo, true); 10002 } 10003 10004 } catch (PackageManagerException e) { 10005 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10006 } 10007 } 10008 10009 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10010 // Upgrade keysets are being used. Determine if new package has a superset of the 10011 // required keys. 10012 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10013 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10014 for (int i = 0; i < upgradeKeySets.length; i++) { 10015 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10016 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10017 return true; 10018 } 10019 } 10020 return false; 10021 } 10022 10023 private void replacePackageLI(PackageParser.Package pkg, 10024 int parseFlags, int scanFlags, UserHandle user, 10025 String installerPackageName, PackageInstalledInfo res) { 10026 PackageParser.Package oldPackage; 10027 String pkgName = pkg.packageName; 10028 int[] allUsers; 10029 boolean[] perUserInstalled; 10030 10031 // First find the old package info and check signatures 10032 synchronized(mPackages) { 10033 oldPackage = mPackages.get(pkgName); 10034 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10035 PackageSetting ps = mSettings.mPackages.get(pkgName); 10036 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10037 // default to original signature matching 10038 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10039 != PackageManager.SIGNATURE_MATCH) { 10040 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10041 "New package has a different signature: " + pkgName); 10042 return; 10043 } 10044 } else { 10045 if(!checkUpgradeKeySetLP(ps, pkg)) { 10046 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10047 "New package not signed by keys specified by upgrade-keysets: " 10048 + pkgName); 10049 return; 10050 } 10051 } 10052 10053 // In case of rollback, remember per-user/profile install state 10054 allUsers = sUserManager.getUserIds(); 10055 perUserInstalled = new boolean[allUsers.length]; 10056 for (int i = 0; i < allUsers.length; i++) { 10057 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10058 } 10059 } 10060 10061 boolean sysPkg = (isSystemApp(oldPackage)); 10062 if (sysPkg) { 10063 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10064 user, allUsers, perUserInstalled, installerPackageName, res); 10065 } else { 10066 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10067 user, allUsers, perUserInstalled, installerPackageName, res); 10068 } 10069 } 10070 10071 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10072 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10073 int[] allUsers, boolean[] perUserInstalled, 10074 String installerPackageName, PackageInstalledInfo res) { 10075 String pkgName = deletedPackage.packageName; 10076 boolean deletedPkg = true; 10077 boolean updatedSettings = false; 10078 10079 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10080 + deletedPackage); 10081 long origUpdateTime; 10082 if (pkg.mExtras != null) { 10083 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10084 } else { 10085 origUpdateTime = 0; 10086 } 10087 10088 // First delete the existing package while retaining the data directory 10089 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10090 res.removedInfo, true)) { 10091 // If the existing package wasn't successfully deleted 10092 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10093 deletedPkg = false; 10094 } else { 10095 // Successfully deleted the old package; proceed with replace. 10096 10097 // If deleted package lived in a container, give users a chance to 10098 // relinquish resources before killing. 10099 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10100 if (DEBUG_INSTALL) { 10101 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10102 } 10103 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10104 final ArrayList<String> pkgList = new ArrayList<String>(1); 10105 pkgList.add(deletedPackage.applicationInfo.packageName); 10106 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10107 } 10108 10109 deleteCodeCacheDirsLI(pkgName); 10110 try { 10111 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10112 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10113 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10114 updatedSettings = true; 10115 } catch (PackageManagerException e) { 10116 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10117 } 10118 } 10119 10120 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10121 // remove package from internal structures. Note that we want deletePackageX to 10122 // delete the package data and cache directories that it created in 10123 // scanPackageLocked, unless those directories existed before we even tried to 10124 // install. 10125 if(updatedSettings) { 10126 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10127 deletePackageLI( 10128 pkgName, null, true, allUsers, perUserInstalled, 10129 PackageManager.DELETE_KEEP_DATA, 10130 res.removedInfo, true); 10131 } 10132 // Since we failed to install the new package we need to restore the old 10133 // package that we deleted. 10134 if (deletedPkg) { 10135 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10136 File restoreFile = new File(deletedPackage.codePath); 10137 // Parse old package 10138 boolean oldOnSd = isExternal(deletedPackage); 10139 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10140 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10141 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10142 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10143 try { 10144 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10145 } catch (PackageManagerException e) { 10146 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10147 + e.getMessage()); 10148 return; 10149 } 10150 // Restore of old package succeeded. Update permissions. 10151 // writer 10152 synchronized (mPackages) { 10153 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10154 UPDATE_PERMISSIONS_ALL); 10155 // can downgrade to reader 10156 mSettings.writeLPr(); 10157 } 10158 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10159 } 10160 } 10161 } 10162 10163 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10164 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10165 int[] allUsers, boolean[] perUserInstalled, 10166 String installerPackageName, PackageInstalledInfo res) { 10167 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10168 + ", old=" + deletedPackage); 10169 boolean disabledSystem = false; 10170 boolean updatedSettings = false; 10171 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10172 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10173 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10174 } 10175 String packageName = deletedPackage.packageName; 10176 if (packageName == null) { 10177 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10178 "Attempt to delete null packageName."); 10179 return; 10180 } 10181 PackageParser.Package oldPkg; 10182 PackageSetting oldPkgSetting; 10183 // reader 10184 synchronized (mPackages) { 10185 oldPkg = mPackages.get(packageName); 10186 oldPkgSetting = mSettings.mPackages.get(packageName); 10187 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10188 (oldPkgSetting == null)) { 10189 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10190 "Couldn't find package:" + packageName + " information"); 10191 return; 10192 } 10193 } 10194 10195 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10196 10197 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10198 res.removedInfo.removedPackage = packageName; 10199 // Remove existing system package 10200 removePackageLI(oldPkgSetting, true); 10201 // writer 10202 synchronized (mPackages) { 10203 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10204 if (!disabledSystem && deletedPackage != null) { 10205 // We didn't need to disable the .apk as a current system package, 10206 // which means we are replacing another update that is already 10207 // installed. We need to make sure to delete the older one's .apk. 10208 res.removedInfo.args = createInstallArgsForExisting(0, 10209 deletedPackage.applicationInfo.getCodePath(), 10210 deletedPackage.applicationInfo.getResourcePath(), 10211 deletedPackage.applicationInfo.nativeLibraryRootDir, 10212 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10213 } else { 10214 res.removedInfo.args = null; 10215 } 10216 } 10217 10218 // Successfully disabled the old package. Now proceed with re-installation 10219 deleteCodeCacheDirsLI(packageName); 10220 10221 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10222 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10223 10224 PackageParser.Package newPackage = null; 10225 try { 10226 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10227 if (newPackage.mExtras != null) { 10228 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10229 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10230 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10231 10232 // is the update attempting to change shared user? that isn't going to work... 10233 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10234 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10235 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10236 + " to " + newPkgSetting.sharedUser); 10237 updatedSettings = true; 10238 } 10239 } 10240 10241 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10242 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10243 updatedSettings = true; 10244 } 10245 10246 } catch (PackageManagerException e) { 10247 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10248 } 10249 10250 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10251 // Re installation failed. Restore old information 10252 // Remove new pkg information 10253 if (newPackage != null) { 10254 removeInstalledPackageLI(newPackage, true); 10255 } 10256 // Add back the old system package 10257 try { 10258 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10259 } catch (PackageManagerException e) { 10260 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10261 } 10262 // Restore the old system information in Settings 10263 synchronized (mPackages) { 10264 if (disabledSystem) { 10265 mSettings.enableSystemPackageLPw(packageName); 10266 } 10267 if (updatedSettings) { 10268 mSettings.setInstallerPackageName(packageName, 10269 oldPkgSetting.installerPackageName); 10270 } 10271 mSettings.writeLPr(); 10272 } 10273 } 10274 } 10275 10276 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10277 int[] allUsers, boolean[] perUserInstalled, 10278 PackageInstalledInfo res) { 10279 String pkgName = newPackage.packageName; 10280 synchronized (mPackages) { 10281 //write settings. the installStatus will be incomplete at this stage. 10282 //note that the new package setting would have already been 10283 //added to mPackages. It hasn't been persisted yet. 10284 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10285 mSettings.writeLPr(); 10286 } 10287 10288 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10289 10290 synchronized (mPackages) { 10291 updatePermissionsLPw(newPackage.packageName, newPackage, 10292 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10293 ? UPDATE_PERMISSIONS_ALL : 0)); 10294 // For system-bundled packages, we assume that installing an upgraded version 10295 // of the package implies that the user actually wants to run that new code, 10296 // so we enable the package. 10297 if (isSystemApp(newPackage)) { 10298 // NB: implicit assumption that system package upgrades apply to all users 10299 if (DEBUG_INSTALL) { 10300 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10301 } 10302 PackageSetting ps = mSettings.mPackages.get(pkgName); 10303 if (ps != null) { 10304 if (res.origUsers != null) { 10305 for (int userHandle : res.origUsers) { 10306 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10307 userHandle, installerPackageName); 10308 } 10309 } 10310 // Also convey the prior install/uninstall state 10311 if (allUsers != null && perUserInstalled != null) { 10312 for (int i = 0; i < allUsers.length; i++) { 10313 if (DEBUG_INSTALL) { 10314 Slog.d(TAG, " user " + allUsers[i] 10315 + " => " + perUserInstalled[i]); 10316 } 10317 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10318 } 10319 // these install state changes will be persisted in the 10320 // upcoming call to mSettings.writeLPr(). 10321 } 10322 } 10323 } 10324 res.name = pkgName; 10325 res.uid = newPackage.applicationInfo.uid; 10326 res.pkg = newPackage; 10327 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10328 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10329 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10330 //to update install status 10331 mSettings.writeLPr(); 10332 } 10333 } 10334 10335 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10336 final int installFlags = args.installFlags; 10337 String installerPackageName = args.installerPackageName; 10338 File tmpPackageFile = new File(args.getCodePath()); 10339 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10340 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10341 boolean replace = false; 10342 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10343 // Result object to be returned 10344 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10345 10346 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10347 // Retrieve PackageSettings and parse package 10348 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10349 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10350 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10351 PackageParser pp = new PackageParser(); 10352 pp.setSeparateProcesses(mSeparateProcesses); 10353 pp.setDisplayMetrics(mMetrics); 10354 10355 final PackageParser.Package pkg; 10356 try { 10357 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10358 } catch (PackageParserException e) { 10359 res.setError("Failed parse during installPackageLI", e); 10360 return; 10361 } 10362 10363 // Mark that we have an install time CPU ABI override. 10364 pkg.cpuAbiOverride = args.abiOverride; 10365 10366 String pkgName = res.name = pkg.packageName; 10367 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10368 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10369 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10370 return; 10371 } 10372 } 10373 10374 try { 10375 pp.collectCertificates(pkg, parseFlags); 10376 pp.collectManifestDigest(pkg); 10377 } catch (PackageParserException e) { 10378 res.setError("Failed collect during installPackageLI", e); 10379 return; 10380 } 10381 10382 /* If the installer passed in a manifest digest, compare it now. */ 10383 if (args.manifestDigest != null) { 10384 if (DEBUG_INSTALL) { 10385 final String parsedManifest = pkg.manifestDigest == null ? "null" 10386 : pkg.manifestDigest.toString(); 10387 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10388 + parsedManifest); 10389 } 10390 10391 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10392 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10393 return; 10394 } 10395 } else if (DEBUG_INSTALL) { 10396 final String parsedManifest = pkg.manifestDigest == null 10397 ? "null" : pkg.manifestDigest.toString(); 10398 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10399 } 10400 10401 // Get rid of all references to package scan path via parser. 10402 pp = null; 10403 String oldCodePath = null; 10404 boolean systemApp = false; 10405 synchronized (mPackages) { 10406 // Check if installing already existing package 10407 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10408 String oldName = mSettings.mRenamedPackages.get(pkgName); 10409 if (pkg.mOriginalPackages != null 10410 && pkg.mOriginalPackages.contains(oldName) 10411 && mPackages.containsKey(oldName)) { 10412 // This package is derived from an original package, 10413 // and this device has been updating from that original 10414 // name. We must continue using the original name, so 10415 // rename the new package here. 10416 pkg.setPackageName(oldName); 10417 pkgName = pkg.packageName; 10418 replace = true; 10419 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10420 + oldName + " pkgName=" + pkgName); 10421 } else if (mPackages.containsKey(pkgName)) { 10422 // This package, under its official name, already exists 10423 // on the device; we should replace it. 10424 replace = true; 10425 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10426 } 10427 } 10428 10429 PackageSetting ps = mSettings.mPackages.get(pkgName); 10430 if (ps != null) { 10431 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10432 10433 // Quick sanity check that we're signed correctly if updating; 10434 // we'll check this again later when scanning, but we want to 10435 // bail early here before tripping over redefined permissions. 10436 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10437 try { 10438 verifySignaturesLP(ps, pkg); 10439 } catch (PackageManagerException e) { 10440 res.setError(e.error, e.getMessage()); 10441 return; 10442 } 10443 } else { 10444 if (!checkUpgradeKeySetLP(ps, pkg)) { 10445 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10446 + pkg.packageName + " upgrade keys do not match the " 10447 + "previously installed version"); 10448 return; 10449 } 10450 } 10451 10452 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10453 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10454 systemApp = (ps.pkg.applicationInfo.flags & 10455 ApplicationInfo.FLAG_SYSTEM) != 0; 10456 } 10457 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10458 } 10459 10460 // Check whether the newly-scanned package wants to define an already-defined perm 10461 int N = pkg.permissions.size(); 10462 for (int i = N-1; i >= 0; i--) { 10463 PackageParser.Permission perm = pkg.permissions.get(i); 10464 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10465 if (bp != null) { 10466 // If the defining package is signed with our cert, it's okay. This 10467 // also includes the "updating the same package" case, of course. 10468 // "updating same package" could also involve key-rotation. 10469 final boolean sigsOk; 10470 if (!bp.sourcePackage.equals(pkg.packageName) 10471 || !(bp.packageSetting instanceof PackageSetting) 10472 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10473 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10474 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10475 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10476 } else { 10477 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10478 } 10479 if (!sigsOk) { 10480 // If the owning package is the system itself, we log but allow 10481 // install to proceed; we fail the install on all other permission 10482 // redefinitions. 10483 if (!bp.sourcePackage.equals("android")) { 10484 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10485 + pkg.packageName + " attempting to redeclare permission " 10486 + perm.info.name + " already owned by " + bp.sourcePackage); 10487 res.origPermission = perm.info.name; 10488 res.origPackage = bp.sourcePackage; 10489 return; 10490 } else { 10491 Slog.w(TAG, "Package " + pkg.packageName 10492 + " attempting to redeclare system permission " 10493 + perm.info.name + "; ignoring new declaration"); 10494 pkg.permissions.remove(i); 10495 } 10496 } 10497 } 10498 } 10499 10500 } 10501 10502 if (systemApp && onSd) { 10503 // Disable updates to system apps on sdcard 10504 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10505 "Cannot install updates to system apps on sdcard"); 10506 return; 10507 } 10508 10509 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10510 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10511 return; 10512 } 10513 10514 if (replace) { 10515 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10516 installerPackageName, res); 10517 } else { 10518 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10519 args.user, installerPackageName, res); 10520 } 10521 synchronized (mPackages) { 10522 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10523 if (ps != null) { 10524 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10525 } 10526 } 10527 } 10528 10529 private static boolean isForwardLocked(PackageParser.Package pkg) { 10530 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10531 } 10532 10533 private static boolean isForwardLocked(ApplicationInfo info) { 10534 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10535 } 10536 10537 private boolean isForwardLocked(PackageSetting ps) { 10538 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10539 } 10540 10541 private static boolean isMultiArch(PackageSetting ps) { 10542 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10543 } 10544 10545 private static boolean isMultiArch(ApplicationInfo info) { 10546 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10547 } 10548 10549 private static boolean isExternal(PackageParser.Package pkg) { 10550 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10551 } 10552 10553 private static boolean isExternal(PackageSetting ps) { 10554 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10555 } 10556 10557 private static boolean isExternal(ApplicationInfo info) { 10558 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10559 } 10560 10561 private static boolean isSystemApp(PackageParser.Package pkg) { 10562 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10563 } 10564 10565 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10566 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10567 } 10568 10569 private static boolean isSystemApp(ApplicationInfo info) { 10570 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10571 } 10572 10573 private static boolean isSystemApp(PackageSetting ps) { 10574 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10575 } 10576 10577 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10578 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10579 } 10580 10581 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10582 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10583 } 10584 10585 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10586 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10587 } 10588 10589 private int packageFlagsToInstallFlags(PackageSetting ps) { 10590 int installFlags = 0; 10591 if (isExternal(ps)) { 10592 installFlags |= PackageManager.INSTALL_EXTERNAL; 10593 } 10594 if (isForwardLocked(ps)) { 10595 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10596 } 10597 return installFlags; 10598 } 10599 10600 private void deleteTempPackageFiles() { 10601 final FilenameFilter filter = new FilenameFilter() { 10602 public boolean accept(File dir, String name) { 10603 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10604 } 10605 }; 10606 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10607 file.delete(); 10608 } 10609 } 10610 10611 @Override 10612 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10613 int flags) { 10614 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10615 flags); 10616 } 10617 10618 @Override 10619 public void deletePackage(final String packageName, 10620 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10621 mContext.enforceCallingOrSelfPermission( 10622 android.Manifest.permission.DELETE_PACKAGES, null); 10623 final int uid = Binder.getCallingUid(); 10624 if (UserHandle.getUserId(uid) != userId) { 10625 mContext.enforceCallingPermission( 10626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10627 "deletePackage for user " + userId); 10628 } 10629 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10630 try { 10631 observer.onPackageDeleted(packageName, 10632 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10633 } catch (RemoteException re) { 10634 } 10635 return; 10636 } 10637 10638 boolean uninstallBlocked = false; 10639 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10640 int[] users = sUserManager.getUserIds(); 10641 for (int i = 0; i < users.length; ++i) { 10642 if (getBlockUninstallForUser(packageName, users[i])) { 10643 uninstallBlocked = true; 10644 break; 10645 } 10646 } 10647 } else { 10648 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10649 } 10650 if (uninstallBlocked) { 10651 try { 10652 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10653 null); 10654 } catch (RemoteException re) { 10655 } 10656 return; 10657 } 10658 10659 if (DEBUG_REMOVE) { 10660 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10661 } 10662 // Queue up an async operation since the package deletion may take a little while. 10663 mHandler.post(new Runnable() { 10664 public void run() { 10665 mHandler.removeCallbacks(this); 10666 final int returnCode = deletePackageX(packageName, userId, flags); 10667 if (observer != null) { 10668 try { 10669 observer.onPackageDeleted(packageName, returnCode, null); 10670 } catch (RemoteException e) { 10671 Log.i(TAG, "Observer no longer exists."); 10672 } //end catch 10673 } //end if 10674 } //end run 10675 }); 10676 } 10677 10678 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10679 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10680 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10681 try { 10682 if (dpm != null) { 10683 if (dpm.isDeviceOwner(packageName)) { 10684 return true; 10685 } 10686 int[] users; 10687 if (userId == UserHandle.USER_ALL) { 10688 users = sUserManager.getUserIds(); 10689 } else { 10690 users = new int[]{userId}; 10691 } 10692 for (int i = 0; i < users.length; ++i) { 10693 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10694 return true; 10695 } 10696 } 10697 } 10698 } catch (RemoteException e) { 10699 } 10700 return false; 10701 } 10702 10703 /** 10704 * This method is an internal method that could be get invoked either 10705 * to delete an installed package or to clean up a failed installation. 10706 * After deleting an installed package, a broadcast is sent to notify any 10707 * listeners that the package has been installed. For cleaning up a failed 10708 * installation, the broadcast is not necessary since the package's 10709 * installation wouldn't have sent the initial broadcast either 10710 * The key steps in deleting a package are 10711 * deleting the package information in internal structures like mPackages, 10712 * deleting the packages base directories through installd 10713 * updating mSettings to reflect current status 10714 * persisting settings for later use 10715 * sending a broadcast if necessary 10716 */ 10717 private int deletePackageX(String packageName, int userId, int flags) { 10718 final PackageRemovedInfo info = new PackageRemovedInfo(); 10719 final boolean res; 10720 10721 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10722 ? UserHandle.ALL : new UserHandle(userId); 10723 10724 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10725 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10726 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10727 } 10728 10729 boolean removedForAllUsers = false; 10730 boolean systemUpdate = false; 10731 10732 // for the uninstall-updates case and restricted profiles, remember the per- 10733 // userhandle installed state 10734 int[] allUsers; 10735 boolean[] perUserInstalled; 10736 synchronized (mPackages) { 10737 PackageSetting ps = mSettings.mPackages.get(packageName); 10738 allUsers = sUserManager.getUserIds(); 10739 perUserInstalled = new boolean[allUsers.length]; 10740 for (int i = 0; i < allUsers.length; i++) { 10741 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10742 } 10743 } 10744 10745 synchronized (mInstallLock) { 10746 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10747 res = deletePackageLI(packageName, removeForUser, 10748 true, allUsers, perUserInstalled, 10749 flags | REMOVE_CHATTY, info, true); 10750 systemUpdate = info.isRemovedPackageSystemUpdate; 10751 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10752 removedForAllUsers = true; 10753 } 10754 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10755 + " removedForAllUsers=" + removedForAllUsers); 10756 } 10757 10758 if (res) { 10759 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10760 10761 // If the removed package was a system update, the old system package 10762 // was re-enabled; we need to broadcast this information 10763 if (systemUpdate) { 10764 Bundle extras = new Bundle(1); 10765 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10766 ? info.removedAppId : info.uid); 10767 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10768 10769 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10770 extras, null, null, null); 10771 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10772 extras, null, null, null); 10773 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10774 null, packageName, null, null); 10775 } 10776 } 10777 // Force a gc here. 10778 Runtime.getRuntime().gc(); 10779 // Delete the resources here after sending the broadcast to let 10780 // other processes clean up before deleting resources. 10781 if (info.args != null) { 10782 synchronized (mInstallLock) { 10783 info.args.doPostDeleteLI(true); 10784 } 10785 } 10786 10787 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10788 } 10789 10790 static class PackageRemovedInfo { 10791 String removedPackage; 10792 int uid = -1; 10793 int removedAppId = -1; 10794 int[] removedUsers = null; 10795 boolean isRemovedPackageSystemUpdate = false; 10796 // Clean up resources deleted packages. 10797 InstallArgs args = null; 10798 10799 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10800 Bundle extras = new Bundle(1); 10801 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10802 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10803 if (replacing) { 10804 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10805 } 10806 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10807 if (removedPackage != null) { 10808 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10809 extras, null, null, removedUsers); 10810 if (fullRemove && !replacing) { 10811 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10812 extras, null, null, removedUsers); 10813 } 10814 } 10815 if (removedAppId >= 0) { 10816 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10817 removedUsers); 10818 } 10819 } 10820 } 10821 10822 /* 10823 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10824 * flag is not set, the data directory is removed as well. 10825 * make sure this flag is set for partially installed apps. If not its meaningless to 10826 * delete a partially installed application. 10827 */ 10828 private void removePackageDataLI(PackageSetting ps, 10829 int[] allUserHandles, boolean[] perUserInstalled, 10830 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10831 String packageName = ps.name; 10832 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10833 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10834 // Retrieve object to delete permissions for shared user later on 10835 final PackageSetting deletedPs; 10836 // reader 10837 synchronized (mPackages) { 10838 deletedPs = mSettings.mPackages.get(packageName); 10839 if (outInfo != null) { 10840 outInfo.removedPackage = packageName; 10841 outInfo.removedUsers = deletedPs != null 10842 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10843 : null; 10844 } 10845 } 10846 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10847 removeDataDirsLI(packageName); 10848 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10849 } 10850 // writer 10851 synchronized (mPackages) { 10852 if (deletedPs != null) { 10853 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10854 if (outInfo != null) { 10855 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10856 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10857 } 10858 if (deletedPs != null) { 10859 updatePermissionsLPw(deletedPs.name, null, 0); 10860 if (deletedPs.sharedUser != null) { 10861 // remove permissions associated with package 10862 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10863 } 10864 } 10865 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10866 } 10867 // make sure to preserve per-user disabled state if this removal was just 10868 // a downgrade of a system app to the factory package 10869 if (allUserHandles != null && perUserInstalled != null) { 10870 if (DEBUG_REMOVE) { 10871 Slog.d(TAG, "Propagating install state across downgrade"); 10872 } 10873 for (int i = 0; i < allUserHandles.length; i++) { 10874 if (DEBUG_REMOVE) { 10875 Slog.d(TAG, " user " + allUserHandles[i] 10876 + " => " + perUserInstalled[i]); 10877 } 10878 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10879 } 10880 } 10881 } 10882 // can downgrade to reader 10883 if (writeSettings) { 10884 // Save settings now 10885 mSettings.writeLPr(); 10886 } 10887 } 10888 if (outInfo != null) { 10889 // A user ID was deleted here. Go through all users and remove it 10890 // from KeyStore. 10891 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10892 } 10893 } 10894 10895 static boolean locationIsPrivileged(File path) { 10896 try { 10897 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10898 .getCanonicalPath(); 10899 return path.getCanonicalPath().startsWith(privilegedAppDir); 10900 } catch (IOException e) { 10901 Slog.e(TAG, "Unable to access code path " + path); 10902 } 10903 return false; 10904 } 10905 10906 /* 10907 * Tries to delete system package. 10908 */ 10909 private boolean deleteSystemPackageLI(PackageSetting newPs, 10910 int[] allUserHandles, boolean[] perUserInstalled, 10911 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10912 final boolean applyUserRestrictions 10913 = (allUserHandles != null) && (perUserInstalled != null); 10914 PackageSetting disabledPs = null; 10915 // Confirm if the system package has been updated 10916 // An updated system app can be deleted. This will also have to restore 10917 // the system pkg from system partition 10918 // reader 10919 synchronized (mPackages) { 10920 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10921 } 10922 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10923 + " disabledPs=" + disabledPs); 10924 if (disabledPs == null) { 10925 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10926 return false; 10927 } else if (DEBUG_REMOVE) { 10928 Slog.d(TAG, "Deleting system pkg from data partition"); 10929 } 10930 if (DEBUG_REMOVE) { 10931 if (applyUserRestrictions) { 10932 Slog.d(TAG, "Remembering install states:"); 10933 for (int i = 0; i < allUserHandles.length; i++) { 10934 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10935 } 10936 } 10937 } 10938 // Delete the updated package 10939 outInfo.isRemovedPackageSystemUpdate = true; 10940 if (disabledPs.versionCode < newPs.versionCode) { 10941 // Delete data for downgrades 10942 flags &= ~PackageManager.DELETE_KEEP_DATA; 10943 } else { 10944 // Preserve data by setting flag 10945 flags |= PackageManager.DELETE_KEEP_DATA; 10946 } 10947 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10948 allUserHandles, perUserInstalled, outInfo, writeSettings); 10949 if (!ret) { 10950 return false; 10951 } 10952 // writer 10953 synchronized (mPackages) { 10954 // Reinstate the old system package 10955 mSettings.enableSystemPackageLPw(newPs.name); 10956 // Remove any native libraries from the upgraded package. 10957 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10958 } 10959 // Install the system package 10960 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10961 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10962 if (locationIsPrivileged(disabledPs.codePath)) { 10963 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10964 } 10965 10966 final PackageParser.Package newPkg; 10967 try { 10968 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10969 } catch (PackageManagerException e) { 10970 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10971 return false; 10972 } 10973 10974 // writer 10975 synchronized (mPackages) { 10976 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10977 updatePermissionsLPw(newPkg.packageName, newPkg, 10978 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10979 if (applyUserRestrictions) { 10980 if (DEBUG_REMOVE) { 10981 Slog.d(TAG, "Propagating install state across reinstall"); 10982 } 10983 for (int i = 0; i < allUserHandles.length; i++) { 10984 if (DEBUG_REMOVE) { 10985 Slog.d(TAG, " user " + allUserHandles[i] 10986 + " => " + perUserInstalled[i]); 10987 } 10988 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10989 } 10990 // Regardless of writeSettings we need to ensure that this restriction 10991 // state propagation is persisted 10992 mSettings.writeAllUsersPackageRestrictionsLPr(); 10993 } 10994 // can downgrade to reader here 10995 if (writeSettings) { 10996 mSettings.writeLPr(); 10997 } 10998 } 10999 return true; 11000 } 11001 11002 private boolean deleteInstalledPackageLI(PackageSetting ps, 11003 boolean deleteCodeAndResources, int flags, 11004 int[] allUserHandles, boolean[] perUserInstalled, 11005 PackageRemovedInfo outInfo, boolean writeSettings) { 11006 if (outInfo != null) { 11007 outInfo.uid = ps.appId; 11008 } 11009 11010 // Delete package data from internal structures and also remove data if flag is set 11011 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11012 11013 // Delete application code and resources 11014 if (deleteCodeAndResources && (outInfo != null)) { 11015 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11016 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11017 getAppDexInstructionSets(ps)); 11018 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11019 } 11020 return true; 11021 } 11022 11023 @Override 11024 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11025 int userId) { 11026 mContext.enforceCallingOrSelfPermission( 11027 android.Manifest.permission.DELETE_PACKAGES, null); 11028 synchronized (mPackages) { 11029 PackageSetting ps = mSettings.mPackages.get(packageName); 11030 if (ps == null) { 11031 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11032 return false; 11033 } 11034 if (!ps.getInstalled(userId)) { 11035 // Can't block uninstall for an app that is not installed or enabled. 11036 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11037 return false; 11038 } 11039 ps.setBlockUninstall(blockUninstall, userId); 11040 mSettings.writePackageRestrictionsLPr(userId); 11041 } 11042 return true; 11043 } 11044 11045 @Override 11046 public boolean getBlockUninstallForUser(String packageName, int userId) { 11047 synchronized (mPackages) { 11048 PackageSetting ps = mSettings.mPackages.get(packageName); 11049 if (ps == null) { 11050 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11051 return false; 11052 } 11053 return ps.getBlockUninstall(userId); 11054 } 11055 } 11056 11057 /* 11058 * This method handles package deletion in general 11059 */ 11060 private boolean deletePackageLI(String packageName, UserHandle user, 11061 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11062 int flags, PackageRemovedInfo outInfo, 11063 boolean writeSettings) { 11064 if (packageName == null) { 11065 Slog.w(TAG, "Attempt to delete null packageName."); 11066 return false; 11067 } 11068 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11069 PackageSetting ps; 11070 boolean dataOnly = false; 11071 int removeUser = -1; 11072 int appId = -1; 11073 synchronized (mPackages) { 11074 ps = mSettings.mPackages.get(packageName); 11075 if (ps == null) { 11076 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11077 return false; 11078 } 11079 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11080 && user.getIdentifier() != UserHandle.USER_ALL) { 11081 // The caller is asking that the package only be deleted for a single 11082 // user. To do this, we just mark its uninstalled state and delete 11083 // its data. If this is a system app, we only allow this to happen if 11084 // they have set the special DELETE_SYSTEM_APP which requests different 11085 // semantics than normal for uninstalling system apps. 11086 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11087 ps.setUserState(user.getIdentifier(), 11088 COMPONENT_ENABLED_STATE_DEFAULT, 11089 false, //installed 11090 true, //stopped 11091 true, //notLaunched 11092 false, //hidden 11093 null, null, null, 11094 false // blockUninstall 11095 ); 11096 if (!isSystemApp(ps)) { 11097 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11098 // Other user still have this package installed, so all 11099 // we need to do is clear this user's data and save that 11100 // it is uninstalled. 11101 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11102 removeUser = user.getIdentifier(); 11103 appId = ps.appId; 11104 mSettings.writePackageRestrictionsLPr(removeUser); 11105 } else { 11106 // We need to set it back to 'installed' so the uninstall 11107 // broadcasts will be sent correctly. 11108 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11109 ps.setInstalled(true, user.getIdentifier()); 11110 } 11111 } else { 11112 // This is a system app, so we assume that the 11113 // other users still have this package installed, so all 11114 // we need to do is clear this user's data and save that 11115 // it is uninstalled. 11116 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11117 removeUser = user.getIdentifier(); 11118 appId = ps.appId; 11119 mSettings.writePackageRestrictionsLPr(removeUser); 11120 } 11121 } 11122 } 11123 11124 if (removeUser >= 0) { 11125 // From above, we determined that we are deleting this only 11126 // for a single user. Continue the work here. 11127 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11128 if (outInfo != null) { 11129 outInfo.removedPackage = packageName; 11130 outInfo.removedAppId = appId; 11131 outInfo.removedUsers = new int[] {removeUser}; 11132 } 11133 mInstaller.clearUserData(packageName, removeUser); 11134 removeKeystoreDataIfNeeded(removeUser, appId); 11135 schedulePackageCleaning(packageName, removeUser, false); 11136 return true; 11137 } 11138 11139 if (dataOnly) { 11140 // Delete application data first 11141 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11142 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11143 return true; 11144 } 11145 11146 boolean ret = false; 11147 if (isSystemApp(ps)) { 11148 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11149 // When an updated system application is deleted we delete the existing resources as well and 11150 // fall back to existing code in system partition 11151 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11152 flags, outInfo, writeSettings); 11153 } else { 11154 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11155 // Kill application pre-emptively especially for apps on sd. 11156 killApplication(packageName, ps.appId, "uninstall pkg"); 11157 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11158 allUserHandles, perUserInstalled, 11159 outInfo, writeSettings); 11160 } 11161 11162 return ret; 11163 } 11164 11165 private final class ClearStorageConnection implements ServiceConnection { 11166 IMediaContainerService mContainerService; 11167 11168 @Override 11169 public void onServiceConnected(ComponentName name, IBinder service) { 11170 synchronized (this) { 11171 mContainerService = IMediaContainerService.Stub.asInterface(service); 11172 notifyAll(); 11173 } 11174 } 11175 11176 @Override 11177 public void onServiceDisconnected(ComponentName name) { 11178 } 11179 } 11180 11181 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11182 final boolean mounted; 11183 if (Environment.isExternalStorageEmulated()) { 11184 mounted = true; 11185 } else { 11186 final String status = Environment.getExternalStorageState(); 11187 11188 mounted = status.equals(Environment.MEDIA_MOUNTED) 11189 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11190 } 11191 11192 if (!mounted) { 11193 return; 11194 } 11195 11196 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11197 int[] users; 11198 if (userId == UserHandle.USER_ALL) { 11199 users = sUserManager.getUserIds(); 11200 } else { 11201 users = new int[] { userId }; 11202 } 11203 final ClearStorageConnection conn = new ClearStorageConnection(); 11204 if (mContext.bindServiceAsUser( 11205 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11206 try { 11207 for (int curUser : users) { 11208 long timeout = SystemClock.uptimeMillis() + 5000; 11209 synchronized (conn) { 11210 long now = SystemClock.uptimeMillis(); 11211 while (conn.mContainerService == null && now < timeout) { 11212 try { 11213 conn.wait(timeout - now); 11214 } catch (InterruptedException e) { 11215 } 11216 } 11217 } 11218 if (conn.mContainerService == null) { 11219 return; 11220 } 11221 11222 final UserEnvironment userEnv = new UserEnvironment(curUser); 11223 clearDirectory(conn.mContainerService, 11224 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11225 if (allData) { 11226 clearDirectory(conn.mContainerService, 11227 userEnv.buildExternalStorageAppDataDirs(packageName)); 11228 clearDirectory(conn.mContainerService, 11229 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11230 } 11231 } 11232 } finally { 11233 mContext.unbindService(conn); 11234 } 11235 } 11236 } 11237 11238 @Override 11239 public void clearApplicationUserData(final String packageName, 11240 final IPackageDataObserver observer, final int userId) { 11241 mContext.enforceCallingOrSelfPermission( 11242 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11243 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11244 // Queue up an async operation since the package deletion may take a little while. 11245 mHandler.post(new Runnable() { 11246 public void run() { 11247 mHandler.removeCallbacks(this); 11248 final boolean succeeded; 11249 synchronized (mInstallLock) { 11250 succeeded = clearApplicationUserDataLI(packageName, userId); 11251 } 11252 clearExternalStorageDataSync(packageName, userId, true); 11253 if (succeeded) { 11254 // invoke DeviceStorageMonitor's update method to clear any notifications 11255 DeviceStorageMonitorInternal 11256 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11257 if (dsm != null) { 11258 dsm.checkMemory(); 11259 } 11260 } 11261 if(observer != null) { 11262 try { 11263 observer.onRemoveCompleted(packageName, succeeded); 11264 } catch (RemoteException e) { 11265 Log.i(TAG, "Observer no longer exists."); 11266 } 11267 } //end if observer 11268 } //end run 11269 }); 11270 } 11271 11272 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11273 if (packageName == null) { 11274 Slog.w(TAG, "Attempt to delete null packageName."); 11275 return false; 11276 } 11277 11278 // Try finding details about the requested package 11279 PackageParser.Package pkg; 11280 synchronized (mPackages) { 11281 pkg = mPackages.get(packageName); 11282 if (pkg == null) { 11283 final PackageSetting ps = mSettings.mPackages.get(packageName); 11284 if (ps != null) { 11285 pkg = ps.pkg; 11286 } 11287 } 11288 } 11289 11290 if (pkg == null) { 11291 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11292 } 11293 11294 // Always delete data directories for package, even if we found no other 11295 // record of app. This helps users recover from UID mismatches without 11296 // resorting to a full data wipe. 11297 int retCode = mInstaller.clearUserData(packageName, userId); 11298 if (retCode < 0) { 11299 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11300 return false; 11301 } 11302 11303 if (pkg == null) { 11304 return false; 11305 } 11306 11307 if (pkg != null && pkg.applicationInfo != null) { 11308 final int appId = pkg.applicationInfo.uid; 11309 removeKeystoreDataIfNeeded(userId, appId); 11310 } 11311 11312 // Create a native library symlink only if we have native libraries 11313 // and if the native libraries are 32 bit libraries. We do not provide 11314 // this symlink for 64 bit libraries. 11315 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11316 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11317 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11318 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11319 Slog.w(TAG, "Failed linking native library dir"); 11320 return false; 11321 } 11322 } 11323 11324 return true; 11325 } 11326 11327 /** 11328 * Remove entries from the keystore daemon. Will only remove it if the 11329 * {@code appId} is valid. 11330 */ 11331 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11332 if (appId < 0) { 11333 return; 11334 } 11335 11336 final KeyStore keyStore = KeyStore.getInstance(); 11337 if (keyStore != null) { 11338 if (userId == UserHandle.USER_ALL) { 11339 for (final int individual : sUserManager.getUserIds()) { 11340 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11341 } 11342 } else { 11343 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11344 } 11345 } else { 11346 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11347 } 11348 } 11349 11350 @Override 11351 public void deleteApplicationCacheFiles(final String packageName, 11352 final IPackageDataObserver observer) { 11353 mContext.enforceCallingOrSelfPermission( 11354 android.Manifest.permission.DELETE_CACHE_FILES, null); 11355 // Queue up an async operation since the package deletion may take a little while. 11356 final int userId = UserHandle.getCallingUserId(); 11357 mHandler.post(new Runnable() { 11358 public void run() { 11359 mHandler.removeCallbacks(this); 11360 final boolean succeded; 11361 synchronized (mInstallLock) { 11362 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11363 } 11364 clearExternalStorageDataSync(packageName, userId, false); 11365 if(observer != null) { 11366 try { 11367 observer.onRemoveCompleted(packageName, succeded); 11368 } catch (RemoteException e) { 11369 Log.i(TAG, "Observer no longer exists."); 11370 } 11371 } //end if observer 11372 } //end run 11373 }); 11374 } 11375 11376 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11377 if (packageName == null) { 11378 Slog.w(TAG, "Attempt to delete null packageName."); 11379 return false; 11380 } 11381 PackageParser.Package p; 11382 synchronized (mPackages) { 11383 p = mPackages.get(packageName); 11384 } 11385 if (p == null) { 11386 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11387 return false; 11388 } 11389 final ApplicationInfo applicationInfo = p.applicationInfo; 11390 if (applicationInfo == null) { 11391 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11392 return false; 11393 } 11394 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11395 if (retCode < 0) { 11396 Slog.w(TAG, "Couldn't remove cache files for package: " 11397 + packageName + " u" + userId); 11398 return false; 11399 } 11400 return true; 11401 } 11402 11403 @Override 11404 public void getPackageSizeInfo(final String packageName, int userHandle, 11405 final IPackageStatsObserver observer) { 11406 mContext.enforceCallingOrSelfPermission( 11407 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11408 if (packageName == null) { 11409 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11410 } 11411 11412 PackageStats stats = new PackageStats(packageName, userHandle); 11413 11414 /* 11415 * Queue up an async operation since the package measurement may take a 11416 * little while. 11417 */ 11418 Message msg = mHandler.obtainMessage(INIT_COPY); 11419 msg.obj = new MeasureParams(stats, observer); 11420 mHandler.sendMessage(msg); 11421 } 11422 11423 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11424 PackageStats pStats) { 11425 if (packageName == null) { 11426 Slog.w(TAG, "Attempt to get size of null packageName."); 11427 return false; 11428 } 11429 PackageParser.Package p; 11430 boolean dataOnly = false; 11431 String libDirRoot = null; 11432 String asecPath = null; 11433 PackageSetting ps = null; 11434 synchronized (mPackages) { 11435 p = mPackages.get(packageName); 11436 ps = mSettings.mPackages.get(packageName); 11437 if(p == null) { 11438 dataOnly = true; 11439 if((ps == null) || (ps.pkg == null)) { 11440 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11441 return false; 11442 } 11443 p = ps.pkg; 11444 } 11445 if (ps != null) { 11446 libDirRoot = ps.legacyNativeLibraryPathString; 11447 } 11448 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11449 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11450 if (secureContainerId != null) { 11451 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11452 } 11453 } 11454 } 11455 String publicSrcDir = null; 11456 if(!dataOnly) { 11457 final ApplicationInfo applicationInfo = p.applicationInfo; 11458 if (applicationInfo == null) { 11459 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11460 return false; 11461 } 11462 if (isForwardLocked(p)) { 11463 publicSrcDir = applicationInfo.getBaseResourcePath(); 11464 } 11465 } 11466 // TODO: extend to measure size of split APKs 11467 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11468 // not just the first level. 11469 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11470 // just the primary. 11471 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11472 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11473 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11474 if (res < 0) { 11475 return false; 11476 } 11477 11478 // Fix-up for forward-locked applications in ASEC containers. 11479 if (!isExternal(p)) { 11480 pStats.codeSize += pStats.externalCodeSize; 11481 pStats.externalCodeSize = 0L; 11482 } 11483 11484 return true; 11485 } 11486 11487 11488 @Override 11489 public void addPackageToPreferred(String packageName) { 11490 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11491 } 11492 11493 @Override 11494 public void removePackageFromPreferred(String packageName) { 11495 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11496 } 11497 11498 @Override 11499 public List<PackageInfo> getPreferredPackages(int flags) { 11500 return new ArrayList<PackageInfo>(); 11501 } 11502 11503 private int getUidTargetSdkVersionLockedLPr(int uid) { 11504 Object obj = mSettings.getUserIdLPr(uid); 11505 if (obj instanceof SharedUserSetting) { 11506 final SharedUserSetting sus = (SharedUserSetting) obj; 11507 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11508 final Iterator<PackageSetting> it = sus.packages.iterator(); 11509 while (it.hasNext()) { 11510 final PackageSetting ps = it.next(); 11511 if (ps.pkg != null) { 11512 int v = ps.pkg.applicationInfo.targetSdkVersion; 11513 if (v < vers) vers = v; 11514 } 11515 } 11516 return vers; 11517 } else if (obj instanceof PackageSetting) { 11518 final PackageSetting ps = (PackageSetting) obj; 11519 if (ps.pkg != null) { 11520 return ps.pkg.applicationInfo.targetSdkVersion; 11521 } 11522 } 11523 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11524 } 11525 11526 @Override 11527 public void addPreferredActivity(IntentFilter filter, int match, 11528 ComponentName[] set, ComponentName activity, int userId) { 11529 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11530 "Adding preferred"); 11531 } 11532 11533 private void addPreferredActivityInternal(IntentFilter filter, int match, 11534 ComponentName[] set, ComponentName activity, boolean always, int userId, 11535 String opname) { 11536 // writer 11537 int callingUid = Binder.getCallingUid(); 11538 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11539 if (filter.countActions() == 0) { 11540 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11541 return; 11542 } 11543 synchronized (mPackages) { 11544 if (mContext.checkCallingOrSelfPermission( 11545 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11546 != PackageManager.PERMISSION_GRANTED) { 11547 if (getUidTargetSdkVersionLockedLPr(callingUid) 11548 < Build.VERSION_CODES.FROYO) { 11549 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11550 + callingUid); 11551 return; 11552 } 11553 mContext.enforceCallingOrSelfPermission( 11554 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11555 } 11556 11557 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11558 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11559 + userId + ":"); 11560 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11561 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11562 mSettings.writePackageRestrictionsLPr(userId); 11563 } 11564 } 11565 11566 @Override 11567 public void replacePreferredActivity(IntentFilter filter, int match, 11568 ComponentName[] set, ComponentName activity, int userId) { 11569 if (filter.countActions() != 1) { 11570 throw new IllegalArgumentException( 11571 "replacePreferredActivity expects filter to have only 1 action."); 11572 } 11573 if (filter.countDataAuthorities() != 0 11574 || filter.countDataPaths() != 0 11575 || filter.countDataSchemes() > 1 11576 || filter.countDataTypes() != 0) { 11577 throw new IllegalArgumentException( 11578 "replacePreferredActivity expects filter to have no data authorities, " + 11579 "paths, or types; and at most one scheme."); 11580 } 11581 11582 final int callingUid = Binder.getCallingUid(); 11583 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11584 synchronized (mPackages) { 11585 if (mContext.checkCallingOrSelfPermission( 11586 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11587 != PackageManager.PERMISSION_GRANTED) { 11588 if (getUidTargetSdkVersionLockedLPr(callingUid) 11589 < Build.VERSION_CODES.FROYO) { 11590 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11591 + Binder.getCallingUid()); 11592 return; 11593 } 11594 mContext.enforceCallingOrSelfPermission( 11595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11596 } 11597 11598 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11599 if (pir != null) { 11600 // Get all of the existing entries that exactly match this filter. 11601 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11602 if (existing != null && existing.size() == 1) { 11603 PreferredActivity cur = existing.get(0); 11604 if (DEBUG_PREFERRED) { 11605 Slog.i(TAG, "Checking replace of preferred:"); 11606 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11607 if (!cur.mPref.mAlways) { 11608 Slog.i(TAG, " -- CUR; not mAlways!"); 11609 } else { 11610 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11611 Slog.i(TAG, " -- CUR: mSet=" 11612 + Arrays.toString(cur.mPref.mSetComponents)); 11613 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11614 Slog.i(TAG, " -- NEW: mMatch=" 11615 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11616 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11617 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11618 } 11619 } 11620 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11621 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11622 && cur.mPref.sameSet(set)) { 11623 // Setting the preferred activity to what it happens to be already 11624 if (DEBUG_PREFERRED) { 11625 Slog.i(TAG, "Replacing with same preferred activity " 11626 + cur.mPref.mShortComponent + " for user " 11627 + userId + ":"); 11628 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11629 } 11630 return; 11631 } 11632 } 11633 11634 if (existing != null) { 11635 if (DEBUG_PREFERRED) { 11636 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11637 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11638 } 11639 for (int i = 0; i < existing.size(); i++) { 11640 PreferredActivity pa = existing.get(i); 11641 if (DEBUG_PREFERRED) { 11642 Slog.i(TAG, "Removing existing preferred activity " 11643 + pa.mPref.mComponent + ":"); 11644 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11645 } 11646 pir.removeFilter(pa); 11647 } 11648 } 11649 } 11650 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11651 "Replacing preferred"); 11652 } 11653 } 11654 11655 @Override 11656 public void clearPackagePreferredActivities(String packageName) { 11657 final int uid = Binder.getCallingUid(); 11658 // writer 11659 synchronized (mPackages) { 11660 PackageParser.Package pkg = mPackages.get(packageName); 11661 if (pkg == null || pkg.applicationInfo.uid != uid) { 11662 if (mContext.checkCallingOrSelfPermission( 11663 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11664 != PackageManager.PERMISSION_GRANTED) { 11665 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11666 < Build.VERSION_CODES.FROYO) { 11667 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11668 + Binder.getCallingUid()); 11669 return; 11670 } 11671 mContext.enforceCallingOrSelfPermission( 11672 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11673 } 11674 } 11675 11676 int user = UserHandle.getCallingUserId(); 11677 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11678 mSettings.writePackageRestrictionsLPr(user); 11679 scheduleWriteSettingsLocked(); 11680 } 11681 } 11682 } 11683 11684 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11685 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11686 ArrayList<PreferredActivity> removed = null; 11687 boolean changed = false; 11688 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11689 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11690 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11691 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11692 continue; 11693 } 11694 Iterator<PreferredActivity> it = pir.filterIterator(); 11695 while (it.hasNext()) { 11696 PreferredActivity pa = it.next(); 11697 // Mark entry for removal only if it matches the package name 11698 // and the entry is of type "always". 11699 if (packageName == null || 11700 (pa.mPref.mComponent.getPackageName().equals(packageName) 11701 && pa.mPref.mAlways)) { 11702 if (removed == null) { 11703 removed = new ArrayList<PreferredActivity>(); 11704 } 11705 removed.add(pa); 11706 } 11707 } 11708 if (removed != null) { 11709 for (int j=0; j<removed.size(); j++) { 11710 PreferredActivity pa = removed.get(j); 11711 pir.removeFilter(pa); 11712 } 11713 changed = true; 11714 } 11715 } 11716 return changed; 11717 } 11718 11719 @Override 11720 public void resetPreferredActivities(int userId) { 11721 /* TODO: Actually use userId. Why is it being passed in? */ 11722 mContext.enforceCallingOrSelfPermission( 11723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11724 // writer 11725 synchronized (mPackages) { 11726 int user = UserHandle.getCallingUserId(); 11727 clearPackagePreferredActivitiesLPw(null, user); 11728 mSettings.readDefaultPreferredAppsLPw(this, user); 11729 mSettings.writePackageRestrictionsLPr(user); 11730 scheduleWriteSettingsLocked(); 11731 } 11732 } 11733 11734 @Override 11735 public int getPreferredActivities(List<IntentFilter> outFilters, 11736 List<ComponentName> outActivities, String packageName) { 11737 11738 int num = 0; 11739 final int userId = UserHandle.getCallingUserId(); 11740 // reader 11741 synchronized (mPackages) { 11742 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11743 if (pir != null) { 11744 final Iterator<PreferredActivity> it = pir.filterIterator(); 11745 while (it.hasNext()) { 11746 final PreferredActivity pa = it.next(); 11747 if (packageName == null 11748 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11749 && pa.mPref.mAlways)) { 11750 if (outFilters != null) { 11751 outFilters.add(new IntentFilter(pa)); 11752 } 11753 if (outActivities != null) { 11754 outActivities.add(pa.mPref.mComponent); 11755 } 11756 } 11757 } 11758 } 11759 } 11760 11761 return num; 11762 } 11763 11764 @Override 11765 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11766 int userId) { 11767 int callingUid = Binder.getCallingUid(); 11768 if (callingUid != Process.SYSTEM_UID) { 11769 throw new SecurityException( 11770 "addPersistentPreferredActivity can only be run by the system"); 11771 } 11772 if (filter.countActions() == 0) { 11773 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11774 return; 11775 } 11776 synchronized (mPackages) { 11777 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11778 " :"); 11779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11780 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11781 new PersistentPreferredActivity(filter, activity)); 11782 mSettings.writePackageRestrictionsLPr(userId); 11783 } 11784 } 11785 11786 @Override 11787 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11788 int callingUid = Binder.getCallingUid(); 11789 if (callingUid != Process.SYSTEM_UID) { 11790 throw new SecurityException( 11791 "clearPackagePersistentPreferredActivities can only be run by the system"); 11792 } 11793 ArrayList<PersistentPreferredActivity> removed = null; 11794 boolean changed = false; 11795 synchronized (mPackages) { 11796 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11797 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11798 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11799 .valueAt(i); 11800 if (userId != thisUserId) { 11801 continue; 11802 } 11803 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11804 while (it.hasNext()) { 11805 PersistentPreferredActivity ppa = it.next(); 11806 // Mark entry for removal only if it matches the package name. 11807 if (ppa.mComponent.getPackageName().equals(packageName)) { 11808 if (removed == null) { 11809 removed = new ArrayList<PersistentPreferredActivity>(); 11810 } 11811 removed.add(ppa); 11812 } 11813 } 11814 if (removed != null) { 11815 for (int j=0; j<removed.size(); j++) { 11816 PersistentPreferredActivity ppa = removed.get(j); 11817 ppir.removeFilter(ppa); 11818 } 11819 changed = true; 11820 } 11821 } 11822 11823 if (changed) { 11824 mSettings.writePackageRestrictionsLPr(userId); 11825 } 11826 } 11827 } 11828 11829 @Override 11830 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11831 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11832 mContext.enforceCallingOrSelfPermission( 11833 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11834 int callingUid = Binder.getCallingUid(); 11835 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11836 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11837 if (intentFilter.countActions() == 0) { 11838 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11839 return; 11840 } 11841 synchronized (mPackages) { 11842 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11843 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11844 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11845 mSettings.writePackageRestrictionsLPr(sourceUserId); 11846 } 11847 } 11848 11849 @Override 11850 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11851 int ownerUserId) { 11852 mContext.enforceCallingOrSelfPermission( 11853 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11854 int callingUid = Binder.getCallingUid(); 11855 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11856 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11857 int callingUserId = UserHandle.getUserId(callingUid); 11858 synchronized (mPackages) { 11859 CrossProfileIntentResolver resolver = 11860 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11861 ArraySet<CrossProfileIntentFilter> set = 11862 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11863 for (CrossProfileIntentFilter filter : set) { 11864 if (filter.getOwnerPackage().equals(ownerPackage) 11865 && filter.getOwnerUserId() == callingUserId) { 11866 resolver.removeFilter(filter); 11867 } 11868 } 11869 mSettings.writePackageRestrictionsLPr(sourceUserId); 11870 } 11871 } 11872 11873 // Enforcing that callingUid is owning pkg on userId 11874 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11875 // The system owns everything. 11876 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11877 return; 11878 } 11879 int callingUserId = UserHandle.getUserId(callingUid); 11880 if (callingUserId != userId) { 11881 throw new SecurityException("calling uid " + callingUid 11882 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11883 + callingUserId); 11884 } 11885 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11886 if (pi == null) { 11887 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11888 + callingUserId); 11889 } 11890 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11891 throw new SecurityException("Calling uid " + callingUid 11892 + " does not own package " + pkg); 11893 } 11894 } 11895 11896 @Override 11897 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11898 Intent intent = new Intent(Intent.ACTION_MAIN); 11899 intent.addCategory(Intent.CATEGORY_HOME); 11900 11901 final int callingUserId = UserHandle.getCallingUserId(); 11902 List<ResolveInfo> list = queryIntentActivities(intent, null, 11903 PackageManager.GET_META_DATA, callingUserId); 11904 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11905 true, false, false, callingUserId); 11906 11907 allHomeCandidates.clear(); 11908 if (list != null) { 11909 for (ResolveInfo ri : list) { 11910 allHomeCandidates.add(ri); 11911 } 11912 } 11913 return (preferred == null || preferred.activityInfo == null) 11914 ? null 11915 : new ComponentName(preferred.activityInfo.packageName, 11916 preferred.activityInfo.name); 11917 } 11918 11919 @Override 11920 public void setApplicationEnabledSetting(String appPackageName, 11921 int newState, int flags, int userId, String callingPackage) { 11922 if (!sUserManager.exists(userId)) return; 11923 if (callingPackage == null) { 11924 callingPackage = Integer.toString(Binder.getCallingUid()); 11925 } 11926 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11927 } 11928 11929 @Override 11930 public void setComponentEnabledSetting(ComponentName componentName, 11931 int newState, int flags, int userId) { 11932 if (!sUserManager.exists(userId)) return; 11933 setEnabledSetting(componentName.getPackageName(), 11934 componentName.getClassName(), newState, flags, userId, null); 11935 } 11936 11937 private void setEnabledSetting(final String packageName, String className, int newState, 11938 final int flags, int userId, String callingPackage) { 11939 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11940 || newState == COMPONENT_ENABLED_STATE_ENABLED 11941 || newState == COMPONENT_ENABLED_STATE_DISABLED 11942 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11943 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11944 throw new IllegalArgumentException("Invalid new component state: " 11945 + newState); 11946 } 11947 PackageSetting pkgSetting; 11948 final int uid = Binder.getCallingUid(); 11949 final int permission = mContext.checkCallingOrSelfPermission( 11950 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11951 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11952 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11953 boolean sendNow = false; 11954 boolean isApp = (className == null); 11955 String componentName = isApp ? packageName : className; 11956 int packageUid = -1; 11957 ArrayList<String> components; 11958 11959 // writer 11960 synchronized (mPackages) { 11961 pkgSetting = mSettings.mPackages.get(packageName); 11962 if (pkgSetting == null) { 11963 if (className == null) { 11964 throw new IllegalArgumentException( 11965 "Unknown package: " + packageName); 11966 } 11967 throw new IllegalArgumentException( 11968 "Unknown component: " + packageName 11969 + "/" + className); 11970 } 11971 // Allow root and verify that userId is not being specified by a different user 11972 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11973 throw new SecurityException( 11974 "Permission Denial: attempt to change component state from pid=" 11975 + Binder.getCallingPid() 11976 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11977 } 11978 if (className == null) { 11979 // We're dealing with an application/package level state change 11980 if (pkgSetting.getEnabled(userId) == newState) { 11981 // Nothing to do 11982 return; 11983 } 11984 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11985 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11986 // Don't care about who enables an app. 11987 callingPackage = null; 11988 } 11989 pkgSetting.setEnabled(newState, userId, callingPackage); 11990 // pkgSetting.pkg.mSetEnabled = newState; 11991 } else { 11992 // We're dealing with a component level state change 11993 // First, verify that this is a valid class name. 11994 PackageParser.Package pkg = pkgSetting.pkg; 11995 if (pkg == null || !pkg.hasComponentClassName(className)) { 11996 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11997 throw new IllegalArgumentException("Component class " + className 11998 + " does not exist in " + packageName); 11999 } else { 12000 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12001 + className + " does not exist in " + packageName); 12002 } 12003 } 12004 switch (newState) { 12005 case COMPONENT_ENABLED_STATE_ENABLED: 12006 if (!pkgSetting.enableComponentLPw(className, userId)) { 12007 return; 12008 } 12009 break; 12010 case COMPONENT_ENABLED_STATE_DISABLED: 12011 if (!pkgSetting.disableComponentLPw(className, userId)) { 12012 return; 12013 } 12014 break; 12015 case COMPONENT_ENABLED_STATE_DEFAULT: 12016 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12017 return; 12018 } 12019 break; 12020 default: 12021 Slog.e(TAG, "Invalid new component state: " + newState); 12022 return; 12023 } 12024 } 12025 mSettings.writePackageRestrictionsLPr(userId); 12026 components = mPendingBroadcasts.get(userId, packageName); 12027 final boolean newPackage = components == null; 12028 if (newPackage) { 12029 components = new ArrayList<String>(); 12030 } 12031 if (!components.contains(componentName)) { 12032 components.add(componentName); 12033 } 12034 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12035 sendNow = true; 12036 // Purge entry from pending broadcast list if another one exists already 12037 // since we are sending one right away. 12038 mPendingBroadcasts.remove(userId, packageName); 12039 } else { 12040 if (newPackage) { 12041 mPendingBroadcasts.put(userId, packageName, components); 12042 } 12043 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12044 // Schedule a message 12045 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12046 } 12047 } 12048 } 12049 12050 long callingId = Binder.clearCallingIdentity(); 12051 try { 12052 if (sendNow) { 12053 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12054 sendPackageChangedBroadcast(packageName, 12055 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12056 } 12057 } finally { 12058 Binder.restoreCallingIdentity(callingId); 12059 } 12060 } 12061 12062 private void sendPackageChangedBroadcast(String packageName, 12063 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12064 if (DEBUG_INSTALL) 12065 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12066 + componentNames); 12067 Bundle extras = new Bundle(4); 12068 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12069 String nameList[] = new String[componentNames.size()]; 12070 componentNames.toArray(nameList); 12071 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12072 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12073 extras.putInt(Intent.EXTRA_UID, packageUid); 12074 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12075 new int[] {UserHandle.getUserId(packageUid)}); 12076 } 12077 12078 @Override 12079 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12080 if (!sUserManager.exists(userId)) return; 12081 final int uid = Binder.getCallingUid(); 12082 final int permission = mContext.checkCallingOrSelfPermission( 12083 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12084 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12085 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12086 // writer 12087 synchronized (mPackages) { 12088 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12089 uid, userId)) { 12090 scheduleWritePackageRestrictionsLocked(userId); 12091 } 12092 } 12093 } 12094 12095 @Override 12096 public String getInstallerPackageName(String packageName) { 12097 // reader 12098 synchronized (mPackages) { 12099 return mSettings.getInstallerPackageNameLPr(packageName); 12100 } 12101 } 12102 12103 @Override 12104 public int getApplicationEnabledSetting(String packageName, int userId) { 12105 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12106 int uid = Binder.getCallingUid(); 12107 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12108 // reader 12109 synchronized (mPackages) { 12110 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12111 } 12112 } 12113 12114 @Override 12115 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12116 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12117 int uid = Binder.getCallingUid(); 12118 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12119 // reader 12120 synchronized (mPackages) { 12121 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12122 } 12123 } 12124 12125 @Override 12126 public void enterSafeMode() { 12127 enforceSystemOrRoot("Only the system can request entering safe mode"); 12128 12129 if (!mSystemReady) { 12130 mSafeMode = true; 12131 } 12132 } 12133 12134 @Override 12135 public void systemReady() { 12136 mSystemReady = true; 12137 12138 // Read the compatibilty setting when the system is ready. 12139 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12140 mContext.getContentResolver(), 12141 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12142 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12143 if (DEBUG_SETTINGS) { 12144 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12145 } 12146 12147 synchronized (mPackages) { 12148 // Verify that all of the preferred activity components actually 12149 // exist. It is possible for applications to be updated and at 12150 // that point remove a previously declared activity component that 12151 // had been set as a preferred activity. We try to clean this up 12152 // the next time we encounter that preferred activity, but it is 12153 // possible for the user flow to never be able to return to that 12154 // situation so here we do a sanity check to make sure we haven't 12155 // left any junk around. 12156 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12157 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12158 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12159 removed.clear(); 12160 for (PreferredActivity pa : pir.filterSet()) { 12161 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12162 removed.add(pa); 12163 } 12164 } 12165 if (removed.size() > 0) { 12166 for (int r=0; r<removed.size(); r++) { 12167 PreferredActivity pa = removed.get(r); 12168 Slog.w(TAG, "Removing dangling preferred activity: " 12169 + pa.mPref.mComponent); 12170 pir.removeFilter(pa); 12171 } 12172 mSettings.writePackageRestrictionsLPr( 12173 mSettings.mPreferredActivities.keyAt(i)); 12174 } 12175 } 12176 } 12177 sUserManager.systemReady(); 12178 12179 // Kick off any messages waiting for system ready 12180 if (mPostSystemReadyMessages != null) { 12181 for (Message msg : mPostSystemReadyMessages) { 12182 msg.sendToTarget(); 12183 } 12184 mPostSystemReadyMessages = null; 12185 } 12186 } 12187 12188 @Override 12189 public boolean isSafeMode() { 12190 return mSafeMode; 12191 } 12192 12193 @Override 12194 public boolean hasSystemUidErrors() { 12195 return mHasSystemUidErrors; 12196 } 12197 12198 static String arrayToString(int[] array) { 12199 StringBuffer buf = new StringBuffer(128); 12200 buf.append('['); 12201 if (array != null) { 12202 for (int i=0; i<array.length; i++) { 12203 if (i > 0) buf.append(", "); 12204 buf.append(array[i]); 12205 } 12206 } 12207 buf.append(']'); 12208 return buf.toString(); 12209 } 12210 12211 static class DumpState { 12212 public static final int DUMP_LIBS = 1 << 0; 12213 public static final int DUMP_FEATURES = 1 << 1; 12214 public static final int DUMP_RESOLVERS = 1 << 2; 12215 public static final int DUMP_PERMISSIONS = 1 << 3; 12216 public static final int DUMP_PACKAGES = 1 << 4; 12217 public static final int DUMP_SHARED_USERS = 1 << 5; 12218 public static final int DUMP_MESSAGES = 1 << 6; 12219 public static final int DUMP_PROVIDERS = 1 << 7; 12220 public static final int DUMP_VERIFIERS = 1 << 8; 12221 public static final int DUMP_PREFERRED = 1 << 9; 12222 public static final int DUMP_PREFERRED_XML = 1 << 10; 12223 public static final int DUMP_KEYSETS = 1 << 11; 12224 public static final int DUMP_VERSION = 1 << 12; 12225 public static final int DUMP_INSTALLS = 1 << 13; 12226 12227 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12228 12229 private int mTypes; 12230 12231 private int mOptions; 12232 12233 private boolean mTitlePrinted; 12234 12235 private SharedUserSetting mSharedUser; 12236 12237 public boolean isDumping(int type) { 12238 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12239 return true; 12240 } 12241 12242 return (mTypes & type) != 0; 12243 } 12244 12245 public void setDump(int type) { 12246 mTypes |= type; 12247 } 12248 12249 public boolean isOptionEnabled(int option) { 12250 return (mOptions & option) != 0; 12251 } 12252 12253 public void setOptionEnabled(int option) { 12254 mOptions |= option; 12255 } 12256 12257 public boolean onTitlePrinted() { 12258 final boolean printed = mTitlePrinted; 12259 mTitlePrinted = true; 12260 return printed; 12261 } 12262 12263 public boolean getTitlePrinted() { 12264 return mTitlePrinted; 12265 } 12266 12267 public void setTitlePrinted(boolean enabled) { 12268 mTitlePrinted = enabled; 12269 } 12270 12271 public SharedUserSetting getSharedUser() { 12272 return mSharedUser; 12273 } 12274 12275 public void setSharedUser(SharedUserSetting user) { 12276 mSharedUser = user; 12277 } 12278 } 12279 12280 @Override 12281 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12282 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12283 != PackageManager.PERMISSION_GRANTED) { 12284 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12285 + Binder.getCallingPid() 12286 + ", uid=" + Binder.getCallingUid() 12287 + " without permission " 12288 + android.Manifest.permission.DUMP); 12289 return; 12290 } 12291 12292 DumpState dumpState = new DumpState(); 12293 boolean fullPreferred = false; 12294 boolean checkin = false; 12295 12296 String packageName = null; 12297 12298 int opti = 0; 12299 while (opti < args.length) { 12300 String opt = args[opti]; 12301 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12302 break; 12303 } 12304 opti++; 12305 12306 if ("-a".equals(opt)) { 12307 // Right now we only know how to print all. 12308 } else if ("-h".equals(opt)) { 12309 pw.println("Package manager dump options:"); 12310 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12311 pw.println(" --checkin: dump for a checkin"); 12312 pw.println(" -f: print details of intent filters"); 12313 pw.println(" -h: print this help"); 12314 pw.println(" cmd may be one of:"); 12315 pw.println(" l[ibraries]: list known shared libraries"); 12316 pw.println(" f[ibraries]: list device features"); 12317 pw.println(" k[eysets]: print known keysets"); 12318 pw.println(" r[esolvers]: dump intent resolvers"); 12319 pw.println(" perm[issions]: dump permissions"); 12320 pw.println(" pref[erred]: print preferred package settings"); 12321 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12322 pw.println(" prov[iders]: dump content providers"); 12323 pw.println(" p[ackages]: dump installed packages"); 12324 pw.println(" s[hared-users]: dump shared user IDs"); 12325 pw.println(" m[essages]: print collected runtime messages"); 12326 pw.println(" v[erifiers]: print package verifier info"); 12327 pw.println(" version: print database version info"); 12328 pw.println(" write: write current settings now"); 12329 pw.println(" <package.name>: info about given package"); 12330 pw.println(" installs: details about install sessions"); 12331 return; 12332 } else if ("--checkin".equals(opt)) { 12333 checkin = true; 12334 } else if ("-f".equals(opt)) { 12335 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12336 } else { 12337 pw.println("Unknown argument: " + opt + "; use -h for help"); 12338 } 12339 } 12340 12341 // Is the caller requesting to dump a particular piece of data? 12342 if (opti < args.length) { 12343 String cmd = args[opti]; 12344 opti++; 12345 // Is this a package name? 12346 if ("android".equals(cmd) || cmd.contains(".")) { 12347 packageName = cmd; 12348 // When dumping a single package, we always dump all of its 12349 // filter information since the amount of data will be reasonable. 12350 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12351 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12352 dumpState.setDump(DumpState.DUMP_LIBS); 12353 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12354 dumpState.setDump(DumpState.DUMP_FEATURES); 12355 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12356 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12357 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12358 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12359 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12360 dumpState.setDump(DumpState.DUMP_PREFERRED); 12361 } else if ("preferred-xml".equals(cmd)) { 12362 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12363 if (opti < args.length && "--full".equals(args[opti])) { 12364 fullPreferred = true; 12365 opti++; 12366 } 12367 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12368 dumpState.setDump(DumpState.DUMP_PACKAGES); 12369 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12370 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12371 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12372 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12373 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12374 dumpState.setDump(DumpState.DUMP_MESSAGES); 12375 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12376 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12377 } else if ("version".equals(cmd)) { 12378 dumpState.setDump(DumpState.DUMP_VERSION); 12379 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12380 dumpState.setDump(DumpState.DUMP_KEYSETS); 12381 } else if ("installs".equals(cmd)) { 12382 dumpState.setDump(DumpState.DUMP_INSTALLS); 12383 } else if ("write".equals(cmd)) { 12384 synchronized (mPackages) { 12385 mSettings.writeLPr(); 12386 pw.println("Settings written."); 12387 return; 12388 } 12389 } 12390 } 12391 12392 if (checkin) { 12393 pw.println("vers,1"); 12394 } 12395 12396 // reader 12397 synchronized (mPackages) { 12398 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12399 if (!checkin) { 12400 if (dumpState.onTitlePrinted()) 12401 pw.println(); 12402 pw.println("Database versions:"); 12403 pw.print(" SDK Version:"); 12404 pw.print(" internal="); 12405 pw.print(mSettings.mInternalSdkPlatform); 12406 pw.print(" external="); 12407 pw.println(mSettings.mExternalSdkPlatform); 12408 pw.print(" DB Version:"); 12409 pw.print(" internal="); 12410 pw.print(mSettings.mInternalDatabaseVersion); 12411 pw.print(" external="); 12412 pw.println(mSettings.mExternalDatabaseVersion); 12413 } 12414 } 12415 12416 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12417 if (!checkin) { 12418 if (dumpState.onTitlePrinted()) 12419 pw.println(); 12420 pw.println("Verifiers:"); 12421 pw.print(" Required: "); 12422 pw.print(mRequiredVerifierPackage); 12423 pw.print(" (uid="); 12424 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12425 pw.println(")"); 12426 } else if (mRequiredVerifierPackage != null) { 12427 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12428 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12429 } 12430 } 12431 12432 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12433 boolean printedHeader = false; 12434 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12435 while (it.hasNext()) { 12436 String name = it.next(); 12437 SharedLibraryEntry ent = mSharedLibraries.get(name); 12438 if (!checkin) { 12439 if (!printedHeader) { 12440 if (dumpState.onTitlePrinted()) 12441 pw.println(); 12442 pw.println("Libraries:"); 12443 printedHeader = true; 12444 } 12445 pw.print(" "); 12446 } else { 12447 pw.print("lib,"); 12448 } 12449 pw.print(name); 12450 if (!checkin) { 12451 pw.print(" -> "); 12452 } 12453 if (ent.path != null) { 12454 if (!checkin) { 12455 pw.print("(jar) "); 12456 pw.print(ent.path); 12457 } else { 12458 pw.print(",jar,"); 12459 pw.print(ent.path); 12460 } 12461 } else { 12462 if (!checkin) { 12463 pw.print("(apk) "); 12464 pw.print(ent.apk); 12465 } else { 12466 pw.print(",apk,"); 12467 pw.print(ent.apk); 12468 } 12469 } 12470 pw.println(); 12471 } 12472 } 12473 12474 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12475 if (dumpState.onTitlePrinted()) 12476 pw.println(); 12477 if (!checkin) { 12478 pw.println("Features:"); 12479 } 12480 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12481 while (it.hasNext()) { 12482 String name = it.next(); 12483 if (!checkin) { 12484 pw.print(" "); 12485 } else { 12486 pw.print("feat,"); 12487 } 12488 pw.println(name); 12489 } 12490 } 12491 12492 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12493 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12494 : "Activity Resolver Table:", " ", packageName, 12495 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12496 dumpState.setTitlePrinted(true); 12497 } 12498 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12499 : "Receiver Resolver Table:", " ", packageName, 12500 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12501 dumpState.setTitlePrinted(true); 12502 } 12503 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12504 : "Service Resolver Table:", " ", packageName, 12505 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12506 dumpState.setTitlePrinted(true); 12507 } 12508 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12509 : "Provider Resolver Table:", " ", packageName, 12510 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12511 dumpState.setTitlePrinted(true); 12512 } 12513 } 12514 12515 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12516 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12517 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12518 int user = mSettings.mPreferredActivities.keyAt(i); 12519 if (pir.dump(pw, 12520 dumpState.getTitlePrinted() 12521 ? "\nPreferred Activities User " + user + ":" 12522 : "Preferred Activities User " + user + ":", " ", 12523 packageName, true)) { 12524 dumpState.setTitlePrinted(true); 12525 } 12526 } 12527 } 12528 12529 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12530 pw.flush(); 12531 FileOutputStream fout = new FileOutputStream(fd); 12532 BufferedOutputStream str = new BufferedOutputStream(fout); 12533 XmlSerializer serializer = new FastXmlSerializer(); 12534 try { 12535 serializer.setOutput(str, "utf-8"); 12536 serializer.startDocument(null, true); 12537 serializer.setFeature( 12538 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12539 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12540 serializer.endDocument(); 12541 serializer.flush(); 12542 } catch (IllegalArgumentException e) { 12543 pw.println("Failed writing: " + e); 12544 } catch (IllegalStateException e) { 12545 pw.println("Failed writing: " + e); 12546 } catch (IOException e) { 12547 pw.println("Failed writing: " + e); 12548 } 12549 } 12550 12551 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12552 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12553 if (packageName == null) { 12554 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12555 if (iperm == 0) { 12556 if (dumpState.onTitlePrinted()) 12557 pw.println(); 12558 pw.println("AppOp Permissions:"); 12559 } 12560 pw.print(" AppOp Permission "); 12561 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12562 pw.println(":"); 12563 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12564 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12565 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12566 } 12567 } 12568 } 12569 } 12570 12571 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12572 boolean printedSomething = false; 12573 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12574 if (packageName != null && !packageName.equals(p.info.packageName)) { 12575 continue; 12576 } 12577 if (!printedSomething) { 12578 if (dumpState.onTitlePrinted()) 12579 pw.println(); 12580 pw.println("Registered ContentProviders:"); 12581 printedSomething = true; 12582 } 12583 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12584 pw.print(" "); pw.println(p.toString()); 12585 } 12586 printedSomething = false; 12587 for (Map.Entry<String, PackageParser.Provider> entry : 12588 mProvidersByAuthority.entrySet()) { 12589 PackageParser.Provider p = entry.getValue(); 12590 if (packageName != null && !packageName.equals(p.info.packageName)) { 12591 continue; 12592 } 12593 if (!printedSomething) { 12594 if (dumpState.onTitlePrinted()) 12595 pw.println(); 12596 pw.println("ContentProvider Authorities:"); 12597 printedSomething = true; 12598 } 12599 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12600 pw.print(" "); pw.println(p.toString()); 12601 if (p.info != null && p.info.applicationInfo != null) { 12602 final String appInfo = p.info.applicationInfo.toString(); 12603 pw.print(" applicationInfo="); pw.println(appInfo); 12604 } 12605 } 12606 } 12607 12608 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12609 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12610 } 12611 12612 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12613 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12614 } 12615 12616 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12617 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12618 } 12619 12620 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12621 // XXX should handle packageName != null by dumping only install data that 12622 // the given package is involved with. 12623 if (dumpState.onTitlePrinted()) pw.println(); 12624 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12625 } 12626 12627 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12628 if (dumpState.onTitlePrinted()) pw.println(); 12629 mSettings.dumpReadMessagesLPr(pw, dumpState); 12630 12631 pw.println(); 12632 pw.println("Package warning messages:"); 12633 final File fname = getSettingsProblemFile(); 12634 FileInputStream in = null; 12635 try { 12636 in = new FileInputStream(fname); 12637 final int avail = in.available(); 12638 final byte[] data = new byte[avail]; 12639 in.read(data); 12640 pw.print(new String(data)); 12641 } catch (FileNotFoundException e) { 12642 } catch (IOException e) { 12643 } finally { 12644 if (in != null) { 12645 try { 12646 in.close(); 12647 } catch (IOException e) { 12648 } 12649 } 12650 } 12651 } 12652 12653 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12654 BufferedReader in = null; 12655 String line = null; 12656 try { 12657 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12658 while ((line = in.readLine()) != null) { 12659 pw.print("msg,"); 12660 pw.println(line); 12661 } 12662 } catch (IOException ignored) { 12663 } finally { 12664 IoUtils.closeQuietly(in); 12665 } 12666 } 12667 } 12668 } 12669 12670 // ------- apps on sdcard specific code ------- 12671 static final boolean DEBUG_SD_INSTALL = false; 12672 12673 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12674 12675 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12676 12677 private boolean mMediaMounted = false; 12678 12679 static String getEncryptKey() { 12680 try { 12681 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12682 SD_ENCRYPTION_KEYSTORE_NAME); 12683 if (sdEncKey == null) { 12684 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12685 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12686 if (sdEncKey == null) { 12687 Slog.e(TAG, "Failed to create encryption keys"); 12688 return null; 12689 } 12690 } 12691 return sdEncKey; 12692 } catch (NoSuchAlgorithmException nsae) { 12693 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12694 return null; 12695 } catch (IOException ioe) { 12696 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12697 return null; 12698 } 12699 } 12700 12701 /* 12702 * Update media status on PackageManager. 12703 */ 12704 @Override 12705 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12706 int callingUid = Binder.getCallingUid(); 12707 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12708 throw new SecurityException("Media status can only be updated by the system"); 12709 } 12710 // reader; this apparently protects mMediaMounted, but should probably 12711 // be a different lock in that case. 12712 synchronized (mPackages) { 12713 Log.i(TAG, "Updating external media status from " 12714 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12715 + (mediaStatus ? "mounted" : "unmounted")); 12716 if (DEBUG_SD_INSTALL) 12717 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12718 + ", mMediaMounted=" + mMediaMounted); 12719 if (mediaStatus == mMediaMounted) { 12720 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12721 : 0, -1); 12722 mHandler.sendMessage(msg); 12723 return; 12724 } 12725 mMediaMounted = mediaStatus; 12726 } 12727 // Queue up an async operation since the package installation may take a 12728 // little while. 12729 mHandler.post(new Runnable() { 12730 public void run() { 12731 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12732 } 12733 }); 12734 } 12735 12736 /** 12737 * Called by MountService when the initial ASECs to scan are available. 12738 * Should block until all the ASEC containers are finished being scanned. 12739 */ 12740 public void scanAvailableAsecs() { 12741 updateExternalMediaStatusInner(true, false, false); 12742 if (mShouldRestoreconData) { 12743 SELinuxMMAC.setRestoreconDone(); 12744 mShouldRestoreconData = false; 12745 } 12746 } 12747 12748 /* 12749 * Collect information of applications on external media, map them against 12750 * existing containers and update information based on current mount status. 12751 * Please note that we always have to report status if reportStatus has been 12752 * set to true especially when unloading packages. 12753 */ 12754 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12755 boolean externalStorage) { 12756 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12757 int[] uidArr = EmptyArray.INT; 12758 12759 final String[] list = PackageHelper.getSecureContainerList(); 12760 if (ArrayUtils.isEmpty(list)) { 12761 Log.i(TAG, "No secure containers found"); 12762 } else { 12763 // Process list of secure containers and categorize them 12764 // as active or stale based on their package internal state. 12765 12766 // reader 12767 synchronized (mPackages) { 12768 for (String cid : list) { 12769 // Leave stages untouched for now; installer service owns them 12770 if (PackageInstallerService.isStageName(cid)) continue; 12771 12772 if (DEBUG_SD_INSTALL) 12773 Log.i(TAG, "Processing container " + cid); 12774 String pkgName = getAsecPackageName(cid); 12775 if (pkgName == null) { 12776 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12777 continue; 12778 } 12779 if (DEBUG_SD_INSTALL) 12780 Log.i(TAG, "Looking for pkg : " + pkgName); 12781 12782 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12783 if (ps == null) { 12784 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12785 continue; 12786 } 12787 12788 /* 12789 * Skip packages that are not external if we're unmounting 12790 * external storage. 12791 */ 12792 if (externalStorage && !isMounted && !isExternal(ps)) { 12793 continue; 12794 } 12795 12796 final AsecInstallArgs args = new AsecInstallArgs(cid, 12797 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12798 // The package status is changed only if the code path 12799 // matches between settings and the container id. 12800 if (ps.codePathString != null 12801 && ps.codePathString.startsWith(args.getCodePath())) { 12802 if (DEBUG_SD_INSTALL) { 12803 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12804 + " at code path: " + ps.codePathString); 12805 } 12806 12807 // We do have a valid package installed on sdcard 12808 processCids.put(args, ps.codePathString); 12809 final int uid = ps.appId; 12810 if (uid != -1) { 12811 uidArr = ArrayUtils.appendInt(uidArr, uid); 12812 } 12813 } else { 12814 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12815 + ps.codePathString); 12816 } 12817 } 12818 } 12819 12820 Arrays.sort(uidArr); 12821 } 12822 12823 // Process packages with valid entries. 12824 if (isMounted) { 12825 if (DEBUG_SD_INSTALL) 12826 Log.i(TAG, "Loading packages"); 12827 loadMediaPackages(processCids, uidArr); 12828 startCleaningPackages(); 12829 mInstallerService.onSecureContainersAvailable(); 12830 } else { 12831 if (DEBUG_SD_INSTALL) 12832 Log.i(TAG, "Unloading packages"); 12833 unloadMediaPackages(processCids, uidArr, reportStatus); 12834 } 12835 } 12836 12837 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12838 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12839 int size = pkgList.size(); 12840 if (size > 0) { 12841 // Send broadcasts here 12842 Bundle extras = new Bundle(); 12843 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12844 .toArray(new String[size])); 12845 if (uidArr != null) { 12846 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12847 } 12848 if (replacing) { 12849 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12850 } 12851 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12852 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12853 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12854 } 12855 } 12856 12857 /* 12858 * Look at potentially valid container ids from processCids If package 12859 * information doesn't match the one on record or package scanning fails, 12860 * the cid is added to list of removeCids. We currently don't delete stale 12861 * containers. 12862 */ 12863 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12864 ArrayList<String> pkgList = new ArrayList<String>(); 12865 Set<AsecInstallArgs> keys = processCids.keySet(); 12866 12867 for (AsecInstallArgs args : keys) { 12868 String codePath = processCids.get(args); 12869 if (DEBUG_SD_INSTALL) 12870 Log.i(TAG, "Loading container : " + args.cid); 12871 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12872 try { 12873 // Make sure there are no container errors first. 12874 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12875 Slog.e(TAG, "Failed to mount cid : " + args.cid 12876 + " when installing from sdcard"); 12877 continue; 12878 } 12879 // Check code path here. 12880 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12881 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12882 + " does not match one in settings " + codePath); 12883 continue; 12884 } 12885 // Parse package 12886 int parseFlags = mDefParseFlags; 12887 if (args.isExternal()) { 12888 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12889 } 12890 if (args.isFwdLocked()) { 12891 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12892 } 12893 12894 synchronized (mInstallLock) { 12895 PackageParser.Package pkg = null; 12896 try { 12897 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12898 } catch (PackageManagerException e) { 12899 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12900 } 12901 // Scan the package 12902 if (pkg != null) { 12903 /* 12904 * TODO why is the lock being held? doPostInstall is 12905 * called in other places without the lock. This needs 12906 * to be straightened out. 12907 */ 12908 // writer 12909 synchronized (mPackages) { 12910 retCode = PackageManager.INSTALL_SUCCEEDED; 12911 pkgList.add(pkg.packageName); 12912 // Post process args 12913 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12914 pkg.applicationInfo.uid); 12915 } 12916 } else { 12917 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12918 } 12919 } 12920 12921 } finally { 12922 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12923 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12924 } 12925 } 12926 } 12927 // writer 12928 synchronized (mPackages) { 12929 // If the platform SDK has changed since the last time we booted, 12930 // we need to re-grant app permission to catch any new ones that 12931 // appear. This is really a hack, and means that apps can in some 12932 // cases get permissions that the user didn't initially explicitly 12933 // allow... it would be nice to have some better way to handle 12934 // this situation. 12935 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12936 if (regrantPermissions) 12937 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12938 + mSdkVersion + "; regranting permissions for external storage"); 12939 mSettings.mExternalSdkPlatform = mSdkVersion; 12940 12941 // Make sure group IDs have been assigned, and any permission 12942 // changes in other apps are accounted for 12943 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12944 | (regrantPermissions 12945 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12946 : 0)); 12947 12948 mSettings.updateExternalDatabaseVersion(); 12949 12950 // can downgrade to reader 12951 // Persist settings 12952 mSettings.writeLPr(); 12953 } 12954 // Send a broadcast to let everyone know we are done processing 12955 if (pkgList.size() > 0) { 12956 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12957 } 12958 } 12959 12960 /* 12961 * Utility method to unload a list of specified containers 12962 */ 12963 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12964 // Just unmount all valid containers. 12965 for (AsecInstallArgs arg : cidArgs) { 12966 synchronized (mInstallLock) { 12967 arg.doPostDeleteLI(false); 12968 } 12969 } 12970 } 12971 12972 /* 12973 * Unload packages mounted on external media. This involves deleting package 12974 * data from internal structures, sending broadcasts about diabled packages, 12975 * gc'ing to free up references, unmounting all secure containers 12976 * corresponding to packages on external media, and posting a 12977 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12978 * that we always have to post this message if status has been requested no 12979 * matter what. 12980 */ 12981 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12982 final boolean reportStatus) { 12983 if (DEBUG_SD_INSTALL) 12984 Log.i(TAG, "unloading media packages"); 12985 ArrayList<String> pkgList = new ArrayList<String>(); 12986 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12987 final Set<AsecInstallArgs> keys = processCids.keySet(); 12988 for (AsecInstallArgs args : keys) { 12989 String pkgName = args.getPackageName(); 12990 if (DEBUG_SD_INSTALL) 12991 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12992 // Delete package internally 12993 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12994 synchronized (mInstallLock) { 12995 boolean res = deletePackageLI(pkgName, null, false, null, null, 12996 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12997 if (res) { 12998 pkgList.add(pkgName); 12999 } else { 13000 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13001 failedList.add(args); 13002 } 13003 } 13004 } 13005 13006 // reader 13007 synchronized (mPackages) { 13008 // We didn't update the settings after removing each package; 13009 // write them now for all packages. 13010 mSettings.writeLPr(); 13011 } 13012 13013 // We have to absolutely send UPDATED_MEDIA_STATUS only 13014 // after confirming that all the receivers processed the ordered 13015 // broadcast when packages get disabled, force a gc to clean things up. 13016 // and unload all the containers. 13017 if (pkgList.size() > 0) { 13018 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13019 new IIntentReceiver.Stub() { 13020 public void performReceive(Intent intent, int resultCode, String data, 13021 Bundle extras, boolean ordered, boolean sticky, 13022 int sendingUser) throws RemoteException { 13023 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13024 reportStatus ? 1 : 0, 1, keys); 13025 mHandler.sendMessage(msg); 13026 } 13027 }); 13028 } else { 13029 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13030 keys); 13031 mHandler.sendMessage(msg); 13032 } 13033 } 13034 13035 /** Binder call */ 13036 @Override 13037 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13038 final int flags) { 13039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13040 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13041 int returnCode = PackageManager.MOVE_SUCCEEDED; 13042 int currInstallFlags = 0; 13043 int newInstallFlags = 0; 13044 13045 File codeFile = null; 13046 String installerPackageName = null; 13047 String packageAbiOverride = null; 13048 13049 // reader 13050 synchronized (mPackages) { 13051 final PackageParser.Package pkg = mPackages.get(packageName); 13052 final PackageSetting ps = mSettings.mPackages.get(packageName); 13053 if (pkg == null || ps == null) { 13054 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13055 } else { 13056 // Disable moving fwd locked apps and system packages 13057 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13058 Slog.w(TAG, "Cannot move system application"); 13059 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13060 } else if (pkg.mOperationPending) { 13061 Slog.w(TAG, "Attempt to move package which has pending operations"); 13062 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13063 } else { 13064 // Find install location first 13065 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13066 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13067 Slog.w(TAG, "Ambigous flags specified for move location."); 13068 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13069 } else { 13070 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13071 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13072 currInstallFlags = isExternal(pkg) 13073 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13074 13075 if (newInstallFlags == currInstallFlags) { 13076 Slog.w(TAG, "No move required. Trying to move to same location"); 13077 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13078 } else { 13079 if (isForwardLocked(pkg)) { 13080 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13081 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13082 } 13083 } 13084 } 13085 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13086 pkg.mOperationPending = true; 13087 } 13088 } 13089 13090 codeFile = new File(pkg.codePath); 13091 installerPackageName = ps.installerPackageName; 13092 packageAbiOverride = ps.cpuAbiOverrideString; 13093 } 13094 } 13095 13096 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13097 try { 13098 observer.packageMoved(packageName, returnCode); 13099 } catch (RemoteException ignored) { 13100 } 13101 return; 13102 } 13103 13104 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13105 @Override 13106 public void onUserActionRequired(Intent intent) throws RemoteException { 13107 throw new IllegalStateException(); 13108 } 13109 13110 @Override 13111 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13112 Bundle extras) throws RemoteException { 13113 Slog.d(TAG, "Install result for move: " 13114 + PackageManager.installStatusToString(returnCode, msg)); 13115 13116 // We usually have a new package now after the install, but if 13117 // we failed we need to clear the pending flag on the original 13118 // package object. 13119 synchronized (mPackages) { 13120 final PackageParser.Package pkg = mPackages.get(packageName); 13121 if (pkg != null) { 13122 pkg.mOperationPending = false; 13123 } 13124 } 13125 13126 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13127 switch (status) { 13128 case PackageInstaller.STATUS_SUCCESS: 13129 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13130 break; 13131 case PackageInstaller.STATUS_FAILURE_STORAGE: 13132 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13133 break; 13134 default: 13135 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13136 break; 13137 } 13138 } 13139 }; 13140 13141 // Treat a move like reinstalling an existing app, which ensures that we 13142 // process everythign uniformly, like unpacking native libraries. 13143 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13144 13145 final Message msg = mHandler.obtainMessage(INIT_COPY); 13146 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13147 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13148 installerPackageName, null, user, packageAbiOverride); 13149 mHandler.sendMessage(msg); 13150 } 13151 13152 @Override 13153 public boolean setInstallLocation(int loc) { 13154 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13155 null); 13156 if (getInstallLocation() == loc) { 13157 return true; 13158 } 13159 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13160 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13161 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13162 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13163 return true; 13164 } 13165 return false; 13166 } 13167 13168 @Override 13169 public int getInstallLocation() { 13170 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13171 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13172 PackageHelper.APP_INSTALL_AUTO); 13173 } 13174 13175 /** Called by UserManagerService */ 13176 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13177 mDirtyUsers.remove(userHandle); 13178 mSettings.removeUserLPw(userHandle); 13179 mPendingBroadcasts.remove(userHandle); 13180 if (mInstaller != null) { 13181 // Technically, we shouldn't be doing this with the package lock 13182 // held. However, this is very rare, and there is already so much 13183 // other disk I/O going on, that we'll let it slide for now. 13184 mInstaller.removeUserDataDirs(userHandle); 13185 } 13186 mUserNeedsBadging.delete(userHandle); 13187 removeUnusedPackagesLILPw(userManager, userHandle); 13188 } 13189 13190 /** 13191 * We're removing userHandle and would like to remove any downloaded packages 13192 * that are no longer in use by any other user. 13193 * @param userHandle the user being removed 13194 */ 13195 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13196 final boolean DEBUG_CLEAN_APKS = false; 13197 int [] users = userManager.getUserIdsLPr(); 13198 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13199 while (psit.hasNext()) { 13200 PackageSetting ps = psit.next(); 13201 if (ps.pkg == null) { 13202 continue; 13203 } 13204 final String packageName = ps.pkg.packageName; 13205 // Skip over if system app 13206 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13207 continue; 13208 } 13209 if (DEBUG_CLEAN_APKS) { 13210 Slog.i(TAG, "Checking package " + packageName); 13211 } 13212 boolean keep = false; 13213 for (int i = 0; i < users.length; i++) { 13214 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13215 keep = true; 13216 if (DEBUG_CLEAN_APKS) { 13217 Slog.i(TAG, " Keeping package " + packageName + " for user " 13218 + users[i]); 13219 } 13220 break; 13221 } 13222 } 13223 if (!keep) { 13224 if (DEBUG_CLEAN_APKS) { 13225 Slog.i(TAG, " Removing package " + packageName); 13226 } 13227 mHandler.post(new Runnable() { 13228 public void run() { 13229 deletePackageX(packageName, userHandle, 0); 13230 } //end run 13231 }); 13232 } 13233 } 13234 } 13235 13236 /** Called by UserManagerService */ 13237 void createNewUserLILPw(int userHandle, File path) { 13238 if (mInstaller != null) { 13239 mInstaller.createUserConfig(userHandle); 13240 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13241 } 13242 } 13243 13244 @Override 13245 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13246 mContext.enforceCallingOrSelfPermission( 13247 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13248 "Only package verification agents can read the verifier device identity"); 13249 13250 synchronized (mPackages) { 13251 return mSettings.getVerifierDeviceIdentityLPw(); 13252 } 13253 } 13254 13255 @Override 13256 public void setPermissionEnforced(String permission, boolean enforced) { 13257 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13258 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13259 synchronized (mPackages) { 13260 if (mSettings.mReadExternalStorageEnforced == null 13261 || mSettings.mReadExternalStorageEnforced != enforced) { 13262 mSettings.mReadExternalStorageEnforced = enforced; 13263 mSettings.writeLPr(); 13264 } 13265 } 13266 // kill any non-foreground processes so we restart them and 13267 // grant/revoke the GID. 13268 final IActivityManager am = ActivityManagerNative.getDefault(); 13269 if (am != null) { 13270 final long token = Binder.clearCallingIdentity(); 13271 try { 13272 am.killProcessesBelowForeground("setPermissionEnforcement"); 13273 } catch (RemoteException e) { 13274 } finally { 13275 Binder.restoreCallingIdentity(token); 13276 } 13277 } 13278 } else { 13279 throw new IllegalArgumentException("No selective enforcement for " + permission); 13280 } 13281 } 13282 13283 @Override 13284 @Deprecated 13285 public boolean isPermissionEnforced(String permission) { 13286 return true; 13287 } 13288 13289 @Override 13290 public boolean isStorageLow() { 13291 final long token = Binder.clearCallingIdentity(); 13292 try { 13293 final DeviceStorageMonitorInternal 13294 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13295 if (dsm != null) { 13296 return dsm.isMemoryLow(); 13297 } else { 13298 return false; 13299 } 13300 } finally { 13301 Binder.restoreCallingIdentity(token); 13302 } 13303 } 13304 13305 @Override 13306 public IPackageInstaller getPackageInstaller() { 13307 return mInstallerService; 13308 } 13309 13310 private boolean userNeedsBadging(int userId) { 13311 int index = mUserNeedsBadging.indexOfKey(userId); 13312 if (index < 0) { 13313 final UserInfo userInfo; 13314 final long token = Binder.clearCallingIdentity(); 13315 try { 13316 userInfo = sUserManager.getUserInfo(userId); 13317 } finally { 13318 Binder.restoreCallingIdentity(token); 13319 } 13320 final boolean b; 13321 if (userInfo != null && userInfo.isManagedProfile()) { 13322 b = true; 13323 } else { 13324 b = false; 13325 } 13326 mUserNeedsBadging.put(userId, b); 13327 return b; 13328 } 13329 return mUserNeedsBadging.valueAt(index); 13330 } 13331 13332 @Override 13333 public KeySet getKeySetByAlias(String packageName, String alias) { 13334 if (packageName == null || alias == null) { 13335 return null; 13336 } 13337 synchronized(mPackages) { 13338 final PackageParser.Package pkg = mPackages.get(packageName); 13339 if (pkg == null) { 13340 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13341 throw new IllegalArgumentException("Unknown package: " + packageName); 13342 } 13343 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13344 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13345 } 13346 } 13347 13348 @Override 13349 public KeySet getSigningKeySet(String packageName) { 13350 if (packageName == null) { 13351 return null; 13352 } 13353 synchronized(mPackages) { 13354 final PackageParser.Package pkg = mPackages.get(packageName); 13355 if (pkg == null) { 13356 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13357 throw new IllegalArgumentException("Unknown package: " + packageName); 13358 } 13359 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13360 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13361 throw new SecurityException("May not access signing KeySet of other apps."); 13362 } 13363 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13364 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13365 } 13366 } 13367 13368 @Override 13369 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13370 if (packageName == null || ks == null) { 13371 return false; 13372 } 13373 synchronized(mPackages) { 13374 final PackageParser.Package pkg = mPackages.get(packageName); 13375 if (pkg == null) { 13376 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13377 throw new IllegalArgumentException("Unknown package: " + packageName); 13378 } 13379 IBinder ksh = ks.getToken(); 13380 if (ksh instanceof KeySetHandle) { 13381 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13382 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13383 } 13384 return false; 13385 } 13386 } 13387 13388 @Override 13389 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13390 if (packageName == null || ks == null) { 13391 return false; 13392 } 13393 synchronized(mPackages) { 13394 final PackageParser.Package pkg = mPackages.get(packageName); 13395 if (pkg == null) { 13396 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13397 throw new IllegalArgumentException("Unknown package: " + packageName); 13398 } 13399 IBinder ksh = ks.getToken(); 13400 if (ksh instanceof KeySetHandle) { 13401 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13402 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13403 } 13404 return false; 13405 } 13406 } 13407 13408 public void getUsageStatsIfNoPackageUsageInfo() { 13409 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13410 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13411 if (usm == null) { 13412 throw new IllegalStateException("UsageStatsManager must be initialized"); 13413 } 13414 long now = System.currentTimeMillis(); 13415 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13416 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13417 String packageName = entry.getKey(); 13418 PackageParser.Package pkg = mPackages.get(packageName); 13419 if (pkg == null) { 13420 continue; 13421 } 13422 UsageStats usage = entry.getValue(); 13423 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13424 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13425 } 13426 } 13427 } 13428} 13429