PackageManagerService.java revision 278dfdf73142e72944478e50a3f02d3b5c6fd370
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.internal.util.ArrayUtils.removeInt; 58 59import android.util.ArrayMap; 60 61import com.android.internal.R; 62import com.android.internal.app.IMediaContainerService; 63import com.android.internal.app.ResolverActivity; 64import com.android.internal.content.NativeLibraryHelper; 65import com.android.internal.content.PackageHelper; 66import com.android.internal.os.IParcelFileDescriptorFactory; 67import com.android.internal.util.ArrayUtils; 68import com.android.internal.util.FastPrintWriter; 69import com.android.internal.util.FastXmlSerializer; 70import com.android.internal.util.IndentingPrintWriter; 71import com.android.server.EventLogTags; 72import com.android.server.IntentResolver; 73import com.android.server.LocalServices; 74import com.android.server.ServiceThread; 75import com.android.server.SystemConfig; 76import com.android.server.Watchdog; 77import com.android.server.pm.Settings.DatabaseVersion; 78import com.android.server.storage.DeviceStorageMonitorInternal; 79 80import org.xmlpull.v1.XmlSerializer; 81 82import android.app.ActivityManager; 83import android.app.ActivityManagerNative; 84import android.app.AppGlobals; 85import android.app.IActivityManager; 86import android.app.admin.IDevicePolicyManager; 87import android.app.backup.IBackupManager; 88import android.app.usage.UsageStats; 89import android.app.usage.UsageStatsManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageDeleteObserver2; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.KeySet; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 116import android.content.pm.PackageInstaller; 117import android.content.pm.PackageManager; 118import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 119import android.content.pm.PackageParser.ActivityIntentInfo; 120import android.content.pm.PackageParser.PackageLite; 121import android.content.pm.PackageParser.PackageParserException; 122import android.content.pm.PackageParser; 123import android.content.pm.PackageStats; 124import android.content.pm.PackageUserState; 125import android.content.pm.ParceledListSlice; 126import android.content.pm.PermissionGroupInfo; 127import android.content.pm.PermissionInfo; 128import android.content.pm.ProviderInfo; 129import android.content.pm.ResolveInfo; 130import android.content.pm.ServiceInfo; 131import android.content.pm.Signature; 132import android.content.pm.UserInfo; 133import android.content.pm.VerificationParams; 134import android.content.pm.VerifierDeviceIdentity; 135import android.content.pm.VerifierInfo; 136import android.content.res.Resources; 137import android.hardware.display.DisplayManager; 138import android.net.Uri; 139import android.os.Binder; 140import android.os.Build; 141import android.os.Bundle; 142import android.os.Environment; 143import android.os.Environment.UserEnvironment; 144import android.os.storage.StorageManager; 145import android.os.Debug; 146import android.os.FileUtils; 147import android.os.Handler; 148import android.os.IBinder; 149import android.os.Looper; 150import android.os.Message; 151import android.os.Parcel; 152import android.os.ParcelFileDescriptor; 153import android.os.Process; 154import android.os.RemoteException; 155import android.os.SELinux; 156import android.os.ServiceManager; 157import android.os.SystemClock; 158import android.os.SystemProperties; 159import android.os.UserHandle; 160import android.os.UserManager; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.PrintStreamPrinter; 175import android.util.Slog; 176import android.util.SparseArray; 177import android.util.SparseBooleanArray; 178import android.view.Display; 179 180import java.io.BufferedInputStream; 181import java.io.BufferedOutputStream; 182import java.io.BufferedReader; 183import java.io.File; 184import java.io.FileDescriptor; 185import java.io.FileInputStream; 186import java.io.FileNotFoundException; 187import java.io.FileOutputStream; 188import java.io.FileReader; 189import java.io.FilenameFilter; 190import java.io.IOException; 191import java.io.InputStream; 192import java.io.PrintWriter; 193import java.nio.charset.StandardCharsets; 194import java.security.NoSuchAlgorithmException; 195import java.security.PublicKey; 196import java.security.cert.CertificateEncodingException; 197import java.security.cert.CertificateException; 198import java.text.SimpleDateFormat; 199import java.util.ArrayList; 200import java.util.Arrays; 201import java.util.Collection; 202import java.util.Collections; 203import java.util.Comparator; 204import java.util.Date; 205import java.util.Iterator; 206import java.util.List; 207import java.util.Map; 208import java.util.Objects; 209import java.util.Set; 210import java.util.concurrent.atomic.AtomicBoolean; 211import java.util.concurrent.atomic.AtomicLong; 212 213import dalvik.system.DexFile; 214import dalvik.system.StaleDexCacheError; 215import dalvik.system.VMRuntime; 216 217import libcore.io.IoUtils; 218import libcore.util.EmptyArray; 219 220/** 221 * Keep track of all those .apks everywhere. 222 * 223 * This is very central to the platform's security; please run the unit 224 * tests whenever making modifications here: 225 * 226mmm frameworks/base/tests/AndroidTests 227adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 228adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 229 * 230 * {@hide} 231 */ 232public class PackageManagerService extends IPackageManager.Stub { 233 static final String TAG = "PackageManager"; 234 static final boolean DEBUG_SETTINGS = false; 235 static final boolean DEBUG_PREFERRED = false; 236 static final boolean DEBUG_UPGRADE = false; 237 private static final boolean DEBUG_INSTALL = false; 238 private static final boolean DEBUG_REMOVE = false; 239 private static final boolean DEBUG_BROADCASTS = false; 240 private static final boolean DEBUG_SHOW_INFO = false; 241 private static final boolean DEBUG_PACKAGE_INFO = false; 242 private static final boolean DEBUG_INTENT_MATCHING = false; 243 private static final boolean DEBUG_PACKAGE_SCANNING = false; 244 private static final boolean DEBUG_VERIFY = false; 245 private static final boolean DEBUG_DEXOPT = false; 246 private static final boolean DEBUG_ABI_SELECTION = false; 247 248 private static final int RADIO_UID = Process.PHONE_UID; 249 private static final int LOG_UID = Process.LOG_UID; 250 private static final int NFC_UID = Process.NFC_UID; 251 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 252 private static final int SHELL_UID = Process.SHELL_UID; 253 254 // Cap the size of permission trees that 3rd party apps can define 255 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 256 257 // Suffix used during package installation when copying/moving 258 // package apks to install directory. 259 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 260 261 static final int SCAN_NO_DEX = 1<<1; 262 static final int SCAN_FORCE_DEX = 1<<2; 263 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 264 static final int SCAN_NEW_INSTALL = 1<<4; 265 static final int SCAN_NO_PATHS = 1<<5; 266 static final int SCAN_UPDATE_TIME = 1<<6; 267 static final int SCAN_DEFER_DEX = 1<<7; 268 static final int SCAN_BOOTING = 1<<8; 269 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 270 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 271 static final int SCAN_REPLACING = 1<<11; 272 273 static final int REMOVE_CHATTY = 1<<16; 274 275 /** 276 * Timeout (in milliseconds) after which the watchdog should declare that 277 * our handler thread is wedged. The usual default for such things is one 278 * minute but we sometimes do very lengthy I/O operations on this thread, 279 * such as installing multi-gigabyte applications, so ours needs to be longer. 280 */ 281 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 282 283 /** 284 * Whether verification is enabled by default. 285 */ 286 private static final boolean DEFAULT_VERIFY_ENABLE = true; 287 288 /** 289 * The default maximum time to wait for the verification agent to return in 290 * milliseconds. 291 */ 292 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 293 294 /** 295 * The default response for package verification timeout. 296 * 297 * This can be either PackageManager.VERIFICATION_ALLOW or 298 * PackageManager.VERIFICATION_REJECT. 299 */ 300 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 301 302 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 303 304 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 305 DEFAULT_CONTAINER_PACKAGE, 306 "com.android.defcontainer.DefaultContainerService"); 307 308 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 309 310 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 311 312 private static String sPreferredInstructionSet; 313 314 final ServiceThread mHandlerThread; 315 316 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 317 private static final String IDMAP_SUFFIX = "@idmap"; 318 319 final PackageHandler mHandler; 320 321 /** 322 * Messages for {@link #mHandler} that need to wait for system ready before 323 * being dispatched. 324 */ 325 private ArrayList<Message> mPostSystemReadyMessages; 326 327 final int mSdkVersion = Build.VERSION.SDK_INT; 328 329 final Context mContext; 330 final boolean mFactoryTest; 331 final boolean mOnlyCore; 332 final boolean mLazyDexOpt; 333 final long mDexOptLRUThresholdInMills; 334 final DisplayMetrics mMetrics; 335 final int mDefParseFlags; 336 final String[] mSeparateProcesses; 337 final boolean mIsUpgrade; 338 339 // This is where all application persistent data goes. 340 final File mAppDataDir; 341 342 // This is where all application persistent data goes for secondary users. 343 final File mUserAppDataDir; 344 345 /** The location for ASEC container files on internal storage. */ 346 final String mAsecInternalPath; 347 348 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 349 // LOCK HELD. Can be called with mInstallLock held. 350 final Installer mInstaller; 351 352 /** Directory where installed third-party apps stored */ 353 final File mAppInstallDir; 354 355 /** 356 * Directory to which applications installed internally have their 357 * 32 bit native libraries copied. 358 */ 359 private File mAppLib32InstallDir; 360 361 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 362 // apps. 363 final File mDrmAppPrivateInstallDir; 364 365 // ---------------------------------------------------------------- 366 367 // Lock for state used when installing and doing other long running 368 // operations. Methods that must be called with this lock held have 369 // the suffix "LI". 370 final Object mInstallLock = new Object(); 371 372 // ---------------------------------------------------------------- 373 374 // Keys are String (package name), values are Package. This also serves 375 // as the lock for the global state. Methods that must be called with 376 // this lock held have the prefix "LP". 377 final ArrayMap<String, PackageParser.Package> mPackages = 378 new ArrayMap<String, PackageParser.Package>(); 379 380 // Tracks available target package names -> overlay package paths. 381 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 382 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 383 384 final Settings mSettings; 385 boolean mRestoredSettings; 386 387 // System configuration read by SystemConfig. 388 final int[] mGlobalGids; 389 final SparseArray<ArraySet<String>> mSystemPermissions; 390 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 391 392 // If mac_permissions.xml was found for seinfo labeling. 393 boolean mFoundPolicyFile; 394 395 // If a recursive restorecon of /data/data/<pkg> is needed. 396 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 397 398 public static final class SharedLibraryEntry { 399 public final String path; 400 public final String apk; 401 402 SharedLibraryEntry(String _path, String _apk) { 403 path = _path; 404 apk = _apk; 405 } 406 } 407 408 // Currently known shared libraries. 409 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 410 new ArrayMap<String, SharedLibraryEntry>(); 411 412 // All available activities, for your resolving pleasure. 413 final ActivityIntentResolver mActivities = 414 new ActivityIntentResolver(); 415 416 // All available receivers, for your resolving pleasure. 417 final ActivityIntentResolver mReceivers = 418 new ActivityIntentResolver(); 419 420 // All available services, for your resolving pleasure. 421 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 422 423 // All available providers, for your resolving pleasure. 424 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 425 426 // Mapping from provider base names (first directory in content URI codePath) 427 // to the provider information. 428 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 429 new ArrayMap<String, PackageParser.Provider>(); 430 431 // Mapping from instrumentation class names to info about them. 432 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 433 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 434 435 // Mapping from permission names to info about them. 436 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 437 new ArrayMap<String, PackageParser.PermissionGroup>(); 438 439 // Packages whose data we have transfered into another package, thus 440 // should no longer exist. 441 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 442 443 // Broadcast actions that are only available to the system. 444 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 445 446 /** List of packages waiting for verification. */ 447 final SparseArray<PackageVerificationState> mPendingVerification 448 = new SparseArray<PackageVerificationState>(); 449 450 /** Set of packages associated with each app op permission. */ 451 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 452 453 final PackageInstallerService mInstallerService; 454 455 ArraySet<PackageParser.Package> mDeferredDexOpt = null; 456 457 // Cache of users who need badging. 458 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 459 460 /** Token for keys in mPendingVerification. */ 461 private int mPendingVerificationToken = 0; 462 463 volatile boolean mSystemReady; 464 volatile boolean mSafeMode; 465 volatile boolean mHasSystemUidErrors; 466 467 ApplicationInfo mAndroidApplication; 468 final ActivityInfo mResolveActivity = new ActivityInfo(); 469 final ResolveInfo mResolveInfo = new ResolveInfo(); 470 ComponentName mResolveComponentName; 471 PackageParser.Package mPlatformPackage; 472 ComponentName mCustomResolverComponentName; 473 474 boolean mResolverReplaced = false; 475 476 // Set of pending broadcasts for aggregating enable/disable of components. 477 static class PendingPackageBroadcasts { 478 // for each user id, a map of <package name -> components within that package> 479 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 480 481 public PendingPackageBroadcasts() { 482 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 483 } 484 485 public ArrayList<String> get(int userId, String packageName) { 486 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 487 return packages.get(packageName); 488 } 489 490 public void put(int userId, String packageName, ArrayList<String> components) { 491 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 492 packages.put(packageName, components); 493 } 494 495 public void remove(int userId, String packageName) { 496 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 497 if (packages != null) { 498 packages.remove(packageName); 499 } 500 } 501 502 public void remove(int userId) { 503 mUidMap.remove(userId); 504 } 505 506 public int userIdCount() { 507 return mUidMap.size(); 508 } 509 510 public int userIdAt(int n) { 511 return mUidMap.keyAt(n); 512 } 513 514 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 515 return mUidMap.get(userId); 516 } 517 518 public int size() { 519 // total number of pending broadcast entries across all userIds 520 int num = 0; 521 for (int i = 0; i< mUidMap.size(); i++) { 522 num += mUidMap.valueAt(i).size(); 523 } 524 return num; 525 } 526 527 public void clear() { 528 mUidMap.clear(); 529 } 530 531 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 532 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 533 if (map == null) { 534 map = new ArrayMap<String, ArrayList<String>>(); 535 mUidMap.put(userId, map); 536 } 537 return map; 538 } 539 } 540 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 541 542 // Service Connection to remote media container service to copy 543 // package uri's from external media onto secure containers 544 // or internal storage. 545 private IMediaContainerService mContainerService = null; 546 547 static final int SEND_PENDING_BROADCAST = 1; 548 static final int MCS_BOUND = 3; 549 static final int END_COPY = 4; 550 static final int INIT_COPY = 5; 551 static final int MCS_UNBIND = 6; 552 static final int START_CLEANING_PACKAGE = 7; 553 static final int FIND_INSTALL_LOC = 8; 554 static final int POST_INSTALL = 9; 555 static final int MCS_RECONNECT = 10; 556 static final int MCS_GIVE_UP = 11; 557 static final int UPDATED_MEDIA_STATUS = 12; 558 static final int WRITE_SETTINGS = 13; 559 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 560 static final int PACKAGE_VERIFIED = 15; 561 static final int CHECK_PENDING_VERIFICATION = 16; 562 563 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 564 565 // Delay time in millisecs 566 static final int BROADCAST_DELAY = 10 * 1000; 567 568 static UserManagerService sUserManager; 569 570 // Stores a list of users whose package restrictions file needs to be updated 571 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 572 573 final private DefaultContainerConnection mDefContainerConn = 574 new DefaultContainerConnection(); 575 class DefaultContainerConnection implements ServiceConnection { 576 public void onServiceConnected(ComponentName name, IBinder service) { 577 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 578 IMediaContainerService imcs = 579 IMediaContainerService.Stub.asInterface(service); 580 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 581 } 582 583 public void onServiceDisconnected(ComponentName name) { 584 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 585 } 586 }; 587 588 // Recordkeeping of restore-after-install operations that are currently in flight 589 // between the Package Manager and the Backup Manager 590 class PostInstallData { 591 public InstallArgs args; 592 public PackageInstalledInfo res; 593 594 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 595 args = _a; 596 res = _r; 597 } 598 }; 599 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 600 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 601 602 private final String mRequiredVerifierPackage; 603 604 private final PackageUsage mPackageUsage = new PackageUsage(); 605 606 private class PackageUsage { 607 private static final int WRITE_INTERVAL 608 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 609 610 private final Object mFileLock = new Object(); 611 private final AtomicLong mLastWritten = new AtomicLong(0); 612 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 613 614 private boolean mIsHistoricalPackageUsageAvailable = true; 615 616 boolean isHistoricalPackageUsageAvailable() { 617 return mIsHistoricalPackageUsageAvailable; 618 } 619 620 void write(boolean force) { 621 if (force) { 622 writeInternal(); 623 return; 624 } 625 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 626 && !DEBUG_DEXOPT) { 627 return; 628 } 629 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 630 new Thread("PackageUsage_DiskWriter") { 631 @Override 632 public void run() { 633 try { 634 writeInternal(); 635 } finally { 636 mBackgroundWriteRunning.set(false); 637 } 638 } 639 }.start(); 640 } 641 } 642 643 private void writeInternal() { 644 synchronized (mPackages) { 645 synchronized (mFileLock) { 646 AtomicFile file = getFile(); 647 FileOutputStream f = null; 648 try { 649 f = file.startWrite(); 650 BufferedOutputStream out = new BufferedOutputStream(f); 651 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 652 StringBuilder sb = new StringBuilder(); 653 for (PackageParser.Package pkg : mPackages.values()) { 654 if (pkg.mLastPackageUsageTimeInMills == 0) { 655 continue; 656 } 657 sb.setLength(0); 658 sb.append(pkg.packageName); 659 sb.append(' '); 660 sb.append((long)pkg.mLastPackageUsageTimeInMills); 661 sb.append('\n'); 662 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 663 } 664 out.flush(); 665 file.finishWrite(f); 666 } catch (IOException e) { 667 if (f != null) { 668 file.failWrite(f); 669 } 670 Log.e(TAG, "Failed to write package usage times", e); 671 } 672 } 673 } 674 mLastWritten.set(SystemClock.elapsedRealtime()); 675 } 676 677 void readLP() { 678 synchronized (mFileLock) { 679 AtomicFile file = getFile(); 680 BufferedInputStream in = null; 681 try { 682 in = new BufferedInputStream(file.openRead()); 683 StringBuffer sb = new StringBuffer(); 684 while (true) { 685 String packageName = readToken(in, sb, ' '); 686 if (packageName == null) { 687 break; 688 } 689 String timeInMillisString = readToken(in, sb, '\n'); 690 if (timeInMillisString == null) { 691 throw new IOException("Failed to find last usage time for package " 692 + packageName); 693 } 694 PackageParser.Package pkg = mPackages.get(packageName); 695 if (pkg == null) { 696 continue; 697 } 698 long timeInMillis; 699 try { 700 timeInMillis = Long.parseLong(timeInMillisString.toString()); 701 } catch (NumberFormatException e) { 702 throw new IOException("Failed to parse " + timeInMillisString 703 + " as a long.", e); 704 } 705 pkg.mLastPackageUsageTimeInMills = timeInMillis; 706 } 707 } catch (FileNotFoundException expected) { 708 mIsHistoricalPackageUsageAvailable = false; 709 } catch (IOException e) { 710 Log.w(TAG, "Failed to read package usage times", e); 711 } finally { 712 IoUtils.closeQuietly(in); 713 } 714 } 715 mLastWritten.set(SystemClock.elapsedRealtime()); 716 } 717 718 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 719 throws IOException { 720 sb.setLength(0); 721 while (true) { 722 int ch = in.read(); 723 if (ch == -1) { 724 if (sb.length() == 0) { 725 return null; 726 } 727 throw new IOException("Unexpected EOF"); 728 } 729 if (ch == endOfToken) { 730 return sb.toString(); 731 } 732 sb.append((char)ch); 733 } 734 } 735 736 private AtomicFile getFile() { 737 File dataDir = Environment.getDataDirectory(); 738 File systemDir = new File(dataDir, "system"); 739 File fname = new File(systemDir, "package-usage.list"); 740 return new AtomicFile(fname); 741 } 742 } 743 744 class PackageHandler extends Handler { 745 private boolean mBound = false; 746 final ArrayList<HandlerParams> mPendingInstalls = 747 new ArrayList<HandlerParams>(); 748 749 private boolean connectToService() { 750 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 751 " DefaultContainerService"); 752 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 753 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 754 if (mContext.bindServiceAsUser(service, mDefContainerConn, 755 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 756 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 757 mBound = true; 758 return true; 759 } 760 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 761 return false; 762 } 763 764 private void disconnectService() { 765 mContainerService = null; 766 mBound = false; 767 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 768 mContext.unbindService(mDefContainerConn); 769 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 770 } 771 772 PackageHandler(Looper looper) { 773 super(looper); 774 } 775 776 public void handleMessage(Message msg) { 777 try { 778 doHandleMessage(msg); 779 } finally { 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 } 782 } 783 784 void doHandleMessage(Message msg) { 785 switch (msg.what) { 786 case INIT_COPY: { 787 HandlerParams params = (HandlerParams) msg.obj; 788 int idx = mPendingInstalls.size(); 789 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 790 // If a bind was already initiated we dont really 791 // need to do anything. The pending install 792 // will be processed later on. 793 if (!mBound) { 794 // If this is the only one pending we might 795 // have to bind to the service again. 796 if (!connectToService()) { 797 Slog.e(TAG, "Failed to bind to media container service"); 798 params.serviceError(); 799 return; 800 } else { 801 // Once we bind to the service, the first 802 // pending request will be processed. 803 mPendingInstalls.add(idx, params); 804 } 805 } else { 806 mPendingInstalls.add(idx, params); 807 // Already bound to the service. Just make 808 // sure we trigger off processing the first request. 809 if (idx == 0) { 810 mHandler.sendEmptyMessage(MCS_BOUND); 811 } 812 } 813 break; 814 } 815 case MCS_BOUND: { 816 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 817 if (msg.obj != null) { 818 mContainerService = (IMediaContainerService) msg.obj; 819 } 820 if (mContainerService == null) { 821 // Something seriously wrong. Bail out 822 Slog.e(TAG, "Cannot bind to media container service"); 823 for (HandlerParams params : mPendingInstalls) { 824 // Indicate service bind error 825 params.serviceError(); 826 } 827 mPendingInstalls.clear(); 828 } else if (mPendingInstalls.size() > 0) { 829 HandlerParams params = mPendingInstalls.get(0); 830 if (params != null) { 831 if (params.startCopy()) { 832 // We are done... look for more work or to 833 // go idle. 834 if (DEBUG_SD_INSTALL) Log.i(TAG, 835 "Checking for more work or unbind..."); 836 // Delete pending install 837 if (mPendingInstalls.size() > 0) { 838 mPendingInstalls.remove(0); 839 } 840 if (mPendingInstalls.size() == 0) { 841 if (mBound) { 842 if (DEBUG_SD_INSTALL) Log.i(TAG, 843 "Posting delayed MCS_UNBIND"); 844 removeMessages(MCS_UNBIND); 845 Message ubmsg = obtainMessage(MCS_UNBIND); 846 // Unbind after a little delay, to avoid 847 // continual thrashing. 848 sendMessageDelayed(ubmsg, 10000); 849 } 850 } else { 851 // There are more pending requests in queue. 852 // Just post MCS_BOUND message to trigger processing 853 // of next pending install. 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting MCS_BOUND for next work"); 856 mHandler.sendEmptyMessage(MCS_BOUND); 857 } 858 } 859 } 860 } else { 861 // Should never happen ideally. 862 Slog.w(TAG, "Empty queue"); 863 } 864 break; 865 } 866 case MCS_RECONNECT: { 867 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 868 if (mPendingInstalls.size() > 0) { 869 if (mBound) { 870 disconnectService(); 871 } 872 if (!connectToService()) { 873 Slog.e(TAG, "Failed to bind to media container service"); 874 for (HandlerParams params : mPendingInstalls) { 875 // Indicate service bind error 876 params.serviceError(); 877 } 878 mPendingInstalls.clear(); 879 } 880 } 881 break; 882 } 883 case MCS_UNBIND: { 884 // If there is no actual work left, then time to unbind. 885 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 886 887 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 888 if (mBound) { 889 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 890 891 disconnectService(); 892 } 893 } else if (mPendingInstalls.size() > 0) { 894 // There are more pending requests in queue. 895 // Just post MCS_BOUND message to trigger processing 896 // of next pending install. 897 mHandler.sendEmptyMessage(MCS_BOUND); 898 } 899 900 break; 901 } 902 case MCS_GIVE_UP: { 903 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 904 mPendingInstalls.remove(0); 905 break; 906 } 907 case SEND_PENDING_BROADCAST: { 908 String packages[]; 909 ArrayList<String> components[]; 910 int size = 0; 911 int uids[]; 912 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 913 synchronized (mPackages) { 914 if (mPendingBroadcasts == null) { 915 return; 916 } 917 size = mPendingBroadcasts.size(); 918 if (size <= 0) { 919 // Nothing to be done. Just return 920 return; 921 } 922 packages = new String[size]; 923 components = new ArrayList[size]; 924 uids = new int[size]; 925 int i = 0; // filling out the above arrays 926 927 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 928 int packageUserId = mPendingBroadcasts.userIdAt(n); 929 Iterator<Map.Entry<String, ArrayList<String>>> it 930 = mPendingBroadcasts.packagesForUserId(packageUserId) 931 .entrySet().iterator(); 932 while (it.hasNext() && i < size) { 933 Map.Entry<String, ArrayList<String>> ent = it.next(); 934 packages[i] = ent.getKey(); 935 components[i] = ent.getValue(); 936 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 937 uids[i] = (ps != null) 938 ? UserHandle.getUid(packageUserId, ps.appId) 939 : -1; 940 i++; 941 } 942 } 943 size = i; 944 mPendingBroadcasts.clear(); 945 } 946 // Send broadcasts 947 for (int i = 0; i < size; i++) { 948 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 949 } 950 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 951 break; 952 } 953 case START_CLEANING_PACKAGE: { 954 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 955 final String packageName = (String)msg.obj; 956 final int userId = msg.arg1; 957 final boolean andCode = msg.arg2 != 0; 958 synchronized (mPackages) { 959 if (userId == UserHandle.USER_ALL) { 960 int[] users = sUserManager.getUserIds(); 961 for (int user : users) { 962 mSettings.addPackageToCleanLPw( 963 new PackageCleanItem(user, packageName, andCode)); 964 } 965 } else { 966 mSettings.addPackageToCleanLPw( 967 new PackageCleanItem(userId, packageName, andCode)); 968 } 969 } 970 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 971 startCleaningPackages(); 972 } break; 973 case POST_INSTALL: { 974 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 975 PostInstallData data = mRunningInstalls.get(msg.arg1); 976 mRunningInstalls.delete(msg.arg1); 977 boolean deleteOld = false; 978 979 if (data != null) { 980 InstallArgs args = data.args; 981 PackageInstalledInfo res = data.res; 982 983 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 984 res.removedInfo.sendBroadcast(false, true, false); 985 Bundle extras = new Bundle(1); 986 extras.putInt(Intent.EXTRA_UID, res.uid); 987 // Determine the set of users who are adding this 988 // package for the first time vs. those who are seeing 989 // an update. 990 int[] firstUsers; 991 int[] updateUsers = new int[0]; 992 if (res.origUsers == null || res.origUsers.length == 0) { 993 firstUsers = res.newUsers; 994 } else { 995 firstUsers = new int[0]; 996 for (int i=0; i<res.newUsers.length; i++) { 997 int user = res.newUsers[i]; 998 boolean isNew = true; 999 for (int j=0; j<res.origUsers.length; j++) { 1000 if (res.origUsers[j] == user) { 1001 isNew = false; 1002 break; 1003 } 1004 } 1005 if (isNew) { 1006 int[] newFirst = new int[firstUsers.length+1]; 1007 System.arraycopy(firstUsers, 0, newFirst, 0, 1008 firstUsers.length); 1009 newFirst[firstUsers.length] = user; 1010 firstUsers = newFirst; 1011 } else { 1012 int[] newUpdate = new int[updateUsers.length+1]; 1013 System.arraycopy(updateUsers, 0, newUpdate, 0, 1014 updateUsers.length); 1015 newUpdate[updateUsers.length] = user; 1016 updateUsers = newUpdate; 1017 } 1018 } 1019 } 1020 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1021 res.pkg.applicationInfo.packageName, 1022 extras, null, null, firstUsers); 1023 final boolean update = res.removedInfo.removedPackage != null; 1024 if (update) { 1025 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1026 } 1027 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1028 res.pkg.applicationInfo.packageName, 1029 extras, null, null, updateUsers); 1030 if (update) { 1031 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1032 res.pkg.applicationInfo.packageName, 1033 extras, null, null, updateUsers); 1034 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1035 null, null, 1036 res.pkg.applicationInfo.packageName, null, updateUsers); 1037 1038 // treat asec-hosted packages like removable media on upgrade 1039 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1040 if (DEBUG_INSTALL) { 1041 Slog.i(TAG, "upgrading pkg " + res.pkg 1042 + " is ASEC-hosted -> AVAILABLE"); 1043 } 1044 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1045 ArrayList<String> pkgList = new ArrayList<String>(1); 1046 pkgList.add(res.pkg.applicationInfo.packageName); 1047 sendResourcesChangedBroadcast(true, true, 1048 pkgList,uidArray, null); 1049 } 1050 } 1051 if (res.removedInfo.args != null) { 1052 // Remove the replaced package's older resources safely now 1053 deleteOld = true; 1054 } 1055 1056 // Log current value of "unknown sources" setting 1057 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1058 getUnknownSourcesSettings()); 1059 } 1060 // Force a gc to clear up things 1061 Runtime.getRuntime().gc(); 1062 // We delete after a gc for applications on sdcard. 1063 if (deleteOld) { 1064 synchronized (mInstallLock) { 1065 res.removedInfo.args.doPostDeleteLI(true); 1066 } 1067 } 1068 if (args.observer != null) { 1069 try { 1070 Bundle extras = extrasForInstallResult(res); 1071 args.observer.onPackageInstalled(res.name, res.returnCode, 1072 res.returnMsg, extras); 1073 } catch (RemoteException e) { 1074 Slog.i(TAG, "Observer no longer exists."); 1075 } 1076 } 1077 } else { 1078 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1079 } 1080 } break; 1081 case UPDATED_MEDIA_STATUS: { 1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1083 boolean reportStatus = msg.arg1 == 1; 1084 boolean doGc = msg.arg2 == 1; 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1086 if (doGc) { 1087 // Force a gc to clear up stale containers. 1088 Runtime.getRuntime().gc(); 1089 } 1090 if (msg.obj != null) { 1091 @SuppressWarnings("unchecked") 1092 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1094 // Unload containers 1095 unloadAllContainers(args); 1096 } 1097 if (reportStatus) { 1098 try { 1099 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1100 PackageHelper.getMountService().finishMediaUpdate(); 1101 } catch (RemoteException e) { 1102 Log.e(TAG, "MountService not running?"); 1103 } 1104 } 1105 } break; 1106 case WRITE_SETTINGS: { 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1108 synchronized (mPackages) { 1109 removeMessages(WRITE_SETTINGS); 1110 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1111 mSettings.writeLPr(); 1112 mDirtyUsers.clear(); 1113 } 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } break; 1116 case WRITE_PACKAGE_RESTRICTIONS: { 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1118 synchronized (mPackages) { 1119 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1120 for (int userId : mDirtyUsers) { 1121 mSettings.writePackageRestrictionsLPr(userId); 1122 } 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case CHECK_PENDING_VERIFICATION: { 1128 final int verificationId = msg.arg1; 1129 final PackageVerificationState state = mPendingVerification.get(verificationId); 1130 1131 if ((state != null) && !state.timeoutExtended()) { 1132 final InstallArgs args = state.getInstallArgs(); 1133 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1134 1135 Slog.i(TAG, "Verification timed out for " + originUri); 1136 mPendingVerification.remove(verificationId); 1137 1138 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1139 1140 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1141 Slog.i(TAG, "Continuing with installation of " + originUri); 1142 state.setVerifierResponse(Binder.getCallingUid(), 1143 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1144 broadcastPackageVerified(verificationId, originUri, 1145 PackageManager.VERIFICATION_ALLOW, 1146 state.getInstallArgs().getUser()); 1147 try { 1148 ret = args.copyApk(mContainerService, true); 1149 } catch (RemoteException e) { 1150 Slog.e(TAG, "Could not contact the ContainerService"); 1151 } 1152 } else { 1153 broadcastPackageVerified(verificationId, originUri, 1154 PackageManager.VERIFICATION_REJECT, 1155 state.getInstallArgs().getUser()); 1156 } 1157 1158 processPendingInstall(args, ret); 1159 mHandler.sendEmptyMessage(MCS_UNBIND); 1160 } 1161 break; 1162 } 1163 case PACKAGE_VERIFIED: { 1164 final int verificationId = msg.arg1; 1165 1166 final PackageVerificationState state = mPendingVerification.get(verificationId); 1167 if (state == null) { 1168 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1169 break; 1170 } 1171 1172 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1173 1174 state.setVerifierResponse(response.callerUid, response.code); 1175 1176 if (state.isVerificationComplete()) { 1177 mPendingVerification.remove(verificationId); 1178 1179 final InstallArgs args = state.getInstallArgs(); 1180 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1181 1182 int ret; 1183 if (state.isInstallAllowed()) { 1184 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1185 broadcastPackageVerified(verificationId, originUri, 1186 response.code, state.getInstallArgs().getUser()); 1187 try { 1188 ret = args.copyApk(mContainerService, true); 1189 } catch (RemoteException e) { 1190 Slog.e(TAG, "Could not contact the ContainerService"); 1191 } 1192 } else { 1193 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1194 } 1195 1196 processPendingInstall(args, ret); 1197 1198 mHandler.sendEmptyMessage(MCS_UNBIND); 1199 } 1200 1201 break; 1202 } 1203 } 1204 } 1205 } 1206 1207 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1208 Bundle extras = null; 1209 switch (res.returnCode) { 1210 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1211 extras = new Bundle(); 1212 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1213 res.origPermission); 1214 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1215 res.origPackage); 1216 break; 1217 } 1218 } 1219 return extras; 1220 } 1221 1222 void scheduleWriteSettingsLocked() { 1223 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1224 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1225 } 1226 } 1227 1228 void scheduleWritePackageRestrictionsLocked(int userId) { 1229 if (!sUserManager.exists(userId)) return; 1230 mDirtyUsers.add(userId); 1231 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1232 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1233 } 1234 } 1235 1236 public static final PackageManagerService main(Context context, Installer installer, 1237 boolean factoryTest, boolean onlyCore) { 1238 PackageManagerService m = new PackageManagerService(context, installer, 1239 factoryTest, onlyCore); 1240 ServiceManager.addService("package", m); 1241 return m; 1242 } 1243 1244 static String[] splitString(String str, char sep) { 1245 int count = 1; 1246 int i = 0; 1247 while ((i=str.indexOf(sep, i)) >= 0) { 1248 count++; 1249 i++; 1250 } 1251 1252 String[] res = new String[count]; 1253 i=0; 1254 count = 0; 1255 int lastI=0; 1256 while ((i=str.indexOf(sep, i)) >= 0) { 1257 res[count] = str.substring(lastI, i); 1258 count++; 1259 i++; 1260 lastI = i; 1261 } 1262 res[count] = str.substring(lastI, str.length()); 1263 return res; 1264 } 1265 1266 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1267 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1268 Context.DISPLAY_SERVICE); 1269 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1270 } 1271 1272 public PackageManagerService(Context context, Installer installer, 1273 boolean factoryTest, boolean onlyCore) { 1274 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1275 SystemClock.uptimeMillis()); 1276 1277 if (mSdkVersion <= 0) { 1278 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1279 } 1280 1281 mContext = context; 1282 mFactoryTest = factoryTest; 1283 mOnlyCore = onlyCore; 1284 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1285 mMetrics = new DisplayMetrics(); 1286 mSettings = new Settings(context); 1287 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 1300 // TODO: add a property to control this? 1301 long dexOptLRUThresholdInMinutes; 1302 if (mLazyDexOpt) { 1303 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1304 } else { 1305 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1306 } 1307 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1308 1309 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1310 if (separateProcesses != null && separateProcesses.length() > 0) { 1311 if ("*".equals(separateProcesses)) { 1312 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1313 mSeparateProcesses = null; 1314 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1315 } else { 1316 mDefParseFlags = 0; 1317 mSeparateProcesses = separateProcesses.split(","); 1318 Slog.w(TAG, "Running with debug.separate_processes: " 1319 + separateProcesses); 1320 } 1321 } else { 1322 mDefParseFlags = 0; 1323 mSeparateProcesses = null; 1324 } 1325 1326 mInstaller = installer; 1327 1328 getDefaultDisplayMetrics(context, mMetrics); 1329 1330 SystemConfig systemConfig = SystemConfig.getInstance(); 1331 mGlobalGids = systemConfig.getGlobalGids(); 1332 mSystemPermissions = systemConfig.getSystemPermissions(); 1333 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1334 1335 synchronized (mInstallLock) { 1336 // writer 1337 synchronized (mPackages) { 1338 mHandlerThread = new ServiceThread(TAG, 1339 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1340 mHandlerThread.start(); 1341 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1342 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1343 1344 File dataDir = Environment.getDataDirectory(); 1345 mAppDataDir = new File(dataDir, "data"); 1346 mAppInstallDir = new File(dataDir, "app"); 1347 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1348 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1349 mUserAppDataDir = new File(dataDir, "user"); 1350 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1351 1352 sUserManager = new UserManagerService(context, this, 1353 mInstallLock, mPackages); 1354 1355 // Propagate permission configuration in to package manager. 1356 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1357 = systemConfig.getPermissions(); 1358 for (int i=0; i<permConfig.size(); i++) { 1359 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1360 BasePermission bp = mSettings.mPermissions.get(perm.name); 1361 if (bp == null) { 1362 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1363 mSettings.mPermissions.put(perm.name, bp); 1364 } 1365 if (perm.gids != null) { 1366 bp.gids = appendInts(bp.gids, perm.gids); 1367 } 1368 } 1369 1370 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1371 for (int i=0; i<libConfig.size(); i++) { 1372 mSharedLibraries.put(libConfig.keyAt(i), 1373 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1374 } 1375 1376 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1377 1378 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1379 mSdkVersion, mOnlyCore); 1380 1381 String customResolverActivity = Resources.getSystem().getString( 1382 R.string.config_customResolverActivity); 1383 if (TextUtils.isEmpty(customResolverActivity)) { 1384 customResolverActivity = null; 1385 } else { 1386 mCustomResolverComponentName = ComponentName.unflattenFromString( 1387 customResolverActivity); 1388 } 1389 1390 long startTime = SystemClock.uptimeMillis(); 1391 1392 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1393 startTime); 1394 1395 // Set flag to monitor and not change apk file paths when 1396 // scanning install directories. 1397 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1398 1399 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1400 1401 /** 1402 * Add everything in the in the boot class path to the 1403 * list of process files because dexopt will have been run 1404 * if necessary during zygote startup. 1405 */ 1406 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1407 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1408 1409 if (bootClassPath != null) { 1410 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1411 for (String element : bootClassPathElements) { 1412 alreadyDexOpted.add(element); 1413 } 1414 } else { 1415 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1416 } 1417 1418 if (systemServerClassPath != null) { 1419 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1420 for (String element : systemServerClassPathElements) { 1421 alreadyDexOpted.add(element); 1422 } 1423 } else { 1424 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1425 } 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 } 1460 } catch (FileNotFoundException e) { 1461 Slog.w(TAG, "Library not found: " + lib); 1462 } catch (IOException e) { 1463 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1464 + e.getMessage()); 1465 } 1466 } 1467 } 1468 } 1469 1470 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1471 1472 // Gross hack for now: we know this file doesn't contain any 1473 // code, so don't dexopt it to avoid the resulting log spew. 1474 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1475 1476 // Gross hack for now: we know this file is only part of 1477 // the boot class path for art, so don't dexopt it to 1478 // avoid the resulting log spew. 1479 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1480 1481 /** 1482 * And there are a number of commands implemented in Java, which 1483 * we currently need to do the dexopt on so that they can be 1484 * run from a non-root shell. 1485 */ 1486 String[] frameworkFiles = frameworkDir.list(); 1487 if (frameworkFiles != null) { 1488 // TODO: We could compile these only for the most preferred ABI. We should 1489 // first double check that the dex files for these commands are not referenced 1490 // by other system apps. 1491 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1492 for (int i=0; i<frameworkFiles.length; i++) { 1493 File libPath = new File(frameworkDir, frameworkFiles[i]); 1494 String path = libPath.getPath(); 1495 // Skip the file if we already did it. 1496 if (alreadyDexOpted.contains(path)) { 1497 continue; 1498 } 1499 // Skip the file if it is not a type we want to dexopt. 1500 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1501 continue; 1502 } 1503 try { 1504 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1505 dexCodeInstructionSet, 1506 false); 1507 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1508 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1509 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1510 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1511 } 1512 } catch (FileNotFoundException e) { 1513 Slog.w(TAG, "Jar not found: " + path); 1514 } catch (IOException e) { 1515 Slog.w(TAG, "Exception reading jar: " + path, e); 1516 } 1517 } 1518 } 1519 } 1520 1521 // Collect vendor overlay packages. 1522 // (Do this before scanning any apps.) 1523 // For security and version matching reason, only consider 1524 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1525 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1526 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1527 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1528 1529 // Find base frameworks (resource packages without code). 1530 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR 1532 | PackageParser.PARSE_IS_PRIVILEGED, 1533 scanFlags | SCAN_NO_DEX, 0); 1534 1535 // Collected privileged system packages. 1536 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1537 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1538 | PackageParser.PARSE_IS_SYSTEM_DIR 1539 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1540 1541 // Collect ordinary system packages. 1542 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1543 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1544 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1545 1546 // Collect all vendor packages. 1547 File vendorAppDir = new File("/vendor/app"); 1548 try { 1549 vendorAppDir = vendorAppDir.getCanonicalFile(); 1550 } catch (IOException e) { 1551 // failed to look up canonical path, continue with original one 1552 } 1553 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1554 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1555 1556 // Collect all OEM packages. 1557 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1558 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1559 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1560 1561 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1562 mInstaller.moveFiles(); 1563 1564 // Prune any system packages that no longer exist. 1565 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1566 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1567 if (!mOnlyCore) { 1568 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1569 while (psit.hasNext()) { 1570 PackageSetting ps = psit.next(); 1571 1572 /* 1573 * If this is not a system app, it can't be a 1574 * disable system app. 1575 */ 1576 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1577 continue; 1578 } 1579 1580 /* 1581 * If the package is scanned, it's not erased. 1582 */ 1583 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1584 if (scannedPkg != null) { 1585 /* 1586 * If the system app is both scanned and in the 1587 * disabled packages list, then it must have been 1588 * added via OTA. Remove it from the currently 1589 * scanned package so the previously user-installed 1590 * application can be scanned. 1591 */ 1592 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1593 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1594 + ps.name + "; removing system app. Last known codePath=" 1595 + ps.codePathString + ", installStatus=" + ps.installStatus 1596 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1597 + scannedPkg.mVersionCode); 1598 removePackageLI(ps, true); 1599 expectingBetter.put(ps.name, ps.codePath); 1600 } 1601 1602 continue; 1603 } 1604 1605 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1606 psit.remove(); 1607 logCriticalInfo(Log.WARN, "System package " + ps.name 1608 + " no longer exists; wiping its data"); 1609 removeDataDirsLI(ps.name); 1610 } else { 1611 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1612 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1613 possiblyDeletedUpdatedSystemApps.add(ps.name); 1614 } 1615 } 1616 } 1617 } 1618 1619 //look for any incomplete package installations 1620 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1621 //clean up list 1622 for(int i = 0; i < deletePkgsList.size(); i++) { 1623 //clean up here 1624 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1625 } 1626 //delete tmp files 1627 deleteTempPackageFiles(); 1628 1629 // Remove any shared userIDs that have no associated packages 1630 mSettings.pruneSharedUsersLPw(); 1631 1632 if (!mOnlyCore) { 1633 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1634 SystemClock.uptimeMillis()); 1635 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1636 1637 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1638 scanFlags, 0); 1639 1640 /** 1641 * Remove disable package settings for any updated system 1642 * apps that were removed via an OTA. If they're not a 1643 * previously-updated app, remove them completely. 1644 * Otherwise, just revoke their system-level permissions. 1645 */ 1646 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1647 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1648 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1649 1650 String msg; 1651 if (deletedPkg == null) { 1652 msg = "Updated system package " + deletedAppName 1653 + " no longer exists; wiping its data"; 1654 removeDataDirsLI(deletedAppName); 1655 } else { 1656 msg = "Updated system app + " + deletedAppName 1657 + " no longer present; removing system privileges for " 1658 + deletedAppName; 1659 1660 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1661 1662 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1663 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1664 } 1665 logCriticalInfo(Log.WARN, msg); 1666 } 1667 1668 /** 1669 * Make sure all system apps that we expected to appear on 1670 * the userdata partition actually showed up. If they never 1671 * appeared, crawl back and revive the system version. 1672 */ 1673 for (int i = 0; i < expectingBetter.size(); i++) { 1674 final String packageName = expectingBetter.keyAt(i); 1675 if (!mPackages.containsKey(packageName)) { 1676 final File scanFile = expectingBetter.valueAt(i); 1677 1678 logCriticalInfo(Log.WARN, "Expected better " + packageName 1679 + " but never showed up; reverting to system"); 1680 1681 final int reparseFlags; 1682 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1683 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1684 | PackageParser.PARSE_IS_SYSTEM_DIR 1685 | PackageParser.PARSE_IS_PRIVILEGED; 1686 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1687 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1688 | PackageParser.PARSE_IS_SYSTEM_DIR; 1689 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1690 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1691 | PackageParser.PARSE_IS_SYSTEM_DIR; 1692 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1693 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1694 | PackageParser.PARSE_IS_SYSTEM_DIR; 1695 } else { 1696 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1697 continue; 1698 } 1699 1700 mSettings.enableSystemPackageLPw(packageName); 1701 1702 try { 1703 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1704 } catch (PackageManagerException e) { 1705 Slog.e(TAG, "Failed to parse original system package: " 1706 + e.getMessage()); 1707 } 1708 } 1709 } 1710 } 1711 1712 // Now that we know all of the shared libraries, update all clients to have 1713 // the correct library paths. 1714 updateAllSharedLibrariesLPw(); 1715 1716 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1717 // NOTE: We ignore potential failures here during a system scan (like 1718 // the rest of the commands above) because there's precious little we 1719 // can do about it. A settings error is reported, though. 1720 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1721 false /* force dexopt */, false /* defer dexopt */); 1722 } 1723 1724 // Now that we know all the packages we are keeping, 1725 // read and update their last usage times. 1726 mPackageUsage.readLP(); 1727 1728 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1729 SystemClock.uptimeMillis()); 1730 Slog.i(TAG, "Time to scan packages: " 1731 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1732 + " seconds"); 1733 1734 // If the platform SDK has changed since the last time we booted, 1735 // we need to re-grant app permission to catch any new ones that 1736 // appear. This is really a hack, and means that apps can in some 1737 // cases get permissions that the user didn't initially explicitly 1738 // allow... it would be nice to have some better way to handle 1739 // this situation. 1740 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1741 != mSdkVersion; 1742 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1743 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1744 + "; regranting permissions for internal storage"); 1745 mSettings.mInternalSdkPlatform = mSdkVersion; 1746 1747 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1748 | (regrantPermissions 1749 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1750 : 0)); 1751 1752 // If this is the first boot, and it is a normal boot, then 1753 // we need to initialize the default preferred apps. 1754 if (!mRestoredSettings && !onlyCore) { 1755 mSettings.readDefaultPreferredAppsLPw(this, 0); 1756 } 1757 1758 // If this is first boot after an OTA, and a normal boot, then 1759 // we need to clear code cache directories. 1760 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1761 if (mIsUpgrade && !onlyCore) { 1762 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1763 for (String pkgName : mSettings.mPackages.keySet()) { 1764 deleteCodeCacheDirsLI(pkgName); 1765 } 1766 mSettings.mFingerprint = Build.FINGERPRINT; 1767 } 1768 1769 // All the changes are done during package scanning. 1770 mSettings.updateInternalDatabaseVersion(); 1771 1772 // can downgrade to reader 1773 mSettings.writeLPr(); 1774 1775 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1776 SystemClock.uptimeMillis()); 1777 1778 1779 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1780 } // synchronized (mPackages) 1781 } // synchronized (mInstallLock) 1782 1783 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1784 1785 // Now after opening every single application zip, make sure they 1786 // are all flushed. Not really needed, but keeps things nice and 1787 // tidy. 1788 Runtime.getRuntime().gc(); 1789 } 1790 1791 @Override 1792 public boolean isFirstBoot() { 1793 return !mRestoredSettings; 1794 } 1795 1796 @Override 1797 public boolean isOnlyCoreApps() { 1798 return mOnlyCore; 1799 } 1800 1801 @Override 1802 public boolean isUpgrade() { 1803 return mIsUpgrade; 1804 } 1805 1806 private String getRequiredVerifierLPr() { 1807 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1808 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1809 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1810 1811 String requiredVerifier = null; 1812 1813 final int N = receivers.size(); 1814 for (int i = 0; i < N; i++) { 1815 final ResolveInfo info = receivers.get(i); 1816 1817 if (info.activityInfo == null) { 1818 continue; 1819 } 1820 1821 final String packageName = info.activityInfo.packageName; 1822 1823 final PackageSetting ps = mSettings.mPackages.get(packageName); 1824 if (ps == null) { 1825 continue; 1826 } 1827 1828 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1829 if (!gp.grantedPermissions 1830 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1831 continue; 1832 } 1833 1834 if (requiredVerifier != null) { 1835 throw new RuntimeException("There can be only one required verifier"); 1836 } 1837 1838 requiredVerifier = packageName; 1839 } 1840 1841 return requiredVerifier; 1842 } 1843 1844 @Override 1845 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1846 throws RemoteException { 1847 try { 1848 return super.onTransact(code, data, reply, flags); 1849 } catch (RuntimeException e) { 1850 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1851 Slog.wtf(TAG, "Package Manager Crash", e); 1852 } 1853 throw e; 1854 } 1855 } 1856 1857 void cleanupInstallFailedPackage(PackageSetting ps) { 1858 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1859 1860 removeDataDirsLI(ps.name); 1861 if (ps.codePath != null) { 1862 if (ps.codePath.isDirectory()) { 1863 FileUtils.deleteContents(ps.codePath); 1864 } 1865 ps.codePath.delete(); 1866 } 1867 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1868 if (ps.resourcePath.isDirectory()) { 1869 FileUtils.deleteContents(ps.resourcePath); 1870 } 1871 ps.resourcePath.delete(); 1872 } 1873 mSettings.removePackageLPw(ps.name); 1874 } 1875 1876 static int[] appendInts(int[] cur, int[] add) { 1877 if (add == null) return cur; 1878 if (cur == null) return add; 1879 final int N = add.length; 1880 for (int i=0; i<N; i++) { 1881 cur = appendInt(cur, add[i]); 1882 } 1883 return cur; 1884 } 1885 1886 static int[] removeInts(int[] cur, int[] rem) { 1887 if (rem == null) return cur; 1888 if (cur == null) return cur; 1889 final int N = rem.length; 1890 for (int i=0; i<N; i++) { 1891 cur = removeInt(cur, rem[i]); 1892 } 1893 return cur; 1894 } 1895 1896 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1897 if (!sUserManager.exists(userId)) return null; 1898 final PackageSetting ps = (PackageSetting) p.mExtras; 1899 if (ps == null) { 1900 return null; 1901 } 1902 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1903 final PackageUserState state = ps.readUserState(userId); 1904 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1905 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1906 state, userId); 1907 } 1908 1909 @Override 1910 public boolean isPackageAvailable(String packageName, int userId) { 1911 if (!sUserManager.exists(userId)) return false; 1912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1913 synchronized (mPackages) { 1914 PackageParser.Package p = mPackages.get(packageName); 1915 if (p != null) { 1916 final PackageSetting ps = (PackageSetting) p.mExtras; 1917 if (ps != null) { 1918 final PackageUserState state = ps.readUserState(userId); 1919 if (state != null) { 1920 return PackageParser.isAvailable(state); 1921 } 1922 } 1923 } 1924 } 1925 return false; 1926 } 1927 1928 @Override 1929 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1930 if (!sUserManager.exists(userId)) return null; 1931 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1932 // reader 1933 synchronized (mPackages) { 1934 PackageParser.Package p = mPackages.get(packageName); 1935 if (DEBUG_PACKAGE_INFO) 1936 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1937 if (p != null) { 1938 return generatePackageInfo(p, flags, userId); 1939 } 1940 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1941 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1942 } 1943 } 1944 return null; 1945 } 1946 1947 @Override 1948 public String[] currentToCanonicalPackageNames(String[] names) { 1949 String[] out = new String[names.length]; 1950 // reader 1951 synchronized (mPackages) { 1952 for (int i=names.length-1; i>=0; i--) { 1953 PackageSetting ps = mSettings.mPackages.get(names[i]); 1954 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1955 } 1956 } 1957 return out; 1958 } 1959 1960 @Override 1961 public String[] canonicalToCurrentPackageNames(String[] names) { 1962 String[] out = new String[names.length]; 1963 // reader 1964 synchronized (mPackages) { 1965 for (int i=names.length-1; i>=0; i--) { 1966 String cur = mSettings.mRenamedPackages.get(names[i]); 1967 out[i] = cur != null ? cur : names[i]; 1968 } 1969 } 1970 return out; 1971 } 1972 1973 @Override 1974 public int getPackageUid(String packageName, int userId) { 1975 if (!sUserManager.exists(userId)) return -1; 1976 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1977 // reader 1978 synchronized (mPackages) { 1979 PackageParser.Package p = mPackages.get(packageName); 1980 if(p != null) { 1981 return UserHandle.getUid(userId, p.applicationInfo.uid); 1982 } 1983 PackageSetting ps = mSettings.mPackages.get(packageName); 1984 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1985 return -1; 1986 } 1987 p = ps.pkg; 1988 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1989 } 1990 } 1991 1992 @Override 1993 public int[] getPackageGids(String packageName) { 1994 // reader 1995 synchronized (mPackages) { 1996 PackageParser.Package p = mPackages.get(packageName); 1997 if (DEBUG_PACKAGE_INFO) 1998 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1999 if (p != null) { 2000 final PackageSetting ps = (PackageSetting)p.mExtras; 2001 return ps.getGids(); 2002 } 2003 } 2004 // stupid thing to indicate an error. 2005 return new int[0]; 2006 } 2007 2008 static final PermissionInfo generatePermissionInfo( 2009 BasePermission bp, int flags) { 2010 if (bp.perm != null) { 2011 return PackageParser.generatePermissionInfo(bp.perm, flags); 2012 } 2013 PermissionInfo pi = new PermissionInfo(); 2014 pi.name = bp.name; 2015 pi.packageName = bp.sourcePackage; 2016 pi.nonLocalizedLabel = bp.name; 2017 pi.protectionLevel = bp.protectionLevel; 2018 return pi; 2019 } 2020 2021 @Override 2022 public PermissionInfo getPermissionInfo(String name, int flags) { 2023 // reader 2024 synchronized (mPackages) { 2025 final BasePermission p = mSettings.mPermissions.get(name); 2026 if (p != null) { 2027 return generatePermissionInfo(p, flags); 2028 } 2029 return null; 2030 } 2031 } 2032 2033 @Override 2034 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2035 // reader 2036 synchronized (mPackages) { 2037 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2038 for (BasePermission p : mSettings.mPermissions.values()) { 2039 if (group == null) { 2040 if (p.perm == null || p.perm.info.group == null) { 2041 out.add(generatePermissionInfo(p, flags)); 2042 } 2043 } else { 2044 if (p.perm != null && group.equals(p.perm.info.group)) { 2045 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2046 } 2047 } 2048 } 2049 2050 if (out.size() > 0) { 2051 return out; 2052 } 2053 return mPermissionGroups.containsKey(group) ? out : null; 2054 } 2055 } 2056 2057 @Override 2058 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2059 // reader 2060 synchronized (mPackages) { 2061 return PackageParser.generatePermissionGroupInfo( 2062 mPermissionGroups.get(name), flags); 2063 } 2064 } 2065 2066 @Override 2067 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2068 // reader 2069 synchronized (mPackages) { 2070 final int N = mPermissionGroups.size(); 2071 ArrayList<PermissionGroupInfo> out 2072 = new ArrayList<PermissionGroupInfo>(N); 2073 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2074 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2075 } 2076 return out; 2077 } 2078 } 2079 2080 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2081 int userId) { 2082 if (!sUserManager.exists(userId)) return null; 2083 PackageSetting ps = mSettings.mPackages.get(packageName); 2084 if (ps != null) { 2085 if (ps.pkg == null) { 2086 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2087 flags, userId); 2088 if (pInfo != null) { 2089 return pInfo.applicationInfo; 2090 } 2091 return null; 2092 } 2093 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2094 ps.readUserState(userId), userId); 2095 } 2096 return null; 2097 } 2098 2099 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2100 int userId) { 2101 if (!sUserManager.exists(userId)) return null; 2102 PackageSetting ps = mSettings.mPackages.get(packageName); 2103 if (ps != null) { 2104 PackageParser.Package pkg = ps.pkg; 2105 if (pkg == null) { 2106 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2107 return null; 2108 } 2109 // Only data remains, so we aren't worried about code paths 2110 pkg = new PackageParser.Package(packageName); 2111 pkg.applicationInfo.packageName = packageName; 2112 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2113 pkg.applicationInfo.dataDir = 2114 getDataPathForPackage(packageName, 0).getPath(); 2115 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2116 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2117 } 2118 return generatePackageInfo(pkg, flags, userId); 2119 } 2120 return null; 2121 } 2122 2123 @Override 2124 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2125 if (!sUserManager.exists(userId)) return null; 2126 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2127 // writer 2128 synchronized (mPackages) { 2129 PackageParser.Package p = mPackages.get(packageName); 2130 if (DEBUG_PACKAGE_INFO) Log.v( 2131 TAG, "getApplicationInfo " + packageName 2132 + ": " + p); 2133 if (p != null) { 2134 PackageSetting ps = mSettings.mPackages.get(packageName); 2135 if (ps == null) return null; 2136 // Note: isEnabledLP() does not apply here - always return info 2137 return PackageParser.generateApplicationInfo( 2138 p, flags, ps.readUserState(userId), userId); 2139 } 2140 if ("android".equals(packageName)||"system".equals(packageName)) { 2141 return mAndroidApplication; 2142 } 2143 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2144 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2145 } 2146 } 2147 return null; 2148 } 2149 2150 2151 @Override 2152 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2153 mContext.enforceCallingOrSelfPermission( 2154 android.Manifest.permission.CLEAR_APP_CACHE, null); 2155 // Queue up an async operation since clearing cache may take a little while. 2156 mHandler.post(new Runnable() { 2157 public void run() { 2158 mHandler.removeCallbacks(this); 2159 int retCode = -1; 2160 synchronized (mInstallLock) { 2161 retCode = mInstaller.freeCache(freeStorageSize); 2162 if (retCode < 0) { 2163 Slog.w(TAG, "Couldn't clear application caches"); 2164 } 2165 } 2166 if (observer != null) { 2167 try { 2168 observer.onRemoveCompleted(null, (retCode >= 0)); 2169 } catch (RemoteException e) { 2170 Slog.w(TAG, "RemoveException when invoking call back"); 2171 } 2172 } 2173 } 2174 }); 2175 } 2176 2177 @Override 2178 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2179 mContext.enforceCallingOrSelfPermission( 2180 android.Manifest.permission.CLEAR_APP_CACHE, null); 2181 // Queue up an async operation since clearing cache may take a little while. 2182 mHandler.post(new Runnable() { 2183 public void run() { 2184 mHandler.removeCallbacks(this); 2185 int retCode = -1; 2186 synchronized (mInstallLock) { 2187 retCode = mInstaller.freeCache(freeStorageSize); 2188 if (retCode < 0) { 2189 Slog.w(TAG, "Couldn't clear application caches"); 2190 } 2191 } 2192 if(pi != null) { 2193 try { 2194 // Callback via pending intent 2195 int code = (retCode >= 0) ? 1 : 0; 2196 pi.sendIntent(null, code, null, 2197 null, null); 2198 } catch (SendIntentException e1) { 2199 Slog.i(TAG, "Failed to send pending intent"); 2200 } 2201 } 2202 } 2203 }); 2204 } 2205 2206 void freeStorage(long freeStorageSize) throws IOException { 2207 synchronized (mInstallLock) { 2208 if (mInstaller.freeCache(freeStorageSize) < 0) { 2209 throw new IOException("Failed to free enough space"); 2210 } 2211 } 2212 } 2213 2214 @Override 2215 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2216 if (!sUserManager.exists(userId)) return null; 2217 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2218 synchronized (mPackages) { 2219 PackageParser.Activity a = mActivities.mActivities.get(component); 2220 2221 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2222 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2223 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2224 if (ps == null) return null; 2225 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2226 userId); 2227 } 2228 if (mResolveComponentName.equals(component)) { 2229 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2230 new PackageUserState(), userId); 2231 } 2232 } 2233 return null; 2234 } 2235 2236 @Override 2237 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2238 String resolvedType) { 2239 synchronized (mPackages) { 2240 PackageParser.Activity a = mActivities.mActivities.get(component); 2241 if (a == null) { 2242 return false; 2243 } 2244 for (int i=0; i<a.intents.size(); i++) { 2245 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2246 intent.getData(), intent.getCategories(), TAG) >= 0) { 2247 return true; 2248 } 2249 } 2250 return false; 2251 } 2252 } 2253 2254 @Override 2255 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2256 if (!sUserManager.exists(userId)) return null; 2257 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2258 synchronized (mPackages) { 2259 PackageParser.Activity a = mReceivers.mActivities.get(component); 2260 if (DEBUG_PACKAGE_INFO) Log.v( 2261 TAG, "getReceiverInfo " + component + ": " + a); 2262 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2263 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2264 if (ps == null) return null; 2265 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2266 userId); 2267 } 2268 } 2269 return null; 2270 } 2271 2272 @Override 2273 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2274 if (!sUserManager.exists(userId)) return null; 2275 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2276 synchronized (mPackages) { 2277 PackageParser.Service s = mServices.mServices.get(component); 2278 if (DEBUG_PACKAGE_INFO) Log.v( 2279 TAG, "getServiceInfo " + component + ": " + s); 2280 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2281 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2282 if (ps == null) return null; 2283 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2284 userId); 2285 } 2286 } 2287 return null; 2288 } 2289 2290 @Override 2291 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2292 if (!sUserManager.exists(userId)) return null; 2293 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2294 synchronized (mPackages) { 2295 PackageParser.Provider p = mProviders.mProviders.get(component); 2296 if (DEBUG_PACKAGE_INFO) Log.v( 2297 TAG, "getProviderInfo " + component + ": " + p); 2298 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2299 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2300 if (ps == null) return null; 2301 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2302 userId); 2303 } 2304 } 2305 return null; 2306 } 2307 2308 @Override 2309 public String[] getSystemSharedLibraryNames() { 2310 Set<String> libSet; 2311 synchronized (mPackages) { 2312 libSet = mSharedLibraries.keySet(); 2313 int size = libSet.size(); 2314 if (size > 0) { 2315 String[] libs = new String[size]; 2316 libSet.toArray(libs); 2317 return libs; 2318 } 2319 } 2320 return null; 2321 } 2322 2323 @Override 2324 public FeatureInfo[] getSystemAvailableFeatures() { 2325 Collection<FeatureInfo> featSet; 2326 synchronized (mPackages) { 2327 featSet = mAvailableFeatures.values(); 2328 int size = featSet.size(); 2329 if (size > 0) { 2330 FeatureInfo[] features = new FeatureInfo[size+1]; 2331 featSet.toArray(features); 2332 FeatureInfo fi = new FeatureInfo(); 2333 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2334 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2335 features[size] = fi; 2336 return features; 2337 } 2338 } 2339 return null; 2340 } 2341 2342 @Override 2343 public boolean hasSystemFeature(String name) { 2344 synchronized (mPackages) { 2345 return mAvailableFeatures.containsKey(name); 2346 } 2347 } 2348 2349 private void checkValidCaller(int uid, int userId) { 2350 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2351 return; 2352 2353 throw new SecurityException("Caller uid=" + uid 2354 + " is not privileged to communicate with user=" + userId); 2355 } 2356 2357 @Override 2358 public int checkPermission(String permName, String pkgName) { 2359 synchronized (mPackages) { 2360 PackageParser.Package p = mPackages.get(pkgName); 2361 if (p != null && p.mExtras != null) { 2362 PackageSetting ps = (PackageSetting)p.mExtras; 2363 if (ps.sharedUser != null) { 2364 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2365 return PackageManager.PERMISSION_GRANTED; 2366 } 2367 } else if (ps.grantedPermissions.contains(permName)) { 2368 return PackageManager.PERMISSION_GRANTED; 2369 } 2370 } 2371 } 2372 return PackageManager.PERMISSION_DENIED; 2373 } 2374 2375 @Override 2376 public int checkUidPermission(String permName, int uid) { 2377 synchronized (mPackages) { 2378 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2379 if (obj != null) { 2380 GrantedPermissions gp = (GrantedPermissions)obj; 2381 if (gp.grantedPermissions.contains(permName)) { 2382 return PackageManager.PERMISSION_GRANTED; 2383 } 2384 } else { 2385 ArraySet<String> perms = mSystemPermissions.get(uid); 2386 if (perms != null && perms.contains(permName)) { 2387 return PackageManager.PERMISSION_GRANTED; 2388 } 2389 } 2390 } 2391 return PackageManager.PERMISSION_DENIED; 2392 } 2393 2394 /** 2395 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2396 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2397 * @param checkShell TODO(yamasani): 2398 * @param message the message to log on security exception 2399 */ 2400 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2401 boolean checkShell, String message) { 2402 if (userId < 0) { 2403 throw new IllegalArgumentException("Invalid userId " + userId); 2404 } 2405 if (checkShell) { 2406 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2407 } 2408 if (userId == UserHandle.getUserId(callingUid)) return; 2409 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2410 if (requireFullPermission) { 2411 mContext.enforceCallingOrSelfPermission( 2412 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2413 } else { 2414 try { 2415 mContext.enforceCallingOrSelfPermission( 2416 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2417 } catch (SecurityException se) { 2418 mContext.enforceCallingOrSelfPermission( 2419 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2420 } 2421 } 2422 } 2423 } 2424 2425 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2426 if (callingUid == Process.SHELL_UID) { 2427 if (userHandle >= 0 2428 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2429 throw new SecurityException("Shell does not have permission to access user " 2430 + userHandle); 2431 } else if (userHandle < 0) { 2432 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2433 + Debug.getCallers(3)); 2434 } 2435 } 2436 } 2437 2438 private BasePermission findPermissionTreeLP(String permName) { 2439 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2440 if (permName.startsWith(bp.name) && 2441 permName.length() > bp.name.length() && 2442 permName.charAt(bp.name.length()) == '.') { 2443 return bp; 2444 } 2445 } 2446 return null; 2447 } 2448 2449 private BasePermission checkPermissionTreeLP(String permName) { 2450 if (permName != null) { 2451 BasePermission bp = findPermissionTreeLP(permName); 2452 if (bp != null) { 2453 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2454 return bp; 2455 } 2456 throw new SecurityException("Calling uid " 2457 + Binder.getCallingUid() 2458 + " is not allowed to add to permission tree " 2459 + bp.name + " owned by uid " + bp.uid); 2460 } 2461 } 2462 throw new SecurityException("No permission tree found for " + permName); 2463 } 2464 2465 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2466 if (s1 == null) { 2467 return s2 == null; 2468 } 2469 if (s2 == null) { 2470 return false; 2471 } 2472 if (s1.getClass() != s2.getClass()) { 2473 return false; 2474 } 2475 return s1.equals(s2); 2476 } 2477 2478 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2479 if (pi1.icon != pi2.icon) return false; 2480 if (pi1.logo != pi2.logo) return false; 2481 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2482 if (!compareStrings(pi1.name, pi2.name)) return false; 2483 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2484 // We'll take care of setting this one. 2485 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2486 // These are not currently stored in settings. 2487 //if (!compareStrings(pi1.group, pi2.group)) return false; 2488 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2489 //if (pi1.labelRes != pi2.labelRes) return false; 2490 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2491 return true; 2492 } 2493 2494 int permissionInfoFootprint(PermissionInfo info) { 2495 int size = info.name.length(); 2496 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2497 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2498 return size; 2499 } 2500 2501 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2502 int size = 0; 2503 for (BasePermission perm : mSettings.mPermissions.values()) { 2504 if (perm.uid == tree.uid) { 2505 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2506 } 2507 } 2508 return size; 2509 } 2510 2511 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2512 // We calculate the max size of permissions defined by this uid and throw 2513 // if that plus the size of 'info' would exceed our stated maximum. 2514 if (tree.uid != Process.SYSTEM_UID) { 2515 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2516 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2517 throw new SecurityException("Permission tree size cap exceeded"); 2518 } 2519 } 2520 } 2521 2522 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2523 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2524 throw new SecurityException("Label must be specified in permission"); 2525 } 2526 BasePermission tree = checkPermissionTreeLP(info.name); 2527 BasePermission bp = mSettings.mPermissions.get(info.name); 2528 boolean added = bp == null; 2529 boolean changed = true; 2530 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2531 if (added) { 2532 enforcePermissionCapLocked(info, tree); 2533 bp = new BasePermission(info.name, tree.sourcePackage, 2534 BasePermission.TYPE_DYNAMIC); 2535 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2536 throw new SecurityException( 2537 "Not allowed to modify non-dynamic permission " 2538 + info.name); 2539 } else { 2540 if (bp.protectionLevel == fixedLevel 2541 && bp.perm.owner.equals(tree.perm.owner) 2542 && bp.uid == tree.uid 2543 && comparePermissionInfos(bp.perm.info, info)) { 2544 changed = false; 2545 } 2546 } 2547 bp.protectionLevel = fixedLevel; 2548 info = new PermissionInfo(info); 2549 info.protectionLevel = fixedLevel; 2550 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2551 bp.perm.info.packageName = tree.perm.info.packageName; 2552 bp.uid = tree.uid; 2553 if (added) { 2554 mSettings.mPermissions.put(info.name, bp); 2555 } 2556 if (changed) { 2557 if (!async) { 2558 mSettings.writeLPr(); 2559 } else { 2560 scheduleWriteSettingsLocked(); 2561 } 2562 } 2563 return added; 2564 } 2565 2566 @Override 2567 public boolean addPermission(PermissionInfo info) { 2568 synchronized (mPackages) { 2569 return addPermissionLocked(info, false); 2570 } 2571 } 2572 2573 @Override 2574 public boolean addPermissionAsync(PermissionInfo info) { 2575 synchronized (mPackages) { 2576 return addPermissionLocked(info, true); 2577 } 2578 } 2579 2580 @Override 2581 public void removePermission(String name) { 2582 synchronized (mPackages) { 2583 checkPermissionTreeLP(name); 2584 BasePermission bp = mSettings.mPermissions.get(name); 2585 if (bp != null) { 2586 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2587 throw new SecurityException( 2588 "Not allowed to modify non-dynamic permission " 2589 + name); 2590 } 2591 mSettings.mPermissions.remove(name); 2592 mSettings.writeLPr(); 2593 } 2594 } 2595 } 2596 2597 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2598 int index = pkg.requestedPermissions.indexOf(bp.name); 2599 if (index == -1) { 2600 throw new SecurityException("Package " + pkg.packageName 2601 + " has not requested permission " + bp.name); 2602 } 2603 boolean isNormal = 2604 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2605 == PermissionInfo.PROTECTION_NORMAL); 2606 boolean isDangerous = 2607 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2608 == PermissionInfo.PROTECTION_DANGEROUS); 2609 boolean isDevelopment = 2610 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2611 2612 if (!isNormal && !isDangerous && !isDevelopment) { 2613 throw new SecurityException("Permission " + bp.name 2614 + " is not a changeable permission type"); 2615 } 2616 2617 if (isNormal || isDangerous) { 2618 if (pkg.requestedPermissionsRequired.get(index)) { 2619 throw new SecurityException("Can't change " + bp.name 2620 + ". It is required by the application"); 2621 } 2622 } 2623 } 2624 2625 @Override 2626 public void grantPermission(String packageName, String permissionName) { 2627 mContext.enforceCallingOrSelfPermission( 2628 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2629 synchronized (mPackages) { 2630 final PackageParser.Package pkg = mPackages.get(packageName); 2631 if (pkg == null) { 2632 throw new IllegalArgumentException("Unknown package: " + packageName); 2633 } 2634 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2635 if (bp == null) { 2636 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2637 } 2638 2639 checkGrantRevokePermissions(pkg, bp); 2640 2641 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2642 if (ps == null) { 2643 return; 2644 } 2645 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2646 if (gp.grantedPermissions.add(permissionName)) { 2647 if (ps.haveGids) { 2648 gp.gids = appendInts(gp.gids, bp.gids); 2649 } 2650 mSettings.writeLPr(); 2651 } 2652 } 2653 } 2654 2655 @Override 2656 public void revokePermission(String packageName, String permissionName) { 2657 int changedAppId = -1; 2658 2659 synchronized (mPackages) { 2660 final PackageParser.Package pkg = mPackages.get(packageName); 2661 if (pkg == null) { 2662 throw new IllegalArgumentException("Unknown package: " + packageName); 2663 } 2664 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2665 mContext.enforceCallingOrSelfPermission( 2666 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2667 } 2668 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2669 if (bp == null) { 2670 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2671 } 2672 2673 checkGrantRevokePermissions(pkg, bp); 2674 2675 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2676 if (ps == null) { 2677 return; 2678 } 2679 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2680 if (gp.grantedPermissions.remove(permissionName)) { 2681 gp.grantedPermissions.remove(permissionName); 2682 if (ps.haveGids) { 2683 gp.gids = removeInts(gp.gids, bp.gids); 2684 } 2685 mSettings.writeLPr(); 2686 changedAppId = ps.appId; 2687 } 2688 } 2689 2690 if (changedAppId >= 0) { 2691 // We changed the perm on someone, kill its processes. 2692 IActivityManager am = ActivityManagerNative.getDefault(); 2693 if (am != null) { 2694 final int callingUserId = UserHandle.getCallingUserId(); 2695 final long ident = Binder.clearCallingIdentity(); 2696 try { 2697 //XXX we should only revoke for the calling user's app permissions, 2698 // but for now we impact all users. 2699 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2700 // "revoke " + permissionName); 2701 int[] users = sUserManager.getUserIds(); 2702 for (int user : users) { 2703 am.killUid(UserHandle.getUid(user, changedAppId), 2704 "revoke " + permissionName); 2705 } 2706 } catch (RemoteException e) { 2707 } finally { 2708 Binder.restoreCallingIdentity(ident); 2709 } 2710 } 2711 } 2712 } 2713 2714 @Override 2715 public boolean isProtectedBroadcast(String actionName) { 2716 synchronized (mPackages) { 2717 return mProtectedBroadcasts.contains(actionName); 2718 } 2719 } 2720 2721 @Override 2722 public int checkSignatures(String pkg1, String pkg2) { 2723 synchronized (mPackages) { 2724 final PackageParser.Package p1 = mPackages.get(pkg1); 2725 final PackageParser.Package p2 = mPackages.get(pkg2); 2726 if (p1 == null || p1.mExtras == null 2727 || p2 == null || p2.mExtras == null) { 2728 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2729 } 2730 return compareSignatures(p1.mSignatures, p2.mSignatures); 2731 } 2732 } 2733 2734 @Override 2735 public int checkUidSignatures(int uid1, int uid2) { 2736 // Map to base uids. 2737 uid1 = UserHandle.getAppId(uid1); 2738 uid2 = UserHandle.getAppId(uid2); 2739 // reader 2740 synchronized (mPackages) { 2741 Signature[] s1; 2742 Signature[] s2; 2743 Object obj = mSettings.getUserIdLPr(uid1); 2744 if (obj != null) { 2745 if (obj instanceof SharedUserSetting) { 2746 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2747 } else if (obj instanceof PackageSetting) { 2748 s1 = ((PackageSetting)obj).signatures.mSignatures; 2749 } else { 2750 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2751 } 2752 } else { 2753 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2754 } 2755 obj = mSettings.getUserIdLPr(uid2); 2756 if (obj != null) { 2757 if (obj instanceof SharedUserSetting) { 2758 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2759 } else if (obj instanceof PackageSetting) { 2760 s2 = ((PackageSetting)obj).signatures.mSignatures; 2761 } else { 2762 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2763 } 2764 } else { 2765 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2766 } 2767 return compareSignatures(s1, s2); 2768 } 2769 } 2770 2771 /** 2772 * Compares two sets of signatures. Returns: 2773 * <br /> 2774 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2775 * <br /> 2776 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2777 * <br /> 2778 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2779 * <br /> 2780 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2781 * <br /> 2782 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2783 */ 2784 static int compareSignatures(Signature[] s1, Signature[] s2) { 2785 if (s1 == null) { 2786 return s2 == null 2787 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2788 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2789 } 2790 2791 if (s2 == null) { 2792 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2793 } 2794 2795 if (s1.length != s2.length) { 2796 return PackageManager.SIGNATURE_NO_MATCH; 2797 } 2798 2799 // Since both signature sets are of size 1, we can compare without HashSets. 2800 if (s1.length == 1) { 2801 return s1[0].equals(s2[0]) ? 2802 PackageManager.SIGNATURE_MATCH : 2803 PackageManager.SIGNATURE_NO_MATCH; 2804 } 2805 2806 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2807 for (Signature sig : s1) { 2808 set1.add(sig); 2809 } 2810 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2811 for (Signature sig : s2) { 2812 set2.add(sig); 2813 } 2814 // Make sure s2 contains all signatures in s1. 2815 if (set1.equals(set2)) { 2816 return PackageManager.SIGNATURE_MATCH; 2817 } 2818 return PackageManager.SIGNATURE_NO_MATCH; 2819 } 2820 2821 /** 2822 * If the database version for this type of package (internal storage or 2823 * external storage) is less than the version where package signatures 2824 * were updated, return true. 2825 */ 2826 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2827 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2828 DatabaseVersion.SIGNATURE_END_ENTITY)) 2829 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2830 DatabaseVersion.SIGNATURE_END_ENTITY)); 2831 } 2832 2833 /** 2834 * Used for backward compatibility to make sure any packages with 2835 * certificate chains get upgraded to the new style. {@code existingSigs} 2836 * will be in the old format (since they were stored on disk from before the 2837 * system upgrade) and {@code scannedSigs} will be in the newer format. 2838 */ 2839 private int compareSignaturesCompat(PackageSignatures existingSigs, 2840 PackageParser.Package scannedPkg) { 2841 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2842 return PackageManager.SIGNATURE_NO_MATCH; 2843 } 2844 2845 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2846 for (Signature sig : existingSigs.mSignatures) { 2847 existingSet.add(sig); 2848 } 2849 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2850 for (Signature sig : scannedPkg.mSignatures) { 2851 try { 2852 Signature[] chainSignatures = sig.getChainSignatures(); 2853 for (Signature chainSig : chainSignatures) { 2854 scannedCompatSet.add(chainSig); 2855 } 2856 } catch (CertificateEncodingException e) { 2857 scannedCompatSet.add(sig); 2858 } 2859 } 2860 /* 2861 * Make sure the expanded scanned set contains all signatures in the 2862 * existing one. 2863 */ 2864 if (scannedCompatSet.equals(existingSet)) { 2865 // Migrate the old signatures to the new scheme. 2866 existingSigs.assignSignatures(scannedPkg.mSignatures); 2867 // The new KeySets will be re-added later in the scanning process. 2868 synchronized (mPackages) { 2869 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2870 } 2871 return PackageManager.SIGNATURE_MATCH; 2872 } 2873 return PackageManager.SIGNATURE_NO_MATCH; 2874 } 2875 2876 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2877 if (isExternal(scannedPkg)) { 2878 return mSettings.isExternalDatabaseVersionOlderThan( 2879 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2880 } else { 2881 return mSettings.isInternalDatabaseVersionOlderThan( 2882 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2883 } 2884 } 2885 2886 private int compareSignaturesRecover(PackageSignatures existingSigs, 2887 PackageParser.Package scannedPkg) { 2888 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2889 return PackageManager.SIGNATURE_NO_MATCH; 2890 } 2891 2892 String msg = null; 2893 try { 2894 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2895 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2896 + scannedPkg.packageName); 2897 return PackageManager.SIGNATURE_MATCH; 2898 } 2899 } catch (CertificateException e) { 2900 msg = e.getMessage(); 2901 } 2902 2903 logCriticalInfo(Log.INFO, 2904 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2905 return PackageManager.SIGNATURE_NO_MATCH; 2906 } 2907 2908 @Override 2909 public String[] getPackagesForUid(int uid) { 2910 uid = UserHandle.getAppId(uid); 2911 // reader 2912 synchronized (mPackages) { 2913 Object obj = mSettings.getUserIdLPr(uid); 2914 if (obj instanceof SharedUserSetting) { 2915 final SharedUserSetting sus = (SharedUserSetting) obj; 2916 final int N = sus.packages.size(); 2917 final String[] res = new String[N]; 2918 final Iterator<PackageSetting> it = sus.packages.iterator(); 2919 int i = 0; 2920 while (it.hasNext()) { 2921 res[i++] = it.next().name; 2922 } 2923 return res; 2924 } else if (obj instanceof PackageSetting) { 2925 final PackageSetting ps = (PackageSetting) obj; 2926 return new String[] { ps.name }; 2927 } 2928 } 2929 return null; 2930 } 2931 2932 @Override 2933 public String getNameForUid(int uid) { 2934 // reader 2935 synchronized (mPackages) { 2936 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2937 if (obj instanceof SharedUserSetting) { 2938 final SharedUserSetting sus = (SharedUserSetting) obj; 2939 return sus.name + ":" + sus.userId; 2940 } else if (obj instanceof PackageSetting) { 2941 final PackageSetting ps = (PackageSetting) obj; 2942 return ps.name; 2943 } 2944 } 2945 return null; 2946 } 2947 2948 @Override 2949 public int getUidForSharedUser(String sharedUserName) { 2950 if(sharedUserName == null) { 2951 return -1; 2952 } 2953 // reader 2954 synchronized (mPackages) { 2955 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2956 if (suid == null) { 2957 return -1; 2958 } 2959 return suid.userId; 2960 } 2961 } 2962 2963 @Override 2964 public int getFlagsForUid(int uid) { 2965 synchronized (mPackages) { 2966 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2967 if (obj instanceof SharedUserSetting) { 2968 final SharedUserSetting sus = (SharedUserSetting) obj; 2969 return sus.pkgFlags; 2970 } else if (obj instanceof PackageSetting) { 2971 final PackageSetting ps = (PackageSetting) obj; 2972 return ps.pkgFlags; 2973 } 2974 } 2975 return 0; 2976 } 2977 2978 @Override 2979 public boolean isUidPrivileged(int uid) { 2980 uid = UserHandle.getAppId(uid); 2981 // reader 2982 synchronized (mPackages) { 2983 Object obj = mSettings.getUserIdLPr(uid); 2984 if (obj instanceof SharedUserSetting) { 2985 final SharedUserSetting sus = (SharedUserSetting) obj; 2986 final Iterator<PackageSetting> it = sus.packages.iterator(); 2987 while (it.hasNext()) { 2988 if (it.next().isPrivileged()) { 2989 return true; 2990 } 2991 } 2992 } else if (obj instanceof PackageSetting) { 2993 final PackageSetting ps = (PackageSetting) obj; 2994 return ps.isPrivileged(); 2995 } 2996 } 2997 return false; 2998 } 2999 3000 @Override 3001 public String[] getAppOpPermissionPackages(String permissionName) { 3002 synchronized (mPackages) { 3003 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3004 if (pkgs == null) { 3005 return null; 3006 } 3007 return pkgs.toArray(new String[pkgs.size()]); 3008 } 3009 } 3010 3011 @Override 3012 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3013 int flags, int userId) { 3014 if (!sUserManager.exists(userId)) return null; 3015 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3016 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3017 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3018 } 3019 3020 @Override 3021 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3022 IntentFilter filter, int match, ComponentName activity) { 3023 final int userId = UserHandle.getCallingUserId(); 3024 if (DEBUG_PREFERRED) { 3025 Log.v(TAG, "setLastChosenActivity intent=" + intent 3026 + " resolvedType=" + resolvedType 3027 + " flags=" + flags 3028 + " filter=" + filter 3029 + " match=" + match 3030 + " activity=" + activity); 3031 filter.dump(new PrintStreamPrinter(System.out), " "); 3032 } 3033 intent.setComponent(null); 3034 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3035 // Find any earlier preferred or last chosen entries and nuke them 3036 findPreferredActivity(intent, resolvedType, 3037 flags, query, 0, false, true, false, userId); 3038 // Add the new activity as the last chosen for this filter 3039 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3040 "Setting last chosen"); 3041 } 3042 3043 @Override 3044 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3045 final int userId = UserHandle.getCallingUserId(); 3046 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3047 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3048 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3049 false, false, false, userId); 3050 } 3051 3052 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3053 int flags, List<ResolveInfo> query, int userId) { 3054 if (query != null) { 3055 final int N = query.size(); 3056 if (N == 1) { 3057 return query.get(0); 3058 } else if (N > 1) { 3059 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3060 // If there is more than one activity with the same priority, 3061 // then let the user decide between them. 3062 ResolveInfo r0 = query.get(0); 3063 ResolveInfo r1 = query.get(1); 3064 if (DEBUG_INTENT_MATCHING || debug) { 3065 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3066 + r1.activityInfo.name + "=" + r1.priority); 3067 } 3068 // If the first activity has a higher priority, or a different 3069 // default, then it is always desireable to pick it. 3070 if (r0.priority != r1.priority 3071 || r0.preferredOrder != r1.preferredOrder 3072 || r0.isDefault != r1.isDefault) { 3073 return query.get(0); 3074 } 3075 // If we have saved a preference for a preferred activity for 3076 // this Intent, use that. 3077 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3078 flags, query, r0.priority, true, false, debug, userId); 3079 if (ri != null) { 3080 return ri; 3081 } 3082 if (userId != 0) { 3083 ri = new ResolveInfo(mResolveInfo); 3084 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3085 ri.activityInfo.applicationInfo = new ApplicationInfo( 3086 ri.activityInfo.applicationInfo); 3087 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3088 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3089 return ri; 3090 } 3091 return mResolveInfo; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3098 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3099 final int N = query.size(); 3100 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3101 .get(userId); 3102 // Get the list of persistent preferred activities that handle the intent 3103 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3104 List<PersistentPreferredActivity> pprefs = ppir != null 3105 ? ppir.queryIntent(intent, resolvedType, 3106 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3107 : null; 3108 if (pprefs != null && pprefs.size() > 0) { 3109 final int M = pprefs.size(); 3110 for (int i=0; i<M; i++) { 3111 final PersistentPreferredActivity ppa = pprefs.get(i); 3112 if (DEBUG_PREFERRED || debug) { 3113 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3114 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3115 + "\n component=" + ppa.mComponent); 3116 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3117 } 3118 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3119 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3120 if (DEBUG_PREFERRED || debug) { 3121 Slog.v(TAG, "Found persistent preferred activity:"); 3122 if (ai != null) { 3123 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3124 } else { 3125 Slog.v(TAG, " null"); 3126 } 3127 } 3128 if (ai == null) { 3129 // This previously registered persistent preferred activity 3130 // component is no longer known. Ignore it and do NOT remove it. 3131 continue; 3132 } 3133 for (int j=0; j<N; j++) { 3134 final ResolveInfo ri = query.get(j); 3135 if (!ri.activityInfo.applicationInfo.packageName 3136 .equals(ai.applicationInfo.packageName)) { 3137 continue; 3138 } 3139 if (!ri.activityInfo.name.equals(ai.name)) { 3140 continue; 3141 } 3142 // Found a persistent preference that can handle the intent. 3143 if (DEBUG_PREFERRED || debug) { 3144 Slog.v(TAG, "Returning persistent preferred activity: " + 3145 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3146 } 3147 return ri; 3148 } 3149 } 3150 } 3151 return null; 3152 } 3153 3154 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3155 List<ResolveInfo> query, int priority, boolean always, 3156 boolean removeMatches, boolean debug, int userId) { 3157 if (!sUserManager.exists(userId)) return null; 3158 // writer 3159 synchronized (mPackages) { 3160 if (intent.getSelector() != null) { 3161 intent = intent.getSelector(); 3162 } 3163 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3164 3165 // Try to find a matching persistent preferred activity. 3166 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3167 debug, userId); 3168 3169 // If a persistent preferred activity matched, use it. 3170 if (pri != null) { 3171 return pri; 3172 } 3173 3174 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3175 // Get the list of preferred activities that handle the intent 3176 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3177 List<PreferredActivity> prefs = pir != null 3178 ? pir.queryIntent(intent, resolvedType, 3179 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3180 : null; 3181 if (prefs != null && prefs.size() > 0) { 3182 boolean changed = false; 3183 try { 3184 // First figure out how good the original match set is. 3185 // We will only allow preferred activities that came 3186 // from the same match quality. 3187 int match = 0; 3188 3189 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3190 3191 final int N = query.size(); 3192 for (int j=0; j<N; j++) { 3193 final ResolveInfo ri = query.get(j); 3194 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3195 + ": 0x" + Integer.toHexString(match)); 3196 if (ri.match > match) { 3197 match = ri.match; 3198 } 3199 } 3200 3201 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3202 + Integer.toHexString(match)); 3203 3204 match &= IntentFilter.MATCH_CATEGORY_MASK; 3205 final int M = prefs.size(); 3206 for (int i=0; i<M; i++) { 3207 final PreferredActivity pa = prefs.get(i); 3208 if (DEBUG_PREFERRED || debug) { 3209 Slog.v(TAG, "Checking PreferredActivity ds=" 3210 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3211 + "\n component=" + pa.mPref.mComponent); 3212 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3213 } 3214 if (pa.mPref.mMatch != match) { 3215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3216 + Integer.toHexString(pa.mPref.mMatch)); 3217 continue; 3218 } 3219 // If it's not an "always" type preferred activity and that's what we're 3220 // looking for, skip it. 3221 if (always && !pa.mPref.mAlways) { 3222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3223 continue; 3224 } 3225 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3226 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3227 if (DEBUG_PREFERRED || debug) { 3228 Slog.v(TAG, "Found preferred activity:"); 3229 if (ai != null) { 3230 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3231 } else { 3232 Slog.v(TAG, " null"); 3233 } 3234 } 3235 if (ai == null) { 3236 // This previously registered preferred activity 3237 // component is no longer known. Most likely an update 3238 // to the app was installed and in the new version this 3239 // component no longer exists. Clean it up by removing 3240 // it from the preferred activities list, and skip it. 3241 Slog.w(TAG, "Removing dangling preferred activity: " 3242 + pa.mPref.mComponent); 3243 pir.removeFilter(pa); 3244 changed = true; 3245 continue; 3246 } 3247 for (int j=0; j<N; j++) { 3248 final ResolveInfo ri = query.get(j); 3249 if (!ri.activityInfo.applicationInfo.packageName 3250 .equals(ai.applicationInfo.packageName)) { 3251 continue; 3252 } 3253 if (!ri.activityInfo.name.equals(ai.name)) { 3254 continue; 3255 } 3256 3257 if (removeMatches) { 3258 pir.removeFilter(pa); 3259 changed = true; 3260 if (DEBUG_PREFERRED) { 3261 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3262 } 3263 break; 3264 } 3265 3266 // Okay we found a previously set preferred or last chosen app. 3267 // If the result set is different from when this 3268 // was created, we need to clear it and re-ask the 3269 // user their preference, if we're looking for an "always" type entry. 3270 if (always && !pa.mPref.sameSet(query, priority)) { 3271 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3272 + intent + " type " + resolvedType); 3273 if (DEBUG_PREFERRED) { 3274 Slog.v(TAG, "Removing preferred activity since set changed " 3275 + pa.mPref.mComponent); 3276 } 3277 pir.removeFilter(pa); 3278 // Re-add the filter as a "last chosen" entry (!always) 3279 PreferredActivity lastChosen = new PreferredActivity( 3280 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3281 pir.addFilter(lastChosen); 3282 changed = true; 3283 return null; 3284 } 3285 3286 // Yay! Either the set matched or we're looking for the last chosen 3287 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3288 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3289 return ri; 3290 } 3291 } 3292 } finally { 3293 if (changed) { 3294 if (DEBUG_PREFERRED) { 3295 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3296 } 3297 scheduleWritePackageRestrictionsLocked(userId); 3298 } 3299 } 3300 } 3301 } 3302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3303 return null; 3304 } 3305 3306 /* 3307 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3308 */ 3309 @Override 3310 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3311 int targetUserId) { 3312 mContext.enforceCallingOrSelfPermission( 3313 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3314 List<CrossProfileIntentFilter> matches = 3315 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3316 if (matches != null) { 3317 int size = matches.size(); 3318 for (int i = 0; i < size; i++) { 3319 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3320 } 3321 } 3322 return false; 3323 } 3324 3325 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3326 String resolvedType, int userId) { 3327 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3328 if (resolver != null) { 3329 return resolver.queryIntent(intent, resolvedType, false, userId); 3330 } 3331 return null; 3332 } 3333 3334 @Override 3335 public List<ResolveInfo> queryIntentActivities(Intent intent, 3336 String resolvedType, int flags, int userId) { 3337 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3338 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3339 ComponentName comp = intent.getComponent(); 3340 if (comp == null) { 3341 if (intent.getSelector() != null) { 3342 intent = intent.getSelector(); 3343 comp = intent.getComponent(); 3344 } 3345 } 3346 3347 if (comp != null) { 3348 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3349 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3350 if (ai != null) { 3351 final ResolveInfo ri = new ResolveInfo(); 3352 ri.activityInfo = ai; 3353 list.add(ri); 3354 } 3355 return list; 3356 } 3357 3358 // reader 3359 synchronized (mPackages) { 3360 final String pkgName = intent.getPackage(); 3361 if (pkgName == null) { 3362 List<CrossProfileIntentFilter> matchingFilters = 3363 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3364 // Check for results that need to skip the current profile. 3365 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3366 resolvedType, flags, userId); 3367 if (resolveInfo != null) { 3368 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3369 result.add(resolveInfo); 3370 return result; 3371 } 3372 // Check for cross profile results. 3373 resolveInfo = queryCrossProfileIntents( 3374 matchingFilters, intent, resolvedType, flags, userId); 3375 3376 // Check for results in the current profile. 3377 List<ResolveInfo> result = mActivities.queryIntent( 3378 intent, resolvedType, flags, userId); 3379 if (resolveInfo != null) { 3380 result.add(resolveInfo); 3381 Collections.sort(result, mResolvePrioritySorter); 3382 } 3383 return result; 3384 } 3385 final PackageParser.Package pkg = mPackages.get(pkgName); 3386 if (pkg != null) { 3387 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3388 pkg.activities, userId); 3389 } 3390 return new ArrayList<ResolveInfo>(); 3391 } 3392 } 3393 3394 private ResolveInfo querySkipCurrentProfileIntents( 3395 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3396 int flags, int sourceUserId) { 3397 if (matchingFilters != null) { 3398 int size = matchingFilters.size(); 3399 for (int i = 0; i < size; i ++) { 3400 CrossProfileIntentFilter filter = matchingFilters.get(i); 3401 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3402 // Checking if there are activities in the target user that can handle the 3403 // intent. 3404 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3405 flags, sourceUserId); 3406 if (resolveInfo != null) { 3407 return resolveInfo; 3408 } 3409 } 3410 } 3411 } 3412 return null; 3413 } 3414 3415 // Return matching ResolveInfo if any for skip current profile intent filters. 3416 private ResolveInfo queryCrossProfileIntents( 3417 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3418 int flags, int sourceUserId) { 3419 if (matchingFilters != null) { 3420 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3421 // match the same intent. For performance reasons, it is better not to 3422 // run queryIntent twice for the same userId 3423 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3424 int size = matchingFilters.size(); 3425 for (int i = 0; i < size; i++) { 3426 CrossProfileIntentFilter filter = matchingFilters.get(i); 3427 int targetUserId = filter.getTargetUserId(); 3428 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3429 && !alreadyTriedUserIds.get(targetUserId)) { 3430 // Checking if there are activities in the target user that can handle the 3431 // intent. 3432 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3433 flags, sourceUserId); 3434 if (resolveInfo != null) return resolveInfo; 3435 alreadyTriedUserIds.put(targetUserId, true); 3436 } 3437 } 3438 } 3439 return null; 3440 } 3441 3442 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3443 String resolvedType, int flags, int sourceUserId) { 3444 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3445 resolvedType, flags, filter.getTargetUserId()); 3446 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3447 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3448 } 3449 return null; 3450 } 3451 3452 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3453 int sourceUserId, int targetUserId) { 3454 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3455 String className; 3456 if (targetUserId == UserHandle.USER_OWNER) { 3457 className = FORWARD_INTENT_TO_USER_OWNER; 3458 } else { 3459 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3460 } 3461 ComponentName forwardingActivityComponentName = new ComponentName( 3462 mAndroidApplication.packageName, className); 3463 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3464 sourceUserId); 3465 if (targetUserId == UserHandle.USER_OWNER) { 3466 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3467 forwardingResolveInfo.noResourceId = true; 3468 } 3469 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3470 forwardingResolveInfo.priority = 0; 3471 forwardingResolveInfo.preferredOrder = 0; 3472 forwardingResolveInfo.match = 0; 3473 forwardingResolveInfo.isDefault = true; 3474 forwardingResolveInfo.filter = filter; 3475 forwardingResolveInfo.targetUserId = targetUserId; 3476 return forwardingResolveInfo; 3477 } 3478 3479 @Override 3480 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3481 Intent[] specifics, String[] specificTypes, Intent intent, 3482 String resolvedType, int flags, int userId) { 3483 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3485 false, "query intent activity options"); 3486 final String resultsAction = intent.getAction(); 3487 3488 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3489 | PackageManager.GET_RESOLVED_FILTER, userId); 3490 3491 if (DEBUG_INTENT_MATCHING) { 3492 Log.v(TAG, "Query " + intent + ": " + results); 3493 } 3494 3495 int specificsPos = 0; 3496 int N; 3497 3498 // todo: note that the algorithm used here is O(N^2). This 3499 // isn't a problem in our current environment, but if we start running 3500 // into situations where we have more than 5 or 10 matches then this 3501 // should probably be changed to something smarter... 3502 3503 // First we go through and resolve each of the specific items 3504 // that were supplied, taking care of removing any corresponding 3505 // duplicate items in the generic resolve list. 3506 if (specifics != null) { 3507 for (int i=0; i<specifics.length; i++) { 3508 final Intent sintent = specifics[i]; 3509 if (sintent == null) { 3510 continue; 3511 } 3512 3513 if (DEBUG_INTENT_MATCHING) { 3514 Log.v(TAG, "Specific #" + i + ": " + sintent); 3515 } 3516 3517 String action = sintent.getAction(); 3518 if (resultsAction != null && resultsAction.equals(action)) { 3519 // If this action was explicitly requested, then don't 3520 // remove things that have it. 3521 action = null; 3522 } 3523 3524 ResolveInfo ri = null; 3525 ActivityInfo ai = null; 3526 3527 ComponentName comp = sintent.getComponent(); 3528 if (comp == null) { 3529 ri = resolveIntent( 3530 sintent, 3531 specificTypes != null ? specificTypes[i] : null, 3532 flags, userId); 3533 if (ri == null) { 3534 continue; 3535 } 3536 if (ri == mResolveInfo) { 3537 // ACK! Must do something better with this. 3538 } 3539 ai = ri.activityInfo; 3540 comp = new ComponentName(ai.applicationInfo.packageName, 3541 ai.name); 3542 } else { 3543 ai = getActivityInfo(comp, flags, userId); 3544 if (ai == null) { 3545 continue; 3546 } 3547 } 3548 3549 // Look for any generic query activities that are duplicates 3550 // of this specific one, and remove them from the results. 3551 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3552 N = results.size(); 3553 int j; 3554 for (j=specificsPos; j<N; j++) { 3555 ResolveInfo sri = results.get(j); 3556 if ((sri.activityInfo.name.equals(comp.getClassName()) 3557 && sri.activityInfo.applicationInfo.packageName.equals( 3558 comp.getPackageName())) 3559 || (action != null && sri.filter.matchAction(action))) { 3560 results.remove(j); 3561 if (DEBUG_INTENT_MATCHING) Log.v( 3562 TAG, "Removing duplicate item from " + j 3563 + " due to specific " + specificsPos); 3564 if (ri == null) { 3565 ri = sri; 3566 } 3567 j--; 3568 N--; 3569 } 3570 } 3571 3572 // Add this specific item to its proper place. 3573 if (ri == null) { 3574 ri = new ResolveInfo(); 3575 ri.activityInfo = ai; 3576 } 3577 results.add(specificsPos, ri); 3578 ri.specificIndex = i; 3579 specificsPos++; 3580 } 3581 } 3582 3583 // Now we go through the remaining generic results and remove any 3584 // duplicate actions that are found here. 3585 N = results.size(); 3586 for (int i=specificsPos; i<N-1; i++) { 3587 final ResolveInfo rii = results.get(i); 3588 if (rii.filter == null) { 3589 continue; 3590 } 3591 3592 // Iterate over all of the actions of this result's intent 3593 // filter... typically this should be just one. 3594 final Iterator<String> it = rii.filter.actionsIterator(); 3595 if (it == null) { 3596 continue; 3597 } 3598 while (it.hasNext()) { 3599 final String action = it.next(); 3600 if (resultsAction != null && resultsAction.equals(action)) { 3601 // If this action was explicitly requested, then don't 3602 // remove things that have it. 3603 continue; 3604 } 3605 for (int j=i+1; j<N; j++) { 3606 final ResolveInfo rij = results.get(j); 3607 if (rij.filter != null && rij.filter.hasAction(action)) { 3608 results.remove(j); 3609 if (DEBUG_INTENT_MATCHING) Log.v( 3610 TAG, "Removing duplicate item from " + j 3611 + " due to action " + action + " at " + i); 3612 j--; 3613 N--; 3614 } 3615 } 3616 } 3617 3618 // If the caller didn't request filter information, drop it now 3619 // so we don't have to marshall/unmarshall it. 3620 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3621 rii.filter = null; 3622 } 3623 } 3624 3625 // Filter out the caller activity if so requested. 3626 if (caller != null) { 3627 N = results.size(); 3628 for (int i=0; i<N; i++) { 3629 ActivityInfo ainfo = results.get(i).activityInfo; 3630 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3631 && caller.getClassName().equals(ainfo.name)) { 3632 results.remove(i); 3633 break; 3634 } 3635 } 3636 } 3637 3638 // If the caller didn't request filter information, 3639 // drop them now so we don't have to 3640 // marshall/unmarshall it. 3641 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3642 N = results.size(); 3643 for (int i=0; i<N; i++) { 3644 results.get(i).filter = null; 3645 } 3646 } 3647 3648 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3649 return results; 3650 } 3651 3652 @Override 3653 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3654 int userId) { 3655 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3656 ComponentName comp = intent.getComponent(); 3657 if (comp == null) { 3658 if (intent.getSelector() != null) { 3659 intent = intent.getSelector(); 3660 comp = intent.getComponent(); 3661 } 3662 } 3663 if (comp != null) { 3664 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3665 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3666 if (ai != null) { 3667 ResolveInfo ri = new ResolveInfo(); 3668 ri.activityInfo = ai; 3669 list.add(ri); 3670 } 3671 return list; 3672 } 3673 3674 // reader 3675 synchronized (mPackages) { 3676 String pkgName = intent.getPackage(); 3677 if (pkgName == null) { 3678 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3679 } 3680 final PackageParser.Package pkg = mPackages.get(pkgName); 3681 if (pkg != null) { 3682 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3683 userId); 3684 } 3685 return null; 3686 } 3687 } 3688 3689 @Override 3690 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3691 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3692 if (!sUserManager.exists(userId)) return null; 3693 if (query != null) { 3694 if (query.size() >= 1) { 3695 // If there is more than one service with the same priority, 3696 // just arbitrarily pick the first one. 3697 return query.get(0); 3698 } 3699 } 3700 return null; 3701 } 3702 3703 @Override 3704 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3705 int userId) { 3706 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3707 ComponentName comp = intent.getComponent(); 3708 if (comp == null) { 3709 if (intent.getSelector() != null) { 3710 intent = intent.getSelector(); 3711 comp = intent.getComponent(); 3712 } 3713 } 3714 if (comp != null) { 3715 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3716 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3717 if (si != null) { 3718 final ResolveInfo ri = new ResolveInfo(); 3719 ri.serviceInfo = si; 3720 list.add(ri); 3721 } 3722 return list; 3723 } 3724 3725 // reader 3726 synchronized (mPackages) { 3727 String pkgName = intent.getPackage(); 3728 if (pkgName == null) { 3729 return mServices.queryIntent(intent, resolvedType, flags, userId); 3730 } 3731 final PackageParser.Package pkg = mPackages.get(pkgName); 3732 if (pkg != null) { 3733 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3734 userId); 3735 } 3736 return null; 3737 } 3738 } 3739 3740 @Override 3741 public List<ResolveInfo> queryIntentContentProviders( 3742 Intent intent, String resolvedType, int flags, int userId) { 3743 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3744 ComponentName comp = intent.getComponent(); 3745 if (comp == null) { 3746 if (intent.getSelector() != null) { 3747 intent = intent.getSelector(); 3748 comp = intent.getComponent(); 3749 } 3750 } 3751 if (comp != null) { 3752 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3753 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3754 if (pi != null) { 3755 final ResolveInfo ri = new ResolveInfo(); 3756 ri.providerInfo = pi; 3757 list.add(ri); 3758 } 3759 return list; 3760 } 3761 3762 // reader 3763 synchronized (mPackages) { 3764 String pkgName = intent.getPackage(); 3765 if (pkgName == null) { 3766 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3767 } 3768 final PackageParser.Package pkg = mPackages.get(pkgName); 3769 if (pkg != null) { 3770 return mProviders.queryIntentForPackage( 3771 intent, resolvedType, flags, pkg.providers, userId); 3772 } 3773 return null; 3774 } 3775 } 3776 3777 @Override 3778 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3779 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3780 3781 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3782 3783 // writer 3784 synchronized (mPackages) { 3785 ArrayList<PackageInfo> list; 3786 if (listUninstalled) { 3787 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3788 for (PackageSetting ps : mSettings.mPackages.values()) { 3789 PackageInfo pi; 3790 if (ps.pkg != null) { 3791 pi = generatePackageInfo(ps.pkg, flags, userId); 3792 } else { 3793 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3794 } 3795 if (pi != null) { 3796 list.add(pi); 3797 } 3798 } 3799 } else { 3800 list = new ArrayList<PackageInfo>(mPackages.size()); 3801 for (PackageParser.Package p : mPackages.values()) { 3802 PackageInfo pi = generatePackageInfo(p, flags, userId); 3803 if (pi != null) { 3804 list.add(pi); 3805 } 3806 } 3807 } 3808 3809 return new ParceledListSlice<PackageInfo>(list); 3810 } 3811 } 3812 3813 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3814 String[] permissions, boolean[] tmp, int flags, int userId) { 3815 int numMatch = 0; 3816 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3817 for (int i=0; i<permissions.length; i++) { 3818 if (gp.grantedPermissions.contains(permissions[i])) { 3819 tmp[i] = true; 3820 numMatch++; 3821 } else { 3822 tmp[i] = false; 3823 } 3824 } 3825 if (numMatch == 0) { 3826 return; 3827 } 3828 PackageInfo pi; 3829 if (ps.pkg != null) { 3830 pi = generatePackageInfo(ps.pkg, flags, userId); 3831 } else { 3832 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3833 } 3834 // The above might return null in cases of uninstalled apps or install-state 3835 // skew across users/profiles. 3836 if (pi != null) { 3837 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3838 if (numMatch == permissions.length) { 3839 pi.requestedPermissions = permissions; 3840 } else { 3841 pi.requestedPermissions = new String[numMatch]; 3842 numMatch = 0; 3843 for (int i=0; i<permissions.length; i++) { 3844 if (tmp[i]) { 3845 pi.requestedPermissions[numMatch] = permissions[i]; 3846 numMatch++; 3847 } 3848 } 3849 } 3850 } 3851 list.add(pi); 3852 } 3853 } 3854 3855 @Override 3856 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3857 String[] permissions, int flags, int userId) { 3858 if (!sUserManager.exists(userId)) return null; 3859 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3860 3861 // writer 3862 synchronized (mPackages) { 3863 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3864 boolean[] tmpBools = new boolean[permissions.length]; 3865 if (listUninstalled) { 3866 for (PackageSetting ps : mSettings.mPackages.values()) { 3867 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3868 } 3869 } else { 3870 for (PackageParser.Package pkg : mPackages.values()) { 3871 PackageSetting ps = (PackageSetting)pkg.mExtras; 3872 if (ps != null) { 3873 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3874 userId); 3875 } 3876 } 3877 } 3878 3879 return new ParceledListSlice<PackageInfo>(list); 3880 } 3881 } 3882 3883 @Override 3884 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3885 if (!sUserManager.exists(userId)) return null; 3886 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3887 3888 // writer 3889 synchronized (mPackages) { 3890 ArrayList<ApplicationInfo> list; 3891 if (listUninstalled) { 3892 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3893 for (PackageSetting ps : mSettings.mPackages.values()) { 3894 ApplicationInfo ai; 3895 if (ps.pkg != null) { 3896 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3897 ps.readUserState(userId), userId); 3898 } else { 3899 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3900 } 3901 if (ai != null) { 3902 list.add(ai); 3903 } 3904 } 3905 } else { 3906 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3907 for (PackageParser.Package p : mPackages.values()) { 3908 if (p.mExtras != null) { 3909 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3910 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3911 if (ai != null) { 3912 list.add(ai); 3913 } 3914 } 3915 } 3916 } 3917 3918 return new ParceledListSlice<ApplicationInfo>(list); 3919 } 3920 } 3921 3922 public List<ApplicationInfo> getPersistentApplications(int flags) { 3923 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3924 3925 // reader 3926 synchronized (mPackages) { 3927 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3928 final int userId = UserHandle.getCallingUserId(); 3929 while (i.hasNext()) { 3930 final PackageParser.Package p = i.next(); 3931 if (p.applicationInfo != null 3932 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3933 && (!mSafeMode || isSystemApp(p))) { 3934 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3935 if (ps != null) { 3936 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3937 ps.readUserState(userId), userId); 3938 if (ai != null) { 3939 finalList.add(ai); 3940 } 3941 } 3942 } 3943 } 3944 } 3945 3946 return finalList; 3947 } 3948 3949 @Override 3950 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3951 if (!sUserManager.exists(userId)) return null; 3952 // reader 3953 synchronized (mPackages) { 3954 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3955 PackageSetting ps = provider != null 3956 ? mSettings.mPackages.get(provider.owner.packageName) 3957 : null; 3958 return ps != null 3959 && mSettings.isEnabledLPr(provider.info, flags, userId) 3960 && (!mSafeMode || (provider.info.applicationInfo.flags 3961 &ApplicationInfo.FLAG_SYSTEM) != 0) 3962 ? PackageParser.generateProviderInfo(provider, flags, 3963 ps.readUserState(userId), userId) 3964 : null; 3965 } 3966 } 3967 3968 /** 3969 * @deprecated 3970 */ 3971 @Deprecated 3972 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3973 // reader 3974 synchronized (mPackages) { 3975 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3976 .entrySet().iterator(); 3977 final int userId = UserHandle.getCallingUserId(); 3978 while (i.hasNext()) { 3979 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3980 PackageParser.Provider p = entry.getValue(); 3981 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3982 3983 if (ps != null && p.syncable 3984 && (!mSafeMode || (p.info.applicationInfo.flags 3985 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3986 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3987 ps.readUserState(userId), userId); 3988 if (info != null) { 3989 outNames.add(entry.getKey()); 3990 outInfo.add(info); 3991 } 3992 } 3993 } 3994 } 3995 } 3996 3997 @Override 3998 public List<ProviderInfo> queryContentProviders(String processName, 3999 int uid, int flags) { 4000 ArrayList<ProviderInfo> finalList = null; 4001 // reader 4002 synchronized (mPackages) { 4003 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4004 final int userId = processName != null ? 4005 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4006 while (i.hasNext()) { 4007 final PackageParser.Provider p = i.next(); 4008 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4009 if (ps != null && p.info.authority != null 4010 && (processName == null 4011 || (p.info.processName.equals(processName) 4012 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4013 && mSettings.isEnabledLPr(p.info, flags, userId) 4014 && (!mSafeMode 4015 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4016 if (finalList == null) { 4017 finalList = new ArrayList<ProviderInfo>(3); 4018 } 4019 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4020 ps.readUserState(userId), userId); 4021 if (info != null) { 4022 finalList.add(info); 4023 } 4024 } 4025 } 4026 } 4027 4028 if (finalList != null) { 4029 Collections.sort(finalList, mProviderInitOrderSorter); 4030 } 4031 4032 return finalList; 4033 } 4034 4035 @Override 4036 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4037 int flags) { 4038 // reader 4039 synchronized (mPackages) { 4040 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4041 return PackageParser.generateInstrumentationInfo(i, flags); 4042 } 4043 } 4044 4045 @Override 4046 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4047 int flags) { 4048 ArrayList<InstrumentationInfo> finalList = 4049 new ArrayList<InstrumentationInfo>(); 4050 4051 // reader 4052 synchronized (mPackages) { 4053 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4054 while (i.hasNext()) { 4055 final PackageParser.Instrumentation p = i.next(); 4056 if (targetPackage == null 4057 || targetPackage.equals(p.info.targetPackage)) { 4058 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4059 flags); 4060 if (ii != null) { 4061 finalList.add(ii); 4062 } 4063 } 4064 } 4065 } 4066 4067 return finalList; 4068 } 4069 4070 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4071 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4072 if (overlays == null) { 4073 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4074 return; 4075 } 4076 for (PackageParser.Package opkg : overlays.values()) { 4077 // Not much to do if idmap fails: we already logged the error 4078 // and we certainly don't want to abort installation of pkg simply 4079 // because an overlay didn't fit properly. For these reasons, 4080 // ignore the return value of createIdmapForPackagePairLI. 4081 createIdmapForPackagePairLI(pkg, opkg); 4082 } 4083 } 4084 4085 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4086 PackageParser.Package opkg) { 4087 if (!opkg.mTrustedOverlay) { 4088 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4089 opkg.baseCodePath + ": overlay not trusted"); 4090 return false; 4091 } 4092 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4093 if (overlaySet == null) { 4094 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4095 opkg.baseCodePath + " but target package has no known overlays"); 4096 return false; 4097 } 4098 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4099 // TODO: generate idmap for split APKs 4100 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4101 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4102 + opkg.baseCodePath); 4103 return false; 4104 } 4105 PackageParser.Package[] overlayArray = 4106 overlaySet.values().toArray(new PackageParser.Package[0]); 4107 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4108 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4109 return p1.mOverlayPriority - p2.mOverlayPriority; 4110 } 4111 }; 4112 Arrays.sort(overlayArray, cmp); 4113 4114 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4115 int i = 0; 4116 for (PackageParser.Package p : overlayArray) { 4117 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4118 } 4119 return true; 4120 } 4121 4122 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4123 final File[] files = dir.listFiles(); 4124 if (ArrayUtils.isEmpty(files)) { 4125 Log.d(TAG, "No files in app dir " + dir); 4126 return; 4127 } 4128 4129 if (DEBUG_PACKAGE_SCANNING) { 4130 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4131 + " flags=0x" + Integer.toHexString(parseFlags)); 4132 } 4133 4134 for (File file : files) { 4135 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4136 && !PackageInstallerService.isStageName(file.getName()); 4137 if (!isPackage) { 4138 // Ignore entries which are not packages 4139 continue; 4140 } 4141 try { 4142 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4143 scanFlags, currentTime, null); 4144 } catch (PackageManagerException e) { 4145 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4146 4147 // Delete invalid userdata apps 4148 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4149 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4150 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4151 if (file.isDirectory()) { 4152 FileUtils.deleteContents(file); 4153 } 4154 file.delete(); 4155 } 4156 } 4157 } 4158 } 4159 4160 private static File getSettingsProblemFile() { 4161 File dataDir = Environment.getDataDirectory(); 4162 File systemDir = new File(dataDir, "system"); 4163 File fname = new File(systemDir, "uiderrors.txt"); 4164 return fname; 4165 } 4166 4167 static void reportSettingsProblem(int priority, String msg) { 4168 logCriticalInfo(priority, msg); 4169 } 4170 4171 static void logCriticalInfo(int priority, String msg) { 4172 Slog.println(priority, TAG, msg); 4173 EventLogTags.writePmCriticalInfo(msg); 4174 try { 4175 File fname = getSettingsProblemFile(); 4176 FileOutputStream out = new FileOutputStream(fname, true); 4177 PrintWriter pw = new FastPrintWriter(out); 4178 SimpleDateFormat formatter = new SimpleDateFormat(); 4179 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4180 pw.println(dateString + ": " + msg); 4181 pw.close(); 4182 FileUtils.setPermissions( 4183 fname.toString(), 4184 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4185 -1, -1); 4186 } catch (java.io.IOException e) { 4187 } 4188 } 4189 4190 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4191 PackageParser.Package pkg, File srcFile, int parseFlags) 4192 throws PackageManagerException { 4193 if (ps != null 4194 && ps.codePath.equals(srcFile) 4195 && ps.timeStamp == srcFile.lastModified() 4196 && !isCompatSignatureUpdateNeeded(pkg) 4197 && !isRecoverSignatureUpdateNeeded(pkg)) { 4198 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4199 if (ps.signatures.mSignatures != null 4200 && ps.signatures.mSignatures.length != 0 4201 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4202 // Optimization: reuse the existing cached certificates 4203 // if the package appears to be unchanged. 4204 pkg.mSignatures = ps.signatures.mSignatures; 4205 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4206 synchronized (mPackages) { 4207 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4208 } 4209 return; 4210 } 4211 4212 Slog.w(TAG, "PackageSetting for " + ps.name 4213 + " is missing signatures. Collecting certs again to recover them."); 4214 } else { 4215 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4216 } 4217 4218 try { 4219 pp.collectCertificates(pkg, parseFlags); 4220 pp.collectManifestDigest(pkg); 4221 } catch (PackageParserException e) { 4222 throw PackageManagerException.from(e); 4223 } 4224 } 4225 4226 /* 4227 * Scan a package and return the newly parsed package. 4228 * Returns null in case of errors and the error code is stored in mLastScanError 4229 */ 4230 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4231 long currentTime, UserHandle user) throws PackageManagerException { 4232 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4233 parseFlags |= mDefParseFlags; 4234 PackageParser pp = new PackageParser(); 4235 pp.setSeparateProcesses(mSeparateProcesses); 4236 pp.setOnlyCoreApps(mOnlyCore); 4237 pp.setDisplayMetrics(mMetrics); 4238 4239 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4240 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4241 } 4242 4243 final PackageParser.Package pkg; 4244 try { 4245 pkg = pp.parsePackage(scanFile, parseFlags); 4246 } catch (PackageParserException e) { 4247 throw PackageManagerException.from(e); 4248 } 4249 4250 PackageSetting ps = null; 4251 PackageSetting updatedPkg; 4252 // reader 4253 synchronized (mPackages) { 4254 // Look to see if we already know about this package. 4255 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4256 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4257 // This package has been renamed to its original name. Let's 4258 // use that. 4259 ps = mSettings.peekPackageLPr(oldName); 4260 } 4261 // If there was no original package, see one for the real package name. 4262 if (ps == null) { 4263 ps = mSettings.peekPackageLPr(pkg.packageName); 4264 } 4265 // Check to see if this package could be hiding/updating a system 4266 // package. Must look for it either under the original or real 4267 // package name depending on our state. 4268 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4269 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4270 } 4271 boolean updatedPkgBetter = false; 4272 // First check if this is a system package that may involve an update 4273 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4274 if (ps != null && !ps.codePath.equals(scanFile)) { 4275 // The path has changed from what was last scanned... check the 4276 // version of the new path against what we have stored to determine 4277 // what to do. 4278 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4279 if (pkg.mVersionCode <= ps.versionCode) { 4280 // The system package has been updated and the code path does not match 4281 // Ignore entry. Skip it. 4282 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4283 + " ignored: updated version " + ps.versionCode 4284 + " better than this " + pkg.mVersionCode); 4285 if (!updatedPkg.codePath.equals(scanFile)) { 4286 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4287 + ps.name + " changing from " + updatedPkg.codePathString 4288 + " to " + scanFile); 4289 updatedPkg.codePath = scanFile; 4290 updatedPkg.codePathString = scanFile.toString(); 4291 updatedPkg.resourcePath = scanFile; 4292 updatedPkg.resourcePathString = scanFile.toString(); 4293 // This is the point at which we know that the system-disk APK 4294 // for this package has moved during a reboot (e.g. due to an OTA), 4295 // so we need to reevaluate it for privilege policy. 4296 if (locationIsPrivileged(scanFile)) { 4297 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4298 } 4299 } 4300 updatedPkg.pkg = pkg; 4301 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4302 } else { 4303 // The current app on the system partition is better than 4304 // what we have updated to on the data partition; switch 4305 // back to the system partition version. 4306 // At this point, its safely assumed that package installation for 4307 // apps in system partition will go through. If not there won't be a working 4308 // version of the app 4309 // writer 4310 synchronized (mPackages) { 4311 // Just remove the loaded entries from package lists. 4312 mPackages.remove(ps.name); 4313 } 4314 4315 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4316 + " reverting from " + ps.codePathString 4317 + ": new version " + pkg.mVersionCode 4318 + " better than installed " + ps.versionCode); 4319 4320 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4321 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4322 getAppDexInstructionSets(ps)); 4323 synchronized (mInstallLock) { 4324 args.cleanUpResourcesLI(); 4325 } 4326 synchronized (mPackages) { 4327 mSettings.enableSystemPackageLPw(ps.name); 4328 } 4329 updatedPkgBetter = true; 4330 } 4331 } 4332 } 4333 4334 if (updatedPkg != null) { 4335 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4336 // initially 4337 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4338 4339 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4340 // flag set initially 4341 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4342 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4343 } 4344 } 4345 4346 // Verify certificates against what was last scanned 4347 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4348 4349 /* 4350 * A new system app appeared, but we already had a non-system one of the 4351 * same name installed earlier. 4352 */ 4353 boolean shouldHideSystemApp = false; 4354 if (updatedPkg == null && ps != null 4355 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4356 /* 4357 * Check to make sure the signatures match first. If they don't, 4358 * wipe the installed application and its data. 4359 */ 4360 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4361 != PackageManager.SIGNATURE_MATCH) { 4362 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4363 + " signatures don't match existing userdata copy; removing"); 4364 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4365 ps = null; 4366 } else { 4367 /* 4368 * If the newly-added system app is an older version than the 4369 * already installed version, hide it. It will be scanned later 4370 * and re-added like an update. 4371 */ 4372 if (pkg.mVersionCode <= ps.versionCode) { 4373 shouldHideSystemApp = true; 4374 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4375 + " but new version " + pkg.mVersionCode + " better than installed " 4376 + ps.versionCode + "; hiding system"); 4377 } else { 4378 /* 4379 * The newly found system app is a newer version that the 4380 * one previously installed. Simply remove the 4381 * already-installed application and replace it with our own 4382 * while keeping the application data. 4383 */ 4384 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4385 + " reverting from " + ps.codePathString + ": new version " 4386 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4387 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4388 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4389 getAppDexInstructionSets(ps)); 4390 synchronized (mInstallLock) { 4391 args.cleanUpResourcesLI(); 4392 } 4393 } 4394 } 4395 } 4396 4397 // The apk is forward locked (not public) if its code and resources 4398 // are kept in different files. (except for app in either system or 4399 // vendor path). 4400 // TODO grab this value from PackageSettings 4401 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4402 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4403 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4404 } 4405 } 4406 4407 // TODO: extend to support forward-locked splits 4408 String resourcePath = null; 4409 String baseResourcePath = null; 4410 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4411 if (ps != null && ps.resourcePathString != null) { 4412 resourcePath = ps.resourcePathString; 4413 baseResourcePath = ps.resourcePathString; 4414 } else { 4415 // Should not happen at all. Just log an error. 4416 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4417 } 4418 } else { 4419 resourcePath = pkg.codePath; 4420 baseResourcePath = pkg.baseCodePath; 4421 } 4422 4423 // Set application objects path explicitly. 4424 pkg.applicationInfo.setCodePath(pkg.codePath); 4425 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4426 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4427 pkg.applicationInfo.setResourcePath(resourcePath); 4428 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4429 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4430 4431 // Note that we invoke the following method only if we are about to unpack an application 4432 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4433 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4434 4435 /* 4436 * If the system app should be overridden by a previously installed 4437 * data, hide the system app now and let the /data/app scan pick it up 4438 * again. 4439 */ 4440 if (shouldHideSystemApp) { 4441 synchronized (mPackages) { 4442 /* 4443 * We have to grant systems permissions before we hide, because 4444 * grantPermissions will assume the package update is trying to 4445 * expand its permissions. 4446 */ 4447 grantPermissionsLPw(pkg, true, pkg.packageName); 4448 mSettings.disableSystemPackageLPw(pkg.packageName); 4449 } 4450 } 4451 4452 return scannedPkg; 4453 } 4454 4455 private static String fixProcessName(String defProcessName, 4456 String processName, int uid) { 4457 if (processName == null) { 4458 return defProcessName; 4459 } 4460 return processName; 4461 } 4462 4463 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4464 throws PackageManagerException { 4465 if (pkgSetting.signatures.mSignatures != null) { 4466 // Already existing package. Make sure signatures match 4467 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4468 == PackageManager.SIGNATURE_MATCH; 4469 if (!match) { 4470 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4471 == PackageManager.SIGNATURE_MATCH; 4472 } 4473 if (!match) { 4474 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4475 == PackageManager.SIGNATURE_MATCH; 4476 } 4477 if (!match) { 4478 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4479 + pkg.packageName + " signatures do not match the " 4480 + "previously installed version; ignoring!"); 4481 } 4482 } 4483 4484 // Check for shared user signatures 4485 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4486 // Already existing package. Make sure signatures match 4487 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4488 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4489 if (!match) { 4490 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4491 == PackageManager.SIGNATURE_MATCH; 4492 } 4493 if (!match) { 4494 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4495 == PackageManager.SIGNATURE_MATCH; 4496 } 4497 if (!match) { 4498 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4499 "Package " + pkg.packageName 4500 + " has no signatures that match those in shared user " 4501 + pkgSetting.sharedUser.name + "; ignoring!"); 4502 } 4503 } 4504 } 4505 4506 /** 4507 * Enforces that only the system UID or root's UID can call a method exposed 4508 * via Binder. 4509 * 4510 * @param message used as message if SecurityException is thrown 4511 * @throws SecurityException if the caller is not system or root 4512 */ 4513 private static final void enforceSystemOrRoot(String message) { 4514 final int uid = Binder.getCallingUid(); 4515 if (uid != Process.SYSTEM_UID && uid != 0) { 4516 throw new SecurityException(message); 4517 } 4518 } 4519 4520 @Override 4521 public void performBootDexOpt() { 4522 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4523 4524 final ArraySet<PackageParser.Package> pkgs; 4525 synchronized (mPackages) { 4526 pkgs = mDeferredDexOpt; 4527 mDeferredDexOpt = null; 4528 } 4529 4530 if (pkgs != null) { 4531 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4532 // in case the device runs out of space. 4533 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4534 // Give priority to core apps. 4535 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4536 PackageParser.Package pkg = it.next(); 4537 if (pkg.coreApp) { 4538 if (DEBUG_DEXOPT) { 4539 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4540 } 4541 sortedPkgs.add(pkg); 4542 it.remove(); 4543 } 4544 } 4545 // Give priority to system apps that listen for pre boot complete. 4546 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4547 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4548 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4549 PackageParser.Package pkg = it.next(); 4550 if (pkgNames.contains(pkg.packageName)) { 4551 if (DEBUG_DEXOPT) { 4552 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4553 } 4554 sortedPkgs.add(pkg); 4555 it.remove(); 4556 } 4557 } 4558 // Give priority to system apps. 4559 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4560 PackageParser.Package pkg = it.next(); 4561 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4562 if (DEBUG_DEXOPT) { 4563 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4564 } 4565 sortedPkgs.add(pkg); 4566 it.remove(); 4567 } 4568 } 4569 // Give priority to updated system apps. 4570 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4571 PackageParser.Package pkg = it.next(); 4572 if (isUpdatedSystemApp(pkg)) { 4573 if (DEBUG_DEXOPT) { 4574 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4575 } 4576 sortedPkgs.add(pkg); 4577 it.remove(); 4578 } 4579 } 4580 // Give priority to apps that listen for boot complete. 4581 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4582 pkgNames = getPackageNamesForIntent(intent); 4583 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4584 PackageParser.Package pkg = it.next(); 4585 if (pkgNames.contains(pkg.packageName)) { 4586 if (DEBUG_DEXOPT) { 4587 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4588 } 4589 sortedPkgs.add(pkg); 4590 it.remove(); 4591 } 4592 } 4593 // Filter out packages that aren't recently used. 4594 filterRecentlyUsedApps(pkgs); 4595 // Add all remaining apps. 4596 for (PackageParser.Package pkg : pkgs) { 4597 if (DEBUG_DEXOPT) { 4598 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4599 } 4600 sortedPkgs.add(pkg); 4601 } 4602 4603 // If we want to be lazy, filter everything that wasn't recently used. 4604 if (mLazyDexOpt) { 4605 filterRecentlyUsedApps(sortedPkgs); 4606 } 4607 4608 int i = 0; 4609 int total = sortedPkgs.size(); 4610 File dataDir = Environment.getDataDirectory(); 4611 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4612 if (lowThreshold == 0) { 4613 throw new IllegalStateException("Invalid low memory threshold"); 4614 } 4615 for (PackageParser.Package pkg : sortedPkgs) { 4616 long usableSpace = dataDir.getUsableSpace(); 4617 if (usableSpace < lowThreshold) { 4618 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4619 break; 4620 } 4621 performBootDexOpt(pkg, ++i, total); 4622 } 4623 } 4624 } 4625 4626 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4627 // Filter out packages that aren't recently used. 4628 // 4629 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4630 // should do a full dexopt. 4631 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4632 int total = pkgs.size(); 4633 int skipped = 0; 4634 long now = System.currentTimeMillis(); 4635 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4636 PackageParser.Package pkg = i.next(); 4637 long then = pkg.mLastPackageUsageTimeInMills; 4638 if (then + mDexOptLRUThresholdInMills < now) { 4639 if (DEBUG_DEXOPT) { 4640 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4641 ((then == 0) ? "never" : new Date(then))); 4642 } 4643 i.remove(); 4644 skipped++; 4645 } 4646 } 4647 if (DEBUG_DEXOPT) { 4648 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4649 } 4650 } 4651 } 4652 4653 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4654 List<ResolveInfo> ris = null; 4655 try { 4656 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4657 intent, null, 0, UserHandle.USER_OWNER); 4658 } catch (RemoteException e) { 4659 } 4660 ArraySet<String> pkgNames = new ArraySet<String>(); 4661 if (ris != null) { 4662 for (ResolveInfo ri : ris) { 4663 pkgNames.add(ri.activityInfo.packageName); 4664 } 4665 } 4666 return pkgNames; 4667 } 4668 4669 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4670 if (DEBUG_DEXOPT) { 4671 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4672 } 4673 if (!isFirstBoot()) { 4674 try { 4675 ActivityManagerNative.getDefault().showBootMessage( 4676 mContext.getResources().getString(R.string.android_upgrading_apk, 4677 curr, total), true); 4678 } catch (RemoteException e) { 4679 } 4680 } 4681 PackageParser.Package p = pkg; 4682 synchronized (mInstallLock) { 4683 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4684 false /* defer */, true /* include dependencies */); 4685 } 4686 } 4687 4688 @Override 4689 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4690 return performDexOpt(packageName, instructionSet, false); 4691 } 4692 4693 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4694 if (info.primaryCpuAbi == null) { 4695 return getPreferredInstructionSet(); 4696 } 4697 4698 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4699 } 4700 4701 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4702 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4703 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4704 if (!dexopt && !updateUsage) { 4705 // We aren't going to dexopt or update usage, so bail early. 4706 return false; 4707 } 4708 PackageParser.Package p; 4709 final String targetInstructionSet; 4710 synchronized (mPackages) { 4711 p = mPackages.get(packageName); 4712 if (p == null) { 4713 return false; 4714 } 4715 if (updateUsage) { 4716 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4717 } 4718 mPackageUsage.write(false); 4719 if (!dexopt) { 4720 // We aren't going to dexopt, so bail early. 4721 return false; 4722 } 4723 4724 targetInstructionSet = instructionSet != null ? instructionSet : 4725 getPrimaryInstructionSet(p.applicationInfo); 4726 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4727 return false; 4728 } 4729 } 4730 4731 synchronized (mInstallLock) { 4732 final String[] instructionSets = new String[] { targetInstructionSet }; 4733 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4734 true /* include dependencies */) == DEX_OPT_PERFORMED; 4735 } 4736 } 4737 4738 public ArraySet<String> getPackagesThatNeedDexOpt() { 4739 ArraySet<String> pkgs = null; 4740 synchronized (mPackages) { 4741 for (PackageParser.Package p : mPackages.values()) { 4742 if (DEBUG_DEXOPT) { 4743 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4744 } 4745 if (!p.mDexOptPerformed.isEmpty()) { 4746 continue; 4747 } 4748 if (pkgs == null) { 4749 pkgs = new ArraySet<String>(); 4750 } 4751 pkgs.add(p.packageName); 4752 } 4753 } 4754 return pkgs; 4755 } 4756 4757 public void shutdown() { 4758 mPackageUsage.write(true); 4759 } 4760 4761 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4762 boolean forceDex, boolean defer, ArraySet<String> done) { 4763 for (int i=0; i<libs.size(); i++) { 4764 PackageParser.Package libPkg; 4765 String libName; 4766 synchronized (mPackages) { 4767 libName = libs.get(i); 4768 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4769 if (lib != null && lib.apk != null) { 4770 libPkg = mPackages.get(lib.apk); 4771 } else { 4772 libPkg = null; 4773 } 4774 } 4775 if (libPkg != null && !done.contains(libName)) { 4776 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4777 } 4778 } 4779 } 4780 4781 static final int DEX_OPT_SKIPPED = 0; 4782 static final int DEX_OPT_PERFORMED = 1; 4783 static final int DEX_OPT_DEFERRED = 2; 4784 static final int DEX_OPT_FAILED = -1; 4785 4786 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4787 boolean forceDex, boolean defer, ArraySet<String> done) { 4788 final String[] instructionSets = targetInstructionSets != null ? 4789 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4790 4791 if (done != null) { 4792 done.add(pkg.packageName); 4793 if (pkg.usesLibraries != null) { 4794 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4795 } 4796 if (pkg.usesOptionalLibraries != null) { 4797 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4798 } 4799 } 4800 4801 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4802 return DEX_OPT_SKIPPED; 4803 } 4804 4805 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4806 4807 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4808 boolean performedDexOpt = false; 4809 // There are three basic cases here: 4810 // 1.) we need to dexopt, either because we are forced or it is needed 4811 // 2.) we are defering a needed dexopt 4812 // 3.) we are skipping an unneeded dexopt 4813 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4814 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4815 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4816 continue; 4817 } 4818 4819 for (String path : paths) { 4820 try { 4821 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4822 // patckage or the one we find does not match the image checksum (i.e. it was 4823 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4824 // odex file and it matches the checksum of the image but not its base address, 4825 // meaning we need to move it. 4826 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4827 pkg.packageName, dexCodeInstructionSet, defer); 4828 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4829 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4830 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4831 + " vmSafeMode=" + vmSafeMode); 4832 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4833 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4834 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4835 4836 if (ret < 0) { 4837 // Don't bother running dexopt again if we failed, it will probably 4838 // just result in an error again. Also, don't bother dexopting for other 4839 // paths & ISAs. 4840 return DEX_OPT_FAILED; 4841 } 4842 4843 performedDexOpt = true; 4844 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4845 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4846 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4847 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4848 pkg.packageName, dexCodeInstructionSet); 4849 4850 if (ret < 0) { 4851 // Don't bother running patchoat again if we failed, it will probably 4852 // just result in an error again. Also, don't bother dexopting for other 4853 // paths & ISAs. 4854 return DEX_OPT_FAILED; 4855 } 4856 4857 performedDexOpt = true; 4858 } 4859 4860 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4861 // paths and instruction sets. We'll deal with them all together when we process 4862 // our list of deferred dexopts. 4863 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4864 if (mDeferredDexOpt == null) { 4865 mDeferredDexOpt = new ArraySet<PackageParser.Package>(); 4866 } 4867 mDeferredDexOpt.add(pkg); 4868 return DEX_OPT_DEFERRED; 4869 } 4870 } catch (FileNotFoundException e) { 4871 Slog.w(TAG, "Apk not found for dexopt: " + path); 4872 return DEX_OPT_FAILED; 4873 } catch (IOException e) { 4874 Slog.w(TAG, "IOException reading apk: " + path, e); 4875 return DEX_OPT_FAILED; 4876 } catch (StaleDexCacheError e) { 4877 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4878 return DEX_OPT_FAILED; 4879 } catch (Exception e) { 4880 Slog.w(TAG, "Exception when doing dexopt : ", e); 4881 return DEX_OPT_FAILED; 4882 } 4883 } 4884 4885 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4886 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4887 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4888 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4889 // it. 4890 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4891 } 4892 4893 // If we've gotten here, we're sure that no error occurred and that we haven't 4894 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4895 // we've skipped all of them because they are up to date. In both cases this 4896 // package doesn't need dexopt any longer. 4897 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4898 } 4899 4900 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4901 if (info.primaryCpuAbi != null) { 4902 if (info.secondaryCpuAbi != null) { 4903 return new String[] { 4904 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4905 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4906 } else { 4907 return new String[] { 4908 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4909 } 4910 } 4911 4912 return new String[] { getPreferredInstructionSet() }; 4913 } 4914 4915 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4916 if (ps.primaryCpuAbiString != null) { 4917 if (ps.secondaryCpuAbiString != null) { 4918 return new String[] { 4919 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4920 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4921 } else { 4922 return new String[] { 4923 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4924 } 4925 } 4926 4927 return new String[] { getPreferredInstructionSet() }; 4928 } 4929 4930 private static String getPreferredInstructionSet() { 4931 if (sPreferredInstructionSet == null) { 4932 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4933 } 4934 4935 return sPreferredInstructionSet; 4936 } 4937 4938 private static List<String> getAllInstructionSets() { 4939 final String[] allAbis = Build.SUPPORTED_ABIS; 4940 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4941 4942 for (String abi : allAbis) { 4943 final String instructionSet = VMRuntime.getInstructionSet(abi); 4944 if (!allInstructionSets.contains(instructionSet)) { 4945 allInstructionSets.add(instructionSet); 4946 } 4947 } 4948 4949 return allInstructionSets; 4950 } 4951 4952 /** 4953 * Returns the instruction set that should be used to compile dex code. In the presence of 4954 * a native bridge this might be different than the one shared libraries use. 4955 */ 4956 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4957 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4958 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4959 } 4960 4961 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4962 ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length); 4963 for (String instructionSet : instructionSets) { 4964 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4965 } 4966 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4967 } 4968 4969 /** 4970 * Returns deduplicated list of supported instructions for dex code. 4971 */ 4972 public static String[] getAllDexCodeInstructionSets() { 4973 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4974 for (int i = 0; i < supportedInstructionSets.length; i++) { 4975 String abi = Build.SUPPORTED_ABIS[i]; 4976 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4977 } 4978 return getDexCodeInstructionSets(supportedInstructionSets); 4979 } 4980 4981 @Override 4982 public void forceDexOpt(String packageName) { 4983 enforceSystemOrRoot("forceDexOpt"); 4984 4985 PackageParser.Package pkg; 4986 synchronized (mPackages) { 4987 pkg = mPackages.get(packageName); 4988 if (pkg == null) { 4989 throw new IllegalArgumentException("Missing package: " + packageName); 4990 } 4991 } 4992 4993 synchronized (mInstallLock) { 4994 final String[] instructionSets = new String[] { 4995 getPrimaryInstructionSet(pkg.applicationInfo) }; 4996 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4997 if (res != DEX_OPT_PERFORMED) { 4998 throw new IllegalStateException("Failed to dexopt: " + res); 4999 } 5000 } 5001 } 5002 5003 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 5004 boolean forceDex, boolean defer, boolean inclDependencies) { 5005 ArraySet<String> done; 5006 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 5007 done = new ArraySet<String>(); 5008 done.add(pkg.packageName); 5009 } else { 5010 done = null; 5011 } 5012 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 5013 } 5014 5015 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5016 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5017 Slog.w(TAG, "Unable to update from " + oldPkg.name 5018 + " to " + newPkg.packageName 5019 + ": old package not in system partition"); 5020 return false; 5021 } else if (mPackages.get(oldPkg.name) != null) { 5022 Slog.w(TAG, "Unable to update from " + oldPkg.name 5023 + " to " + newPkg.packageName 5024 + ": old package still exists"); 5025 return false; 5026 } 5027 return true; 5028 } 5029 5030 File getDataPathForUser(int userId) { 5031 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5032 } 5033 5034 private File getDataPathForPackage(String packageName, int userId) { 5035 /* 5036 * Until we fully support multiple users, return the directory we 5037 * previously would have. The PackageManagerTests will need to be 5038 * revised when this is changed back.. 5039 */ 5040 if (userId == 0) { 5041 return new File(mAppDataDir, packageName); 5042 } else { 5043 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5044 + File.separator + packageName); 5045 } 5046 } 5047 5048 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5049 int[] users = sUserManager.getUserIds(); 5050 int res = mInstaller.install(packageName, uid, uid, seinfo); 5051 if (res < 0) { 5052 return res; 5053 } 5054 for (int user : users) { 5055 if (user != 0) { 5056 res = mInstaller.createUserData(packageName, 5057 UserHandle.getUid(user, uid), user, seinfo); 5058 if (res < 0) { 5059 return res; 5060 } 5061 } 5062 } 5063 return res; 5064 } 5065 5066 private int removeDataDirsLI(String packageName) { 5067 int[] users = sUserManager.getUserIds(); 5068 int res = 0; 5069 for (int user : users) { 5070 int resInner = mInstaller.remove(packageName, user); 5071 if (resInner < 0) { 5072 res = resInner; 5073 } 5074 } 5075 5076 return res; 5077 } 5078 5079 private int deleteCodeCacheDirsLI(String packageName) { 5080 int[] users = sUserManager.getUserIds(); 5081 int res = 0; 5082 for (int user : users) { 5083 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5084 if (resInner < 0) { 5085 res = resInner; 5086 } 5087 } 5088 return res; 5089 } 5090 5091 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5092 PackageParser.Package changingLib) { 5093 if (file.path != null) { 5094 usesLibraryFiles.add(file.path); 5095 return; 5096 } 5097 PackageParser.Package p = mPackages.get(file.apk); 5098 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5099 // If we are doing this while in the middle of updating a library apk, 5100 // then we need to make sure to use that new apk for determining the 5101 // dependencies here. (We haven't yet finished committing the new apk 5102 // to the package manager state.) 5103 if (p == null || p.packageName.equals(changingLib.packageName)) { 5104 p = changingLib; 5105 } 5106 } 5107 if (p != null) { 5108 usesLibraryFiles.addAll(p.getAllCodePaths()); 5109 } 5110 } 5111 5112 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5113 PackageParser.Package changingLib) throws PackageManagerException { 5114 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5115 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5116 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5117 for (int i=0; i<N; i++) { 5118 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5119 if (file == null) { 5120 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5121 "Package " + pkg.packageName + " requires unavailable shared library " 5122 + pkg.usesLibraries.get(i) + "; failing!"); 5123 } 5124 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5125 } 5126 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5127 for (int i=0; i<N; i++) { 5128 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5129 if (file == null) { 5130 Slog.w(TAG, "Package " + pkg.packageName 5131 + " desires unavailable shared library " 5132 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5133 } else { 5134 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5135 } 5136 } 5137 N = usesLibraryFiles.size(); 5138 if (N > 0) { 5139 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5140 } else { 5141 pkg.usesLibraryFiles = null; 5142 } 5143 } 5144 } 5145 5146 private static boolean hasString(List<String> list, List<String> which) { 5147 if (list == null) { 5148 return false; 5149 } 5150 for (int i=list.size()-1; i>=0; i--) { 5151 for (int j=which.size()-1; j>=0; j--) { 5152 if (which.get(j).equals(list.get(i))) { 5153 return true; 5154 } 5155 } 5156 } 5157 return false; 5158 } 5159 5160 private void updateAllSharedLibrariesLPw() { 5161 for (PackageParser.Package pkg : mPackages.values()) { 5162 try { 5163 updateSharedLibrariesLPw(pkg, null); 5164 } catch (PackageManagerException e) { 5165 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5166 } 5167 } 5168 } 5169 5170 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5171 PackageParser.Package changingPkg) { 5172 ArrayList<PackageParser.Package> res = null; 5173 for (PackageParser.Package pkg : mPackages.values()) { 5174 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5175 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5176 if (res == null) { 5177 res = new ArrayList<PackageParser.Package>(); 5178 } 5179 res.add(pkg); 5180 try { 5181 updateSharedLibrariesLPw(pkg, changingPkg); 5182 } catch (PackageManagerException e) { 5183 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5184 } 5185 } 5186 } 5187 return res; 5188 } 5189 5190 /** 5191 * Derive the value of the {@code cpuAbiOverride} based on the provided 5192 * value and an optional stored value from the package settings. 5193 */ 5194 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5195 String cpuAbiOverride = null; 5196 5197 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5198 cpuAbiOverride = null; 5199 } else if (abiOverride != null) { 5200 cpuAbiOverride = abiOverride; 5201 } else if (settings != null) { 5202 cpuAbiOverride = settings.cpuAbiOverrideString; 5203 } 5204 5205 return cpuAbiOverride; 5206 } 5207 5208 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5209 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5210 boolean success = false; 5211 try { 5212 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5213 currentTime, user); 5214 success = true; 5215 return res; 5216 } finally { 5217 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5218 removeDataDirsLI(pkg.packageName); 5219 } 5220 } 5221 } 5222 5223 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5224 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5225 final File scanFile = new File(pkg.codePath); 5226 if (pkg.applicationInfo.getCodePath() == null || 5227 pkg.applicationInfo.getResourcePath() == null) { 5228 // Bail out. The resource and code paths haven't been set. 5229 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5230 "Code and resource paths haven't been set correctly"); 5231 } 5232 5233 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5234 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5235 } else { 5236 // Only allow system apps to be flagged as core apps. 5237 pkg.coreApp = false; 5238 } 5239 5240 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5241 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5242 } 5243 5244 if (mCustomResolverComponentName != null && 5245 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5246 setUpCustomResolverActivity(pkg); 5247 } 5248 5249 if (pkg.packageName.equals("android")) { 5250 synchronized (mPackages) { 5251 if (mAndroidApplication != null) { 5252 Slog.w(TAG, "*************************************************"); 5253 Slog.w(TAG, "Core android package being redefined. Skipping."); 5254 Slog.w(TAG, " file=" + scanFile); 5255 Slog.w(TAG, "*************************************************"); 5256 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5257 "Core android package being redefined. Skipping."); 5258 } 5259 5260 // Set up information for our fall-back user intent resolution activity. 5261 mPlatformPackage = pkg; 5262 pkg.mVersionCode = mSdkVersion; 5263 mAndroidApplication = pkg.applicationInfo; 5264 5265 if (!mResolverReplaced) { 5266 mResolveActivity.applicationInfo = mAndroidApplication; 5267 mResolveActivity.name = ResolverActivity.class.getName(); 5268 mResolveActivity.packageName = mAndroidApplication.packageName; 5269 mResolveActivity.processName = "system:ui"; 5270 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5271 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5272 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5273 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5274 mResolveActivity.exported = true; 5275 mResolveActivity.enabled = true; 5276 mResolveInfo.activityInfo = mResolveActivity; 5277 mResolveInfo.priority = 0; 5278 mResolveInfo.preferredOrder = 0; 5279 mResolveInfo.match = 0; 5280 mResolveComponentName = new ComponentName( 5281 mAndroidApplication.packageName, mResolveActivity.name); 5282 } 5283 } 5284 } 5285 5286 if (DEBUG_PACKAGE_SCANNING) { 5287 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5288 Log.d(TAG, "Scanning package " + pkg.packageName); 5289 } 5290 5291 if (mPackages.containsKey(pkg.packageName) 5292 || mSharedLibraries.containsKey(pkg.packageName)) { 5293 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5294 "Application package " + pkg.packageName 5295 + " already installed. Skipping duplicate."); 5296 } 5297 5298 // Initialize package source and resource directories 5299 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5300 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5301 5302 SharedUserSetting suid = null; 5303 PackageSetting pkgSetting = null; 5304 5305 if (!isSystemApp(pkg)) { 5306 // Only system apps can use these features. 5307 pkg.mOriginalPackages = null; 5308 pkg.mRealPackage = null; 5309 pkg.mAdoptPermissions = null; 5310 } 5311 5312 // writer 5313 synchronized (mPackages) { 5314 if (pkg.mSharedUserId != null) { 5315 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5316 if (suid == null) { 5317 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5318 "Creating application package " + pkg.packageName 5319 + " for shared user failed"); 5320 } 5321 if (DEBUG_PACKAGE_SCANNING) { 5322 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5323 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5324 + "): packages=" + suid.packages); 5325 } 5326 } 5327 5328 // Check if we are renaming from an original package name. 5329 PackageSetting origPackage = null; 5330 String realName = null; 5331 if (pkg.mOriginalPackages != null) { 5332 // This package may need to be renamed to a previously 5333 // installed name. Let's check on that... 5334 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5335 if (pkg.mOriginalPackages.contains(renamed)) { 5336 // This package had originally been installed as the 5337 // original name, and we have already taken care of 5338 // transitioning to the new one. Just update the new 5339 // one to continue using the old name. 5340 realName = pkg.mRealPackage; 5341 if (!pkg.packageName.equals(renamed)) { 5342 // Callers into this function may have already taken 5343 // care of renaming the package; only do it here if 5344 // it is not already done. 5345 pkg.setPackageName(renamed); 5346 } 5347 5348 } else { 5349 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5350 if ((origPackage = mSettings.peekPackageLPr( 5351 pkg.mOriginalPackages.get(i))) != null) { 5352 // We do have the package already installed under its 5353 // original name... should we use it? 5354 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5355 // New package is not compatible with original. 5356 origPackage = null; 5357 continue; 5358 } else if (origPackage.sharedUser != null) { 5359 // Make sure uid is compatible between packages. 5360 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5361 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5362 + " to " + pkg.packageName + ": old uid " 5363 + origPackage.sharedUser.name 5364 + " differs from " + pkg.mSharedUserId); 5365 origPackage = null; 5366 continue; 5367 } 5368 } else { 5369 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5370 + pkg.packageName + " to old name " + origPackage.name); 5371 } 5372 break; 5373 } 5374 } 5375 } 5376 } 5377 5378 if (mTransferedPackages.contains(pkg.packageName)) { 5379 Slog.w(TAG, "Package " + pkg.packageName 5380 + " was transferred to another, but its .apk remains"); 5381 } 5382 5383 // Just create the setting, don't add it yet. For already existing packages 5384 // the PkgSetting exists already and doesn't have to be created. 5385 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5386 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5387 pkg.applicationInfo.primaryCpuAbi, 5388 pkg.applicationInfo.secondaryCpuAbi, 5389 pkg.applicationInfo.flags, user, false); 5390 if (pkgSetting == null) { 5391 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5392 "Creating application package " + pkg.packageName + " failed"); 5393 } 5394 5395 if (pkgSetting.origPackage != null) { 5396 // If we are first transitioning from an original package, 5397 // fix up the new package's name now. We need to do this after 5398 // looking up the package under its new name, so getPackageLP 5399 // can take care of fiddling things correctly. 5400 pkg.setPackageName(origPackage.name); 5401 5402 // File a report about this. 5403 String msg = "New package " + pkgSetting.realName 5404 + " renamed to replace old package " + pkgSetting.name; 5405 reportSettingsProblem(Log.WARN, msg); 5406 5407 // Make a note of it. 5408 mTransferedPackages.add(origPackage.name); 5409 5410 // No longer need to retain this. 5411 pkgSetting.origPackage = null; 5412 } 5413 5414 if (realName != null) { 5415 // Make a note of it. 5416 mTransferedPackages.add(pkg.packageName); 5417 } 5418 5419 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5420 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5421 } 5422 5423 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5424 // Check all shared libraries and map to their actual file path. 5425 // We only do this here for apps not on a system dir, because those 5426 // are the only ones that can fail an install due to this. We 5427 // will take care of the system apps by updating all of their 5428 // library paths after the scan is done. 5429 updateSharedLibrariesLPw(pkg, null); 5430 } 5431 5432 if (mFoundPolicyFile) { 5433 SELinuxMMAC.assignSeinfoValue(pkg); 5434 } 5435 5436 pkg.applicationInfo.uid = pkgSetting.appId; 5437 pkg.mExtras = pkgSetting; 5438 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5439 try { 5440 verifySignaturesLP(pkgSetting, pkg); 5441 // We just determined the app is signed correctly, so bring 5442 // over the latest parsed certs. 5443 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5444 } catch (PackageManagerException e) { 5445 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5446 throw e; 5447 } 5448 // The signature has changed, but this package is in the system 5449 // image... let's recover! 5450 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5451 // However... if this package is part of a shared user, but it 5452 // doesn't match the signature of the shared user, let's fail. 5453 // What this means is that you can't change the signatures 5454 // associated with an overall shared user, which doesn't seem all 5455 // that unreasonable. 5456 if (pkgSetting.sharedUser != null) { 5457 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5458 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5459 throw new PackageManagerException( 5460 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5461 "Signature mismatch for shared user : " 5462 + pkgSetting.sharedUser); 5463 } 5464 } 5465 // File a report about this. 5466 String msg = "System package " + pkg.packageName 5467 + " signature changed; retaining data."; 5468 reportSettingsProblem(Log.WARN, msg); 5469 } 5470 } else { 5471 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5472 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5473 + pkg.packageName + " upgrade keys do not match the " 5474 + "previously installed version"); 5475 } else { 5476 // We just determined the app is signed correctly, so bring 5477 // over the latest parsed certs. 5478 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5479 } 5480 } 5481 // Verify that this new package doesn't have any content providers 5482 // that conflict with existing packages. Only do this if the 5483 // package isn't already installed, since we don't want to break 5484 // things that are installed. 5485 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5486 final int N = pkg.providers.size(); 5487 int i; 5488 for (i=0; i<N; i++) { 5489 PackageParser.Provider p = pkg.providers.get(i); 5490 if (p.info.authority != null) { 5491 String names[] = p.info.authority.split(";"); 5492 for (int j = 0; j < names.length; j++) { 5493 if (mProvidersByAuthority.containsKey(names[j])) { 5494 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5495 final String otherPackageName = 5496 ((other != null && other.getComponentName() != null) ? 5497 other.getComponentName().getPackageName() : "?"); 5498 throw new PackageManagerException( 5499 INSTALL_FAILED_CONFLICTING_PROVIDER, 5500 "Can't install because provider name " + names[j] 5501 + " (in package " + pkg.applicationInfo.packageName 5502 + ") is already used by " + otherPackageName); 5503 } 5504 } 5505 } 5506 } 5507 } 5508 5509 if (pkg.mAdoptPermissions != null) { 5510 // This package wants to adopt ownership of permissions from 5511 // another package. 5512 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5513 final String origName = pkg.mAdoptPermissions.get(i); 5514 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5515 if (orig != null) { 5516 if (verifyPackageUpdateLPr(orig, pkg)) { 5517 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5518 + pkg.packageName); 5519 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5520 } 5521 } 5522 } 5523 } 5524 } 5525 5526 final String pkgName = pkg.packageName; 5527 5528 final long scanFileTime = scanFile.lastModified(); 5529 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5530 pkg.applicationInfo.processName = fixProcessName( 5531 pkg.applicationInfo.packageName, 5532 pkg.applicationInfo.processName, 5533 pkg.applicationInfo.uid); 5534 5535 File dataPath; 5536 if (mPlatformPackage == pkg) { 5537 // The system package is special. 5538 dataPath = new File(Environment.getDataDirectory(), "system"); 5539 5540 pkg.applicationInfo.dataDir = dataPath.getPath(); 5541 5542 } else { 5543 // This is a normal package, need to make its data directory. 5544 dataPath = getDataPathForPackage(pkg.packageName, 0); 5545 5546 boolean uidError = false; 5547 if (dataPath.exists()) { 5548 int currentUid = 0; 5549 try { 5550 StructStat stat = Os.stat(dataPath.getPath()); 5551 currentUid = stat.st_uid; 5552 } catch (ErrnoException e) { 5553 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5554 } 5555 5556 // If we have mismatched owners for the data path, we have a problem. 5557 if (currentUid != pkg.applicationInfo.uid) { 5558 boolean recovered = false; 5559 if (currentUid == 0) { 5560 // The directory somehow became owned by root. Wow. 5561 // This is probably because the system was stopped while 5562 // installd was in the middle of messing with its libs 5563 // directory. Ask installd to fix that. 5564 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5565 pkg.applicationInfo.uid); 5566 if (ret >= 0) { 5567 recovered = true; 5568 String msg = "Package " + pkg.packageName 5569 + " unexpectedly changed to uid 0; recovered to " + 5570 + pkg.applicationInfo.uid; 5571 reportSettingsProblem(Log.WARN, msg); 5572 } 5573 } 5574 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5575 || (scanFlags&SCAN_BOOTING) != 0)) { 5576 // If this is a system app, we can at least delete its 5577 // current data so the application will still work. 5578 int ret = removeDataDirsLI(pkgName); 5579 if (ret >= 0) { 5580 // TODO: Kill the processes first 5581 // Old data gone! 5582 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5583 ? "System package " : "Third party package "; 5584 String msg = prefix + pkg.packageName 5585 + " has changed from uid: " 5586 + currentUid + " to " 5587 + pkg.applicationInfo.uid + "; old data erased"; 5588 reportSettingsProblem(Log.WARN, msg); 5589 recovered = true; 5590 5591 // And now re-install the app. 5592 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5593 pkg.applicationInfo.seinfo); 5594 if (ret == -1) { 5595 // Ack should not happen! 5596 msg = prefix + pkg.packageName 5597 + " could not have data directory re-created after delete."; 5598 reportSettingsProblem(Log.WARN, msg); 5599 throw new PackageManagerException( 5600 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5601 } 5602 } 5603 if (!recovered) { 5604 mHasSystemUidErrors = true; 5605 } 5606 } else if (!recovered) { 5607 // If we allow this install to proceed, we will be broken. 5608 // Abort, abort! 5609 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5610 "scanPackageLI"); 5611 } 5612 if (!recovered) { 5613 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5614 + pkg.applicationInfo.uid + "/fs_" 5615 + currentUid; 5616 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5617 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5618 String msg = "Package " + pkg.packageName 5619 + " has mismatched uid: " 5620 + currentUid + " on disk, " 5621 + pkg.applicationInfo.uid + " in settings"; 5622 // writer 5623 synchronized (mPackages) { 5624 mSettings.mReadMessages.append(msg); 5625 mSettings.mReadMessages.append('\n'); 5626 uidError = true; 5627 if (!pkgSetting.uidError) { 5628 reportSettingsProblem(Log.ERROR, msg); 5629 } 5630 } 5631 } 5632 } 5633 pkg.applicationInfo.dataDir = dataPath.getPath(); 5634 if (mShouldRestoreconData) { 5635 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5636 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5637 pkg.applicationInfo.uid); 5638 } 5639 } else { 5640 if (DEBUG_PACKAGE_SCANNING) { 5641 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5642 Log.v(TAG, "Want this data dir: " + dataPath); 5643 } 5644 //invoke installer to do the actual installation 5645 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5646 pkg.applicationInfo.seinfo); 5647 if (ret < 0) { 5648 // Error from installer 5649 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5650 "Unable to create data dirs [errorCode=" + ret + "]"); 5651 } 5652 5653 if (dataPath.exists()) { 5654 pkg.applicationInfo.dataDir = dataPath.getPath(); 5655 } else { 5656 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5657 pkg.applicationInfo.dataDir = null; 5658 } 5659 } 5660 5661 pkgSetting.uidError = uidError; 5662 } 5663 5664 final String path = scanFile.getPath(); 5665 final String codePath = pkg.applicationInfo.getCodePath(); 5666 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5667 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5668 setBundledAppAbisAndRoots(pkg, pkgSetting); 5669 5670 // If we haven't found any native libraries for the app, check if it has 5671 // renderscript code. We'll need to force the app to 32 bit if it has 5672 // renderscript bitcode. 5673 if (pkg.applicationInfo.primaryCpuAbi == null 5674 && pkg.applicationInfo.secondaryCpuAbi == null 5675 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5676 NativeLibraryHelper.Handle handle = null; 5677 try { 5678 handle = NativeLibraryHelper.Handle.create(scanFile); 5679 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5680 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5681 } 5682 } catch (IOException ioe) { 5683 Slog.w(TAG, "Error scanning system app : " + ioe); 5684 } finally { 5685 IoUtils.closeQuietly(handle); 5686 } 5687 } 5688 5689 setNativeLibraryPaths(pkg); 5690 } else { 5691 // TODO: We can probably be smarter about this stuff. For installed apps, 5692 // we can calculate this information at install time once and for all. For 5693 // system apps, we can probably assume that this information doesn't change 5694 // after the first boot scan. As things stand, we do lots of unnecessary work. 5695 5696 // Give ourselves some initial paths; we'll come back for another 5697 // pass once we've determined ABI below. 5698 setNativeLibraryPaths(pkg); 5699 5700 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5701 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5702 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5703 5704 NativeLibraryHelper.Handle handle = null; 5705 try { 5706 handle = NativeLibraryHelper.Handle.create(scanFile); 5707 // TODO(multiArch): This can be null for apps that didn't go through the 5708 // usual installation process. We can calculate it again, like we 5709 // do during install time. 5710 // 5711 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5712 // unnecessary. 5713 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5714 5715 // Null out the abis so that they can be recalculated. 5716 pkg.applicationInfo.primaryCpuAbi = null; 5717 pkg.applicationInfo.secondaryCpuAbi = null; 5718 if (isMultiArch(pkg.applicationInfo)) { 5719 // Warn if we've set an abiOverride for multi-lib packages.. 5720 // By definition, we need to copy both 32 and 64 bit libraries for 5721 // such packages. 5722 if (pkg.cpuAbiOverride != null 5723 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5724 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5725 } 5726 5727 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5728 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5729 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5730 if (isAsec) { 5731 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5732 } else { 5733 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5734 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5735 useIsaSpecificSubdirs); 5736 } 5737 } 5738 5739 maybeThrowExceptionForMultiArchCopy( 5740 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5741 5742 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5743 if (isAsec) { 5744 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5745 } else { 5746 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5747 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5748 useIsaSpecificSubdirs); 5749 } 5750 } 5751 5752 maybeThrowExceptionForMultiArchCopy( 5753 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5754 5755 if (abi64 >= 0) { 5756 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5757 } 5758 5759 if (abi32 >= 0) { 5760 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5761 if (abi64 >= 0) { 5762 pkg.applicationInfo.secondaryCpuAbi = abi; 5763 } else { 5764 pkg.applicationInfo.primaryCpuAbi = abi; 5765 } 5766 } 5767 } else { 5768 String[] abiList = (cpuAbiOverride != null) ? 5769 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5770 5771 // Enable gross and lame hacks for apps that are built with old 5772 // SDK tools. We must scan their APKs for renderscript bitcode and 5773 // not launch them if it's present. Don't bother checking on devices 5774 // that don't have 64 bit support. 5775 boolean needsRenderScriptOverride = false; 5776 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5777 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5778 abiList = Build.SUPPORTED_32_BIT_ABIS; 5779 needsRenderScriptOverride = true; 5780 } 5781 5782 final int copyRet; 5783 if (isAsec) { 5784 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5785 } else { 5786 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5787 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5788 } 5789 5790 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5791 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5792 "Error unpackaging native libs for app, errorCode=" + copyRet); 5793 } 5794 5795 if (copyRet >= 0) { 5796 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5797 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5798 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5799 } else if (needsRenderScriptOverride) { 5800 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5801 } 5802 } 5803 } catch (IOException ioe) { 5804 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5805 } finally { 5806 IoUtils.closeQuietly(handle); 5807 } 5808 5809 // Now that we've calculated the ABIs and determined if it's an internal app, 5810 // we will go ahead and populate the nativeLibraryPath. 5811 setNativeLibraryPaths(pkg); 5812 5813 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5814 final int[] userIds = sUserManager.getUserIds(); 5815 synchronized (mInstallLock) { 5816 // Create a native library symlink only if we have native libraries 5817 // and if the native libraries are 32 bit libraries. We do not provide 5818 // this symlink for 64 bit libraries. 5819 if (pkg.applicationInfo.primaryCpuAbi != null && 5820 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5821 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5822 for (int userId : userIds) { 5823 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5824 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5825 "Failed linking native library dir (user=" + userId + ")"); 5826 } 5827 } 5828 } 5829 } 5830 } 5831 5832 // This is a special case for the "system" package, where the ABI is 5833 // dictated by the zygote configuration (and init.rc). We should keep track 5834 // of this ABI so that we can deal with "normal" applications that run under 5835 // the same UID correctly. 5836 if (mPlatformPackage == pkg) { 5837 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5838 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5839 } 5840 5841 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5842 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5843 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5844 // Copy the derived override back to the parsed package, so that we can 5845 // update the package settings accordingly. 5846 pkg.cpuAbiOverride = cpuAbiOverride; 5847 5848 if (DEBUG_ABI_SELECTION) { 5849 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5850 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5851 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5852 } 5853 5854 // Push the derived path down into PackageSettings so we know what to 5855 // clean up at uninstall time. 5856 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5857 5858 if (DEBUG_ABI_SELECTION) { 5859 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5860 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5861 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5862 } 5863 5864 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5865 // We don't do this here during boot because we can do it all 5866 // at once after scanning all existing packages. 5867 // 5868 // We also do this *before* we perform dexopt on this package, so that 5869 // we can avoid redundant dexopts, and also to make sure we've got the 5870 // code and package path correct. 5871 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5872 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5873 } 5874 5875 if ((scanFlags & SCAN_NO_DEX) == 0) { 5876 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5877 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5878 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5879 } 5880 } 5881 5882 if (mFactoryTest && pkg.requestedPermissions.contains( 5883 android.Manifest.permission.FACTORY_TEST)) { 5884 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5885 } 5886 5887 ArrayList<PackageParser.Package> clientLibPkgs = null; 5888 5889 // writer 5890 synchronized (mPackages) { 5891 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5892 // Only system apps can add new shared libraries. 5893 if (pkg.libraryNames != null) { 5894 for (int i=0; i<pkg.libraryNames.size(); i++) { 5895 String name = pkg.libraryNames.get(i); 5896 boolean allowed = false; 5897 if (isUpdatedSystemApp(pkg)) { 5898 // New library entries can only be added through the 5899 // system image. This is important to get rid of a lot 5900 // of nasty edge cases: for example if we allowed a non- 5901 // system update of the app to add a library, then uninstalling 5902 // the update would make the library go away, and assumptions 5903 // we made such as through app install filtering would now 5904 // have allowed apps on the device which aren't compatible 5905 // with it. Better to just have the restriction here, be 5906 // conservative, and create many fewer cases that can negatively 5907 // impact the user experience. 5908 final PackageSetting sysPs = mSettings 5909 .getDisabledSystemPkgLPr(pkg.packageName); 5910 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5911 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5912 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5913 allowed = true; 5914 allowed = true; 5915 break; 5916 } 5917 } 5918 } 5919 } else { 5920 allowed = true; 5921 } 5922 if (allowed) { 5923 if (!mSharedLibraries.containsKey(name)) { 5924 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5925 } else if (!name.equals(pkg.packageName)) { 5926 Slog.w(TAG, "Package " + pkg.packageName + " library " 5927 + name + " already exists; skipping"); 5928 } 5929 } else { 5930 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5931 + name + " that is not declared on system image; skipping"); 5932 } 5933 } 5934 if ((scanFlags&SCAN_BOOTING) == 0) { 5935 // If we are not booting, we need to update any applications 5936 // that are clients of our shared library. If we are booting, 5937 // this will all be done once the scan is complete. 5938 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5939 } 5940 } 5941 } 5942 } 5943 5944 // We also need to dexopt any apps that are dependent on this library. Note that 5945 // if these fail, we should abort the install since installing the library will 5946 // result in some apps being broken. 5947 if (clientLibPkgs != null) { 5948 if ((scanFlags & SCAN_NO_DEX) == 0) { 5949 for (int i = 0; i < clientLibPkgs.size(); i++) { 5950 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5951 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5952 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5953 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5954 "scanPackageLI failed to dexopt clientLibPkgs"); 5955 } 5956 } 5957 } 5958 } 5959 5960 // Request the ActivityManager to kill the process(only for existing packages) 5961 // so that we do not end up in a confused state while the user is still using the older 5962 // version of the application while the new one gets installed. 5963 if ((scanFlags & SCAN_REPLACING) != 0) { 5964 killApplication(pkg.applicationInfo.packageName, 5965 pkg.applicationInfo.uid, "update pkg"); 5966 } 5967 5968 // Also need to kill any apps that are dependent on the library. 5969 if (clientLibPkgs != null) { 5970 for (int i=0; i<clientLibPkgs.size(); i++) { 5971 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5972 killApplication(clientPkg.applicationInfo.packageName, 5973 clientPkg.applicationInfo.uid, "update lib"); 5974 } 5975 } 5976 5977 // writer 5978 synchronized (mPackages) { 5979 // We don't expect installation to fail beyond this point 5980 5981 // Add the new setting to mSettings 5982 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5983 // Add the new setting to mPackages 5984 mPackages.put(pkg.applicationInfo.packageName, pkg); 5985 // Make sure we don't accidentally delete its data. 5986 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5987 while (iter.hasNext()) { 5988 PackageCleanItem item = iter.next(); 5989 if (pkgName.equals(item.packageName)) { 5990 iter.remove(); 5991 } 5992 } 5993 5994 // Take care of first install / last update times. 5995 if (currentTime != 0) { 5996 if (pkgSetting.firstInstallTime == 0) { 5997 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5998 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5999 pkgSetting.lastUpdateTime = currentTime; 6000 } 6001 } else if (pkgSetting.firstInstallTime == 0) { 6002 // We need *something*. Take time time stamp of the file. 6003 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6004 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6005 if (scanFileTime != pkgSetting.timeStamp) { 6006 // A package on the system image has changed; consider this 6007 // to be an update. 6008 pkgSetting.lastUpdateTime = scanFileTime; 6009 } 6010 } 6011 6012 // Add the package's KeySets to the global KeySetManagerService 6013 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6014 try { 6015 // Old KeySetData no longer valid. 6016 ksms.removeAppKeySetDataLPw(pkg.packageName); 6017 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6018 if (pkg.mKeySetMapping != null) { 6019 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6020 pkg.mKeySetMapping.entrySet()) { 6021 if (entry.getValue() != null) { 6022 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6023 entry.getValue(), entry.getKey()); 6024 } 6025 } 6026 if (pkg.mUpgradeKeySets != null) { 6027 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6028 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6029 } 6030 } 6031 } 6032 } catch (NullPointerException e) { 6033 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6034 } catch (IllegalArgumentException e) { 6035 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6036 } 6037 6038 int N = pkg.providers.size(); 6039 StringBuilder r = null; 6040 int i; 6041 for (i=0; i<N; i++) { 6042 PackageParser.Provider p = pkg.providers.get(i); 6043 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6044 p.info.processName, pkg.applicationInfo.uid); 6045 mProviders.addProvider(p); 6046 p.syncable = p.info.isSyncable; 6047 if (p.info.authority != null) { 6048 String names[] = p.info.authority.split(";"); 6049 p.info.authority = null; 6050 for (int j = 0; j < names.length; j++) { 6051 if (j == 1 && p.syncable) { 6052 // We only want the first authority for a provider to possibly be 6053 // syncable, so if we already added this provider using a different 6054 // authority clear the syncable flag. We copy the provider before 6055 // changing it because the mProviders object contains a reference 6056 // to a provider that we don't want to change. 6057 // Only do this for the second authority since the resulting provider 6058 // object can be the same for all future authorities for this provider. 6059 p = new PackageParser.Provider(p); 6060 p.syncable = false; 6061 } 6062 if (!mProvidersByAuthority.containsKey(names[j])) { 6063 mProvidersByAuthority.put(names[j], p); 6064 if (p.info.authority == null) { 6065 p.info.authority = names[j]; 6066 } else { 6067 p.info.authority = p.info.authority + ";" + names[j]; 6068 } 6069 if (DEBUG_PACKAGE_SCANNING) { 6070 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6071 Log.d(TAG, "Registered content provider: " + names[j] 6072 + ", className = " + p.info.name + ", isSyncable = " 6073 + p.info.isSyncable); 6074 } 6075 } else { 6076 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6077 Slog.w(TAG, "Skipping provider name " + names[j] + 6078 " (in package " + pkg.applicationInfo.packageName + 6079 "): name already used by " 6080 + ((other != null && other.getComponentName() != null) 6081 ? other.getComponentName().getPackageName() : "?")); 6082 } 6083 } 6084 } 6085 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6086 if (r == null) { 6087 r = new StringBuilder(256); 6088 } else { 6089 r.append(' '); 6090 } 6091 r.append(p.info.name); 6092 } 6093 } 6094 if (r != null) { 6095 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6096 } 6097 6098 N = pkg.services.size(); 6099 r = null; 6100 for (i=0; i<N; i++) { 6101 PackageParser.Service s = pkg.services.get(i); 6102 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6103 s.info.processName, pkg.applicationInfo.uid); 6104 mServices.addService(s); 6105 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6106 if (r == null) { 6107 r = new StringBuilder(256); 6108 } else { 6109 r.append(' '); 6110 } 6111 r.append(s.info.name); 6112 } 6113 } 6114 if (r != null) { 6115 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6116 } 6117 6118 N = pkg.receivers.size(); 6119 r = null; 6120 for (i=0; i<N; i++) { 6121 PackageParser.Activity a = pkg.receivers.get(i); 6122 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6123 a.info.processName, pkg.applicationInfo.uid); 6124 mReceivers.addActivity(a, "receiver"); 6125 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6126 if (r == null) { 6127 r = new StringBuilder(256); 6128 } else { 6129 r.append(' '); 6130 } 6131 r.append(a.info.name); 6132 } 6133 } 6134 if (r != null) { 6135 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6136 } 6137 6138 N = pkg.activities.size(); 6139 r = null; 6140 for (i=0; i<N; i++) { 6141 PackageParser.Activity a = pkg.activities.get(i); 6142 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6143 a.info.processName, pkg.applicationInfo.uid); 6144 mActivities.addActivity(a, "activity"); 6145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6146 if (r == null) { 6147 r = new StringBuilder(256); 6148 } else { 6149 r.append(' '); 6150 } 6151 r.append(a.info.name); 6152 } 6153 } 6154 if (r != null) { 6155 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6156 } 6157 6158 N = pkg.permissionGroups.size(); 6159 r = null; 6160 for (i=0; i<N; i++) { 6161 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6162 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6163 if (cur == null) { 6164 mPermissionGroups.put(pg.info.name, pg); 6165 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6166 if (r == null) { 6167 r = new StringBuilder(256); 6168 } else { 6169 r.append(' '); 6170 } 6171 r.append(pg.info.name); 6172 } 6173 } else { 6174 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6175 + pg.info.packageName + " ignored: original from " 6176 + cur.info.packageName); 6177 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6178 if (r == null) { 6179 r = new StringBuilder(256); 6180 } else { 6181 r.append(' '); 6182 } 6183 r.append("DUP:"); 6184 r.append(pg.info.name); 6185 } 6186 } 6187 } 6188 if (r != null) { 6189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6190 } 6191 6192 N = pkg.permissions.size(); 6193 r = null; 6194 for (i=0; i<N; i++) { 6195 PackageParser.Permission p = pkg.permissions.get(i); 6196 ArrayMap<String, BasePermission> permissionMap = 6197 p.tree ? mSettings.mPermissionTrees 6198 : mSettings.mPermissions; 6199 p.group = mPermissionGroups.get(p.info.group); 6200 if (p.info.group == null || p.group != null) { 6201 BasePermission bp = permissionMap.get(p.info.name); 6202 6203 // Allow system apps to redefine non-system permissions 6204 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6205 final boolean currentOwnerIsSystem = (bp.perm != null 6206 && isSystemApp(bp.perm.owner)); 6207 if (isSystemApp(p.owner)) { 6208 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6209 // It's a built-in permission and no owner, take ownership now 6210 bp.packageSetting = pkgSetting; 6211 bp.perm = p; 6212 bp.uid = pkg.applicationInfo.uid; 6213 bp.sourcePackage = p.info.packageName; 6214 } else if (!currentOwnerIsSystem) { 6215 String msg = "New decl " + p.owner + " of permission " 6216 + p.info.name + " is system; overriding " + bp.sourcePackage; 6217 reportSettingsProblem(Log.WARN, msg); 6218 bp = null; 6219 } 6220 } 6221 } 6222 6223 if (bp == null) { 6224 bp = new BasePermission(p.info.name, p.info.packageName, 6225 BasePermission.TYPE_NORMAL); 6226 permissionMap.put(p.info.name, bp); 6227 } 6228 6229 if (bp.perm == null) { 6230 if (bp.sourcePackage == null 6231 || bp.sourcePackage.equals(p.info.packageName)) { 6232 BasePermission tree = findPermissionTreeLP(p.info.name); 6233 if (tree == null 6234 || tree.sourcePackage.equals(p.info.packageName)) { 6235 bp.packageSetting = pkgSetting; 6236 bp.perm = p; 6237 bp.uid = pkg.applicationInfo.uid; 6238 bp.sourcePackage = p.info.packageName; 6239 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6240 if (r == null) { 6241 r = new StringBuilder(256); 6242 } else { 6243 r.append(' '); 6244 } 6245 r.append(p.info.name); 6246 } 6247 } else { 6248 Slog.w(TAG, "Permission " + p.info.name + " from package " 6249 + p.info.packageName + " ignored: base tree " 6250 + tree.name + " is from package " 6251 + tree.sourcePackage); 6252 } 6253 } else { 6254 Slog.w(TAG, "Permission " + p.info.name + " from package " 6255 + p.info.packageName + " ignored: original from " 6256 + bp.sourcePackage); 6257 } 6258 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6259 if (r == null) { 6260 r = new StringBuilder(256); 6261 } else { 6262 r.append(' '); 6263 } 6264 r.append("DUP:"); 6265 r.append(p.info.name); 6266 } 6267 if (bp.perm == p) { 6268 bp.protectionLevel = p.info.protectionLevel; 6269 } 6270 } else { 6271 Slog.w(TAG, "Permission " + p.info.name + " from package " 6272 + p.info.packageName + " ignored: no group " 6273 + p.group); 6274 } 6275 } 6276 if (r != null) { 6277 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6278 } 6279 6280 N = pkg.instrumentation.size(); 6281 r = null; 6282 for (i=0; i<N; i++) { 6283 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6284 a.info.packageName = pkg.applicationInfo.packageName; 6285 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6286 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6287 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6288 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6289 a.info.dataDir = pkg.applicationInfo.dataDir; 6290 6291 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6292 // need other information about the application, like the ABI and what not ? 6293 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6294 mInstrumentation.put(a.getComponentName(), a); 6295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6296 if (r == null) { 6297 r = new StringBuilder(256); 6298 } else { 6299 r.append(' '); 6300 } 6301 r.append(a.info.name); 6302 } 6303 } 6304 if (r != null) { 6305 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6306 } 6307 6308 if (pkg.protectedBroadcasts != null) { 6309 N = pkg.protectedBroadcasts.size(); 6310 for (i=0; i<N; i++) { 6311 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6312 } 6313 } 6314 6315 pkgSetting.setTimeStamp(scanFileTime); 6316 6317 // Create idmap files for pairs of (packages, overlay packages). 6318 // Note: "android", ie framework-res.apk, is handled by native layers. 6319 if (pkg.mOverlayTarget != null) { 6320 // This is an overlay package. 6321 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6322 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6323 mOverlays.put(pkg.mOverlayTarget, 6324 new ArrayMap<String, PackageParser.Package>()); 6325 } 6326 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6327 map.put(pkg.packageName, pkg); 6328 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6329 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6330 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6331 "scanPackageLI failed to createIdmap"); 6332 } 6333 } 6334 } else if (mOverlays.containsKey(pkg.packageName) && 6335 !pkg.packageName.equals("android")) { 6336 // This is a regular package, with one or more known overlay packages. 6337 createIdmapsForPackageLI(pkg); 6338 } 6339 } 6340 6341 return pkg; 6342 } 6343 6344 /** 6345 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6346 * i.e, so that all packages can be run inside a single process if required. 6347 * 6348 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6349 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6350 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6351 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6352 * updating a package that belongs to a shared user. 6353 * 6354 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6355 * adds unnecessary complexity. 6356 */ 6357 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6358 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6359 String requiredInstructionSet = null; 6360 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6361 requiredInstructionSet = VMRuntime.getInstructionSet( 6362 scannedPackage.applicationInfo.primaryCpuAbi); 6363 } 6364 6365 PackageSetting requirer = null; 6366 for (PackageSetting ps : packagesForUser) { 6367 // If packagesForUser contains scannedPackage, we skip it. This will happen 6368 // when scannedPackage is an update of an existing package. Without this check, 6369 // we will never be able to change the ABI of any package belonging to a shared 6370 // user, even if it's compatible with other packages. 6371 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6372 if (ps.primaryCpuAbiString == null) { 6373 continue; 6374 } 6375 6376 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6377 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6378 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6379 // this but there's not much we can do. 6380 String errorMessage = "Instruction set mismatch, " 6381 + ((requirer == null) ? "[caller]" : requirer) 6382 + " requires " + requiredInstructionSet + " whereas " + ps 6383 + " requires " + instructionSet; 6384 Slog.w(TAG, errorMessage); 6385 } 6386 6387 if (requiredInstructionSet == null) { 6388 requiredInstructionSet = instructionSet; 6389 requirer = ps; 6390 } 6391 } 6392 } 6393 6394 if (requiredInstructionSet != null) { 6395 String adjustedAbi; 6396 if (requirer != null) { 6397 // requirer != null implies that either scannedPackage was null or that scannedPackage 6398 // did not require an ABI, in which case we have to adjust scannedPackage to match 6399 // the ABI of the set (which is the same as requirer's ABI) 6400 adjustedAbi = requirer.primaryCpuAbiString; 6401 if (scannedPackage != null) { 6402 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6403 } 6404 } else { 6405 // requirer == null implies that we're updating all ABIs in the set to 6406 // match scannedPackage. 6407 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6408 } 6409 6410 for (PackageSetting ps : packagesForUser) { 6411 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6412 if (ps.primaryCpuAbiString != null) { 6413 continue; 6414 } 6415 6416 ps.primaryCpuAbiString = adjustedAbi; 6417 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6418 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6419 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6420 6421 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6422 deferDexOpt, true) == DEX_OPT_FAILED) { 6423 ps.primaryCpuAbiString = null; 6424 ps.pkg.applicationInfo.primaryCpuAbi = null; 6425 return; 6426 } else { 6427 mInstaller.rmdex(ps.codePathString, 6428 getDexCodeInstructionSet(getPreferredInstructionSet())); 6429 } 6430 } 6431 } 6432 } 6433 } 6434 } 6435 6436 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6437 synchronized (mPackages) { 6438 mResolverReplaced = true; 6439 // Set up information for custom user intent resolution activity. 6440 mResolveActivity.applicationInfo = pkg.applicationInfo; 6441 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6442 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6443 mResolveActivity.processName = pkg.applicationInfo.packageName; 6444 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6445 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6446 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6447 mResolveActivity.theme = 0; 6448 mResolveActivity.exported = true; 6449 mResolveActivity.enabled = true; 6450 mResolveInfo.activityInfo = mResolveActivity; 6451 mResolveInfo.priority = 0; 6452 mResolveInfo.preferredOrder = 0; 6453 mResolveInfo.match = 0; 6454 mResolveComponentName = mCustomResolverComponentName; 6455 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6456 mResolveComponentName); 6457 } 6458 } 6459 6460 private static String calculateBundledApkRoot(final String codePathString) { 6461 final File codePath = new File(codePathString); 6462 final File codeRoot; 6463 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6464 codeRoot = Environment.getRootDirectory(); 6465 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6466 codeRoot = Environment.getOemDirectory(); 6467 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6468 codeRoot = Environment.getVendorDirectory(); 6469 } else { 6470 // Unrecognized code path; take its top real segment as the apk root: 6471 // e.g. /something/app/blah.apk => /something 6472 try { 6473 File f = codePath.getCanonicalFile(); 6474 File parent = f.getParentFile(); // non-null because codePath is a file 6475 File tmp; 6476 while ((tmp = parent.getParentFile()) != null) { 6477 f = parent; 6478 parent = tmp; 6479 } 6480 codeRoot = f; 6481 Slog.w(TAG, "Unrecognized code path " 6482 + codePath + " - using " + codeRoot); 6483 } catch (IOException e) { 6484 // Can't canonicalize the code path -- shenanigans? 6485 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6486 return Environment.getRootDirectory().getPath(); 6487 } 6488 } 6489 return codeRoot.getPath(); 6490 } 6491 6492 /** 6493 * Derive and set the location of native libraries for the given package, 6494 * which varies depending on where and how the package was installed. 6495 */ 6496 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6497 final ApplicationInfo info = pkg.applicationInfo; 6498 final String codePath = pkg.codePath; 6499 final File codeFile = new File(codePath); 6500 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6501 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6502 6503 info.nativeLibraryRootDir = null; 6504 info.nativeLibraryRootRequiresIsa = false; 6505 info.nativeLibraryDir = null; 6506 info.secondaryNativeLibraryDir = null; 6507 6508 if (isApkFile(codeFile)) { 6509 // Monolithic install 6510 if (bundledApp) { 6511 // If "/system/lib64/apkname" exists, assume that is the per-package 6512 // native library directory to use; otherwise use "/system/lib/apkname". 6513 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6514 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6515 getPrimaryInstructionSet(info)); 6516 6517 // This is a bundled system app so choose the path based on the ABI. 6518 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6519 // is just the default path. 6520 final String apkName = deriveCodePathName(codePath); 6521 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6522 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6523 apkName).getAbsolutePath(); 6524 6525 if (info.secondaryCpuAbi != null) { 6526 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6527 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6528 secondaryLibDir, apkName).getAbsolutePath(); 6529 } 6530 } else if (asecApp) { 6531 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6532 .getAbsolutePath(); 6533 } else { 6534 final String apkName = deriveCodePathName(codePath); 6535 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6536 .getAbsolutePath(); 6537 } 6538 6539 info.nativeLibraryRootRequiresIsa = false; 6540 info.nativeLibraryDir = info.nativeLibraryRootDir; 6541 } else { 6542 // Cluster install 6543 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6544 info.nativeLibraryRootRequiresIsa = true; 6545 6546 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6547 getPrimaryInstructionSet(info)).getAbsolutePath(); 6548 6549 if (info.secondaryCpuAbi != null) { 6550 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6551 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6552 } 6553 } 6554 } 6555 6556 /** 6557 * Calculate the abis and roots for a bundled app. These can uniquely 6558 * be determined from the contents of the system partition, i.e whether 6559 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6560 * of this information, and instead assume that the system was built 6561 * sensibly. 6562 */ 6563 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6564 PackageSetting pkgSetting) { 6565 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6566 6567 // If "/system/lib64/apkname" exists, assume that is the per-package 6568 // native library directory to use; otherwise use "/system/lib/apkname". 6569 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6570 setBundledAppAbi(pkg, apkRoot, apkName); 6571 // pkgSetting might be null during rescan following uninstall of updates 6572 // to a bundled app, so accommodate that possibility. The settings in 6573 // that case will be established later from the parsed package. 6574 // 6575 // If the settings aren't null, sync them up with what we've just derived. 6576 // note that apkRoot isn't stored in the package settings. 6577 if (pkgSetting != null) { 6578 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6579 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6580 } 6581 } 6582 6583 /** 6584 * Deduces the ABI of a bundled app and sets the relevant fields on the 6585 * parsed pkg object. 6586 * 6587 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6588 * under which system libraries are installed. 6589 * @param apkName the name of the installed package. 6590 */ 6591 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6592 final File codeFile = new File(pkg.codePath); 6593 6594 final boolean has64BitLibs; 6595 final boolean has32BitLibs; 6596 if (isApkFile(codeFile)) { 6597 // Monolithic install 6598 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6599 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6600 } else { 6601 // Cluster install 6602 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6603 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6604 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6605 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6606 has64BitLibs = (new File(rootDir, isa)).exists(); 6607 } else { 6608 has64BitLibs = false; 6609 } 6610 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6611 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6612 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6613 has32BitLibs = (new File(rootDir, isa)).exists(); 6614 } else { 6615 has32BitLibs = false; 6616 } 6617 } 6618 6619 if (has64BitLibs && !has32BitLibs) { 6620 // The package has 64 bit libs, but not 32 bit libs. Its primary 6621 // ABI should be 64 bit. We can safely assume here that the bundled 6622 // native libraries correspond to the most preferred ABI in the list. 6623 6624 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6625 pkg.applicationInfo.secondaryCpuAbi = null; 6626 } else if (has32BitLibs && !has64BitLibs) { 6627 // The package has 32 bit libs but not 64 bit libs. Its primary 6628 // ABI should be 32 bit. 6629 6630 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6631 pkg.applicationInfo.secondaryCpuAbi = null; 6632 } else if (has32BitLibs && has64BitLibs) { 6633 // The application has both 64 and 32 bit bundled libraries. We check 6634 // here that the app declares multiArch support, and warn if it doesn't. 6635 // 6636 // We will be lenient here and record both ABIs. The primary will be the 6637 // ABI that's higher on the list, i.e, a device that's configured to prefer 6638 // 64 bit apps will see a 64 bit primary ABI, 6639 6640 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6641 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6642 } 6643 6644 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6645 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6646 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6647 } else { 6648 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6649 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6650 } 6651 } else { 6652 pkg.applicationInfo.primaryCpuAbi = null; 6653 pkg.applicationInfo.secondaryCpuAbi = null; 6654 } 6655 } 6656 6657 private void killApplication(String pkgName, int appId, String reason) { 6658 // Request the ActivityManager to kill the process(only for existing packages) 6659 // so that we do not end up in a confused state while the user is still using the older 6660 // version of the application while the new one gets installed. 6661 IActivityManager am = ActivityManagerNative.getDefault(); 6662 if (am != null) { 6663 try { 6664 am.killApplicationWithAppId(pkgName, appId, reason); 6665 } catch (RemoteException e) { 6666 } 6667 } 6668 } 6669 6670 void removePackageLI(PackageSetting ps, boolean chatty) { 6671 if (DEBUG_INSTALL) { 6672 if (chatty) 6673 Log.d(TAG, "Removing package " + ps.name); 6674 } 6675 6676 // writer 6677 synchronized (mPackages) { 6678 mPackages.remove(ps.name); 6679 final PackageParser.Package pkg = ps.pkg; 6680 if (pkg != null) { 6681 cleanPackageDataStructuresLILPw(pkg, chatty); 6682 } 6683 } 6684 } 6685 6686 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6687 if (DEBUG_INSTALL) { 6688 if (chatty) 6689 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6690 } 6691 6692 // writer 6693 synchronized (mPackages) { 6694 mPackages.remove(pkg.applicationInfo.packageName); 6695 cleanPackageDataStructuresLILPw(pkg, chatty); 6696 } 6697 } 6698 6699 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6700 int N = pkg.providers.size(); 6701 StringBuilder r = null; 6702 int i; 6703 for (i=0; i<N; i++) { 6704 PackageParser.Provider p = pkg.providers.get(i); 6705 mProviders.removeProvider(p); 6706 if (p.info.authority == null) { 6707 6708 /* There was another ContentProvider with this authority when 6709 * this app was installed so this authority is null, 6710 * Ignore it as we don't have to unregister the provider. 6711 */ 6712 continue; 6713 } 6714 String names[] = p.info.authority.split(";"); 6715 for (int j = 0; j < names.length; j++) { 6716 if (mProvidersByAuthority.get(names[j]) == p) { 6717 mProvidersByAuthority.remove(names[j]); 6718 if (DEBUG_REMOVE) { 6719 if (chatty) 6720 Log.d(TAG, "Unregistered content provider: " + names[j] 6721 + ", className = " + p.info.name + ", isSyncable = " 6722 + p.info.isSyncable); 6723 } 6724 } 6725 } 6726 if (DEBUG_REMOVE && chatty) { 6727 if (r == null) { 6728 r = new StringBuilder(256); 6729 } else { 6730 r.append(' '); 6731 } 6732 r.append(p.info.name); 6733 } 6734 } 6735 if (r != null) { 6736 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6737 } 6738 6739 N = pkg.services.size(); 6740 r = null; 6741 for (i=0; i<N; i++) { 6742 PackageParser.Service s = pkg.services.get(i); 6743 mServices.removeService(s); 6744 if (chatty) { 6745 if (r == null) { 6746 r = new StringBuilder(256); 6747 } else { 6748 r.append(' '); 6749 } 6750 r.append(s.info.name); 6751 } 6752 } 6753 if (r != null) { 6754 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6755 } 6756 6757 N = pkg.receivers.size(); 6758 r = null; 6759 for (i=0; i<N; i++) { 6760 PackageParser.Activity a = pkg.receivers.get(i); 6761 mReceivers.removeActivity(a, "receiver"); 6762 if (DEBUG_REMOVE && chatty) { 6763 if (r == null) { 6764 r = new StringBuilder(256); 6765 } else { 6766 r.append(' '); 6767 } 6768 r.append(a.info.name); 6769 } 6770 } 6771 if (r != null) { 6772 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6773 } 6774 6775 N = pkg.activities.size(); 6776 r = null; 6777 for (i=0; i<N; i++) { 6778 PackageParser.Activity a = pkg.activities.get(i); 6779 mActivities.removeActivity(a, "activity"); 6780 if (DEBUG_REMOVE && chatty) { 6781 if (r == null) { 6782 r = new StringBuilder(256); 6783 } else { 6784 r.append(' '); 6785 } 6786 r.append(a.info.name); 6787 } 6788 } 6789 if (r != null) { 6790 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6791 } 6792 6793 N = pkg.permissions.size(); 6794 r = null; 6795 for (i=0; i<N; i++) { 6796 PackageParser.Permission p = pkg.permissions.get(i); 6797 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6798 if (bp == null) { 6799 bp = mSettings.mPermissionTrees.get(p.info.name); 6800 } 6801 if (bp != null && bp.perm == p) { 6802 bp.perm = null; 6803 if (DEBUG_REMOVE && chatty) { 6804 if (r == null) { 6805 r = new StringBuilder(256); 6806 } else { 6807 r.append(' '); 6808 } 6809 r.append(p.info.name); 6810 } 6811 } 6812 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6813 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6814 if (appOpPerms != null) { 6815 appOpPerms.remove(pkg.packageName); 6816 } 6817 } 6818 } 6819 if (r != null) { 6820 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6821 } 6822 6823 N = pkg.requestedPermissions.size(); 6824 r = null; 6825 for (i=0; i<N; i++) { 6826 String perm = pkg.requestedPermissions.get(i); 6827 BasePermission bp = mSettings.mPermissions.get(perm); 6828 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6829 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6830 if (appOpPerms != null) { 6831 appOpPerms.remove(pkg.packageName); 6832 if (appOpPerms.isEmpty()) { 6833 mAppOpPermissionPackages.remove(perm); 6834 } 6835 } 6836 } 6837 } 6838 if (r != null) { 6839 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6840 } 6841 6842 N = pkg.instrumentation.size(); 6843 r = null; 6844 for (i=0; i<N; i++) { 6845 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6846 mInstrumentation.remove(a.getComponentName()); 6847 if (DEBUG_REMOVE && chatty) { 6848 if (r == null) { 6849 r = new StringBuilder(256); 6850 } else { 6851 r.append(' '); 6852 } 6853 r.append(a.info.name); 6854 } 6855 } 6856 if (r != null) { 6857 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6858 } 6859 6860 r = null; 6861 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6862 // Only system apps can hold shared libraries. 6863 if (pkg.libraryNames != null) { 6864 for (i=0; i<pkg.libraryNames.size(); i++) { 6865 String name = pkg.libraryNames.get(i); 6866 SharedLibraryEntry cur = mSharedLibraries.get(name); 6867 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6868 mSharedLibraries.remove(name); 6869 if (DEBUG_REMOVE && chatty) { 6870 if (r == null) { 6871 r = new StringBuilder(256); 6872 } else { 6873 r.append(' '); 6874 } 6875 r.append(name); 6876 } 6877 } 6878 } 6879 } 6880 } 6881 if (r != null) { 6882 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6883 } 6884 } 6885 6886 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6887 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6888 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6889 return true; 6890 } 6891 } 6892 return false; 6893 } 6894 6895 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6896 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6897 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6898 6899 private void updatePermissionsLPw(String changingPkg, 6900 PackageParser.Package pkgInfo, int flags) { 6901 // Make sure there are no dangling permission trees. 6902 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6903 while (it.hasNext()) { 6904 final BasePermission bp = it.next(); 6905 if (bp.packageSetting == null) { 6906 // We may not yet have parsed the package, so just see if 6907 // we still know about its settings. 6908 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6909 } 6910 if (bp.packageSetting == null) { 6911 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6912 + " from package " + bp.sourcePackage); 6913 it.remove(); 6914 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6915 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6916 Slog.i(TAG, "Removing old permission tree: " + bp.name 6917 + " from package " + bp.sourcePackage); 6918 flags |= UPDATE_PERMISSIONS_ALL; 6919 it.remove(); 6920 } 6921 } 6922 } 6923 6924 // Make sure all dynamic permissions have been assigned to a package, 6925 // and make sure there are no dangling permissions. 6926 it = mSettings.mPermissions.values().iterator(); 6927 while (it.hasNext()) { 6928 final BasePermission bp = it.next(); 6929 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6930 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6931 + bp.name + " pkg=" + bp.sourcePackage 6932 + " info=" + bp.pendingInfo); 6933 if (bp.packageSetting == null && bp.pendingInfo != null) { 6934 final BasePermission tree = findPermissionTreeLP(bp.name); 6935 if (tree != null && tree.perm != null) { 6936 bp.packageSetting = tree.packageSetting; 6937 bp.perm = new PackageParser.Permission(tree.perm.owner, 6938 new PermissionInfo(bp.pendingInfo)); 6939 bp.perm.info.packageName = tree.perm.info.packageName; 6940 bp.perm.info.name = bp.name; 6941 bp.uid = tree.uid; 6942 } 6943 } 6944 } 6945 if (bp.packageSetting == null) { 6946 // We may not yet have parsed the package, so just see if 6947 // we still know about its settings. 6948 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6949 } 6950 if (bp.packageSetting == null) { 6951 Slog.w(TAG, "Removing dangling permission: " + bp.name 6952 + " from package " + bp.sourcePackage); 6953 it.remove(); 6954 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6955 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6956 Slog.i(TAG, "Removing old permission: " + bp.name 6957 + " from package " + bp.sourcePackage); 6958 flags |= UPDATE_PERMISSIONS_ALL; 6959 it.remove(); 6960 } 6961 } 6962 } 6963 6964 // Now update the permissions for all packages, in particular 6965 // replace the granted permissions of the system packages. 6966 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6967 for (PackageParser.Package pkg : mPackages.values()) { 6968 if (pkg != pkgInfo) { 6969 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6970 changingPkg); 6971 } 6972 } 6973 } 6974 6975 if (pkgInfo != null) { 6976 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6977 } 6978 } 6979 6980 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6981 String packageOfInterest) { 6982 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6983 if (ps == null) { 6984 return; 6985 } 6986 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6987 ArraySet<String> origPermissions = gp.grantedPermissions; 6988 boolean changedPermission = false; 6989 6990 if (replace) { 6991 ps.permissionsFixed = false; 6992 if (gp == ps) { 6993 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6994 gp.grantedPermissions.clear(); 6995 gp.gids = mGlobalGids; 6996 } 6997 } 6998 6999 if (gp.gids == null) { 7000 gp.gids = mGlobalGids; 7001 } 7002 7003 final int N = pkg.requestedPermissions.size(); 7004 for (int i=0; i<N; i++) { 7005 final String name = pkg.requestedPermissions.get(i); 7006 final boolean required = pkg.requestedPermissionsRequired.get(i); 7007 final BasePermission bp = mSettings.mPermissions.get(name); 7008 if (DEBUG_INSTALL) { 7009 if (gp != ps) { 7010 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7011 } 7012 } 7013 7014 if (bp == null || bp.packageSetting == null) { 7015 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7016 Slog.w(TAG, "Unknown permission " + name 7017 + " in package " + pkg.packageName); 7018 } 7019 continue; 7020 } 7021 7022 final String perm = bp.name; 7023 boolean allowed; 7024 boolean allowedSig = false; 7025 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7026 // Keep track of app op permissions. 7027 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7028 if (pkgs == null) { 7029 pkgs = new ArraySet<>(); 7030 mAppOpPermissionPackages.put(bp.name, pkgs); 7031 } 7032 pkgs.add(pkg.packageName); 7033 } 7034 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7035 if (level == PermissionInfo.PROTECTION_NORMAL 7036 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7037 // We grant a normal or dangerous permission if any of the following 7038 // are true: 7039 // 1) The permission is required 7040 // 2) The permission is optional, but was granted in the past 7041 // 3) The permission is optional, but was requested by an 7042 // app in /system (not /data) 7043 // 7044 // Otherwise, reject the permission. 7045 allowed = (required || origPermissions.contains(perm) 7046 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7047 } else if (bp.packageSetting == null) { 7048 // This permission is invalid; skip it. 7049 allowed = false; 7050 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7051 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7052 if (allowed) { 7053 allowedSig = true; 7054 } 7055 } else { 7056 allowed = false; 7057 } 7058 if (DEBUG_INSTALL) { 7059 if (gp != ps) { 7060 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7061 } 7062 } 7063 if (allowed) { 7064 if (!isSystemApp(ps) && ps.permissionsFixed) { 7065 // If this is an existing, non-system package, then 7066 // we can't add any new permissions to it. 7067 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7068 // Except... if this is a permission that was added 7069 // to the platform (note: need to only do this when 7070 // updating the platform). 7071 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7072 } 7073 } 7074 if (allowed) { 7075 if (!gp.grantedPermissions.contains(perm)) { 7076 changedPermission = true; 7077 gp.grantedPermissions.add(perm); 7078 gp.gids = appendInts(gp.gids, bp.gids); 7079 } else if (!ps.haveGids) { 7080 gp.gids = appendInts(gp.gids, bp.gids); 7081 } 7082 } else { 7083 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7084 Slog.w(TAG, "Not granting permission " + perm 7085 + " to package " + pkg.packageName 7086 + " because it was previously installed without"); 7087 } 7088 } 7089 } else { 7090 if (gp.grantedPermissions.remove(perm)) { 7091 changedPermission = true; 7092 gp.gids = removeInts(gp.gids, bp.gids); 7093 Slog.i(TAG, "Un-granting permission " + perm 7094 + " from package " + pkg.packageName 7095 + " (protectionLevel=" + bp.protectionLevel 7096 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7097 + ")"); 7098 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7099 // Don't print warning for app op permissions, since it is fine for them 7100 // not to be granted, there is a UI for the user to decide. 7101 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7102 Slog.w(TAG, "Not granting permission " + perm 7103 + " to package " + pkg.packageName 7104 + " (protectionLevel=" + bp.protectionLevel 7105 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7106 + ")"); 7107 } 7108 } 7109 } 7110 } 7111 7112 if ((changedPermission || replace) && !ps.permissionsFixed && 7113 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7114 // This is the first that we have heard about this package, so the 7115 // permissions we have now selected are fixed until explicitly 7116 // changed. 7117 ps.permissionsFixed = true; 7118 } 7119 ps.haveGids = true; 7120 } 7121 7122 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7123 boolean allowed = false; 7124 final int NP = PackageParser.NEW_PERMISSIONS.length; 7125 for (int ip=0; ip<NP; ip++) { 7126 final PackageParser.NewPermissionInfo npi 7127 = PackageParser.NEW_PERMISSIONS[ip]; 7128 if (npi.name.equals(perm) 7129 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7130 allowed = true; 7131 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7132 + pkg.packageName); 7133 break; 7134 } 7135 } 7136 return allowed; 7137 } 7138 7139 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7140 BasePermission bp, ArraySet<String> origPermissions) { 7141 boolean allowed; 7142 allowed = (compareSignatures( 7143 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7144 == PackageManager.SIGNATURE_MATCH) 7145 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7146 == PackageManager.SIGNATURE_MATCH); 7147 if (!allowed && (bp.protectionLevel 7148 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7149 if (isSystemApp(pkg)) { 7150 // For updated system applications, a system permission 7151 // is granted only if it had been defined by the original application. 7152 if (isUpdatedSystemApp(pkg)) { 7153 final PackageSetting sysPs = mSettings 7154 .getDisabledSystemPkgLPr(pkg.packageName); 7155 final GrantedPermissions origGp = sysPs.sharedUser != null 7156 ? sysPs.sharedUser : sysPs; 7157 7158 if (origGp.grantedPermissions.contains(perm)) { 7159 // If the original was granted this permission, we take 7160 // that grant decision as read and propagate it to the 7161 // update. 7162 allowed = true; 7163 } else { 7164 // The system apk may have been updated with an older 7165 // version of the one on the data partition, but which 7166 // granted a new system permission that it didn't have 7167 // before. In this case we do want to allow the app to 7168 // now get the new permission if the ancestral apk is 7169 // privileged to get it. 7170 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7171 for (int j=0; 7172 j<sysPs.pkg.requestedPermissions.size(); j++) { 7173 if (perm.equals( 7174 sysPs.pkg.requestedPermissions.get(j))) { 7175 allowed = true; 7176 break; 7177 } 7178 } 7179 } 7180 } 7181 } else { 7182 allowed = isPrivilegedApp(pkg); 7183 } 7184 } 7185 } 7186 if (!allowed && (bp.protectionLevel 7187 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7188 // For development permissions, a development permission 7189 // is granted only if it was already granted. 7190 allowed = origPermissions.contains(perm); 7191 } 7192 return allowed; 7193 } 7194 7195 final class ActivityIntentResolver 7196 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7197 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7198 boolean defaultOnly, int userId) { 7199 if (!sUserManager.exists(userId)) return null; 7200 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7201 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7202 } 7203 7204 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7205 int userId) { 7206 if (!sUserManager.exists(userId)) return null; 7207 mFlags = flags; 7208 return super.queryIntent(intent, resolvedType, 7209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7210 } 7211 7212 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7213 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7214 if (!sUserManager.exists(userId)) return null; 7215 if (packageActivities == null) { 7216 return null; 7217 } 7218 mFlags = flags; 7219 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7220 final int N = packageActivities.size(); 7221 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7222 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7223 7224 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7225 for (int i = 0; i < N; ++i) { 7226 intentFilters = packageActivities.get(i).intents; 7227 if (intentFilters != null && intentFilters.size() > 0) { 7228 PackageParser.ActivityIntentInfo[] array = 7229 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7230 intentFilters.toArray(array); 7231 listCut.add(array); 7232 } 7233 } 7234 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7235 } 7236 7237 public final void addActivity(PackageParser.Activity a, String type) { 7238 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7239 mActivities.put(a.getComponentName(), a); 7240 if (DEBUG_SHOW_INFO) 7241 Log.v( 7242 TAG, " " + type + " " + 7243 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7244 if (DEBUG_SHOW_INFO) 7245 Log.v(TAG, " Class=" + a.info.name); 7246 final int NI = a.intents.size(); 7247 for (int j=0; j<NI; j++) { 7248 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7249 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7250 intent.setPriority(0); 7251 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7252 + a.className + " with priority > 0, forcing to 0"); 7253 } 7254 if (DEBUG_SHOW_INFO) { 7255 Log.v(TAG, " IntentFilter:"); 7256 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7257 } 7258 if (!intent.debugCheck()) { 7259 Log.w(TAG, "==> For Activity " + a.info.name); 7260 } 7261 addFilter(intent); 7262 } 7263 } 7264 7265 public final void removeActivity(PackageParser.Activity a, String type) { 7266 mActivities.remove(a.getComponentName()); 7267 if (DEBUG_SHOW_INFO) { 7268 Log.v(TAG, " " + type + " " 7269 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7270 : a.info.name) + ":"); 7271 Log.v(TAG, " Class=" + a.info.name); 7272 } 7273 final int NI = a.intents.size(); 7274 for (int j=0; j<NI; j++) { 7275 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7276 if (DEBUG_SHOW_INFO) { 7277 Log.v(TAG, " IntentFilter:"); 7278 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7279 } 7280 removeFilter(intent); 7281 } 7282 } 7283 7284 @Override 7285 protected boolean allowFilterResult( 7286 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7287 ActivityInfo filterAi = filter.activity.info; 7288 for (int i=dest.size()-1; i>=0; i--) { 7289 ActivityInfo destAi = dest.get(i).activityInfo; 7290 if (destAi.name == filterAi.name 7291 && destAi.packageName == filterAi.packageName) { 7292 return false; 7293 } 7294 } 7295 return true; 7296 } 7297 7298 @Override 7299 protected ActivityIntentInfo[] newArray(int size) { 7300 return new ActivityIntentInfo[size]; 7301 } 7302 7303 @Override 7304 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7305 if (!sUserManager.exists(userId)) return true; 7306 PackageParser.Package p = filter.activity.owner; 7307 if (p != null) { 7308 PackageSetting ps = (PackageSetting)p.mExtras; 7309 if (ps != null) { 7310 // System apps are never considered stopped for purposes of 7311 // filtering, because there may be no way for the user to 7312 // actually re-launch them. 7313 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7314 && ps.getStopped(userId); 7315 } 7316 } 7317 return false; 7318 } 7319 7320 @Override 7321 protected boolean isPackageForFilter(String packageName, 7322 PackageParser.ActivityIntentInfo info) { 7323 return packageName.equals(info.activity.owner.packageName); 7324 } 7325 7326 @Override 7327 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7328 int match, int userId) { 7329 if (!sUserManager.exists(userId)) return null; 7330 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7331 return null; 7332 } 7333 final PackageParser.Activity activity = info.activity; 7334 if (mSafeMode && (activity.info.applicationInfo.flags 7335 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7336 return null; 7337 } 7338 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7339 if (ps == null) { 7340 return null; 7341 } 7342 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7343 ps.readUserState(userId), userId); 7344 if (ai == null) { 7345 return null; 7346 } 7347 final ResolveInfo res = new ResolveInfo(); 7348 res.activityInfo = ai; 7349 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7350 res.filter = info; 7351 } 7352 res.priority = info.getPriority(); 7353 res.preferredOrder = activity.owner.mPreferredOrder; 7354 //System.out.println("Result: " + res.activityInfo.className + 7355 // " = " + res.priority); 7356 res.match = match; 7357 res.isDefault = info.hasDefault; 7358 res.labelRes = info.labelRes; 7359 res.nonLocalizedLabel = info.nonLocalizedLabel; 7360 if (userNeedsBadging(userId)) { 7361 res.noResourceId = true; 7362 } else { 7363 res.icon = info.icon; 7364 } 7365 res.system = isSystemApp(res.activityInfo.applicationInfo); 7366 return res; 7367 } 7368 7369 @Override 7370 protected void sortResults(List<ResolveInfo> results) { 7371 Collections.sort(results, mResolvePrioritySorter); 7372 } 7373 7374 @Override 7375 protected void dumpFilter(PrintWriter out, String prefix, 7376 PackageParser.ActivityIntentInfo filter) { 7377 out.print(prefix); out.print( 7378 Integer.toHexString(System.identityHashCode(filter.activity))); 7379 out.print(' '); 7380 filter.activity.printComponentShortName(out); 7381 out.print(" filter "); 7382 out.println(Integer.toHexString(System.identityHashCode(filter))); 7383 } 7384 7385 @Override 7386 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7387 return filter.activity; 7388 } 7389 7390 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7391 PackageParser.Activity activity = (PackageParser.Activity)label; 7392 out.print(prefix); out.print( 7393 Integer.toHexString(System.identityHashCode(activity))); 7394 out.print(' '); 7395 activity.printComponentShortName(out); 7396 if (count > 1) { 7397 out.print(" ("); out.print(count); out.print(" filters)"); 7398 } 7399 out.println(); 7400 } 7401 7402// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7403// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7404// final List<ResolveInfo> retList = Lists.newArrayList(); 7405// while (i.hasNext()) { 7406// final ResolveInfo resolveInfo = i.next(); 7407// if (isEnabledLP(resolveInfo.activityInfo)) { 7408// retList.add(resolveInfo); 7409// } 7410// } 7411// return retList; 7412// } 7413 7414 // Keys are String (activity class name), values are Activity. 7415 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7416 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7417 private int mFlags; 7418 } 7419 7420 private final class ServiceIntentResolver 7421 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7423 boolean defaultOnly, int userId) { 7424 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7425 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7426 } 7427 7428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7429 int userId) { 7430 if (!sUserManager.exists(userId)) return null; 7431 mFlags = flags; 7432 return super.queryIntent(intent, resolvedType, 7433 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7434 } 7435 7436 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7437 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7438 if (!sUserManager.exists(userId)) return null; 7439 if (packageServices == null) { 7440 return null; 7441 } 7442 mFlags = flags; 7443 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7444 final int N = packageServices.size(); 7445 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7446 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7447 7448 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7449 for (int i = 0; i < N; ++i) { 7450 intentFilters = packageServices.get(i).intents; 7451 if (intentFilters != null && intentFilters.size() > 0) { 7452 PackageParser.ServiceIntentInfo[] array = 7453 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7454 intentFilters.toArray(array); 7455 listCut.add(array); 7456 } 7457 } 7458 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7459 } 7460 7461 public final void addService(PackageParser.Service s) { 7462 mServices.put(s.getComponentName(), s); 7463 if (DEBUG_SHOW_INFO) { 7464 Log.v(TAG, " " 7465 + (s.info.nonLocalizedLabel != null 7466 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7467 Log.v(TAG, " Class=" + s.info.name); 7468 } 7469 final int NI = s.intents.size(); 7470 int j; 7471 for (j=0; j<NI; j++) { 7472 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7473 if (DEBUG_SHOW_INFO) { 7474 Log.v(TAG, " IntentFilter:"); 7475 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7476 } 7477 if (!intent.debugCheck()) { 7478 Log.w(TAG, "==> For Service " + s.info.name); 7479 } 7480 addFilter(intent); 7481 } 7482 } 7483 7484 public final void removeService(PackageParser.Service s) { 7485 mServices.remove(s.getComponentName()); 7486 if (DEBUG_SHOW_INFO) { 7487 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7488 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7489 Log.v(TAG, " Class=" + s.info.name); 7490 } 7491 final int NI = s.intents.size(); 7492 int j; 7493 for (j=0; j<NI; j++) { 7494 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7495 if (DEBUG_SHOW_INFO) { 7496 Log.v(TAG, " IntentFilter:"); 7497 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7498 } 7499 removeFilter(intent); 7500 } 7501 } 7502 7503 @Override 7504 protected boolean allowFilterResult( 7505 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7506 ServiceInfo filterSi = filter.service.info; 7507 for (int i=dest.size()-1; i>=0; i--) { 7508 ServiceInfo destAi = dest.get(i).serviceInfo; 7509 if (destAi.name == filterSi.name 7510 && destAi.packageName == filterSi.packageName) { 7511 return false; 7512 } 7513 } 7514 return true; 7515 } 7516 7517 @Override 7518 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7519 return new PackageParser.ServiceIntentInfo[size]; 7520 } 7521 7522 @Override 7523 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7524 if (!sUserManager.exists(userId)) return true; 7525 PackageParser.Package p = filter.service.owner; 7526 if (p != null) { 7527 PackageSetting ps = (PackageSetting)p.mExtras; 7528 if (ps != null) { 7529 // System apps are never considered stopped for purposes of 7530 // filtering, because there may be no way for the user to 7531 // actually re-launch them. 7532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7533 && ps.getStopped(userId); 7534 } 7535 } 7536 return false; 7537 } 7538 7539 @Override 7540 protected boolean isPackageForFilter(String packageName, 7541 PackageParser.ServiceIntentInfo info) { 7542 return packageName.equals(info.service.owner.packageName); 7543 } 7544 7545 @Override 7546 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7547 int match, int userId) { 7548 if (!sUserManager.exists(userId)) return null; 7549 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7550 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7551 return null; 7552 } 7553 final PackageParser.Service service = info.service; 7554 if (mSafeMode && (service.info.applicationInfo.flags 7555 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7556 return null; 7557 } 7558 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7559 if (ps == null) { 7560 return null; 7561 } 7562 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7563 ps.readUserState(userId), userId); 7564 if (si == null) { 7565 return null; 7566 } 7567 final ResolveInfo res = new ResolveInfo(); 7568 res.serviceInfo = si; 7569 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7570 res.filter = filter; 7571 } 7572 res.priority = info.getPriority(); 7573 res.preferredOrder = service.owner.mPreferredOrder; 7574 //System.out.println("Result: " + res.activityInfo.className + 7575 // " = " + res.priority); 7576 res.match = match; 7577 res.isDefault = info.hasDefault; 7578 res.labelRes = info.labelRes; 7579 res.nonLocalizedLabel = info.nonLocalizedLabel; 7580 res.icon = info.icon; 7581 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7582 return res; 7583 } 7584 7585 @Override 7586 protected void sortResults(List<ResolveInfo> results) { 7587 Collections.sort(results, mResolvePrioritySorter); 7588 } 7589 7590 @Override 7591 protected void dumpFilter(PrintWriter out, String prefix, 7592 PackageParser.ServiceIntentInfo filter) { 7593 out.print(prefix); out.print( 7594 Integer.toHexString(System.identityHashCode(filter.service))); 7595 out.print(' '); 7596 filter.service.printComponentShortName(out); 7597 out.print(" filter "); 7598 out.println(Integer.toHexString(System.identityHashCode(filter))); 7599 } 7600 7601 @Override 7602 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7603 return filter.service; 7604 } 7605 7606 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7607 PackageParser.Service service = (PackageParser.Service)label; 7608 out.print(prefix); out.print( 7609 Integer.toHexString(System.identityHashCode(service))); 7610 out.print(' '); 7611 service.printComponentShortName(out); 7612 if (count > 1) { 7613 out.print(" ("); out.print(count); out.print(" filters)"); 7614 } 7615 out.println(); 7616 } 7617 7618// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7619// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7620// final List<ResolveInfo> retList = Lists.newArrayList(); 7621// while (i.hasNext()) { 7622// final ResolveInfo resolveInfo = (ResolveInfo) i; 7623// if (isEnabledLP(resolveInfo.serviceInfo)) { 7624// retList.add(resolveInfo); 7625// } 7626// } 7627// return retList; 7628// } 7629 7630 // Keys are String (activity class name), values are Activity. 7631 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7632 = new ArrayMap<ComponentName, PackageParser.Service>(); 7633 private int mFlags; 7634 }; 7635 7636 private final class ProviderIntentResolver 7637 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7639 boolean defaultOnly, int userId) { 7640 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7641 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7642 } 7643 7644 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7645 int userId) { 7646 if (!sUserManager.exists(userId)) 7647 return null; 7648 mFlags = flags; 7649 return super.queryIntent(intent, resolvedType, 7650 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7651 } 7652 7653 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7654 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7655 if (!sUserManager.exists(userId)) 7656 return null; 7657 if (packageProviders == null) { 7658 return null; 7659 } 7660 mFlags = flags; 7661 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7662 final int N = packageProviders.size(); 7663 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7664 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7665 7666 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7667 for (int i = 0; i < N; ++i) { 7668 intentFilters = packageProviders.get(i).intents; 7669 if (intentFilters != null && intentFilters.size() > 0) { 7670 PackageParser.ProviderIntentInfo[] array = 7671 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7672 intentFilters.toArray(array); 7673 listCut.add(array); 7674 } 7675 } 7676 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7677 } 7678 7679 public final void addProvider(PackageParser.Provider p) { 7680 if (mProviders.containsKey(p.getComponentName())) { 7681 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7682 return; 7683 } 7684 7685 mProviders.put(p.getComponentName(), p); 7686 if (DEBUG_SHOW_INFO) { 7687 Log.v(TAG, " " 7688 + (p.info.nonLocalizedLabel != null 7689 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7690 Log.v(TAG, " Class=" + p.info.name); 7691 } 7692 final int NI = p.intents.size(); 7693 int j; 7694 for (j = 0; j < NI; j++) { 7695 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7696 if (DEBUG_SHOW_INFO) { 7697 Log.v(TAG, " IntentFilter:"); 7698 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7699 } 7700 if (!intent.debugCheck()) { 7701 Log.w(TAG, "==> For Provider " + p.info.name); 7702 } 7703 addFilter(intent); 7704 } 7705 } 7706 7707 public final void removeProvider(PackageParser.Provider p) { 7708 mProviders.remove(p.getComponentName()); 7709 if (DEBUG_SHOW_INFO) { 7710 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7711 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7712 Log.v(TAG, " Class=" + p.info.name); 7713 } 7714 final int NI = p.intents.size(); 7715 int j; 7716 for (j = 0; j < NI; j++) { 7717 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7718 if (DEBUG_SHOW_INFO) { 7719 Log.v(TAG, " IntentFilter:"); 7720 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7721 } 7722 removeFilter(intent); 7723 } 7724 } 7725 7726 @Override 7727 protected boolean allowFilterResult( 7728 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7729 ProviderInfo filterPi = filter.provider.info; 7730 for (int i = dest.size() - 1; i >= 0; i--) { 7731 ProviderInfo destPi = dest.get(i).providerInfo; 7732 if (destPi.name == filterPi.name 7733 && destPi.packageName == filterPi.packageName) { 7734 return false; 7735 } 7736 } 7737 return true; 7738 } 7739 7740 @Override 7741 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7742 return new PackageParser.ProviderIntentInfo[size]; 7743 } 7744 7745 @Override 7746 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7747 if (!sUserManager.exists(userId)) 7748 return true; 7749 PackageParser.Package p = filter.provider.owner; 7750 if (p != null) { 7751 PackageSetting ps = (PackageSetting) p.mExtras; 7752 if (ps != null) { 7753 // System apps are never considered stopped for purposes of 7754 // filtering, because there may be no way for the user to 7755 // actually re-launch them. 7756 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7757 && ps.getStopped(userId); 7758 } 7759 } 7760 return false; 7761 } 7762 7763 @Override 7764 protected boolean isPackageForFilter(String packageName, 7765 PackageParser.ProviderIntentInfo info) { 7766 return packageName.equals(info.provider.owner.packageName); 7767 } 7768 7769 @Override 7770 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7771 int match, int userId) { 7772 if (!sUserManager.exists(userId)) 7773 return null; 7774 final PackageParser.ProviderIntentInfo info = filter; 7775 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7776 return null; 7777 } 7778 final PackageParser.Provider provider = info.provider; 7779 if (mSafeMode && (provider.info.applicationInfo.flags 7780 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7781 return null; 7782 } 7783 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7784 if (ps == null) { 7785 return null; 7786 } 7787 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7788 ps.readUserState(userId), userId); 7789 if (pi == null) { 7790 return null; 7791 } 7792 final ResolveInfo res = new ResolveInfo(); 7793 res.providerInfo = pi; 7794 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7795 res.filter = filter; 7796 } 7797 res.priority = info.getPriority(); 7798 res.preferredOrder = provider.owner.mPreferredOrder; 7799 res.match = match; 7800 res.isDefault = info.hasDefault; 7801 res.labelRes = info.labelRes; 7802 res.nonLocalizedLabel = info.nonLocalizedLabel; 7803 res.icon = info.icon; 7804 res.system = isSystemApp(res.providerInfo.applicationInfo); 7805 return res; 7806 } 7807 7808 @Override 7809 protected void sortResults(List<ResolveInfo> results) { 7810 Collections.sort(results, mResolvePrioritySorter); 7811 } 7812 7813 @Override 7814 protected void dumpFilter(PrintWriter out, String prefix, 7815 PackageParser.ProviderIntentInfo filter) { 7816 out.print(prefix); 7817 out.print( 7818 Integer.toHexString(System.identityHashCode(filter.provider))); 7819 out.print(' '); 7820 filter.provider.printComponentShortName(out); 7821 out.print(" filter "); 7822 out.println(Integer.toHexString(System.identityHashCode(filter))); 7823 } 7824 7825 @Override 7826 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7827 return filter.provider; 7828 } 7829 7830 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7831 PackageParser.Provider provider = (PackageParser.Provider)label; 7832 out.print(prefix); out.print( 7833 Integer.toHexString(System.identityHashCode(provider))); 7834 out.print(' '); 7835 provider.printComponentShortName(out); 7836 if (count > 1) { 7837 out.print(" ("); out.print(count); out.print(" filters)"); 7838 } 7839 out.println(); 7840 } 7841 7842 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7843 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7844 private int mFlags; 7845 }; 7846 7847 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7848 new Comparator<ResolveInfo>() { 7849 public int compare(ResolveInfo r1, ResolveInfo r2) { 7850 int v1 = r1.priority; 7851 int v2 = r2.priority; 7852 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7853 if (v1 != v2) { 7854 return (v1 > v2) ? -1 : 1; 7855 } 7856 v1 = r1.preferredOrder; 7857 v2 = r2.preferredOrder; 7858 if (v1 != v2) { 7859 return (v1 > v2) ? -1 : 1; 7860 } 7861 if (r1.isDefault != r2.isDefault) { 7862 return r1.isDefault ? -1 : 1; 7863 } 7864 v1 = r1.match; 7865 v2 = r2.match; 7866 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7867 if (v1 != v2) { 7868 return (v1 > v2) ? -1 : 1; 7869 } 7870 if (r1.system != r2.system) { 7871 return r1.system ? -1 : 1; 7872 } 7873 return 0; 7874 } 7875 }; 7876 7877 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7878 new Comparator<ProviderInfo>() { 7879 public int compare(ProviderInfo p1, ProviderInfo p2) { 7880 final int v1 = p1.initOrder; 7881 final int v2 = p2.initOrder; 7882 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7883 } 7884 }; 7885 7886 static final void sendPackageBroadcast(String action, String pkg, 7887 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7888 int[] userIds) { 7889 IActivityManager am = ActivityManagerNative.getDefault(); 7890 if (am != null) { 7891 try { 7892 if (userIds == null) { 7893 userIds = am.getRunningUserIds(); 7894 } 7895 for (int id : userIds) { 7896 final Intent intent = new Intent(action, 7897 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7898 if (extras != null) { 7899 intent.putExtras(extras); 7900 } 7901 if (targetPkg != null) { 7902 intent.setPackage(targetPkg); 7903 } 7904 // Modify the UID when posting to other users 7905 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7906 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7907 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7908 intent.putExtra(Intent.EXTRA_UID, uid); 7909 } 7910 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7911 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7912 if (DEBUG_BROADCASTS) { 7913 RuntimeException here = new RuntimeException("here"); 7914 here.fillInStackTrace(); 7915 Slog.d(TAG, "Sending to user " + id + ": " 7916 + intent.toShortString(false, true, false, false) 7917 + " " + intent.getExtras(), here); 7918 } 7919 am.broadcastIntent(null, intent, null, finishedReceiver, 7920 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7921 finishedReceiver != null, false, id); 7922 } 7923 } catch (RemoteException ex) { 7924 } 7925 } 7926 } 7927 7928 /** 7929 * Check if the external storage media is available. This is true if there 7930 * is a mounted external storage medium or if the external storage is 7931 * emulated. 7932 */ 7933 private boolean isExternalMediaAvailable() { 7934 return mMediaMounted || Environment.isExternalStorageEmulated(); 7935 } 7936 7937 @Override 7938 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7939 // writer 7940 synchronized (mPackages) { 7941 if (!isExternalMediaAvailable()) { 7942 // If the external storage is no longer mounted at this point, 7943 // the caller may not have been able to delete all of this 7944 // packages files and can not delete any more. Bail. 7945 return null; 7946 } 7947 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7948 if (lastPackage != null) { 7949 pkgs.remove(lastPackage); 7950 } 7951 if (pkgs.size() > 0) { 7952 return pkgs.get(0); 7953 } 7954 } 7955 return null; 7956 } 7957 7958 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7959 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7960 userId, andCode ? 1 : 0, packageName); 7961 if (mSystemReady) { 7962 msg.sendToTarget(); 7963 } else { 7964 if (mPostSystemReadyMessages == null) { 7965 mPostSystemReadyMessages = new ArrayList<>(); 7966 } 7967 mPostSystemReadyMessages.add(msg); 7968 } 7969 } 7970 7971 void startCleaningPackages() { 7972 // reader 7973 synchronized (mPackages) { 7974 if (!isExternalMediaAvailable()) { 7975 return; 7976 } 7977 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7978 return; 7979 } 7980 } 7981 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7982 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7983 IActivityManager am = ActivityManagerNative.getDefault(); 7984 if (am != null) { 7985 try { 7986 am.startService(null, intent, null, UserHandle.USER_OWNER); 7987 } catch (RemoteException e) { 7988 } 7989 } 7990 } 7991 7992 @Override 7993 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7994 int installFlags, String installerPackageName, VerificationParams verificationParams, 7995 String packageAbiOverride) { 7996 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7997 packageAbiOverride, UserHandle.getCallingUserId()); 7998 } 7999 8000 @Override 8001 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8002 int installFlags, String installerPackageName, VerificationParams verificationParams, 8003 String packageAbiOverride, int userId) { 8004 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8005 8006 final int callingUid = Binder.getCallingUid(); 8007 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8008 8009 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8010 try { 8011 if (observer != null) { 8012 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8013 } 8014 } catch (RemoteException re) { 8015 } 8016 return; 8017 } 8018 8019 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8020 installFlags |= PackageManager.INSTALL_FROM_ADB; 8021 8022 } else { 8023 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8024 // about installerPackageName. 8025 8026 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8027 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8028 } 8029 8030 UserHandle user; 8031 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8032 user = UserHandle.ALL; 8033 } else { 8034 user = new UserHandle(userId); 8035 } 8036 8037 verificationParams.setInstallerUid(callingUid); 8038 8039 final File originFile = new File(originPath); 8040 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8041 8042 final Message msg = mHandler.obtainMessage(INIT_COPY); 8043 msg.obj = new InstallParams(origin, observer, installFlags, 8044 installerPackageName, verificationParams, user, packageAbiOverride); 8045 mHandler.sendMessage(msg); 8046 } 8047 8048 void installStage(String packageName, File stagedDir, String stagedCid, 8049 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8050 String installerPackageName, int installerUid, UserHandle user) { 8051 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8052 params.referrerUri, installerUid, null); 8053 8054 final OriginInfo origin; 8055 if (stagedDir != null) { 8056 origin = OriginInfo.fromStagedFile(stagedDir); 8057 } else { 8058 origin = OriginInfo.fromStagedContainer(stagedCid); 8059 } 8060 8061 final Message msg = mHandler.obtainMessage(INIT_COPY); 8062 msg.obj = new InstallParams(origin, observer, params.installFlags, 8063 installerPackageName, verifParams, user, params.abiOverride); 8064 mHandler.sendMessage(msg); 8065 } 8066 8067 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8068 Bundle extras = new Bundle(1); 8069 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8070 8071 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8072 packageName, extras, null, null, new int[] {userId}); 8073 try { 8074 IActivityManager am = ActivityManagerNative.getDefault(); 8075 final boolean isSystem = 8076 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8077 if (isSystem && am.isUserRunning(userId, false)) { 8078 // The just-installed/enabled app is bundled on the system, so presumed 8079 // to be able to run automatically without needing an explicit launch. 8080 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8081 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8082 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8083 .setPackage(packageName); 8084 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8085 android.app.AppOpsManager.OP_NONE, false, false, userId); 8086 } 8087 } catch (RemoteException e) { 8088 // shouldn't happen 8089 Slog.w(TAG, "Unable to bootstrap installed package", e); 8090 } 8091 } 8092 8093 @Override 8094 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8095 int userId) { 8096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8097 PackageSetting pkgSetting; 8098 final int uid = Binder.getCallingUid(); 8099 enforceCrossUserPermission(uid, userId, true, true, 8100 "setApplicationHiddenSetting for user " + userId); 8101 8102 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8103 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8104 return false; 8105 } 8106 8107 long callingId = Binder.clearCallingIdentity(); 8108 try { 8109 boolean sendAdded = false; 8110 boolean sendRemoved = false; 8111 // writer 8112 synchronized (mPackages) { 8113 pkgSetting = mSettings.mPackages.get(packageName); 8114 if (pkgSetting == null) { 8115 return false; 8116 } 8117 if (pkgSetting.getHidden(userId) != hidden) { 8118 pkgSetting.setHidden(hidden, userId); 8119 mSettings.writePackageRestrictionsLPr(userId); 8120 if (hidden) { 8121 sendRemoved = true; 8122 } else { 8123 sendAdded = true; 8124 } 8125 } 8126 } 8127 if (sendAdded) { 8128 sendPackageAddedForUser(packageName, pkgSetting, userId); 8129 return true; 8130 } 8131 if (sendRemoved) { 8132 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8133 "hiding pkg"); 8134 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8135 } 8136 } finally { 8137 Binder.restoreCallingIdentity(callingId); 8138 } 8139 return false; 8140 } 8141 8142 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8143 int userId) { 8144 final PackageRemovedInfo info = new PackageRemovedInfo(); 8145 info.removedPackage = packageName; 8146 info.removedUsers = new int[] {userId}; 8147 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8148 info.sendBroadcast(false, false, false); 8149 } 8150 8151 /** 8152 * Returns true if application is not found or there was an error. Otherwise it returns 8153 * the hidden state of the package for the given user. 8154 */ 8155 @Override 8156 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8158 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8159 false, "getApplicationHidden for user " + userId); 8160 PackageSetting pkgSetting; 8161 long callingId = Binder.clearCallingIdentity(); 8162 try { 8163 // writer 8164 synchronized (mPackages) { 8165 pkgSetting = mSettings.mPackages.get(packageName); 8166 if (pkgSetting == null) { 8167 return true; 8168 } 8169 return pkgSetting.getHidden(userId); 8170 } 8171 } finally { 8172 Binder.restoreCallingIdentity(callingId); 8173 } 8174 } 8175 8176 /** 8177 * @hide 8178 */ 8179 @Override 8180 public int installExistingPackageAsUser(String packageName, int userId) { 8181 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8182 null); 8183 PackageSetting pkgSetting; 8184 final int uid = Binder.getCallingUid(); 8185 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8186 + userId); 8187 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8188 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8189 } 8190 8191 long callingId = Binder.clearCallingIdentity(); 8192 try { 8193 boolean sendAdded = false; 8194 Bundle extras = new Bundle(1); 8195 8196 // writer 8197 synchronized (mPackages) { 8198 pkgSetting = mSettings.mPackages.get(packageName); 8199 if (pkgSetting == null) { 8200 return PackageManager.INSTALL_FAILED_INVALID_URI; 8201 } 8202 if (!pkgSetting.getInstalled(userId)) { 8203 pkgSetting.setInstalled(true, userId); 8204 pkgSetting.setHidden(false, userId); 8205 mSettings.writePackageRestrictionsLPr(userId); 8206 sendAdded = true; 8207 } 8208 } 8209 8210 if (sendAdded) { 8211 sendPackageAddedForUser(packageName, pkgSetting, userId); 8212 } 8213 } finally { 8214 Binder.restoreCallingIdentity(callingId); 8215 } 8216 8217 return PackageManager.INSTALL_SUCCEEDED; 8218 } 8219 8220 boolean isUserRestricted(int userId, String restrictionKey) { 8221 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8222 if (restrictions.getBoolean(restrictionKey, false)) { 8223 Log.w(TAG, "User is restricted: " + restrictionKey); 8224 return true; 8225 } 8226 return false; 8227 } 8228 8229 @Override 8230 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8231 mContext.enforceCallingOrSelfPermission( 8232 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8233 "Only package verification agents can verify applications"); 8234 8235 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8236 final PackageVerificationResponse response = new PackageVerificationResponse( 8237 verificationCode, Binder.getCallingUid()); 8238 msg.arg1 = id; 8239 msg.obj = response; 8240 mHandler.sendMessage(msg); 8241 } 8242 8243 @Override 8244 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8245 long millisecondsToDelay) { 8246 mContext.enforceCallingOrSelfPermission( 8247 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8248 "Only package verification agents can extend verification timeouts"); 8249 8250 final PackageVerificationState state = mPendingVerification.get(id); 8251 final PackageVerificationResponse response = new PackageVerificationResponse( 8252 verificationCodeAtTimeout, Binder.getCallingUid()); 8253 8254 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8255 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8256 } 8257 if (millisecondsToDelay < 0) { 8258 millisecondsToDelay = 0; 8259 } 8260 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8261 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8262 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8263 } 8264 8265 if ((state != null) && !state.timeoutExtended()) { 8266 state.extendTimeout(); 8267 8268 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8269 msg.arg1 = id; 8270 msg.obj = response; 8271 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8272 } 8273 } 8274 8275 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8276 int verificationCode, UserHandle user) { 8277 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8278 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8279 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8280 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8281 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8282 8283 mContext.sendBroadcastAsUser(intent, user, 8284 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8285 } 8286 8287 private ComponentName matchComponentForVerifier(String packageName, 8288 List<ResolveInfo> receivers) { 8289 ActivityInfo targetReceiver = null; 8290 8291 final int NR = receivers.size(); 8292 for (int i = 0; i < NR; i++) { 8293 final ResolveInfo info = receivers.get(i); 8294 if (info.activityInfo == null) { 8295 continue; 8296 } 8297 8298 if (packageName.equals(info.activityInfo.packageName)) { 8299 targetReceiver = info.activityInfo; 8300 break; 8301 } 8302 } 8303 8304 if (targetReceiver == null) { 8305 return null; 8306 } 8307 8308 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8309 } 8310 8311 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8312 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8313 if (pkgInfo.verifiers.length == 0) { 8314 return null; 8315 } 8316 8317 final int N = pkgInfo.verifiers.length; 8318 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8319 for (int i = 0; i < N; i++) { 8320 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8321 8322 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8323 receivers); 8324 if (comp == null) { 8325 continue; 8326 } 8327 8328 final int verifierUid = getUidForVerifier(verifierInfo); 8329 if (verifierUid == -1) { 8330 continue; 8331 } 8332 8333 if (DEBUG_VERIFY) { 8334 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8335 + " with the correct signature"); 8336 } 8337 sufficientVerifiers.add(comp); 8338 verificationState.addSufficientVerifier(verifierUid); 8339 } 8340 8341 return sufficientVerifiers; 8342 } 8343 8344 private int getUidForVerifier(VerifierInfo verifierInfo) { 8345 synchronized (mPackages) { 8346 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8347 if (pkg == null) { 8348 return -1; 8349 } else if (pkg.mSignatures.length != 1) { 8350 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8351 + " has more than one signature; ignoring"); 8352 return -1; 8353 } 8354 8355 /* 8356 * If the public key of the package's signature does not match 8357 * our expected public key, then this is a different package and 8358 * we should skip. 8359 */ 8360 8361 final byte[] expectedPublicKey; 8362 try { 8363 final Signature verifierSig = pkg.mSignatures[0]; 8364 final PublicKey publicKey = verifierSig.getPublicKey(); 8365 expectedPublicKey = publicKey.getEncoded(); 8366 } catch (CertificateException e) { 8367 return -1; 8368 } 8369 8370 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8371 8372 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8373 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8374 + " does not have the expected public key; ignoring"); 8375 return -1; 8376 } 8377 8378 return pkg.applicationInfo.uid; 8379 } 8380 } 8381 8382 @Override 8383 public void finishPackageInstall(int token) { 8384 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8385 8386 if (DEBUG_INSTALL) { 8387 Slog.v(TAG, "BM finishing package install for " + token); 8388 } 8389 8390 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8391 mHandler.sendMessage(msg); 8392 } 8393 8394 /** 8395 * Get the verification agent timeout. 8396 * 8397 * @return verification timeout in milliseconds 8398 */ 8399 private long getVerificationTimeout() { 8400 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8401 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8402 DEFAULT_VERIFICATION_TIMEOUT); 8403 } 8404 8405 /** 8406 * Get the default verification agent response code. 8407 * 8408 * @return default verification response code 8409 */ 8410 private int getDefaultVerificationResponse() { 8411 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8412 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8413 DEFAULT_VERIFICATION_RESPONSE); 8414 } 8415 8416 /** 8417 * Check whether or not package verification has been enabled. 8418 * 8419 * @return true if verification should be performed 8420 */ 8421 private boolean isVerificationEnabled(int userId, int installFlags) { 8422 if (!DEFAULT_VERIFY_ENABLE) { 8423 return false; 8424 } 8425 8426 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8427 8428 // Check if installing from ADB 8429 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8430 // Do not run verification in a test harness environment 8431 if (ActivityManager.isRunningInTestHarness()) { 8432 return false; 8433 } 8434 if (ensureVerifyAppsEnabled) { 8435 return true; 8436 } 8437 // Check if the developer does not want package verification for ADB installs 8438 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8439 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8440 return false; 8441 } 8442 } 8443 8444 if (ensureVerifyAppsEnabled) { 8445 return true; 8446 } 8447 8448 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8449 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8450 } 8451 8452 /** 8453 * Get the "allow unknown sources" setting. 8454 * 8455 * @return the current "allow unknown sources" setting 8456 */ 8457 private int getUnknownSourcesSettings() { 8458 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8459 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8460 -1); 8461 } 8462 8463 @Override 8464 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8465 final int uid = Binder.getCallingUid(); 8466 // writer 8467 synchronized (mPackages) { 8468 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8469 if (targetPackageSetting == null) { 8470 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8471 } 8472 8473 PackageSetting installerPackageSetting; 8474 if (installerPackageName != null) { 8475 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8476 if (installerPackageSetting == null) { 8477 throw new IllegalArgumentException("Unknown installer package: " 8478 + installerPackageName); 8479 } 8480 } else { 8481 installerPackageSetting = null; 8482 } 8483 8484 Signature[] callerSignature; 8485 Object obj = mSettings.getUserIdLPr(uid); 8486 if (obj != null) { 8487 if (obj instanceof SharedUserSetting) { 8488 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8489 } else if (obj instanceof PackageSetting) { 8490 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8491 } else { 8492 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8493 } 8494 } else { 8495 throw new SecurityException("Unknown calling uid " + uid); 8496 } 8497 8498 // Verify: can't set installerPackageName to a package that is 8499 // not signed with the same cert as the caller. 8500 if (installerPackageSetting != null) { 8501 if (compareSignatures(callerSignature, 8502 installerPackageSetting.signatures.mSignatures) 8503 != PackageManager.SIGNATURE_MATCH) { 8504 throw new SecurityException( 8505 "Caller does not have same cert as new installer package " 8506 + installerPackageName); 8507 } 8508 } 8509 8510 // Verify: if target already has an installer package, it must 8511 // be signed with the same cert as the caller. 8512 if (targetPackageSetting.installerPackageName != null) { 8513 PackageSetting setting = mSettings.mPackages.get( 8514 targetPackageSetting.installerPackageName); 8515 // If the currently set package isn't valid, then it's always 8516 // okay to change it. 8517 if (setting != null) { 8518 if (compareSignatures(callerSignature, 8519 setting.signatures.mSignatures) 8520 != PackageManager.SIGNATURE_MATCH) { 8521 throw new SecurityException( 8522 "Caller does not have same cert as old installer package " 8523 + targetPackageSetting.installerPackageName); 8524 } 8525 } 8526 } 8527 8528 // Okay! 8529 targetPackageSetting.installerPackageName = installerPackageName; 8530 scheduleWriteSettingsLocked(); 8531 } 8532 } 8533 8534 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8535 // Queue up an async operation since the package installation may take a little while. 8536 mHandler.post(new Runnable() { 8537 public void run() { 8538 mHandler.removeCallbacks(this); 8539 // Result object to be returned 8540 PackageInstalledInfo res = new PackageInstalledInfo(); 8541 res.returnCode = currentStatus; 8542 res.uid = -1; 8543 res.pkg = null; 8544 res.removedInfo = new PackageRemovedInfo(); 8545 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8546 args.doPreInstall(res.returnCode); 8547 synchronized (mInstallLock) { 8548 installPackageLI(args, res); 8549 } 8550 args.doPostInstall(res.returnCode, res.uid); 8551 } 8552 8553 // A restore should be performed at this point if (a) the install 8554 // succeeded, (b) the operation is not an update, and (c) the new 8555 // package has not opted out of backup participation. 8556 final boolean update = res.removedInfo.removedPackage != null; 8557 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8558 boolean doRestore = !update 8559 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8560 8561 // Set up the post-install work request bookkeeping. This will be used 8562 // and cleaned up by the post-install event handling regardless of whether 8563 // there's a restore pass performed. Token values are >= 1. 8564 int token; 8565 if (mNextInstallToken < 0) mNextInstallToken = 1; 8566 token = mNextInstallToken++; 8567 8568 PostInstallData data = new PostInstallData(args, res); 8569 mRunningInstalls.put(token, data); 8570 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8571 8572 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8573 // Pass responsibility to the Backup Manager. It will perform a 8574 // restore if appropriate, then pass responsibility back to the 8575 // Package Manager to run the post-install observer callbacks 8576 // and broadcasts. 8577 IBackupManager bm = IBackupManager.Stub.asInterface( 8578 ServiceManager.getService(Context.BACKUP_SERVICE)); 8579 if (bm != null) { 8580 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8581 + " to BM for possible restore"); 8582 try { 8583 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8584 } catch (RemoteException e) { 8585 // can't happen; the backup manager is local 8586 } catch (Exception e) { 8587 Slog.e(TAG, "Exception trying to enqueue restore", e); 8588 doRestore = false; 8589 } 8590 } else { 8591 Slog.e(TAG, "Backup Manager not found!"); 8592 doRestore = false; 8593 } 8594 } 8595 8596 if (!doRestore) { 8597 // No restore possible, or the Backup Manager was mysteriously not 8598 // available -- just fire the post-install work request directly. 8599 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8600 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8601 mHandler.sendMessage(msg); 8602 } 8603 } 8604 }); 8605 } 8606 8607 private abstract class HandlerParams { 8608 private static final int MAX_RETRIES = 4; 8609 8610 /** 8611 * Number of times startCopy() has been attempted and had a non-fatal 8612 * error. 8613 */ 8614 private int mRetries = 0; 8615 8616 /** User handle for the user requesting the information or installation. */ 8617 private final UserHandle mUser; 8618 8619 HandlerParams(UserHandle user) { 8620 mUser = user; 8621 } 8622 8623 UserHandle getUser() { 8624 return mUser; 8625 } 8626 8627 final boolean startCopy() { 8628 boolean res; 8629 try { 8630 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8631 8632 if (++mRetries > MAX_RETRIES) { 8633 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8634 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8635 handleServiceError(); 8636 return false; 8637 } else { 8638 handleStartCopy(); 8639 res = true; 8640 } 8641 } catch (RemoteException e) { 8642 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8643 mHandler.sendEmptyMessage(MCS_RECONNECT); 8644 res = false; 8645 } 8646 handleReturnCode(); 8647 return res; 8648 } 8649 8650 final void serviceError() { 8651 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8652 handleServiceError(); 8653 handleReturnCode(); 8654 } 8655 8656 abstract void handleStartCopy() throws RemoteException; 8657 abstract void handleServiceError(); 8658 abstract void handleReturnCode(); 8659 } 8660 8661 class MeasureParams extends HandlerParams { 8662 private final PackageStats mStats; 8663 private boolean mSuccess; 8664 8665 private final IPackageStatsObserver mObserver; 8666 8667 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8668 super(new UserHandle(stats.userHandle)); 8669 mObserver = observer; 8670 mStats = stats; 8671 } 8672 8673 @Override 8674 public String toString() { 8675 return "MeasureParams{" 8676 + Integer.toHexString(System.identityHashCode(this)) 8677 + " " + mStats.packageName + "}"; 8678 } 8679 8680 @Override 8681 void handleStartCopy() throws RemoteException { 8682 synchronized (mInstallLock) { 8683 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8684 } 8685 8686 if (mSuccess) { 8687 final boolean mounted; 8688 if (Environment.isExternalStorageEmulated()) { 8689 mounted = true; 8690 } else { 8691 final String status = Environment.getExternalStorageState(); 8692 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8693 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8694 } 8695 8696 if (mounted) { 8697 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8698 8699 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8700 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8701 8702 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8703 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8704 8705 // Always subtract cache size, since it's a subdirectory 8706 mStats.externalDataSize -= mStats.externalCacheSize; 8707 8708 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8709 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8710 8711 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8712 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8713 } 8714 } 8715 } 8716 8717 @Override 8718 void handleReturnCode() { 8719 if (mObserver != null) { 8720 try { 8721 mObserver.onGetStatsCompleted(mStats, mSuccess); 8722 } catch (RemoteException e) { 8723 Slog.i(TAG, "Observer no longer exists."); 8724 } 8725 } 8726 } 8727 8728 @Override 8729 void handleServiceError() { 8730 Slog.e(TAG, "Could not measure application " + mStats.packageName 8731 + " external storage"); 8732 } 8733 } 8734 8735 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8736 throws RemoteException { 8737 long result = 0; 8738 for (File path : paths) { 8739 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8740 } 8741 return result; 8742 } 8743 8744 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8745 for (File path : paths) { 8746 try { 8747 mcs.clearDirectory(path.getAbsolutePath()); 8748 } catch (RemoteException e) { 8749 } 8750 } 8751 } 8752 8753 static class OriginInfo { 8754 /** 8755 * Location where install is coming from, before it has been 8756 * copied/renamed into place. This could be a single monolithic APK 8757 * file, or a cluster directory. This location may be untrusted. 8758 */ 8759 final File file; 8760 final String cid; 8761 8762 /** 8763 * Flag indicating that {@link #file} or {@link #cid} has already been 8764 * staged, meaning downstream users don't need to defensively copy the 8765 * contents. 8766 */ 8767 final boolean staged; 8768 8769 /** 8770 * Flag indicating that {@link #file} or {@link #cid} is an already 8771 * installed app that is being moved. 8772 */ 8773 final boolean existing; 8774 8775 final String resolvedPath; 8776 final File resolvedFile; 8777 8778 static OriginInfo fromNothing() { 8779 return new OriginInfo(null, null, false, false); 8780 } 8781 8782 static OriginInfo fromUntrustedFile(File file) { 8783 return new OriginInfo(file, null, false, false); 8784 } 8785 8786 static OriginInfo fromExistingFile(File file) { 8787 return new OriginInfo(file, null, false, true); 8788 } 8789 8790 static OriginInfo fromStagedFile(File file) { 8791 return new OriginInfo(file, null, true, false); 8792 } 8793 8794 static OriginInfo fromStagedContainer(String cid) { 8795 return new OriginInfo(null, cid, true, false); 8796 } 8797 8798 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8799 this.file = file; 8800 this.cid = cid; 8801 this.staged = staged; 8802 this.existing = existing; 8803 8804 if (cid != null) { 8805 resolvedPath = PackageHelper.getSdDir(cid); 8806 resolvedFile = new File(resolvedPath); 8807 } else if (file != null) { 8808 resolvedPath = file.getAbsolutePath(); 8809 resolvedFile = file; 8810 } else { 8811 resolvedPath = null; 8812 resolvedFile = null; 8813 } 8814 } 8815 } 8816 8817 class InstallParams extends HandlerParams { 8818 final OriginInfo origin; 8819 final IPackageInstallObserver2 observer; 8820 int installFlags; 8821 final String installerPackageName; 8822 final VerificationParams verificationParams; 8823 private InstallArgs mArgs; 8824 private int mRet; 8825 final String packageAbiOverride; 8826 8827 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8828 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8829 String packageAbiOverride) { 8830 super(user); 8831 this.origin = origin; 8832 this.observer = observer; 8833 this.installFlags = installFlags; 8834 this.installerPackageName = installerPackageName; 8835 this.verificationParams = verificationParams; 8836 this.packageAbiOverride = packageAbiOverride; 8837 } 8838 8839 @Override 8840 public String toString() { 8841 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8842 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8843 } 8844 8845 public ManifestDigest getManifestDigest() { 8846 if (verificationParams == null) { 8847 return null; 8848 } 8849 return verificationParams.getManifestDigest(); 8850 } 8851 8852 private int installLocationPolicy(PackageInfoLite pkgLite) { 8853 String packageName = pkgLite.packageName; 8854 int installLocation = pkgLite.installLocation; 8855 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8856 // reader 8857 synchronized (mPackages) { 8858 PackageParser.Package pkg = mPackages.get(packageName); 8859 if (pkg != null) { 8860 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8861 // Check for downgrading. 8862 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8863 try { 8864 checkDowngrade(pkg, pkgLite); 8865 } catch (PackageManagerException e) { 8866 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8867 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8868 } 8869 } 8870 // Check for updated system application. 8871 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8872 if (onSd) { 8873 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8874 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8875 } 8876 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8877 } else { 8878 if (onSd) { 8879 // Install flag overrides everything. 8880 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8881 } 8882 // If current upgrade specifies particular preference 8883 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8884 // Application explicitly specified internal. 8885 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8886 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8887 // App explictly prefers external. Let policy decide 8888 } else { 8889 // Prefer previous location 8890 if (isExternal(pkg)) { 8891 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8892 } 8893 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8894 } 8895 } 8896 } else { 8897 // Invalid install. Return error code 8898 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8899 } 8900 } 8901 } 8902 // All the special cases have been taken care of. 8903 // Return result based on recommended install location. 8904 if (onSd) { 8905 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8906 } 8907 return pkgLite.recommendedInstallLocation; 8908 } 8909 8910 /* 8911 * Invoke remote method to get package information and install 8912 * location values. Override install location based on default 8913 * policy if needed and then create install arguments based 8914 * on the install location. 8915 */ 8916 public void handleStartCopy() throws RemoteException { 8917 int ret = PackageManager.INSTALL_SUCCEEDED; 8918 8919 // If we're already staged, we've firmly committed to an install location 8920 if (origin.staged) { 8921 if (origin.file != null) { 8922 installFlags |= PackageManager.INSTALL_INTERNAL; 8923 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8924 } else if (origin.cid != null) { 8925 installFlags |= PackageManager.INSTALL_EXTERNAL; 8926 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8927 } else { 8928 throw new IllegalStateException("Invalid stage location"); 8929 } 8930 } 8931 8932 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8933 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8934 8935 PackageInfoLite pkgLite = null; 8936 8937 if (onInt && onSd) { 8938 // Check if both bits are set. 8939 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8940 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8941 } else { 8942 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8943 packageAbiOverride); 8944 8945 /* 8946 * If we have too little free space, try to free cache 8947 * before giving up. 8948 */ 8949 if (!origin.staged && pkgLite.recommendedInstallLocation 8950 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8951 // TODO: focus freeing disk space on the target device 8952 final StorageManager storage = StorageManager.from(mContext); 8953 final long lowThreshold = storage.getStorageLowBytes( 8954 Environment.getDataDirectory()); 8955 8956 final long sizeBytes = mContainerService.calculateInstalledSize( 8957 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8958 8959 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8960 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8961 installFlags, packageAbiOverride); 8962 } 8963 8964 /* 8965 * The cache free must have deleted the file we 8966 * downloaded to install. 8967 * 8968 * TODO: fix the "freeCache" call to not delete 8969 * the file we care about. 8970 */ 8971 if (pkgLite.recommendedInstallLocation 8972 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8973 pkgLite.recommendedInstallLocation 8974 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8975 } 8976 } 8977 } 8978 8979 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8980 int loc = pkgLite.recommendedInstallLocation; 8981 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8982 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8983 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8984 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8985 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8986 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8987 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8988 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8989 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8990 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8991 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8992 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8993 } else { 8994 // Override with defaults if needed. 8995 loc = installLocationPolicy(pkgLite); 8996 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8997 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8998 } else if (!onSd && !onInt) { 8999 // Override install location with flags 9000 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9001 // Set the flag to install on external media. 9002 installFlags |= PackageManager.INSTALL_EXTERNAL; 9003 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9004 } else { 9005 // Make sure the flag for installing on external 9006 // media is unset 9007 installFlags |= PackageManager.INSTALL_INTERNAL; 9008 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9009 } 9010 } 9011 } 9012 } 9013 9014 final InstallArgs args = createInstallArgs(this); 9015 mArgs = args; 9016 9017 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9018 /* 9019 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9020 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9021 */ 9022 int userIdentifier = getUser().getIdentifier(); 9023 if (userIdentifier == UserHandle.USER_ALL 9024 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9025 userIdentifier = UserHandle.USER_OWNER; 9026 } 9027 9028 /* 9029 * Determine if we have any installed package verifiers. If we 9030 * do, then we'll defer to them to verify the packages. 9031 */ 9032 final int requiredUid = mRequiredVerifierPackage == null ? -1 9033 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9034 if (!origin.existing && requiredUid != -1 9035 && isVerificationEnabled(userIdentifier, installFlags)) { 9036 final Intent verification = new Intent( 9037 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9038 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9039 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9040 PACKAGE_MIME_TYPE); 9041 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9042 9043 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9044 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9045 0 /* TODO: Which userId? */); 9046 9047 if (DEBUG_VERIFY) { 9048 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9049 + verification.toString() + " with " + pkgLite.verifiers.length 9050 + " optional verifiers"); 9051 } 9052 9053 final int verificationId = mPendingVerificationToken++; 9054 9055 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9056 9057 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9058 installerPackageName); 9059 9060 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9061 installFlags); 9062 9063 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9064 pkgLite.packageName); 9065 9066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9067 pkgLite.versionCode); 9068 9069 if (verificationParams != null) { 9070 if (verificationParams.getVerificationURI() != null) { 9071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9072 verificationParams.getVerificationURI()); 9073 } 9074 if (verificationParams.getOriginatingURI() != null) { 9075 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9076 verificationParams.getOriginatingURI()); 9077 } 9078 if (verificationParams.getReferrer() != null) { 9079 verification.putExtra(Intent.EXTRA_REFERRER, 9080 verificationParams.getReferrer()); 9081 } 9082 if (verificationParams.getOriginatingUid() >= 0) { 9083 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9084 verificationParams.getOriginatingUid()); 9085 } 9086 if (verificationParams.getInstallerUid() >= 0) { 9087 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9088 verificationParams.getInstallerUid()); 9089 } 9090 } 9091 9092 final PackageVerificationState verificationState = new PackageVerificationState( 9093 requiredUid, args); 9094 9095 mPendingVerification.append(verificationId, verificationState); 9096 9097 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9098 receivers, verificationState); 9099 9100 /* 9101 * If any sufficient verifiers were listed in the package 9102 * manifest, attempt to ask them. 9103 */ 9104 if (sufficientVerifiers != null) { 9105 final int N = sufficientVerifiers.size(); 9106 if (N == 0) { 9107 Slog.i(TAG, "Additional verifiers required, but none installed."); 9108 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9109 } else { 9110 for (int i = 0; i < N; i++) { 9111 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9112 9113 final Intent sufficientIntent = new Intent(verification); 9114 sufficientIntent.setComponent(verifierComponent); 9115 9116 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9117 } 9118 } 9119 } 9120 9121 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9122 mRequiredVerifierPackage, receivers); 9123 if (ret == PackageManager.INSTALL_SUCCEEDED 9124 && mRequiredVerifierPackage != null) { 9125 /* 9126 * Send the intent to the required verification agent, 9127 * but only start the verification timeout after the 9128 * target BroadcastReceivers have run. 9129 */ 9130 verification.setComponent(requiredVerifierComponent); 9131 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9133 new BroadcastReceiver() { 9134 @Override 9135 public void onReceive(Context context, Intent intent) { 9136 final Message msg = mHandler 9137 .obtainMessage(CHECK_PENDING_VERIFICATION); 9138 msg.arg1 = verificationId; 9139 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9140 } 9141 }, null, 0, null, null); 9142 9143 /* 9144 * We don't want the copy to proceed until verification 9145 * succeeds, so null out this field. 9146 */ 9147 mArgs = null; 9148 } 9149 } else { 9150 /* 9151 * No package verification is enabled, so immediately start 9152 * the remote call to initiate copy using temporary file. 9153 */ 9154 ret = args.copyApk(mContainerService, true); 9155 } 9156 } 9157 9158 mRet = ret; 9159 } 9160 9161 @Override 9162 void handleReturnCode() { 9163 // If mArgs is null, then MCS couldn't be reached. When it 9164 // reconnects, it will try again to install. At that point, this 9165 // will succeed. 9166 if (mArgs != null) { 9167 processPendingInstall(mArgs, mRet); 9168 } 9169 } 9170 9171 @Override 9172 void handleServiceError() { 9173 mArgs = createInstallArgs(this); 9174 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9175 } 9176 9177 public boolean isForwardLocked() { 9178 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9179 } 9180 } 9181 9182 /** 9183 * Used during creation of InstallArgs 9184 * 9185 * @param installFlags package installation flags 9186 * @return true if should be installed on external storage 9187 */ 9188 private static boolean installOnSd(int installFlags) { 9189 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9190 return false; 9191 } 9192 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9193 return true; 9194 } 9195 return false; 9196 } 9197 9198 /** 9199 * Used during creation of InstallArgs 9200 * 9201 * @param installFlags package installation flags 9202 * @return true if should be installed as forward locked 9203 */ 9204 private static boolean installForwardLocked(int installFlags) { 9205 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9206 } 9207 9208 private InstallArgs createInstallArgs(InstallParams params) { 9209 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9210 return new AsecInstallArgs(params); 9211 } else { 9212 return new FileInstallArgs(params); 9213 } 9214 } 9215 9216 /** 9217 * Create args that describe an existing installed package. Typically used 9218 * when cleaning up old installs, or used as a move source. 9219 */ 9220 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9221 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9222 final boolean isInAsec; 9223 if (installOnSd(installFlags)) { 9224 /* Apps on SD card are always in ASEC containers. */ 9225 isInAsec = true; 9226 } else if (installForwardLocked(installFlags) 9227 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9228 /* 9229 * Forward-locked apps are only in ASEC containers if they're the 9230 * new style 9231 */ 9232 isInAsec = true; 9233 } else { 9234 isInAsec = false; 9235 } 9236 9237 if (isInAsec) { 9238 return new AsecInstallArgs(codePath, instructionSets, 9239 installOnSd(installFlags), installForwardLocked(installFlags)); 9240 } else { 9241 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9242 instructionSets); 9243 } 9244 } 9245 9246 static abstract class InstallArgs { 9247 /** @see InstallParams#origin */ 9248 final OriginInfo origin; 9249 9250 final IPackageInstallObserver2 observer; 9251 // Always refers to PackageManager flags only 9252 final int installFlags; 9253 final String installerPackageName; 9254 final ManifestDigest manifestDigest; 9255 final UserHandle user; 9256 final String abiOverride; 9257 9258 // The list of instruction sets supported by this app. This is currently 9259 // only used during the rmdex() phase to clean up resources. We can get rid of this 9260 // if we move dex files under the common app path. 9261 /* nullable */ String[] instructionSets; 9262 9263 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9264 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9265 String[] instructionSets, String abiOverride) { 9266 this.origin = origin; 9267 this.installFlags = installFlags; 9268 this.observer = observer; 9269 this.installerPackageName = installerPackageName; 9270 this.manifestDigest = manifestDigest; 9271 this.user = user; 9272 this.instructionSets = instructionSets; 9273 this.abiOverride = abiOverride; 9274 } 9275 9276 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9277 abstract int doPreInstall(int status); 9278 9279 /** 9280 * Rename package into final resting place. All paths on the given 9281 * scanned package should be updated to reflect the rename. 9282 */ 9283 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9284 abstract int doPostInstall(int status, int uid); 9285 9286 /** @see PackageSettingBase#codePathString */ 9287 abstract String getCodePath(); 9288 /** @see PackageSettingBase#resourcePathString */ 9289 abstract String getResourcePath(); 9290 abstract String getLegacyNativeLibraryPath(); 9291 9292 // Need installer lock especially for dex file removal. 9293 abstract void cleanUpResourcesLI(); 9294 abstract boolean doPostDeleteLI(boolean delete); 9295 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9296 9297 /** 9298 * Called before the source arguments are copied. This is used mostly 9299 * for MoveParams when it needs to read the source file to put it in the 9300 * destination. 9301 */ 9302 int doPreCopy() { 9303 return PackageManager.INSTALL_SUCCEEDED; 9304 } 9305 9306 /** 9307 * Called after the source arguments are copied. This is used mostly for 9308 * MoveParams when it needs to read the source file to put it in the 9309 * destination. 9310 * 9311 * @return 9312 */ 9313 int doPostCopy(int uid) { 9314 return PackageManager.INSTALL_SUCCEEDED; 9315 } 9316 9317 protected boolean isFwdLocked() { 9318 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9319 } 9320 9321 protected boolean isExternal() { 9322 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9323 } 9324 9325 UserHandle getUser() { 9326 return user; 9327 } 9328 } 9329 9330 /** 9331 * Logic to handle installation of non-ASEC applications, including copying 9332 * and renaming logic. 9333 */ 9334 class FileInstallArgs extends InstallArgs { 9335 private File codeFile; 9336 private File resourceFile; 9337 private File legacyNativeLibraryPath; 9338 9339 // Example topology: 9340 // /data/app/com.example/base.apk 9341 // /data/app/com.example/split_foo.apk 9342 // /data/app/com.example/lib/arm/libfoo.so 9343 // /data/app/com.example/lib/arm64/libfoo.so 9344 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9345 9346 /** New install */ 9347 FileInstallArgs(InstallParams params) { 9348 super(params.origin, params.observer, params.installFlags, 9349 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9350 null /* instruction sets */, params.packageAbiOverride); 9351 if (isFwdLocked()) { 9352 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9353 } 9354 } 9355 9356 /** Existing install */ 9357 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9358 String[] instructionSets) { 9359 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9360 this.codeFile = (codePath != null) ? new File(codePath) : null; 9361 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9362 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9363 new File(legacyNativeLibraryPath) : null; 9364 } 9365 9366 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9367 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9368 isFwdLocked(), abiOverride); 9369 9370 final StorageManager storage = StorageManager.from(mContext); 9371 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9372 } 9373 9374 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9375 if (origin.staged) { 9376 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9377 codeFile = origin.file; 9378 resourceFile = origin.file; 9379 return PackageManager.INSTALL_SUCCEEDED; 9380 } 9381 9382 try { 9383 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9384 codeFile = tempDir; 9385 resourceFile = tempDir; 9386 } catch (IOException e) { 9387 Slog.w(TAG, "Failed to create copy file: " + e); 9388 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9389 } 9390 9391 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9392 @Override 9393 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9394 if (!FileUtils.isValidExtFilename(name)) { 9395 throw new IllegalArgumentException("Invalid filename: " + name); 9396 } 9397 try { 9398 final File file = new File(codeFile, name); 9399 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9400 O_RDWR | O_CREAT, 0644); 9401 Os.chmod(file.getAbsolutePath(), 0644); 9402 return new ParcelFileDescriptor(fd); 9403 } catch (ErrnoException e) { 9404 throw new RemoteException("Failed to open: " + e.getMessage()); 9405 } 9406 } 9407 }; 9408 9409 int ret = PackageManager.INSTALL_SUCCEEDED; 9410 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9411 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9412 Slog.e(TAG, "Failed to copy package"); 9413 return ret; 9414 } 9415 9416 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9417 NativeLibraryHelper.Handle handle = null; 9418 try { 9419 handle = NativeLibraryHelper.Handle.create(codeFile); 9420 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9421 abiOverride); 9422 } catch (IOException e) { 9423 Slog.e(TAG, "Copying native libraries failed", e); 9424 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9425 } finally { 9426 IoUtils.closeQuietly(handle); 9427 } 9428 9429 return ret; 9430 } 9431 9432 int doPreInstall(int status) { 9433 if (status != PackageManager.INSTALL_SUCCEEDED) { 9434 cleanUp(); 9435 } 9436 return status; 9437 } 9438 9439 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9440 if (status != PackageManager.INSTALL_SUCCEEDED) { 9441 cleanUp(); 9442 return false; 9443 } else { 9444 final File beforeCodeFile = codeFile; 9445 final File afterCodeFile = getNextCodePath(pkg.packageName); 9446 9447 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9448 try { 9449 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9450 } catch (ErrnoException e) { 9451 Slog.d(TAG, "Failed to rename", e); 9452 return false; 9453 } 9454 9455 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9456 Slog.d(TAG, "Failed to restorecon"); 9457 return false; 9458 } 9459 9460 // Reflect the rename internally 9461 codeFile = afterCodeFile; 9462 resourceFile = afterCodeFile; 9463 9464 // Reflect the rename in scanned details 9465 pkg.codePath = afterCodeFile.getAbsolutePath(); 9466 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9467 pkg.baseCodePath); 9468 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9469 pkg.splitCodePaths); 9470 9471 // Reflect the rename in app info 9472 pkg.applicationInfo.setCodePath(pkg.codePath); 9473 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9474 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9475 pkg.applicationInfo.setResourcePath(pkg.codePath); 9476 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9477 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9478 9479 return true; 9480 } 9481 } 9482 9483 int doPostInstall(int status, int uid) { 9484 if (status != PackageManager.INSTALL_SUCCEEDED) { 9485 cleanUp(); 9486 } 9487 return status; 9488 } 9489 9490 @Override 9491 String getCodePath() { 9492 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9493 } 9494 9495 @Override 9496 String getResourcePath() { 9497 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9498 } 9499 9500 @Override 9501 String getLegacyNativeLibraryPath() { 9502 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9503 } 9504 9505 private boolean cleanUp() { 9506 if (codeFile == null || !codeFile.exists()) { 9507 return false; 9508 } 9509 9510 if (codeFile.isDirectory()) { 9511 FileUtils.deleteContents(codeFile); 9512 } 9513 codeFile.delete(); 9514 9515 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9516 resourceFile.delete(); 9517 } 9518 9519 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9520 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9521 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9522 } 9523 legacyNativeLibraryPath.delete(); 9524 } 9525 9526 return true; 9527 } 9528 9529 void cleanUpResourcesLI() { 9530 // Try enumerating all code paths before deleting 9531 List<String> allCodePaths = Collections.EMPTY_LIST; 9532 if (codeFile != null && codeFile.exists()) { 9533 try { 9534 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9535 allCodePaths = pkg.getAllCodePaths(); 9536 } catch (PackageParserException e) { 9537 // Ignored; we tried our best 9538 } 9539 } 9540 9541 cleanUp(); 9542 9543 if (!allCodePaths.isEmpty()) { 9544 if (instructionSets == null) { 9545 throw new IllegalStateException("instructionSet == null"); 9546 } 9547 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9548 for (String codePath : allCodePaths) { 9549 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9550 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9551 if (retCode < 0) { 9552 Slog.w(TAG, "Couldn't remove dex file for package: " 9553 + " at location " + codePath + ", retcode=" + retCode); 9554 // we don't consider this to be a failure of the core package deletion 9555 } 9556 } 9557 } 9558 } 9559 } 9560 9561 boolean doPostDeleteLI(boolean delete) { 9562 // XXX err, shouldn't we respect the delete flag? 9563 cleanUpResourcesLI(); 9564 return true; 9565 } 9566 } 9567 9568 private boolean isAsecExternal(String cid) { 9569 final String asecPath = PackageHelper.getSdFilesystem(cid); 9570 return !asecPath.startsWith(mAsecInternalPath); 9571 } 9572 9573 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9574 PackageManagerException { 9575 if (copyRet < 0) { 9576 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9577 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9578 throw new PackageManagerException(copyRet, message); 9579 } 9580 } 9581 } 9582 9583 /** 9584 * Extract the MountService "container ID" from the full code path of an 9585 * .apk. 9586 */ 9587 static String cidFromCodePath(String fullCodePath) { 9588 int eidx = fullCodePath.lastIndexOf("/"); 9589 String subStr1 = fullCodePath.substring(0, eidx); 9590 int sidx = subStr1.lastIndexOf("/"); 9591 return subStr1.substring(sidx+1, eidx); 9592 } 9593 9594 /** 9595 * Logic to handle installation of ASEC applications, including copying and 9596 * renaming logic. 9597 */ 9598 class AsecInstallArgs extends InstallArgs { 9599 static final String RES_FILE_NAME = "pkg.apk"; 9600 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9601 9602 String cid; 9603 String packagePath; 9604 String resourcePath; 9605 String legacyNativeLibraryDir; 9606 9607 /** New install */ 9608 AsecInstallArgs(InstallParams params) { 9609 super(params.origin, params.observer, params.installFlags, 9610 params.installerPackageName, params.getManifestDigest(), 9611 params.getUser(), null /* instruction sets */, 9612 params.packageAbiOverride); 9613 } 9614 9615 /** Existing install */ 9616 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9617 boolean isExternal, boolean isForwardLocked) { 9618 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9619 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9620 instructionSets, null); 9621 // Hackily pretend we're still looking at a full code path 9622 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9623 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9624 } 9625 9626 // Extract cid from fullCodePath 9627 int eidx = fullCodePath.lastIndexOf("/"); 9628 String subStr1 = fullCodePath.substring(0, eidx); 9629 int sidx = subStr1.lastIndexOf("/"); 9630 cid = subStr1.substring(sidx+1, eidx); 9631 setMountPath(subStr1); 9632 } 9633 9634 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9635 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9636 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9637 instructionSets, null); 9638 this.cid = cid; 9639 setMountPath(PackageHelper.getSdDir(cid)); 9640 } 9641 9642 void createCopyFile() { 9643 cid = mInstallerService.allocateExternalStageCidLegacy(); 9644 } 9645 9646 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9647 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9648 abiOverride); 9649 9650 final File target; 9651 if (isExternal()) { 9652 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9653 } else { 9654 target = Environment.getDataDirectory(); 9655 } 9656 9657 final StorageManager storage = StorageManager.from(mContext); 9658 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9659 } 9660 9661 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9662 if (origin.staged) { 9663 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9664 cid = origin.cid; 9665 setMountPath(PackageHelper.getSdDir(cid)); 9666 return PackageManager.INSTALL_SUCCEEDED; 9667 } 9668 9669 if (temp) { 9670 createCopyFile(); 9671 } else { 9672 /* 9673 * Pre-emptively destroy the container since it's destroyed if 9674 * copying fails due to it existing anyway. 9675 */ 9676 PackageHelper.destroySdDir(cid); 9677 } 9678 9679 final String newMountPath = imcs.copyPackageToContainer( 9680 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9681 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9682 9683 if (newMountPath != null) { 9684 setMountPath(newMountPath); 9685 return PackageManager.INSTALL_SUCCEEDED; 9686 } else { 9687 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9688 } 9689 } 9690 9691 @Override 9692 String getCodePath() { 9693 return packagePath; 9694 } 9695 9696 @Override 9697 String getResourcePath() { 9698 return resourcePath; 9699 } 9700 9701 @Override 9702 String getLegacyNativeLibraryPath() { 9703 return legacyNativeLibraryDir; 9704 } 9705 9706 int doPreInstall(int status) { 9707 if (status != PackageManager.INSTALL_SUCCEEDED) { 9708 // Destroy container 9709 PackageHelper.destroySdDir(cid); 9710 } else { 9711 boolean mounted = PackageHelper.isContainerMounted(cid); 9712 if (!mounted) { 9713 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9714 Process.SYSTEM_UID); 9715 if (newMountPath != null) { 9716 setMountPath(newMountPath); 9717 } else { 9718 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9719 } 9720 } 9721 } 9722 return status; 9723 } 9724 9725 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9726 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9727 String newMountPath = null; 9728 if (PackageHelper.isContainerMounted(cid)) { 9729 // Unmount the container 9730 if (!PackageHelper.unMountSdDir(cid)) { 9731 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9732 return false; 9733 } 9734 } 9735 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9736 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9737 " which might be stale. Will try to clean up."); 9738 // Clean up the stale container and proceed to recreate. 9739 if (!PackageHelper.destroySdDir(newCacheId)) { 9740 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9741 return false; 9742 } 9743 // Successfully cleaned up stale container. Try to rename again. 9744 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9745 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9746 + " inspite of cleaning it up."); 9747 return false; 9748 } 9749 } 9750 if (!PackageHelper.isContainerMounted(newCacheId)) { 9751 Slog.w(TAG, "Mounting container " + newCacheId); 9752 newMountPath = PackageHelper.mountSdDir(newCacheId, 9753 getEncryptKey(), Process.SYSTEM_UID); 9754 } else { 9755 newMountPath = PackageHelper.getSdDir(newCacheId); 9756 } 9757 if (newMountPath == null) { 9758 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9759 return false; 9760 } 9761 Log.i(TAG, "Succesfully renamed " + cid + 9762 " to " + newCacheId + 9763 " at new path: " + newMountPath); 9764 cid = newCacheId; 9765 9766 final File beforeCodeFile = new File(packagePath); 9767 setMountPath(newMountPath); 9768 final File afterCodeFile = new File(packagePath); 9769 9770 // Reflect the rename in scanned details 9771 pkg.codePath = afterCodeFile.getAbsolutePath(); 9772 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9773 pkg.baseCodePath); 9774 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9775 pkg.splitCodePaths); 9776 9777 // Reflect the rename in app info 9778 pkg.applicationInfo.setCodePath(pkg.codePath); 9779 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9780 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9781 pkg.applicationInfo.setResourcePath(pkg.codePath); 9782 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9783 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9784 9785 return true; 9786 } 9787 9788 private void setMountPath(String mountPath) { 9789 final File mountFile = new File(mountPath); 9790 9791 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9792 if (monolithicFile.exists()) { 9793 packagePath = monolithicFile.getAbsolutePath(); 9794 if (isFwdLocked()) { 9795 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9796 } else { 9797 resourcePath = packagePath; 9798 } 9799 } else { 9800 packagePath = mountFile.getAbsolutePath(); 9801 resourcePath = packagePath; 9802 } 9803 9804 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9805 } 9806 9807 int doPostInstall(int status, int uid) { 9808 if (status != PackageManager.INSTALL_SUCCEEDED) { 9809 cleanUp(); 9810 } else { 9811 final int groupOwner; 9812 final String protectedFile; 9813 if (isFwdLocked()) { 9814 groupOwner = UserHandle.getSharedAppGid(uid); 9815 protectedFile = RES_FILE_NAME; 9816 } else { 9817 groupOwner = -1; 9818 protectedFile = null; 9819 } 9820 9821 if (uid < Process.FIRST_APPLICATION_UID 9822 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9823 Slog.e(TAG, "Failed to finalize " + cid); 9824 PackageHelper.destroySdDir(cid); 9825 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9826 } 9827 9828 boolean mounted = PackageHelper.isContainerMounted(cid); 9829 if (!mounted) { 9830 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9831 } 9832 } 9833 return status; 9834 } 9835 9836 private void cleanUp() { 9837 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9838 9839 // Destroy secure container 9840 PackageHelper.destroySdDir(cid); 9841 } 9842 9843 private List<String> getAllCodePaths() { 9844 final File codeFile = new File(getCodePath()); 9845 if (codeFile != null && codeFile.exists()) { 9846 try { 9847 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9848 return pkg.getAllCodePaths(); 9849 } catch (PackageParserException e) { 9850 // Ignored; we tried our best 9851 } 9852 } 9853 return Collections.EMPTY_LIST; 9854 } 9855 9856 void cleanUpResourcesLI() { 9857 // Enumerate all code paths before deleting 9858 cleanUpResourcesLI(getAllCodePaths()); 9859 } 9860 9861 private void cleanUpResourcesLI(List<String> allCodePaths) { 9862 cleanUp(); 9863 9864 if (!allCodePaths.isEmpty()) { 9865 if (instructionSets == null) { 9866 throw new IllegalStateException("instructionSet == null"); 9867 } 9868 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9869 for (String codePath : allCodePaths) { 9870 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9871 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9872 if (retCode < 0) { 9873 Slog.w(TAG, "Couldn't remove dex file for package: " 9874 + " at location " + codePath + ", retcode=" + retCode); 9875 // we don't consider this to be a failure of the core package deletion 9876 } 9877 } 9878 } 9879 } 9880 } 9881 9882 boolean matchContainer(String app) { 9883 if (cid.startsWith(app)) { 9884 return true; 9885 } 9886 return false; 9887 } 9888 9889 String getPackageName() { 9890 return getAsecPackageName(cid); 9891 } 9892 9893 boolean doPostDeleteLI(boolean delete) { 9894 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9895 final List<String> allCodePaths = getAllCodePaths(); 9896 boolean mounted = PackageHelper.isContainerMounted(cid); 9897 if (mounted) { 9898 // Unmount first 9899 if (PackageHelper.unMountSdDir(cid)) { 9900 mounted = false; 9901 } 9902 } 9903 if (!mounted && delete) { 9904 cleanUpResourcesLI(allCodePaths); 9905 } 9906 return !mounted; 9907 } 9908 9909 @Override 9910 int doPreCopy() { 9911 if (isFwdLocked()) { 9912 if (!PackageHelper.fixSdPermissions(cid, 9913 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9914 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9915 } 9916 } 9917 9918 return PackageManager.INSTALL_SUCCEEDED; 9919 } 9920 9921 @Override 9922 int doPostCopy(int uid) { 9923 if (isFwdLocked()) { 9924 if (uid < Process.FIRST_APPLICATION_UID 9925 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9926 RES_FILE_NAME)) { 9927 Slog.e(TAG, "Failed to finalize " + cid); 9928 PackageHelper.destroySdDir(cid); 9929 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9930 } 9931 } 9932 9933 return PackageManager.INSTALL_SUCCEEDED; 9934 } 9935 } 9936 9937 static String getAsecPackageName(String packageCid) { 9938 int idx = packageCid.lastIndexOf("-"); 9939 if (idx == -1) { 9940 return packageCid; 9941 } 9942 return packageCid.substring(0, idx); 9943 } 9944 9945 // Utility method used to create code paths based on package name and available index. 9946 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9947 String idxStr = ""; 9948 int idx = 1; 9949 // Fall back to default value of idx=1 if prefix is not 9950 // part of oldCodePath 9951 if (oldCodePath != null) { 9952 String subStr = oldCodePath; 9953 // Drop the suffix right away 9954 if (suffix != null && subStr.endsWith(suffix)) { 9955 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9956 } 9957 // If oldCodePath already contains prefix find out the 9958 // ending index to either increment or decrement. 9959 int sidx = subStr.lastIndexOf(prefix); 9960 if (sidx != -1) { 9961 subStr = subStr.substring(sidx + prefix.length()); 9962 if (subStr != null) { 9963 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9964 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9965 } 9966 try { 9967 idx = Integer.parseInt(subStr); 9968 if (idx <= 1) { 9969 idx++; 9970 } else { 9971 idx--; 9972 } 9973 } catch(NumberFormatException e) { 9974 } 9975 } 9976 } 9977 } 9978 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9979 return prefix + idxStr; 9980 } 9981 9982 private File getNextCodePath(String packageName) { 9983 int suffix = 1; 9984 File result; 9985 do { 9986 result = new File(mAppInstallDir, packageName + "-" + suffix); 9987 suffix++; 9988 } while (result.exists()); 9989 return result; 9990 } 9991 9992 // Utility method used to ignore ADD/REMOVE events 9993 // by directory observer. 9994 private static boolean ignoreCodePath(String fullPathStr) { 9995 String apkName = deriveCodePathName(fullPathStr); 9996 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9997 if (idx != -1 && ((idx+1) < apkName.length())) { 9998 // Make sure the package ends with a numeral 9999 String version = apkName.substring(idx+1); 10000 try { 10001 Integer.parseInt(version); 10002 return true; 10003 } catch (NumberFormatException e) {} 10004 } 10005 return false; 10006 } 10007 10008 // Utility method that returns the relative package path with respect 10009 // to the installation directory. Like say for /data/data/com.test-1.apk 10010 // string com.test-1 is returned. 10011 static String deriveCodePathName(String codePath) { 10012 if (codePath == null) { 10013 return null; 10014 } 10015 final File codeFile = new File(codePath); 10016 final String name = codeFile.getName(); 10017 if (codeFile.isDirectory()) { 10018 return name; 10019 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10020 final int lastDot = name.lastIndexOf('.'); 10021 return name.substring(0, lastDot); 10022 } else { 10023 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10024 return null; 10025 } 10026 } 10027 10028 class PackageInstalledInfo { 10029 String name; 10030 int uid; 10031 // The set of users that originally had this package installed. 10032 int[] origUsers; 10033 // The set of users that now have this package installed. 10034 int[] newUsers; 10035 PackageParser.Package pkg; 10036 int returnCode; 10037 String returnMsg; 10038 PackageRemovedInfo removedInfo; 10039 10040 public void setError(int code, String msg) { 10041 returnCode = code; 10042 returnMsg = msg; 10043 Slog.w(TAG, msg); 10044 } 10045 10046 public void setError(String msg, PackageParserException e) { 10047 returnCode = e.error; 10048 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10049 Slog.w(TAG, msg, e); 10050 } 10051 10052 public void setError(String msg, PackageManagerException e) { 10053 returnCode = e.error; 10054 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10055 Slog.w(TAG, msg, e); 10056 } 10057 10058 // In some error cases we want to convey more info back to the observer 10059 String origPackage; 10060 String origPermission; 10061 } 10062 10063 /* 10064 * Install a non-existing package. 10065 */ 10066 private void installNewPackageLI(PackageParser.Package pkg, 10067 int parseFlags, int scanFlags, UserHandle user, 10068 String installerPackageName, PackageInstalledInfo res) { 10069 // Remember this for later, in case we need to rollback this install 10070 String pkgName = pkg.packageName; 10071 10072 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10073 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10074 synchronized(mPackages) { 10075 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10076 // A package with the same name is already installed, though 10077 // it has been renamed to an older name. The package we 10078 // are trying to install should be installed as an update to 10079 // the existing one, but that has not been requested, so bail. 10080 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10081 + " without first uninstalling package running as " 10082 + mSettings.mRenamedPackages.get(pkgName)); 10083 return; 10084 } 10085 if (mPackages.containsKey(pkgName)) { 10086 // Don't allow installation over an existing package with the same name. 10087 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10088 + " without first uninstalling."); 10089 return; 10090 } 10091 } 10092 10093 try { 10094 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10095 System.currentTimeMillis(), user); 10096 10097 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10098 // delete the partially installed application. the data directory will have to be 10099 // restored if it was already existing 10100 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10101 // remove package from internal structures. Note that we want deletePackageX to 10102 // delete the package data and cache directories that it created in 10103 // scanPackageLocked, unless those directories existed before we even tried to 10104 // install. 10105 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10106 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10107 res.removedInfo, true); 10108 } 10109 10110 } catch (PackageManagerException e) { 10111 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10112 } 10113 } 10114 10115 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10116 // Upgrade keysets are being used. Determine if new package has a superset of the 10117 // required keys. 10118 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10119 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10120 for (int i = 0; i < upgradeKeySets.length; i++) { 10121 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10122 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10123 return true; 10124 } 10125 } 10126 return false; 10127 } 10128 10129 private void replacePackageLI(PackageParser.Package pkg, 10130 int parseFlags, int scanFlags, UserHandle user, 10131 String installerPackageName, PackageInstalledInfo res) { 10132 PackageParser.Package oldPackage; 10133 String pkgName = pkg.packageName; 10134 int[] allUsers; 10135 boolean[] perUserInstalled; 10136 10137 // First find the old package info and check signatures 10138 synchronized(mPackages) { 10139 oldPackage = mPackages.get(pkgName); 10140 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10141 PackageSetting ps = mSettings.mPackages.get(pkgName); 10142 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10143 // default to original signature matching 10144 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10145 != PackageManager.SIGNATURE_MATCH) { 10146 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10147 "New package has a different signature: " + pkgName); 10148 return; 10149 } 10150 } else { 10151 if(!checkUpgradeKeySetLP(ps, pkg)) { 10152 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10153 "New package not signed by keys specified by upgrade-keysets: " 10154 + pkgName); 10155 return; 10156 } 10157 } 10158 10159 // In case of rollback, remember per-user/profile install state 10160 allUsers = sUserManager.getUserIds(); 10161 perUserInstalled = new boolean[allUsers.length]; 10162 for (int i = 0; i < allUsers.length; i++) { 10163 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10164 } 10165 } 10166 10167 boolean sysPkg = (isSystemApp(oldPackage)); 10168 if (sysPkg) { 10169 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10170 user, allUsers, perUserInstalled, installerPackageName, res); 10171 } else { 10172 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10173 user, allUsers, perUserInstalled, installerPackageName, res); 10174 } 10175 } 10176 10177 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10178 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10179 int[] allUsers, boolean[] perUserInstalled, 10180 String installerPackageName, PackageInstalledInfo res) { 10181 String pkgName = deletedPackage.packageName; 10182 boolean deletedPkg = true; 10183 boolean updatedSettings = false; 10184 10185 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10186 + deletedPackage); 10187 long origUpdateTime; 10188 if (pkg.mExtras != null) { 10189 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10190 } else { 10191 origUpdateTime = 0; 10192 } 10193 10194 // First delete the existing package while retaining the data directory 10195 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10196 res.removedInfo, true)) { 10197 // If the existing package wasn't successfully deleted 10198 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10199 deletedPkg = false; 10200 } else { 10201 // Successfully deleted the old package; proceed with replace. 10202 10203 // If deleted package lived in a container, give users a chance to 10204 // relinquish resources before killing. 10205 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10206 if (DEBUG_INSTALL) { 10207 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10208 } 10209 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10210 final ArrayList<String> pkgList = new ArrayList<String>(1); 10211 pkgList.add(deletedPackage.applicationInfo.packageName); 10212 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10213 } 10214 10215 deleteCodeCacheDirsLI(pkgName); 10216 try { 10217 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10218 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10219 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10220 updatedSettings = true; 10221 } catch (PackageManagerException e) { 10222 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10223 } 10224 } 10225 10226 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10227 // remove package from internal structures. Note that we want deletePackageX to 10228 // delete the package data and cache directories that it created in 10229 // scanPackageLocked, unless those directories existed before we even tried to 10230 // install. 10231 if(updatedSettings) { 10232 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10233 deletePackageLI( 10234 pkgName, null, true, allUsers, perUserInstalled, 10235 PackageManager.DELETE_KEEP_DATA, 10236 res.removedInfo, true); 10237 } 10238 // Since we failed to install the new package we need to restore the old 10239 // package that we deleted. 10240 if (deletedPkg) { 10241 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10242 File restoreFile = new File(deletedPackage.codePath); 10243 // Parse old package 10244 boolean oldOnSd = isExternal(deletedPackage); 10245 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10246 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10247 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10248 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10249 try { 10250 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10251 } catch (PackageManagerException e) { 10252 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10253 + e.getMessage()); 10254 return; 10255 } 10256 // Restore of old package succeeded. Update permissions. 10257 // writer 10258 synchronized (mPackages) { 10259 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10260 UPDATE_PERMISSIONS_ALL); 10261 // can downgrade to reader 10262 mSettings.writeLPr(); 10263 } 10264 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10265 } 10266 } 10267 } 10268 10269 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10270 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10271 int[] allUsers, boolean[] perUserInstalled, 10272 String installerPackageName, PackageInstalledInfo res) { 10273 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10274 + ", old=" + deletedPackage); 10275 boolean disabledSystem = false; 10276 boolean updatedSettings = false; 10277 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10278 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10279 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10280 } 10281 String packageName = deletedPackage.packageName; 10282 if (packageName == null) { 10283 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10284 "Attempt to delete null packageName."); 10285 return; 10286 } 10287 PackageParser.Package oldPkg; 10288 PackageSetting oldPkgSetting; 10289 // reader 10290 synchronized (mPackages) { 10291 oldPkg = mPackages.get(packageName); 10292 oldPkgSetting = mSettings.mPackages.get(packageName); 10293 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10294 (oldPkgSetting == null)) { 10295 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10296 "Couldn't find package:" + packageName + " information"); 10297 return; 10298 } 10299 } 10300 10301 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10302 10303 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10304 res.removedInfo.removedPackage = packageName; 10305 // Remove existing system package 10306 removePackageLI(oldPkgSetting, true); 10307 // writer 10308 synchronized (mPackages) { 10309 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10310 if (!disabledSystem && deletedPackage != null) { 10311 // We didn't need to disable the .apk as a current system package, 10312 // which means we are replacing another update that is already 10313 // installed. We need to make sure to delete the older one's .apk. 10314 res.removedInfo.args = createInstallArgsForExisting(0, 10315 deletedPackage.applicationInfo.getCodePath(), 10316 deletedPackage.applicationInfo.getResourcePath(), 10317 deletedPackage.applicationInfo.nativeLibraryRootDir, 10318 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10319 } else { 10320 res.removedInfo.args = null; 10321 } 10322 } 10323 10324 // Successfully disabled the old package. Now proceed with re-installation 10325 deleteCodeCacheDirsLI(packageName); 10326 10327 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10328 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10329 10330 PackageParser.Package newPackage = null; 10331 try { 10332 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10333 if (newPackage.mExtras != null) { 10334 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10335 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10336 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10337 10338 // is the update attempting to change shared user? that isn't going to work... 10339 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10340 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10341 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10342 + " to " + newPkgSetting.sharedUser); 10343 updatedSettings = true; 10344 } 10345 } 10346 10347 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10348 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10349 updatedSettings = true; 10350 } 10351 10352 } catch (PackageManagerException e) { 10353 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10354 } 10355 10356 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10357 // Re installation failed. Restore old information 10358 // Remove new pkg information 10359 if (newPackage != null) { 10360 removeInstalledPackageLI(newPackage, true); 10361 } 10362 // Add back the old system package 10363 try { 10364 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10365 } catch (PackageManagerException e) { 10366 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10367 } 10368 // Restore the old system information in Settings 10369 synchronized (mPackages) { 10370 if (disabledSystem) { 10371 mSettings.enableSystemPackageLPw(packageName); 10372 } 10373 if (updatedSettings) { 10374 mSettings.setInstallerPackageName(packageName, 10375 oldPkgSetting.installerPackageName); 10376 } 10377 mSettings.writeLPr(); 10378 } 10379 } 10380 } 10381 10382 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10383 int[] allUsers, boolean[] perUserInstalled, 10384 PackageInstalledInfo res) { 10385 String pkgName = newPackage.packageName; 10386 synchronized (mPackages) { 10387 //write settings. the installStatus will be incomplete at this stage. 10388 //note that the new package setting would have already been 10389 //added to mPackages. It hasn't been persisted yet. 10390 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10391 mSettings.writeLPr(); 10392 } 10393 10394 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10395 10396 synchronized (mPackages) { 10397 updatePermissionsLPw(newPackage.packageName, newPackage, 10398 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10399 ? UPDATE_PERMISSIONS_ALL : 0)); 10400 // For system-bundled packages, we assume that installing an upgraded version 10401 // of the package implies that the user actually wants to run that new code, 10402 // so we enable the package. 10403 if (isSystemApp(newPackage)) { 10404 // NB: implicit assumption that system package upgrades apply to all users 10405 if (DEBUG_INSTALL) { 10406 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10407 } 10408 PackageSetting ps = mSettings.mPackages.get(pkgName); 10409 if (ps != null) { 10410 if (res.origUsers != null) { 10411 for (int userHandle : res.origUsers) { 10412 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10413 userHandle, installerPackageName); 10414 } 10415 } 10416 // Also convey the prior install/uninstall state 10417 if (allUsers != null && perUserInstalled != null) { 10418 for (int i = 0; i < allUsers.length; i++) { 10419 if (DEBUG_INSTALL) { 10420 Slog.d(TAG, " user " + allUsers[i] 10421 + " => " + perUserInstalled[i]); 10422 } 10423 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10424 } 10425 // these install state changes will be persisted in the 10426 // upcoming call to mSettings.writeLPr(). 10427 } 10428 } 10429 } 10430 res.name = pkgName; 10431 res.uid = newPackage.applicationInfo.uid; 10432 res.pkg = newPackage; 10433 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10434 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10435 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10436 //to update install status 10437 mSettings.writeLPr(); 10438 } 10439 } 10440 10441 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10442 final int installFlags = args.installFlags; 10443 String installerPackageName = args.installerPackageName; 10444 File tmpPackageFile = new File(args.getCodePath()); 10445 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10446 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10447 boolean replace = false; 10448 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10449 // Result object to be returned 10450 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10451 10452 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10453 // Retrieve PackageSettings and parse package 10454 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10455 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10456 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10457 PackageParser pp = new PackageParser(); 10458 pp.setSeparateProcesses(mSeparateProcesses); 10459 pp.setDisplayMetrics(mMetrics); 10460 10461 final PackageParser.Package pkg; 10462 try { 10463 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10464 } catch (PackageParserException e) { 10465 res.setError("Failed parse during installPackageLI", e); 10466 return; 10467 } 10468 10469 // Mark that we have an install time CPU ABI override. 10470 pkg.cpuAbiOverride = args.abiOverride; 10471 10472 String pkgName = res.name = pkg.packageName; 10473 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10474 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10475 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10476 return; 10477 } 10478 } 10479 10480 try { 10481 pp.collectCertificates(pkg, parseFlags); 10482 pp.collectManifestDigest(pkg); 10483 } catch (PackageParserException e) { 10484 res.setError("Failed collect during installPackageLI", e); 10485 return; 10486 } 10487 10488 /* If the installer passed in a manifest digest, compare it now. */ 10489 if (args.manifestDigest != null) { 10490 if (DEBUG_INSTALL) { 10491 final String parsedManifest = pkg.manifestDigest == null ? "null" 10492 : pkg.manifestDigest.toString(); 10493 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10494 + parsedManifest); 10495 } 10496 10497 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10498 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10499 return; 10500 } 10501 } else if (DEBUG_INSTALL) { 10502 final String parsedManifest = pkg.manifestDigest == null 10503 ? "null" : pkg.manifestDigest.toString(); 10504 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10505 } 10506 10507 // Get rid of all references to package scan path via parser. 10508 pp = null; 10509 String oldCodePath = null; 10510 boolean systemApp = false; 10511 synchronized (mPackages) { 10512 // Check if installing already existing package 10513 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10514 String oldName = mSettings.mRenamedPackages.get(pkgName); 10515 if (pkg.mOriginalPackages != null 10516 && pkg.mOriginalPackages.contains(oldName) 10517 && mPackages.containsKey(oldName)) { 10518 // This package is derived from an original package, 10519 // and this device has been updating from that original 10520 // name. We must continue using the original name, so 10521 // rename the new package here. 10522 pkg.setPackageName(oldName); 10523 pkgName = pkg.packageName; 10524 replace = true; 10525 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10526 + oldName + " pkgName=" + pkgName); 10527 } else if (mPackages.containsKey(pkgName)) { 10528 // This package, under its official name, already exists 10529 // on the device; we should replace it. 10530 replace = true; 10531 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10532 } 10533 } 10534 10535 PackageSetting ps = mSettings.mPackages.get(pkgName); 10536 if (ps != null) { 10537 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10538 10539 // Quick sanity check that we're signed correctly if updating; 10540 // we'll check this again later when scanning, but we want to 10541 // bail early here before tripping over redefined permissions. 10542 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10543 try { 10544 verifySignaturesLP(ps, pkg); 10545 } catch (PackageManagerException e) { 10546 res.setError(e.error, e.getMessage()); 10547 return; 10548 } 10549 } else { 10550 if (!checkUpgradeKeySetLP(ps, pkg)) { 10551 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10552 + pkg.packageName + " upgrade keys do not match the " 10553 + "previously installed version"); 10554 return; 10555 } 10556 } 10557 10558 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10559 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10560 systemApp = (ps.pkg.applicationInfo.flags & 10561 ApplicationInfo.FLAG_SYSTEM) != 0; 10562 } 10563 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10564 } 10565 10566 // Check whether the newly-scanned package wants to define an already-defined perm 10567 int N = pkg.permissions.size(); 10568 for (int i = N-1; i >= 0; i--) { 10569 PackageParser.Permission perm = pkg.permissions.get(i); 10570 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10571 if (bp != null) { 10572 // If the defining package is signed with our cert, it's okay. This 10573 // also includes the "updating the same package" case, of course. 10574 // "updating same package" could also involve key-rotation. 10575 final boolean sigsOk; 10576 if (!bp.sourcePackage.equals(pkg.packageName) 10577 || !(bp.packageSetting instanceof PackageSetting) 10578 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10579 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10580 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10581 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10582 } else { 10583 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10584 } 10585 if (!sigsOk) { 10586 // If the owning package is the system itself, we log but allow 10587 // install to proceed; we fail the install on all other permission 10588 // redefinitions. 10589 if (!bp.sourcePackage.equals("android")) { 10590 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10591 + pkg.packageName + " attempting to redeclare permission " 10592 + perm.info.name + " already owned by " + bp.sourcePackage); 10593 res.origPermission = perm.info.name; 10594 res.origPackage = bp.sourcePackage; 10595 return; 10596 } else { 10597 Slog.w(TAG, "Package " + pkg.packageName 10598 + " attempting to redeclare system permission " 10599 + perm.info.name + "; ignoring new declaration"); 10600 pkg.permissions.remove(i); 10601 } 10602 } 10603 } 10604 } 10605 10606 } 10607 10608 if (systemApp && onSd) { 10609 // Disable updates to system apps on sdcard 10610 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10611 "Cannot install updates to system apps on sdcard"); 10612 return; 10613 } 10614 10615 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10616 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10617 return; 10618 } 10619 10620 if (replace) { 10621 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10622 installerPackageName, res); 10623 } else { 10624 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10625 args.user, installerPackageName, res); 10626 } 10627 synchronized (mPackages) { 10628 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10629 if (ps != null) { 10630 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10631 } 10632 } 10633 } 10634 10635 private static boolean isForwardLocked(PackageParser.Package pkg) { 10636 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10637 } 10638 10639 private static boolean isForwardLocked(ApplicationInfo info) { 10640 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10641 } 10642 10643 private boolean isForwardLocked(PackageSetting ps) { 10644 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10645 } 10646 10647 private static boolean isMultiArch(PackageSetting ps) { 10648 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10649 } 10650 10651 private static boolean isMultiArch(ApplicationInfo info) { 10652 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10653 } 10654 10655 private static boolean isExternal(PackageParser.Package pkg) { 10656 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10657 } 10658 10659 private static boolean isExternal(PackageSetting ps) { 10660 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10661 } 10662 10663 private static boolean isExternal(ApplicationInfo info) { 10664 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10665 } 10666 10667 private static boolean isSystemApp(PackageParser.Package pkg) { 10668 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10669 } 10670 10671 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10672 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10673 } 10674 10675 private static boolean isSystemApp(ApplicationInfo info) { 10676 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10677 } 10678 10679 private static boolean isSystemApp(PackageSetting ps) { 10680 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10681 } 10682 10683 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10684 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10685 } 10686 10687 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10688 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10689 } 10690 10691 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10692 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10693 } 10694 10695 private int packageFlagsToInstallFlags(PackageSetting ps) { 10696 int installFlags = 0; 10697 if (isExternal(ps)) { 10698 installFlags |= PackageManager.INSTALL_EXTERNAL; 10699 } 10700 if (isForwardLocked(ps)) { 10701 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10702 } 10703 return installFlags; 10704 } 10705 10706 private void deleteTempPackageFiles() { 10707 final FilenameFilter filter = new FilenameFilter() { 10708 public boolean accept(File dir, String name) { 10709 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10710 } 10711 }; 10712 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10713 file.delete(); 10714 } 10715 } 10716 10717 @Override 10718 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10719 int flags) { 10720 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10721 flags); 10722 } 10723 10724 @Override 10725 public void deletePackage(final String packageName, 10726 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10727 mContext.enforceCallingOrSelfPermission( 10728 android.Manifest.permission.DELETE_PACKAGES, null); 10729 final int uid = Binder.getCallingUid(); 10730 if (UserHandle.getUserId(uid) != userId) { 10731 mContext.enforceCallingPermission( 10732 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10733 "deletePackage for user " + userId); 10734 } 10735 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10736 try { 10737 observer.onPackageDeleted(packageName, 10738 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10739 } catch (RemoteException re) { 10740 } 10741 return; 10742 } 10743 10744 boolean uninstallBlocked = false; 10745 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10746 int[] users = sUserManager.getUserIds(); 10747 for (int i = 0; i < users.length; ++i) { 10748 if (getBlockUninstallForUser(packageName, users[i])) { 10749 uninstallBlocked = true; 10750 break; 10751 } 10752 } 10753 } else { 10754 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10755 } 10756 if (uninstallBlocked) { 10757 try { 10758 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10759 null); 10760 } catch (RemoteException re) { 10761 } 10762 return; 10763 } 10764 10765 if (DEBUG_REMOVE) { 10766 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10767 } 10768 // Queue up an async operation since the package deletion may take a little while. 10769 mHandler.post(new Runnable() { 10770 public void run() { 10771 mHandler.removeCallbacks(this); 10772 final int returnCode = deletePackageX(packageName, userId, flags); 10773 if (observer != null) { 10774 try { 10775 observer.onPackageDeleted(packageName, returnCode, null); 10776 } catch (RemoteException e) { 10777 Log.i(TAG, "Observer no longer exists."); 10778 } //end catch 10779 } //end if 10780 } //end run 10781 }); 10782 } 10783 10784 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10785 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10786 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10787 try { 10788 if (dpm != null) { 10789 if (dpm.isDeviceOwner(packageName)) { 10790 return true; 10791 } 10792 int[] users; 10793 if (userId == UserHandle.USER_ALL) { 10794 users = sUserManager.getUserIds(); 10795 } else { 10796 users = new int[]{userId}; 10797 } 10798 for (int i = 0; i < users.length; ++i) { 10799 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10800 return true; 10801 } 10802 } 10803 } 10804 } catch (RemoteException e) { 10805 } 10806 return false; 10807 } 10808 10809 /** 10810 * This method is an internal method that could be get invoked either 10811 * to delete an installed package or to clean up a failed installation. 10812 * After deleting an installed package, a broadcast is sent to notify any 10813 * listeners that the package has been installed. For cleaning up a failed 10814 * installation, the broadcast is not necessary since the package's 10815 * installation wouldn't have sent the initial broadcast either 10816 * The key steps in deleting a package are 10817 * deleting the package information in internal structures like mPackages, 10818 * deleting the packages base directories through installd 10819 * updating mSettings to reflect current status 10820 * persisting settings for later use 10821 * sending a broadcast if necessary 10822 */ 10823 private int deletePackageX(String packageName, int userId, int flags) { 10824 final PackageRemovedInfo info = new PackageRemovedInfo(); 10825 final boolean res; 10826 10827 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10828 ? UserHandle.ALL : new UserHandle(userId); 10829 10830 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10831 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10832 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10833 } 10834 10835 boolean removedForAllUsers = false; 10836 boolean systemUpdate = false; 10837 10838 // for the uninstall-updates case and restricted profiles, remember the per- 10839 // userhandle installed state 10840 int[] allUsers; 10841 boolean[] perUserInstalled; 10842 synchronized (mPackages) { 10843 PackageSetting ps = mSettings.mPackages.get(packageName); 10844 allUsers = sUserManager.getUserIds(); 10845 perUserInstalled = new boolean[allUsers.length]; 10846 for (int i = 0; i < allUsers.length; i++) { 10847 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10848 } 10849 } 10850 10851 synchronized (mInstallLock) { 10852 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10853 res = deletePackageLI(packageName, removeForUser, 10854 true, allUsers, perUserInstalled, 10855 flags | REMOVE_CHATTY, info, true); 10856 systemUpdate = info.isRemovedPackageSystemUpdate; 10857 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10858 removedForAllUsers = true; 10859 } 10860 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10861 + " removedForAllUsers=" + removedForAllUsers); 10862 } 10863 10864 if (res) { 10865 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10866 10867 // If the removed package was a system update, the old system package 10868 // was re-enabled; we need to broadcast this information 10869 if (systemUpdate) { 10870 Bundle extras = new Bundle(1); 10871 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10872 ? info.removedAppId : info.uid); 10873 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10874 10875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10876 extras, null, null, null); 10877 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10878 extras, null, null, null); 10879 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10880 null, packageName, null, null); 10881 } 10882 } 10883 // Force a gc here. 10884 Runtime.getRuntime().gc(); 10885 // Delete the resources here after sending the broadcast to let 10886 // other processes clean up before deleting resources. 10887 if (info.args != null) { 10888 synchronized (mInstallLock) { 10889 info.args.doPostDeleteLI(true); 10890 } 10891 } 10892 10893 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10894 } 10895 10896 static class PackageRemovedInfo { 10897 String removedPackage; 10898 int uid = -1; 10899 int removedAppId = -1; 10900 int[] removedUsers = null; 10901 boolean isRemovedPackageSystemUpdate = false; 10902 // Clean up resources deleted packages. 10903 InstallArgs args = null; 10904 10905 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10906 Bundle extras = new Bundle(1); 10907 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10908 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10909 if (replacing) { 10910 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10911 } 10912 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10913 if (removedPackage != null) { 10914 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10915 extras, null, null, removedUsers); 10916 if (fullRemove && !replacing) { 10917 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10918 extras, null, null, removedUsers); 10919 } 10920 } 10921 if (removedAppId >= 0) { 10922 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10923 removedUsers); 10924 } 10925 } 10926 } 10927 10928 /* 10929 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10930 * flag is not set, the data directory is removed as well. 10931 * make sure this flag is set for partially installed apps. If not its meaningless to 10932 * delete a partially installed application. 10933 */ 10934 private void removePackageDataLI(PackageSetting ps, 10935 int[] allUserHandles, boolean[] perUserInstalled, 10936 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10937 String packageName = ps.name; 10938 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10939 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10940 // Retrieve object to delete permissions for shared user later on 10941 final PackageSetting deletedPs; 10942 // reader 10943 synchronized (mPackages) { 10944 deletedPs = mSettings.mPackages.get(packageName); 10945 if (outInfo != null) { 10946 outInfo.removedPackage = packageName; 10947 outInfo.removedUsers = deletedPs != null 10948 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10949 : null; 10950 } 10951 } 10952 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10953 removeDataDirsLI(packageName); 10954 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10955 } 10956 // writer 10957 synchronized (mPackages) { 10958 if (deletedPs != null) { 10959 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10960 if (outInfo != null) { 10961 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10962 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10963 } 10964 if (deletedPs != null) { 10965 updatePermissionsLPw(deletedPs.name, null, 0); 10966 if (deletedPs.sharedUser != null) { 10967 // remove permissions associated with package 10968 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10969 } 10970 } 10971 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10972 } 10973 // make sure to preserve per-user disabled state if this removal was just 10974 // a downgrade of a system app to the factory package 10975 if (allUserHandles != null && perUserInstalled != null) { 10976 if (DEBUG_REMOVE) { 10977 Slog.d(TAG, "Propagating install state across downgrade"); 10978 } 10979 for (int i = 0; i < allUserHandles.length; i++) { 10980 if (DEBUG_REMOVE) { 10981 Slog.d(TAG, " user " + allUserHandles[i] 10982 + " => " + perUserInstalled[i]); 10983 } 10984 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10985 } 10986 } 10987 } 10988 // can downgrade to reader 10989 if (writeSettings) { 10990 // Save settings now 10991 mSettings.writeLPr(); 10992 } 10993 } 10994 if (outInfo != null) { 10995 // A user ID was deleted here. Go through all users and remove it 10996 // from KeyStore. 10997 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10998 } 10999 } 11000 11001 static boolean locationIsPrivileged(File path) { 11002 try { 11003 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11004 .getCanonicalPath(); 11005 return path.getCanonicalPath().startsWith(privilegedAppDir); 11006 } catch (IOException e) { 11007 Slog.e(TAG, "Unable to access code path " + path); 11008 } 11009 return false; 11010 } 11011 11012 /* 11013 * Tries to delete system package. 11014 */ 11015 private boolean deleteSystemPackageLI(PackageSetting newPs, 11016 int[] allUserHandles, boolean[] perUserInstalled, 11017 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11018 final boolean applyUserRestrictions 11019 = (allUserHandles != null) && (perUserInstalled != null); 11020 PackageSetting disabledPs = null; 11021 // Confirm if the system package has been updated 11022 // An updated system app can be deleted. This will also have to restore 11023 // the system pkg from system partition 11024 // reader 11025 synchronized (mPackages) { 11026 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11027 } 11028 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11029 + " disabledPs=" + disabledPs); 11030 if (disabledPs == null) { 11031 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11032 return false; 11033 } else if (DEBUG_REMOVE) { 11034 Slog.d(TAG, "Deleting system pkg from data partition"); 11035 } 11036 if (DEBUG_REMOVE) { 11037 if (applyUserRestrictions) { 11038 Slog.d(TAG, "Remembering install states:"); 11039 for (int i = 0; i < allUserHandles.length; i++) { 11040 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11041 } 11042 } 11043 } 11044 // Delete the updated package 11045 outInfo.isRemovedPackageSystemUpdate = true; 11046 if (disabledPs.versionCode < newPs.versionCode) { 11047 // Delete data for downgrades 11048 flags &= ~PackageManager.DELETE_KEEP_DATA; 11049 } else { 11050 // Preserve data by setting flag 11051 flags |= PackageManager.DELETE_KEEP_DATA; 11052 } 11053 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11054 allUserHandles, perUserInstalled, outInfo, writeSettings); 11055 if (!ret) { 11056 return false; 11057 } 11058 // writer 11059 synchronized (mPackages) { 11060 // Reinstate the old system package 11061 mSettings.enableSystemPackageLPw(newPs.name); 11062 // Remove any native libraries from the upgraded package. 11063 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11064 } 11065 // Install the system package 11066 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11067 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11068 if (locationIsPrivileged(disabledPs.codePath)) { 11069 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11070 } 11071 11072 final PackageParser.Package newPkg; 11073 try { 11074 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11075 } catch (PackageManagerException e) { 11076 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11077 return false; 11078 } 11079 11080 // writer 11081 synchronized (mPackages) { 11082 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11083 updatePermissionsLPw(newPkg.packageName, newPkg, 11084 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11085 if (applyUserRestrictions) { 11086 if (DEBUG_REMOVE) { 11087 Slog.d(TAG, "Propagating install state across reinstall"); 11088 } 11089 for (int i = 0; i < allUserHandles.length; i++) { 11090 if (DEBUG_REMOVE) { 11091 Slog.d(TAG, " user " + allUserHandles[i] 11092 + " => " + perUserInstalled[i]); 11093 } 11094 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11095 } 11096 // Regardless of writeSettings we need to ensure that this restriction 11097 // state propagation is persisted 11098 mSettings.writeAllUsersPackageRestrictionsLPr(); 11099 } 11100 // can downgrade to reader here 11101 if (writeSettings) { 11102 mSettings.writeLPr(); 11103 } 11104 } 11105 return true; 11106 } 11107 11108 private boolean deleteInstalledPackageLI(PackageSetting ps, 11109 boolean deleteCodeAndResources, int flags, 11110 int[] allUserHandles, boolean[] perUserInstalled, 11111 PackageRemovedInfo outInfo, boolean writeSettings) { 11112 if (outInfo != null) { 11113 outInfo.uid = ps.appId; 11114 } 11115 11116 // Delete package data from internal structures and also remove data if flag is set 11117 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11118 11119 // Delete application code and resources 11120 if (deleteCodeAndResources && (outInfo != null)) { 11121 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11122 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11123 getAppDexInstructionSets(ps)); 11124 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11125 } 11126 return true; 11127 } 11128 11129 @Override 11130 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11131 int userId) { 11132 mContext.enforceCallingOrSelfPermission( 11133 android.Manifest.permission.DELETE_PACKAGES, null); 11134 synchronized (mPackages) { 11135 PackageSetting ps = mSettings.mPackages.get(packageName); 11136 if (ps == null) { 11137 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11138 return false; 11139 } 11140 if (!ps.getInstalled(userId)) { 11141 // Can't block uninstall for an app that is not installed or enabled. 11142 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11143 return false; 11144 } 11145 ps.setBlockUninstall(blockUninstall, userId); 11146 mSettings.writePackageRestrictionsLPr(userId); 11147 } 11148 return true; 11149 } 11150 11151 @Override 11152 public boolean getBlockUninstallForUser(String packageName, int userId) { 11153 synchronized (mPackages) { 11154 PackageSetting ps = mSettings.mPackages.get(packageName); 11155 if (ps == null) { 11156 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11157 return false; 11158 } 11159 return ps.getBlockUninstall(userId); 11160 } 11161 } 11162 11163 /* 11164 * This method handles package deletion in general 11165 */ 11166 private boolean deletePackageLI(String packageName, UserHandle user, 11167 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11168 int flags, PackageRemovedInfo outInfo, 11169 boolean writeSettings) { 11170 if (packageName == null) { 11171 Slog.w(TAG, "Attempt to delete null packageName."); 11172 return false; 11173 } 11174 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11175 PackageSetting ps; 11176 boolean dataOnly = false; 11177 int removeUser = -1; 11178 int appId = -1; 11179 synchronized (mPackages) { 11180 ps = mSettings.mPackages.get(packageName); 11181 if (ps == null) { 11182 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11183 return false; 11184 } 11185 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11186 && user.getIdentifier() != UserHandle.USER_ALL) { 11187 // The caller is asking that the package only be deleted for a single 11188 // user. To do this, we just mark its uninstalled state and delete 11189 // its data. If this is a system app, we only allow this to happen if 11190 // they have set the special DELETE_SYSTEM_APP which requests different 11191 // semantics than normal for uninstalling system apps. 11192 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11193 ps.setUserState(user.getIdentifier(), 11194 COMPONENT_ENABLED_STATE_DEFAULT, 11195 false, //installed 11196 true, //stopped 11197 true, //notLaunched 11198 false, //hidden 11199 null, null, null, 11200 false // blockUninstall 11201 ); 11202 if (!isSystemApp(ps)) { 11203 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11204 // Other user still have this package installed, so all 11205 // we need to do is clear this user's data and save that 11206 // it is uninstalled. 11207 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11208 removeUser = user.getIdentifier(); 11209 appId = ps.appId; 11210 mSettings.writePackageRestrictionsLPr(removeUser); 11211 } else { 11212 // We need to set it back to 'installed' so the uninstall 11213 // broadcasts will be sent correctly. 11214 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11215 ps.setInstalled(true, user.getIdentifier()); 11216 } 11217 } else { 11218 // This is a system app, so we assume that the 11219 // other users still have this package installed, so all 11220 // we need to do is clear this user's data and save that 11221 // it is uninstalled. 11222 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11223 removeUser = user.getIdentifier(); 11224 appId = ps.appId; 11225 mSettings.writePackageRestrictionsLPr(removeUser); 11226 } 11227 } 11228 } 11229 11230 if (removeUser >= 0) { 11231 // From above, we determined that we are deleting this only 11232 // for a single user. Continue the work here. 11233 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11234 if (outInfo != null) { 11235 outInfo.removedPackage = packageName; 11236 outInfo.removedAppId = appId; 11237 outInfo.removedUsers = new int[] {removeUser}; 11238 } 11239 mInstaller.clearUserData(packageName, removeUser); 11240 removeKeystoreDataIfNeeded(removeUser, appId); 11241 schedulePackageCleaning(packageName, removeUser, false); 11242 return true; 11243 } 11244 11245 if (dataOnly) { 11246 // Delete application data first 11247 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11248 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11249 return true; 11250 } 11251 11252 boolean ret = false; 11253 if (isSystemApp(ps)) { 11254 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11255 // When an updated system application is deleted we delete the existing resources as well and 11256 // fall back to existing code in system partition 11257 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11258 flags, outInfo, writeSettings); 11259 } else { 11260 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11261 // Kill application pre-emptively especially for apps on sd. 11262 killApplication(packageName, ps.appId, "uninstall pkg"); 11263 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11264 allUserHandles, perUserInstalled, 11265 outInfo, writeSettings); 11266 } 11267 11268 return ret; 11269 } 11270 11271 private final class ClearStorageConnection implements ServiceConnection { 11272 IMediaContainerService mContainerService; 11273 11274 @Override 11275 public void onServiceConnected(ComponentName name, IBinder service) { 11276 synchronized (this) { 11277 mContainerService = IMediaContainerService.Stub.asInterface(service); 11278 notifyAll(); 11279 } 11280 } 11281 11282 @Override 11283 public void onServiceDisconnected(ComponentName name) { 11284 } 11285 } 11286 11287 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11288 final boolean mounted; 11289 if (Environment.isExternalStorageEmulated()) { 11290 mounted = true; 11291 } else { 11292 final String status = Environment.getExternalStorageState(); 11293 11294 mounted = status.equals(Environment.MEDIA_MOUNTED) 11295 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11296 } 11297 11298 if (!mounted) { 11299 return; 11300 } 11301 11302 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11303 int[] users; 11304 if (userId == UserHandle.USER_ALL) { 11305 users = sUserManager.getUserIds(); 11306 } else { 11307 users = new int[] { userId }; 11308 } 11309 final ClearStorageConnection conn = new ClearStorageConnection(); 11310 if (mContext.bindServiceAsUser( 11311 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11312 try { 11313 for (int curUser : users) { 11314 long timeout = SystemClock.uptimeMillis() + 5000; 11315 synchronized (conn) { 11316 long now = SystemClock.uptimeMillis(); 11317 while (conn.mContainerService == null && now < timeout) { 11318 try { 11319 conn.wait(timeout - now); 11320 } catch (InterruptedException e) { 11321 } 11322 } 11323 } 11324 if (conn.mContainerService == null) { 11325 return; 11326 } 11327 11328 final UserEnvironment userEnv = new UserEnvironment(curUser); 11329 clearDirectory(conn.mContainerService, 11330 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11331 if (allData) { 11332 clearDirectory(conn.mContainerService, 11333 userEnv.buildExternalStorageAppDataDirs(packageName)); 11334 clearDirectory(conn.mContainerService, 11335 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11336 } 11337 } 11338 } finally { 11339 mContext.unbindService(conn); 11340 } 11341 } 11342 } 11343 11344 @Override 11345 public void clearApplicationUserData(final String packageName, 11346 final IPackageDataObserver observer, final int userId) { 11347 mContext.enforceCallingOrSelfPermission( 11348 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11349 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11350 // Queue up an async operation since the package deletion may take a little while. 11351 mHandler.post(new Runnable() { 11352 public void run() { 11353 mHandler.removeCallbacks(this); 11354 final boolean succeeded; 11355 synchronized (mInstallLock) { 11356 succeeded = clearApplicationUserDataLI(packageName, userId); 11357 } 11358 clearExternalStorageDataSync(packageName, userId, true); 11359 if (succeeded) { 11360 // invoke DeviceStorageMonitor's update method to clear any notifications 11361 DeviceStorageMonitorInternal 11362 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11363 if (dsm != null) { 11364 dsm.checkMemory(); 11365 } 11366 } 11367 if(observer != null) { 11368 try { 11369 observer.onRemoveCompleted(packageName, succeeded); 11370 } catch (RemoteException e) { 11371 Log.i(TAG, "Observer no longer exists."); 11372 } 11373 } //end if observer 11374 } //end run 11375 }); 11376 } 11377 11378 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11379 if (packageName == null) { 11380 Slog.w(TAG, "Attempt to delete null packageName."); 11381 return false; 11382 } 11383 11384 // Try finding details about the requested package 11385 PackageParser.Package pkg; 11386 synchronized (mPackages) { 11387 pkg = mPackages.get(packageName); 11388 if (pkg == null) { 11389 final PackageSetting ps = mSettings.mPackages.get(packageName); 11390 if (ps != null) { 11391 pkg = ps.pkg; 11392 } 11393 } 11394 } 11395 11396 if (pkg == null) { 11397 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11398 } 11399 11400 // Always delete data directories for package, even if we found no other 11401 // record of app. This helps users recover from UID mismatches without 11402 // resorting to a full data wipe. 11403 int retCode = mInstaller.clearUserData(packageName, userId); 11404 if (retCode < 0) { 11405 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11406 return false; 11407 } 11408 11409 if (pkg == null) { 11410 return false; 11411 } 11412 11413 if (pkg != null && pkg.applicationInfo != null) { 11414 final int appId = pkg.applicationInfo.uid; 11415 removeKeystoreDataIfNeeded(userId, appId); 11416 } 11417 11418 // Create a native library symlink only if we have native libraries 11419 // and if the native libraries are 32 bit libraries. We do not provide 11420 // this symlink for 64 bit libraries. 11421 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11422 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11423 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11424 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11425 Slog.w(TAG, "Failed linking native library dir"); 11426 return false; 11427 } 11428 } 11429 11430 return true; 11431 } 11432 11433 /** 11434 * Remove entries from the keystore daemon. Will only remove it if the 11435 * {@code appId} is valid. 11436 */ 11437 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11438 if (appId < 0) { 11439 return; 11440 } 11441 11442 final KeyStore keyStore = KeyStore.getInstance(); 11443 if (keyStore != null) { 11444 if (userId == UserHandle.USER_ALL) { 11445 for (final int individual : sUserManager.getUserIds()) { 11446 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11447 } 11448 } else { 11449 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11450 } 11451 } else { 11452 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11453 } 11454 } 11455 11456 @Override 11457 public void deleteApplicationCacheFiles(final String packageName, 11458 final IPackageDataObserver observer) { 11459 mContext.enforceCallingOrSelfPermission( 11460 android.Manifest.permission.DELETE_CACHE_FILES, null); 11461 // Queue up an async operation since the package deletion may take a little while. 11462 final int userId = UserHandle.getCallingUserId(); 11463 mHandler.post(new Runnable() { 11464 public void run() { 11465 mHandler.removeCallbacks(this); 11466 final boolean succeded; 11467 synchronized (mInstallLock) { 11468 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11469 } 11470 clearExternalStorageDataSync(packageName, userId, false); 11471 if(observer != null) { 11472 try { 11473 observer.onRemoveCompleted(packageName, succeded); 11474 } catch (RemoteException e) { 11475 Log.i(TAG, "Observer no longer exists."); 11476 } 11477 } //end if observer 11478 } //end run 11479 }); 11480 } 11481 11482 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11483 if (packageName == null) { 11484 Slog.w(TAG, "Attempt to delete null packageName."); 11485 return false; 11486 } 11487 PackageParser.Package p; 11488 synchronized (mPackages) { 11489 p = mPackages.get(packageName); 11490 } 11491 if (p == null) { 11492 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11493 return false; 11494 } 11495 final ApplicationInfo applicationInfo = p.applicationInfo; 11496 if (applicationInfo == null) { 11497 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11498 return false; 11499 } 11500 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11501 if (retCode < 0) { 11502 Slog.w(TAG, "Couldn't remove cache files for package: " 11503 + packageName + " u" + userId); 11504 return false; 11505 } 11506 return true; 11507 } 11508 11509 @Override 11510 public void getPackageSizeInfo(final String packageName, int userHandle, 11511 final IPackageStatsObserver observer) { 11512 mContext.enforceCallingOrSelfPermission( 11513 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11514 if (packageName == null) { 11515 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11516 } 11517 11518 PackageStats stats = new PackageStats(packageName, userHandle); 11519 11520 /* 11521 * Queue up an async operation since the package measurement may take a 11522 * little while. 11523 */ 11524 Message msg = mHandler.obtainMessage(INIT_COPY); 11525 msg.obj = new MeasureParams(stats, observer); 11526 mHandler.sendMessage(msg); 11527 } 11528 11529 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11530 PackageStats pStats) { 11531 if (packageName == null) { 11532 Slog.w(TAG, "Attempt to get size of null packageName."); 11533 return false; 11534 } 11535 PackageParser.Package p; 11536 boolean dataOnly = false; 11537 String libDirRoot = null; 11538 String asecPath = null; 11539 PackageSetting ps = null; 11540 synchronized (mPackages) { 11541 p = mPackages.get(packageName); 11542 ps = mSettings.mPackages.get(packageName); 11543 if(p == null) { 11544 dataOnly = true; 11545 if((ps == null) || (ps.pkg == null)) { 11546 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11547 return false; 11548 } 11549 p = ps.pkg; 11550 } 11551 if (ps != null) { 11552 libDirRoot = ps.legacyNativeLibraryPathString; 11553 } 11554 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11555 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11556 if (secureContainerId != null) { 11557 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11558 } 11559 } 11560 } 11561 String publicSrcDir = null; 11562 if(!dataOnly) { 11563 final ApplicationInfo applicationInfo = p.applicationInfo; 11564 if (applicationInfo == null) { 11565 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11566 return false; 11567 } 11568 if (isForwardLocked(p)) { 11569 publicSrcDir = applicationInfo.getBaseResourcePath(); 11570 } 11571 } 11572 // TODO: extend to measure size of split APKs 11573 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11574 // not just the first level. 11575 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11576 // just the primary. 11577 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11578 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11579 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11580 if (res < 0) { 11581 return false; 11582 } 11583 11584 // Fix-up for forward-locked applications in ASEC containers. 11585 if (!isExternal(p)) { 11586 pStats.codeSize += pStats.externalCodeSize; 11587 pStats.externalCodeSize = 0L; 11588 } 11589 11590 return true; 11591 } 11592 11593 11594 @Override 11595 public void addPackageToPreferred(String packageName) { 11596 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11597 } 11598 11599 @Override 11600 public void removePackageFromPreferred(String packageName) { 11601 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11602 } 11603 11604 @Override 11605 public List<PackageInfo> getPreferredPackages(int flags) { 11606 return new ArrayList<PackageInfo>(); 11607 } 11608 11609 private int getUidTargetSdkVersionLockedLPr(int uid) { 11610 Object obj = mSettings.getUserIdLPr(uid); 11611 if (obj instanceof SharedUserSetting) { 11612 final SharedUserSetting sus = (SharedUserSetting) obj; 11613 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11614 final Iterator<PackageSetting> it = sus.packages.iterator(); 11615 while (it.hasNext()) { 11616 final PackageSetting ps = it.next(); 11617 if (ps.pkg != null) { 11618 int v = ps.pkg.applicationInfo.targetSdkVersion; 11619 if (v < vers) vers = v; 11620 } 11621 } 11622 return vers; 11623 } else if (obj instanceof PackageSetting) { 11624 final PackageSetting ps = (PackageSetting) obj; 11625 if (ps.pkg != null) { 11626 return ps.pkg.applicationInfo.targetSdkVersion; 11627 } 11628 } 11629 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11630 } 11631 11632 @Override 11633 public void addPreferredActivity(IntentFilter filter, int match, 11634 ComponentName[] set, ComponentName activity, int userId) { 11635 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11636 "Adding preferred"); 11637 } 11638 11639 private void addPreferredActivityInternal(IntentFilter filter, int match, 11640 ComponentName[] set, ComponentName activity, boolean always, int userId, 11641 String opname) { 11642 // writer 11643 int callingUid = Binder.getCallingUid(); 11644 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11645 if (filter.countActions() == 0) { 11646 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11647 return; 11648 } 11649 synchronized (mPackages) { 11650 if (mContext.checkCallingOrSelfPermission( 11651 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11652 != PackageManager.PERMISSION_GRANTED) { 11653 if (getUidTargetSdkVersionLockedLPr(callingUid) 11654 < Build.VERSION_CODES.FROYO) { 11655 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11656 + callingUid); 11657 return; 11658 } 11659 mContext.enforceCallingOrSelfPermission( 11660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11661 } 11662 11663 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11664 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11665 + userId + ":"); 11666 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11667 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11668 scheduleWritePackageRestrictionsLocked(userId); 11669 } 11670 } 11671 11672 @Override 11673 public void replacePreferredActivity(IntentFilter filter, int match, 11674 ComponentName[] set, ComponentName activity, int userId) { 11675 if (filter.countActions() != 1) { 11676 throw new IllegalArgumentException( 11677 "replacePreferredActivity expects filter to have only 1 action."); 11678 } 11679 if (filter.countDataAuthorities() != 0 11680 || filter.countDataPaths() != 0 11681 || filter.countDataSchemes() > 1 11682 || filter.countDataTypes() != 0) { 11683 throw new IllegalArgumentException( 11684 "replacePreferredActivity expects filter to have no data authorities, " + 11685 "paths, or types; and at most one scheme."); 11686 } 11687 11688 final int callingUid = Binder.getCallingUid(); 11689 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11690 synchronized (mPackages) { 11691 if (mContext.checkCallingOrSelfPermission( 11692 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11693 != PackageManager.PERMISSION_GRANTED) { 11694 if (getUidTargetSdkVersionLockedLPr(callingUid) 11695 < Build.VERSION_CODES.FROYO) { 11696 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11697 + Binder.getCallingUid()); 11698 return; 11699 } 11700 mContext.enforceCallingOrSelfPermission( 11701 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11702 } 11703 11704 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11705 if (pir != null) { 11706 // Get all of the existing entries that exactly match this filter. 11707 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11708 if (existing != null && existing.size() == 1) { 11709 PreferredActivity cur = existing.get(0); 11710 if (DEBUG_PREFERRED) { 11711 Slog.i(TAG, "Checking replace of preferred:"); 11712 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11713 if (!cur.mPref.mAlways) { 11714 Slog.i(TAG, " -- CUR; not mAlways!"); 11715 } else { 11716 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11717 Slog.i(TAG, " -- CUR: mSet=" 11718 + Arrays.toString(cur.mPref.mSetComponents)); 11719 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11720 Slog.i(TAG, " -- NEW: mMatch=" 11721 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11722 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11723 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11724 } 11725 } 11726 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11727 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11728 && cur.mPref.sameSet(set)) { 11729 // Setting the preferred activity to what it happens to be already 11730 if (DEBUG_PREFERRED) { 11731 Slog.i(TAG, "Replacing with same preferred activity " 11732 + cur.mPref.mShortComponent + " for user " 11733 + userId + ":"); 11734 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11735 } 11736 return; 11737 } 11738 } 11739 11740 if (existing != null) { 11741 if (DEBUG_PREFERRED) { 11742 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11743 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11744 } 11745 for (int i = 0; i < existing.size(); i++) { 11746 PreferredActivity pa = existing.get(i); 11747 if (DEBUG_PREFERRED) { 11748 Slog.i(TAG, "Removing existing preferred activity " 11749 + pa.mPref.mComponent + ":"); 11750 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11751 } 11752 pir.removeFilter(pa); 11753 } 11754 } 11755 } 11756 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11757 "Replacing preferred"); 11758 } 11759 } 11760 11761 @Override 11762 public void clearPackagePreferredActivities(String packageName) { 11763 final int uid = Binder.getCallingUid(); 11764 // writer 11765 synchronized (mPackages) { 11766 PackageParser.Package pkg = mPackages.get(packageName); 11767 if (pkg == null || pkg.applicationInfo.uid != uid) { 11768 if (mContext.checkCallingOrSelfPermission( 11769 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11770 != PackageManager.PERMISSION_GRANTED) { 11771 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11772 < Build.VERSION_CODES.FROYO) { 11773 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11774 + Binder.getCallingUid()); 11775 return; 11776 } 11777 mContext.enforceCallingOrSelfPermission( 11778 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11779 } 11780 } 11781 11782 int user = UserHandle.getCallingUserId(); 11783 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11784 scheduleWritePackageRestrictionsLocked(user); 11785 } 11786 } 11787 } 11788 11789 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11790 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11791 ArrayList<PreferredActivity> removed = null; 11792 boolean changed = false; 11793 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11794 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11795 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11796 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11797 continue; 11798 } 11799 Iterator<PreferredActivity> it = pir.filterIterator(); 11800 while (it.hasNext()) { 11801 PreferredActivity pa = it.next(); 11802 // Mark entry for removal only if it matches the package name 11803 // and the entry is of type "always". 11804 if (packageName == null || 11805 (pa.mPref.mComponent.getPackageName().equals(packageName) 11806 && pa.mPref.mAlways)) { 11807 if (removed == null) { 11808 removed = new ArrayList<PreferredActivity>(); 11809 } 11810 removed.add(pa); 11811 } 11812 } 11813 if (removed != null) { 11814 for (int j=0; j<removed.size(); j++) { 11815 PreferredActivity pa = removed.get(j); 11816 pir.removeFilter(pa); 11817 } 11818 changed = true; 11819 } 11820 } 11821 return changed; 11822 } 11823 11824 @Override 11825 public void resetPreferredActivities(int userId) { 11826 /* TODO: Actually use userId. Why is it being passed in? */ 11827 mContext.enforceCallingOrSelfPermission( 11828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11829 // writer 11830 synchronized (mPackages) { 11831 int user = UserHandle.getCallingUserId(); 11832 clearPackagePreferredActivitiesLPw(null, user); 11833 mSettings.readDefaultPreferredAppsLPw(this, user); 11834 scheduleWritePackageRestrictionsLocked(user); 11835 } 11836 } 11837 11838 @Override 11839 public int getPreferredActivities(List<IntentFilter> outFilters, 11840 List<ComponentName> outActivities, String packageName) { 11841 11842 int num = 0; 11843 final int userId = UserHandle.getCallingUserId(); 11844 // reader 11845 synchronized (mPackages) { 11846 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11847 if (pir != null) { 11848 final Iterator<PreferredActivity> it = pir.filterIterator(); 11849 while (it.hasNext()) { 11850 final PreferredActivity pa = it.next(); 11851 if (packageName == null 11852 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11853 && pa.mPref.mAlways)) { 11854 if (outFilters != null) { 11855 outFilters.add(new IntentFilter(pa)); 11856 } 11857 if (outActivities != null) { 11858 outActivities.add(pa.mPref.mComponent); 11859 } 11860 } 11861 } 11862 } 11863 } 11864 11865 return num; 11866 } 11867 11868 @Override 11869 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11870 int userId) { 11871 int callingUid = Binder.getCallingUid(); 11872 if (callingUid != Process.SYSTEM_UID) { 11873 throw new SecurityException( 11874 "addPersistentPreferredActivity can only be run by the system"); 11875 } 11876 if (filter.countActions() == 0) { 11877 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11878 return; 11879 } 11880 synchronized (mPackages) { 11881 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11882 " :"); 11883 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11884 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11885 new PersistentPreferredActivity(filter, activity)); 11886 scheduleWritePackageRestrictionsLocked(userId); 11887 } 11888 } 11889 11890 @Override 11891 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11892 int callingUid = Binder.getCallingUid(); 11893 if (callingUid != Process.SYSTEM_UID) { 11894 throw new SecurityException( 11895 "clearPackagePersistentPreferredActivities can only be run by the system"); 11896 } 11897 ArrayList<PersistentPreferredActivity> removed = null; 11898 boolean changed = false; 11899 synchronized (mPackages) { 11900 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11901 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11902 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11903 .valueAt(i); 11904 if (userId != thisUserId) { 11905 continue; 11906 } 11907 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11908 while (it.hasNext()) { 11909 PersistentPreferredActivity ppa = it.next(); 11910 // Mark entry for removal only if it matches the package name. 11911 if (ppa.mComponent.getPackageName().equals(packageName)) { 11912 if (removed == null) { 11913 removed = new ArrayList<PersistentPreferredActivity>(); 11914 } 11915 removed.add(ppa); 11916 } 11917 } 11918 if (removed != null) { 11919 for (int j=0; j<removed.size(); j++) { 11920 PersistentPreferredActivity ppa = removed.get(j); 11921 ppir.removeFilter(ppa); 11922 } 11923 changed = true; 11924 } 11925 } 11926 11927 if (changed) { 11928 scheduleWritePackageRestrictionsLocked(userId); 11929 } 11930 } 11931 } 11932 11933 @Override 11934 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11935 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11936 mContext.enforceCallingOrSelfPermission( 11937 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11938 int callingUid = Binder.getCallingUid(); 11939 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11940 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11941 if (intentFilter.countActions() == 0) { 11942 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11943 return; 11944 } 11945 synchronized (mPackages) { 11946 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11947 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11948 CrossProfileIntentResolver resolver = 11949 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11950 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11951 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11952 if (existing != null) { 11953 int size = existing.size(); 11954 for (int i = 0; i < size; i++) { 11955 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11956 return; 11957 } 11958 } 11959 } 11960 resolver.addFilter(newFilter); 11961 scheduleWritePackageRestrictionsLocked(sourceUserId); 11962 } 11963 } 11964 11965 @Override 11966 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11967 int ownerUserId) { 11968 mContext.enforceCallingOrSelfPermission( 11969 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11970 int callingUid = Binder.getCallingUid(); 11971 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11972 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11973 int callingUserId = UserHandle.getUserId(callingUid); 11974 synchronized (mPackages) { 11975 CrossProfileIntentResolver resolver = 11976 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11977 ArraySet<CrossProfileIntentFilter> set = 11978 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11979 for (CrossProfileIntentFilter filter : set) { 11980 if (filter.getOwnerPackage().equals(ownerPackage) 11981 && filter.getOwnerUserId() == callingUserId) { 11982 resolver.removeFilter(filter); 11983 } 11984 } 11985 scheduleWritePackageRestrictionsLocked(sourceUserId); 11986 } 11987 } 11988 11989 // Enforcing that callingUid is owning pkg on userId 11990 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11991 // The system owns everything. 11992 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11993 return; 11994 } 11995 int callingUserId = UserHandle.getUserId(callingUid); 11996 if (callingUserId != userId) { 11997 throw new SecurityException("calling uid " + callingUid 11998 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11999 + callingUserId); 12000 } 12001 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12002 if (pi == null) { 12003 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12004 + callingUserId); 12005 } 12006 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12007 throw new SecurityException("Calling uid " + callingUid 12008 + " does not own package " + pkg); 12009 } 12010 } 12011 12012 @Override 12013 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12014 Intent intent = new Intent(Intent.ACTION_MAIN); 12015 intent.addCategory(Intent.CATEGORY_HOME); 12016 12017 final int callingUserId = UserHandle.getCallingUserId(); 12018 List<ResolveInfo> list = queryIntentActivities(intent, null, 12019 PackageManager.GET_META_DATA, callingUserId); 12020 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12021 true, false, false, callingUserId); 12022 12023 allHomeCandidates.clear(); 12024 if (list != null) { 12025 for (ResolveInfo ri : list) { 12026 allHomeCandidates.add(ri); 12027 } 12028 } 12029 return (preferred == null || preferred.activityInfo == null) 12030 ? null 12031 : new ComponentName(preferred.activityInfo.packageName, 12032 preferred.activityInfo.name); 12033 } 12034 12035 @Override 12036 public void setApplicationEnabledSetting(String appPackageName, 12037 int newState, int flags, int userId, String callingPackage) { 12038 if (!sUserManager.exists(userId)) return; 12039 if (callingPackage == null) { 12040 callingPackage = Integer.toString(Binder.getCallingUid()); 12041 } 12042 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12043 } 12044 12045 @Override 12046 public void setComponentEnabledSetting(ComponentName componentName, 12047 int newState, int flags, int userId) { 12048 if (!sUserManager.exists(userId)) return; 12049 setEnabledSetting(componentName.getPackageName(), 12050 componentName.getClassName(), newState, flags, userId, null); 12051 } 12052 12053 private void setEnabledSetting(final String packageName, String className, int newState, 12054 final int flags, int userId, String callingPackage) { 12055 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12056 || newState == COMPONENT_ENABLED_STATE_ENABLED 12057 || newState == COMPONENT_ENABLED_STATE_DISABLED 12058 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12059 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12060 throw new IllegalArgumentException("Invalid new component state: " 12061 + newState); 12062 } 12063 PackageSetting pkgSetting; 12064 final int uid = Binder.getCallingUid(); 12065 final int permission = mContext.checkCallingOrSelfPermission( 12066 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12067 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12068 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12069 boolean sendNow = false; 12070 boolean isApp = (className == null); 12071 String componentName = isApp ? packageName : className; 12072 int packageUid = -1; 12073 ArrayList<String> components; 12074 12075 // writer 12076 synchronized (mPackages) { 12077 pkgSetting = mSettings.mPackages.get(packageName); 12078 if (pkgSetting == null) { 12079 if (className == null) { 12080 throw new IllegalArgumentException( 12081 "Unknown package: " + packageName); 12082 } 12083 throw new IllegalArgumentException( 12084 "Unknown component: " + packageName 12085 + "/" + className); 12086 } 12087 // Allow root and verify that userId is not being specified by a different user 12088 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12089 throw new SecurityException( 12090 "Permission Denial: attempt to change component state from pid=" 12091 + Binder.getCallingPid() 12092 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12093 } 12094 if (className == null) { 12095 // We're dealing with an application/package level state change 12096 if (pkgSetting.getEnabled(userId) == newState) { 12097 // Nothing to do 12098 return; 12099 } 12100 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12101 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12102 // Don't care about who enables an app. 12103 callingPackage = null; 12104 } 12105 pkgSetting.setEnabled(newState, userId, callingPackage); 12106 // pkgSetting.pkg.mSetEnabled = newState; 12107 } else { 12108 // We're dealing with a component level state change 12109 // First, verify that this is a valid class name. 12110 PackageParser.Package pkg = pkgSetting.pkg; 12111 if (pkg == null || !pkg.hasComponentClassName(className)) { 12112 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12113 throw new IllegalArgumentException("Component class " + className 12114 + " does not exist in " + packageName); 12115 } else { 12116 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12117 + className + " does not exist in " + packageName); 12118 } 12119 } 12120 switch (newState) { 12121 case COMPONENT_ENABLED_STATE_ENABLED: 12122 if (!pkgSetting.enableComponentLPw(className, userId)) { 12123 return; 12124 } 12125 break; 12126 case COMPONENT_ENABLED_STATE_DISABLED: 12127 if (!pkgSetting.disableComponentLPw(className, userId)) { 12128 return; 12129 } 12130 break; 12131 case COMPONENT_ENABLED_STATE_DEFAULT: 12132 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12133 return; 12134 } 12135 break; 12136 default: 12137 Slog.e(TAG, "Invalid new component state: " + newState); 12138 return; 12139 } 12140 } 12141 mSettings.writePackageRestrictionsLPr(userId); 12142 components = mPendingBroadcasts.get(userId, packageName); 12143 final boolean newPackage = components == null; 12144 if (newPackage) { 12145 components = new ArrayList<String>(); 12146 } 12147 if (!components.contains(componentName)) { 12148 components.add(componentName); 12149 } 12150 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12151 sendNow = true; 12152 // Purge entry from pending broadcast list if another one exists already 12153 // since we are sending one right away. 12154 mPendingBroadcasts.remove(userId, packageName); 12155 } else { 12156 if (newPackage) { 12157 mPendingBroadcasts.put(userId, packageName, components); 12158 } 12159 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12160 // Schedule a message 12161 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12162 } 12163 } 12164 } 12165 12166 long callingId = Binder.clearCallingIdentity(); 12167 try { 12168 if (sendNow) { 12169 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12170 sendPackageChangedBroadcast(packageName, 12171 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12172 } 12173 } finally { 12174 Binder.restoreCallingIdentity(callingId); 12175 } 12176 } 12177 12178 private void sendPackageChangedBroadcast(String packageName, 12179 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12180 if (DEBUG_INSTALL) 12181 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12182 + componentNames); 12183 Bundle extras = new Bundle(4); 12184 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12185 String nameList[] = new String[componentNames.size()]; 12186 componentNames.toArray(nameList); 12187 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12188 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12189 extras.putInt(Intent.EXTRA_UID, packageUid); 12190 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12191 new int[] {UserHandle.getUserId(packageUid)}); 12192 } 12193 12194 @Override 12195 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12196 if (!sUserManager.exists(userId)) return; 12197 final int uid = Binder.getCallingUid(); 12198 final int permission = mContext.checkCallingOrSelfPermission( 12199 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12200 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12201 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12202 // writer 12203 synchronized (mPackages) { 12204 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12205 uid, userId)) { 12206 scheduleWritePackageRestrictionsLocked(userId); 12207 } 12208 } 12209 } 12210 12211 @Override 12212 public String getInstallerPackageName(String packageName) { 12213 // reader 12214 synchronized (mPackages) { 12215 return mSettings.getInstallerPackageNameLPr(packageName); 12216 } 12217 } 12218 12219 @Override 12220 public int getApplicationEnabledSetting(String packageName, int userId) { 12221 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12222 int uid = Binder.getCallingUid(); 12223 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12224 // reader 12225 synchronized (mPackages) { 12226 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12227 } 12228 } 12229 12230 @Override 12231 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12232 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12233 int uid = Binder.getCallingUid(); 12234 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12235 // reader 12236 synchronized (mPackages) { 12237 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12238 } 12239 } 12240 12241 @Override 12242 public void enterSafeMode() { 12243 enforceSystemOrRoot("Only the system can request entering safe mode"); 12244 12245 if (!mSystemReady) { 12246 mSafeMode = true; 12247 } 12248 } 12249 12250 @Override 12251 public void systemReady() { 12252 mSystemReady = true; 12253 12254 // Read the compatibilty setting when the system is ready. 12255 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12256 mContext.getContentResolver(), 12257 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12258 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12259 if (DEBUG_SETTINGS) { 12260 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12261 } 12262 12263 synchronized (mPackages) { 12264 // Verify that all of the preferred activity components actually 12265 // exist. It is possible for applications to be updated and at 12266 // that point remove a previously declared activity component that 12267 // had been set as a preferred activity. We try to clean this up 12268 // the next time we encounter that preferred activity, but it is 12269 // possible for the user flow to never be able to return to that 12270 // situation so here we do a sanity check to make sure we haven't 12271 // left any junk around. 12272 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12273 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12274 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12275 removed.clear(); 12276 for (PreferredActivity pa : pir.filterSet()) { 12277 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12278 removed.add(pa); 12279 } 12280 } 12281 if (removed.size() > 0) { 12282 for (int r=0; r<removed.size(); r++) { 12283 PreferredActivity pa = removed.get(r); 12284 Slog.w(TAG, "Removing dangling preferred activity: " 12285 + pa.mPref.mComponent); 12286 pir.removeFilter(pa); 12287 } 12288 mSettings.writePackageRestrictionsLPr( 12289 mSettings.mPreferredActivities.keyAt(i)); 12290 } 12291 } 12292 } 12293 sUserManager.systemReady(); 12294 12295 // Kick off any messages waiting for system ready 12296 if (mPostSystemReadyMessages != null) { 12297 for (Message msg : mPostSystemReadyMessages) { 12298 msg.sendToTarget(); 12299 } 12300 mPostSystemReadyMessages = null; 12301 } 12302 } 12303 12304 @Override 12305 public boolean isSafeMode() { 12306 return mSafeMode; 12307 } 12308 12309 @Override 12310 public boolean hasSystemUidErrors() { 12311 return mHasSystemUidErrors; 12312 } 12313 12314 static String arrayToString(int[] array) { 12315 StringBuffer buf = new StringBuffer(128); 12316 buf.append('['); 12317 if (array != null) { 12318 for (int i=0; i<array.length; i++) { 12319 if (i > 0) buf.append(", "); 12320 buf.append(array[i]); 12321 } 12322 } 12323 buf.append(']'); 12324 return buf.toString(); 12325 } 12326 12327 static class DumpState { 12328 public static final int DUMP_LIBS = 1 << 0; 12329 public static final int DUMP_FEATURES = 1 << 1; 12330 public static final int DUMP_RESOLVERS = 1 << 2; 12331 public static final int DUMP_PERMISSIONS = 1 << 3; 12332 public static final int DUMP_PACKAGES = 1 << 4; 12333 public static final int DUMP_SHARED_USERS = 1 << 5; 12334 public static final int DUMP_MESSAGES = 1 << 6; 12335 public static final int DUMP_PROVIDERS = 1 << 7; 12336 public static final int DUMP_VERIFIERS = 1 << 8; 12337 public static final int DUMP_PREFERRED = 1 << 9; 12338 public static final int DUMP_PREFERRED_XML = 1 << 10; 12339 public static final int DUMP_KEYSETS = 1 << 11; 12340 public static final int DUMP_VERSION = 1 << 12; 12341 public static final int DUMP_INSTALLS = 1 << 13; 12342 12343 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12344 12345 private int mTypes; 12346 12347 private int mOptions; 12348 12349 private boolean mTitlePrinted; 12350 12351 private SharedUserSetting mSharedUser; 12352 12353 public boolean isDumping(int type) { 12354 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12355 return true; 12356 } 12357 12358 return (mTypes & type) != 0; 12359 } 12360 12361 public void setDump(int type) { 12362 mTypes |= type; 12363 } 12364 12365 public boolean isOptionEnabled(int option) { 12366 return (mOptions & option) != 0; 12367 } 12368 12369 public void setOptionEnabled(int option) { 12370 mOptions |= option; 12371 } 12372 12373 public boolean onTitlePrinted() { 12374 final boolean printed = mTitlePrinted; 12375 mTitlePrinted = true; 12376 return printed; 12377 } 12378 12379 public boolean getTitlePrinted() { 12380 return mTitlePrinted; 12381 } 12382 12383 public void setTitlePrinted(boolean enabled) { 12384 mTitlePrinted = enabled; 12385 } 12386 12387 public SharedUserSetting getSharedUser() { 12388 return mSharedUser; 12389 } 12390 12391 public void setSharedUser(SharedUserSetting user) { 12392 mSharedUser = user; 12393 } 12394 } 12395 12396 @Override 12397 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12398 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12399 != PackageManager.PERMISSION_GRANTED) { 12400 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12401 + Binder.getCallingPid() 12402 + ", uid=" + Binder.getCallingUid() 12403 + " without permission " 12404 + android.Manifest.permission.DUMP); 12405 return; 12406 } 12407 12408 DumpState dumpState = new DumpState(); 12409 boolean fullPreferred = false; 12410 boolean checkin = false; 12411 12412 String packageName = null; 12413 12414 int opti = 0; 12415 while (opti < args.length) { 12416 String opt = args[opti]; 12417 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12418 break; 12419 } 12420 opti++; 12421 12422 if ("-a".equals(opt)) { 12423 // Right now we only know how to print all. 12424 } else if ("-h".equals(opt)) { 12425 pw.println("Package manager dump options:"); 12426 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12427 pw.println(" --checkin: dump for a checkin"); 12428 pw.println(" -f: print details of intent filters"); 12429 pw.println(" -h: print this help"); 12430 pw.println(" cmd may be one of:"); 12431 pw.println(" l[ibraries]: list known shared libraries"); 12432 pw.println(" f[ibraries]: list device features"); 12433 pw.println(" k[eysets]: print known keysets"); 12434 pw.println(" r[esolvers]: dump intent resolvers"); 12435 pw.println(" perm[issions]: dump permissions"); 12436 pw.println(" pref[erred]: print preferred package settings"); 12437 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12438 pw.println(" prov[iders]: dump content providers"); 12439 pw.println(" p[ackages]: dump installed packages"); 12440 pw.println(" s[hared-users]: dump shared user IDs"); 12441 pw.println(" m[essages]: print collected runtime messages"); 12442 pw.println(" v[erifiers]: print package verifier info"); 12443 pw.println(" version: print database version info"); 12444 pw.println(" write: write current settings now"); 12445 pw.println(" <package.name>: info about given package"); 12446 pw.println(" installs: details about install sessions"); 12447 return; 12448 } else if ("--checkin".equals(opt)) { 12449 checkin = true; 12450 } else if ("-f".equals(opt)) { 12451 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12452 } else { 12453 pw.println("Unknown argument: " + opt + "; use -h for help"); 12454 } 12455 } 12456 12457 // Is the caller requesting to dump a particular piece of data? 12458 if (opti < args.length) { 12459 String cmd = args[opti]; 12460 opti++; 12461 // Is this a package name? 12462 if ("android".equals(cmd) || cmd.contains(".")) { 12463 packageName = cmd; 12464 // When dumping a single package, we always dump all of its 12465 // filter information since the amount of data will be reasonable. 12466 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12467 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12468 dumpState.setDump(DumpState.DUMP_LIBS); 12469 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12470 dumpState.setDump(DumpState.DUMP_FEATURES); 12471 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12472 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12473 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12474 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12475 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12476 dumpState.setDump(DumpState.DUMP_PREFERRED); 12477 } else if ("preferred-xml".equals(cmd)) { 12478 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12479 if (opti < args.length && "--full".equals(args[opti])) { 12480 fullPreferred = true; 12481 opti++; 12482 } 12483 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12484 dumpState.setDump(DumpState.DUMP_PACKAGES); 12485 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12486 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12487 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12488 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12489 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12490 dumpState.setDump(DumpState.DUMP_MESSAGES); 12491 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12492 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12493 } else if ("version".equals(cmd)) { 12494 dumpState.setDump(DumpState.DUMP_VERSION); 12495 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12496 dumpState.setDump(DumpState.DUMP_KEYSETS); 12497 } else if ("installs".equals(cmd)) { 12498 dumpState.setDump(DumpState.DUMP_INSTALLS); 12499 } else if ("write".equals(cmd)) { 12500 synchronized (mPackages) { 12501 mSettings.writeLPr(); 12502 pw.println("Settings written."); 12503 return; 12504 } 12505 } 12506 } 12507 12508 if (checkin) { 12509 pw.println("vers,1"); 12510 } 12511 12512 // reader 12513 synchronized (mPackages) { 12514 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12515 if (!checkin) { 12516 if (dumpState.onTitlePrinted()) 12517 pw.println(); 12518 pw.println("Database versions:"); 12519 pw.print(" SDK Version:"); 12520 pw.print(" internal="); 12521 pw.print(mSettings.mInternalSdkPlatform); 12522 pw.print(" external="); 12523 pw.println(mSettings.mExternalSdkPlatform); 12524 pw.print(" DB Version:"); 12525 pw.print(" internal="); 12526 pw.print(mSettings.mInternalDatabaseVersion); 12527 pw.print(" external="); 12528 pw.println(mSettings.mExternalDatabaseVersion); 12529 } 12530 } 12531 12532 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12533 if (!checkin) { 12534 if (dumpState.onTitlePrinted()) 12535 pw.println(); 12536 pw.println("Verifiers:"); 12537 pw.print(" Required: "); 12538 pw.print(mRequiredVerifierPackage); 12539 pw.print(" (uid="); 12540 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12541 pw.println(")"); 12542 } else if (mRequiredVerifierPackage != null) { 12543 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12544 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12545 } 12546 } 12547 12548 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12549 boolean printedHeader = false; 12550 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12551 while (it.hasNext()) { 12552 String name = it.next(); 12553 SharedLibraryEntry ent = mSharedLibraries.get(name); 12554 if (!checkin) { 12555 if (!printedHeader) { 12556 if (dumpState.onTitlePrinted()) 12557 pw.println(); 12558 pw.println("Libraries:"); 12559 printedHeader = true; 12560 } 12561 pw.print(" "); 12562 } else { 12563 pw.print("lib,"); 12564 } 12565 pw.print(name); 12566 if (!checkin) { 12567 pw.print(" -> "); 12568 } 12569 if (ent.path != null) { 12570 if (!checkin) { 12571 pw.print("(jar) "); 12572 pw.print(ent.path); 12573 } else { 12574 pw.print(",jar,"); 12575 pw.print(ent.path); 12576 } 12577 } else { 12578 if (!checkin) { 12579 pw.print("(apk) "); 12580 pw.print(ent.apk); 12581 } else { 12582 pw.print(",apk,"); 12583 pw.print(ent.apk); 12584 } 12585 } 12586 pw.println(); 12587 } 12588 } 12589 12590 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12591 if (dumpState.onTitlePrinted()) 12592 pw.println(); 12593 if (!checkin) { 12594 pw.println("Features:"); 12595 } 12596 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12597 while (it.hasNext()) { 12598 String name = it.next(); 12599 if (!checkin) { 12600 pw.print(" "); 12601 } else { 12602 pw.print("feat,"); 12603 } 12604 pw.println(name); 12605 } 12606 } 12607 12608 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12609 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12610 : "Activity Resolver Table:", " ", packageName, 12611 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12612 dumpState.setTitlePrinted(true); 12613 } 12614 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12615 : "Receiver Resolver Table:", " ", packageName, 12616 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12617 dumpState.setTitlePrinted(true); 12618 } 12619 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12620 : "Service Resolver Table:", " ", packageName, 12621 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12622 dumpState.setTitlePrinted(true); 12623 } 12624 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12625 : "Provider Resolver Table:", " ", packageName, 12626 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12627 dumpState.setTitlePrinted(true); 12628 } 12629 } 12630 12631 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12632 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12633 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12634 int user = mSettings.mPreferredActivities.keyAt(i); 12635 if (pir.dump(pw, 12636 dumpState.getTitlePrinted() 12637 ? "\nPreferred Activities User " + user + ":" 12638 : "Preferred Activities User " + user + ":", " ", 12639 packageName, true, false)) { 12640 dumpState.setTitlePrinted(true); 12641 } 12642 } 12643 } 12644 12645 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12646 pw.flush(); 12647 FileOutputStream fout = new FileOutputStream(fd); 12648 BufferedOutputStream str = new BufferedOutputStream(fout); 12649 XmlSerializer serializer = new FastXmlSerializer(); 12650 try { 12651 serializer.setOutput(str, "utf-8"); 12652 serializer.startDocument(null, true); 12653 serializer.setFeature( 12654 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12655 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12656 serializer.endDocument(); 12657 serializer.flush(); 12658 } catch (IllegalArgumentException e) { 12659 pw.println("Failed writing: " + e); 12660 } catch (IllegalStateException e) { 12661 pw.println("Failed writing: " + e); 12662 } catch (IOException e) { 12663 pw.println("Failed writing: " + e); 12664 } 12665 } 12666 12667 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12668 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12669 if (packageName == null) { 12670 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12671 if (iperm == 0) { 12672 if (dumpState.onTitlePrinted()) 12673 pw.println(); 12674 pw.println("AppOp Permissions:"); 12675 } 12676 pw.print(" AppOp Permission "); 12677 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12678 pw.println(":"); 12679 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12680 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12681 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12682 } 12683 } 12684 } 12685 } 12686 12687 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12688 boolean printedSomething = false; 12689 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12690 if (packageName != null && !packageName.equals(p.info.packageName)) { 12691 continue; 12692 } 12693 if (!printedSomething) { 12694 if (dumpState.onTitlePrinted()) 12695 pw.println(); 12696 pw.println("Registered ContentProviders:"); 12697 printedSomething = true; 12698 } 12699 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12700 pw.print(" "); pw.println(p.toString()); 12701 } 12702 printedSomething = false; 12703 for (Map.Entry<String, PackageParser.Provider> entry : 12704 mProvidersByAuthority.entrySet()) { 12705 PackageParser.Provider p = entry.getValue(); 12706 if (packageName != null && !packageName.equals(p.info.packageName)) { 12707 continue; 12708 } 12709 if (!printedSomething) { 12710 if (dumpState.onTitlePrinted()) 12711 pw.println(); 12712 pw.println("ContentProvider Authorities:"); 12713 printedSomething = true; 12714 } 12715 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12716 pw.print(" "); pw.println(p.toString()); 12717 if (p.info != null && p.info.applicationInfo != null) { 12718 final String appInfo = p.info.applicationInfo.toString(); 12719 pw.print(" applicationInfo="); pw.println(appInfo); 12720 } 12721 } 12722 } 12723 12724 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12725 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12726 } 12727 12728 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12729 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12730 } 12731 12732 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12733 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12734 } 12735 12736 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12737 // XXX should handle packageName != null by dumping only install data that 12738 // the given package is involved with. 12739 if (dumpState.onTitlePrinted()) pw.println(); 12740 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12741 } 12742 12743 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12744 if (dumpState.onTitlePrinted()) pw.println(); 12745 mSettings.dumpReadMessagesLPr(pw, dumpState); 12746 12747 pw.println(); 12748 pw.println("Package warning messages:"); 12749 BufferedReader in = null; 12750 String line = null; 12751 try { 12752 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12753 while ((line = in.readLine()) != null) { 12754 if (line.contains("ignored: updated version")) continue; 12755 pw.println(line); 12756 } 12757 } catch (IOException ignored) { 12758 } finally { 12759 IoUtils.closeQuietly(in); 12760 } 12761 } 12762 12763 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12764 BufferedReader in = null; 12765 String line = null; 12766 try { 12767 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12768 while ((line = in.readLine()) != null) { 12769 if (line.contains("ignored: updated version")) continue; 12770 pw.print("msg,"); 12771 pw.println(line); 12772 } 12773 } catch (IOException ignored) { 12774 } finally { 12775 IoUtils.closeQuietly(in); 12776 } 12777 } 12778 } 12779 } 12780 12781 // ------- apps on sdcard specific code ------- 12782 static final boolean DEBUG_SD_INSTALL = false; 12783 12784 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12785 12786 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12787 12788 private boolean mMediaMounted = false; 12789 12790 static String getEncryptKey() { 12791 try { 12792 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12793 SD_ENCRYPTION_KEYSTORE_NAME); 12794 if (sdEncKey == null) { 12795 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12796 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12797 if (sdEncKey == null) { 12798 Slog.e(TAG, "Failed to create encryption keys"); 12799 return null; 12800 } 12801 } 12802 return sdEncKey; 12803 } catch (NoSuchAlgorithmException nsae) { 12804 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12805 return null; 12806 } catch (IOException ioe) { 12807 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12808 return null; 12809 } 12810 } 12811 12812 /* 12813 * Update media status on PackageManager. 12814 */ 12815 @Override 12816 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12817 int callingUid = Binder.getCallingUid(); 12818 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12819 throw new SecurityException("Media status can only be updated by the system"); 12820 } 12821 // reader; this apparently protects mMediaMounted, but should probably 12822 // be a different lock in that case. 12823 synchronized (mPackages) { 12824 Log.i(TAG, "Updating external media status from " 12825 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12826 + (mediaStatus ? "mounted" : "unmounted")); 12827 if (DEBUG_SD_INSTALL) 12828 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12829 + ", mMediaMounted=" + mMediaMounted); 12830 if (mediaStatus == mMediaMounted) { 12831 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12832 : 0, -1); 12833 mHandler.sendMessage(msg); 12834 return; 12835 } 12836 mMediaMounted = mediaStatus; 12837 } 12838 // Queue up an async operation since the package installation may take a 12839 // little while. 12840 mHandler.post(new Runnable() { 12841 public void run() { 12842 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12843 } 12844 }); 12845 } 12846 12847 /** 12848 * Called by MountService when the initial ASECs to scan are available. 12849 * Should block until all the ASEC containers are finished being scanned. 12850 */ 12851 public void scanAvailableAsecs() { 12852 updateExternalMediaStatusInner(true, false, false); 12853 if (mShouldRestoreconData) { 12854 SELinuxMMAC.setRestoreconDone(); 12855 mShouldRestoreconData = false; 12856 } 12857 } 12858 12859 /* 12860 * Collect information of applications on external media, map them against 12861 * existing containers and update information based on current mount status. 12862 * Please note that we always have to report status if reportStatus has been 12863 * set to true especially when unloading packages. 12864 */ 12865 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12866 boolean externalStorage) { 12867 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12868 int[] uidArr = EmptyArray.INT; 12869 12870 final String[] list = PackageHelper.getSecureContainerList(); 12871 if (ArrayUtils.isEmpty(list)) { 12872 Log.i(TAG, "No secure containers found"); 12873 } else { 12874 // Process list of secure containers and categorize them 12875 // as active or stale based on their package internal state. 12876 12877 // reader 12878 synchronized (mPackages) { 12879 for (String cid : list) { 12880 // Leave stages untouched for now; installer service owns them 12881 if (PackageInstallerService.isStageName(cid)) continue; 12882 12883 if (DEBUG_SD_INSTALL) 12884 Log.i(TAG, "Processing container " + cid); 12885 String pkgName = getAsecPackageName(cid); 12886 if (pkgName == null) { 12887 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12888 continue; 12889 } 12890 if (DEBUG_SD_INSTALL) 12891 Log.i(TAG, "Looking for pkg : " + pkgName); 12892 12893 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12894 if (ps == null) { 12895 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12896 continue; 12897 } 12898 12899 /* 12900 * Skip packages that are not external if we're unmounting 12901 * external storage. 12902 */ 12903 if (externalStorage && !isMounted && !isExternal(ps)) { 12904 continue; 12905 } 12906 12907 final AsecInstallArgs args = new AsecInstallArgs(cid, 12908 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12909 // The package status is changed only if the code path 12910 // matches between settings and the container id. 12911 if (ps.codePathString != null 12912 && ps.codePathString.startsWith(args.getCodePath())) { 12913 if (DEBUG_SD_INSTALL) { 12914 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12915 + " at code path: " + ps.codePathString); 12916 } 12917 12918 // We do have a valid package installed on sdcard 12919 processCids.put(args, ps.codePathString); 12920 final int uid = ps.appId; 12921 if (uid != -1) { 12922 uidArr = ArrayUtils.appendInt(uidArr, uid); 12923 } 12924 } else { 12925 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12926 + ps.codePathString); 12927 } 12928 } 12929 } 12930 12931 Arrays.sort(uidArr); 12932 } 12933 12934 // Process packages with valid entries. 12935 if (isMounted) { 12936 if (DEBUG_SD_INSTALL) 12937 Log.i(TAG, "Loading packages"); 12938 loadMediaPackages(processCids, uidArr); 12939 startCleaningPackages(); 12940 mInstallerService.onSecureContainersAvailable(); 12941 } else { 12942 if (DEBUG_SD_INSTALL) 12943 Log.i(TAG, "Unloading packages"); 12944 unloadMediaPackages(processCids, uidArr, reportStatus); 12945 } 12946 } 12947 12948 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12949 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12950 int size = pkgList.size(); 12951 if (size > 0) { 12952 // Send broadcasts here 12953 Bundle extras = new Bundle(); 12954 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12955 .toArray(new String[size])); 12956 if (uidArr != null) { 12957 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12958 } 12959 if (replacing) { 12960 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12961 } 12962 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12963 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12964 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12965 } 12966 } 12967 12968 /* 12969 * Look at potentially valid container ids from processCids If package 12970 * information doesn't match the one on record or package scanning fails, 12971 * the cid is added to list of removeCids. We currently don't delete stale 12972 * containers. 12973 */ 12974 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12975 ArrayList<String> pkgList = new ArrayList<String>(); 12976 Set<AsecInstallArgs> keys = processCids.keySet(); 12977 12978 for (AsecInstallArgs args : keys) { 12979 String codePath = processCids.get(args); 12980 if (DEBUG_SD_INSTALL) 12981 Log.i(TAG, "Loading container : " + args.cid); 12982 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12983 try { 12984 // Make sure there are no container errors first. 12985 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12986 Slog.e(TAG, "Failed to mount cid : " + args.cid 12987 + " when installing from sdcard"); 12988 continue; 12989 } 12990 // Check code path here. 12991 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12992 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12993 + " does not match one in settings " + codePath); 12994 continue; 12995 } 12996 // Parse package 12997 int parseFlags = mDefParseFlags; 12998 if (args.isExternal()) { 12999 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13000 } 13001 if (args.isFwdLocked()) { 13002 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13003 } 13004 13005 synchronized (mInstallLock) { 13006 PackageParser.Package pkg = null; 13007 try { 13008 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13009 } catch (PackageManagerException e) { 13010 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13011 } 13012 // Scan the package 13013 if (pkg != null) { 13014 /* 13015 * TODO why is the lock being held? doPostInstall is 13016 * called in other places without the lock. This needs 13017 * to be straightened out. 13018 */ 13019 // writer 13020 synchronized (mPackages) { 13021 retCode = PackageManager.INSTALL_SUCCEEDED; 13022 pkgList.add(pkg.packageName); 13023 // Post process args 13024 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13025 pkg.applicationInfo.uid); 13026 } 13027 } else { 13028 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13029 } 13030 } 13031 13032 } finally { 13033 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13034 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13035 } 13036 } 13037 } 13038 // writer 13039 synchronized (mPackages) { 13040 // If the platform SDK has changed since the last time we booted, 13041 // we need to re-grant app permission to catch any new ones that 13042 // appear. This is really a hack, and means that apps can in some 13043 // cases get permissions that the user didn't initially explicitly 13044 // allow... it would be nice to have some better way to handle 13045 // this situation. 13046 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13047 if (regrantPermissions) 13048 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13049 + mSdkVersion + "; regranting permissions for external storage"); 13050 mSettings.mExternalSdkPlatform = mSdkVersion; 13051 13052 // Make sure group IDs have been assigned, and any permission 13053 // changes in other apps are accounted for 13054 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13055 | (regrantPermissions 13056 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13057 : 0)); 13058 13059 mSettings.updateExternalDatabaseVersion(); 13060 13061 // can downgrade to reader 13062 // Persist settings 13063 mSettings.writeLPr(); 13064 } 13065 // Send a broadcast to let everyone know we are done processing 13066 if (pkgList.size() > 0) { 13067 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13068 } 13069 } 13070 13071 /* 13072 * Utility method to unload a list of specified containers 13073 */ 13074 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13075 // Just unmount all valid containers. 13076 for (AsecInstallArgs arg : cidArgs) { 13077 synchronized (mInstallLock) { 13078 arg.doPostDeleteLI(false); 13079 } 13080 } 13081 } 13082 13083 /* 13084 * Unload packages mounted on external media. This involves deleting package 13085 * data from internal structures, sending broadcasts about diabled packages, 13086 * gc'ing to free up references, unmounting all secure containers 13087 * corresponding to packages on external media, and posting a 13088 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13089 * that we always have to post this message if status has been requested no 13090 * matter what. 13091 */ 13092 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13093 final boolean reportStatus) { 13094 if (DEBUG_SD_INSTALL) 13095 Log.i(TAG, "unloading media packages"); 13096 ArrayList<String> pkgList = new ArrayList<String>(); 13097 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13098 final Set<AsecInstallArgs> keys = processCids.keySet(); 13099 for (AsecInstallArgs args : keys) { 13100 String pkgName = args.getPackageName(); 13101 if (DEBUG_SD_INSTALL) 13102 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13103 // Delete package internally 13104 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13105 synchronized (mInstallLock) { 13106 boolean res = deletePackageLI(pkgName, null, false, null, null, 13107 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13108 if (res) { 13109 pkgList.add(pkgName); 13110 } else { 13111 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13112 failedList.add(args); 13113 } 13114 } 13115 } 13116 13117 // reader 13118 synchronized (mPackages) { 13119 // We didn't update the settings after removing each package; 13120 // write them now for all packages. 13121 mSettings.writeLPr(); 13122 } 13123 13124 // We have to absolutely send UPDATED_MEDIA_STATUS only 13125 // after confirming that all the receivers processed the ordered 13126 // broadcast when packages get disabled, force a gc to clean things up. 13127 // and unload all the containers. 13128 if (pkgList.size() > 0) { 13129 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13130 new IIntentReceiver.Stub() { 13131 public void performReceive(Intent intent, int resultCode, String data, 13132 Bundle extras, boolean ordered, boolean sticky, 13133 int sendingUser) throws RemoteException { 13134 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13135 reportStatus ? 1 : 0, 1, keys); 13136 mHandler.sendMessage(msg); 13137 } 13138 }); 13139 } else { 13140 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13141 keys); 13142 mHandler.sendMessage(msg); 13143 } 13144 } 13145 13146 /** Binder call */ 13147 @Override 13148 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13149 final int flags) { 13150 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13151 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13152 int returnCode = PackageManager.MOVE_SUCCEEDED; 13153 int currInstallFlags = 0; 13154 int newInstallFlags = 0; 13155 13156 File codeFile = null; 13157 String installerPackageName = null; 13158 String packageAbiOverride = null; 13159 13160 // reader 13161 synchronized (mPackages) { 13162 final PackageParser.Package pkg = mPackages.get(packageName); 13163 final PackageSetting ps = mSettings.mPackages.get(packageName); 13164 if (pkg == null || ps == null) { 13165 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13166 } else { 13167 // Disable moving fwd locked apps and system packages 13168 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13169 Slog.w(TAG, "Cannot move system application"); 13170 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13171 } else if (pkg.mOperationPending) { 13172 Slog.w(TAG, "Attempt to move package which has pending operations"); 13173 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13174 } else { 13175 // Find install location first 13176 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13177 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13178 Slog.w(TAG, "Ambigous flags specified for move location."); 13179 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13180 } else { 13181 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13182 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13183 currInstallFlags = isExternal(pkg) 13184 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13185 13186 if (newInstallFlags == currInstallFlags) { 13187 Slog.w(TAG, "No move required. Trying to move to same location"); 13188 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13189 } else { 13190 if (isForwardLocked(pkg)) { 13191 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13192 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13193 } 13194 } 13195 } 13196 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13197 pkg.mOperationPending = true; 13198 } 13199 } 13200 13201 codeFile = new File(pkg.codePath); 13202 installerPackageName = ps.installerPackageName; 13203 packageAbiOverride = ps.cpuAbiOverrideString; 13204 } 13205 } 13206 13207 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13208 try { 13209 observer.packageMoved(packageName, returnCode); 13210 } catch (RemoteException ignored) { 13211 } 13212 return; 13213 } 13214 13215 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13216 @Override 13217 public void onUserActionRequired(Intent intent) throws RemoteException { 13218 throw new IllegalStateException(); 13219 } 13220 13221 @Override 13222 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13223 Bundle extras) throws RemoteException { 13224 Slog.d(TAG, "Install result for move: " 13225 + PackageManager.installStatusToString(returnCode, msg)); 13226 13227 // We usually have a new package now after the install, but if 13228 // we failed we need to clear the pending flag on the original 13229 // package object. 13230 synchronized (mPackages) { 13231 final PackageParser.Package pkg = mPackages.get(packageName); 13232 if (pkg != null) { 13233 pkg.mOperationPending = false; 13234 } 13235 } 13236 13237 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13238 switch (status) { 13239 case PackageInstaller.STATUS_SUCCESS: 13240 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13241 break; 13242 case PackageInstaller.STATUS_FAILURE_STORAGE: 13243 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13244 break; 13245 default: 13246 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13247 break; 13248 } 13249 } 13250 }; 13251 13252 // Treat a move like reinstalling an existing app, which ensures that we 13253 // process everythign uniformly, like unpacking native libraries. 13254 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13255 13256 final Message msg = mHandler.obtainMessage(INIT_COPY); 13257 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13258 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13259 installerPackageName, null, user, packageAbiOverride); 13260 mHandler.sendMessage(msg); 13261 } 13262 13263 @Override 13264 public boolean setInstallLocation(int loc) { 13265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13266 null); 13267 if (getInstallLocation() == loc) { 13268 return true; 13269 } 13270 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13271 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13272 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13273 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13274 return true; 13275 } 13276 return false; 13277 } 13278 13279 @Override 13280 public int getInstallLocation() { 13281 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13282 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13283 PackageHelper.APP_INSTALL_AUTO); 13284 } 13285 13286 /** Called by UserManagerService */ 13287 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13288 mDirtyUsers.remove(userHandle); 13289 mSettings.removeUserLPw(userHandle); 13290 mPendingBroadcasts.remove(userHandle); 13291 if (mInstaller != null) { 13292 // Technically, we shouldn't be doing this with the package lock 13293 // held. However, this is very rare, and there is already so much 13294 // other disk I/O going on, that we'll let it slide for now. 13295 mInstaller.removeUserDataDirs(userHandle); 13296 } 13297 mUserNeedsBadging.delete(userHandle); 13298 removeUnusedPackagesLILPw(userManager, userHandle); 13299 } 13300 13301 /** 13302 * We're removing userHandle and would like to remove any downloaded packages 13303 * that are no longer in use by any other user. 13304 * @param userHandle the user being removed 13305 */ 13306 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13307 final boolean DEBUG_CLEAN_APKS = false; 13308 int [] users = userManager.getUserIdsLPr(); 13309 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13310 while (psit.hasNext()) { 13311 PackageSetting ps = psit.next(); 13312 if (ps.pkg == null) { 13313 continue; 13314 } 13315 final String packageName = ps.pkg.packageName; 13316 // Skip over if system app 13317 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13318 continue; 13319 } 13320 if (DEBUG_CLEAN_APKS) { 13321 Slog.i(TAG, "Checking package " + packageName); 13322 } 13323 boolean keep = false; 13324 for (int i = 0; i < users.length; i++) { 13325 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13326 keep = true; 13327 if (DEBUG_CLEAN_APKS) { 13328 Slog.i(TAG, " Keeping package " + packageName + " for user " 13329 + users[i]); 13330 } 13331 break; 13332 } 13333 } 13334 if (!keep) { 13335 if (DEBUG_CLEAN_APKS) { 13336 Slog.i(TAG, " Removing package " + packageName); 13337 } 13338 mHandler.post(new Runnable() { 13339 public void run() { 13340 deletePackageX(packageName, userHandle, 0); 13341 } //end run 13342 }); 13343 } 13344 } 13345 } 13346 13347 /** Called by UserManagerService */ 13348 void createNewUserLILPw(int userHandle, File path) { 13349 if (mInstaller != null) { 13350 mInstaller.createUserConfig(userHandle); 13351 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13352 } 13353 } 13354 13355 @Override 13356 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13357 mContext.enforceCallingOrSelfPermission( 13358 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13359 "Only package verification agents can read the verifier device identity"); 13360 13361 synchronized (mPackages) { 13362 return mSettings.getVerifierDeviceIdentityLPw(); 13363 } 13364 } 13365 13366 @Override 13367 public void setPermissionEnforced(String permission, boolean enforced) { 13368 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13369 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13370 synchronized (mPackages) { 13371 if (mSettings.mReadExternalStorageEnforced == null 13372 || mSettings.mReadExternalStorageEnforced != enforced) { 13373 mSettings.mReadExternalStorageEnforced = enforced; 13374 mSettings.writeLPr(); 13375 } 13376 } 13377 // kill any non-foreground processes so we restart them and 13378 // grant/revoke the GID. 13379 final IActivityManager am = ActivityManagerNative.getDefault(); 13380 if (am != null) { 13381 final long token = Binder.clearCallingIdentity(); 13382 try { 13383 am.killProcessesBelowForeground("setPermissionEnforcement"); 13384 } catch (RemoteException e) { 13385 } finally { 13386 Binder.restoreCallingIdentity(token); 13387 } 13388 } 13389 } else { 13390 throw new IllegalArgumentException("No selective enforcement for " + permission); 13391 } 13392 } 13393 13394 @Override 13395 @Deprecated 13396 public boolean isPermissionEnforced(String permission) { 13397 return true; 13398 } 13399 13400 @Override 13401 public boolean isStorageLow() { 13402 final long token = Binder.clearCallingIdentity(); 13403 try { 13404 final DeviceStorageMonitorInternal 13405 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13406 if (dsm != null) { 13407 return dsm.isMemoryLow(); 13408 } else { 13409 return false; 13410 } 13411 } finally { 13412 Binder.restoreCallingIdentity(token); 13413 } 13414 } 13415 13416 @Override 13417 public IPackageInstaller getPackageInstaller() { 13418 return mInstallerService; 13419 } 13420 13421 private boolean userNeedsBadging(int userId) { 13422 int index = mUserNeedsBadging.indexOfKey(userId); 13423 if (index < 0) { 13424 final UserInfo userInfo; 13425 final long token = Binder.clearCallingIdentity(); 13426 try { 13427 userInfo = sUserManager.getUserInfo(userId); 13428 } finally { 13429 Binder.restoreCallingIdentity(token); 13430 } 13431 final boolean b; 13432 if (userInfo != null && userInfo.isManagedProfile()) { 13433 b = true; 13434 } else { 13435 b = false; 13436 } 13437 mUserNeedsBadging.put(userId, b); 13438 return b; 13439 } 13440 return mUserNeedsBadging.valueAt(index); 13441 } 13442 13443 @Override 13444 public KeySet getKeySetByAlias(String packageName, String alias) { 13445 if (packageName == null || alias == null) { 13446 return null; 13447 } 13448 synchronized(mPackages) { 13449 final PackageParser.Package pkg = mPackages.get(packageName); 13450 if (pkg == null) { 13451 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13452 throw new IllegalArgumentException("Unknown package: " + packageName); 13453 } 13454 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13455 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13456 } 13457 } 13458 13459 @Override 13460 public KeySet getSigningKeySet(String packageName) { 13461 if (packageName == null) { 13462 return null; 13463 } 13464 synchronized(mPackages) { 13465 final PackageParser.Package pkg = mPackages.get(packageName); 13466 if (pkg == null) { 13467 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13468 throw new IllegalArgumentException("Unknown package: " + packageName); 13469 } 13470 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13471 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13472 throw new SecurityException("May not access signing KeySet of other apps."); 13473 } 13474 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13475 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13476 } 13477 } 13478 13479 @Override 13480 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13481 if (packageName == null || ks == null) { 13482 return false; 13483 } 13484 synchronized(mPackages) { 13485 final PackageParser.Package pkg = mPackages.get(packageName); 13486 if (pkg == null) { 13487 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13488 throw new IllegalArgumentException("Unknown package: " + packageName); 13489 } 13490 IBinder ksh = ks.getToken(); 13491 if (ksh instanceof KeySetHandle) { 13492 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13493 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13494 } 13495 return false; 13496 } 13497 } 13498 13499 @Override 13500 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13501 if (packageName == null || ks == null) { 13502 return false; 13503 } 13504 synchronized(mPackages) { 13505 final PackageParser.Package pkg = mPackages.get(packageName); 13506 if (pkg == null) { 13507 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13508 throw new IllegalArgumentException("Unknown package: " + packageName); 13509 } 13510 IBinder ksh = ks.getToken(); 13511 if (ksh instanceof KeySetHandle) { 13512 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13513 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13514 } 13515 return false; 13516 } 13517 } 13518 13519 public void getUsageStatsIfNoPackageUsageInfo() { 13520 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13521 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13522 if (usm == null) { 13523 throw new IllegalStateException("UsageStatsManager must be initialized"); 13524 } 13525 long now = System.currentTimeMillis(); 13526 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13527 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13528 String packageName = entry.getKey(); 13529 PackageParser.Package pkg = mPackages.get(packageName); 13530 if (pkg == null) { 13531 continue; 13532 } 13533 UsageStats usage = entry.getValue(); 13534 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13535 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13536 } 13537 } 13538 } 13539 13540 /** 13541 * Check and throw if the given before/after packages would be considered a 13542 * downgrade. 13543 */ 13544 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13545 throws PackageManagerException { 13546 if (after.versionCode < before.mVersionCode) { 13547 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13548 "Update version code " + after.versionCode + " is older than current " 13549 + before.mVersionCode); 13550 } else if (after.versionCode == before.mVersionCode) { 13551 if (after.baseRevisionCode < before.baseRevisionCode) { 13552 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13553 "Update base revision code " + after.baseRevisionCode 13554 + " is older than current " + before.baseRevisionCode); 13555 } 13556 13557 if (!ArrayUtils.isEmpty(after.splitNames)) { 13558 for (int i = 0; i < after.splitNames.length; i++) { 13559 final String splitName = after.splitNames[i]; 13560 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13561 if (j != -1) { 13562 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13563 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13564 "Update split " + splitName + " revision code " 13565 + after.splitRevisionCodes[i] + " is older than current " 13566 + before.splitRevisionCodes[j]); 13567 } 13568 } 13569 } 13570 } 13571 } 13572 } 13573} 13574