PackageManagerService.java revision 900e3b5fc5bb4bf4947f63c0fed0757dfb7effa6
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageParser; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.storage.StorageManager; 141import android.os.Debug; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.security.KeyStore; 158import android.security.SystemKeyStore; 159import android.system.ErrnoException; 160import android.system.Os; 161import android.system.StructStat; 162import android.text.TextUtils; 163import android.util.ArraySet; 164import android.util.AtomicFile; 165import android.util.DisplayMetrics; 166import android.util.EventLog; 167import android.util.ExceptionUtils; 168import android.util.Log; 169import android.util.LogPrinter; 170import android.util.PrintStreamPrinter; 171import android.util.Slog; 172import android.util.SparseArray; 173import android.util.SparseBooleanArray; 174import android.view.Display; 175 176import java.io.BufferedInputStream; 177import java.io.BufferedOutputStream; 178import java.io.File; 179import java.io.FileDescriptor; 180import java.io.FileInputStream; 181import java.io.FileNotFoundException; 182import java.io.FileOutputStream; 183import java.io.FilenameFilter; 184import java.io.IOException; 185import java.io.InputStream; 186import java.io.PrintWriter; 187import java.nio.charset.StandardCharsets; 188import java.security.NoSuchAlgorithmException; 189import java.security.PublicKey; 190import java.security.cert.CertificateEncodingException; 191import java.security.cert.CertificateException; 192import java.text.SimpleDateFormat; 193import java.util.ArrayList; 194import java.util.Arrays; 195import java.util.Collection; 196import java.util.Collections; 197import java.util.Comparator; 198import java.util.Date; 199import java.util.HashMap; 200import java.util.HashSet; 201import java.util.Iterator; 202import java.util.List; 203import java.util.Map; 204import java.util.Objects; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214import libcore.util.EmptyArray; 215 216/** 217 * Keep track of all those .apks everywhere. 218 * 219 * This is very central to the platform's security; please run the unit 220 * tests whenever making modifications here: 221 * 222mmm frameworks/base/tests/AndroidTests 223adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 224adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 225 * 226 * {@hide} 227 */ 228public class PackageManagerService extends IPackageManager.Stub { 229 static final String TAG = "PackageManager"; 230 static final boolean DEBUG_SETTINGS = false; 231 static final boolean DEBUG_PREFERRED = false; 232 static final boolean DEBUG_UPGRADE = false; 233 private static final boolean DEBUG_INSTALL = false; 234 private static final boolean DEBUG_REMOVE = false; 235 private static final boolean DEBUG_BROADCASTS = false; 236 private static final boolean DEBUG_SHOW_INFO = false; 237 private static final boolean DEBUG_PACKAGE_INFO = false; 238 private static final boolean DEBUG_INTENT_MATCHING = false; 239 private static final boolean DEBUG_PACKAGE_SCANNING = false; 240 private static final boolean DEBUG_VERIFY = false; 241 private static final boolean DEBUG_DEXOPT = false; 242 private static final boolean DEBUG_ABI_SELECTION = false; 243 244 private static final int RADIO_UID = Process.PHONE_UID; 245 private static final int LOG_UID = Process.LOG_UID; 246 private static final int NFC_UID = Process.NFC_UID; 247 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 248 private static final int SHELL_UID = Process.SHELL_UID; 249 250 // Cap the size of permission trees that 3rd party apps can define 251 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 252 253 // Suffix used during package installation when copying/moving 254 // package apks to install directory. 255 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 256 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 static final int SCAN_REPLACING = 1<<11; 268 269 static final int REMOVE_CHATTY = 1<<16; 270 271 /** 272 * Timeout (in milliseconds) after which the watchdog should declare that 273 * our handler thread is wedged. The usual default for such things is one 274 * minute but we sometimes do very lengthy I/O operations on this thread, 275 * such as installing multi-gigabyte applications, so ours needs to be longer. 276 */ 277 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 278 279 /** 280 * Whether verification is enabled by default. 281 */ 282 private static final boolean DEFAULT_VERIFY_ENABLE = true; 283 284 /** 285 * The default maximum time to wait for the verification agent to return in 286 * milliseconds. 287 */ 288 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 289 290 /** 291 * The default response for package verification timeout. 292 * 293 * This can be either PackageManager.VERIFICATION_ALLOW or 294 * PackageManager.VERIFICATION_REJECT. 295 */ 296 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 297 298 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 299 300 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 301 DEFAULT_CONTAINER_PACKAGE, 302 "com.android.defcontainer.DefaultContainerService"); 303 304 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 305 306 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 307 308 private static String sPreferredInstructionSet; 309 310 final ServiceThread mHandlerThread; 311 312 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 313 private static final String IDMAP_SUFFIX = "@idmap"; 314 315 final PackageHandler mHandler; 316 317 /** 318 * Messages for {@link #mHandler} that need to wait for system ready before 319 * being dispatched. 320 */ 321 private ArrayList<Message> mPostSystemReadyMessages; 322 323 final int mSdkVersion = Build.VERSION.SDK_INT; 324 325 final Context mContext; 326 final boolean mFactoryTest; 327 final boolean mOnlyCore; 328 final boolean mLazyDexOpt; 329 final DisplayMetrics mMetrics; 330 final int mDefParseFlags; 331 final String[] mSeparateProcesses; 332 333 // This is where all application persistent data goes. 334 final File mAppDataDir; 335 336 // This is where all application persistent data goes for secondary users. 337 final File mUserAppDataDir; 338 339 /** The location for ASEC container files on internal storage. */ 340 final String mAsecInternalPath; 341 342 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 343 // LOCK HELD. Can be called with mInstallLock held. 344 final Installer mInstaller; 345 346 /** Directory where installed third-party apps stored */ 347 final File mAppInstallDir; 348 349 /** 350 * Directory to which applications installed internally have their 351 * 32 bit native libraries copied. 352 */ 353 private File mAppLib32InstallDir; 354 355 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 356 // apps. 357 final File mDrmAppPrivateInstallDir; 358 359 // ---------------------------------------------------------------- 360 361 // Lock for state used when installing and doing other long running 362 // operations. Methods that must be called with this lock held have 363 // the suffix "LI". 364 final Object mInstallLock = new Object(); 365 366 // ---------------------------------------------------------------- 367 368 // Keys are String (package name), values are Package. This also serves 369 // as the lock for the global state. Methods that must be called with 370 // this lock held have the prefix "LP". 371 final HashMap<String, PackageParser.Package> mPackages = 372 new HashMap<String, PackageParser.Package>(); 373 374 // Tracks available target package names -> overlay package paths. 375 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 376 new HashMap<String, HashMap<String, PackageParser.Package>>(); 377 378 final Settings mSettings; 379 boolean mRestoredSettings; 380 381 // System configuration read by SystemConfig. 382 final int[] mGlobalGids; 383 final SparseArray<HashSet<String>> mSystemPermissions; 384 final HashMap<String, FeatureInfo> mAvailableFeatures; 385 386 // If mac_permissions.xml was found for seinfo labeling. 387 boolean mFoundPolicyFile; 388 389 // If a recursive restorecon of /data/data/<pkg> is needed. 390 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 391 392 public static final class SharedLibraryEntry { 393 public final String path; 394 public final String apk; 395 396 SharedLibraryEntry(String _path, String _apk) { 397 path = _path; 398 apk = _apk; 399 } 400 } 401 402 // Currently known shared libraries. 403 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 404 new HashMap<String, SharedLibraryEntry>(); 405 406 // All available activities, for your resolving pleasure. 407 final ActivityIntentResolver mActivities = 408 new ActivityIntentResolver(); 409 410 // All available receivers, for your resolving pleasure. 411 final ActivityIntentResolver mReceivers = 412 new ActivityIntentResolver(); 413 414 // All available services, for your resolving pleasure. 415 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 416 417 // All available providers, for your resolving pleasure. 418 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 419 420 // Mapping from provider base names (first directory in content URI codePath) 421 // to the provider information. 422 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 423 new HashMap<String, PackageParser.Provider>(); 424 425 // Mapping from instrumentation class names to info about them. 426 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 427 new HashMap<ComponentName, PackageParser.Instrumentation>(); 428 429 // Mapping from permission names to info about them. 430 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 431 new HashMap<String, PackageParser.PermissionGroup>(); 432 433 // Packages whose data we have transfered into another package, thus 434 // should no longer exist. 435 final HashSet<String> mTransferedPackages = new HashSet<String>(); 436 437 // Broadcast actions that are only available to the system. 438 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 439 440 /** List of packages waiting for verification. */ 441 final SparseArray<PackageVerificationState> mPendingVerification 442 = new SparseArray<PackageVerificationState>(); 443 444 /** Set of packages associated with each app op permission. */ 445 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 446 447 final PackageInstallerService mInstallerService; 448 449 HashSet<PackageParser.Package> mDeferredDexOpt = null; 450 451 // Cache of users who need badging. 452 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 453 454 /** Token for keys in mPendingVerification. */ 455 private int mPendingVerificationToken = 0; 456 457 volatile boolean mSystemReady; 458 volatile boolean mSafeMode; 459 volatile boolean mHasSystemUidErrors; 460 461 ApplicationInfo mAndroidApplication; 462 final ActivityInfo mResolveActivity = new ActivityInfo(); 463 final ResolveInfo mResolveInfo = new ResolveInfo(); 464 ComponentName mResolveComponentName; 465 PackageParser.Package mPlatformPackage; 466 ComponentName mCustomResolverComponentName; 467 468 boolean mResolverReplaced = false; 469 470 // Set of pending broadcasts for aggregating enable/disable of components. 471 static class PendingPackageBroadcasts { 472 // for each user id, a map of <package name -> components within that package> 473 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 474 475 public PendingPackageBroadcasts() { 476 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 477 } 478 479 public ArrayList<String> get(int userId, String packageName) { 480 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 481 return packages.get(packageName); 482 } 483 484 public void put(int userId, String packageName, ArrayList<String> components) { 485 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 486 packages.put(packageName, components); 487 } 488 489 public void remove(int userId, String packageName) { 490 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 491 if (packages != null) { 492 packages.remove(packageName); 493 } 494 } 495 496 public void remove(int userId) { 497 mUidMap.remove(userId); 498 } 499 500 public int userIdCount() { 501 return mUidMap.size(); 502 } 503 504 public int userIdAt(int n) { 505 return mUidMap.keyAt(n); 506 } 507 508 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 509 return mUidMap.get(userId); 510 } 511 512 public int size() { 513 // total number of pending broadcast entries across all userIds 514 int num = 0; 515 for (int i = 0; i< mUidMap.size(); i++) { 516 num += mUidMap.valueAt(i).size(); 517 } 518 return num; 519 } 520 521 public void clear() { 522 mUidMap.clear(); 523 } 524 525 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 526 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 527 if (map == null) { 528 map = new HashMap<String, ArrayList<String>>(); 529 mUidMap.put(userId, map); 530 } 531 return map; 532 } 533 } 534 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 535 536 // Service Connection to remote media container service to copy 537 // package uri's from external media onto secure containers 538 // or internal storage. 539 private IMediaContainerService mContainerService = null; 540 541 static final int SEND_PENDING_BROADCAST = 1; 542 static final int MCS_BOUND = 3; 543 static final int END_COPY = 4; 544 static final int INIT_COPY = 5; 545 static final int MCS_UNBIND = 6; 546 static final int START_CLEANING_PACKAGE = 7; 547 static final int FIND_INSTALL_LOC = 8; 548 static final int POST_INSTALL = 9; 549 static final int MCS_RECONNECT = 10; 550 static final int MCS_GIVE_UP = 11; 551 static final int UPDATED_MEDIA_STATUS = 12; 552 static final int WRITE_SETTINGS = 13; 553 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 554 static final int PACKAGE_VERIFIED = 15; 555 static final int CHECK_PENDING_VERIFICATION = 16; 556 557 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 558 559 // Delay time in millisecs 560 static final int BROADCAST_DELAY = 10 * 1000; 561 562 static UserManagerService sUserManager; 563 564 // Stores a list of users whose package restrictions file needs to be updated 565 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 566 567 final private DefaultContainerConnection mDefContainerConn = 568 new DefaultContainerConnection(); 569 class DefaultContainerConnection implements ServiceConnection { 570 public void onServiceConnected(ComponentName name, IBinder service) { 571 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 572 IMediaContainerService imcs = 573 IMediaContainerService.Stub.asInterface(service); 574 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 575 } 576 577 public void onServiceDisconnected(ComponentName name) { 578 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 579 } 580 }; 581 582 // Recordkeeping of restore-after-install operations that are currently in flight 583 // between the Package Manager and the Backup Manager 584 class PostInstallData { 585 public InstallArgs args; 586 public PackageInstalledInfo res; 587 588 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 589 args = _a; 590 res = _r; 591 } 592 }; 593 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 594 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 595 596 private final String mRequiredVerifierPackage; 597 598 private final PackageUsage mPackageUsage = new PackageUsage(); 599 600 private class PackageUsage { 601 private static final int WRITE_INTERVAL 602 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 603 604 private final Object mFileLock = new Object(); 605 private final AtomicLong mLastWritten = new AtomicLong(0); 606 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 607 608 private boolean mIsHistoricalPackageUsageAvailable = true; 609 610 boolean isHistoricalPackageUsageAvailable() { 611 return mIsHistoricalPackageUsageAvailable; 612 } 613 614 void write(boolean force) { 615 if (force) { 616 writeInternal(); 617 return; 618 } 619 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 620 && !DEBUG_DEXOPT) { 621 return; 622 } 623 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 624 new Thread("PackageUsage_DiskWriter") { 625 @Override 626 public void run() { 627 try { 628 writeInternal(); 629 } finally { 630 mBackgroundWriteRunning.set(false); 631 } 632 } 633 }.start(); 634 } 635 } 636 637 private void writeInternal() { 638 synchronized (mPackages) { 639 synchronized (mFileLock) { 640 AtomicFile file = getFile(); 641 FileOutputStream f = null; 642 try { 643 f = file.startWrite(); 644 BufferedOutputStream out = new BufferedOutputStream(f); 645 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 646 StringBuilder sb = new StringBuilder(); 647 for (PackageParser.Package pkg : mPackages.values()) { 648 if (pkg.mLastPackageUsageTimeInMills == 0) { 649 continue; 650 } 651 sb.setLength(0); 652 sb.append(pkg.packageName); 653 sb.append(' '); 654 sb.append((long)pkg.mLastPackageUsageTimeInMills); 655 sb.append('\n'); 656 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 657 } 658 out.flush(); 659 file.finishWrite(f); 660 } catch (IOException e) { 661 if (f != null) { 662 file.failWrite(f); 663 } 664 Log.e(TAG, "Failed to write package usage times", e); 665 } 666 } 667 } 668 mLastWritten.set(SystemClock.elapsedRealtime()); 669 } 670 671 void readLP() { 672 synchronized (mFileLock) { 673 AtomicFile file = getFile(); 674 BufferedInputStream in = null; 675 try { 676 in = new BufferedInputStream(file.openRead()); 677 StringBuffer sb = new StringBuffer(); 678 while (true) { 679 String packageName = readToken(in, sb, ' '); 680 if (packageName == null) { 681 break; 682 } 683 String timeInMillisString = readToken(in, sb, '\n'); 684 if (timeInMillisString == null) { 685 throw new IOException("Failed to find last usage time for package " 686 + packageName); 687 } 688 PackageParser.Package pkg = mPackages.get(packageName); 689 if (pkg == null) { 690 continue; 691 } 692 long timeInMillis; 693 try { 694 timeInMillis = Long.parseLong(timeInMillisString.toString()); 695 } catch (NumberFormatException e) { 696 throw new IOException("Failed to parse " + timeInMillisString 697 + " as a long.", e); 698 } 699 pkg.mLastPackageUsageTimeInMills = timeInMillis; 700 } 701 } catch (FileNotFoundException expected) { 702 mIsHistoricalPackageUsageAvailable = false; 703 } catch (IOException e) { 704 Log.w(TAG, "Failed to read package usage times", e); 705 } finally { 706 IoUtils.closeQuietly(in); 707 } 708 } 709 mLastWritten.set(SystemClock.elapsedRealtime()); 710 } 711 712 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 713 throws IOException { 714 sb.setLength(0); 715 while (true) { 716 int ch = in.read(); 717 if (ch == -1) { 718 if (sb.length() == 0) { 719 return null; 720 } 721 throw new IOException("Unexpected EOF"); 722 } 723 if (ch == endOfToken) { 724 return sb.toString(); 725 } 726 sb.append((char)ch); 727 } 728 } 729 730 private AtomicFile getFile() { 731 File dataDir = Environment.getDataDirectory(); 732 File systemDir = new File(dataDir, "system"); 733 File fname = new File(systemDir, "package-usage.list"); 734 return new AtomicFile(fname); 735 } 736 } 737 738 class PackageHandler extends Handler { 739 private boolean mBound = false; 740 final ArrayList<HandlerParams> mPendingInstalls = 741 new ArrayList<HandlerParams>(); 742 743 private boolean connectToService() { 744 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 745 " DefaultContainerService"); 746 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 747 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 748 if (mContext.bindServiceAsUser(service, mDefContainerConn, 749 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 750 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 751 mBound = true; 752 return true; 753 } 754 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 755 return false; 756 } 757 758 private void disconnectService() { 759 mContainerService = null; 760 mBound = false; 761 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 762 mContext.unbindService(mDefContainerConn); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 764 } 765 766 PackageHandler(Looper looper) { 767 super(looper); 768 } 769 770 public void handleMessage(Message msg) { 771 try { 772 doHandleMessage(msg); 773 } finally { 774 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 775 } 776 } 777 778 void doHandleMessage(Message msg) { 779 switch (msg.what) { 780 case INIT_COPY: { 781 HandlerParams params = (HandlerParams) msg.obj; 782 int idx = mPendingInstalls.size(); 783 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 784 // If a bind was already initiated we dont really 785 // need to do anything. The pending install 786 // will be processed later on. 787 if (!mBound) { 788 // If this is the only one pending we might 789 // have to bind to the service again. 790 if (!connectToService()) { 791 Slog.e(TAG, "Failed to bind to media container service"); 792 params.serviceError(); 793 return; 794 } else { 795 // Once we bind to the service, the first 796 // pending request will be processed. 797 mPendingInstalls.add(idx, params); 798 } 799 } else { 800 mPendingInstalls.add(idx, params); 801 // Already bound to the service. Just make 802 // sure we trigger off processing the first request. 803 if (idx == 0) { 804 mHandler.sendEmptyMessage(MCS_BOUND); 805 } 806 } 807 break; 808 } 809 case MCS_BOUND: { 810 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 811 if (msg.obj != null) { 812 mContainerService = (IMediaContainerService) msg.obj; 813 } 814 if (mContainerService == null) { 815 // Something seriously wrong. Bail out 816 Slog.e(TAG, "Cannot bind to media container service"); 817 for (HandlerParams params : mPendingInstalls) { 818 // Indicate service bind error 819 params.serviceError(); 820 } 821 mPendingInstalls.clear(); 822 } else if (mPendingInstalls.size() > 0) { 823 HandlerParams params = mPendingInstalls.get(0); 824 if (params != null) { 825 if (params.startCopy()) { 826 // We are done... look for more work or to 827 // go idle. 828 if (DEBUG_SD_INSTALL) Log.i(TAG, 829 "Checking for more work or unbind..."); 830 // Delete pending install 831 if (mPendingInstalls.size() > 0) { 832 mPendingInstalls.remove(0); 833 } 834 if (mPendingInstalls.size() == 0) { 835 if (mBound) { 836 if (DEBUG_SD_INSTALL) Log.i(TAG, 837 "Posting delayed MCS_UNBIND"); 838 removeMessages(MCS_UNBIND); 839 Message ubmsg = obtainMessage(MCS_UNBIND); 840 // Unbind after a little delay, to avoid 841 // continual thrashing. 842 sendMessageDelayed(ubmsg, 10000); 843 } 844 } else { 845 // There are more pending requests in queue. 846 // Just post MCS_BOUND message to trigger processing 847 // of next pending install. 848 if (DEBUG_SD_INSTALL) Log.i(TAG, 849 "Posting MCS_BOUND for next work"); 850 mHandler.sendEmptyMessage(MCS_BOUND); 851 } 852 } 853 } 854 } else { 855 // Should never happen ideally. 856 Slog.w(TAG, "Empty queue"); 857 } 858 break; 859 } 860 case MCS_RECONNECT: { 861 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 862 if (mPendingInstalls.size() > 0) { 863 if (mBound) { 864 disconnectService(); 865 } 866 if (!connectToService()) { 867 Slog.e(TAG, "Failed to bind to media container service"); 868 for (HandlerParams params : mPendingInstalls) { 869 // Indicate service bind error 870 params.serviceError(); 871 } 872 mPendingInstalls.clear(); 873 } 874 } 875 break; 876 } 877 case MCS_UNBIND: { 878 // If there is no actual work left, then time to unbind. 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 880 881 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 882 if (mBound) { 883 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 884 885 disconnectService(); 886 } 887 } else if (mPendingInstalls.size() > 0) { 888 // There are more pending requests in queue. 889 // Just post MCS_BOUND message to trigger processing 890 // of next pending install. 891 mHandler.sendEmptyMessage(MCS_BOUND); 892 } 893 894 break; 895 } 896 case MCS_GIVE_UP: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 898 mPendingInstalls.remove(0); 899 break; 900 } 901 case SEND_PENDING_BROADCAST: { 902 String packages[]; 903 ArrayList<String> components[]; 904 int size = 0; 905 int uids[]; 906 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 907 synchronized (mPackages) { 908 if (mPendingBroadcasts == null) { 909 return; 910 } 911 size = mPendingBroadcasts.size(); 912 if (size <= 0) { 913 // Nothing to be done. Just return 914 return; 915 } 916 packages = new String[size]; 917 components = new ArrayList[size]; 918 uids = new int[size]; 919 int i = 0; // filling out the above arrays 920 921 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 922 int packageUserId = mPendingBroadcasts.userIdAt(n); 923 Iterator<Map.Entry<String, ArrayList<String>>> it 924 = mPendingBroadcasts.packagesForUserId(packageUserId) 925 .entrySet().iterator(); 926 while (it.hasNext() && i < size) { 927 Map.Entry<String, ArrayList<String>> ent = it.next(); 928 packages[i] = ent.getKey(); 929 components[i] = ent.getValue(); 930 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 931 uids[i] = (ps != null) 932 ? UserHandle.getUid(packageUserId, ps.appId) 933 : -1; 934 i++; 935 } 936 } 937 size = i; 938 mPendingBroadcasts.clear(); 939 } 940 // Send broadcasts 941 for (int i = 0; i < size; i++) { 942 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 943 } 944 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 945 break; 946 } 947 case START_CLEANING_PACKAGE: { 948 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 949 final String packageName = (String)msg.obj; 950 final int userId = msg.arg1; 951 final boolean andCode = msg.arg2 != 0; 952 synchronized (mPackages) { 953 if (userId == UserHandle.USER_ALL) { 954 int[] users = sUserManager.getUserIds(); 955 for (int user : users) { 956 mSettings.addPackageToCleanLPw( 957 new PackageCleanItem(user, packageName, andCode)); 958 } 959 } else { 960 mSettings.addPackageToCleanLPw( 961 new PackageCleanItem(userId, packageName, andCode)); 962 } 963 } 964 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 965 startCleaningPackages(); 966 } break; 967 case POST_INSTALL: { 968 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 969 PostInstallData data = mRunningInstalls.get(msg.arg1); 970 mRunningInstalls.delete(msg.arg1); 971 boolean deleteOld = false; 972 973 if (data != null) { 974 InstallArgs args = data.args; 975 PackageInstalledInfo res = data.res; 976 977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 978 res.removedInfo.sendBroadcast(false, true, false); 979 Bundle extras = new Bundle(1); 980 extras.putInt(Intent.EXTRA_UID, res.uid); 981 // Determine the set of users who are adding this 982 // package for the first time vs. those who are seeing 983 // an update. 984 int[] firstUsers; 985 int[] updateUsers = new int[0]; 986 if (res.origUsers == null || res.origUsers.length == 0) { 987 firstUsers = res.newUsers; 988 } else { 989 firstUsers = new int[0]; 990 for (int i=0; i<res.newUsers.length; i++) { 991 int user = res.newUsers[i]; 992 boolean isNew = true; 993 for (int j=0; j<res.origUsers.length; j++) { 994 if (res.origUsers[j] == user) { 995 isNew = false; 996 break; 997 } 998 } 999 if (isNew) { 1000 int[] newFirst = new int[firstUsers.length+1]; 1001 System.arraycopy(firstUsers, 0, newFirst, 0, 1002 firstUsers.length); 1003 newFirst[firstUsers.length] = user; 1004 firstUsers = newFirst; 1005 } else { 1006 int[] newUpdate = new int[updateUsers.length+1]; 1007 System.arraycopy(updateUsers, 0, newUpdate, 0, 1008 updateUsers.length); 1009 newUpdate[updateUsers.length] = user; 1010 updateUsers = newUpdate; 1011 } 1012 } 1013 } 1014 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1015 res.pkg.applicationInfo.packageName, 1016 extras, null, null, firstUsers); 1017 final boolean update = res.removedInfo.removedPackage != null; 1018 if (update) { 1019 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1020 } 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, updateUsers); 1024 if (update) { 1025 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1026 res.pkg.applicationInfo.packageName, 1027 extras, null, null, updateUsers); 1028 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1029 null, null, 1030 res.pkg.applicationInfo.packageName, null, updateUsers); 1031 1032 // treat asec-hosted packages like removable media on upgrade 1033 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1034 if (DEBUG_INSTALL) { 1035 Slog.i(TAG, "upgrading pkg " + res.pkg 1036 + " is ASEC-hosted -> AVAILABLE"); 1037 } 1038 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1039 ArrayList<String> pkgList = new ArrayList<String>(1); 1040 pkgList.add(res.pkg.applicationInfo.packageName); 1041 sendResourcesChangedBroadcast(true, true, 1042 pkgList,uidArray, null); 1043 } 1044 } 1045 if (res.removedInfo.args != null) { 1046 // Remove the replaced package's older resources safely now 1047 deleteOld = true; 1048 } 1049 1050 // Log current value of "unknown sources" setting 1051 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1052 getUnknownSourcesSettings()); 1053 } 1054 // Force a gc to clear up things 1055 Runtime.getRuntime().gc(); 1056 // We delete after a gc for applications on sdcard. 1057 if (deleteOld) { 1058 synchronized (mInstallLock) { 1059 res.removedInfo.args.doPostDeleteLI(true); 1060 } 1061 } 1062 if (args.observer != null) { 1063 try { 1064 Bundle extras = extrasForInstallResult(res); 1065 args.observer.onPackageInstalled(res.name, res.returnCode, 1066 res.returnMsg, extras); 1067 } catch (RemoteException e) { 1068 Slog.i(TAG, "Observer no longer exists."); 1069 } 1070 } 1071 } else { 1072 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1073 } 1074 } break; 1075 case UPDATED_MEDIA_STATUS: { 1076 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1077 boolean reportStatus = msg.arg1 == 1; 1078 boolean doGc = msg.arg2 == 1; 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1080 if (doGc) { 1081 // Force a gc to clear up stale containers. 1082 Runtime.getRuntime().gc(); 1083 } 1084 if (msg.obj != null) { 1085 @SuppressWarnings("unchecked") 1086 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1088 // Unload containers 1089 unloadAllContainers(args); 1090 } 1091 if (reportStatus) { 1092 try { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1094 PackageHelper.getMountService().finishMediaUpdate(); 1095 } catch (RemoteException e) { 1096 Log.e(TAG, "MountService not running?"); 1097 } 1098 } 1099 } break; 1100 case WRITE_SETTINGS: { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1102 synchronized (mPackages) { 1103 removeMessages(WRITE_SETTINGS); 1104 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1105 mSettings.writeLPr(); 1106 mDirtyUsers.clear(); 1107 } 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1109 } break; 1110 case WRITE_PACKAGE_RESTRICTIONS: { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1112 synchronized (mPackages) { 1113 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1114 for (int userId : mDirtyUsers) { 1115 mSettings.writePackageRestrictionsLPr(userId); 1116 } 1117 mDirtyUsers.clear(); 1118 } 1119 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1120 } break; 1121 case CHECK_PENDING_VERIFICATION: { 1122 final int verificationId = msg.arg1; 1123 final PackageVerificationState state = mPendingVerification.get(verificationId); 1124 1125 if ((state != null) && !state.timeoutExtended()) { 1126 final InstallArgs args = state.getInstallArgs(); 1127 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1128 1129 Slog.i(TAG, "Verification timed out for " + originUri); 1130 mPendingVerification.remove(verificationId); 1131 1132 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1133 1134 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1135 Slog.i(TAG, "Continuing with installation of " + originUri); 1136 state.setVerifierResponse(Binder.getCallingUid(), 1137 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1138 broadcastPackageVerified(verificationId, originUri, 1139 PackageManager.VERIFICATION_ALLOW, 1140 state.getInstallArgs().getUser()); 1141 try { 1142 ret = args.copyApk(mContainerService, true); 1143 } catch (RemoteException e) { 1144 Slog.e(TAG, "Could not contact the ContainerService"); 1145 } 1146 } else { 1147 broadcastPackageVerified(verificationId, originUri, 1148 PackageManager.VERIFICATION_REJECT, 1149 state.getInstallArgs().getUser()); 1150 } 1151 1152 processPendingInstall(args, ret); 1153 mHandler.sendEmptyMessage(MCS_UNBIND); 1154 } 1155 break; 1156 } 1157 case PACKAGE_VERIFIED: { 1158 final int verificationId = msg.arg1; 1159 1160 final PackageVerificationState state = mPendingVerification.get(verificationId); 1161 if (state == null) { 1162 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1163 break; 1164 } 1165 1166 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1167 1168 state.setVerifierResponse(response.callerUid, response.code); 1169 1170 if (state.isVerificationComplete()) { 1171 mPendingVerification.remove(verificationId); 1172 1173 final InstallArgs args = state.getInstallArgs(); 1174 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1175 1176 int ret; 1177 if (state.isInstallAllowed()) { 1178 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1179 broadcastPackageVerified(verificationId, originUri, 1180 response.code, state.getInstallArgs().getUser()); 1181 try { 1182 ret = args.copyApk(mContainerService, true); 1183 } catch (RemoteException e) { 1184 Slog.e(TAG, "Could not contact the ContainerService"); 1185 } 1186 } else { 1187 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1188 } 1189 1190 processPendingInstall(args, ret); 1191 1192 mHandler.sendEmptyMessage(MCS_UNBIND); 1193 } 1194 1195 break; 1196 } 1197 } 1198 } 1199 } 1200 1201 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1202 Bundle extras = null; 1203 switch (res.returnCode) { 1204 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1205 extras = new Bundle(); 1206 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1207 res.origPermission); 1208 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1209 res.origPackage); 1210 break; 1211 } 1212 } 1213 return extras; 1214 } 1215 1216 void scheduleWriteSettingsLocked() { 1217 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1218 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1219 } 1220 } 1221 1222 void scheduleWritePackageRestrictionsLocked(int userId) { 1223 if (!sUserManager.exists(userId)) return; 1224 mDirtyUsers.add(userId); 1225 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1226 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1227 } 1228 } 1229 1230 public static final PackageManagerService main(Context context, Installer installer, 1231 boolean factoryTest, boolean onlyCore) { 1232 PackageManagerService m = new PackageManagerService(context, installer, 1233 factoryTest, onlyCore); 1234 ServiceManager.addService("package", m); 1235 return m; 1236 } 1237 1238 static String[] splitString(String str, char sep) { 1239 int count = 1; 1240 int i = 0; 1241 while ((i=str.indexOf(sep, i)) >= 0) { 1242 count++; 1243 i++; 1244 } 1245 1246 String[] res = new String[count]; 1247 i=0; 1248 count = 0; 1249 int lastI=0; 1250 while ((i=str.indexOf(sep, i)) >= 0) { 1251 res[count] = str.substring(lastI, i); 1252 count++; 1253 i++; 1254 lastI = i; 1255 } 1256 res[count] = str.substring(lastI, str.length()); 1257 return res; 1258 } 1259 1260 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1261 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1262 Context.DISPLAY_SERVICE); 1263 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1264 } 1265 1266 public PackageManagerService(Context context, Installer installer, 1267 boolean factoryTest, boolean onlyCore) { 1268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1269 SystemClock.uptimeMillis()); 1270 1271 if (mSdkVersion <= 0) { 1272 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1273 } 1274 1275 mContext = context; 1276 mFactoryTest = factoryTest; 1277 mOnlyCore = onlyCore; 1278 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1279 mMetrics = new DisplayMetrics(); 1280 mSettings = new Settings(context); 1281 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 1294 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1295 if (separateProcesses != null && separateProcesses.length() > 0) { 1296 if ("*".equals(separateProcesses)) { 1297 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1298 mSeparateProcesses = null; 1299 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1300 } else { 1301 mDefParseFlags = 0; 1302 mSeparateProcesses = separateProcesses.split(","); 1303 Slog.w(TAG, "Running with debug.separate_processes: " 1304 + separateProcesses); 1305 } 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = null; 1309 } 1310 1311 mInstaller = installer; 1312 1313 getDefaultDisplayMetrics(context, mMetrics); 1314 1315 SystemConfig systemConfig = SystemConfig.getInstance(); 1316 mGlobalGids = systemConfig.getGlobalGids(); 1317 mSystemPermissions = systemConfig.getSystemPermissions(); 1318 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1319 1320 synchronized (mInstallLock) { 1321 // writer 1322 synchronized (mPackages) { 1323 mHandlerThread = new ServiceThread(TAG, 1324 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1325 mHandlerThread.start(); 1326 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1327 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1328 1329 File dataDir = Environment.getDataDirectory(); 1330 mAppDataDir = new File(dataDir, "data"); 1331 mAppInstallDir = new File(dataDir, "app"); 1332 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1333 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1334 mUserAppDataDir = new File(dataDir, "user"); 1335 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1336 1337 sUserManager = new UserManagerService(context, this, 1338 mInstallLock, mPackages); 1339 1340 // Propagate permission configuration in to package manager. 1341 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1342 = systemConfig.getPermissions(); 1343 for (int i=0; i<permConfig.size(); i++) { 1344 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1345 BasePermission bp = mSettings.mPermissions.get(perm.name); 1346 if (bp == null) { 1347 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1348 mSettings.mPermissions.put(perm.name, bp); 1349 } 1350 if (perm.gids != null) { 1351 bp.gids = appendInts(bp.gids, perm.gids); 1352 } 1353 } 1354 1355 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1356 for (int i=0; i<libConfig.size(); i++) { 1357 mSharedLibraries.put(libConfig.keyAt(i), 1358 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1359 } 1360 1361 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1362 1363 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1364 mSdkVersion, mOnlyCore); 1365 1366 String customResolverActivity = Resources.getSystem().getString( 1367 R.string.config_customResolverActivity); 1368 if (TextUtils.isEmpty(customResolverActivity)) { 1369 customResolverActivity = null; 1370 } else { 1371 mCustomResolverComponentName = ComponentName.unflattenFromString( 1372 customResolverActivity); 1373 } 1374 1375 long startTime = SystemClock.uptimeMillis(); 1376 1377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1378 startTime); 1379 1380 // Set flag to monitor and not change apk file paths when 1381 // scanning install directories. 1382 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1383 1384 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1385 1386 /** 1387 * Add everything in the in the boot class path to the 1388 * list of process files because dexopt will have been run 1389 * if necessary during zygote startup. 1390 */ 1391 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1392 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1393 1394 if (bootClassPath != null) { 1395 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1396 for (String element : bootClassPathElements) { 1397 alreadyDexOpted.add(element); 1398 } 1399 } else { 1400 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1401 } 1402 1403 if (systemServerClassPath != null) { 1404 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1405 for (String element : systemServerClassPathElements) { 1406 alreadyDexOpted.add(element); 1407 } 1408 } else { 1409 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1410 } 1411 1412 boolean didDexOptLibraryOrTool = false; 1413 1414 final List<String> allInstructionSets = getAllInstructionSets(); 1415 final String[] dexCodeInstructionSets = 1416 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1417 1418 /** 1419 * Ensure all external libraries have had dexopt run on them. 1420 */ 1421 if (mSharedLibraries.size() > 0) { 1422 // NOTE: For now, we're compiling these system "shared libraries" 1423 // (and framework jars) into all available architectures. It's possible 1424 // to compile them only when we come across an app that uses them (there's 1425 // already logic for that in scanPackageLI) but that adds some complexity. 1426 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1427 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1428 final String lib = libEntry.path; 1429 if (lib == null) { 1430 continue; 1431 } 1432 1433 try { 1434 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1435 dexCodeInstructionSet, 1436 false); 1437 if (dexoptRequired != DexFile.UP_TO_DATE) { 1438 alreadyDexOpted.add(lib); 1439 1440 // The list of "shared libraries" we have at this point is 1441 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1442 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1443 } else { 1444 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1445 } 1446 didDexOptLibraryOrTool = true; 1447 } 1448 } catch (FileNotFoundException e) { 1449 Slog.w(TAG, "Library not found: " + lib); 1450 } catch (IOException e) { 1451 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1452 + e.getMessage()); 1453 } 1454 } 1455 } 1456 } 1457 1458 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1459 1460 // Gross hack for now: we know this file doesn't contain any 1461 // code, so don't dexopt it to avoid the resulting log spew. 1462 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1463 1464 // Gross hack for now: we know this file is only part of 1465 // the boot class path for art, so don't dexopt it to 1466 // avoid the resulting log spew. 1467 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1468 1469 /** 1470 * And there are a number of commands implemented in Java, which 1471 * we currently need to do the dexopt on so that they can be 1472 * run from a non-root shell. 1473 */ 1474 String[] frameworkFiles = frameworkDir.list(); 1475 if (frameworkFiles != null) { 1476 // TODO: We could compile these only for the most preferred ABI. We should 1477 // first double check that the dex files for these commands are not referenced 1478 // by other system apps. 1479 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1480 for (int i=0; i<frameworkFiles.length; i++) { 1481 File libPath = new File(frameworkDir, frameworkFiles[i]); 1482 String path = libPath.getPath(); 1483 // Skip the file if we already did it. 1484 if (alreadyDexOpted.contains(path)) { 1485 continue; 1486 } 1487 // Skip the file if it is not a type we want to dexopt. 1488 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1489 continue; 1490 } 1491 try { 1492 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1493 dexCodeInstructionSet, 1494 false); 1495 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1496 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1497 didDexOptLibraryOrTool = true; 1498 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1499 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1500 didDexOptLibraryOrTool = true; 1501 } 1502 } catch (FileNotFoundException e) { 1503 Slog.w(TAG, "Jar not found: " + path); 1504 } catch (IOException e) { 1505 Slog.w(TAG, "Exception reading jar: " + path, e); 1506 } 1507 } 1508 } 1509 } 1510 1511 // Collect vendor overlay packages. 1512 // (Do this before scanning any apps.) 1513 // For security and version matching reason, only consider 1514 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1515 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1516 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1518 1519 // Find base frameworks (resource packages without code). 1520 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1521 | PackageParser.PARSE_IS_SYSTEM_DIR 1522 | PackageParser.PARSE_IS_PRIVILEGED, 1523 scanFlags | SCAN_NO_DEX, 0); 1524 1525 // Collected privileged system packages. 1526 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1527 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1528 | PackageParser.PARSE_IS_SYSTEM_DIR 1529 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1530 1531 // Collect ordinary system packages. 1532 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1533 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1534 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1535 1536 // Collect all vendor packages. 1537 File vendorAppDir = new File("/vendor/app"); 1538 try { 1539 vendorAppDir = vendorAppDir.getCanonicalFile(); 1540 } catch (IOException e) { 1541 // failed to look up canonical path, continue with original one 1542 } 1543 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1544 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1545 1546 // Collect all OEM packages. 1547 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1548 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1549 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1550 1551 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1552 mInstaller.moveFiles(); 1553 1554 // Prune any system packages that no longer exist. 1555 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1556 if (!mOnlyCore) { 1557 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1558 while (psit.hasNext()) { 1559 PackageSetting ps = psit.next(); 1560 1561 /* 1562 * If this is not a system app, it can't be a 1563 * disable system app. 1564 */ 1565 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1566 continue; 1567 } 1568 1569 /* 1570 * If the package is scanned, it's not erased. 1571 */ 1572 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1573 if (scannedPkg != null) { 1574 /* 1575 * If the system app is both scanned and in the 1576 * disabled packages list, then it must have been 1577 * added via OTA. Remove it from the currently 1578 * scanned package so the previously user-installed 1579 * application can be scanned. 1580 */ 1581 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1582 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1583 + ps.name + "; removing system app. Last known codePath=" 1584 + ps.codePathString + ", installStatus=" + ps.installStatus 1585 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1586 + scannedPkg.mVersionCode); 1587 removePackageLI(ps, true); 1588 } 1589 1590 continue; 1591 } 1592 1593 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1594 psit.remove(); 1595 logCriticalInfo(Log.WARN, "System package " + ps.name 1596 + " no longer exists; wiping its data"); 1597 removeDataDirsLI(ps.name); 1598 } else { 1599 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1600 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1601 possiblyDeletedUpdatedSystemApps.add(ps.name); 1602 } 1603 } 1604 } 1605 } 1606 1607 //look for any incomplete package installations 1608 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1609 //clean up list 1610 for(int i = 0; i < deletePkgsList.size(); i++) { 1611 //clean up here 1612 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1613 } 1614 //delete tmp files 1615 deleteTempPackageFiles(); 1616 1617 // Remove any shared userIDs that have no associated packages 1618 mSettings.pruneSharedUsersLPw(); 1619 1620 if (!mOnlyCore) { 1621 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1622 SystemClock.uptimeMillis()); 1623 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1624 1625 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1626 scanFlags, 0); 1627 1628 /** 1629 * Remove disable package settings for any updated system 1630 * apps that were removed via an OTA. If they're not a 1631 * previously-updated app, remove them completely. 1632 * Otherwise, just revoke their system-level permissions. 1633 */ 1634 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1635 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1636 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1637 1638 String msg; 1639 if (deletedPkg == null) { 1640 msg = "Updated system package " + deletedAppName 1641 + " no longer exists; wiping its data"; 1642 removeDataDirsLI(deletedAppName); 1643 } else { 1644 msg = "Updated system app + " + deletedAppName 1645 + " no longer present; removing system privileges for " 1646 + deletedAppName; 1647 1648 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1649 1650 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1651 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1652 } 1653 logCriticalInfo(Log.WARN, msg); 1654 } 1655 } 1656 1657 // Now that we know all of the shared libraries, update all clients to have 1658 // the correct library paths. 1659 updateAllSharedLibrariesLPw(); 1660 1661 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1662 // NOTE: We ignore potential failures here during a system scan (like 1663 // the rest of the commands above) because there's precious little we 1664 // can do about it. A settings error is reported, though. 1665 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1666 false /* force dexopt */, false /* defer dexopt */); 1667 } 1668 1669 // Now that we know all the packages we are keeping, 1670 // read and update their last usage times. 1671 mPackageUsage.readLP(); 1672 1673 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1674 SystemClock.uptimeMillis()); 1675 Slog.i(TAG, "Time to scan packages: " 1676 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1677 + " seconds"); 1678 1679 // If the platform SDK has changed since the last time we booted, 1680 // we need to re-grant app permission to catch any new ones that 1681 // appear. This is really a hack, and means that apps can in some 1682 // cases get permissions that the user didn't initially explicitly 1683 // allow... it would be nice to have some better way to handle 1684 // this situation. 1685 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1686 != mSdkVersion; 1687 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1688 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1689 + "; regranting permissions for internal storage"); 1690 mSettings.mInternalSdkPlatform = mSdkVersion; 1691 1692 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1693 | (regrantPermissions 1694 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1695 : 0)); 1696 1697 // If this is the first boot, and it is a normal boot, then 1698 // we need to initialize the default preferred apps. 1699 if (!mRestoredSettings && !onlyCore) { 1700 mSettings.readDefaultPreferredAppsLPw(this, 0); 1701 } 1702 1703 // If this is first boot after an OTA, and a normal boot, then 1704 // we need to clear code cache directories. 1705 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1706 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1707 for (String pkgName : mSettings.mPackages.keySet()) { 1708 deleteCodeCacheDirsLI(pkgName); 1709 } 1710 mSettings.mFingerprint = Build.FINGERPRINT; 1711 } 1712 1713 // All the changes are done during package scanning. 1714 mSettings.updateInternalDatabaseVersion(); 1715 1716 // can downgrade to reader 1717 mSettings.writeLPr(); 1718 1719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1720 SystemClock.uptimeMillis()); 1721 1722 1723 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1724 } // synchronized (mPackages) 1725 } // synchronized (mInstallLock) 1726 1727 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1728 1729 // Now after opening every single application zip, make sure they 1730 // are all flushed. Not really needed, but keeps things nice and 1731 // tidy. 1732 Runtime.getRuntime().gc(); 1733 } 1734 1735 @Override 1736 public boolean isFirstBoot() { 1737 return !mRestoredSettings; 1738 } 1739 1740 @Override 1741 public boolean isOnlyCoreApps() { 1742 return mOnlyCore; 1743 } 1744 1745 private String getRequiredVerifierLPr() { 1746 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1747 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1748 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1749 1750 String requiredVerifier = null; 1751 1752 final int N = receivers.size(); 1753 for (int i = 0; i < N; i++) { 1754 final ResolveInfo info = receivers.get(i); 1755 1756 if (info.activityInfo == null) { 1757 continue; 1758 } 1759 1760 final String packageName = info.activityInfo.packageName; 1761 1762 final PackageSetting ps = mSettings.mPackages.get(packageName); 1763 if (ps == null) { 1764 continue; 1765 } 1766 1767 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1768 if (!gp.grantedPermissions 1769 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1770 continue; 1771 } 1772 1773 if (requiredVerifier != null) { 1774 throw new RuntimeException("There can be only one required verifier"); 1775 } 1776 1777 requiredVerifier = packageName; 1778 } 1779 1780 return requiredVerifier; 1781 } 1782 1783 @Override 1784 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1785 throws RemoteException { 1786 try { 1787 return super.onTransact(code, data, reply, flags); 1788 } catch (RuntimeException e) { 1789 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1790 Slog.wtf(TAG, "Package Manager Crash", e); 1791 } 1792 throw e; 1793 } 1794 } 1795 1796 void cleanupInstallFailedPackage(PackageSetting ps) { 1797 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1798 1799 removeDataDirsLI(ps.name); 1800 if (ps.codePath != null) { 1801 if (ps.codePath.isDirectory()) { 1802 FileUtils.deleteContents(ps.codePath); 1803 } 1804 ps.codePath.delete(); 1805 } 1806 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1807 if (ps.resourcePath.isDirectory()) { 1808 FileUtils.deleteContents(ps.resourcePath); 1809 } 1810 ps.resourcePath.delete(); 1811 } 1812 mSettings.removePackageLPw(ps.name); 1813 } 1814 1815 static int[] appendInts(int[] cur, int[] add) { 1816 if (add == null) return cur; 1817 if (cur == null) return add; 1818 final int N = add.length; 1819 for (int i=0; i<N; i++) { 1820 cur = appendInt(cur, add[i]); 1821 } 1822 return cur; 1823 } 1824 1825 static int[] removeInts(int[] cur, int[] rem) { 1826 if (rem == null) return cur; 1827 if (cur == null) return cur; 1828 final int N = rem.length; 1829 for (int i=0; i<N; i++) { 1830 cur = removeInt(cur, rem[i]); 1831 } 1832 return cur; 1833 } 1834 1835 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1836 if (!sUserManager.exists(userId)) return null; 1837 final PackageSetting ps = (PackageSetting) p.mExtras; 1838 if (ps == null) { 1839 return null; 1840 } 1841 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1842 final PackageUserState state = ps.readUserState(userId); 1843 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1844 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1845 state, userId); 1846 } 1847 1848 @Override 1849 public boolean isPackageAvailable(String packageName, int userId) { 1850 if (!sUserManager.exists(userId)) return false; 1851 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1852 synchronized (mPackages) { 1853 PackageParser.Package p = mPackages.get(packageName); 1854 if (p != null) { 1855 final PackageSetting ps = (PackageSetting) p.mExtras; 1856 if (ps != null) { 1857 final PackageUserState state = ps.readUserState(userId); 1858 if (state != null) { 1859 return PackageParser.isAvailable(state); 1860 } 1861 } 1862 } 1863 } 1864 return false; 1865 } 1866 1867 @Override 1868 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1869 if (!sUserManager.exists(userId)) return null; 1870 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1871 // reader 1872 synchronized (mPackages) { 1873 PackageParser.Package p = mPackages.get(packageName); 1874 if (DEBUG_PACKAGE_INFO) 1875 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1876 if (p != null) { 1877 return generatePackageInfo(p, flags, userId); 1878 } 1879 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1880 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1881 } 1882 } 1883 return null; 1884 } 1885 1886 @Override 1887 public String[] currentToCanonicalPackageNames(String[] names) { 1888 String[] out = new String[names.length]; 1889 // reader 1890 synchronized (mPackages) { 1891 for (int i=names.length-1; i>=0; i--) { 1892 PackageSetting ps = mSettings.mPackages.get(names[i]); 1893 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1894 } 1895 } 1896 return out; 1897 } 1898 1899 @Override 1900 public String[] canonicalToCurrentPackageNames(String[] names) { 1901 String[] out = new String[names.length]; 1902 // reader 1903 synchronized (mPackages) { 1904 for (int i=names.length-1; i>=0; i--) { 1905 String cur = mSettings.mRenamedPackages.get(names[i]); 1906 out[i] = cur != null ? cur : names[i]; 1907 } 1908 } 1909 return out; 1910 } 1911 1912 @Override 1913 public int getPackageUid(String packageName, int userId) { 1914 if (!sUserManager.exists(userId)) return -1; 1915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1916 // reader 1917 synchronized (mPackages) { 1918 PackageParser.Package p = mPackages.get(packageName); 1919 if(p != null) { 1920 return UserHandle.getUid(userId, p.applicationInfo.uid); 1921 } 1922 PackageSetting ps = mSettings.mPackages.get(packageName); 1923 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1924 return -1; 1925 } 1926 p = ps.pkg; 1927 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1928 } 1929 } 1930 1931 @Override 1932 public int[] getPackageGids(String packageName) { 1933 // reader 1934 synchronized (mPackages) { 1935 PackageParser.Package p = mPackages.get(packageName); 1936 if (DEBUG_PACKAGE_INFO) 1937 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1938 if (p != null) { 1939 final PackageSetting ps = (PackageSetting)p.mExtras; 1940 return ps.getGids(); 1941 } 1942 } 1943 // stupid thing to indicate an error. 1944 return new int[0]; 1945 } 1946 1947 static final PermissionInfo generatePermissionInfo( 1948 BasePermission bp, int flags) { 1949 if (bp.perm != null) { 1950 return PackageParser.generatePermissionInfo(bp.perm, flags); 1951 } 1952 PermissionInfo pi = new PermissionInfo(); 1953 pi.name = bp.name; 1954 pi.packageName = bp.sourcePackage; 1955 pi.nonLocalizedLabel = bp.name; 1956 pi.protectionLevel = bp.protectionLevel; 1957 return pi; 1958 } 1959 1960 @Override 1961 public PermissionInfo getPermissionInfo(String name, int flags) { 1962 // reader 1963 synchronized (mPackages) { 1964 final BasePermission p = mSettings.mPermissions.get(name); 1965 if (p != null) { 1966 return generatePermissionInfo(p, flags); 1967 } 1968 return null; 1969 } 1970 } 1971 1972 @Override 1973 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1974 // reader 1975 synchronized (mPackages) { 1976 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1977 for (BasePermission p : mSettings.mPermissions.values()) { 1978 if (group == null) { 1979 if (p.perm == null || p.perm.info.group == null) { 1980 out.add(generatePermissionInfo(p, flags)); 1981 } 1982 } else { 1983 if (p.perm != null && group.equals(p.perm.info.group)) { 1984 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1985 } 1986 } 1987 } 1988 1989 if (out.size() > 0) { 1990 return out; 1991 } 1992 return mPermissionGroups.containsKey(group) ? out : null; 1993 } 1994 } 1995 1996 @Override 1997 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1998 // reader 1999 synchronized (mPackages) { 2000 return PackageParser.generatePermissionGroupInfo( 2001 mPermissionGroups.get(name), flags); 2002 } 2003 } 2004 2005 @Override 2006 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2007 // reader 2008 synchronized (mPackages) { 2009 final int N = mPermissionGroups.size(); 2010 ArrayList<PermissionGroupInfo> out 2011 = new ArrayList<PermissionGroupInfo>(N); 2012 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2013 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2014 } 2015 return out; 2016 } 2017 } 2018 2019 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2020 int userId) { 2021 if (!sUserManager.exists(userId)) return null; 2022 PackageSetting ps = mSettings.mPackages.get(packageName); 2023 if (ps != null) { 2024 if (ps.pkg == null) { 2025 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2026 flags, userId); 2027 if (pInfo != null) { 2028 return pInfo.applicationInfo; 2029 } 2030 return null; 2031 } 2032 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2033 ps.readUserState(userId), userId); 2034 } 2035 return null; 2036 } 2037 2038 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2039 int userId) { 2040 if (!sUserManager.exists(userId)) return null; 2041 PackageSetting ps = mSettings.mPackages.get(packageName); 2042 if (ps != null) { 2043 PackageParser.Package pkg = ps.pkg; 2044 if (pkg == null) { 2045 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2046 return null; 2047 } 2048 // Only data remains, so we aren't worried about code paths 2049 pkg = new PackageParser.Package(packageName); 2050 pkg.applicationInfo.packageName = packageName; 2051 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2052 pkg.applicationInfo.dataDir = 2053 getDataPathForPackage(packageName, 0).getPath(); 2054 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2055 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2056 } 2057 return generatePackageInfo(pkg, flags, userId); 2058 } 2059 return null; 2060 } 2061 2062 @Override 2063 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2064 if (!sUserManager.exists(userId)) return null; 2065 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2066 // writer 2067 synchronized (mPackages) { 2068 PackageParser.Package p = mPackages.get(packageName); 2069 if (DEBUG_PACKAGE_INFO) Log.v( 2070 TAG, "getApplicationInfo " + packageName 2071 + ": " + p); 2072 if (p != null) { 2073 PackageSetting ps = mSettings.mPackages.get(packageName); 2074 if (ps == null) return null; 2075 // Note: isEnabledLP() does not apply here - always return info 2076 return PackageParser.generateApplicationInfo( 2077 p, flags, ps.readUserState(userId), userId); 2078 } 2079 if ("android".equals(packageName)||"system".equals(packageName)) { 2080 return mAndroidApplication; 2081 } 2082 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2083 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2084 } 2085 } 2086 return null; 2087 } 2088 2089 2090 @Override 2091 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2092 mContext.enforceCallingOrSelfPermission( 2093 android.Manifest.permission.CLEAR_APP_CACHE, null); 2094 // Queue up an async operation since clearing cache may take a little while. 2095 mHandler.post(new Runnable() { 2096 public void run() { 2097 mHandler.removeCallbacks(this); 2098 int retCode = -1; 2099 synchronized (mInstallLock) { 2100 retCode = mInstaller.freeCache(freeStorageSize); 2101 if (retCode < 0) { 2102 Slog.w(TAG, "Couldn't clear application caches"); 2103 } 2104 } 2105 if (observer != null) { 2106 try { 2107 observer.onRemoveCompleted(null, (retCode >= 0)); 2108 } catch (RemoteException e) { 2109 Slog.w(TAG, "RemoveException when invoking call back"); 2110 } 2111 } 2112 } 2113 }); 2114 } 2115 2116 @Override 2117 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2118 mContext.enforceCallingOrSelfPermission( 2119 android.Manifest.permission.CLEAR_APP_CACHE, null); 2120 // Queue up an async operation since clearing cache may take a little while. 2121 mHandler.post(new Runnable() { 2122 public void run() { 2123 mHandler.removeCallbacks(this); 2124 int retCode = -1; 2125 synchronized (mInstallLock) { 2126 retCode = mInstaller.freeCache(freeStorageSize); 2127 if (retCode < 0) { 2128 Slog.w(TAG, "Couldn't clear application caches"); 2129 } 2130 } 2131 if(pi != null) { 2132 try { 2133 // Callback via pending intent 2134 int code = (retCode >= 0) ? 1 : 0; 2135 pi.sendIntent(null, code, null, 2136 null, null); 2137 } catch (SendIntentException e1) { 2138 Slog.i(TAG, "Failed to send pending intent"); 2139 } 2140 } 2141 } 2142 }); 2143 } 2144 2145 void freeStorage(long freeStorageSize) throws IOException { 2146 synchronized (mInstallLock) { 2147 if (mInstaller.freeCache(freeStorageSize) < 0) { 2148 throw new IOException("Failed to free enough space"); 2149 } 2150 } 2151 } 2152 2153 @Override 2154 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2155 if (!sUserManager.exists(userId)) return null; 2156 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2157 synchronized (mPackages) { 2158 PackageParser.Activity a = mActivities.mActivities.get(component); 2159 2160 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2161 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2162 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2163 if (ps == null) return null; 2164 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2165 userId); 2166 } 2167 if (mResolveComponentName.equals(component)) { 2168 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2169 new PackageUserState(), userId); 2170 } 2171 } 2172 return null; 2173 } 2174 2175 @Override 2176 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2177 String resolvedType) { 2178 synchronized (mPackages) { 2179 PackageParser.Activity a = mActivities.mActivities.get(component); 2180 if (a == null) { 2181 return false; 2182 } 2183 for (int i=0; i<a.intents.size(); i++) { 2184 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2185 intent.getData(), intent.getCategories(), TAG) >= 0) { 2186 return true; 2187 } 2188 } 2189 return false; 2190 } 2191 } 2192 2193 @Override 2194 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2195 if (!sUserManager.exists(userId)) return null; 2196 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2197 synchronized (mPackages) { 2198 PackageParser.Activity a = mReceivers.mActivities.get(component); 2199 if (DEBUG_PACKAGE_INFO) Log.v( 2200 TAG, "getReceiverInfo " + component + ": " + a); 2201 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2202 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2203 if (ps == null) return null; 2204 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2205 userId); 2206 } 2207 } 2208 return null; 2209 } 2210 2211 @Override 2212 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2213 if (!sUserManager.exists(userId)) return null; 2214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2215 synchronized (mPackages) { 2216 PackageParser.Service s = mServices.mServices.get(component); 2217 if (DEBUG_PACKAGE_INFO) Log.v( 2218 TAG, "getServiceInfo " + component + ": " + s); 2219 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2220 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2221 if (ps == null) return null; 2222 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2223 userId); 2224 } 2225 } 2226 return null; 2227 } 2228 2229 @Override 2230 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2231 if (!sUserManager.exists(userId)) return null; 2232 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2233 synchronized (mPackages) { 2234 PackageParser.Provider p = mProviders.mProviders.get(component); 2235 if (DEBUG_PACKAGE_INFO) Log.v( 2236 TAG, "getProviderInfo " + component + ": " + p); 2237 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2238 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2239 if (ps == null) return null; 2240 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2241 userId); 2242 } 2243 } 2244 return null; 2245 } 2246 2247 @Override 2248 public String[] getSystemSharedLibraryNames() { 2249 Set<String> libSet; 2250 synchronized (mPackages) { 2251 libSet = mSharedLibraries.keySet(); 2252 int size = libSet.size(); 2253 if (size > 0) { 2254 String[] libs = new String[size]; 2255 libSet.toArray(libs); 2256 return libs; 2257 } 2258 } 2259 return null; 2260 } 2261 2262 @Override 2263 public FeatureInfo[] getSystemAvailableFeatures() { 2264 Collection<FeatureInfo> featSet; 2265 synchronized (mPackages) { 2266 featSet = mAvailableFeatures.values(); 2267 int size = featSet.size(); 2268 if (size > 0) { 2269 FeatureInfo[] features = new FeatureInfo[size+1]; 2270 featSet.toArray(features); 2271 FeatureInfo fi = new FeatureInfo(); 2272 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2273 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2274 features[size] = fi; 2275 return features; 2276 } 2277 } 2278 return null; 2279 } 2280 2281 @Override 2282 public boolean hasSystemFeature(String name) { 2283 synchronized (mPackages) { 2284 return mAvailableFeatures.containsKey(name); 2285 } 2286 } 2287 2288 private void checkValidCaller(int uid, int userId) { 2289 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2290 return; 2291 2292 throw new SecurityException("Caller uid=" + uid 2293 + " is not privileged to communicate with user=" + userId); 2294 } 2295 2296 @Override 2297 public int checkPermission(String permName, String pkgName) { 2298 synchronized (mPackages) { 2299 PackageParser.Package p = mPackages.get(pkgName); 2300 if (p != null && p.mExtras != null) { 2301 PackageSetting ps = (PackageSetting)p.mExtras; 2302 if (ps.sharedUser != null) { 2303 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2304 return PackageManager.PERMISSION_GRANTED; 2305 } 2306 } else if (ps.grantedPermissions.contains(permName)) { 2307 return PackageManager.PERMISSION_GRANTED; 2308 } 2309 } 2310 } 2311 return PackageManager.PERMISSION_DENIED; 2312 } 2313 2314 @Override 2315 public int checkUidPermission(String permName, int uid) { 2316 synchronized (mPackages) { 2317 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2318 if (obj != null) { 2319 GrantedPermissions gp = (GrantedPermissions)obj; 2320 if (gp.grantedPermissions.contains(permName)) { 2321 return PackageManager.PERMISSION_GRANTED; 2322 } 2323 } else { 2324 HashSet<String> perms = mSystemPermissions.get(uid); 2325 if (perms != null && perms.contains(permName)) { 2326 return PackageManager.PERMISSION_GRANTED; 2327 } 2328 } 2329 } 2330 return PackageManager.PERMISSION_DENIED; 2331 } 2332 2333 /** 2334 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2335 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2336 * @param checkShell TODO(yamasani): 2337 * @param message the message to log on security exception 2338 */ 2339 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2340 boolean checkShell, String message) { 2341 if (userId < 0) { 2342 throw new IllegalArgumentException("Invalid userId " + userId); 2343 } 2344 if (checkShell) { 2345 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2346 } 2347 if (userId == UserHandle.getUserId(callingUid)) return; 2348 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2349 if (requireFullPermission) { 2350 mContext.enforceCallingOrSelfPermission( 2351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2352 } else { 2353 try { 2354 mContext.enforceCallingOrSelfPermission( 2355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2356 } catch (SecurityException se) { 2357 mContext.enforceCallingOrSelfPermission( 2358 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2359 } 2360 } 2361 } 2362 } 2363 2364 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2365 if (callingUid == Process.SHELL_UID) { 2366 if (userHandle >= 0 2367 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2368 throw new SecurityException("Shell does not have permission to access user " 2369 + userHandle); 2370 } else if (userHandle < 0) { 2371 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2372 + Debug.getCallers(3)); 2373 } 2374 } 2375 } 2376 2377 private BasePermission findPermissionTreeLP(String permName) { 2378 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2379 if (permName.startsWith(bp.name) && 2380 permName.length() > bp.name.length() && 2381 permName.charAt(bp.name.length()) == '.') { 2382 return bp; 2383 } 2384 } 2385 return null; 2386 } 2387 2388 private BasePermission checkPermissionTreeLP(String permName) { 2389 if (permName != null) { 2390 BasePermission bp = findPermissionTreeLP(permName); 2391 if (bp != null) { 2392 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2393 return bp; 2394 } 2395 throw new SecurityException("Calling uid " 2396 + Binder.getCallingUid() 2397 + " is not allowed to add to permission tree " 2398 + bp.name + " owned by uid " + bp.uid); 2399 } 2400 } 2401 throw new SecurityException("No permission tree found for " + permName); 2402 } 2403 2404 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2405 if (s1 == null) { 2406 return s2 == null; 2407 } 2408 if (s2 == null) { 2409 return false; 2410 } 2411 if (s1.getClass() != s2.getClass()) { 2412 return false; 2413 } 2414 return s1.equals(s2); 2415 } 2416 2417 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2418 if (pi1.icon != pi2.icon) return false; 2419 if (pi1.logo != pi2.logo) return false; 2420 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2421 if (!compareStrings(pi1.name, pi2.name)) return false; 2422 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2423 // We'll take care of setting this one. 2424 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2425 // These are not currently stored in settings. 2426 //if (!compareStrings(pi1.group, pi2.group)) return false; 2427 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2428 //if (pi1.labelRes != pi2.labelRes) return false; 2429 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2430 return true; 2431 } 2432 2433 int permissionInfoFootprint(PermissionInfo info) { 2434 int size = info.name.length(); 2435 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2436 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2437 return size; 2438 } 2439 2440 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2441 int size = 0; 2442 for (BasePermission perm : mSettings.mPermissions.values()) { 2443 if (perm.uid == tree.uid) { 2444 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2445 } 2446 } 2447 return size; 2448 } 2449 2450 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2451 // We calculate the max size of permissions defined by this uid and throw 2452 // if that plus the size of 'info' would exceed our stated maximum. 2453 if (tree.uid != Process.SYSTEM_UID) { 2454 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2455 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2456 throw new SecurityException("Permission tree size cap exceeded"); 2457 } 2458 } 2459 } 2460 2461 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2462 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2463 throw new SecurityException("Label must be specified in permission"); 2464 } 2465 BasePermission tree = checkPermissionTreeLP(info.name); 2466 BasePermission bp = mSettings.mPermissions.get(info.name); 2467 boolean added = bp == null; 2468 boolean changed = true; 2469 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2470 if (added) { 2471 enforcePermissionCapLocked(info, tree); 2472 bp = new BasePermission(info.name, tree.sourcePackage, 2473 BasePermission.TYPE_DYNAMIC); 2474 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2475 throw new SecurityException( 2476 "Not allowed to modify non-dynamic permission " 2477 + info.name); 2478 } else { 2479 if (bp.protectionLevel == fixedLevel 2480 && bp.perm.owner.equals(tree.perm.owner) 2481 && bp.uid == tree.uid 2482 && comparePermissionInfos(bp.perm.info, info)) { 2483 changed = false; 2484 } 2485 } 2486 bp.protectionLevel = fixedLevel; 2487 info = new PermissionInfo(info); 2488 info.protectionLevel = fixedLevel; 2489 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2490 bp.perm.info.packageName = tree.perm.info.packageName; 2491 bp.uid = tree.uid; 2492 if (added) { 2493 mSettings.mPermissions.put(info.name, bp); 2494 } 2495 if (changed) { 2496 if (!async) { 2497 mSettings.writeLPr(); 2498 } else { 2499 scheduleWriteSettingsLocked(); 2500 } 2501 } 2502 return added; 2503 } 2504 2505 @Override 2506 public boolean addPermission(PermissionInfo info) { 2507 synchronized (mPackages) { 2508 return addPermissionLocked(info, false); 2509 } 2510 } 2511 2512 @Override 2513 public boolean addPermissionAsync(PermissionInfo info) { 2514 synchronized (mPackages) { 2515 return addPermissionLocked(info, true); 2516 } 2517 } 2518 2519 @Override 2520 public void removePermission(String name) { 2521 synchronized (mPackages) { 2522 checkPermissionTreeLP(name); 2523 BasePermission bp = mSettings.mPermissions.get(name); 2524 if (bp != null) { 2525 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2526 throw new SecurityException( 2527 "Not allowed to modify non-dynamic permission " 2528 + name); 2529 } 2530 mSettings.mPermissions.remove(name); 2531 mSettings.writeLPr(); 2532 } 2533 } 2534 } 2535 2536 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2537 int index = pkg.requestedPermissions.indexOf(bp.name); 2538 if (index == -1) { 2539 throw new SecurityException("Package " + pkg.packageName 2540 + " has not requested permission " + bp.name); 2541 } 2542 boolean isNormal = 2543 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2544 == PermissionInfo.PROTECTION_NORMAL); 2545 boolean isDangerous = 2546 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2547 == PermissionInfo.PROTECTION_DANGEROUS); 2548 boolean isDevelopment = 2549 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2550 2551 if (!isNormal && !isDangerous && !isDevelopment) { 2552 throw new SecurityException("Permission " + bp.name 2553 + " is not a changeable permission type"); 2554 } 2555 2556 if (isNormal || isDangerous) { 2557 if (pkg.requestedPermissionsRequired.get(index)) { 2558 throw new SecurityException("Can't change " + bp.name 2559 + ". It is required by the application"); 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public void grantPermission(String packageName, String permissionName) { 2566 mContext.enforceCallingOrSelfPermission( 2567 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2568 synchronized (mPackages) { 2569 final PackageParser.Package pkg = mPackages.get(packageName); 2570 if (pkg == null) { 2571 throw new IllegalArgumentException("Unknown package: " + packageName); 2572 } 2573 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2574 if (bp == null) { 2575 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2576 } 2577 2578 checkGrantRevokePermissions(pkg, bp); 2579 2580 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2581 if (ps == null) { 2582 return; 2583 } 2584 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2585 if (gp.grantedPermissions.add(permissionName)) { 2586 if (ps.haveGids) { 2587 gp.gids = appendInts(gp.gids, bp.gids); 2588 } 2589 mSettings.writeLPr(); 2590 } 2591 } 2592 } 2593 2594 @Override 2595 public void revokePermission(String packageName, String permissionName) { 2596 int changedAppId = -1; 2597 2598 synchronized (mPackages) { 2599 final PackageParser.Package pkg = mPackages.get(packageName); 2600 if (pkg == null) { 2601 throw new IllegalArgumentException("Unknown package: " + packageName); 2602 } 2603 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2604 mContext.enforceCallingOrSelfPermission( 2605 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2606 } 2607 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2608 if (bp == null) { 2609 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2610 } 2611 2612 checkGrantRevokePermissions(pkg, bp); 2613 2614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2615 if (ps == null) { 2616 return; 2617 } 2618 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2619 if (gp.grantedPermissions.remove(permissionName)) { 2620 gp.grantedPermissions.remove(permissionName); 2621 if (ps.haveGids) { 2622 gp.gids = removeInts(gp.gids, bp.gids); 2623 } 2624 mSettings.writeLPr(); 2625 changedAppId = ps.appId; 2626 } 2627 } 2628 2629 if (changedAppId >= 0) { 2630 // We changed the perm on someone, kill its processes. 2631 IActivityManager am = ActivityManagerNative.getDefault(); 2632 if (am != null) { 2633 final int callingUserId = UserHandle.getCallingUserId(); 2634 final long ident = Binder.clearCallingIdentity(); 2635 try { 2636 //XXX we should only revoke for the calling user's app permissions, 2637 // but for now we impact all users. 2638 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2639 // "revoke " + permissionName); 2640 int[] users = sUserManager.getUserIds(); 2641 for (int user : users) { 2642 am.killUid(UserHandle.getUid(user, changedAppId), 2643 "revoke " + permissionName); 2644 } 2645 } catch (RemoteException e) { 2646 } finally { 2647 Binder.restoreCallingIdentity(ident); 2648 } 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public boolean isProtectedBroadcast(String actionName) { 2655 synchronized (mPackages) { 2656 return mProtectedBroadcasts.contains(actionName); 2657 } 2658 } 2659 2660 @Override 2661 public int checkSignatures(String pkg1, String pkg2) { 2662 synchronized (mPackages) { 2663 final PackageParser.Package p1 = mPackages.get(pkg1); 2664 final PackageParser.Package p2 = mPackages.get(pkg2); 2665 if (p1 == null || p1.mExtras == null 2666 || p2 == null || p2.mExtras == null) { 2667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2668 } 2669 return compareSignatures(p1.mSignatures, p2.mSignatures); 2670 } 2671 } 2672 2673 @Override 2674 public int checkUidSignatures(int uid1, int uid2) { 2675 // Map to base uids. 2676 uid1 = UserHandle.getAppId(uid1); 2677 uid2 = UserHandle.getAppId(uid2); 2678 // reader 2679 synchronized (mPackages) { 2680 Signature[] s1; 2681 Signature[] s2; 2682 Object obj = mSettings.getUserIdLPr(uid1); 2683 if (obj != null) { 2684 if (obj instanceof SharedUserSetting) { 2685 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2686 } else if (obj instanceof PackageSetting) { 2687 s1 = ((PackageSetting)obj).signatures.mSignatures; 2688 } else { 2689 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2690 } 2691 } else { 2692 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2693 } 2694 obj = mSettings.getUserIdLPr(uid2); 2695 if (obj != null) { 2696 if (obj instanceof SharedUserSetting) { 2697 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2698 } else if (obj instanceof PackageSetting) { 2699 s2 = ((PackageSetting)obj).signatures.mSignatures; 2700 } else { 2701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2702 } 2703 } else { 2704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2705 } 2706 return compareSignatures(s1, s2); 2707 } 2708 } 2709 2710 /** 2711 * Compares two sets of signatures. Returns: 2712 * <br /> 2713 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2714 * <br /> 2715 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2722 */ 2723 static int compareSignatures(Signature[] s1, Signature[] s2) { 2724 if (s1 == null) { 2725 return s2 == null 2726 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2727 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2728 } 2729 2730 if (s2 == null) { 2731 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2732 } 2733 2734 if (s1.length != s2.length) { 2735 return PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 // Since both signature sets are of size 1, we can compare without HashSets. 2739 if (s1.length == 1) { 2740 return s1[0].equals(s2[0]) ? 2741 PackageManager.SIGNATURE_MATCH : 2742 PackageManager.SIGNATURE_NO_MATCH; 2743 } 2744 2745 HashSet<Signature> set1 = new HashSet<Signature>(); 2746 for (Signature sig : s1) { 2747 set1.add(sig); 2748 } 2749 HashSet<Signature> set2 = new HashSet<Signature>(); 2750 for (Signature sig : s2) { 2751 set2.add(sig); 2752 } 2753 // Make sure s2 contains all signatures in s1. 2754 if (set1.equals(set2)) { 2755 return PackageManager.SIGNATURE_MATCH; 2756 } 2757 return PackageManager.SIGNATURE_NO_MATCH; 2758 } 2759 2760 /** 2761 * If the database version for this type of package (internal storage or 2762 * external storage) is less than the version where package signatures 2763 * were updated, return true. 2764 */ 2765 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2766 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2767 DatabaseVersion.SIGNATURE_END_ENTITY)) 2768 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2769 DatabaseVersion.SIGNATURE_END_ENTITY)); 2770 } 2771 2772 /** 2773 * Used for backward compatibility to make sure any packages with 2774 * certificate chains get upgraded to the new style. {@code existingSigs} 2775 * will be in the old format (since they were stored on disk from before the 2776 * system upgrade) and {@code scannedSigs} will be in the newer format. 2777 */ 2778 private int compareSignaturesCompat(PackageSignatures existingSigs, 2779 PackageParser.Package scannedPkg) { 2780 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2781 return PackageManager.SIGNATURE_NO_MATCH; 2782 } 2783 2784 HashSet<Signature> existingSet = new HashSet<Signature>(); 2785 for (Signature sig : existingSigs.mSignatures) { 2786 existingSet.add(sig); 2787 } 2788 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2789 for (Signature sig : scannedPkg.mSignatures) { 2790 try { 2791 Signature[] chainSignatures = sig.getChainSignatures(); 2792 for (Signature chainSig : chainSignatures) { 2793 scannedCompatSet.add(chainSig); 2794 } 2795 } catch (CertificateEncodingException e) { 2796 scannedCompatSet.add(sig); 2797 } 2798 } 2799 /* 2800 * Make sure the expanded scanned set contains all signatures in the 2801 * existing one. 2802 */ 2803 if (scannedCompatSet.equals(existingSet)) { 2804 // Migrate the old signatures to the new scheme. 2805 existingSigs.assignSignatures(scannedPkg.mSignatures); 2806 // The new KeySets will be re-added later in the scanning process. 2807 synchronized (mPackages) { 2808 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2809 } 2810 return PackageManager.SIGNATURE_MATCH; 2811 } 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 @Override 2816 public String[] getPackagesForUid(int uid) { 2817 uid = UserHandle.getAppId(uid); 2818 // reader 2819 synchronized (mPackages) { 2820 Object obj = mSettings.getUserIdLPr(uid); 2821 if (obj instanceof SharedUserSetting) { 2822 final SharedUserSetting sus = (SharedUserSetting) obj; 2823 final int N = sus.packages.size(); 2824 final String[] res = new String[N]; 2825 final Iterator<PackageSetting> it = sus.packages.iterator(); 2826 int i = 0; 2827 while (it.hasNext()) { 2828 res[i++] = it.next().name; 2829 } 2830 return res; 2831 } else if (obj instanceof PackageSetting) { 2832 final PackageSetting ps = (PackageSetting) obj; 2833 return new String[] { ps.name }; 2834 } 2835 } 2836 return null; 2837 } 2838 2839 @Override 2840 public String getNameForUid(int uid) { 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 return sus.name + ":" + sus.userId; 2847 } else if (obj instanceof PackageSetting) { 2848 final PackageSetting ps = (PackageSetting) obj; 2849 return ps.name; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public int getUidForSharedUser(String sharedUserName) { 2857 if(sharedUserName == null) { 2858 return -1; 2859 } 2860 // reader 2861 synchronized (mPackages) { 2862 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2863 if (suid == null) { 2864 return -1; 2865 } 2866 return suid.userId; 2867 } 2868 } 2869 2870 @Override 2871 public int getFlagsForUid(int uid) { 2872 synchronized (mPackages) { 2873 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2874 if (obj instanceof SharedUserSetting) { 2875 final SharedUserSetting sus = (SharedUserSetting) obj; 2876 return sus.pkgFlags; 2877 } else if (obj instanceof PackageSetting) { 2878 final PackageSetting ps = (PackageSetting) obj; 2879 return ps.pkgFlags; 2880 } 2881 } 2882 return 0; 2883 } 2884 2885 @Override 2886 public String[] getAppOpPermissionPackages(String permissionName) { 2887 synchronized (mPackages) { 2888 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2889 if (pkgs == null) { 2890 return null; 2891 } 2892 return pkgs.toArray(new String[pkgs.size()]); 2893 } 2894 } 2895 2896 @Override 2897 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2898 int flags, int userId) { 2899 if (!sUserManager.exists(userId)) return null; 2900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2901 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2902 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2903 } 2904 2905 @Override 2906 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2907 IntentFilter filter, int match, ComponentName activity) { 2908 final int userId = UserHandle.getCallingUserId(); 2909 if (DEBUG_PREFERRED) { 2910 Log.v(TAG, "setLastChosenActivity intent=" + intent 2911 + " resolvedType=" + resolvedType 2912 + " flags=" + flags 2913 + " filter=" + filter 2914 + " match=" + match 2915 + " activity=" + activity); 2916 filter.dump(new PrintStreamPrinter(System.out), " "); 2917 } 2918 intent.setComponent(null); 2919 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2920 // Find any earlier preferred or last chosen entries and nuke them 2921 findPreferredActivity(intent, resolvedType, 2922 flags, query, 0, false, true, false, userId); 2923 // Add the new activity as the last chosen for this filter 2924 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2925 "Setting last chosen"); 2926 } 2927 2928 @Override 2929 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2930 final int userId = UserHandle.getCallingUserId(); 2931 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2932 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2933 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2934 false, false, false, userId); 2935 } 2936 2937 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2938 int flags, List<ResolveInfo> query, int userId) { 2939 if (query != null) { 2940 final int N = query.size(); 2941 if (N == 1) { 2942 return query.get(0); 2943 } else if (N > 1) { 2944 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2945 // If there is more than one activity with the same priority, 2946 // then let the user decide between them. 2947 ResolveInfo r0 = query.get(0); 2948 ResolveInfo r1 = query.get(1); 2949 if (DEBUG_INTENT_MATCHING || debug) { 2950 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2951 + r1.activityInfo.name + "=" + r1.priority); 2952 } 2953 // If the first activity has a higher priority, or a different 2954 // default, then it is always desireable to pick it. 2955 if (r0.priority != r1.priority 2956 || r0.preferredOrder != r1.preferredOrder 2957 || r0.isDefault != r1.isDefault) { 2958 return query.get(0); 2959 } 2960 // If we have saved a preference for a preferred activity for 2961 // this Intent, use that. 2962 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2963 flags, query, r0.priority, true, false, debug, userId); 2964 if (ri != null) { 2965 return ri; 2966 } 2967 if (userId != 0) { 2968 ri = new ResolveInfo(mResolveInfo); 2969 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2970 ri.activityInfo.applicationInfo = new ApplicationInfo( 2971 ri.activityInfo.applicationInfo); 2972 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2973 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2974 return ri; 2975 } 2976 return mResolveInfo; 2977 } 2978 } 2979 return null; 2980 } 2981 2982 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2983 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2984 final int N = query.size(); 2985 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2986 .get(userId); 2987 // Get the list of persistent preferred activities that handle the intent 2988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2989 List<PersistentPreferredActivity> pprefs = ppir != null 2990 ? ppir.queryIntent(intent, resolvedType, 2991 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2992 : null; 2993 if (pprefs != null && pprefs.size() > 0) { 2994 final int M = pprefs.size(); 2995 for (int i=0; i<M; i++) { 2996 final PersistentPreferredActivity ppa = pprefs.get(i); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2999 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3000 + "\n component=" + ppa.mComponent); 3001 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3002 } 3003 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3004 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3005 if (DEBUG_PREFERRED || debug) { 3006 Slog.v(TAG, "Found persistent preferred activity:"); 3007 if (ai != null) { 3008 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3009 } else { 3010 Slog.v(TAG, " null"); 3011 } 3012 } 3013 if (ai == null) { 3014 // This previously registered persistent preferred activity 3015 // component is no longer known. Ignore it and do NOT remove it. 3016 continue; 3017 } 3018 for (int j=0; j<N; j++) { 3019 final ResolveInfo ri = query.get(j); 3020 if (!ri.activityInfo.applicationInfo.packageName 3021 .equals(ai.applicationInfo.packageName)) { 3022 continue; 3023 } 3024 if (!ri.activityInfo.name.equals(ai.name)) { 3025 continue; 3026 } 3027 // Found a persistent preference that can handle the intent. 3028 if (DEBUG_PREFERRED || debug) { 3029 Slog.v(TAG, "Returning persistent preferred activity: " + 3030 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3031 } 3032 return ri; 3033 } 3034 } 3035 } 3036 return null; 3037 } 3038 3039 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3040 List<ResolveInfo> query, int priority, boolean always, 3041 boolean removeMatches, boolean debug, int userId) { 3042 if (!sUserManager.exists(userId)) return null; 3043 // writer 3044 synchronized (mPackages) { 3045 if (intent.getSelector() != null) { 3046 intent = intent.getSelector(); 3047 } 3048 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3049 3050 // Try to find a matching persistent preferred activity. 3051 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3052 debug, userId); 3053 3054 // If a persistent preferred activity matched, use it. 3055 if (pri != null) { 3056 return pri; 3057 } 3058 3059 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3060 // Get the list of preferred activities that handle the intent 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3062 List<PreferredActivity> prefs = pir != null 3063 ? pir.queryIntent(intent, resolvedType, 3064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3065 : null; 3066 if (prefs != null && prefs.size() > 0) { 3067 boolean changed = false; 3068 try { 3069 // First figure out how good the original match set is. 3070 // We will only allow preferred activities that came 3071 // from the same match quality. 3072 int match = 0; 3073 3074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3075 3076 final int N = query.size(); 3077 for (int j=0; j<N; j++) { 3078 final ResolveInfo ri = query.get(j); 3079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3080 + ": 0x" + Integer.toHexString(match)); 3081 if (ri.match > match) { 3082 match = ri.match; 3083 } 3084 } 3085 3086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3087 + Integer.toHexString(match)); 3088 3089 match &= IntentFilter.MATCH_CATEGORY_MASK; 3090 final int M = prefs.size(); 3091 for (int i=0; i<M; i++) { 3092 final PreferredActivity pa = prefs.get(i); 3093 if (DEBUG_PREFERRED || debug) { 3094 Slog.v(TAG, "Checking PreferredActivity ds=" 3095 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3096 + "\n component=" + pa.mPref.mComponent); 3097 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3098 } 3099 if (pa.mPref.mMatch != match) { 3100 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3101 + Integer.toHexString(pa.mPref.mMatch)); 3102 continue; 3103 } 3104 // If it's not an "always" type preferred activity and that's what we're 3105 // looking for, skip it. 3106 if (always && !pa.mPref.mAlways) { 3107 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3108 continue; 3109 } 3110 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3111 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3112 if (DEBUG_PREFERRED || debug) { 3113 Slog.v(TAG, "Found preferred activity:"); 3114 if (ai != null) { 3115 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3116 } else { 3117 Slog.v(TAG, " null"); 3118 } 3119 } 3120 if (ai == null) { 3121 // This previously registered preferred activity 3122 // component is no longer known. Most likely an update 3123 // to the app was installed and in the new version this 3124 // component no longer exists. Clean it up by removing 3125 // it from the preferred activities list, and skip it. 3126 Slog.w(TAG, "Removing dangling preferred activity: " 3127 + pa.mPref.mComponent); 3128 pir.removeFilter(pa); 3129 changed = true; 3130 continue; 3131 } 3132 for (int j=0; j<N; j++) { 3133 final ResolveInfo ri = query.get(j); 3134 if (!ri.activityInfo.applicationInfo.packageName 3135 .equals(ai.applicationInfo.packageName)) { 3136 continue; 3137 } 3138 if (!ri.activityInfo.name.equals(ai.name)) { 3139 continue; 3140 } 3141 3142 if (removeMatches) { 3143 pir.removeFilter(pa); 3144 changed = true; 3145 if (DEBUG_PREFERRED) { 3146 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3147 } 3148 break; 3149 } 3150 3151 // Okay we found a previously set preferred or last chosen app. 3152 // If the result set is different from when this 3153 // was created, we need to clear it and re-ask the 3154 // user their preference, if we're looking for an "always" type entry. 3155 if (always && !pa.mPref.sameSet(query, priority)) { 3156 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3157 + intent + " type " + resolvedType); 3158 if (DEBUG_PREFERRED) { 3159 Slog.v(TAG, "Removing preferred activity since set changed " 3160 + pa.mPref.mComponent); 3161 } 3162 pir.removeFilter(pa); 3163 // Re-add the filter as a "last chosen" entry (!always) 3164 PreferredActivity lastChosen = new PreferredActivity( 3165 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3166 pir.addFilter(lastChosen); 3167 changed = true; 3168 return null; 3169 } 3170 3171 // Yay! Either the set matched or we're looking for the last chosen 3172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3173 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3174 return ri; 3175 } 3176 } 3177 } finally { 3178 if (changed) { 3179 if (DEBUG_PREFERRED) { 3180 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3181 } 3182 mSettings.writePackageRestrictionsLPr(userId); 3183 } 3184 } 3185 } 3186 } 3187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3188 return null; 3189 } 3190 3191 /* 3192 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3193 */ 3194 @Override 3195 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3196 int targetUserId) { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3199 List<CrossProfileIntentFilter> matches = 3200 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3201 if (matches != null) { 3202 int size = matches.size(); 3203 for (int i = 0; i < size; i++) { 3204 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3205 } 3206 } 3207 return false; 3208 } 3209 3210 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3211 String resolvedType, int userId) { 3212 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3213 if (resolver != null) { 3214 return resolver.queryIntent(intent, resolvedType, false, userId); 3215 } 3216 return null; 3217 } 3218 3219 @Override 3220 public List<ResolveInfo> queryIntentActivities(Intent intent, 3221 String resolvedType, int flags, int userId) { 3222 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3223 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3224 ComponentName comp = intent.getComponent(); 3225 if (comp == null) { 3226 if (intent.getSelector() != null) { 3227 intent = intent.getSelector(); 3228 comp = intent.getComponent(); 3229 } 3230 } 3231 3232 if (comp != null) { 3233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3234 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3235 if (ai != null) { 3236 final ResolveInfo ri = new ResolveInfo(); 3237 ri.activityInfo = ai; 3238 list.add(ri); 3239 } 3240 return list; 3241 } 3242 3243 // reader 3244 synchronized (mPackages) { 3245 final String pkgName = intent.getPackage(); 3246 if (pkgName == null) { 3247 List<CrossProfileIntentFilter> matchingFilters = 3248 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3249 // Check for results that need to skip the current profile. 3250 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3251 resolvedType, flags, userId); 3252 if (resolveInfo != null) { 3253 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3254 result.add(resolveInfo); 3255 return result; 3256 } 3257 // Check for cross profile results. 3258 resolveInfo = queryCrossProfileIntents( 3259 matchingFilters, intent, resolvedType, flags, userId); 3260 3261 // Check for results in the current profile. 3262 List<ResolveInfo> result = mActivities.queryIntent( 3263 intent, resolvedType, flags, userId); 3264 if (resolveInfo != null) { 3265 result.add(resolveInfo); 3266 Collections.sort(result, mResolvePrioritySorter); 3267 } 3268 return result; 3269 } 3270 final PackageParser.Package pkg = mPackages.get(pkgName); 3271 if (pkg != null) { 3272 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3273 pkg.activities, userId); 3274 } 3275 return new ArrayList<ResolveInfo>(); 3276 } 3277 } 3278 3279 private ResolveInfo querySkipCurrentProfileIntents( 3280 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3281 int flags, int sourceUserId) { 3282 if (matchingFilters != null) { 3283 int size = matchingFilters.size(); 3284 for (int i = 0; i < size; i ++) { 3285 CrossProfileIntentFilter filter = matchingFilters.get(i); 3286 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3287 // Checking if there are activities in the target user that can handle the 3288 // intent. 3289 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3290 flags, sourceUserId); 3291 if (resolveInfo != null) { 3292 return resolveInfo; 3293 } 3294 } 3295 } 3296 } 3297 return null; 3298 } 3299 3300 // Return matching ResolveInfo if any for skip current profile intent filters. 3301 private ResolveInfo queryCrossProfileIntents( 3302 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3303 int flags, int sourceUserId) { 3304 if (matchingFilters != null) { 3305 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3306 // match the same intent. For performance reasons, it is better not to 3307 // run queryIntent twice for the same userId 3308 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3309 int size = matchingFilters.size(); 3310 for (int i = 0; i < size; i++) { 3311 CrossProfileIntentFilter filter = matchingFilters.get(i); 3312 int targetUserId = filter.getTargetUserId(); 3313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3314 && !alreadyTriedUserIds.get(targetUserId)) { 3315 // Checking if there are activities in the target user that can handle the 3316 // intent. 3317 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3318 flags, sourceUserId); 3319 if (resolveInfo != null) return resolveInfo; 3320 alreadyTriedUserIds.put(targetUserId, true); 3321 } 3322 } 3323 } 3324 return null; 3325 } 3326 3327 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3328 String resolvedType, int flags, int sourceUserId) { 3329 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3330 resolvedType, flags, filter.getTargetUserId()); 3331 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3332 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3333 } 3334 return null; 3335 } 3336 3337 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3338 int sourceUserId, int targetUserId) { 3339 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3340 String className; 3341 if (targetUserId == UserHandle.USER_OWNER) { 3342 className = FORWARD_INTENT_TO_USER_OWNER; 3343 } else { 3344 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3345 } 3346 ComponentName forwardingActivityComponentName = new ComponentName( 3347 mAndroidApplication.packageName, className); 3348 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3349 sourceUserId); 3350 if (targetUserId == UserHandle.USER_OWNER) { 3351 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3352 forwardingResolveInfo.noResourceId = true; 3353 } 3354 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3355 forwardingResolveInfo.priority = 0; 3356 forwardingResolveInfo.preferredOrder = 0; 3357 forwardingResolveInfo.match = 0; 3358 forwardingResolveInfo.isDefault = true; 3359 forwardingResolveInfo.filter = filter; 3360 forwardingResolveInfo.targetUserId = targetUserId; 3361 return forwardingResolveInfo; 3362 } 3363 3364 @Override 3365 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3366 Intent[] specifics, String[] specificTypes, Intent intent, 3367 String resolvedType, int flags, int userId) { 3368 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3370 false, "query intent activity options"); 3371 final String resultsAction = intent.getAction(); 3372 3373 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3374 | PackageManager.GET_RESOLVED_FILTER, userId); 3375 3376 if (DEBUG_INTENT_MATCHING) { 3377 Log.v(TAG, "Query " + intent + ": " + results); 3378 } 3379 3380 int specificsPos = 0; 3381 int N; 3382 3383 // todo: note that the algorithm used here is O(N^2). This 3384 // isn't a problem in our current environment, but if we start running 3385 // into situations where we have more than 5 or 10 matches then this 3386 // should probably be changed to something smarter... 3387 3388 // First we go through and resolve each of the specific items 3389 // that were supplied, taking care of removing any corresponding 3390 // duplicate items in the generic resolve list. 3391 if (specifics != null) { 3392 for (int i=0; i<specifics.length; i++) { 3393 final Intent sintent = specifics[i]; 3394 if (sintent == null) { 3395 continue; 3396 } 3397 3398 if (DEBUG_INTENT_MATCHING) { 3399 Log.v(TAG, "Specific #" + i + ": " + sintent); 3400 } 3401 3402 String action = sintent.getAction(); 3403 if (resultsAction != null && resultsAction.equals(action)) { 3404 // If this action was explicitly requested, then don't 3405 // remove things that have it. 3406 action = null; 3407 } 3408 3409 ResolveInfo ri = null; 3410 ActivityInfo ai = null; 3411 3412 ComponentName comp = sintent.getComponent(); 3413 if (comp == null) { 3414 ri = resolveIntent( 3415 sintent, 3416 specificTypes != null ? specificTypes[i] : null, 3417 flags, userId); 3418 if (ri == null) { 3419 continue; 3420 } 3421 if (ri == mResolveInfo) { 3422 // ACK! Must do something better with this. 3423 } 3424 ai = ri.activityInfo; 3425 comp = new ComponentName(ai.applicationInfo.packageName, 3426 ai.name); 3427 } else { 3428 ai = getActivityInfo(comp, flags, userId); 3429 if (ai == null) { 3430 continue; 3431 } 3432 } 3433 3434 // Look for any generic query activities that are duplicates 3435 // of this specific one, and remove them from the results. 3436 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3437 N = results.size(); 3438 int j; 3439 for (j=specificsPos; j<N; j++) { 3440 ResolveInfo sri = results.get(j); 3441 if ((sri.activityInfo.name.equals(comp.getClassName()) 3442 && sri.activityInfo.applicationInfo.packageName.equals( 3443 comp.getPackageName())) 3444 || (action != null && sri.filter.matchAction(action))) { 3445 results.remove(j); 3446 if (DEBUG_INTENT_MATCHING) Log.v( 3447 TAG, "Removing duplicate item from " + j 3448 + " due to specific " + specificsPos); 3449 if (ri == null) { 3450 ri = sri; 3451 } 3452 j--; 3453 N--; 3454 } 3455 } 3456 3457 // Add this specific item to its proper place. 3458 if (ri == null) { 3459 ri = new ResolveInfo(); 3460 ri.activityInfo = ai; 3461 } 3462 results.add(specificsPos, ri); 3463 ri.specificIndex = i; 3464 specificsPos++; 3465 } 3466 } 3467 3468 // Now we go through the remaining generic results and remove any 3469 // duplicate actions that are found here. 3470 N = results.size(); 3471 for (int i=specificsPos; i<N-1; i++) { 3472 final ResolveInfo rii = results.get(i); 3473 if (rii.filter == null) { 3474 continue; 3475 } 3476 3477 // Iterate over all of the actions of this result's intent 3478 // filter... typically this should be just one. 3479 final Iterator<String> it = rii.filter.actionsIterator(); 3480 if (it == null) { 3481 continue; 3482 } 3483 while (it.hasNext()) { 3484 final String action = it.next(); 3485 if (resultsAction != null && resultsAction.equals(action)) { 3486 // If this action was explicitly requested, then don't 3487 // remove things that have it. 3488 continue; 3489 } 3490 for (int j=i+1; j<N; j++) { 3491 final ResolveInfo rij = results.get(j); 3492 if (rij.filter != null && rij.filter.hasAction(action)) { 3493 results.remove(j); 3494 if (DEBUG_INTENT_MATCHING) Log.v( 3495 TAG, "Removing duplicate item from " + j 3496 + " due to action " + action + " at " + i); 3497 j--; 3498 N--; 3499 } 3500 } 3501 } 3502 3503 // If the caller didn't request filter information, drop it now 3504 // so we don't have to marshall/unmarshall it. 3505 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3506 rii.filter = null; 3507 } 3508 } 3509 3510 // Filter out the caller activity if so requested. 3511 if (caller != null) { 3512 N = results.size(); 3513 for (int i=0; i<N; i++) { 3514 ActivityInfo ainfo = results.get(i).activityInfo; 3515 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3516 && caller.getClassName().equals(ainfo.name)) { 3517 results.remove(i); 3518 break; 3519 } 3520 } 3521 } 3522 3523 // If the caller didn't request filter information, 3524 // drop them now so we don't have to 3525 // marshall/unmarshall it. 3526 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3527 N = results.size(); 3528 for (int i=0; i<N; i++) { 3529 results.get(i).filter = null; 3530 } 3531 } 3532 3533 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3534 return results; 3535 } 3536 3537 @Override 3538 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3539 int userId) { 3540 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3541 ComponentName comp = intent.getComponent(); 3542 if (comp == null) { 3543 if (intent.getSelector() != null) { 3544 intent = intent.getSelector(); 3545 comp = intent.getComponent(); 3546 } 3547 } 3548 if (comp != null) { 3549 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3550 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3551 if (ai != null) { 3552 ResolveInfo ri = new ResolveInfo(); 3553 ri.activityInfo = ai; 3554 list.add(ri); 3555 } 3556 return list; 3557 } 3558 3559 // reader 3560 synchronized (mPackages) { 3561 String pkgName = intent.getPackage(); 3562 if (pkgName == null) { 3563 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3564 } 3565 final PackageParser.Package pkg = mPackages.get(pkgName); 3566 if (pkg != null) { 3567 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3568 userId); 3569 } 3570 return null; 3571 } 3572 } 3573 3574 @Override 3575 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3576 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3577 if (!sUserManager.exists(userId)) return null; 3578 if (query != null) { 3579 if (query.size() >= 1) { 3580 // If there is more than one service with the same priority, 3581 // just arbitrarily pick the first one. 3582 return query.get(0); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3590 int userId) { 3591 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3592 ComponentName comp = intent.getComponent(); 3593 if (comp == null) { 3594 if (intent.getSelector() != null) { 3595 intent = intent.getSelector(); 3596 comp = intent.getComponent(); 3597 } 3598 } 3599 if (comp != null) { 3600 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3601 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3602 if (si != null) { 3603 final ResolveInfo ri = new ResolveInfo(); 3604 ri.serviceInfo = si; 3605 list.add(ri); 3606 } 3607 return list; 3608 } 3609 3610 // reader 3611 synchronized (mPackages) { 3612 String pkgName = intent.getPackage(); 3613 if (pkgName == null) { 3614 return mServices.queryIntent(intent, resolvedType, flags, userId); 3615 } 3616 final PackageParser.Package pkg = mPackages.get(pkgName); 3617 if (pkg != null) { 3618 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3619 userId); 3620 } 3621 return null; 3622 } 3623 } 3624 3625 @Override 3626 public List<ResolveInfo> queryIntentContentProviders( 3627 Intent intent, String resolvedType, int flags, int userId) { 3628 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3629 ComponentName comp = intent.getComponent(); 3630 if (comp == null) { 3631 if (intent.getSelector() != null) { 3632 intent = intent.getSelector(); 3633 comp = intent.getComponent(); 3634 } 3635 } 3636 if (comp != null) { 3637 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3638 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3639 if (pi != null) { 3640 final ResolveInfo ri = new ResolveInfo(); 3641 ri.providerInfo = pi; 3642 list.add(ri); 3643 } 3644 return list; 3645 } 3646 3647 // reader 3648 synchronized (mPackages) { 3649 String pkgName = intent.getPackage(); 3650 if (pkgName == null) { 3651 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3652 } 3653 final PackageParser.Package pkg = mPackages.get(pkgName); 3654 if (pkg != null) { 3655 return mProviders.queryIntentForPackage( 3656 intent, resolvedType, flags, pkg.providers, userId); 3657 } 3658 return null; 3659 } 3660 } 3661 3662 @Override 3663 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3664 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3665 3666 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3667 3668 // writer 3669 synchronized (mPackages) { 3670 ArrayList<PackageInfo> list; 3671 if (listUninstalled) { 3672 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3673 for (PackageSetting ps : mSettings.mPackages.values()) { 3674 PackageInfo pi; 3675 if (ps.pkg != null) { 3676 pi = generatePackageInfo(ps.pkg, flags, userId); 3677 } else { 3678 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3679 } 3680 if (pi != null) { 3681 list.add(pi); 3682 } 3683 } 3684 } else { 3685 list = new ArrayList<PackageInfo>(mPackages.size()); 3686 for (PackageParser.Package p : mPackages.values()) { 3687 PackageInfo pi = generatePackageInfo(p, flags, userId); 3688 if (pi != null) { 3689 list.add(pi); 3690 } 3691 } 3692 } 3693 3694 return new ParceledListSlice<PackageInfo>(list); 3695 } 3696 } 3697 3698 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3699 String[] permissions, boolean[] tmp, int flags, int userId) { 3700 int numMatch = 0; 3701 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3702 for (int i=0; i<permissions.length; i++) { 3703 if (gp.grantedPermissions.contains(permissions[i])) { 3704 tmp[i] = true; 3705 numMatch++; 3706 } else { 3707 tmp[i] = false; 3708 } 3709 } 3710 if (numMatch == 0) { 3711 return; 3712 } 3713 PackageInfo pi; 3714 if (ps.pkg != null) { 3715 pi = generatePackageInfo(ps.pkg, flags, userId); 3716 } else { 3717 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3718 } 3719 // The above might return null in cases of uninstalled apps or install-state 3720 // skew across users/profiles. 3721 if (pi != null) { 3722 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3723 if (numMatch == permissions.length) { 3724 pi.requestedPermissions = permissions; 3725 } else { 3726 pi.requestedPermissions = new String[numMatch]; 3727 numMatch = 0; 3728 for (int i=0; i<permissions.length; i++) { 3729 if (tmp[i]) { 3730 pi.requestedPermissions[numMatch] = permissions[i]; 3731 numMatch++; 3732 } 3733 } 3734 } 3735 } 3736 list.add(pi); 3737 } 3738 } 3739 3740 @Override 3741 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3742 String[] permissions, int flags, int userId) { 3743 if (!sUserManager.exists(userId)) return null; 3744 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3745 3746 // writer 3747 synchronized (mPackages) { 3748 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3749 boolean[] tmpBools = new boolean[permissions.length]; 3750 if (listUninstalled) { 3751 for (PackageSetting ps : mSettings.mPackages.values()) { 3752 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3753 } 3754 } else { 3755 for (PackageParser.Package pkg : mPackages.values()) { 3756 PackageSetting ps = (PackageSetting)pkg.mExtras; 3757 if (ps != null) { 3758 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3759 userId); 3760 } 3761 } 3762 } 3763 3764 return new ParceledListSlice<PackageInfo>(list); 3765 } 3766 } 3767 3768 @Override 3769 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3770 if (!sUserManager.exists(userId)) return null; 3771 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3772 3773 // writer 3774 synchronized (mPackages) { 3775 ArrayList<ApplicationInfo> list; 3776 if (listUninstalled) { 3777 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3778 for (PackageSetting ps : mSettings.mPackages.values()) { 3779 ApplicationInfo ai; 3780 if (ps.pkg != null) { 3781 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3782 ps.readUserState(userId), userId); 3783 } else { 3784 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3785 } 3786 if (ai != null) { 3787 list.add(ai); 3788 } 3789 } 3790 } else { 3791 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3792 for (PackageParser.Package p : mPackages.values()) { 3793 if (p.mExtras != null) { 3794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3795 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3796 if (ai != null) { 3797 list.add(ai); 3798 } 3799 } 3800 } 3801 } 3802 3803 return new ParceledListSlice<ApplicationInfo>(list); 3804 } 3805 } 3806 3807 public List<ApplicationInfo> getPersistentApplications(int flags) { 3808 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3809 3810 // reader 3811 synchronized (mPackages) { 3812 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3813 final int userId = UserHandle.getCallingUserId(); 3814 while (i.hasNext()) { 3815 final PackageParser.Package p = i.next(); 3816 if (p.applicationInfo != null 3817 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3818 && (!mSafeMode || isSystemApp(p))) { 3819 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3820 if (ps != null) { 3821 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3822 ps.readUserState(userId), userId); 3823 if (ai != null) { 3824 finalList.add(ai); 3825 } 3826 } 3827 } 3828 } 3829 } 3830 3831 return finalList; 3832 } 3833 3834 @Override 3835 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3836 if (!sUserManager.exists(userId)) return null; 3837 // reader 3838 synchronized (mPackages) { 3839 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3840 PackageSetting ps = provider != null 3841 ? mSettings.mPackages.get(provider.owner.packageName) 3842 : null; 3843 return ps != null 3844 && mSettings.isEnabledLPr(provider.info, flags, userId) 3845 && (!mSafeMode || (provider.info.applicationInfo.flags 3846 &ApplicationInfo.FLAG_SYSTEM) != 0) 3847 ? PackageParser.generateProviderInfo(provider, flags, 3848 ps.readUserState(userId), userId) 3849 : null; 3850 } 3851 } 3852 3853 /** 3854 * @deprecated 3855 */ 3856 @Deprecated 3857 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3858 // reader 3859 synchronized (mPackages) { 3860 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3861 .entrySet().iterator(); 3862 final int userId = UserHandle.getCallingUserId(); 3863 while (i.hasNext()) { 3864 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3865 PackageParser.Provider p = entry.getValue(); 3866 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3867 3868 if (ps != null && p.syncable 3869 && (!mSafeMode || (p.info.applicationInfo.flags 3870 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3871 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3872 ps.readUserState(userId), userId); 3873 if (info != null) { 3874 outNames.add(entry.getKey()); 3875 outInfo.add(info); 3876 } 3877 } 3878 } 3879 } 3880 } 3881 3882 @Override 3883 public List<ProviderInfo> queryContentProviders(String processName, 3884 int uid, int flags) { 3885 ArrayList<ProviderInfo> finalList = null; 3886 // reader 3887 synchronized (mPackages) { 3888 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3889 final int userId = processName != null ? 3890 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3891 while (i.hasNext()) { 3892 final PackageParser.Provider p = i.next(); 3893 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3894 if (ps != null && p.info.authority != null 3895 && (processName == null 3896 || (p.info.processName.equals(processName) 3897 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3898 && mSettings.isEnabledLPr(p.info, flags, userId) 3899 && (!mSafeMode 3900 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3901 if (finalList == null) { 3902 finalList = new ArrayList<ProviderInfo>(3); 3903 } 3904 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3905 ps.readUserState(userId), userId); 3906 if (info != null) { 3907 finalList.add(info); 3908 } 3909 } 3910 } 3911 } 3912 3913 if (finalList != null) { 3914 Collections.sort(finalList, mProviderInitOrderSorter); 3915 } 3916 3917 return finalList; 3918 } 3919 3920 @Override 3921 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3922 int flags) { 3923 // reader 3924 synchronized (mPackages) { 3925 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3926 return PackageParser.generateInstrumentationInfo(i, flags); 3927 } 3928 } 3929 3930 @Override 3931 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3932 int flags) { 3933 ArrayList<InstrumentationInfo> finalList = 3934 new ArrayList<InstrumentationInfo>(); 3935 3936 // reader 3937 synchronized (mPackages) { 3938 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3939 while (i.hasNext()) { 3940 final PackageParser.Instrumentation p = i.next(); 3941 if (targetPackage == null 3942 || targetPackage.equals(p.info.targetPackage)) { 3943 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3944 flags); 3945 if (ii != null) { 3946 finalList.add(ii); 3947 } 3948 } 3949 } 3950 } 3951 3952 return finalList; 3953 } 3954 3955 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3956 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3957 if (overlays == null) { 3958 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3959 return; 3960 } 3961 for (PackageParser.Package opkg : overlays.values()) { 3962 // Not much to do if idmap fails: we already logged the error 3963 // and we certainly don't want to abort installation of pkg simply 3964 // because an overlay didn't fit properly. For these reasons, 3965 // ignore the return value of createIdmapForPackagePairLI. 3966 createIdmapForPackagePairLI(pkg, opkg); 3967 } 3968 } 3969 3970 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3971 PackageParser.Package opkg) { 3972 if (!opkg.mTrustedOverlay) { 3973 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 3974 opkg.baseCodePath + ": overlay not trusted"); 3975 return false; 3976 } 3977 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3978 if (overlaySet == null) { 3979 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 3980 opkg.baseCodePath + " but target package has no known overlays"); 3981 return false; 3982 } 3983 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3984 // TODO: generate idmap for split APKs 3985 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 3986 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 3987 + opkg.baseCodePath); 3988 return false; 3989 } 3990 PackageParser.Package[] overlayArray = 3991 overlaySet.values().toArray(new PackageParser.Package[0]); 3992 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3993 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3994 return p1.mOverlayPriority - p2.mOverlayPriority; 3995 } 3996 }; 3997 Arrays.sort(overlayArray, cmp); 3998 3999 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4000 int i = 0; 4001 for (PackageParser.Package p : overlayArray) { 4002 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4003 } 4004 return true; 4005 } 4006 4007 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4008 final File[] files = dir.listFiles(); 4009 if (ArrayUtils.isEmpty(files)) { 4010 Log.d(TAG, "No files in app dir " + dir); 4011 return; 4012 } 4013 4014 if (DEBUG_PACKAGE_SCANNING) { 4015 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4016 + " flags=0x" + Integer.toHexString(parseFlags)); 4017 } 4018 4019 for (File file : files) { 4020 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4021 && !PackageInstallerService.isStageName(file.getName()); 4022 if (!isPackage) { 4023 // Ignore entries which are not packages 4024 continue; 4025 } 4026 try { 4027 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4028 scanFlags, currentTime, null); 4029 } catch (PackageManagerException e) { 4030 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4031 4032 // Delete invalid userdata apps 4033 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4034 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4035 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4036 if (file.isDirectory()) { 4037 FileUtils.deleteContents(file); 4038 } 4039 file.delete(); 4040 } 4041 } 4042 } 4043 } 4044 4045 private static File getSettingsProblemFile() { 4046 File dataDir = Environment.getDataDirectory(); 4047 File systemDir = new File(dataDir, "system"); 4048 File fname = new File(systemDir, "uiderrors.txt"); 4049 return fname; 4050 } 4051 4052 static void reportSettingsProblem(int priority, String msg) { 4053 logCriticalInfo(priority, msg); 4054 } 4055 4056 static void logCriticalInfo(int priority, String msg) { 4057 Slog.println(priority, TAG, msg); 4058 EventLogTags.writePmCriticalInfo(msg); 4059 try { 4060 File fname = getSettingsProblemFile(); 4061 FileOutputStream out = new FileOutputStream(fname, true); 4062 PrintWriter pw = new FastPrintWriter(out); 4063 SimpleDateFormat formatter = new SimpleDateFormat(); 4064 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4065 pw.println(dateString + ": " + msg); 4066 pw.close(); 4067 FileUtils.setPermissions( 4068 fname.toString(), 4069 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4070 -1, -1); 4071 } catch (java.io.IOException e) { 4072 } 4073 } 4074 4075 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4076 PackageParser.Package pkg, File srcFile, int parseFlags) 4077 throws PackageManagerException { 4078 if (ps != null 4079 && ps.codePath.equals(srcFile) 4080 && ps.timeStamp == srcFile.lastModified() 4081 && !isCompatSignatureUpdateNeeded(pkg)) { 4082 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4083 if (ps.signatures.mSignatures != null 4084 && ps.signatures.mSignatures.length != 0 4085 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4086 // Optimization: reuse the existing cached certificates 4087 // if the package appears to be unchanged. 4088 pkg.mSignatures = ps.signatures.mSignatures; 4089 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4090 synchronized (mPackages) { 4091 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4092 } 4093 return; 4094 } 4095 4096 Slog.w(TAG, "PackageSetting for " + ps.name 4097 + " is missing signatures. Collecting certs again to recover them."); 4098 } else { 4099 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4100 } 4101 4102 try { 4103 pp.collectCertificates(pkg, parseFlags); 4104 pp.collectManifestDigest(pkg); 4105 } catch (PackageParserException e) { 4106 throw PackageManagerException.from(e); 4107 } 4108 } 4109 4110 /* 4111 * Scan a package and return the newly parsed package. 4112 * Returns null in case of errors and the error code is stored in mLastScanError 4113 */ 4114 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4115 long currentTime, UserHandle user) throws PackageManagerException { 4116 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4117 parseFlags |= mDefParseFlags; 4118 PackageParser pp = new PackageParser(); 4119 pp.setSeparateProcesses(mSeparateProcesses); 4120 pp.setOnlyCoreApps(mOnlyCore); 4121 pp.setDisplayMetrics(mMetrics); 4122 4123 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4124 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4125 } 4126 4127 final PackageParser.Package pkg; 4128 try { 4129 pkg = pp.parsePackage(scanFile, parseFlags); 4130 } catch (PackageParserException e) { 4131 throw PackageManagerException.from(e); 4132 } 4133 4134 PackageSetting ps = null; 4135 PackageSetting updatedPkg; 4136 // reader 4137 synchronized (mPackages) { 4138 // Look to see if we already know about this package. 4139 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4140 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4141 // This package has been renamed to its original name. Let's 4142 // use that. 4143 ps = mSettings.peekPackageLPr(oldName); 4144 } 4145 // If there was no original package, see one for the real package name. 4146 if (ps == null) { 4147 ps = mSettings.peekPackageLPr(pkg.packageName); 4148 } 4149 // Check to see if this package could be hiding/updating a system 4150 // package. Must look for it either under the original or real 4151 // package name depending on our state. 4152 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4153 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4154 } 4155 boolean updatedPkgBetter = false; 4156 // First check if this is a system package that may involve an update 4157 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4158 if (ps != null && !ps.codePath.equals(scanFile)) { 4159 // The path has changed from what was last scanned... check the 4160 // version of the new path against what we have stored to determine 4161 // what to do. 4162 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4163 if (pkg.mVersionCode < ps.versionCode) { 4164 // The system package has been updated and the code path does not match 4165 // Ignore entry. Skip it. 4166 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4167 + " ignored: updated version " + ps.versionCode 4168 + " better than this " + pkg.mVersionCode); 4169 if (!updatedPkg.codePath.equals(scanFile)) { 4170 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4171 + ps.name + " changing from " + updatedPkg.codePathString 4172 + " to " + scanFile); 4173 updatedPkg.codePath = scanFile; 4174 updatedPkg.codePathString = scanFile.toString(); 4175 // This is the point at which we know that the system-disk APK 4176 // for this package has moved during a reboot (e.g. due to an OTA), 4177 // so we need to reevaluate it for privilege policy. 4178 if (locationIsPrivileged(scanFile)) { 4179 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4180 } 4181 } 4182 updatedPkg.pkg = pkg; 4183 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4184 } else { 4185 // The current app on the system partition is better than 4186 // what we have updated to on the data partition; switch 4187 // back to the system partition version. 4188 // At this point, its safely assumed that package installation for 4189 // apps in system partition will go through. If not there won't be a working 4190 // version of the app 4191 // writer 4192 synchronized (mPackages) { 4193 // Just remove the loaded entries from package lists. 4194 mPackages.remove(ps.name); 4195 } 4196 4197 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4198 + "reverting from " + ps.codePathString 4199 + ": new version " + pkg.mVersionCode 4200 + " better than installed " + ps.versionCode); 4201 4202 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4203 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4204 getAppDexInstructionSets(ps)); 4205 synchronized (mInstallLock) { 4206 args.cleanUpResourcesLI(); 4207 } 4208 synchronized (mPackages) { 4209 mSettings.enableSystemPackageLPw(ps.name); 4210 } 4211 updatedPkgBetter = true; 4212 } 4213 } 4214 } 4215 4216 if (updatedPkg != null) { 4217 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4218 // initially 4219 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4220 4221 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4222 // flag set initially 4223 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4224 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4225 } 4226 } 4227 4228 // Verify certificates against what was last scanned 4229 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4230 4231 /* 4232 * A new system app appeared, but we already had a non-system one of the 4233 * same name installed earlier. 4234 */ 4235 boolean shouldHideSystemApp = false; 4236 if (updatedPkg == null && ps != null 4237 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4238 /* 4239 * Check to make sure the signatures match first. If they don't, 4240 * wipe the installed application and its data. 4241 */ 4242 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4243 != PackageManager.SIGNATURE_MATCH) { 4244 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4245 + " signatures don't match existing userdata copy; removing"); 4246 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4247 ps = null; 4248 } else { 4249 /* 4250 * If the newly-added system app is an older version than the 4251 * already installed version, hide it. It will be scanned later 4252 * and re-added like an update. 4253 */ 4254 if (pkg.mVersionCode < ps.versionCode) { 4255 shouldHideSystemApp = true; 4256 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4257 + " but new version " + pkg.mVersionCode + " better than installed " 4258 + ps.versionCode + "; hiding system"); 4259 } else { 4260 /* 4261 * The newly found system app is a newer version that the 4262 * one previously installed. Simply remove the 4263 * already-installed application and replace it with our own 4264 * while keeping the application data. 4265 */ 4266 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4267 + " reverting from " + ps.codePathString + ": new version " 4268 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4269 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4270 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4271 getAppDexInstructionSets(ps)); 4272 synchronized (mInstallLock) { 4273 args.cleanUpResourcesLI(); 4274 } 4275 } 4276 } 4277 } 4278 4279 // The apk is forward locked (not public) if its code and resources 4280 // are kept in different files. (except for app in either system or 4281 // vendor path). 4282 // TODO grab this value from PackageSettings 4283 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4284 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4285 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4286 } 4287 } 4288 4289 // TODO: extend to support forward-locked splits 4290 String resourcePath = null; 4291 String baseResourcePath = null; 4292 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4293 if (ps != null && ps.resourcePathString != null) { 4294 resourcePath = ps.resourcePathString; 4295 baseResourcePath = ps.resourcePathString; 4296 } else { 4297 // Should not happen at all. Just log an error. 4298 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4299 } 4300 } else { 4301 resourcePath = pkg.codePath; 4302 baseResourcePath = pkg.baseCodePath; 4303 } 4304 4305 // Set application objects path explicitly. 4306 pkg.applicationInfo.setCodePath(pkg.codePath); 4307 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4308 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4309 pkg.applicationInfo.setResourcePath(resourcePath); 4310 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4311 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4312 4313 // Note that we invoke the following method only if we are about to unpack an application 4314 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4315 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4316 4317 /* 4318 * If the system app should be overridden by a previously installed 4319 * data, hide the system app now and let the /data/app scan pick it up 4320 * again. 4321 */ 4322 if (shouldHideSystemApp) { 4323 synchronized (mPackages) { 4324 /* 4325 * We have to grant systems permissions before we hide, because 4326 * grantPermissions will assume the package update is trying to 4327 * expand its permissions. 4328 */ 4329 grantPermissionsLPw(pkg, true, pkg.packageName); 4330 mSettings.disableSystemPackageLPw(pkg.packageName); 4331 } 4332 } 4333 4334 return scannedPkg; 4335 } 4336 4337 private static String fixProcessName(String defProcessName, 4338 String processName, int uid) { 4339 if (processName == null) { 4340 return defProcessName; 4341 } 4342 return processName; 4343 } 4344 4345 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4346 throws PackageManagerException { 4347 if (pkgSetting.signatures.mSignatures != null) { 4348 // Already existing package. Make sure signatures match 4349 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4350 == PackageManager.SIGNATURE_MATCH; 4351 if (!match) { 4352 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4353 == PackageManager.SIGNATURE_MATCH; 4354 } 4355 if (!match) { 4356 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4357 + pkg.packageName + " signatures do not match the " 4358 + "previously installed version; ignoring!"); 4359 } 4360 } 4361 4362 // Check for shared user signatures 4363 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4364 // Already existing package. Make sure signatures match 4365 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4366 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4367 if (!match) { 4368 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4369 == PackageManager.SIGNATURE_MATCH; 4370 } 4371 if (!match) { 4372 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4373 "Package " + pkg.packageName 4374 + " has no signatures that match those in shared user " 4375 + pkgSetting.sharedUser.name + "; ignoring!"); 4376 } 4377 } 4378 } 4379 4380 /** 4381 * Enforces that only the system UID or root's UID can call a method exposed 4382 * via Binder. 4383 * 4384 * @param message used as message if SecurityException is thrown 4385 * @throws SecurityException if the caller is not system or root 4386 */ 4387 private static final void enforceSystemOrRoot(String message) { 4388 final int uid = Binder.getCallingUid(); 4389 if (uid != Process.SYSTEM_UID && uid != 0) { 4390 throw new SecurityException(message); 4391 } 4392 } 4393 4394 @Override 4395 public void performBootDexOpt() { 4396 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4397 4398 final HashSet<PackageParser.Package> pkgs; 4399 synchronized (mPackages) { 4400 pkgs = mDeferredDexOpt; 4401 mDeferredDexOpt = null; 4402 } 4403 4404 if (pkgs != null) { 4405 // Filter out packages that aren't recently used. 4406 // 4407 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4408 // should do a full dexopt. 4409 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4410 // TODO: add a property to control this? 4411 long dexOptLRUThresholdInMinutes; 4412 if (mLazyDexOpt) { 4413 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4414 } else { 4415 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4416 } 4417 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4418 4419 int total = pkgs.size(); 4420 int skipped = 0; 4421 long now = System.currentTimeMillis(); 4422 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4423 PackageParser.Package pkg = i.next(); 4424 long then = pkg.mLastPackageUsageTimeInMills; 4425 if (then + dexOptLRUThresholdInMills < now) { 4426 if (DEBUG_DEXOPT) { 4427 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4428 ((then == 0) ? "never" : new Date(then))); 4429 } 4430 i.remove(); 4431 skipped++; 4432 } 4433 } 4434 if (DEBUG_DEXOPT) { 4435 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4436 } 4437 } 4438 4439 int i = 0; 4440 for (PackageParser.Package pkg : pkgs) { 4441 i++; 4442 if (DEBUG_DEXOPT) { 4443 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4444 + ": " + pkg.packageName); 4445 } 4446 if (!isFirstBoot()) { 4447 try { 4448 ActivityManagerNative.getDefault().showBootMessage( 4449 mContext.getResources().getString( 4450 R.string.android_upgrading_apk, 4451 i, pkgs.size()), true); 4452 } catch (RemoteException e) { 4453 } 4454 } 4455 PackageParser.Package p = pkg; 4456 synchronized (mInstallLock) { 4457 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4458 true /* include dependencies */); 4459 } 4460 } 4461 } 4462 } 4463 4464 @Override 4465 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4466 return performDexOpt(packageName, instructionSet, false); 4467 } 4468 4469 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4470 if (info.primaryCpuAbi == null) { 4471 return getPreferredInstructionSet(); 4472 } 4473 4474 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4475 } 4476 4477 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4478 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4479 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4480 if (!dexopt && !updateUsage) { 4481 // We aren't going to dexopt or update usage, so bail early. 4482 return false; 4483 } 4484 PackageParser.Package p; 4485 final String targetInstructionSet; 4486 synchronized (mPackages) { 4487 p = mPackages.get(packageName); 4488 if (p == null) { 4489 return false; 4490 } 4491 if (updateUsage) { 4492 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4493 } 4494 mPackageUsage.write(false); 4495 if (!dexopt) { 4496 // We aren't going to dexopt, so bail early. 4497 return false; 4498 } 4499 4500 targetInstructionSet = instructionSet != null ? instructionSet : 4501 getPrimaryInstructionSet(p.applicationInfo); 4502 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4503 return false; 4504 } 4505 } 4506 4507 synchronized (mInstallLock) { 4508 final String[] instructionSets = new String[] { targetInstructionSet }; 4509 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4510 true /* include dependencies */) == DEX_OPT_PERFORMED; 4511 } 4512 } 4513 4514 public HashSet<String> getPackagesThatNeedDexOpt() { 4515 HashSet<String> pkgs = null; 4516 synchronized (mPackages) { 4517 for (PackageParser.Package p : mPackages.values()) { 4518 if (DEBUG_DEXOPT) { 4519 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4520 } 4521 if (!p.mDexOptPerformed.isEmpty()) { 4522 continue; 4523 } 4524 if (pkgs == null) { 4525 pkgs = new HashSet<String>(); 4526 } 4527 pkgs.add(p.packageName); 4528 } 4529 } 4530 return pkgs; 4531 } 4532 4533 public void shutdown() { 4534 mPackageUsage.write(true); 4535 } 4536 4537 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4538 boolean forceDex, boolean defer, HashSet<String> done) { 4539 for (int i=0; i<libs.size(); i++) { 4540 PackageParser.Package libPkg; 4541 String libName; 4542 synchronized (mPackages) { 4543 libName = libs.get(i); 4544 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4545 if (lib != null && lib.apk != null) { 4546 libPkg = mPackages.get(lib.apk); 4547 } else { 4548 libPkg = null; 4549 } 4550 } 4551 if (libPkg != null && !done.contains(libName)) { 4552 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4553 } 4554 } 4555 } 4556 4557 static final int DEX_OPT_SKIPPED = 0; 4558 static final int DEX_OPT_PERFORMED = 1; 4559 static final int DEX_OPT_DEFERRED = 2; 4560 static final int DEX_OPT_FAILED = -1; 4561 4562 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4563 boolean forceDex, boolean defer, HashSet<String> done) { 4564 final String[] instructionSets = targetInstructionSets != null ? 4565 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4566 4567 if (done != null) { 4568 done.add(pkg.packageName); 4569 if (pkg.usesLibraries != null) { 4570 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4571 } 4572 if (pkg.usesOptionalLibraries != null) { 4573 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4574 } 4575 } 4576 4577 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4578 return DEX_OPT_SKIPPED; 4579 } 4580 4581 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4582 4583 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4584 boolean performedDexOpt = false; 4585 // There are three basic cases here: 4586 // 1.) we need to dexopt, either because we are forced or it is needed 4587 // 2.) we are defering a needed dexopt 4588 // 3.) we are skipping an unneeded dexopt 4589 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4590 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4591 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4592 continue; 4593 } 4594 4595 for (String path : paths) { 4596 try { 4597 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4598 // patckage or the one we find does not match the image checksum (i.e. it was 4599 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4600 // odex file and it matches the checksum of the image but not its base address, 4601 // meaning we need to move it. 4602 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4603 pkg.packageName, dexCodeInstructionSet, defer); 4604 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4605 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4606 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4607 + " vmSafeMode=" + vmSafeMode); 4608 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4609 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4610 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4611 4612 if (ret < 0) { 4613 // Don't bother running dexopt again if we failed, it will probably 4614 // just result in an error again. Also, don't bother dexopting for other 4615 // paths & ISAs. 4616 return DEX_OPT_FAILED; 4617 } 4618 4619 performedDexOpt = true; 4620 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4621 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4622 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4623 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4624 pkg.packageName, dexCodeInstructionSet); 4625 4626 if (ret < 0) { 4627 // Don't bother running patchoat again if we failed, it will probably 4628 // just result in an error again. Also, don't bother dexopting for other 4629 // paths & ISAs. 4630 return DEX_OPT_FAILED; 4631 } 4632 4633 performedDexOpt = true; 4634 } 4635 4636 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4637 // paths and instruction sets. We'll deal with them all together when we process 4638 // our list of deferred dexopts. 4639 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4640 if (mDeferredDexOpt == null) { 4641 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4642 } 4643 mDeferredDexOpt.add(pkg); 4644 return DEX_OPT_DEFERRED; 4645 } 4646 } catch (FileNotFoundException e) { 4647 Slog.w(TAG, "Apk not found for dexopt: " + path); 4648 return DEX_OPT_FAILED; 4649 } catch (IOException e) { 4650 Slog.w(TAG, "IOException reading apk: " + path, e); 4651 return DEX_OPT_FAILED; 4652 } catch (StaleDexCacheError e) { 4653 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4654 return DEX_OPT_FAILED; 4655 } catch (Exception e) { 4656 Slog.w(TAG, "Exception when doing dexopt : ", e); 4657 return DEX_OPT_FAILED; 4658 } 4659 } 4660 4661 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4662 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4663 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4664 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4665 // it. 4666 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4667 } 4668 4669 // If we've gotten here, we're sure that no error occurred and that we haven't 4670 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4671 // we've skipped all of them because they are up to date. In both cases this 4672 // package doesn't need dexopt any longer. 4673 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4674 } 4675 4676 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4677 if (info.primaryCpuAbi != null) { 4678 if (info.secondaryCpuAbi != null) { 4679 return new String[] { 4680 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4681 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4682 } else { 4683 return new String[] { 4684 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4685 } 4686 } 4687 4688 return new String[] { getPreferredInstructionSet() }; 4689 } 4690 4691 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4692 if (ps.primaryCpuAbiString != null) { 4693 if (ps.secondaryCpuAbiString != null) { 4694 return new String[] { 4695 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4696 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4697 } else { 4698 return new String[] { 4699 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4700 } 4701 } 4702 4703 return new String[] { getPreferredInstructionSet() }; 4704 } 4705 4706 private static String getPreferredInstructionSet() { 4707 if (sPreferredInstructionSet == null) { 4708 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4709 } 4710 4711 return sPreferredInstructionSet; 4712 } 4713 4714 private static List<String> getAllInstructionSets() { 4715 final String[] allAbis = Build.SUPPORTED_ABIS; 4716 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4717 4718 for (String abi : allAbis) { 4719 final String instructionSet = VMRuntime.getInstructionSet(abi); 4720 if (!allInstructionSets.contains(instructionSet)) { 4721 allInstructionSets.add(instructionSet); 4722 } 4723 } 4724 4725 return allInstructionSets; 4726 } 4727 4728 /** 4729 * Returns the instruction set that should be used to compile dex code. In the presence of 4730 * a native bridge this might be different than the one shared libraries use. 4731 */ 4732 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4733 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4734 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4735 } 4736 4737 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4738 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4739 for (String instructionSet : instructionSets) { 4740 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4741 } 4742 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4743 } 4744 4745 /** 4746 * Returns deduplicated list of supported instructions for dex code. 4747 */ 4748 public static String[] getAllDexCodeInstructionSets() { 4749 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4750 for (int i = 0; i < supportedInstructionSets.length; i++) { 4751 String abi = Build.SUPPORTED_ABIS[i]; 4752 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4753 } 4754 return getDexCodeInstructionSets(supportedInstructionSets); 4755 } 4756 4757 @Override 4758 public void forceDexOpt(String packageName) { 4759 enforceSystemOrRoot("forceDexOpt"); 4760 4761 PackageParser.Package pkg; 4762 synchronized (mPackages) { 4763 pkg = mPackages.get(packageName); 4764 if (pkg == null) { 4765 throw new IllegalArgumentException("Missing package: " + packageName); 4766 } 4767 } 4768 4769 synchronized (mInstallLock) { 4770 final String[] instructionSets = new String[] { 4771 getPrimaryInstructionSet(pkg.applicationInfo) }; 4772 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4773 if (res != DEX_OPT_PERFORMED) { 4774 throw new IllegalStateException("Failed to dexopt: " + res); 4775 } 4776 } 4777 } 4778 4779 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4780 boolean forceDex, boolean defer, boolean inclDependencies) { 4781 HashSet<String> done; 4782 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4783 done = new HashSet<String>(); 4784 done.add(pkg.packageName); 4785 } else { 4786 done = null; 4787 } 4788 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4789 } 4790 4791 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4792 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4793 Slog.w(TAG, "Unable to update from " + oldPkg.name 4794 + " to " + newPkg.packageName 4795 + ": old package not in system partition"); 4796 return false; 4797 } else if (mPackages.get(oldPkg.name) != null) { 4798 Slog.w(TAG, "Unable to update from " + oldPkg.name 4799 + " to " + newPkg.packageName 4800 + ": old package still exists"); 4801 return false; 4802 } 4803 return true; 4804 } 4805 4806 File getDataPathForUser(int userId) { 4807 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4808 } 4809 4810 private File getDataPathForPackage(String packageName, int userId) { 4811 /* 4812 * Until we fully support multiple users, return the directory we 4813 * previously would have. The PackageManagerTests will need to be 4814 * revised when this is changed back.. 4815 */ 4816 if (userId == 0) { 4817 return new File(mAppDataDir, packageName); 4818 } else { 4819 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4820 + File.separator + packageName); 4821 } 4822 } 4823 4824 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4825 int[] users = sUserManager.getUserIds(); 4826 int res = mInstaller.install(packageName, uid, uid, seinfo); 4827 if (res < 0) { 4828 return res; 4829 } 4830 for (int user : users) { 4831 if (user != 0) { 4832 res = mInstaller.createUserData(packageName, 4833 UserHandle.getUid(user, uid), user, seinfo); 4834 if (res < 0) { 4835 return res; 4836 } 4837 } 4838 } 4839 return res; 4840 } 4841 4842 private int removeDataDirsLI(String packageName) { 4843 int[] users = sUserManager.getUserIds(); 4844 int res = 0; 4845 for (int user : users) { 4846 int resInner = mInstaller.remove(packageName, user); 4847 if (resInner < 0) { 4848 res = resInner; 4849 } 4850 } 4851 4852 return res; 4853 } 4854 4855 private int deleteCodeCacheDirsLI(String packageName) { 4856 int[] users = sUserManager.getUserIds(); 4857 int res = 0; 4858 for (int user : users) { 4859 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4860 if (resInner < 0) { 4861 res = resInner; 4862 } 4863 } 4864 return res; 4865 } 4866 4867 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4868 PackageParser.Package changingLib) { 4869 if (file.path != null) { 4870 usesLibraryFiles.add(file.path); 4871 return; 4872 } 4873 PackageParser.Package p = mPackages.get(file.apk); 4874 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4875 // If we are doing this while in the middle of updating a library apk, 4876 // then we need to make sure to use that new apk for determining the 4877 // dependencies here. (We haven't yet finished committing the new apk 4878 // to the package manager state.) 4879 if (p == null || p.packageName.equals(changingLib.packageName)) { 4880 p = changingLib; 4881 } 4882 } 4883 if (p != null) { 4884 usesLibraryFiles.addAll(p.getAllCodePaths()); 4885 } 4886 } 4887 4888 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4889 PackageParser.Package changingLib) throws PackageManagerException { 4890 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4891 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4892 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4893 for (int i=0; i<N; i++) { 4894 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4895 if (file == null) { 4896 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4897 "Package " + pkg.packageName + " requires unavailable shared library " 4898 + pkg.usesLibraries.get(i) + "; failing!"); 4899 } 4900 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4901 } 4902 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4903 for (int i=0; i<N; i++) { 4904 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4905 if (file == null) { 4906 Slog.w(TAG, "Package " + pkg.packageName 4907 + " desires unavailable shared library " 4908 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4909 } else { 4910 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4911 } 4912 } 4913 N = usesLibraryFiles.size(); 4914 if (N > 0) { 4915 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4916 } else { 4917 pkg.usesLibraryFiles = null; 4918 } 4919 } 4920 } 4921 4922 private static boolean hasString(List<String> list, List<String> which) { 4923 if (list == null) { 4924 return false; 4925 } 4926 for (int i=list.size()-1; i>=0; i--) { 4927 for (int j=which.size()-1; j>=0; j--) { 4928 if (which.get(j).equals(list.get(i))) { 4929 return true; 4930 } 4931 } 4932 } 4933 return false; 4934 } 4935 4936 private void updateAllSharedLibrariesLPw() { 4937 for (PackageParser.Package pkg : mPackages.values()) { 4938 try { 4939 updateSharedLibrariesLPw(pkg, null); 4940 } catch (PackageManagerException e) { 4941 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4942 } 4943 } 4944 } 4945 4946 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4947 PackageParser.Package changingPkg) { 4948 ArrayList<PackageParser.Package> res = null; 4949 for (PackageParser.Package pkg : mPackages.values()) { 4950 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4951 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4952 if (res == null) { 4953 res = new ArrayList<PackageParser.Package>(); 4954 } 4955 res.add(pkg); 4956 try { 4957 updateSharedLibrariesLPw(pkg, changingPkg); 4958 } catch (PackageManagerException e) { 4959 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4960 } 4961 } 4962 } 4963 return res; 4964 } 4965 4966 /** 4967 * Derive the value of the {@code cpuAbiOverride} based on the provided 4968 * value and an optional stored value from the package settings. 4969 */ 4970 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4971 String cpuAbiOverride = null; 4972 4973 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 4974 cpuAbiOverride = null; 4975 } else if (abiOverride != null) { 4976 cpuAbiOverride = abiOverride; 4977 } else if (settings != null) { 4978 cpuAbiOverride = settings.cpuAbiOverrideString; 4979 } 4980 4981 return cpuAbiOverride; 4982 } 4983 4984 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4985 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 4986 boolean success = false; 4987 try { 4988 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 4989 currentTime, user); 4990 success = true; 4991 return res; 4992 } finally { 4993 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 4994 removeDataDirsLI(pkg.packageName); 4995 } 4996 } 4997 } 4998 4999 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5000 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5001 final File scanFile = new File(pkg.codePath); 5002 if (pkg.applicationInfo.getCodePath() == null || 5003 pkg.applicationInfo.getResourcePath() == null) { 5004 // Bail out. The resource and code paths haven't been set. 5005 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5006 "Code and resource paths haven't been set correctly"); 5007 } 5008 5009 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5010 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5011 } 5012 5013 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5014 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5015 } 5016 5017 if (mCustomResolverComponentName != null && 5018 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5019 setUpCustomResolverActivity(pkg); 5020 } 5021 5022 if (pkg.packageName.equals("android")) { 5023 synchronized (mPackages) { 5024 if (mAndroidApplication != null) { 5025 Slog.w(TAG, "*************************************************"); 5026 Slog.w(TAG, "Core android package being redefined. Skipping."); 5027 Slog.w(TAG, " file=" + scanFile); 5028 Slog.w(TAG, "*************************************************"); 5029 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5030 "Core android package being redefined. Skipping."); 5031 } 5032 5033 // Set up information for our fall-back user intent resolution activity. 5034 mPlatformPackage = pkg; 5035 pkg.mVersionCode = mSdkVersion; 5036 mAndroidApplication = pkg.applicationInfo; 5037 5038 if (!mResolverReplaced) { 5039 mResolveActivity.applicationInfo = mAndroidApplication; 5040 mResolveActivity.name = ResolverActivity.class.getName(); 5041 mResolveActivity.packageName = mAndroidApplication.packageName; 5042 mResolveActivity.processName = "system:ui"; 5043 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5044 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5045 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5046 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5047 mResolveActivity.exported = true; 5048 mResolveActivity.enabled = true; 5049 mResolveInfo.activityInfo = mResolveActivity; 5050 mResolveInfo.priority = 0; 5051 mResolveInfo.preferredOrder = 0; 5052 mResolveInfo.match = 0; 5053 mResolveComponentName = new ComponentName( 5054 mAndroidApplication.packageName, mResolveActivity.name); 5055 } 5056 } 5057 } 5058 5059 if (DEBUG_PACKAGE_SCANNING) { 5060 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5061 Log.d(TAG, "Scanning package " + pkg.packageName); 5062 } 5063 5064 if (mPackages.containsKey(pkg.packageName) 5065 || mSharedLibraries.containsKey(pkg.packageName)) { 5066 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5067 "Application package " + pkg.packageName 5068 + " already installed. Skipping duplicate."); 5069 } 5070 5071 // Initialize package source and resource directories 5072 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5073 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5074 5075 SharedUserSetting suid = null; 5076 PackageSetting pkgSetting = null; 5077 5078 if (!isSystemApp(pkg)) { 5079 // Only system apps can use these features. 5080 pkg.mOriginalPackages = null; 5081 pkg.mRealPackage = null; 5082 pkg.mAdoptPermissions = null; 5083 } 5084 5085 // writer 5086 synchronized (mPackages) { 5087 if (pkg.mSharedUserId != null) { 5088 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5089 if (suid == null) { 5090 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5091 "Creating application package " + pkg.packageName 5092 + " for shared user failed"); 5093 } 5094 if (DEBUG_PACKAGE_SCANNING) { 5095 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5096 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5097 + "): packages=" + suid.packages); 5098 } 5099 } 5100 5101 // Check if we are renaming from an original package name. 5102 PackageSetting origPackage = null; 5103 String realName = null; 5104 if (pkg.mOriginalPackages != null) { 5105 // This package may need to be renamed to a previously 5106 // installed name. Let's check on that... 5107 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5108 if (pkg.mOriginalPackages.contains(renamed)) { 5109 // This package had originally been installed as the 5110 // original name, and we have already taken care of 5111 // transitioning to the new one. Just update the new 5112 // one to continue using the old name. 5113 realName = pkg.mRealPackage; 5114 if (!pkg.packageName.equals(renamed)) { 5115 // Callers into this function may have already taken 5116 // care of renaming the package; only do it here if 5117 // it is not already done. 5118 pkg.setPackageName(renamed); 5119 } 5120 5121 } else { 5122 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5123 if ((origPackage = mSettings.peekPackageLPr( 5124 pkg.mOriginalPackages.get(i))) != null) { 5125 // We do have the package already installed under its 5126 // original name... should we use it? 5127 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5128 // New package is not compatible with original. 5129 origPackage = null; 5130 continue; 5131 } else if (origPackage.sharedUser != null) { 5132 // Make sure uid is compatible between packages. 5133 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5134 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5135 + " to " + pkg.packageName + ": old uid " 5136 + origPackage.sharedUser.name 5137 + " differs from " + pkg.mSharedUserId); 5138 origPackage = null; 5139 continue; 5140 } 5141 } else { 5142 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5143 + pkg.packageName + " to old name " + origPackage.name); 5144 } 5145 break; 5146 } 5147 } 5148 } 5149 } 5150 5151 if (mTransferedPackages.contains(pkg.packageName)) { 5152 Slog.w(TAG, "Package " + pkg.packageName 5153 + " was transferred to another, but its .apk remains"); 5154 } 5155 5156 // Just create the setting, don't add it yet. For already existing packages 5157 // the PkgSetting exists already and doesn't have to be created. 5158 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5159 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5160 pkg.applicationInfo.primaryCpuAbi, 5161 pkg.applicationInfo.secondaryCpuAbi, 5162 pkg.applicationInfo.flags, user, false); 5163 if (pkgSetting == null) { 5164 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5165 "Creating application package " + pkg.packageName + " failed"); 5166 } 5167 5168 if (pkgSetting.origPackage != null) { 5169 // If we are first transitioning from an original package, 5170 // fix up the new package's name now. We need to do this after 5171 // looking up the package under its new name, so getPackageLP 5172 // can take care of fiddling things correctly. 5173 pkg.setPackageName(origPackage.name); 5174 5175 // File a report about this. 5176 String msg = "New package " + pkgSetting.realName 5177 + " renamed to replace old package " + pkgSetting.name; 5178 reportSettingsProblem(Log.WARN, msg); 5179 5180 // Make a note of it. 5181 mTransferedPackages.add(origPackage.name); 5182 5183 // No longer need to retain this. 5184 pkgSetting.origPackage = null; 5185 } 5186 5187 if (realName != null) { 5188 // Make a note of it. 5189 mTransferedPackages.add(pkg.packageName); 5190 } 5191 5192 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5193 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5194 } 5195 5196 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5197 // Check all shared libraries and map to their actual file path. 5198 // We only do this here for apps not on a system dir, because those 5199 // are the only ones that can fail an install due to this. We 5200 // will take care of the system apps by updating all of their 5201 // library paths after the scan is done. 5202 updateSharedLibrariesLPw(pkg, null); 5203 } 5204 5205 if (mFoundPolicyFile) { 5206 SELinuxMMAC.assignSeinfoValue(pkg); 5207 } 5208 5209 pkg.applicationInfo.uid = pkgSetting.appId; 5210 pkg.mExtras = pkgSetting; 5211 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5212 try { 5213 verifySignaturesLP(pkgSetting, pkg); 5214 } catch (PackageManagerException e) { 5215 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5216 throw e; 5217 } 5218 // The signature has changed, but this package is in the system 5219 // image... let's recover! 5220 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5221 // However... if this package is part of a shared user, but it 5222 // doesn't match the signature of the shared user, let's fail. 5223 // What this means is that you can't change the signatures 5224 // associated with an overall shared user, which doesn't seem all 5225 // that unreasonable. 5226 if (pkgSetting.sharedUser != null) { 5227 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5228 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5229 throw new PackageManagerException( 5230 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5231 "Signature mismatch for shared user : " 5232 + pkgSetting.sharedUser); 5233 } 5234 } 5235 // File a report about this. 5236 String msg = "System package " + pkg.packageName 5237 + " signature changed; retaining data."; 5238 reportSettingsProblem(Log.WARN, msg); 5239 } 5240 } else { 5241 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5242 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5243 + pkg.packageName + " upgrade keys do not match the " 5244 + "previously installed version"); 5245 } else { 5246 // signatures may have changed as result of upgrade 5247 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5248 } 5249 } 5250 // Verify that this new package doesn't have any content providers 5251 // that conflict with existing packages. Only do this if the 5252 // package isn't already installed, since we don't want to break 5253 // things that are installed. 5254 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5255 final int N = pkg.providers.size(); 5256 int i; 5257 for (i=0; i<N; i++) { 5258 PackageParser.Provider p = pkg.providers.get(i); 5259 if (p.info.authority != null) { 5260 String names[] = p.info.authority.split(";"); 5261 for (int j = 0; j < names.length; j++) { 5262 if (mProvidersByAuthority.containsKey(names[j])) { 5263 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5264 final String otherPackageName = 5265 ((other != null && other.getComponentName() != null) ? 5266 other.getComponentName().getPackageName() : "?"); 5267 throw new PackageManagerException( 5268 INSTALL_FAILED_CONFLICTING_PROVIDER, 5269 "Can't install because provider name " + names[j] 5270 + " (in package " + pkg.applicationInfo.packageName 5271 + ") is already used by " + otherPackageName); 5272 } 5273 } 5274 } 5275 } 5276 } 5277 5278 if (pkg.mAdoptPermissions != null) { 5279 // This package wants to adopt ownership of permissions from 5280 // another package. 5281 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5282 final String origName = pkg.mAdoptPermissions.get(i); 5283 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5284 if (orig != null) { 5285 if (verifyPackageUpdateLPr(orig, pkg)) { 5286 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5287 + pkg.packageName); 5288 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5289 } 5290 } 5291 } 5292 } 5293 } 5294 5295 final String pkgName = pkg.packageName; 5296 5297 final long scanFileTime = scanFile.lastModified(); 5298 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5299 pkg.applicationInfo.processName = fixProcessName( 5300 pkg.applicationInfo.packageName, 5301 pkg.applicationInfo.processName, 5302 pkg.applicationInfo.uid); 5303 5304 File dataPath; 5305 if (mPlatformPackage == pkg) { 5306 // The system package is special. 5307 dataPath = new File(Environment.getDataDirectory(), "system"); 5308 5309 pkg.applicationInfo.dataDir = dataPath.getPath(); 5310 5311 } else { 5312 // This is a normal package, need to make its data directory. 5313 dataPath = getDataPathForPackage(pkg.packageName, 0); 5314 5315 boolean uidError = false; 5316 if (dataPath.exists()) { 5317 int currentUid = 0; 5318 try { 5319 StructStat stat = Os.stat(dataPath.getPath()); 5320 currentUid = stat.st_uid; 5321 } catch (ErrnoException e) { 5322 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5323 } 5324 5325 // If we have mismatched owners for the data path, we have a problem. 5326 if (currentUid != pkg.applicationInfo.uid) { 5327 boolean recovered = false; 5328 if (currentUid == 0) { 5329 // The directory somehow became owned by root. Wow. 5330 // This is probably because the system was stopped while 5331 // installd was in the middle of messing with its libs 5332 // directory. Ask installd to fix that. 5333 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5334 pkg.applicationInfo.uid); 5335 if (ret >= 0) { 5336 recovered = true; 5337 String msg = "Package " + pkg.packageName 5338 + " unexpectedly changed to uid 0; recovered to " + 5339 + pkg.applicationInfo.uid; 5340 reportSettingsProblem(Log.WARN, msg); 5341 } 5342 } 5343 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5344 || (scanFlags&SCAN_BOOTING) != 0)) { 5345 // If this is a system app, we can at least delete its 5346 // current data so the application will still work. 5347 int ret = removeDataDirsLI(pkgName); 5348 if (ret >= 0) { 5349 // TODO: Kill the processes first 5350 // Old data gone! 5351 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5352 ? "System package " : "Third party package "; 5353 String msg = prefix + pkg.packageName 5354 + " has changed from uid: " 5355 + currentUid + " to " 5356 + pkg.applicationInfo.uid + "; old data erased"; 5357 reportSettingsProblem(Log.WARN, msg); 5358 recovered = true; 5359 5360 // And now re-install the app. 5361 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5362 pkg.applicationInfo.seinfo); 5363 if (ret == -1) { 5364 // Ack should not happen! 5365 msg = prefix + pkg.packageName 5366 + " could not have data directory re-created after delete."; 5367 reportSettingsProblem(Log.WARN, msg); 5368 throw new PackageManagerException( 5369 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5370 } 5371 } 5372 if (!recovered) { 5373 mHasSystemUidErrors = true; 5374 } 5375 } else if (!recovered) { 5376 // If we allow this install to proceed, we will be broken. 5377 // Abort, abort! 5378 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5379 "scanPackageLI"); 5380 } 5381 if (!recovered) { 5382 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5383 + pkg.applicationInfo.uid + "/fs_" 5384 + currentUid; 5385 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5386 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5387 String msg = "Package " + pkg.packageName 5388 + " has mismatched uid: " 5389 + currentUid + " on disk, " 5390 + pkg.applicationInfo.uid + " in settings"; 5391 // writer 5392 synchronized (mPackages) { 5393 mSettings.mReadMessages.append(msg); 5394 mSettings.mReadMessages.append('\n'); 5395 uidError = true; 5396 if (!pkgSetting.uidError) { 5397 reportSettingsProblem(Log.ERROR, msg); 5398 } 5399 } 5400 } 5401 } 5402 pkg.applicationInfo.dataDir = dataPath.getPath(); 5403 if (mShouldRestoreconData) { 5404 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5405 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5406 pkg.applicationInfo.uid); 5407 } 5408 } else { 5409 if (DEBUG_PACKAGE_SCANNING) { 5410 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5411 Log.v(TAG, "Want this data dir: " + dataPath); 5412 } 5413 //invoke installer to do the actual installation 5414 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5415 pkg.applicationInfo.seinfo); 5416 if (ret < 0) { 5417 // Error from installer 5418 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5419 "Unable to create data dirs [errorCode=" + ret + "]"); 5420 } 5421 5422 if (dataPath.exists()) { 5423 pkg.applicationInfo.dataDir = dataPath.getPath(); 5424 } else { 5425 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5426 pkg.applicationInfo.dataDir = null; 5427 } 5428 } 5429 5430 pkgSetting.uidError = uidError; 5431 } 5432 5433 final String path = scanFile.getPath(); 5434 final String codePath = pkg.applicationInfo.getCodePath(); 5435 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5436 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5437 setBundledAppAbisAndRoots(pkg, pkgSetting); 5438 5439 // If we haven't found any native libraries for the app, check if it has 5440 // renderscript code. We'll need to force the app to 32 bit if it has 5441 // renderscript bitcode. 5442 if (pkg.applicationInfo.primaryCpuAbi == null 5443 && pkg.applicationInfo.secondaryCpuAbi == null 5444 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5445 NativeLibraryHelper.Handle handle = null; 5446 try { 5447 handle = NativeLibraryHelper.Handle.create(scanFile); 5448 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5449 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5450 } 5451 } catch (IOException ioe) { 5452 Slog.w(TAG, "Error scanning system app : " + ioe); 5453 } finally { 5454 IoUtils.closeQuietly(handle); 5455 } 5456 } 5457 5458 setNativeLibraryPaths(pkg); 5459 } else { 5460 // TODO: We can probably be smarter about this stuff. For installed apps, 5461 // we can calculate this information at install time once and for all. For 5462 // system apps, we can probably assume that this information doesn't change 5463 // after the first boot scan. As things stand, we do lots of unnecessary work. 5464 5465 // Give ourselves some initial paths; we'll come back for another 5466 // pass once we've determined ABI below. 5467 setNativeLibraryPaths(pkg); 5468 5469 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5470 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5471 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5472 5473 NativeLibraryHelper.Handle handle = null; 5474 try { 5475 handle = NativeLibraryHelper.Handle.create(scanFile); 5476 // TODO(multiArch): This can be null for apps that didn't go through the 5477 // usual installation process. We can calculate it again, like we 5478 // do during install time. 5479 // 5480 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5481 // unnecessary. 5482 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5483 5484 // Null out the abis so that they can be recalculated. 5485 pkg.applicationInfo.primaryCpuAbi = null; 5486 pkg.applicationInfo.secondaryCpuAbi = null; 5487 if (isMultiArch(pkg.applicationInfo)) { 5488 // Warn if we've set an abiOverride for multi-lib packages.. 5489 // By definition, we need to copy both 32 and 64 bit libraries for 5490 // such packages. 5491 if (pkg.cpuAbiOverride != null 5492 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5493 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5494 } 5495 5496 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5497 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5498 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5499 if (isAsec) { 5500 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5501 } else { 5502 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5503 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5504 useIsaSpecificSubdirs); 5505 } 5506 } 5507 5508 maybeThrowExceptionForMultiArchCopy( 5509 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5510 5511 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5512 if (isAsec) { 5513 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5514 } else { 5515 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5516 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5517 useIsaSpecificSubdirs); 5518 } 5519 } 5520 5521 maybeThrowExceptionForMultiArchCopy( 5522 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5523 5524 if (abi64 >= 0) { 5525 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5526 } 5527 5528 if (abi32 >= 0) { 5529 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5530 if (abi64 >= 0) { 5531 pkg.applicationInfo.secondaryCpuAbi = abi; 5532 } else { 5533 pkg.applicationInfo.primaryCpuAbi = abi; 5534 } 5535 } 5536 } else { 5537 String[] abiList = (cpuAbiOverride != null) ? 5538 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5539 5540 // Enable gross and lame hacks for apps that are built with old 5541 // SDK tools. We must scan their APKs for renderscript bitcode and 5542 // not launch them if it's present. Don't bother checking on devices 5543 // that don't have 64 bit support. 5544 boolean needsRenderScriptOverride = false; 5545 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5546 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5547 abiList = Build.SUPPORTED_32_BIT_ABIS; 5548 needsRenderScriptOverride = true; 5549 } 5550 5551 final int copyRet; 5552 if (isAsec) { 5553 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5554 } else { 5555 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5556 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5557 } 5558 5559 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5560 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5561 "Error unpackaging native libs for app, errorCode=" + copyRet); 5562 } 5563 5564 if (copyRet >= 0) { 5565 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5566 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5567 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5568 } else if (needsRenderScriptOverride) { 5569 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5570 } 5571 } 5572 } catch (IOException ioe) { 5573 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5574 } finally { 5575 IoUtils.closeQuietly(handle); 5576 } 5577 5578 // Now that we've calculated the ABIs and determined if it's an internal app, 5579 // we will go ahead and populate the nativeLibraryPath. 5580 setNativeLibraryPaths(pkg); 5581 5582 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5583 final int[] userIds = sUserManager.getUserIds(); 5584 synchronized (mInstallLock) { 5585 // Create a native library symlink only if we have native libraries 5586 // and if the native libraries are 32 bit libraries. We do not provide 5587 // this symlink for 64 bit libraries. 5588 if (pkg.applicationInfo.primaryCpuAbi != null && 5589 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5590 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5591 for (int userId : userIds) { 5592 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5593 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5594 "Failed linking native library dir (user=" + userId + ")"); 5595 } 5596 } 5597 } 5598 } 5599 } 5600 5601 // This is a special case for the "system" package, where the ABI is 5602 // dictated by the zygote configuration (and init.rc). We should keep track 5603 // of this ABI so that we can deal with "normal" applications that run under 5604 // the same UID correctly. 5605 if (mPlatformPackage == pkg) { 5606 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5607 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5608 } 5609 5610 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5611 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5612 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5613 // Copy the derived override back to the parsed package, so that we can 5614 // update the package settings accordingly. 5615 pkg.cpuAbiOverride = cpuAbiOverride; 5616 5617 if (DEBUG_ABI_SELECTION) { 5618 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5619 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5620 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5621 } 5622 5623 // Push the derived path down into PackageSettings so we know what to 5624 // clean up at uninstall time. 5625 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5626 5627 if (DEBUG_ABI_SELECTION) { 5628 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5629 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5630 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5631 } 5632 5633 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5634 // We don't do this here during boot because we can do it all 5635 // at once after scanning all existing packages. 5636 // 5637 // We also do this *before* we perform dexopt on this package, so that 5638 // we can avoid redundant dexopts, and also to make sure we've got the 5639 // code and package path correct. 5640 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5641 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5642 } 5643 5644 if ((scanFlags & SCAN_NO_DEX) == 0) { 5645 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5646 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5647 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5648 } 5649 } 5650 5651 if (mFactoryTest && pkg.requestedPermissions.contains( 5652 android.Manifest.permission.FACTORY_TEST)) { 5653 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5654 } 5655 5656 ArrayList<PackageParser.Package> clientLibPkgs = null; 5657 5658 // writer 5659 synchronized (mPackages) { 5660 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5661 // Only system apps can add new shared libraries. 5662 if (pkg.libraryNames != null) { 5663 for (int i=0; i<pkg.libraryNames.size(); i++) { 5664 String name = pkg.libraryNames.get(i); 5665 boolean allowed = false; 5666 if (isUpdatedSystemApp(pkg)) { 5667 // New library entries can only be added through the 5668 // system image. This is important to get rid of a lot 5669 // of nasty edge cases: for example if we allowed a non- 5670 // system update of the app to add a library, then uninstalling 5671 // the update would make the library go away, and assumptions 5672 // we made such as through app install filtering would now 5673 // have allowed apps on the device which aren't compatible 5674 // with it. Better to just have the restriction here, be 5675 // conservative, and create many fewer cases that can negatively 5676 // impact the user experience. 5677 final PackageSetting sysPs = mSettings 5678 .getDisabledSystemPkgLPr(pkg.packageName); 5679 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5680 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5681 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5682 allowed = true; 5683 allowed = true; 5684 break; 5685 } 5686 } 5687 } 5688 } else { 5689 allowed = true; 5690 } 5691 if (allowed) { 5692 if (!mSharedLibraries.containsKey(name)) { 5693 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5694 } else if (!name.equals(pkg.packageName)) { 5695 Slog.w(TAG, "Package " + pkg.packageName + " library " 5696 + name + " already exists; skipping"); 5697 } 5698 } else { 5699 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5700 + name + " that is not declared on system image; skipping"); 5701 } 5702 } 5703 if ((scanFlags&SCAN_BOOTING) == 0) { 5704 // If we are not booting, we need to update any applications 5705 // that are clients of our shared library. If we are booting, 5706 // this will all be done once the scan is complete. 5707 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5708 } 5709 } 5710 } 5711 } 5712 5713 // We also need to dexopt any apps that are dependent on this library. Note that 5714 // if these fail, we should abort the install since installing the library will 5715 // result in some apps being broken. 5716 if (clientLibPkgs != null) { 5717 if ((scanFlags & SCAN_NO_DEX) == 0) { 5718 for (int i = 0; i < clientLibPkgs.size(); i++) { 5719 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5720 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5721 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5722 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5723 "scanPackageLI failed to dexopt clientLibPkgs"); 5724 } 5725 } 5726 } 5727 } 5728 5729 // Request the ActivityManager to kill the process(only for existing packages) 5730 // so that we do not end up in a confused state while the user is still using the older 5731 // version of the application while the new one gets installed. 5732 if ((scanFlags & SCAN_REPLACING) != 0) { 5733 killApplication(pkg.applicationInfo.packageName, 5734 pkg.applicationInfo.uid, "update pkg"); 5735 } 5736 5737 // Also need to kill any apps that are dependent on the library. 5738 if (clientLibPkgs != null) { 5739 for (int i=0; i<clientLibPkgs.size(); i++) { 5740 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5741 killApplication(clientPkg.applicationInfo.packageName, 5742 clientPkg.applicationInfo.uid, "update lib"); 5743 } 5744 } 5745 5746 // writer 5747 synchronized (mPackages) { 5748 // We don't expect installation to fail beyond this point 5749 5750 // Add the new setting to mSettings 5751 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5752 // Add the new setting to mPackages 5753 mPackages.put(pkg.applicationInfo.packageName, pkg); 5754 // Make sure we don't accidentally delete its data. 5755 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5756 while (iter.hasNext()) { 5757 PackageCleanItem item = iter.next(); 5758 if (pkgName.equals(item.packageName)) { 5759 iter.remove(); 5760 } 5761 } 5762 5763 // Take care of first install / last update times. 5764 if (currentTime != 0) { 5765 if (pkgSetting.firstInstallTime == 0) { 5766 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5767 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5768 pkgSetting.lastUpdateTime = currentTime; 5769 } 5770 } else if (pkgSetting.firstInstallTime == 0) { 5771 // We need *something*. Take time time stamp of the file. 5772 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5773 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5774 if (scanFileTime != pkgSetting.timeStamp) { 5775 // A package on the system image has changed; consider this 5776 // to be an update. 5777 pkgSetting.lastUpdateTime = scanFileTime; 5778 } 5779 } 5780 5781 // Add the package's KeySets to the global KeySetManagerService 5782 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5783 try { 5784 // Old KeySetData no longer valid. 5785 ksms.removeAppKeySetDataLPw(pkg.packageName); 5786 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5787 if (pkg.mKeySetMapping != null) { 5788 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5789 pkg.mKeySetMapping.entrySet()) { 5790 if (entry.getValue() != null) { 5791 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5792 entry.getValue(), entry.getKey()); 5793 } 5794 } 5795 if (pkg.mUpgradeKeySets != null) { 5796 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5797 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5798 } 5799 } 5800 } 5801 } catch (NullPointerException e) { 5802 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5803 } catch (IllegalArgumentException e) { 5804 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5805 } 5806 5807 int N = pkg.providers.size(); 5808 StringBuilder r = null; 5809 int i; 5810 for (i=0; i<N; i++) { 5811 PackageParser.Provider p = pkg.providers.get(i); 5812 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5813 p.info.processName, pkg.applicationInfo.uid); 5814 mProviders.addProvider(p); 5815 p.syncable = p.info.isSyncable; 5816 if (p.info.authority != null) { 5817 String names[] = p.info.authority.split(";"); 5818 p.info.authority = null; 5819 for (int j = 0; j < names.length; j++) { 5820 if (j == 1 && p.syncable) { 5821 // We only want the first authority for a provider to possibly be 5822 // syncable, so if we already added this provider using a different 5823 // authority clear the syncable flag. We copy the provider before 5824 // changing it because the mProviders object contains a reference 5825 // to a provider that we don't want to change. 5826 // Only do this for the second authority since the resulting provider 5827 // object can be the same for all future authorities for this provider. 5828 p = new PackageParser.Provider(p); 5829 p.syncable = false; 5830 } 5831 if (!mProvidersByAuthority.containsKey(names[j])) { 5832 mProvidersByAuthority.put(names[j], p); 5833 if (p.info.authority == null) { 5834 p.info.authority = names[j]; 5835 } else { 5836 p.info.authority = p.info.authority + ";" + names[j]; 5837 } 5838 if (DEBUG_PACKAGE_SCANNING) { 5839 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5840 Log.d(TAG, "Registered content provider: " + names[j] 5841 + ", className = " + p.info.name + ", isSyncable = " 5842 + p.info.isSyncable); 5843 } 5844 } else { 5845 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5846 Slog.w(TAG, "Skipping provider name " + names[j] + 5847 " (in package " + pkg.applicationInfo.packageName + 5848 "): name already used by " 5849 + ((other != null && other.getComponentName() != null) 5850 ? other.getComponentName().getPackageName() : "?")); 5851 } 5852 } 5853 } 5854 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5855 if (r == null) { 5856 r = new StringBuilder(256); 5857 } else { 5858 r.append(' '); 5859 } 5860 r.append(p.info.name); 5861 } 5862 } 5863 if (r != null) { 5864 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5865 } 5866 5867 N = pkg.services.size(); 5868 r = null; 5869 for (i=0; i<N; i++) { 5870 PackageParser.Service s = pkg.services.get(i); 5871 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5872 s.info.processName, pkg.applicationInfo.uid); 5873 mServices.addService(s); 5874 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5875 if (r == null) { 5876 r = new StringBuilder(256); 5877 } else { 5878 r.append(' '); 5879 } 5880 r.append(s.info.name); 5881 } 5882 } 5883 if (r != null) { 5884 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5885 } 5886 5887 N = pkg.receivers.size(); 5888 r = null; 5889 for (i=0; i<N; i++) { 5890 PackageParser.Activity a = pkg.receivers.get(i); 5891 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5892 a.info.processName, pkg.applicationInfo.uid); 5893 mReceivers.addActivity(a, "receiver"); 5894 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5895 if (r == null) { 5896 r = new StringBuilder(256); 5897 } else { 5898 r.append(' '); 5899 } 5900 r.append(a.info.name); 5901 } 5902 } 5903 if (r != null) { 5904 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5905 } 5906 5907 N = pkg.activities.size(); 5908 r = null; 5909 for (i=0; i<N; i++) { 5910 PackageParser.Activity a = pkg.activities.get(i); 5911 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5912 a.info.processName, pkg.applicationInfo.uid); 5913 mActivities.addActivity(a, "activity"); 5914 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5915 if (r == null) { 5916 r = new StringBuilder(256); 5917 } else { 5918 r.append(' '); 5919 } 5920 r.append(a.info.name); 5921 } 5922 } 5923 if (r != null) { 5924 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5925 } 5926 5927 N = pkg.permissionGroups.size(); 5928 r = null; 5929 for (i=0; i<N; i++) { 5930 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5931 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5932 if (cur == null) { 5933 mPermissionGroups.put(pg.info.name, pg); 5934 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5935 if (r == null) { 5936 r = new StringBuilder(256); 5937 } else { 5938 r.append(' '); 5939 } 5940 r.append(pg.info.name); 5941 } 5942 } else { 5943 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5944 + pg.info.packageName + " ignored: original from " 5945 + cur.info.packageName); 5946 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5947 if (r == null) { 5948 r = new StringBuilder(256); 5949 } else { 5950 r.append(' '); 5951 } 5952 r.append("DUP:"); 5953 r.append(pg.info.name); 5954 } 5955 } 5956 } 5957 if (r != null) { 5958 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5959 } 5960 5961 N = pkg.permissions.size(); 5962 r = null; 5963 for (i=0; i<N; i++) { 5964 PackageParser.Permission p = pkg.permissions.get(i); 5965 HashMap<String, BasePermission> permissionMap = 5966 p.tree ? mSettings.mPermissionTrees 5967 : mSettings.mPermissions; 5968 p.group = mPermissionGroups.get(p.info.group); 5969 if (p.info.group == null || p.group != null) { 5970 BasePermission bp = permissionMap.get(p.info.name); 5971 5972 // Allow system apps to redefine non-system permissions 5973 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 5974 final boolean currentOwnerIsSystem = (bp.perm != null 5975 && isSystemApp(bp.perm.owner)); 5976 if (isSystemApp(p.owner)) { 5977 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 5978 // It's a built-in permission and no owner, take ownership now 5979 bp.packageSetting = pkgSetting; 5980 bp.perm = p; 5981 bp.uid = pkg.applicationInfo.uid; 5982 bp.sourcePackage = p.info.packageName; 5983 } else if (!currentOwnerIsSystem) { 5984 String msg = "New decl " + p.owner + " of permission " 5985 + p.info.name + " is system; overriding " + bp.sourcePackage; 5986 reportSettingsProblem(Log.WARN, msg); 5987 bp = null; 5988 } 5989 } 5990 } 5991 5992 if (bp == null) { 5993 bp = new BasePermission(p.info.name, p.info.packageName, 5994 BasePermission.TYPE_NORMAL); 5995 permissionMap.put(p.info.name, bp); 5996 } 5997 5998 if (bp.perm == null) { 5999 if (bp.sourcePackage == null 6000 || bp.sourcePackage.equals(p.info.packageName)) { 6001 BasePermission tree = findPermissionTreeLP(p.info.name); 6002 if (tree == null 6003 || tree.sourcePackage.equals(p.info.packageName)) { 6004 bp.packageSetting = pkgSetting; 6005 bp.perm = p; 6006 bp.uid = pkg.applicationInfo.uid; 6007 bp.sourcePackage = p.info.packageName; 6008 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6009 if (r == null) { 6010 r = new StringBuilder(256); 6011 } else { 6012 r.append(' '); 6013 } 6014 r.append(p.info.name); 6015 } 6016 } else { 6017 Slog.w(TAG, "Permission " + p.info.name + " from package " 6018 + p.info.packageName + " ignored: base tree " 6019 + tree.name + " is from package " 6020 + tree.sourcePackage); 6021 } 6022 } else { 6023 Slog.w(TAG, "Permission " + p.info.name + " from package " 6024 + p.info.packageName + " ignored: original from " 6025 + bp.sourcePackage); 6026 } 6027 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6028 if (r == null) { 6029 r = new StringBuilder(256); 6030 } else { 6031 r.append(' '); 6032 } 6033 r.append("DUP:"); 6034 r.append(p.info.name); 6035 } 6036 if (bp.perm == p) { 6037 bp.protectionLevel = p.info.protectionLevel; 6038 } 6039 } else { 6040 Slog.w(TAG, "Permission " + p.info.name + " from package " 6041 + p.info.packageName + " ignored: no group " 6042 + p.group); 6043 } 6044 } 6045 if (r != null) { 6046 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6047 } 6048 6049 N = pkg.instrumentation.size(); 6050 r = null; 6051 for (i=0; i<N; i++) { 6052 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6053 a.info.packageName = pkg.applicationInfo.packageName; 6054 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6055 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6056 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6057 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6058 a.info.dataDir = pkg.applicationInfo.dataDir; 6059 6060 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6061 // need other information about the application, like the ABI and what not ? 6062 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6063 mInstrumentation.put(a.getComponentName(), a); 6064 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6065 if (r == null) { 6066 r = new StringBuilder(256); 6067 } else { 6068 r.append(' '); 6069 } 6070 r.append(a.info.name); 6071 } 6072 } 6073 if (r != null) { 6074 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6075 } 6076 6077 if (pkg.protectedBroadcasts != null) { 6078 N = pkg.protectedBroadcasts.size(); 6079 for (i=0; i<N; i++) { 6080 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6081 } 6082 } 6083 6084 pkgSetting.setTimeStamp(scanFileTime); 6085 6086 // Create idmap files for pairs of (packages, overlay packages). 6087 // Note: "android", ie framework-res.apk, is handled by native layers. 6088 if (pkg.mOverlayTarget != null) { 6089 // This is an overlay package. 6090 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6091 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6092 mOverlays.put(pkg.mOverlayTarget, 6093 new HashMap<String, PackageParser.Package>()); 6094 } 6095 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6096 map.put(pkg.packageName, pkg); 6097 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6098 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6099 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6100 "scanPackageLI failed to createIdmap"); 6101 } 6102 } 6103 } else if (mOverlays.containsKey(pkg.packageName) && 6104 !pkg.packageName.equals("android")) { 6105 // This is a regular package, with one or more known overlay packages. 6106 createIdmapsForPackageLI(pkg); 6107 } 6108 } 6109 6110 return pkg; 6111 } 6112 6113 /** 6114 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6115 * i.e, so that all packages can be run inside a single process if required. 6116 * 6117 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6118 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6119 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6120 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6121 * updating a package that belongs to a shared user. 6122 * 6123 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6124 * adds unnecessary complexity. 6125 */ 6126 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6127 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6128 String requiredInstructionSet = null; 6129 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6130 requiredInstructionSet = VMRuntime.getInstructionSet( 6131 scannedPackage.applicationInfo.primaryCpuAbi); 6132 } 6133 6134 PackageSetting requirer = null; 6135 for (PackageSetting ps : packagesForUser) { 6136 // If packagesForUser contains scannedPackage, we skip it. This will happen 6137 // when scannedPackage is an update of an existing package. Without this check, 6138 // we will never be able to change the ABI of any package belonging to a shared 6139 // user, even if it's compatible with other packages. 6140 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6141 if (ps.primaryCpuAbiString == null) { 6142 continue; 6143 } 6144 6145 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6146 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6147 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6148 // this but there's not much we can do. 6149 String errorMessage = "Instruction set mismatch, " 6150 + ((requirer == null) ? "[caller]" : requirer) 6151 + " requires " + requiredInstructionSet + " whereas " + ps 6152 + " requires " + instructionSet; 6153 Slog.w(TAG, errorMessage); 6154 } 6155 6156 if (requiredInstructionSet == null) { 6157 requiredInstructionSet = instructionSet; 6158 requirer = ps; 6159 } 6160 } 6161 } 6162 6163 if (requiredInstructionSet != null) { 6164 String adjustedAbi; 6165 if (requirer != null) { 6166 // requirer != null implies that either scannedPackage was null or that scannedPackage 6167 // did not require an ABI, in which case we have to adjust scannedPackage to match 6168 // the ABI of the set (which is the same as requirer's ABI) 6169 adjustedAbi = requirer.primaryCpuAbiString; 6170 if (scannedPackage != null) { 6171 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6172 } 6173 } else { 6174 // requirer == null implies that we're updating all ABIs in the set to 6175 // match scannedPackage. 6176 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6177 } 6178 6179 for (PackageSetting ps : packagesForUser) { 6180 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6181 if (ps.primaryCpuAbiString != null) { 6182 continue; 6183 } 6184 6185 ps.primaryCpuAbiString = adjustedAbi; 6186 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6187 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6188 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6189 6190 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6191 deferDexOpt, true) == DEX_OPT_FAILED) { 6192 ps.primaryCpuAbiString = null; 6193 ps.pkg.applicationInfo.primaryCpuAbi = null; 6194 return; 6195 } else { 6196 mInstaller.rmdex(ps.codePathString, 6197 getDexCodeInstructionSet(getPreferredInstructionSet())); 6198 } 6199 } 6200 } 6201 } 6202 } 6203 } 6204 6205 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6206 synchronized (mPackages) { 6207 mResolverReplaced = true; 6208 // Set up information for custom user intent resolution activity. 6209 mResolveActivity.applicationInfo = pkg.applicationInfo; 6210 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6211 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6212 mResolveActivity.processName = null; 6213 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6214 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6215 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6216 mResolveActivity.theme = 0; 6217 mResolveActivity.exported = true; 6218 mResolveActivity.enabled = true; 6219 mResolveInfo.activityInfo = mResolveActivity; 6220 mResolveInfo.priority = 0; 6221 mResolveInfo.preferredOrder = 0; 6222 mResolveInfo.match = 0; 6223 mResolveComponentName = mCustomResolverComponentName; 6224 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6225 mResolveComponentName); 6226 } 6227 } 6228 6229 private static String calculateBundledApkRoot(final String codePathString) { 6230 final File codePath = new File(codePathString); 6231 final File codeRoot; 6232 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6233 codeRoot = Environment.getRootDirectory(); 6234 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6235 codeRoot = Environment.getOemDirectory(); 6236 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6237 codeRoot = Environment.getVendorDirectory(); 6238 } else { 6239 // Unrecognized code path; take its top real segment as the apk root: 6240 // e.g. /something/app/blah.apk => /something 6241 try { 6242 File f = codePath.getCanonicalFile(); 6243 File parent = f.getParentFile(); // non-null because codePath is a file 6244 File tmp; 6245 while ((tmp = parent.getParentFile()) != null) { 6246 f = parent; 6247 parent = tmp; 6248 } 6249 codeRoot = f; 6250 Slog.w(TAG, "Unrecognized code path " 6251 + codePath + " - using " + codeRoot); 6252 } catch (IOException e) { 6253 // Can't canonicalize the code path -- shenanigans? 6254 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6255 return Environment.getRootDirectory().getPath(); 6256 } 6257 } 6258 return codeRoot.getPath(); 6259 } 6260 6261 /** 6262 * Derive and set the location of native libraries for the given package, 6263 * which varies depending on where and how the package was installed. 6264 */ 6265 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6266 final ApplicationInfo info = pkg.applicationInfo; 6267 final String codePath = pkg.codePath; 6268 final File codeFile = new File(codePath); 6269 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6270 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6271 6272 info.nativeLibraryRootDir = null; 6273 info.nativeLibraryRootRequiresIsa = false; 6274 info.nativeLibraryDir = null; 6275 info.secondaryNativeLibraryDir = null; 6276 6277 if (isApkFile(codeFile)) { 6278 // Monolithic install 6279 if (bundledApp) { 6280 // If "/system/lib64/apkname" exists, assume that is the per-package 6281 // native library directory to use; otherwise use "/system/lib/apkname". 6282 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6283 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6284 getPrimaryInstructionSet(info)); 6285 6286 // This is a bundled system app so choose the path based on the ABI. 6287 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6288 // is just the default path. 6289 final String apkName = deriveCodePathName(codePath); 6290 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6291 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6292 apkName).getAbsolutePath(); 6293 6294 if (info.secondaryCpuAbi != null) { 6295 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6296 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6297 secondaryLibDir, apkName).getAbsolutePath(); 6298 } 6299 } else if (asecApp) { 6300 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6301 .getAbsolutePath(); 6302 } else { 6303 final String apkName = deriveCodePathName(codePath); 6304 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6305 .getAbsolutePath(); 6306 } 6307 6308 info.nativeLibraryRootRequiresIsa = false; 6309 info.nativeLibraryDir = info.nativeLibraryRootDir; 6310 } else { 6311 // Cluster install 6312 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6313 info.nativeLibraryRootRequiresIsa = true; 6314 6315 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6316 getPrimaryInstructionSet(info)).getAbsolutePath(); 6317 6318 if (info.secondaryCpuAbi != null) { 6319 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6320 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6321 } 6322 } 6323 } 6324 6325 /** 6326 * Calculate the abis and roots for a bundled app. These can uniquely 6327 * be determined from the contents of the system partition, i.e whether 6328 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6329 * of this information, and instead assume that the system was built 6330 * sensibly. 6331 */ 6332 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6333 PackageSetting pkgSetting) { 6334 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6335 6336 // If "/system/lib64/apkname" exists, assume that is the per-package 6337 // native library directory to use; otherwise use "/system/lib/apkname". 6338 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6339 setBundledAppAbi(pkg, apkRoot, apkName); 6340 // pkgSetting might be null during rescan following uninstall of updates 6341 // to a bundled app, so accommodate that possibility. The settings in 6342 // that case will be established later from the parsed package. 6343 // 6344 // If the settings aren't null, sync them up with what we've just derived. 6345 // note that apkRoot isn't stored in the package settings. 6346 if (pkgSetting != null) { 6347 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6348 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6349 } 6350 } 6351 6352 /** 6353 * Deduces the ABI of a bundled app and sets the relevant fields on the 6354 * parsed pkg object. 6355 * 6356 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6357 * under which system libraries are installed. 6358 * @param apkName the name of the installed package. 6359 */ 6360 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6361 final File codeFile = new File(pkg.codePath); 6362 6363 final boolean has64BitLibs; 6364 final boolean has32BitLibs; 6365 if (isApkFile(codeFile)) { 6366 // Monolithic install 6367 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6368 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6369 } else { 6370 // Cluster install 6371 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6372 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6373 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6374 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6375 has64BitLibs = (new File(rootDir, isa)).exists(); 6376 } else { 6377 has64BitLibs = false; 6378 } 6379 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6380 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6381 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6382 has32BitLibs = (new File(rootDir, isa)).exists(); 6383 } else { 6384 has32BitLibs = false; 6385 } 6386 } 6387 6388 if (has64BitLibs && !has32BitLibs) { 6389 // The package has 64 bit libs, but not 32 bit libs. Its primary 6390 // ABI should be 64 bit. We can safely assume here that the bundled 6391 // native libraries correspond to the most preferred ABI in the list. 6392 6393 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6394 pkg.applicationInfo.secondaryCpuAbi = null; 6395 } else if (has32BitLibs && !has64BitLibs) { 6396 // The package has 32 bit libs but not 64 bit libs. Its primary 6397 // ABI should be 32 bit. 6398 6399 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6400 pkg.applicationInfo.secondaryCpuAbi = null; 6401 } else if (has32BitLibs && has64BitLibs) { 6402 // The application has both 64 and 32 bit bundled libraries. We check 6403 // here that the app declares multiArch support, and warn if it doesn't. 6404 // 6405 // We will be lenient here and record both ABIs. The primary will be the 6406 // ABI that's higher on the list, i.e, a device that's configured to prefer 6407 // 64 bit apps will see a 64 bit primary ABI, 6408 6409 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6410 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6411 } 6412 6413 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6414 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6415 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6416 } else { 6417 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6418 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6419 } 6420 } else { 6421 pkg.applicationInfo.primaryCpuAbi = null; 6422 pkg.applicationInfo.secondaryCpuAbi = null; 6423 } 6424 } 6425 6426 private void killApplication(String pkgName, int appId, String reason) { 6427 // Request the ActivityManager to kill the process(only for existing packages) 6428 // so that we do not end up in a confused state while the user is still using the older 6429 // version of the application while the new one gets installed. 6430 IActivityManager am = ActivityManagerNative.getDefault(); 6431 if (am != null) { 6432 try { 6433 am.killApplicationWithAppId(pkgName, appId, reason); 6434 } catch (RemoteException e) { 6435 } 6436 } 6437 } 6438 6439 void removePackageLI(PackageSetting ps, boolean chatty) { 6440 if (DEBUG_INSTALL) { 6441 if (chatty) 6442 Log.d(TAG, "Removing package " + ps.name); 6443 } 6444 6445 // writer 6446 synchronized (mPackages) { 6447 mPackages.remove(ps.name); 6448 final PackageParser.Package pkg = ps.pkg; 6449 if (pkg != null) { 6450 cleanPackageDataStructuresLILPw(pkg, chatty); 6451 } 6452 } 6453 } 6454 6455 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6456 if (DEBUG_INSTALL) { 6457 if (chatty) 6458 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6459 } 6460 6461 // writer 6462 synchronized (mPackages) { 6463 mPackages.remove(pkg.applicationInfo.packageName); 6464 cleanPackageDataStructuresLILPw(pkg, chatty); 6465 } 6466 } 6467 6468 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6469 int N = pkg.providers.size(); 6470 StringBuilder r = null; 6471 int i; 6472 for (i=0; i<N; i++) { 6473 PackageParser.Provider p = pkg.providers.get(i); 6474 mProviders.removeProvider(p); 6475 if (p.info.authority == null) { 6476 6477 /* There was another ContentProvider with this authority when 6478 * this app was installed so this authority is null, 6479 * Ignore it as we don't have to unregister the provider. 6480 */ 6481 continue; 6482 } 6483 String names[] = p.info.authority.split(";"); 6484 for (int j = 0; j < names.length; j++) { 6485 if (mProvidersByAuthority.get(names[j]) == p) { 6486 mProvidersByAuthority.remove(names[j]); 6487 if (DEBUG_REMOVE) { 6488 if (chatty) 6489 Log.d(TAG, "Unregistered content provider: " + names[j] 6490 + ", className = " + p.info.name + ", isSyncable = " 6491 + p.info.isSyncable); 6492 } 6493 } 6494 } 6495 if (DEBUG_REMOVE && chatty) { 6496 if (r == null) { 6497 r = new StringBuilder(256); 6498 } else { 6499 r.append(' '); 6500 } 6501 r.append(p.info.name); 6502 } 6503 } 6504 if (r != null) { 6505 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6506 } 6507 6508 N = pkg.services.size(); 6509 r = null; 6510 for (i=0; i<N; i++) { 6511 PackageParser.Service s = pkg.services.get(i); 6512 mServices.removeService(s); 6513 if (chatty) { 6514 if (r == null) { 6515 r = new StringBuilder(256); 6516 } else { 6517 r.append(' '); 6518 } 6519 r.append(s.info.name); 6520 } 6521 } 6522 if (r != null) { 6523 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6524 } 6525 6526 N = pkg.receivers.size(); 6527 r = null; 6528 for (i=0; i<N; i++) { 6529 PackageParser.Activity a = pkg.receivers.get(i); 6530 mReceivers.removeActivity(a, "receiver"); 6531 if (DEBUG_REMOVE && chatty) { 6532 if (r == null) { 6533 r = new StringBuilder(256); 6534 } else { 6535 r.append(' '); 6536 } 6537 r.append(a.info.name); 6538 } 6539 } 6540 if (r != null) { 6541 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6542 } 6543 6544 N = pkg.activities.size(); 6545 r = null; 6546 for (i=0; i<N; i++) { 6547 PackageParser.Activity a = pkg.activities.get(i); 6548 mActivities.removeActivity(a, "activity"); 6549 if (DEBUG_REMOVE && chatty) { 6550 if (r == null) { 6551 r = new StringBuilder(256); 6552 } else { 6553 r.append(' '); 6554 } 6555 r.append(a.info.name); 6556 } 6557 } 6558 if (r != null) { 6559 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6560 } 6561 6562 N = pkg.permissions.size(); 6563 r = null; 6564 for (i=0; i<N; i++) { 6565 PackageParser.Permission p = pkg.permissions.get(i); 6566 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6567 if (bp == null) { 6568 bp = mSettings.mPermissionTrees.get(p.info.name); 6569 } 6570 if (bp != null && bp.perm == p) { 6571 bp.perm = null; 6572 if (DEBUG_REMOVE && chatty) { 6573 if (r == null) { 6574 r = new StringBuilder(256); 6575 } else { 6576 r.append(' '); 6577 } 6578 r.append(p.info.name); 6579 } 6580 } 6581 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6582 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6583 if (appOpPerms != null) { 6584 appOpPerms.remove(pkg.packageName); 6585 } 6586 } 6587 } 6588 if (r != null) { 6589 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6590 } 6591 6592 N = pkg.requestedPermissions.size(); 6593 r = null; 6594 for (i=0; i<N; i++) { 6595 String perm = pkg.requestedPermissions.get(i); 6596 BasePermission bp = mSettings.mPermissions.get(perm); 6597 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6598 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6599 if (appOpPerms != null) { 6600 appOpPerms.remove(pkg.packageName); 6601 if (appOpPerms.isEmpty()) { 6602 mAppOpPermissionPackages.remove(perm); 6603 } 6604 } 6605 } 6606 } 6607 if (r != null) { 6608 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6609 } 6610 6611 N = pkg.instrumentation.size(); 6612 r = null; 6613 for (i=0; i<N; i++) { 6614 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6615 mInstrumentation.remove(a.getComponentName()); 6616 if (DEBUG_REMOVE && chatty) { 6617 if (r == null) { 6618 r = new StringBuilder(256); 6619 } else { 6620 r.append(' '); 6621 } 6622 r.append(a.info.name); 6623 } 6624 } 6625 if (r != null) { 6626 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6627 } 6628 6629 r = null; 6630 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6631 // Only system apps can hold shared libraries. 6632 if (pkg.libraryNames != null) { 6633 for (i=0; i<pkg.libraryNames.size(); i++) { 6634 String name = pkg.libraryNames.get(i); 6635 SharedLibraryEntry cur = mSharedLibraries.get(name); 6636 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6637 mSharedLibraries.remove(name); 6638 if (DEBUG_REMOVE && chatty) { 6639 if (r == null) { 6640 r = new StringBuilder(256); 6641 } else { 6642 r.append(' '); 6643 } 6644 r.append(name); 6645 } 6646 } 6647 } 6648 } 6649 } 6650 if (r != null) { 6651 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6652 } 6653 } 6654 6655 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6656 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6657 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6658 return true; 6659 } 6660 } 6661 return false; 6662 } 6663 6664 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6665 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6666 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6667 6668 private void updatePermissionsLPw(String changingPkg, 6669 PackageParser.Package pkgInfo, int flags) { 6670 // Make sure there are no dangling permission trees. 6671 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6672 while (it.hasNext()) { 6673 final BasePermission bp = it.next(); 6674 if (bp.packageSetting == null) { 6675 // We may not yet have parsed the package, so just see if 6676 // we still know about its settings. 6677 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6678 } 6679 if (bp.packageSetting == null) { 6680 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6681 + " from package " + bp.sourcePackage); 6682 it.remove(); 6683 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6684 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6685 Slog.i(TAG, "Removing old permission tree: " + bp.name 6686 + " from package " + bp.sourcePackage); 6687 flags |= UPDATE_PERMISSIONS_ALL; 6688 it.remove(); 6689 } 6690 } 6691 } 6692 6693 // Make sure all dynamic permissions have been assigned to a package, 6694 // and make sure there are no dangling permissions. 6695 it = mSettings.mPermissions.values().iterator(); 6696 while (it.hasNext()) { 6697 final BasePermission bp = it.next(); 6698 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6699 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6700 + bp.name + " pkg=" + bp.sourcePackage 6701 + " info=" + bp.pendingInfo); 6702 if (bp.packageSetting == null && bp.pendingInfo != null) { 6703 final BasePermission tree = findPermissionTreeLP(bp.name); 6704 if (tree != null && tree.perm != null) { 6705 bp.packageSetting = tree.packageSetting; 6706 bp.perm = new PackageParser.Permission(tree.perm.owner, 6707 new PermissionInfo(bp.pendingInfo)); 6708 bp.perm.info.packageName = tree.perm.info.packageName; 6709 bp.perm.info.name = bp.name; 6710 bp.uid = tree.uid; 6711 } 6712 } 6713 } 6714 if (bp.packageSetting == null) { 6715 // We may not yet have parsed the package, so just see if 6716 // we still know about its settings. 6717 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6718 } 6719 if (bp.packageSetting == null) { 6720 Slog.w(TAG, "Removing dangling permission: " + bp.name 6721 + " from package " + bp.sourcePackage); 6722 it.remove(); 6723 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6724 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6725 Slog.i(TAG, "Removing old permission: " + bp.name 6726 + " from package " + bp.sourcePackage); 6727 flags |= UPDATE_PERMISSIONS_ALL; 6728 it.remove(); 6729 } 6730 } 6731 } 6732 6733 // Now update the permissions for all packages, in particular 6734 // replace the granted permissions of the system packages. 6735 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6736 for (PackageParser.Package pkg : mPackages.values()) { 6737 if (pkg != pkgInfo) { 6738 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6739 changingPkg); 6740 } 6741 } 6742 } 6743 6744 if (pkgInfo != null) { 6745 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6746 } 6747 } 6748 6749 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6750 String packageOfInterest) { 6751 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6752 if (ps == null) { 6753 return; 6754 } 6755 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6756 HashSet<String> origPermissions = gp.grantedPermissions; 6757 boolean changedPermission = false; 6758 6759 if (replace) { 6760 ps.permissionsFixed = false; 6761 if (gp == ps) { 6762 origPermissions = new HashSet<String>(gp.grantedPermissions); 6763 gp.grantedPermissions.clear(); 6764 gp.gids = mGlobalGids; 6765 } 6766 } 6767 6768 if (gp.gids == null) { 6769 gp.gids = mGlobalGids; 6770 } 6771 6772 final int N = pkg.requestedPermissions.size(); 6773 for (int i=0; i<N; i++) { 6774 final String name = pkg.requestedPermissions.get(i); 6775 final boolean required = pkg.requestedPermissionsRequired.get(i); 6776 final BasePermission bp = mSettings.mPermissions.get(name); 6777 if (DEBUG_INSTALL) { 6778 if (gp != ps) { 6779 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6780 } 6781 } 6782 6783 if (bp == null || bp.packageSetting == null) { 6784 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6785 Slog.w(TAG, "Unknown permission " + name 6786 + " in package " + pkg.packageName); 6787 } 6788 continue; 6789 } 6790 6791 final String perm = bp.name; 6792 boolean allowed; 6793 boolean allowedSig = false; 6794 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6795 // Keep track of app op permissions. 6796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6797 if (pkgs == null) { 6798 pkgs = new ArraySet<>(); 6799 mAppOpPermissionPackages.put(bp.name, pkgs); 6800 } 6801 pkgs.add(pkg.packageName); 6802 } 6803 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6804 if (level == PermissionInfo.PROTECTION_NORMAL 6805 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6806 // We grant a normal or dangerous permission if any of the following 6807 // are true: 6808 // 1) The permission is required 6809 // 2) The permission is optional, but was granted in the past 6810 // 3) The permission is optional, but was requested by an 6811 // app in /system (not /data) 6812 // 6813 // Otherwise, reject the permission. 6814 allowed = (required || origPermissions.contains(perm) 6815 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6816 } else if (bp.packageSetting == null) { 6817 // This permission is invalid; skip it. 6818 allowed = false; 6819 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6820 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6821 if (allowed) { 6822 allowedSig = true; 6823 } 6824 } else { 6825 allowed = false; 6826 } 6827 if (DEBUG_INSTALL) { 6828 if (gp != ps) { 6829 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6830 } 6831 } 6832 if (allowed) { 6833 if (!isSystemApp(ps) && ps.permissionsFixed) { 6834 // If this is an existing, non-system package, then 6835 // we can't add any new permissions to it. 6836 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6837 // Except... if this is a permission that was added 6838 // to the platform (note: need to only do this when 6839 // updating the platform). 6840 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6841 } 6842 } 6843 if (allowed) { 6844 if (!gp.grantedPermissions.contains(perm)) { 6845 changedPermission = true; 6846 gp.grantedPermissions.add(perm); 6847 gp.gids = appendInts(gp.gids, bp.gids); 6848 } else if (!ps.haveGids) { 6849 gp.gids = appendInts(gp.gids, bp.gids); 6850 } 6851 } else { 6852 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6853 Slog.w(TAG, "Not granting permission " + perm 6854 + " to package " + pkg.packageName 6855 + " because it was previously installed without"); 6856 } 6857 } 6858 } else { 6859 if (gp.grantedPermissions.remove(perm)) { 6860 changedPermission = true; 6861 gp.gids = removeInts(gp.gids, bp.gids); 6862 Slog.i(TAG, "Un-granting permission " + perm 6863 + " from package " + pkg.packageName 6864 + " (protectionLevel=" + bp.protectionLevel 6865 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6866 + ")"); 6867 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6868 // Don't print warning for app op permissions, since it is fine for them 6869 // not to be granted, there is a UI for the user to decide. 6870 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6871 Slog.w(TAG, "Not granting permission " + perm 6872 + " to package " + pkg.packageName 6873 + " (protectionLevel=" + bp.protectionLevel 6874 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6875 + ")"); 6876 } 6877 } 6878 } 6879 } 6880 6881 if ((changedPermission || replace) && !ps.permissionsFixed && 6882 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6883 // This is the first that we have heard about this package, so the 6884 // permissions we have now selected are fixed until explicitly 6885 // changed. 6886 ps.permissionsFixed = true; 6887 } 6888 ps.haveGids = true; 6889 } 6890 6891 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6892 boolean allowed = false; 6893 final int NP = PackageParser.NEW_PERMISSIONS.length; 6894 for (int ip=0; ip<NP; ip++) { 6895 final PackageParser.NewPermissionInfo npi 6896 = PackageParser.NEW_PERMISSIONS[ip]; 6897 if (npi.name.equals(perm) 6898 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6899 allowed = true; 6900 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6901 + pkg.packageName); 6902 break; 6903 } 6904 } 6905 return allowed; 6906 } 6907 6908 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6909 BasePermission bp, HashSet<String> origPermissions) { 6910 boolean allowed; 6911 allowed = (compareSignatures( 6912 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6913 == PackageManager.SIGNATURE_MATCH) 6914 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6915 == PackageManager.SIGNATURE_MATCH); 6916 if (!allowed && (bp.protectionLevel 6917 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6918 if (isSystemApp(pkg)) { 6919 // For updated system applications, a system permission 6920 // is granted only if it had been defined by the original application. 6921 if (isUpdatedSystemApp(pkg)) { 6922 final PackageSetting sysPs = mSettings 6923 .getDisabledSystemPkgLPr(pkg.packageName); 6924 final GrantedPermissions origGp = sysPs.sharedUser != null 6925 ? sysPs.sharedUser : sysPs; 6926 6927 if (origGp.grantedPermissions.contains(perm)) { 6928 // If the original was granted this permission, we take 6929 // that grant decision as read and propagate it to the 6930 // update. 6931 allowed = true; 6932 } else { 6933 // The system apk may have been updated with an older 6934 // version of the one on the data partition, but which 6935 // granted a new system permission that it didn't have 6936 // before. In this case we do want to allow the app to 6937 // now get the new permission if the ancestral apk is 6938 // privileged to get it. 6939 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6940 for (int j=0; 6941 j<sysPs.pkg.requestedPermissions.size(); j++) { 6942 if (perm.equals( 6943 sysPs.pkg.requestedPermissions.get(j))) { 6944 allowed = true; 6945 break; 6946 } 6947 } 6948 } 6949 } 6950 } else { 6951 allowed = isPrivilegedApp(pkg); 6952 } 6953 } 6954 } 6955 if (!allowed && (bp.protectionLevel 6956 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6957 // For development permissions, a development permission 6958 // is granted only if it was already granted. 6959 allowed = origPermissions.contains(perm); 6960 } 6961 return allowed; 6962 } 6963 6964 final class ActivityIntentResolver 6965 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6966 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6967 boolean defaultOnly, int userId) { 6968 if (!sUserManager.exists(userId)) return null; 6969 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6970 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6971 } 6972 6973 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6974 int userId) { 6975 if (!sUserManager.exists(userId)) return null; 6976 mFlags = flags; 6977 return super.queryIntent(intent, resolvedType, 6978 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6979 } 6980 6981 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6982 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6983 if (!sUserManager.exists(userId)) return null; 6984 if (packageActivities == null) { 6985 return null; 6986 } 6987 mFlags = flags; 6988 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6989 final int N = packageActivities.size(); 6990 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6991 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6992 6993 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6994 for (int i = 0; i < N; ++i) { 6995 intentFilters = packageActivities.get(i).intents; 6996 if (intentFilters != null && intentFilters.size() > 0) { 6997 PackageParser.ActivityIntentInfo[] array = 6998 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6999 intentFilters.toArray(array); 7000 listCut.add(array); 7001 } 7002 } 7003 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7004 } 7005 7006 public final void addActivity(PackageParser.Activity a, String type) { 7007 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7008 mActivities.put(a.getComponentName(), a); 7009 if (DEBUG_SHOW_INFO) 7010 Log.v( 7011 TAG, " " + type + " " + 7012 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7013 if (DEBUG_SHOW_INFO) 7014 Log.v(TAG, " Class=" + a.info.name); 7015 final int NI = a.intents.size(); 7016 for (int j=0; j<NI; j++) { 7017 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7018 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7019 intent.setPriority(0); 7020 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7021 + a.className + " with priority > 0, forcing to 0"); 7022 } 7023 if (DEBUG_SHOW_INFO) { 7024 Log.v(TAG, " IntentFilter:"); 7025 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7026 } 7027 if (!intent.debugCheck()) { 7028 Log.w(TAG, "==> For Activity " + a.info.name); 7029 } 7030 addFilter(intent); 7031 } 7032 } 7033 7034 public final void removeActivity(PackageParser.Activity a, String type) { 7035 mActivities.remove(a.getComponentName()); 7036 if (DEBUG_SHOW_INFO) { 7037 Log.v(TAG, " " + type + " " 7038 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7039 : a.info.name) + ":"); 7040 Log.v(TAG, " Class=" + a.info.name); 7041 } 7042 final int NI = a.intents.size(); 7043 for (int j=0; j<NI; j++) { 7044 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7045 if (DEBUG_SHOW_INFO) { 7046 Log.v(TAG, " IntentFilter:"); 7047 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7048 } 7049 removeFilter(intent); 7050 } 7051 } 7052 7053 @Override 7054 protected boolean allowFilterResult( 7055 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7056 ActivityInfo filterAi = filter.activity.info; 7057 for (int i=dest.size()-1; i>=0; i--) { 7058 ActivityInfo destAi = dest.get(i).activityInfo; 7059 if (destAi.name == filterAi.name 7060 && destAi.packageName == filterAi.packageName) { 7061 return false; 7062 } 7063 } 7064 return true; 7065 } 7066 7067 @Override 7068 protected ActivityIntentInfo[] newArray(int size) { 7069 return new ActivityIntentInfo[size]; 7070 } 7071 7072 @Override 7073 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7074 if (!sUserManager.exists(userId)) return true; 7075 PackageParser.Package p = filter.activity.owner; 7076 if (p != null) { 7077 PackageSetting ps = (PackageSetting)p.mExtras; 7078 if (ps != null) { 7079 // System apps are never considered stopped for purposes of 7080 // filtering, because there may be no way for the user to 7081 // actually re-launch them. 7082 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7083 && ps.getStopped(userId); 7084 } 7085 } 7086 return false; 7087 } 7088 7089 @Override 7090 protected boolean isPackageForFilter(String packageName, 7091 PackageParser.ActivityIntentInfo info) { 7092 return packageName.equals(info.activity.owner.packageName); 7093 } 7094 7095 @Override 7096 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7097 int match, int userId) { 7098 if (!sUserManager.exists(userId)) return null; 7099 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7100 return null; 7101 } 7102 final PackageParser.Activity activity = info.activity; 7103 if (mSafeMode && (activity.info.applicationInfo.flags 7104 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7105 return null; 7106 } 7107 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7108 if (ps == null) { 7109 return null; 7110 } 7111 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7112 ps.readUserState(userId), userId); 7113 if (ai == null) { 7114 return null; 7115 } 7116 final ResolveInfo res = new ResolveInfo(); 7117 res.activityInfo = ai; 7118 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7119 res.filter = info; 7120 } 7121 res.priority = info.getPriority(); 7122 res.preferredOrder = activity.owner.mPreferredOrder; 7123 //System.out.println("Result: " + res.activityInfo.className + 7124 // " = " + res.priority); 7125 res.match = match; 7126 res.isDefault = info.hasDefault; 7127 res.labelRes = info.labelRes; 7128 res.nonLocalizedLabel = info.nonLocalizedLabel; 7129 if (userNeedsBadging(userId)) { 7130 res.noResourceId = true; 7131 } else { 7132 res.icon = info.icon; 7133 } 7134 res.system = isSystemApp(res.activityInfo.applicationInfo); 7135 return res; 7136 } 7137 7138 @Override 7139 protected void sortResults(List<ResolveInfo> results) { 7140 Collections.sort(results, mResolvePrioritySorter); 7141 } 7142 7143 @Override 7144 protected void dumpFilter(PrintWriter out, String prefix, 7145 PackageParser.ActivityIntentInfo filter) { 7146 out.print(prefix); out.print( 7147 Integer.toHexString(System.identityHashCode(filter.activity))); 7148 out.print(' '); 7149 filter.activity.printComponentShortName(out); 7150 out.print(" filter "); 7151 out.println(Integer.toHexString(System.identityHashCode(filter))); 7152 } 7153 7154// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7155// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7156// final List<ResolveInfo> retList = Lists.newArrayList(); 7157// while (i.hasNext()) { 7158// final ResolveInfo resolveInfo = i.next(); 7159// if (isEnabledLP(resolveInfo.activityInfo)) { 7160// retList.add(resolveInfo); 7161// } 7162// } 7163// return retList; 7164// } 7165 7166 // Keys are String (activity class name), values are Activity. 7167 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7168 = new HashMap<ComponentName, PackageParser.Activity>(); 7169 private int mFlags; 7170 } 7171 7172 private final class ServiceIntentResolver 7173 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7174 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7175 boolean defaultOnly, int userId) { 7176 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7177 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7178 } 7179 7180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7181 int userId) { 7182 if (!sUserManager.exists(userId)) return null; 7183 mFlags = flags; 7184 return super.queryIntent(intent, resolvedType, 7185 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7186 } 7187 7188 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7189 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7190 if (!sUserManager.exists(userId)) return null; 7191 if (packageServices == null) { 7192 return null; 7193 } 7194 mFlags = flags; 7195 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7196 final int N = packageServices.size(); 7197 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7198 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7199 7200 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7201 for (int i = 0; i < N; ++i) { 7202 intentFilters = packageServices.get(i).intents; 7203 if (intentFilters != null && intentFilters.size() > 0) { 7204 PackageParser.ServiceIntentInfo[] array = 7205 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7206 intentFilters.toArray(array); 7207 listCut.add(array); 7208 } 7209 } 7210 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7211 } 7212 7213 public final void addService(PackageParser.Service s) { 7214 mServices.put(s.getComponentName(), s); 7215 if (DEBUG_SHOW_INFO) { 7216 Log.v(TAG, " " 7217 + (s.info.nonLocalizedLabel != null 7218 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7219 Log.v(TAG, " Class=" + s.info.name); 7220 } 7221 final int NI = s.intents.size(); 7222 int j; 7223 for (j=0; j<NI; j++) { 7224 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7225 if (DEBUG_SHOW_INFO) { 7226 Log.v(TAG, " IntentFilter:"); 7227 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7228 } 7229 if (!intent.debugCheck()) { 7230 Log.w(TAG, "==> For Service " + s.info.name); 7231 } 7232 addFilter(intent); 7233 } 7234 } 7235 7236 public final void removeService(PackageParser.Service s) { 7237 mServices.remove(s.getComponentName()); 7238 if (DEBUG_SHOW_INFO) { 7239 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7240 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7241 Log.v(TAG, " Class=" + s.info.name); 7242 } 7243 final int NI = s.intents.size(); 7244 int j; 7245 for (j=0; j<NI; j++) { 7246 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7247 if (DEBUG_SHOW_INFO) { 7248 Log.v(TAG, " IntentFilter:"); 7249 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7250 } 7251 removeFilter(intent); 7252 } 7253 } 7254 7255 @Override 7256 protected boolean allowFilterResult( 7257 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7258 ServiceInfo filterSi = filter.service.info; 7259 for (int i=dest.size()-1; i>=0; i--) { 7260 ServiceInfo destAi = dest.get(i).serviceInfo; 7261 if (destAi.name == filterSi.name 7262 && destAi.packageName == filterSi.packageName) { 7263 return false; 7264 } 7265 } 7266 return true; 7267 } 7268 7269 @Override 7270 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7271 return new PackageParser.ServiceIntentInfo[size]; 7272 } 7273 7274 @Override 7275 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7276 if (!sUserManager.exists(userId)) return true; 7277 PackageParser.Package p = filter.service.owner; 7278 if (p != null) { 7279 PackageSetting ps = (PackageSetting)p.mExtras; 7280 if (ps != null) { 7281 // System apps are never considered stopped for purposes of 7282 // filtering, because there may be no way for the user to 7283 // actually re-launch them. 7284 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7285 && ps.getStopped(userId); 7286 } 7287 } 7288 return false; 7289 } 7290 7291 @Override 7292 protected boolean isPackageForFilter(String packageName, 7293 PackageParser.ServiceIntentInfo info) { 7294 return packageName.equals(info.service.owner.packageName); 7295 } 7296 7297 @Override 7298 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7299 int match, int userId) { 7300 if (!sUserManager.exists(userId)) return null; 7301 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7302 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7303 return null; 7304 } 7305 final PackageParser.Service service = info.service; 7306 if (mSafeMode && (service.info.applicationInfo.flags 7307 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7308 return null; 7309 } 7310 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7311 if (ps == null) { 7312 return null; 7313 } 7314 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7315 ps.readUserState(userId), userId); 7316 if (si == null) { 7317 return null; 7318 } 7319 final ResolveInfo res = new ResolveInfo(); 7320 res.serviceInfo = si; 7321 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7322 res.filter = filter; 7323 } 7324 res.priority = info.getPriority(); 7325 res.preferredOrder = service.owner.mPreferredOrder; 7326 //System.out.println("Result: " + res.activityInfo.className + 7327 // " = " + res.priority); 7328 res.match = match; 7329 res.isDefault = info.hasDefault; 7330 res.labelRes = info.labelRes; 7331 res.nonLocalizedLabel = info.nonLocalizedLabel; 7332 res.icon = info.icon; 7333 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7334 return res; 7335 } 7336 7337 @Override 7338 protected void sortResults(List<ResolveInfo> results) { 7339 Collections.sort(results, mResolvePrioritySorter); 7340 } 7341 7342 @Override 7343 protected void dumpFilter(PrintWriter out, String prefix, 7344 PackageParser.ServiceIntentInfo filter) { 7345 out.print(prefix); out.print( 7346 Integer.toHexString(System.identityHashCode(filter.service))); 7347 out.print(' '); 7348 filter.service.printComponentShortName(out); 7349 out.print(" filter "); 7350 out.println(Integer.toHexString(System.identityHashCode(filter))); 7351 } 7352 7353// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7354// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7355// final List<ResolveInfo> retList = Lists.newArrayList(); 7356// while (i.hasNext()) { 7357// final ResolveInfo resolveInfo = (ResolveInfo) i; 7358// if (isEnabledLP(resolveInfo.serviceInfo)) { 7359// retList.add(resolveInfo); 7360// } 7361// } 7362// return retList; 7363// } 7364 7365 // Keys are String (activity class name), values are Activity. 7366 private final HashMap<ComponentName, PackageParser.Service> mServices 7367 = new HashMap<ComponentName, PackageParser.Service>(); 7368 private int mFlags; 7369 }; 7370 7371 private final class ProviderIntentResolver 7372 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7373 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7374 boolean defaultOnly, int userId) { 7375 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7376 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7377 } 7378 7379 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7380 int userId) { 7381 if (!sUserManager.exists(userId)) 7382 return null; 7383 mFlags = flags; 7384 return super.queryIntent(intent, resolvedType, 7385 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7386 } 7387 7388 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7389 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7390 if (!sUserManager.exists(userId)) 7391 return null; 7392 if (packageProviders == null) { 7393 return null; 7394 } 7395 mFlags = flags; 7396 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7397 final int N = packageProviders.size(); 7398 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7399 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7400 7401 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7402 for (int i = 0; i < N; ++i) { 7403 intentFilters = packageProviders.get(i).intents; 7404 if (intentFilters != null && intentFilters.size() > 0) { 7405 PackageParser.ProviderIntentInfo[] array = 7406 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7407 intentFilters.toArray(array); 7408 listCut.add(array); 7409 } 7410 } 7411 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7412 } 7413 7414 public final void addProvider(PackageParser.Provider p) { 7415 if (mProviders.containsKey(p.getComponentName())) { 7416 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7417 return; 7418 } 7419 7420 mProviders.put(p.getComponentName(), p); 7421 if (DEBUG_SHOW_INFO) { 7422 Log.v(TAG, " " 7423 + (p.info.nonLocalizedLabel != null 7424 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7425 Log.v(TAG, " Class=" + p.info.name); 7426 } 7427 final int NI = p.intents.size(); 7428 int j; 7429 for (j = 0; j < NI; j++) { 7430 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7431 if (DEBUG_SHOW_INFO) { 7432 Log.v(TAG, " IntentFilter:"); 7433 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7434 } 7435 if (!intent.debugCheck()) { 7436 Log.w(TAG, "==> For Provider " + p.info.name); 7437 } 7438 addFilter(intent); 7439 } 7440 } 7441 7442 public final void removeProvider(PackageParser.Provider p) { 7443 mProviders.remove(p.getComponentName()); 7444 if (DEBUG_SHOW_INFO) { 7445 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7446 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7447 Log.v(TAG, " Class=" + p.info.name); 7448 } 7449 final int NI = p.intents.size(); 7450 int j; 7451 for (j = 0; j < NI; j++) { 7452 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7453 if (DEBUG_SHOW_INFO) { 7454 Log.v(TAG, " IntentFilter:"); 7455 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7456 } 7457 removeFilter(intent); 7458 } 7459 } 7460 7461 @Override 7462 protected boolean allowFilterResult( 7463 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7464 ProviderInfo filterPi = filter.provider.info; 7465 for (int i = dest.size() - 1; i >= 0; i--) { 7466 ProviderInfo destPi = dest.get(i).providerInfo; 7467 if (destPi.name == filterPi.name 7468 && destPi.packageName == filterPi.packageName) { 7469 return false; 7470 } 7471 } 7472 return true; 7473 } 7474 7475 @Override 7476 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7477 return new PackageParser.ProviderIntentInfo[size]; 7478 } 7479 7480 @Override 7481 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7482 if (!sUserManager.exists(userId)) 7483 return true; 7484 PackageParser.Package p = filter.provider.owner; 7485 if (p != null) { 7486 PackageSetting ps = (PackageSetting) p.mExtras; 7487 if (ps != null) { 7488 // System apps are never considered stopped for purposes of 7489 // filtering, because there may be no way for the user to 7490 // actually re-launch them. 7491 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7492 && ps.getStopped(userId); 7493 } 7494 } 7495 return false; 7496 } 7497 7498 @Override 7499 protected boolean isPackageForFilter(String packageName, 7500 PackageParser.ProviderIntentInfo info) { 7501 return packageName.equals(info.provider.owner.packageName); 7502 } 7503 7504 @Override 7505 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7506 int match, int userId) { 7507 if (!sUserManager.exists(userId)) 7508 return null; 7509 final PackageParser.ProviderIntentInfo info = filter; 7510 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7511 return null; 7512 } 7513 final PackageParser.Provider provider = info.provider; 7514 if (mSafeMode && (provider.info.applicationInfo.flags 7515 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7516 return null; 7517 } 7518 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7519 if (ps == null) { 7520 return null; 7521 } 7522 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7523 ps.readUserState(userId), userId); 7524 if (pi == null) { 7525 return null; 7526 } 7527 final ResolveInfo res = new ResolveInfo(); 7528 res.providerInfo = pi; 7529 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7530 res.filter = filter; 7531 } 7532 res.priority = info.getPriority(); 7533 res.preferredOrder = provider.owner.mPreferredOrder; 7534 res.match = match; 7535 res.isDefault = info.hasDefault; 7536 res.labelRes = info.labelRes; 7537 res.nonLocalizedLabel = info.nonLocalizedLabel; 7538 res.icon = info.icon; 7539 res.system = isSystemApp(res.providerInfo.applicationInfo); 7540 return res; 7541 } 7542 7543 @Override 7544 protected void sortResults(List<ResolveInfo> results) { 7545 Collections.sort(results, mResolvePrioritySorter); 7546 } 7547 7548 @Override 7549 protected void dumpFilter(PrintWriter out, String prefix, 7550 PackageParser.ProviderIntentInfo filter) { 7551 out.print(prefix); 7552 out.print( 7553 Integer.toHexString(System.identityHashCode(filter.provider))); 7554 out.print(' '); 7555 filter.provider.printComponentShortName(out); 7556 out.print(" filter "); 7557 out.println(Integer.toHexString(System.identityHashCode(filter))); 7558 } 7559 7560 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7561 = new HashMap<ComponentName, PackageParser.Provider>(); 7562 private int mFlags; 7563 }; 7564 7565 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7566 new Comparator<ResolveInfo>() { 7567 public int compare(ResolveInfo r1, ResolveInfo r2) { 7568 int v1 = r1.priority; 7569 int v2 = r2.priority; 7570 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7571 if (v1 != v2) { 7572 return (v1 > v2) ? -1 : 1; 7573 } 7574 v1 = r1.preferredOrder; 7575 v2 = r2.preferredOrder; 7576 if (v1 != v2) { 7577 return (v1 > v2) ? -1 : 1; 7578 } 7579 if (r1.isDefault != r2.isDefault) { 7580 return r1.isDefault ? -1 : 1; 7581 } 7582 v1 = r1.match; 7583 v2 = r2.match; 7584 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7585 if (v1 != v2) { 7586 return (v1 > v2) ? -1 : 1; 7587 } 7588 if (r1.system != r2.system) { 7589 return r1.system ? -1 : 1; 7590 } 7591 return 0; 7592 } 7593 }; 7594 7595 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7596 new Comparator<ProviderInfo>() { 7597 public int compare(ProviderInfo p1, ProviderInfo p2) { 7598 final int v1 = p1.initOrder; 7599 final int v2 = p2.initOrder; 7600 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7601 } 7602 }; 7603 7604 static final void sendPackageBroadcast(String action, String pkg, 7605 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7606 int[] userIds) { 7607 IActivityManager am = ActivityManagerNative.getDefault(); 7608 if (am != null) { 7609 try { 7610 if (userIds == null) { 7611 userIds = am.getRunningUserIds(); 7612 } 7613 for (int id : userIds) { 7614 final Intent intent = new Intent(action, 7615 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7616 if (extras != null) { 7617 intent.putExtras(extras); 7618 } 7619 if (targetPkg != null) { 7620 intent.setPackage(targetPkg); 7621 } 7622 // Modify the UID when posting to other users 7623 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7624 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7625 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7626 intent.putExtra(Intent.EXTRA_UID, uid); 7627 } 7628 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7629 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7630 if (DEBUG_BROADCASTS) { 7631 RuntimeException here = new RuntimeException("here"); 7632 here.fillInStackTrace(); 7633 Slog.d(TAG, "Sending to user " + id + ": " 7634 + intent.toShortString(false, true, false, false) 7635 + " " + intent.getExtras(), here); 7636 } 7637 am.broadcastIntent(null, intent, null, finishedReceiver, 7638 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7639 finishedReceiver != null, false, id); 7640 } 7641 } catch (RemoteException ex) { 7642 } 7643 } 7644 } 7645 7646 /** 7647 * Check if the external storage media is available. This is true if there 7648 * is a mounted external storage medium or if the external storage is 7649 * emulated. 7650 */ 7651 private boolean isExternalMediaAvailable() { 7652 return mMediaMounted || Environment.isExternalStorageEmulated(); 7653 } 7654 7655 @Override 7656 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7657 // writer 7658 synchronized (mPackages) { 7659 if (!isExternalMediaAvailable()) { 7660 // If the external storage is no longer mounted at this point, 7661 // the caller may not have been able to delete all of this 7662 // packages files and can not delete any more. Bail. 7663 return null; 7664 } 7665 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7666 if (lastPackage != null) { 7667 pkgs.remove(lastPackage); 7668 } 7669 if (pkgs.size() > 0) { 7670 return pkgs.get(0); 7671 } 7672 } 7673 return null; 7674 } 7675 7676 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7677 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7678 userId, andCode ? 1 : 0, packageName); 7679 if (mSystemReady) { 7680 msg.sendToTarget(); 7681 } else { 7682 if (mPostSystemReadyMessages == null) { 7683 mPostSystemReadyMessages = new ArrayList<>(); 7684 } 7685 mPostSystemReadyMessages.add(msg); 7686 } 7687 } 7688 7689 void startCleaningPackages() { 7690 // reader 7691 synchronized (mPackages) { 7692 if (!isExternalMediaAvailable()) { 7693 return; 7694 } 7695 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7696 return; 7697 } 7698 } 7699 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7700 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7701 IActivityManager am = ActivityManagerNative.getDefault(); 7702 if (am != null) { 7703 try { 7704 am.startService(null, intent, null, UserHandle.USER_OWNER); 7705 } catch (RemoteException e) { 7706 } 7707 } 7708 } 7709 7710 @Override 7711 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7712 int installFlags, String installerPackageName, VerificationParams verificationParams, 7713 String packageAbiOverride) { 7714 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7715 packageAbiOverride, UserHandle.getCallingUserId()); 7716 } 7717 7718 @Override 7719 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7720 int installFlags, String installerPackageName, VerificationParams verificationParams, 7721 String packageAbiOverride, int userId) { 7722 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7723 7724 final int callingUid = Binder.getCallingUid(); 7725 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7726 7727 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7728 try { 7729 if (observer != null) { 7730 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7731 } 7732 } catch (RemoteException re) { 7733 } 7734 return; 7735 } 7736 7737 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7738 installFlags |= PackageManager.INSTALL_FROM_ADB; 7739 7740 } else { 7741 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7742 // about installerPackageName. 7743 7744 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7745 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7746 } 7747 7748 UserHandle user; 7749 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7750 user = UserHandle.ALL; 7751 } else { 7752 user = new UserHandle(userId); 7753 } 7754 7755 verificationParams.setInstallerUid(callingUid); 7756 7757 final File originFile = new File(originPath); 7758 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7759 7760 final Message msg = mHandler.obtainMessage(INIT_COPY); 7761 msg.obj = new InstallParams(origin, observer, installFlags, 7762 installerPackageName, verificationParams, user, packageAbiOverride); 7763 mHandler.sendMessage(msg); 7764 } 7765 7766 void installStage(String packageName, File stagedDir, String stagedCid, 7767 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7768 String installerPackageName, int installerUid, UserHandle user) { 7769 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7770 params.referrerUri, installerUid, null); 7771 7772 final OriginInfo origin; 7773 if (stagedDir != null) { 7774 origin = OriginInfo.fromStagedFile(stagedDir); 7775 } else { 7776 origin = OriginInfo.fromStagedContainer(stagedCid); 7777 } 7778 7779 final Message msg = mHandler.obtainMessage(INIT_COPY); 7780 msg.obj = new InstallParams(origin, observer, params.installFlags, 7781 installerPackageName, verifParams, user, params.abiOverride); 7782 mHandler.sendMessage(msg); 7783 } 7784 7785 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7786 Bundle extras = new Bundle(1); 7787 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7788 7789 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7790 packageName, extras, null, null, new int[] {userId}); 7791 try { 7792 IActivityManager am = ActivityManagerNative.getDefault(); 7793 final boolean isSystem = 7794 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7795 if (isSystem && am.isUserRunning(userId, false)) { 7796 // The just-installed/enabled app is bundled on the system, so presumed 7797 // to be able to run automatically without needing an explicit launch. 7798 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7799 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7800 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7801 .setPackage(packageName); 7802 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7803 android.app.AppOpsManager.OP_NONE, false, false, userId); 7804 } 7805 } catch (RemoteException e) { 7806 // shouldn't happen 7807 Slog.w(TAG, "Unable to bootstrap installed package", e); 7808 } 7809 } 7810 7811 @Override 7812 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7813 int userId) { 7814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7815 PackageSetting pkgSetting; 7816 final int uid = Binder.getCallingUid(); 7817 enforceCrossUserPermission(uid, userId, true, true, 7818 "setApplicationHiddenSetting for user " + userId); 7819 7820 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7821 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7822 return false; 7823 } 7824 7825 long callingId = Binder.clearCallingIdentity(); 7826 try { 7827 boolean sendAdded = false; 7828 boolean sendRemoved = false; 7829 // writer 7830 synchronized (mPackages) { 7831 pkgSetting = mSettings.mPackages.get(packageName); 7832 if (pkgSetting == null) { 7833 return false; 7834 } 7835 if (pkgSetting.getHidden(userId) != hidden) { 7836 pkgSetting.setHidden(hidden, userId); 7837 mSettings.writePackageRestrictionsLPr(userId); 7838 if (hidden) { 7839 sendRemoved = true; 7840 } else { 7841 sendAdded = true; 7842 } 7843 } 7844 } 7845 if (sendAdded) { 7846 sendPackageAddedForUser(packageName, pkgSetting, userId); 7847 return true; 7848 } 7849 if (sendRemoved) { 7850 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7851 "hiding pkg"); 7852 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7853 } 7854 } finally { 7855 Binder.restoreCallingIdentity(callingId); 7856 } 7857 return false; 7858 } 7859 7860 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7861 int userId) { 7862 final PackageRemovedInfo info = new PackageRemovedInfo(); 7863 info.removedPackage = packageName; 7864 info.removedUsers = new int[] {userId}; 7865 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7866 info.sendBroadcast(false, false, false); 7867 } 7868 7869 /** 7870 * Returns true if application is not found or there was an error. Otherwise it returns 7871 * the hidden state of the package for the given user. 7872 */ 7873 @Override 7874 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7875 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7876 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7877 false, "getApplicationHidden for user " + userId); 7878 PackageSetting pkgSetting; 7879 long callingId = Binder.clearCallingIdentity(); 7880 try { 7881 // writer 7882 synchronized (mPackages) { 7883 pkgSetting = mSettings.mPackages.get(packageName); 7884 if (pkgSetting == null) { 7885 return true; 7886 } 7887 return pkgSetting.getHidden(userId); 7888 } 7889 } finally { 7890 Binder.restoreCallingIdentity(callingId); 7891 } 7892 } 7893 7894 /** 7895 * @hide 7896 */ 7897 @Override 7898 public int installExistingPackageAsUser(String packageName, int userId) { 7899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7900 null); 7901 PackageSetting pkgSetting; 7902 final int uid = Binder.getCallingUid(); 7903 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 7904 + userId); 7905 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7906 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7907 } 7908 7909 long callingId = Binder.clearCallingIdentity(); 7910 try { 7911 boolean sendAdded = false; 7912 Bundle extras = new Bundle(1); 7913 7914 // writer 7915 synchronized (mPackages) { 7916 pkgSetting = mSettings.mPackages.get(packageName); 7917 if (pkgSetting == null) { 7918 return PackageManager.INSTALL_FAILED_INVALID_URI; 7919 } 7920 if (!pkgSetting.getInstalled(userId)) { 7921 pkgSetting.setInstalled(true, userId); 7922 pkgSetting.setHidden(false, userId); 7923 mSettings.writePackageRestrictionsLPr(userId); 7924 sendAdded = true; 7925 } 7926 } 7927 7928 if (sendAdded) { 7929 sendPackageAddedForUser(packageName, pkgSetting, userId); 7930 } 7931 } finally { 7932 Binder.restoreCallingIdentity(callingId); 7933 } 7934 7935 return PackageManager.INSTALL_SUCCEEDED; 7936 } 7937 7938 boolean isUserRestricted(int userId, String restrictionKey) { 7939 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7940 if (restrictions.getBoolean(restrictionKey, false)) { 7941 Log.w(TAG, "User is restricted: " + restrictionKey); 7942 return true; 7943 } 7944 return false; 7945 } 7946 7947 @Override 7948 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7949 mContext.enforceCallingOrSelfPermission( 7950 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7951 "Only package verification agents can verify applications"); 7952 7953 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7954 final PackageVerificationResponse response = new PackageVerificationResponse( 7955 verificationCode, Binder.getCallingUid()); 7956 msg.arg1 = id; 7957 msg.obj = response; 7958 mHandler.sendMessage(msg); 7959 } 7960 7961 @Override 7962 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7963 long millisecondsToDelay) { 7964 mContext.enforceCallingOrSelfPermission( 7965 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7966 "Only package verification agents can extend verification timeouts"); 7967 7968 final PackageVerificationState state = mPendingVerification.get(id); 7969 final PackageVerificationResponse response = new PackageVerificationResponse( 7970 verificationCodeAtTimeout, Binder.getCallingUid()); 7971 7972 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7973 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7974 } 7975 if (millisecondsToDelay < 0) { 7976 millisecondsToDelay = 0; 7977 } 7978 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7979 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7980 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7981 } 7982 7983 if ((state != null) && !state.timeoutExtended()) { 7984 state.extendTimeout(); 7985 7986 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7987 msg.arg1 = id; 7988 msg.obj = response; 7989 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7990 } 7991 } 7992 7993 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7994 int verificationCode, UserHandle user) { 7995 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7996 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7997 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7998 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7999 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8000 8001 mContext.sendBroadcastAsUser(intent, user, 8002 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8003 } 8004 8005 private ComponentName matchComponentForVerifier(String packageName, 8006 List<ResolveInfo> receivers) { 8007 ActivityInfo targetReceiver = null; 8008 8009 final int NR = receivers.size(); 8010 for (int i = 0; i < NR; i++) { 8011 final ResolveInfo info = receivers.get(i); 8012 if (info.activityInfo == null) { 8013 continue; 8014 } 8015 8016 if (packageName.equals(info.activityInfo.packageName)) { 8017 targetReceiver = info.activityInfo; 8018 break; 8019 } 8020 } 8021 8022 if (targetReceiver == null) { 8023 return null; 8024 } 8025 8026 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8027 } 8028 8029 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8030 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8031 if (pkgInfo.verifiers.length == 0) { 8032 return null; 8033 } 8034 8035 final int N = pkgInfo.verifiers.length; 8036 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8037 for (int i = 0; i < N; i++) { 8038 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8039 8040 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8041 receivers); 8042 if (comp == null) { 8043 continue; 8044 } 8045 8046 final int verifierUid = getUidForVerifier(verifierInfo); 8047 if (verifierUid == -1) { 8048 continue; 8049 } 8050 8051 if (DEBUG_VERIFY) { 8052 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8053 + " with the correct signature"); 8054 } 8055 sufficientVerifiers.add(comp); 8056 verificationState.addSufficientVerifier(verifierUid); 8057 } 8058 8059 return sufficientVerifiers; 8060 } 8061 8062 private int getUidForVerifier(VerifierInfo verifierInfo) { 8063 synchronized (mPackages) { 8064 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8065 if (pkg == null) { 8066 return -1; 8067 } else if (pkg.mSignatures.length != 1) { 8068 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8069 + " has more than one signature; ignoring"); 8070 return -1; 8071 } 8072 8073 /* 8074 * If the public key of the package's signature does not match 8075 * our expected public key, then this is a different package and 8076 * we should skip. 8077 */ 8078 8079 final byte[] expectedPublicKey; 8080 try { 8081 final Signature verifierSig = pkg.mSignatures[0]; 8082 final PublicKey publicKey = verifierSig.getPublicKey(); 8083 expectedPublicKey = publicKey.getEncoded(); 8084 } catch (CertificateException e) { 8085 return -1; 8086 } 8087 8088 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8089 8090 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8091 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8092 + " does not have the expected public key; ignoring"); 8093 return -1; 8094 } 8095 8096 return pkg.applicationInfo.uid; 8097 } 8098 } 8099 8100 @Override 8101 public void finishPackageInstall(int token) { 8102 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8103 8104 if (DEBUG_INSTALL) { 8105 Slog.v(TAG, "BM finishing package install for " + token); 8106 } 8107 8108 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8109 mHandler.sendMessage(msg); 8110 } 8111 8112 /** 8113 * Get the verification agent timeout. 8114 * 8115 * @return verification timeout in milliseconds 8116 */ 8117 private long getVerificationTimeout() { 8118 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8119 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8120 DEFAULT_VERIFICATION_TIMEOUT); 8121 } 8122 8123 /** 8124 * Get the default verification agent response code. 8125 * 8126 * @return default verification response code 8127 */ 8128 private int getDefaultVerificationResponse() { 8129 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8130 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8131 DEFAULT_VERIFICATION_RESPONSE); 8132 } 8133 8134 /** 8135 * Check whether or not package verification has been enabled. 8136 * 8137 * @return true if verification should be performed 8138 */ 8139 private boolean isVerificationEnabled(int userId, int installFlags) { 8140 if (!DEFAULT_VERIFY_ENABLE) { 8141 return false; 8142 } 8143 8144 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8145 8146 // Check if installing from ADB 8147 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8148 // Do not run verification in a test harness environment 8149 if (ActivityManager.isRunningInTestHarness()) { 8150 return false; 8151 } 8152 if (ensureVerifyAppsEnabled) { 8153 return true; 8154 } 8155 // Check if the developer does not want package verification for ADB installs 8156 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8157 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8158 return false; 8159 } 8160 } 8161 8162 if (ensureVerifyAppsEnabled) { 8163 return true; 8164 } 8165 8166 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8167 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8168 } 8169 8170 /** 8171 * Get the "allow unknown sources" setting. 8172 * 8173 * @return the current "allow unknown sources" setting 8174 */ 8175 private int getUnknownSourcesSettings() { 8176 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8177 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8178 -1); 8179 } 8180 8181 @Override 8182 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8183 final int uid = Binder.getCallingUid(); 8184 // writer 8185 synchronized (mPackages) { 8186 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8187 if (targetPackageSetting == null) { 8188 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8189 } 8190 8191 PackageSetting installerPackageSetting; 8192 if (installerPackageName != null) { 8193 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8194 if (installerPackageSetting == null) { 8195 throw new IllegalArgumentException("Unknown installer package: " 8196 + installerPackageName); 8197 } 8198 } else { 8199 installerPackageSetting = null; 8200 } 8201 8202 Signature[] callerSignature; 8203 Object obj = mSettings.getUserIdLPr(uid); 8204 if (obj != null) { 8205 if (obj instanceof SharedUserSetting) { 8206 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8207 } else if (obj instanceof PackageSetting) { 8208 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8209 } else { 8210 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8211 } 8212 } else { 8213 throw new SecurityException("Unknown calling uid " + uid); 8214 } 8215 8216 // Verify: can't set installerPackageName to a package that is 8217 // not signed with the same cert as the caller. 8218 if (installerPackageSetting != null) { 8219 if (compareSignatures(callerSignature, 8220 installerPackageSetting.signatures.mSignatures) 8221 != PackageManager.SIGNATURE_MATCH) { 8222 throw new SecurityException( 8223 "Caller does not have same cert as new installer package " 8224 + installerPackageName); 8225 } 8226 } 8227 8228 // Verify: if target already has an installer package, it must 8229 // be signed with the same cert as the caller. 8230 if (targetPackageSetting.installerPackageName != null) { 8231 PackageSetting setting = mSettings.mPackages.get( 8232 targetPackageSetting.installerPackageName); 8233 // If the currently set package isn't valid, then it's always 8234 // okay to change it. 8235 if (setting != null) { 8236 if (compareSignatures(callerSignature, 8237 setting.signatures.mSignatures) 8238 != PackageManager.SIGNATURE_MATCH) { 8239 throw new SecurityException( 8240 "Caller does not have same cert as old installer package " 8241 + targetPackageSetting.installerPackageName); 8242 } 8243 } 8244 } 8245 8246 // Okay! 8247 targetPackageSetting.installerPackageName = installerPackageName; 8248 scheduleWriteSettingsLocked(); 8249 } 8250 } 8251 8252 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8253 // Queue up an async operation since the package installation may take a little while. 8254 mHandler.post(new Runnable() { 8255 public void run() { 8256 mHandler.removeCallbacks(this); 8257 // Result object to be returned 8258 PackageInstalledInfo res = new PackageInstalledInfo(); 8259 res.returnCode = currentStatus; 8260 res.uid = -1; 8261 res.pkg = null; 8262 res.removedInfo = new PackageRemovedInfo(); 8263 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8264 args.doPreInstall(res.returnCode); 8265 synchronized (mInstallLock) { 8266 installPackageLI(args, res); 8267 } 8268 args.doPostInstall(res.returnCode, res.uid); 8269 } 8270 8271 // A restore should be performed at this point if (a) the install 8272 // succeeded, (b) the operation is not an update, and (c) the new 8273 // package has not opted out of backup participation. 8274 final boolean update = res.removedInfo.removedPackage != null; 8275 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8276 boolean doRestore = !update 8277 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8278 8279 // Set up the post-install work request bookkeeping. This will be used 8280 // and cleaned up by the post-install event handling regardless of whether 8281 // there's a restore pass performed. Token values are >= 1. 8282 int token; 8283 if (mNextInstallToken < 0) mNextInstallToken = 1; 8284 token = mNextInstallToken++; 8285 8286 PostInstallData data = new PostInstallData(args, res); 8287 mRunningInstalls.put(token, data); 8288 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8289 8290 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8291 // Pass responsibility to the Backup Manager. It will perform a 8292 // restore if appropriate, then pass responsibility back to the 8293 // Package Manager to run the post-install observer callbacks 8294 // and broadcasts. 8295 IBackupManager bm = IBackupManager.Stub.asInterface( 8296 ServiceManager.getService(Context.BACKUP_SERVICE)); 8297 if (bm != null) { 8298 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8299 + " to BM for possible restore"); 8300 try { 8301 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8302 } catch (RemoteException e) { 8303 // can't happen; the backup manager is local 8304 } catch (Exception e) { 8305 Slog.e(TAG, "Exception trying to enqueue restore", e); 8306 doRestore = false; 8307 } 8308 } else { 8309 Slog.e(TAG, "Backup Manager not found!"); 8310 doRestore = false; 8311 } 8312 } 8313 8314 if (!doRestore) { 8315 // No restore possible, or the Backup Manager was mysteriously not 8316 // available -- just fire the post-install work request directly. 8317 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8318 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8319 mHandler.sendMessage(msg); 8320 } 8321 } 8322 }); 8323 } 8324 8325 private abstract class HandlerParams { 8326 private static final int MAX_RETRIES = 4; 8327 8328 /** 8329 * Number of times startCopy() has been attempted and had a non-fatal 8330 * error. 8331 */ 8332 private int mRetries = 0; 8333 8334 /** User handle for the user requesting the information or installation. */ 8335 private final UserHandle mUser; 8336 8337 HandlerParams(UserHandle user) { 8338 mUser = user; 8339 } 8340 8341 UserHandle getUser() { 8342 return mUser; 8343 } 8344 8345 final boolean startCopy() { 8346 boolean res; 8347 try { 8348 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8349 8350 if (++mRetries > MAX_RETRIES) { 8351 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8352 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8353 handleServiceError(); 8354 return false; 8355 } else { 8356 handleStartCopy(); 8357 res = true; 8358 } 8359 } catch (RemoteException e) { 8360 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8361 mHandler.sendEmptyMessage(MCS_RECONNECT); 8362 res = false; 8363 } 8364 handleReturnCode(); 8365 return res; 8366 } 8367 8368 final void serviceError() { 8369 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8370 handleServiceError(); 8371 handleReturnCode(); 8372 } 8373 8374 abstract void handleStartCopy() throws RemoteException; 8375 abstract void handleServiceError(); 8376 abstract void handleReturnCode(); 8377 } 8378 8379 class MeasureParams extends HandlerParams { 8380 private final PackageStats mStats; 8381 private boolean mSuccess; 8382 8383 private final IPackageStatsObserver mObserver; 8384 8385 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8386 super(new UserHandle(stats.userHandle)); 8387 mObserver = observer; 8388 mStats = stats; 8389 } 8390 8391 @Override 8392 public String toString() { 8393 return "MeasureParams{" 8394 + Integer.toHexString(System.identityHashCode(this)) 8395 + " " + mStats.packageName + "}"; 8396 } 8397 8398 @Override 8399 void handleStartCopy() throws RemoteException { 8400 synchronized (mInstallLock) { 8401 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8402 } 8403 8404 if (mSuccess) { 8405 final boolean mounted; 8406 if (Environment.isExternalStorageEmulated()) { 8407 mounted = true; 8408 } else { 8409 final String status = Environment.getExternalStorageState(); 8410 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8411 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8412 } 8413 8414 if (mounted) { 8415 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8416 8417 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8418 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8419 8420 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8421 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8422 8423 // Always subtract cache size, since it's a subdirectory 8424 mStats.externalDataSize -= mStats.externalCacheSize; 8425 8426 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8427 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8428 8429 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8430 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8431 } 8432 } 8433 } 8434 8435 @Override 8436 void handleReturnCode() { 8437 if (mObserver != null) { 8438 try { 8439 mObserver.onGetStatsCompleted(mStats, mSuccess); 8440 } catch (RemoteException e) { 8441 Slog.i(TAG, "Observer no longer exists."); 8442 } 8443 } 8444 } 8445 8446 @Override 8447 void handleServiceError() { 8448 Slog.e(TAG, "Could not measure application " + mStats.packageName 8449 + " external storage"); 8450 } 8451 } 8452 8453 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8454 throws RemoteException { 8455 long result = 0; 8456 for (File path : paths) { 8457 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8458 } 8459 return result; 8460 } 8461 8462 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8463 for (File path : paths) { 8464 try { 8465 mcs.clearDirectory(path.getAbsolutePath()); 8466 } catch (RemoteException e) { 8467 } 8468 } 8469 } 8470 8471 static class OriginInfo { 8472 /** 8473 * Location where install is coming from, before it has been 8474 * copied/renamed into place. This could be a single monolithic APK 8475 * file, or a cluster directory. This location may be untrusted. 8476 */ 8477 final File file; 8478 final String cid; 8479 8480 /** 8481 * Flag indicating that {@link #file} or {@link #cid} has already been 8482 * staged, meaning downstream users don't need to defensively copy the 8483 * contents. 8484 */ 8485 final boolean staged; 8486 8487 /** 8488 * Flag indicating that {@link #file} or {@link #cid} is an already 8489 * installed app that is being moved. 8490 */ 8491 final boolean existing; 8492 8493 final String resolvedPath; 8494 final File resolvedFile; 8495 8496 static OriginInfo fromNothing() { 8497 return new OriginInfo(null, null, false, false); 8498 } 8499 8500 static OriginInfo fromUntrustedFile(File file) { 8501 return new OriginInfo(file, null, false, false); 8502 } 8503 8504 static OriginInfo fromExistingFile(File file) { 8505 return new OriginInfo(file, null, false, true); 8506 } 8507 8508 static OriginInfo fromStagedFile(File file) { 8509 return new OriginInfo(file, null, true, false); 8510 } 8511 8512 static OriginInfo fromStagedContainer(String cid) { 8513 return new OriginInfo(null, cid, true, false); 8514 } 8515 8516 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8517 this.file = file; 8518 this.cid = cid; 8519 this.staged = staged; 8520 this.existing = existing; 8521 8522 if (cid != null) { 8523 resolvedPath = PackageHelper.getSdDir(cid); 8524 resolvedFile = new File(resolvedPath); 8525 } else if (file != null) { 8526 resolvedPath = file.getAbsolutePath(); 8527 resolvedFile = file; 8528 } else { 8529 resolvedPath = null; 8530 resolvedFile = null; 8531 } 8532 } 8533 } 8534 8535 class InstallParams extends HandlerParams { 8536 final OriginInfo origin; 8537 final IPackageInstallObserver2 observer; 8538 int installFlags; 8539 final String installerPackageName; 8540 final VerificationParams verificationParams; 8541 private InstallArgs mArgs; 8542 private int mRet; 8543 final String packageAbiOverride; 8544 8545 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8546 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8547 String packageAbiOverride) { 8548 super(user); 8549 this.origin = origin; 8550 this.observer = observer; 8551 this.installFlags = installFlags; 8552 this.installerPackageName = installerPackageName; 8553 this.verificationParams = verificationParams; 8554 this.packageAbiOverride = packageAbiOverride; 8555 } 8556 8557 @Override 8558 public String toString() { 8559 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8560 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8561 } 8562 8563 public ManifestDigest getManifestDigest() { 8564 if (verificationParams == null) { 8565 return null; 8566 } 8567 return verificationParams.getManifestDigest(); 8568 } 8569 8570 private int installLocationPolicy(PackageInfoLite pkgLite) { 8571 String packageName = pkgLite.packageName; 8572 int installLocation = pkgLite.installLocation; 8573 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8574 // reader 8575 synchronized (mPackages) { 8576 PackageParser.Package pkg = mPackages.get(packageName); 8577 if (pkg != null) { 8578 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8579 // Check for downgrading. 8580 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8581 if (pkgLite.versionCode < pkg.mVersionCode) { 8582 Slog.w(TAG, "Can't install update of " + packageName 8583 + " update version " + pkgLite.versionCode 8584 + " is older than installed version " 8585 + pkg.mVersionCode); 8586 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8587 } 8588 } 8589 // Check for updated system application. 8590 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8591 if (onSd) { 8592 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8593 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8594 } 8595 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8596 } else { 8597 if (onSd) { 8598 // Install flag overrides everything. 8599 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8600 } 8601 // If current upgrade specifies particular preference 8602 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8603 // Application explicitly specified internal. 8604 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8605 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8606 // App explictly prefers external. Let policy decide 8607 } else { 8608 // Prefer previous location 8609 if (isExternal(pkg)) { 8610 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8611 } 8612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8613 } 8614 } 8615 } else { 8616 // Invalid install. Return error code 8617 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8618 } 8619 } 8620 } 8621 // All the special cases have been taken care of. 8622 // Return result based on recommended install location. 8623 if (onSd) { 8624 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8625 } 8626 return pkgLite.recommendedInstallLocation; 8627 } 8628 8629 /* 8630 * Invoke remote method to get package information and install 8631 * location values. Override install location based on default 8632 * policy if needed and then create install arguments based 8633 * on the install location. 8634 */ 8635 public void handleStartCopy() throws RemoteException { 8636 int ret = PackageManager.INSTALL_SUCCEEDED; 8637 8638 // If we're already staged, we've firmly committed to an install location 8639 if (origin.staged) { 8640 if (origin.file != null) { 8641 installFlags |= PackageManager.INSTALL_INTERNAL; 8642 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8643 } else if (origin.cid != null) { 8644 installFlags |= PackageManager.INSTALL_EXTERNAL; 8645 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8646 } else { 8647 throw new IllegalStateException("Invalid stage location"); 8648 } 8649 } 8650 8651 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8652 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8653 8654 PackageInfoLite pkgLite = null; 8655 8656 if (onInt && onSd) { 8657 // Check if both bits are set. 8658 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8659 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8660 } else { 8661 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8662 packageAbiOverride); 8663 8664 /* 8665 * If we have too little free space, try to free cache 8666 * before giving up. 8667 */ 8668 if (!origin.staged && pkgLite.recommendedInstallLocation 8669 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8670 // TODO: focus freeing disk space on the target device 8671 final StorageManager storage = StorageManager.from(mContext); 8672 final long lowThreshold = storage.getStorageLowBytes( 8673 Environment.getDataDirectory()); 8674 8675 final long sizeBytes = mContainerService.calculateInstalledSize( 8676 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8677 8678 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8679 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8680 installFlags, packageAbiOverride); 8681 } 8682 8683 /* 8684 * The cache free must have deleted the file we 8685 * downloaded to install. 8686 * 8687 * TODO: fix the "freeCache" call to not delete 8688 * the file we care about. 8689 */ 8690 if (pkgLite.recommendedInstallLocation 8691 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8692 pkgLite.recommendedInstallLocation 8693 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8694 } 8695 } 8696 } 8697 8698 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8699 int loc = pkgLite.recommendedInstallLocation; 8700 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8701 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8702 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8703 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8704 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8705 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8706 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8707 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8708 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8709 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8710 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8711 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8712 } else { 8713 // Override with defaults if needed. 8714 loc = installLocationPolicy(pkgLite); 8715 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8716 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8717 } else if (!onSd && !onInt) { 8718 // Override install location with flags 8719 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8720 // Set the flag to install on external media. 8721 installFlags |= PackageManager.INSTALL_EXTERNAL; 8722 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8723 } else { 8724 // Make sure the flag for installing on external 8725 // media is unset 8726 installFlags |= PackageManager.INSTALL_INTERNAL; 8727 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8728 } 8729 } 8730 } 8731 } 8732 8733 final InstallArgs args = createInstallArgs(this); 8734 mArgs = args; 8735 8736 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8737 /* 8738 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8739 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8740 */ 8741 int userIdentifier = getUser().getIdentifier(); 8742 if (userIdentifier == UserHandle.USER_ALL 8743 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8744 userIdentifier = UserHandle.USER_OWNER; 8745 } 8746 8747 /* 8748 * Determine if we have any installed package verifiers. If we 8749 * do, then we'll defer to them to verify the packages. 8750 */ 8751 final int requiredUid = mRequiredVerifierPackage == null ? -1 8752 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8753 if (!origin.existing && requiredUid != -1 8754 && isVerificationEnabled(userIdentifier, installFlags)) { 8755 final Intent verification = new Intent( 8756 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8757 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8758 PACKAGE_MIME_TYPE); 8759 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8760 8761 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8762 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8763 0 /* TODO: Which userId? */); 8764 8765 if (DEBUG_VERIFY) { 8766 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8767 + verification.toString() + " with " + pkgLite.verifiers.length 8768 + " optional verifiers"); 8769 } 8770 8771 final int verificationId = mPendingVerificationToken++; 8772 8773 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8774 8775 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8776 installerPackageName); 8777 8778 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8779 installFlags); 8780 8781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8782 pkgLite.packageName); 8783 8784 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8785 pkgLite.versionCode); 8786 8787 if (verificationParams != null) { 8788 if (verificationParams.getVerificationURI() != null) { 8789 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8790 verificationParams.getVerificationURI()); 8791 } 8792 if (verificationParams.getOriginatingURI() != null) { 8793 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8794 verificationParams.getOriginatingURI()); 8795 } 8796 if (verificationParams.getReferrer() != null) { 8797 verification.putExtra(Intent.EXTRA_REFERRER, 8798 verificationParams.getReferrer()); 8799 } 8800 if (verificationParams.getOriginatingUid() >= 0) { 8801 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8802 verificationParams.getOriginatingUid()); 8803 } 8804 if (verificationParams.getInstallerUid() >= 0) { 8805 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8806 verificationParams.getInstallerUid()); 8807 } 8808 } 8809 8810 final PackageVerificationState verificationState = new PackageVerificationState( 8811 requiredUid, args); 8812 8813 mPendingVerification.append(verificationId, verificationState); 8814 8815 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8816 receivers, verificationState); 8817 8818 /* 8819 * If any sufficient verifiers were listed in the package 8820 * manifest, attempt to ask them. 8821 */ 8822 if (sufficientVerifiers != null) { 8823 final int N = sufficientVerifiers.size(); 8824 if (N == 0) { 8825 Slog.i(TAG, "Additional verifiers required, but none installed."); 8826 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8827 } else { 8828 for (int i = 0; i < N; i++) { 8829 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8830 8831 final Intent sufficientIntent = new Intent(verification); 8832 sufficientIntent.setComponent(verifierComponent); 8833 8834 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8835 } 8836 } 8837 } 8838 8839 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8840 mRequiredVerifierPackage, receivers); 8841 if (ret == PackageManager.INSTALL_SUCCEEDED 8842 && mRequiredVerifierPackage != null) { 8843 /* 8844 * Send the intent to the required verification agent, 8845 * but only start the verification timeout after the 8846 * target BroadcastReceivers have run. 8847 */ 8848 verification.setComponent(requiredVerifierComponent); 8849 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8850 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8851 new BroadcastReceiver() { 8852 @Override 8853 public void onReceive(Context context, Intent intent) { 8854 final Message msg = mHandler 8855 .obtainMessage(CHECK_PENDING_VERIFICATION); 8856 msg.arg1 = verificationId; 8857 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8858 } 8859 }, null, 0, null, null); 8860 8861 /* 8862 * We don't want the copy to proceed until verification 8863 * succeeds, so null out this field. 8864 */ 8865 mArgs = null; 8866 } 8867 } else { 8868 /* 8869 * No package verification is enabled, so immediately start 8870 * the remote call to initiate copy using temporary file. 8871 */ 8872 ret = args.copyApk(mContainerService, true); 8873 } 8874 } 8875 8876 mRet = ret; 8877 } 8878 8879 @Override 8880 void handleReturnCode() { 8881 // If mArgs is null, then MCS couldn't be reached. When it 8882 // reconnects, it will try again to install. At that point, this 8883 // will succeed. 8884 if (mArgs != null) { 8885 processPendingInstall(mArgs, mRet); 8886 } 8887 } 8888 8889 @Override 8890 void handleServiceError() { 8891 mArgs = createInstallArgs(this); 8892 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8893 } 8894 8895 public boolean isForwardLocked() { 8896 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8897 } 8898 } 8899 8900 /** 8901 * Used during creation of InstallArgs 8902 * 8903 * @param installFlags package installation flags 8904 * @return true if should be installed on external storage 8905 */ 8906 private static boolean installOnSd(int installFlags) { 8907 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8908 return false; 8909 } 8910 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8911 return true; 8912 } 8913 return false; 8914 } 8915 8916 /** 8917 * Used during creation of InstallArgs 8918 * 8919 * @param installFlags package installation flags 8920 * @return true if should be installed as forward locked 8921 */ 8922 private static boolean installForwardLocked(int installFlags) { 8923 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8924 } 8925 8926 private InstallArgs createInstallArgs(InstallParams params) { 8927 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8928 return new AsecInstallArgs(params); 8929 } else { 8930 return new FileInstallArgs(params); 8931 } 8932 } 8933 8934 /** 8935 * Create args that describe an existing installed package. Typically used 8936 * when cleaning up old installs, or used as a move source. 8937 */ 8938 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8939 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8940 final boolean isInAsec; 8941 if (installOnSd(installFlags)) { 8942 /* Apps on SD card are always in ASEC containers. */ 8943 isInAsec = true; 8944 } else if (installForwardLocked(installFlags) 8945 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8946 /* 8947 * Forward-locked apps are only in ASEC containers if they're the 8948 * new style 8949 */ 8950 isInAsec = true; 8951 } else { 8952 isInAsec = false; 8953 } 8954 8955 if (isInAsec) { 8956 return new AsecInstallArgs(codePath, instructionSets, 8957 installOnSd(installFlags), installForwardLocked(installFlags)); 8958 } else { 8959 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8960 instructionSets); 8961 } 8962 } 8963 8964 static abstract class InstallArgs { 8965 /** @see InstallParams#origin */ 8966 final OriginInfo origin; 8967 8968 final IPackageInstallObserver2 observer; 8969 // Always refers to PackageManager flags only 8970 final int installFlags; 8971 final String installerPackageName; 8972 final ManifestDigest manifestDigest; 8973 final UserHandle user; 8974 final String abiOverride; 8975 8976 // The list of instruction sets supported by this app. This is currently 8977 // only used during the rmdex() phase to clean up resources. We can get rid of this 8978 // if we move dex files under the common app path. 8979 /* nullable */ String[] instructionSets; 8980 8981 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8982 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8983 String[] instructionSets, String abiOverride) { 8984 this.origin = origin; 8985 this.installFlags = installFlags; 8986 this.observer = observer; 8987 this.installerPackageName = installerPackageName; 8988 this.manifestDigest = manifestDigest; 8989 this.user = user; 8990 this.instructionSets = instructionSets; 8991 this.abiOverride = abiOverride; 8992 } 8993 8994 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8995 abstract int doPreInstall(int status); 8996 8997 /** 8998 * Rename package into final resting place. All paths on the given 8999 * scanned package should be updated to reflect the rename. 9000 */ 9001 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9002 abstract int doPostInstall(int status, int uid); 9003 9004 /** @see PackageSettingBase#codePathString */ 9005 abstract String getCodePath(); 9006 /** @see PackageSettingBase#resourcePathString */ 9007 abstract String getResourcePath(); 9008 abstract String getLegacyNativeLibraryPath(); 9009 9010 // Need installer lock especially for dex file removal. 9011 abstract void cleanUpResourcesLI(); 9012 abstract boolean doPostDeleteLI(boolean delete); 9013 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9014 9015 /** 9016 * Called before the source arguments are copied. This is used mostly 9017 * for MoveParams when it needs to read the source file to put it in the 9018 * destination. 9019 */ 9020 int doPreCopy() { 9021 return PackageManager.INSTALL_SUCCEEDED; 9022 } 9023 9024 /** 9025 * Called after the source arguments are copied. This is used mostly for 9026 * MoveParams when it needs to read the source file to put it in the 9027 * destination. 9028 * 9029 * @return 9030 */ 9031 int doPostCopy(int uid) { 9032 return PackageManager.INSTALL_SUCCEEDED; 9033 } 9034 9035 protected boolean isFwdLocked() { 9036 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9037 } 9038 9039 protected boolean isExternal() { 9040 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9041 } 9042 9043 UserHandle getUser() { 9044 return user; 9045 } 9046 } 9047 9048 /** 9049 * Logic to handle installation of non-ASEC applications, including copying 9050 * and renaming logic. 9051 */ 9052 class FileInstallArgs extends InstallArgs { 9053 private File codeFile; 9054 private File resourceFile; 9055 private File legacyNativeLibraryPath; 9056 9057 // Example topology: 9058 // /data/app/com.example/base.apk 9059 // /data/app/com.example/split_foo.apk 9060 // /data/app/com.example/lib/arm/libfoo.so 9061 // /data/app/com.example/lib/arm64/libfoo.so 9062 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9063 9064 /** New install */ 9065 FileInstallArgs(InstallParams params) { 9066 super(params.origin, params.observer, params.installFlags, 9067 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9068 null /* instruction sets */, params.packageAbiOverride); 9069 if (isFwdLocked()) { 9070 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9071 } 9072 } 9073 9074 /** Existing install */ 9075 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9076 String[] instructionSets) { 9077 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9078 this.codeFile = (codePath != null) ? new File(codePath) : null; 9079 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9080 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9081 new File(legacyNativeLibraryPath) : null; 9082 } 9083 9084 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9085 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9086 isFwdLocked(), abiOverride); 9087 9088 final StorageManager storage = StorageManager.from(mContext); 9089 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9090 } 9091 9092 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9093 if (origin.staged) { 9094 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9095 codeFile = origin.file; 9096 resourceFile = origin.file; 9097 return PackageManager.INSTALL_SUCCEEDED; 9098 } 9099 9100 try { 9101 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9102 codeFile = tempDir; 9103 resourceFile = tempDir; 9104 } catch (IOException e) { 9105 Slog.w(TAG, "Failed to create copy file: " + e); 9106 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9107 } 9108 9109 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9110 @Override 9111 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9112 if (!FileUtils.isValidExtFilename(name)) { 9113 throw new IllegalArgumentException("Invalid filename: " + name); 9114 } 9115 try { 9116 final File file = new File(codeFile, name); 9117 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9118 O_RDWR | O_CREAT, 0644); 9119 Os.chmod(file.getAbsolutePath(), 0644); 9120 return new ParcelFileDescriptor(fd); 9121 } catch (ErrnoException e) { 9122 throw new RemoteException("Failed to open: " + e.getMessage()); 9123 } 9124 } 9125 }; 9126 9127 int ret = PackageManager.INSTALL_SUCCEEDED; 9128 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9129 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9130 Slog.e(TAG, "Failed to copy package"); 9131 return ret; 9132 } 9133 9134 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9135 NativeLibraryHelper.Handle handle = null; 9136 try { 9137 handle = NativeLibraryHelper.Handle.create(codeFile); 9138 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9139 abiOverride); 9140 } catch (IOException e) { 9141 Slog.e(TAG, "Copying native libraries failed", e); 9142 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9143 } finally { 9144 IoUtils.closeQuietly(handle); 9145 } 9146 9147 return ret; 9148 } 9149 9150 int doPreInstall(int status) { 9151 if (status != PackageManager.INSTALL_SUCCEEDED) { 9152 cleanUp(); 9153 } 9154 return status; 9155 } 9156 9157 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9158 if (status != PackageManager.INSTALL_SUCCEEDED) { 9159 cleanUp(); 9160 return false; 9161 } else { 9162 final File beforeCodeFile = codeFile; 9163 final File afterCodeFile = getNextCodePath(pkg.packageName); 9164 9165 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9166 try { 9167 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9168 } catch (ErrnoException e) { 9169 Slog.d(TAG, "Failed to rename", e); 9170 return false; 9171 } 9172 9173 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9174 Slog.d(TAG, "Failed to restorecon"); 9175 return false; 9176 } 9177 9178 // Reflect the rename internally 9179 codeFile = afterCodeFile; 9180 resourceFile = afterCodeFile; 9181 9182 // Reflect the rename in scanned details 9183 pkg.codePath = afterCodeFile.getAbsolutePath(); 9184 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9185 pkg.baseCodePath); 9186 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9187 pkg.splitCodePaths); 9188 9189 // Reflect the rename in app info 9190 pkg.applicationInfo.setCodePath(pkg.codePath); 9191 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9192 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9193 pkg.applicationInfo.setResourcePath(pkg.codePath); 9194 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9195 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9196 9197 return true; 9198 } 9199 } 9200 9201 int doPostInstall(int status, int uid) { 9202 if (status != PackageManager.INSTALL_SUCCEEDED) { 9203 cleanUp(); 9204 } 9205 return status; 9206 } 9207 9208 @Override 9209 String getCodePath() { 9210 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9211 } 9212 9213 @Override 9214 String getResourcePath() { 9215 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9216 } 9217 9218 @Override 9219 String getLegacyNativeLibraryPath() { 9220 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9221 } 9222 9223 private boolean cleanUp() { 9224 if (codeFile == null || !codeFile.exists()) { 9225 return false; 9226 } 9227 9228 if (codeFile.isDirectory()) { 9229 FileUtils.deleteContents(codeFile); 9230 } 9231 codeFile.delete(); 9232 9233 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9234 resourceFile.delete(); 9235 } 9236 9237 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9238 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9239 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9240 } 9241 legacyNativeLibraryPath.delete(); 9242 } 9243 9244 return true; 9245 } 9246 9247 void cleanUpResourcesLI() { 9248 // Try enumerating all code paths before deleting 9249 List<String> allCodePaths = Collections.EMPTY_LIST; 9250 if (codeFile != null && codeFile.exists()) { 9251 try { 9252 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9253 allCodePaths = pkg.getAllCodePaths(); 9254 } catch (PackageParserException e) { 9255 // Ignored; we tried our best 9256 } 9257 } 9258 9259 cleanUp(); 9260 9261 if (!allCodePaths.isEmpty()) { 9262 if (instructionSets == null) { 9263 throw new IllegalStateException("instructionSet == null"); 9264 } 9265 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9266 for (String codePath : allCodePaths) { 9267 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9268 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9269 if (retCode < 0) { 9270 Slog.w(TAG, "Couldn't remove dex file for package: " 9271 + " at location " + codePath + ", retcode=" + retCode); 9272 // we don't consider this to be a failure of the core package deletion 9273 } 9274 } 9275 } 9276 } 9277 } 9278 9279 boolean doPostDeleteLI(boolean delete) { 9280 // XXX err, shouldn't we respect the delete flag? 9281 cleanUpResourcesLI(); 9282 return true; 9283 } 9284 } 9285 9286 private boolean isAsecExternal(String cid) { 9287 final String asecPath = PackageHelper.getSdFilesystem(cid); 9288 return !asecPath.startsWith(mAsecInternalPath); 9289 } 9290 9291 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9292 PackageManagerException { 9293 if (copyRet < 0) { 9294 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9295 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9296 throw new PackageManagerException(copyRet, message); 9297 } 9298 } 9299 } 9300 9301 /** 9302 * Extract the MountService "container ID" from the full code path of an 9303 * .apk. 9304 */ 9305 static String cidFromCodePath(String fullCodePath) { 9306 int eidx = fullCodePath.lastIndexOf("/"); 9307 String subStr1 = fullCodePath.substring(0, eidx); 9308 int sidx = subStr1.lastIndexOf("/"); 9309 return subStr1.substring(sidx+1, eidx); 9310 } 9311 9312 /** 9313 * Logic to handle installation of ASEC applications, including copying and 9314 * renaming logic. 9315 */ 9316 class AsecInstallArgs extends InstallArgs { 9317 static final String RES_FILE_NAME = "pkg.apk"; 9318 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9319 9320 String cid; 9321 String packagePath; 9322 String resourcePath; 9323 String legacyNativeLibraryDir; 9324 9325 /** New install */ 9326 AsecInstallArgs(InstallParams params) { 9327 super(params.origin, params.observer, params.installFlags, 9328 params.installerPackageName, params.getManifestDigest(), 9329 params.getUser(), null /* instruction sets */, 9330 params.packageAbiOverride); 9331 } 9332 9333 /** Existing install */ 9334 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9335 boolean isExternal, boolean isForwardLocked) { 9336 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9337 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9338 instructionSets, null); 9339 // Hackily pretend we're still looking at a full code path 9340 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9341 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9342 } 9343 9344 // Extract cid from fullCodePath 9345 int eidx = fullCodePath.lastIndexOf("/"); 9346 String subStr1 = fullCodePath.substring(0, eidx); 9347 int sidx = subStr1.lastIndexOf("/"); 9348 cid = subStr1.substring(sidx+1, eidx); 9349 setMountPath(subStr1); 9350 } 9351 9352 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9353 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9354 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9355 instructionSets, null); 9356 this.cid = cid; 9357 setMountPath(PackageHelper.getSdDir(cid)); 9358 } 9359 9360 void createCopyFile() { 9361 cid = mInstallerService.allocateExternalStageCidLegacy(); 9362 } 9363 9364 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9365 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9366 abiOverride); 9367 9368 final File target; 9369 if (isExternal()) { 9370 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9371 } else { 9372 target = Environment.getDataDirectory(); 9373 } 9374 9375 final StorageManager storage = StorageManager.from(mContext); 9376 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9377 } 9378 9379 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9380 if (origin.staged) { 9381 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9382 cid = origin.cid; 9383 setMountPath(PackageHelper.getSdDir(cid)); 9384 return PackageManager.INSTALL_SUCCEEDED; 9385 } 9386 9387 if (temp) { 9388 createCopyFile(); 9389 } else { 9390 /* 9391 * Pre-emptively destroy the container since it's destroyed if 9392 * copying fails due to it existing anyway. 9393 */ 9394 PackageHelper.destroySdDir(cid); 9395 } 9396 9397 final String newMountPath = imcs.copyPackageToContainer( 9398 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9399 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9400 9401 if (newMountPath != null) { 9402 setMountPath(newMountPath); 9403 return PackageManager.INSTALL_SUCCEEDED; 9404 } else { 9405 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9406 } 9407 } 9408 9409 @Override 9410 String getCodePath() { 9411 return packagePath; 9412 } 9413 9414 @Override 9415 String getResourcePath() { 9416 return resourcePath; 9417 } 9418 9419 @Override 9420 String getLegacyNativeLibraryPath() { 9421 return legacyNativeLibraryDir; 9422 } 9423 9424 int doPreInstall(int status) { 9425 if (status != PackageManager.INSTALL_SUCCEEDED) { 9426 // Destroy container 9427 PackageHelper.destroySdDir(cid); 9428 } else { 9429 boolean mounted = PackageHelper.isContainerMounted(cid); 9430 if (!mounted) { 9431 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9432 Process.SYSTEM_UID); 9433 if (newMountPath != null) { 9434 setMountPath(newMountPath); 9435 } else { 9436 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9437 } 9438 } 9439 } 9440 return status; 9441 } 9442 9443 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9444 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9445 String newMountPath = null; 9446 if (PackageHelper.isContainerMounted(cid)) { 9447 // Unmount the container 9448 if (!PackageHelper.unMountSdDir(cid)) { 9449 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9450 return false; 9451 } 9452 } 9453 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9454 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9455 " which might be stale. Will try to clean up."); 9456 // Clean up the stale container and proceed to recreate. 9457 if (!PackageHelper.destroySdDir(newCacheId)) { 9458 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9459 return false; 9460 } 9461 // Successfully cleaned up stale container. Try to rename again. 9462 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9463 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9464 + " inspite of cleaning it up."); 9465 return false; 9466 } 9467 } 9468 if (!PackageHelper.isContainerMounted(newCacheId)) { 9469 Slog.w(TAG, "Mounting container " + newCacheId); 9470 newMountPath = PackageHelper.mountSdDir(newCacheId, 9471 getEncryptKey(), Process.SYSTEM_UID); 9472 } else { 9473 newMountPath = PackageHelper.getSdDir(newCacheId); 9474 } 9475 if (newMountPath == null) { 9476 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9477 return false; 9478 } 9479 Log.i(TAG, "Succesfully renamed " + cid + 9480 " to " + newCacheId + 9481 " at new path: " + newMountPath); 9482 cid = newCacheId; 9483 9484 final File beforeCodeFile = new File(packagePath); 9485 setMountPath(newMountPath); 9486 final File afterCodeFile = new File(packagePath); 9487 9488 // Reflect the rename in scanned details 9489 pkg.codePath = afterCodeFile.getAbsolutePath(); 9490 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9491 pkg.baseCodePath); 9492 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9493 pkg.splitCodePaths); 9494 9495 // Reflect the rename in app info 9496 pkg.applicationInfo.setCodePath(pkg.codePath); 9497 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9498 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9499 pkg.applicationInfo.setResourcePath(pkg.codePath); 9500 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9501 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9502 9503 return true; 9504 } 9505 9506 private void setMountPath(String mountPath) { 9507 final File mountFile = new File(mountPath); 9508 9509 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9510 if (monolithicFile.exists()) { 9511 packagePath = monolithicFile.getAbsolutePath(); 9512 if (isFwdLocked()) { 9513 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9514 } else { 9515 resourcePath = packagePath; 9516 } 9517 } else { 9518 packagePath = mountFile.getAbsolutePath(); 9519 resourcePath = packagePath; 9520 } 9521 9522 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9523 } 9524 9525 int doPostInstall(int status, int uid) { 9526 if (status != PackageManager.INSTALL_SUCCEEDED) { 9527 cleanUp(); 9528 } else { 9529 final int groupOwner; 9530 final String protectedFile; 9531 if (isFwdLocked()) { 9532 groupOwner = UserHandle.getSharedAppGid(uid); 9533 protectedFile = RES_FILE_NAME; 9534 } else { 9535 groupOwner = -1; 9536 protectedFile = null; 9537 } 9538 9539 if (uid < Process.FIRST_APPLICATION_UID 9540 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9541 Slog.e(TAG, "Failed to finalize " + cid); 9542 PackageHelper.destroySdDir(cid); 9543 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9544 } 9545 9546 boolean mounted = PackageHelper.isContainerMounted(cid); 9547 if (!mounted) { 9548 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9549 } 9550 } 9551 return status; 9552 } 9553 9554 private void cleanUp() { 9555 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9556 9557 // Destroy secure container 9558 PackageHelper.destroySdDir(cid); 9559 } 9560 9561 private List<String> getAllCodePaths() { 9562 final File codeFile = new File(getCodePath()); 9563 if (codeFile != null && codeFile.exists()) { 9564 try { 9565 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9566 return pkg.getAllCodePaths(); 9567 } catch (PackageParserException e) { 9568 // Ignored; we tried our best 9569 } 9570 } 9571 return Collections.EMPTY_LIST; 9572 } 9573 9574 void cleanUpResourcesLI() { 9575 // Enumerate all code paths before deleting 9576 cleanUpResourcesLI(getAllCodePaths()); 9577 } 9578 9579 private void cleanUpResourcesLI(List<String> allCodePaths) { 9580 cleanUp(); 9581 9582 if (!allCodePaths.isEmpty()) { 9583 if (instructionSets == null) { 9584 throw new IllegalStateException("instructionSet == null"); 9585 } 9586 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9587 for (String codePath : allCodePaths) { 9588 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9589 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9590 if (retCode < 0) { 9591 Slog.w(TAG, "Couldn't remove dex file for package: " 9592 + " at location " + codePath + ", retcode=" + retCode); 9593 // we don't consider this to be a failure of the core package deletion 9594 } 9595 } 9596 } 9597 } 9598 } 9599 9600 boolean matchContainer(String app) { 9601 if (cid.startsWith(app)) { 9602 return true; 9603 } 9604 return false; 9605 } 9606 9607 String getPackageName() { 9608 return getAsecPackageName(cid); 9609 } 9610 9611 boolean doPostDeleteLI(boolean delete) { 9612 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9613 final List<String> allCodePaths = getAllCodePaths(); 9614 boolean mounted = PackageHelper.isContainerMounted(cid); 9615 if (mounted) { 9616 // Unmount first 9617 if (PackageHelper.unMountSdDir(cid)) { 9618 mounted = false; 9619 } 9620 } 9621 if (!mounted && delete) { 9622 cleanUpResourcesLI(allCodePaths); 9623 } 9624 return !mounted; 9625 } 9626 9627 @Override 9628 int doPreCopy() { 9629 if (isFwdLocked()) { 9630 if (!PackageHelper.fixSdPermissions(cid, 9631 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9632 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9633 } 9634 } 9635 9636 return PackageManager.INSTALL_SUCCEEDED; 9637 } 9638 9639 @Override 9640 int doPostCopy(int uid) { 9641 if (isFwdLocked()) { 9642 if (uid < Process.FIRST_APPLICATION_UID 9643 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9644 RES_FILE_NAME)) { 9645 Slog.e(TAG, "Failed to finalize " + cid); 9646 PackageHelper.destroySdDir(cid); 9647 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9648 } 9649 } 9650 9651 return PackageManager.INSTALL_SUCCEEDED; 9652 } 9653 } 9654 9655 static String getAsecPackageName(String packageCid) { 9656 int idx = packageCid.lastIndexOf("-"); 9657 if (idx == -1) { 9658 return packageCid; 9659 } 9660 return packageCid.substring(0, idx); 9661 } 9662 9663 // Utility method used to create code paths based on package name and available index. 9664 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9665 String idxStr = ""; 9666 int idx = 1; 9667 // Fall back to default value of idx=1 if prefix is not 9668 // part of oldCodePath 9669 if (oldCodePath != null) { 9670 String subStr = oldCodePath; 9671 // Drop the suffix right away 9672 if (suffix != null && subStr.endsWith(suffix)) { 9673 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9674 } 9675 // If oldCodePath already contains prefix find out the 9676 // ending index to either increment or decrement. 9677 int sidx = subStr.lastIndexOf(prefix); 9678 if (sidx != -1) { 9679 subStr = subStr.substring(sidx + prefix.length()); 9680 if (subStr != null) { 9681 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9682 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9683 } 9684 try { 9685 idx = Integer.parseInt(subStr); 9686 if (idx <= 1) { 9687 idx++; 9688 } else { 9689 idx--; 9690 } 9691 } catch(NumberFormatException e) { 9692 } 9693 } 9694 } 9695 } 9696 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9697 return prefix + idxStr; 9698 } 9699 9700 private File getNextCodePath(String packageName) { 9701 int suffix = 1; 9702 File result; 9703 do { 9704 result = new File(mAppInstallDir, packageName + "-" + suffix); 9705 suffix++; 9706 } while (result.exists()); 9707 return result; 9708 } 9709 9710 // Utility method used to ignore ADD/REMOVE events 9711 // by directory observer. 9712 private static boolean ignoreCodePath(String fullPathStr) { 9713 String apkName = deriveCodePathName(fullPathStr); 9714 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9715 if (idx != -1 && ((idx+1) < apkName.length())) { 9716 // Make sure the package ends with a numeral 9717 String version = apkName.substring(idx+1); 9718 try { 9719 Integer.parseInt(version); 9720 return true; 9721 } catch (NumberFormatException e) {} 9722 } 9723 return false; 9724 } 9725 9726 // Utility method that returns the relative package path with respect 9727 // to the installation directory. Like say for /data/data/com.test-1.apk 9728 // string com.test-1 is returned. 9729 static String deriveCodePathName(String codePath) { 9730 if (codePath == null) { 9731 return null; 9732 } 9733 final File codeFile = new File(codePath); 9734 final String name = codeFile.getName(); 9735 if (codeFile.isDirectory()) { 9736 return name; 9737 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9738 final int lastDot = name.lastIndexOf('.'); 9739 return name.substring(0, lastDot); 9740 } else { 9741 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9742 return null; 9743 } 9744 } 9745 9746 class PackageInstalledInfo { 9747 String name; 9748 int uid; 9749 // The set of users that originally had this package installed. 9750 int[] origUsers; 9751 // The set of users that now have this package installed. 9752 int[] newUsers; 9753 PackageParser.Package pkg; 9754 int returnCode; 9755 String returnMsg; 9756 PackageRemovedInfo removedInfo; 9757 9758 public void setError(int code, String msg) { 9759 returnCode = code; 9760 returnMsg = msg; 9761 Slog.w(TAG, msg); 9762 } 9763 9764 public void setError(String msg, PackageParserException e) { 9765 returnCode = e.error; 9766 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9767 Slog.w(TAG, msg, e); 9768 } 9769 9770 public void setError(String msg, PackageManagerException e) { 9771 returnCode = e.error; 9772 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9773 Slog.w(TAG, msg, e); 9774 } 9775 9776 // In some error cases we want to convey more info back to the observer 9777 String origPackage; 9778 String origPermission; 9779 } 9780 9781 /* 9782 * Install a non-existing package. 9783 */ 9784 private void installNewPackageLI(PackageParser.Package pkg, 9785 int parseFlags, int scanFlags, UserHandle user, 9786 String installerPackageName, PackageInstalledInfo res) { 9787 // Remember this for later, in case we need to rollback this install 9788 String pkgName = pkg.packageName; 9789 9790 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9791 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9792 synchronized(mPackages) { 9793 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9794 // A package with the same name is already installed, though 9795 // it has been renamed to an older name. The package we 9796 // are trying to install should be installed as an update to 9797 // the existing one, but that has not been requested, so bail. 9798 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9799 + " without first uninstalling package running as " 9800 + mSettings.mRenamedPackages.get(pkgName)); 9801 return; 9802 } 9803 if (mPackages.containsKey(pkgName)) { 9804 // Don't allow installation over an existing package with the same name. 9805 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9806 + " without first uninstalling."); 9807 return; 9808 } 9809 } 9810 9811 try { 9812 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9813 System.currentTimeMillis(), user); 9814 9815 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9816 // delete the partially installed application. the data directory will have to be 9817 // restored if it was already existing 9818 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9819 // remove package from internal structures. Note that we want deletePackageX to 9820 // delete the package data and cache directories that it created in 9821 // scanPackageLocked, unless those directories existed before we even tried to 9822 // install. 9823 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9824 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9825 res.removedInfo, true); 9826 } 9827 9828 } catch (PackageManagerException e) { 9829 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9830 } 9831 } 9832 9833 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9834 // Upgrade keysets are being used. Determine if new package has a superset of the 9835 // required keys. 9836 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9837 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9838 for (int i = 0; i < upgradeKeySets.length; i++) { 9839 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9840 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9841 return true; 9842 } 9843 } 9844 return false; 9845 } 9846 9847 private void replacePackageLI(PackageParser.Package pkg, 9848 int parseFlags, int scanFlags, UserHandle user, 9849 String installerPackageName, PackageInstalledInfo res) { 9850 PackageParser.Package oldPackage; 9851 String pkgName = pkg.packageName; 9852 int[] allUsers; 9853 boolean[] perUserInstalled; 9854 9855 // First find the old package info and check signatures 9856 synchronized(mPackages) { 9857 oldPackage = mPackages.get(pkgName); 9858 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9859 PackageSetting ps = mSettings.mPackages.get(pkgName); 9860 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9861 // default to original signature matching 9862 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9863 != PackageManager.SIGNATURE_MATCH) { 9864 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9865 "New package has a different signature: " + pkgName); 9866 return; 9867 } 9868 } else { 9869 if(!checkUpgradeKeySetLP(ps, pkg)) { 9870 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9871 "New package not signed by keys specified by upgrade-keysets: " 9872 + pkgName); 9873 return; 9874 } 9875 } 9876 9877 // In case of rollback, remember per-user/profile install state 9878 allUsers = sUserManager.getUserIds(); 9879 perUserInstalled = new boolean[allUsers.length]; 9880 for (int i = 0; i < allUsers.length; i++) { 9881 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9882 } 9883 } 9884 9885 boolean sysPkg = (isSystemApp(oldPackage)); 9886 if (sysPkg) { 9887 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9888 user, allUsers, perUserInstalled, installerPackageName, res); 9889 } else { 9890 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9891 user, allUsers, perUserInstalled, installerPackageName, res); 9892 } 9893 } 9894 9895 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9896 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9897 int[] allUsers, boolean[] perUserInstalled, 9898 String installerPackageName, PackageInstalledInfo res) { 9899 String pkgName = deletedPackage.packageName; 9900 boolean deletedPkg = true; 9901 boolean updatedSettings = false; 9902 9903 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9904 + deletedPackage); 9905 long origUpdateTime; 9906 if (pkg.mExtras != null) { 9907 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9908 } else { 9909 origUpdateTime = 0; 9910 } 9911 9912 // First delete the existing package while retaining the data directory 9913 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9914 res.removedInfo, true)) { 9915 // If the existing package wasn't successfully deleted 9916 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9917 deletedPkg = false; 9918 } else { 9919 // Successfully deleted the old package; proceed with replace. 9920 9921 // If deleted package lived in a container, give users a chance to 9922 // relinquish resources before killing. 9923 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9924 if (DEBUG_INSTALL) { 9925 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9926 } 9927 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9928 final ArrayList<String> pkgList = new ArrayList<String>(1); 9929 pkgList.add(deletedPackage.applicationInfo.packageName); 9930 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9931 } 9932 9933 deleteCodeCacheDirsLI(pkgName); 9934 try { 9935 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9936 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9937 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9938 updatedSettings = true; 9939 } catch (PackageManagerException e) { 9940 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9941 } 9942 } 9943 9944 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9945 // remove package from internal structures. Note that we want deletePackageX to 9946 // delete the package data and cache directories that it created in 9947 // scanPackageLocked, unless those directories existed before we even tried to 9948 // install. 9949 if(updatedSettings) { 9950 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9951 deletePackageLI( 9952 pkgName, null, true, allUsers, perUserInstalled, 9953 PackageManager.DELETE_KEEP_DATA, 9954 res.removedInfo, true); 9955 } 9956 // Since we failed to install the new package we need to restore the old 9957 // package that we deleted. 9958 if (deletedPkg) { 9959 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9960 File restoreFile = new File(deletedPackage.codePath); 9961 // Parse old package 9962 boolean oldOnSd = isExternal(deletedPackage); 9963 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9964 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9965 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9966 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9967 try { 9968 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9969 } catch (PackageManagerException e) { 9970 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9971 + e.getMessage()); 9972 return; 9973 } 9974 // Restore of old package succeeded. Update permissions. 9975 // writer 9976 synchronized (mPackages) { 9977 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9978 UPDATE_PERMISSIONS_ALL); 9979 // can downgrade to reader 9980 mSettings.writeLPr(); 9981 } 9982 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9983 } 9984 } 9985 } 9986 9987 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9988 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9989 int[] allUsers, boolean[] perUserInstalled, 9990 String installerPackageName, PackageInstalledInfo res) { 9991 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9992 + ", old=" + deletedPackage); 9993 boolean updatedSettings = false; 9994 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9995 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9996 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9997 } 9998 String packageName = deletedPackage.packageName; 9999 if (packageName == null) { 10000 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10001 "Attempt to delete null packageName."); 10002 return; 10003 } 10004 PackageParser.Package oldPkg; 10005 PackageSetting oldPkgSetting; 10006 // reader 10007 synchronized (mPackages) { 10008 oldPkg = mPackages.get(packageName); 10009 oldPkgSetting = mSettings.mPackages.get(packageName); 10010 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10011 (oldPkgSetting == null)) { 10012 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10013 "Couldn't find package:" + packageName + " information"); 10014 return; 10015 } 10016 } 10017 10018 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10019 10020 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10021 res.removedInfo.removedPackage = packageName; 10022 // Remove existing system package 10023 removePackageLI(oldPkgSetting, true); 10024 // writer 10025 synchronized (mPackages) { 10026 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10027 // We didn't need to disable the .apk as a current system package, 10028 // which means we are replacing another update that is already 10029 // installed. We need to make sure to delete the older one's .apk. 10030 res.removedInfo.args = createInstallArgsForExisting(0, 10031 deletedPackage.applicationInfo.getCodePath(), 10032 deletedPackage.applicationInfo.getResourcePath(), 10033 deletedPackage.applicationInfo.nativeLibraryRootDir, 10034 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10035 } else { 10036 res.removedInfo.args = null; 10037 } 10038 } 10039 10040 // Successfully disabled the old package. Now proceed with re-installation 10041 deleteCodeCacheDirsLI(packageName); 10042 10043 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10044 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10045 10046 PackageParser.Package newPackage = null; 10047 try { 10048 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10049 if (newPackage.mExtras != null) { 10050 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10051 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10052 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10053 10054 // is the update attempting to change shared user? that isn't going to work... 10055 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10056 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10057 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10058 + " to " + newPkgSetting.sharedUser); 10059 updatedSettings = true; 10060 } 10061 } 10062 10063 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10064 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10065 updatedSettings = true; 10066 } 10067 10068 } catch (PackageManagerException e) { 10069 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10070 } 10071 10072 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10073 // Re installation failed. Restore old information 10074 // Remove new pkg information 10075 if (newPackage != null) { 10076 removeInstalledPackageLI(newPackage, true); 10077 } 10078 // Add back the old system package 10079 try { 10080 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10081 } catch (PackageManagerException e) { 10082 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10083 } 10084 // Restore the old system information in Settings 10085 synchronized(mPackages) { 10086 if (updatedSettings) { 10087 mSettings.enableSystemPackageLPw(packageName); 10088 mSettings.setInstallerPackageName(packageName, 10089 oldPkgSetting.installerPackageName); 10090 } 10091 mSettings.writeLPr(); 10092 } 10093 } 10094 } 10095 10096 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10097 int[] allUsers, boolean[] perUserInstalled, 10098 PackageInstalledInfo res) { 10099 String pkgName = newPackage.packageName; 10100 synchronized (mPackages) { 10101 //write settings. the installStatus will be incomplete at this stage. 10102 //note that the new package setting would have already been 10103 //added to mPackages. It hasn't been persisted yet. 10104 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10105 mSettings.writeLPr(); 10106 } 10107 10108 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10109 10110 synchronized (mPackages) { 10111 updatePermissionsLPw(newPackage.packageName, newPackage, 10112 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10113 ? UPDATE_PERMISSIONS_ALL : 0)); 10114 // For system-bundled packages, we assume that installing an upgraded version 10115 // of the package implies that the user actually wants to run that new code, 10116 // so we enable the package. 10117 if (isSystemApp(newPackage)) { 10118 // NB: implicit assumption that system package upgrades apply to all users 10119 if (DEBUG_INSTALL) { 10120 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10121 } 10122 PackageSetting ps = mSettings.mPackages.get(pkgName); 10123 if (ps != null) { 10124 if (res.origUsers != null) { 10125 for (int userHandle : res.origUsers) { 10126 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10127 userHandle, installerPackageName); 10128 } 10129 } 10130 // Also convey the prior install/uninstall state 10131 if (allUsers != null && perUserInstalled != null) { 10132 for (int i = 0; i < allUsers.length; i++) { 10133 if (DEBUG_INSTALL) { 10134 Slog.d(TAG, " user " + allUsers[i] 10135 + " => " + perUserInstalled[i]); 10136 } 10137 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10138 } 10139 // these install state changes will be persisted in the 10140 // upcoming call to mSettings.writeLPr(). 10141 } 10142 } 10143 } 10144 res.name = pkgName; 10145 res.uid = newPackage.applicationInfo.uid; 10146 res.pkg = newPackage; 10147 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10148 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10149 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10150 //to update install status 10151 mSettings.writeLPr(); 10152 } 10153 } 10154 10155 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10156 final int installFlags = args.installFlags; 10157 String installerPackageName = args.installerPackageName; 10158 File tmpPackageFile = new File(args.getCodePath()); 10159 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10160 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10161 boolean replace = false; 10162 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10163 // Result object to be returned 10164 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10165 10166 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10167 // Retrieve PackageSettings and parse package 10168 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10169 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10170 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10171 PackageParser pp = new PackageParser(); 10172 pp.setSeparateProcesses(mSeparateProcesses); 10173 pp.setDisplayMetrics(mMetrics); 10174 10175 final PackageParser.Package pkg; 10176 try { 10177 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10178 } catch (PackageParserException e) { 10179 res.setError("Failed parse during installPackageLI", e); 10180 return; 10181 } 10182 10183 // Mark that we have an install time CPU ABI override. 10184 pkg.cpuAbiOverride = args.abiOverride; 10185 10186 String pkgName = res.name = pkg.packageName; 10187 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10188 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10189 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10190 return; 10191 } 10192 } 10193 10194 try { 10195 pp.collectCertificates(pkg, parseFlags); 10196 pp.collectManifestDigest(pkg); 10197 } catch (PackageParserException e) { 10198 res.setError("Failed collect during installPackageLI", e); 10199 return; 10200 } 10201 10202 /* If the installer passed in a manifest digest, compare it now. */ 10203 if (args.manifestDigest != null) { 10204 if (DEBUG_INSTALL) { 10205 final String parsedManifest = pkg.manifestDigest == null ? "null" 10206 : pkg.manifestDigest.toString(); 10207 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10208 + parsedManifest); 10209 } 10210 10211 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10212 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10213 return; 10214 } 10215 } else if (DEBUG_INSTALL) { 10216 final String parsedManifest = pkg.manifestDigest == null 10217 ? "null" : pkg.manifestDigest.toString(); 10218 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10219 } 10220 10221 // Get rid of all references to package scan path via parser. 10222 pp = null; 10223 String oldCodePath = null; 10224 boolean systemApp = false; 10225 synchronized (mPackages) { 10226 // Check whether the newly-scanned package wants to define an already-defined perm 10227 int N = pkg.permissions.size(); 10228 for (int i = N-1; i >= 0; i--) { 10229 PackageParser.Permission perm = pkg.permissions.get(i); 10230 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10231 if (bp != null) { 10232 // If the defining package is signed with our cert, it's okay. This 10233 // also includes the "updating the same package" case, of course. 10234 // "updating same package" could also involve key-rotation. 10235 final boolean sigsOk; 10236 if (!bp.sourcePackage.equals(pkg.packageName) 10237 || !(bp.packageSetting instanceof PackageSetting) 10238 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10239 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10240 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10241 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10242 } else { 10243 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10244 } 10245 if (!sigsOk) { 10246 // If the owning package is the system itself, we log but allow 10247 // install to proceed; we fail the install on all other permission 10248 // redefinitions. 10249 if (!bp.sourcePackage.equals("android")) { 10250 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10251 + pkg.packageName + " attempting to redeclare permission " 10252 + perm.info.name + " already owned by " + bp.sourcePackage); 10253 res.origPermission = perm.info.name; 10254 res.origPackage = bp.sourcePackage; 10255 return; 10256 } else { 10257 Slog.w(TAG, "Package " + pkg.packageName 10258 + " attempting to redeclare system permission " 10259 + perm.info.name + "; ignoring new declaration"); 10260 pkg.permissions.remove(i); 10261 } 10262 } 10263 } 10264 } 10265 10266 // Check if installing already existing package 10267 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10268 String oldName = mSettings.mRenamedPackages.get(pkgName); 10269 if (pkg.mOriginalPackages != null 10270 && pkg.mOriginalPackages.contains(oldName) 10271 && mPackages.containsKey(oldName)) { 10272 // This package is derived from an original package, 10273 // and this device has been updating from that original 10274 // name. We must continue using the original name, so 10275 // rename the new package here. 10276 pkg.setPackageName(oldName); 10277 pkgName = pkg.packageName; 10278 replace = true; 10279 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10280 + oldName + " pkgName=" + pkgName); 10281 } else if (mPackages.containsKey(pkgName)) { 10282 // This package, under its official name, already exists 10283 // on the device; we should replace it. 10284 replace = true; 10285 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10286 } 10287 } 10288 PackageSetting ps = mSettings.mPackages.get(pkgName); 10289 if (ps != null) { 10290 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10291 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10292 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10293 systemApp = (ps.pkg.applicationInfo.flags & 10294 ApplicationInfo.FLAG_SYSTEM) != 0; 10295 } 10296 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10297 } 10298 } 10299 10300 if (systemApp && onSd) { 10301 // Disable updates to system apps on sdcard 10302 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10303 "Cannot install updates to system apps on sdcard"); 10304 return; 10305 } 10306 10307 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10308 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10309 return; 10310 } 10311 10312 if (replace) { 10313 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10314 installerPackageName, res); 10315 } else { 10316 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10317 args.user, installerPackageName, res); 10318 } 10319 synchronized (mPackages) { 10320 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10321 if (ps != null) { 10322 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10323 } 10324 } 10325 } 10326 10327 private static boolean isForwardLocked(PackageParser.Package pkg) { 10328 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10329 } 10330 10331 private static boolean isForwardLocked(ApplicationInfo info) { 10332 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10333 } 10334 10335 private boolean isForwardLocked(PackageSetting ps) { 10336 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10337 } 10338 10339 private static boolean isMultiArch(PackageSetting ps) { 10340 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10341 } 10342 10343 private static boolean isMultiArch(ApplicationInfo info) { 10344 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10345 } 10346 10347 private static boolean isExternal(PackageParser.Package pkg) { 10348 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10349 } 10350 10351 private static boolean isExternal(PackageSetting ps) { 10352 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10353 } 10354 10355 private static boolean isExternal(ApplicationInfo info) { 10356 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10357 } 10358 10359 private static boolean isSystemApp(PackageParser.Package pkg) { 10360 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10361 } 10362 10363 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10364 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10365 } 10366 10367 private static boolean isSystemApp(ApplicationInfo info) { 10368 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10369 } 10370 10371 private static boolean isSystemApp(PackageSetting ps) { 10372 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10373 } 10374 10375 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10376 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10377 } 10378 10379 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10380 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10381 } 10382 10383 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10384 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10385 } 10386 10387 private int packageFlagsToInstallFlags(PackageSetting ps) { 10388 int installFlags = 0; 10389 if (isExternal(ps)) { 10390 installFlags |= PackageManager.INSTALL_EXTERNAL; 10391 } 10392 if (isForwardLocked(ps)) { 10393 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10394 } 10395 return installFlags; 10396 } 10397 10398 private void deleteTempPackageFiles() { 10399 final FilenameFilter filter = new FilenameFilter() { 10400 public boolean accept(File dir, String name) { 10401 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10402 } 10403 }; 10404 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10405 file.delete(); 10406 } 10407 } 10408 10409 @Override 10410 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10411 int flags) { 10412 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10413 flags); 10414 } 10415 10416 @Override 10417 public void deletePackage(final String packageName, 10418 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10419 mContext.enforceCallingOrSelfPermission( 10420 android.Manifest.permission.DELETE_PACKAGES, null); 10421 final int uid = Binder.getCallingUid(); 10422 if (UserHandle.getUserId(uid) != userId) { 10423 mContext.enforceCallingPermission( 10424 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10425 "deletePackage for user " + userId); 10426 } 10427 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10428 try { 10429 observer.onPackageDeleted(packageName, 10430 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10431 } catch (RemoteException re) { 10432 } 10433 return; 10434 } 10435 10436 boolean uninstallBlocked = false; 10437 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10438 int[] users = sUserManager.getUserIds(); 10439 for (int i = 0; i < users.length; ++i) { 10440 if (getBlockUninstallForUser(packageName, users[i])) { 10441 uninstallBlocked = true; 10442 break; 10443 } 10444 } 10445 } else { 10446 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10447 } 10448 if (uninstallBlocked) { 10449 try { 10450 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10451 null); 10452 } catch (RemoteException re) { 10453 } 10454 return; 10455 } 10456 10457 if (DEBUG_REMOVE) { 10458 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10459 } 10460 // Queue up an async operation since the package deletion may take a little while. 10461 mHandler.post(new Runnable() { 10462 public void run() { 10463 mHandler.removeCallbacks(this); 10464 final int returnCode = deletePackageX(packageName, userId, flags); 10465 if (observer != null) { 10466 try { 10467 observer.onPackageDeleted(packageName, returnCode, null); 10468 } catch (RemoteException e) { 10469 Log.i(TAG, "Observer no longer exists."); 10470 } //end catch 10471 } //end if 10472 } //end run 10473 }); 10474 } 10475 10476 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10477 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10478 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10479 try { 10480 if (dpm != null) { 10481 if (dpm.isDeviceOwner(packageName)) { 10482 return true; 10483 } 10484 int[] users; 10485 if (userId == UserHandle.USER_ALL) { 10486 users = sUserManager.getUserIds(); 10487 } else { 10488 users = new int[]{userId}; 10489 } 10490 for (int i = 0; i < users.length; ++i) { 10491 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10492 return true; 10493 } 10494 } 10495 } 10496 } catch (RemoteException e) { 10497 } 10498 return false; 10499 } 10500 10501 /** 10502 * This method is an internal method that could be get invoked either 10503 * to delete an installed package or to clean up a failed installation. 10504 * After deleting an installed package, a broadcast is sent to notify any 10505 * listeners that the package has been installed. For cleaning up a failed 10506 * installation, the broadcast is not necessary since the package's 10507 * installation wouldn't have sent the initial broadcast either 10508 * The key steps in deleting a package are 10509 * deleting the package information in internal structures like mPackages, 10510 * deleting the packages base directories through installd 10511 * updating mSettings to reflect current status 10512 * persisting settings for later use 10513 * sending a broadcast if necessary 10514 */ 10515 private int deletePackageX(String packageName, int userId, int flags) { 10516 final PackageRemovedInfo info = new PackageRemovedInfo(); 10517 final boolean res; 10518 10519 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10520 ? UserHandle.ALL : new UserHandle(userId); 10521 10522 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10523 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10524 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10525 } 10526 10527 boolean removedForAllUsers = false; 10528 boolean systemUpdate = false; 10529 10530 // for the uninstall-updates case and restricted profiles, remember the per- 10531 // userhandle installed state 10532 int[] allUsers; 10533 boolean[] perUserInstalled; 10534 synchronized (mPackages) { 10535 PackageSetting ps = mSettings.mPackages.get(packageName); 10536 allUsers = sUserManager.getUserIds(); 10537 perUserInstalled = new boolean[allUsers.length]; 10538 for (int i = 0; i < allUsers.length; i++) { 10539 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10540 } 10541 } 10542 10543 synchronized (mInstallLock) { 10544 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10545 res = deletePackageLI(packageName, removeForUser, 10546 true, allUsers, perUserInstalled, 10547 flags | REMOVE_CHATTY, info, true); 10548 systemUpdate = info.isRemovedPackageSystemUpdate; 10549 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10550 removedForAllUsers = true; 10551 } 10552 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10553 + " removedForAllUsers=" + removedForAllUsers); 10554 } 10555 10556 if (res) { 10557 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10558 10559 // If the removed package was a system update, the old system package 10560 // was re-enabled; we need to broadcast this information 10561 if (systemUpdate) { 10562 Bundle extras = new Bundle(1); 10563 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10564 ? info.removedAppId : info.uid); 10565 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10566 10567 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10568 extras, null, null, null); 10569 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10570 extras, null, null, null); 10571 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10572 null, packageName, null, null); 10573 } 10574 } 10575 // Force a gc here. 10576 Runtime.getRuntime().gc(); 10577 // Delete the resources here after sending the broadcast to let 10578 // other processes clean up before deleting resources. 10579 if (info.args != null) { 10580 synchronized (mInstallLock) { 10581 info.args.doPostDeleteLI(true); 10582 } 10583 } 10584 10585 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10586 } 10587 10588 static class PackageRemovedInfo { 10589 String removedPackage; 10590 int uid = -1; 10591 int removedAppId = -1; 10592 int[] removedUsers = null; 10593 boolean isRemovedPackageSystemUpdate = false; 10594 // Clean up resources deleted packages. 10595 InstallArgs args = null; 10596 10597 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10598 Bundle extras = new Bundle(1); 10599 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10600 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10601 if (replacing) { 10602 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10603 } 10604 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10605 if (removedPackage != null) { 10606 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10607 extras, null, null, removedUsers); 10608 if (fullRemove && !replacing) { 10609 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10610 extras, null, null, removedUsers); 10611 } 10612 } 10613 if (removedAppId >= 0) { 10614 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10615 removedUsers); 10616 } 10617 } 10618 } 10619 10620 /* 10621 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10622 * flag is not set, the data directory is removed as well. 10623 * make sure this flag is set for partially installed apps. If not its meaningless to 10624 * delete a partially installed application. 10625 */ 10626 private void removePackageDataLI(PackageSetting ps, 10627 int[] allUserHandles, boolean[] perUserInstalled, 10628 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10629 String packageName = ps.name; 10630 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10631 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10632 // Retrieve object to delete permissions for shared user later on 10633 final PackageSetting deletedPs; 10634 // reader 10635 synchronized (mPackages) { 10636 deletedPs = mSettings.mPackages.get(packageName); 10637 if (outInfo != null) { 10638 outInfo.removedPackage = packageName; 10639 outInfo.removedUsers = deletedPs != null 10640 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10641 : null; 10642 } 10643 } 10644 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10645 removeDataDirsLI(packageName); 10646 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10647 } 10648 // writer 10649 synchronized (mPackages) { 10650 if (deletedPs != null) { 10651 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10652 if (outInfo != null) { 10653 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10654 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10655 } 10656 if (deletedPs != null) { 10657 updatePermissionsLPw(deletedPs.name, null, 0); 10658 if (deletedPs.sharedUser != null) { 10659 // remove permissions associated with package 10660 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10661 } 10662 } 10663 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10664 } 10665 // make sure to preserve per-user disabled state if this removal was just 10666 // a downgrade of a system app to the factory package 10667 if (allUserHandles != null && perUserInstalled != null) { 10668 if (DEBUG_REMOVE) { 10669 Slog.d(TAG, "Propagating install state across downgrade"); 10670 } 10671 for (int i = 0; i < allUserHandles.length; i++) { 10672 if (DEBUG_REMOVE) { 10673 Slog.d(TAG, " user " + allUserHandles[i] 10674 + " => " + perUserInstalled[i]); 10675 } 10676 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10677 } 10678 } 10679 } 10680 // can downgrade to reader 10681 if (writeSettings) { 10682 // Save settings now 10683 mSettings.writeLPr(); 10684 } 10685 } 10686 if (outInfo != null) { 10687 // A user ID was deleted here. Go through all users and remove it 10688 // from KeyStore. 10689 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10690 } 10691 } 10692 10693 static boolean locationIsPrivileged(File path) { 10694 try { 10695 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10696 .getCanonicalPath(); 10697 return path.getCanonicalPath().startsWith(privilegedAppDir); 10698 } catch (IOException e) { 10699 Slog.e(TAG, "Unable to access code path " + path); 10700 } 10701 return false; 10702 } 10703 10704 /* 10705 * Tries to delete system package. 10706 */ 10707 private boolean deleteSystemPackageLI(PackageSetting newPs, 10708 int[] allUserHandles, boolean[] perUserInstalled, 10709 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10710 final boolean applyUserRestrictions 10711 = (allUserHandles != null) && (perUserInstalled != null); 10712 PackageSetting disabledPs = null; 10713 // Confirm if the system package has been updated 10714 // An updated system app can be deleted. This will also have to restore 10715 // the system pkg from system partition 10716 // reader 10717 synchronized (mPackages) { 10718 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10719 } 10720 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10721 + " disabledPs=" + disabledPs); 10722 if (disabledPs == null) { 10723 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10724 return false; 10725 } else if (DEBUG_REMOVE) { 10726 Slog.d(TAG, "Deleting system pkg from data partition"); 10727 } 10728 if (DEBUG_REMOVE) { 10729 if (applyUserRestrictions) { 10730 Slog.d(TAG, "Remembering install states:"); 10731 for (int i = 0; i < allUserHandles.length; i++) { 10732 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10733 } 10734 } 10735 } 10736 // Delete the updated package 10737 outInfo.isRemovedPackageSystemUpdate = true; 10738 if (disabledPs.versionCode < newPs.versionCode) { 10739 // Delete data for downgrades 10740 flags &= ~PackageManager.DELETE_KEEP_DATA; 10741 } else { 10742 // Preserve data by setting flag 10743 flags |= PackageManager.DELETE_KEEP_DATA; 10744 } 10745 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10746 allUserHandles, perUserInstalled, outInfo, writeSettings); 10747 if (!ret) { 10748 return false; 10749 } 10750 // writer 10751 synchronized (mPackages) { 10752 // Reinstate the old system package 10753 mSettings.enableSystemPackageLPw(newPs.name); 10754 // Remove any native libraries from the upgraded package. 10755 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10756 } 10757 // Install the system package 10758 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10759 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10760 if (locationIsPrivileged(disabledPs.codePath)) { 10761 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10762 } 10763 10764 final PackageParser.Package newPkg; 10765 try { 10766 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10767 } catch (PackageManagerException e) { 10768 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10769 return false; 10770 } 10771 10772 // writer 10773 synchronized (mPackages) { 10774 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10775 updatePermissionsLPw(newPkg.packageName, newPkg, 10776 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10777 if (applyUserRestrictions) { 10778 if (DEBUG_REMOVE) { 10779 Slog.d(TAG, "Propagating install state across reinstall"); 10780 } 10781 for (int i = 0; i < allUserHandles.length; i++) { 10782 if (DEBUG_REMOVE) { 10783 Slog.d(TAG, " user " + allUserHandles[i] 10784 + " => " + perUserInstalled[i]); 10785 } 10786 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10787 } 10788 // Regardless of writeSettings we need to ensure that this restriction 10789 // state propagation is persisted 10790 mSettings.writeAllUsersPackageRestrictionsLPr(); 10791 } 10792 // can downgrade to reader here 10793 if (writeSettings) { 10794 mSettings.writeLPr(); 10795 } 10796 } 10797 return true; 10798 } 10799 10800 private boolean deleteInstalledPackageLI(PackageSetting ps, 10801 boolean deleteCodeAndResources, int flags, 10802 int[] allUserHandles, boolean[] perUserInstalled, 10803 PackageRemovedInfo outInfo, boolean writeSettings) { 10804 if (outInfo != null) { 10805 outInfo.uid = ps.appId; 10806 } 10807 10808 // Delete package data from internal structures and also remove data if flag is set 10809 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10810 10811 // Delete application code and resources 10812 if (deleteCodeAndResources && (outInfo != null)) { 10813 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10814 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10815 getAppDexInstructionSets(ps)); 10816 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10817 } 10818 return true; 10819 } 10820 10821 @Override 10822 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10823 int userId) { 10824 mContext.enforceCallingOrSelfPermission( 10825 android.Manifest.permission.DELETE_PACKAGES, null); 10826 synchronized (mPackages) { 10827 PackageSetting ps = mSettings.mPackages.get(packageName); 10828 if (ps == null) { 10829 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10830 return false; 10831 } 10832 if (!ps.getInstalled(userId)) { 10833 // Can't block uninstall for an app that is not installed or enabled. 10834 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10835 return false; 10836 } 10837 ps.setBlockUninstall(blockUninstall, userId); 10838 mSettings.writePackageRestrictionsLPr(userId); 10839 } 10840 return true; 10841 } 10842 10843 @Override 10844 public boolean getBlockUninstallForUser(String packageName, int userId) { 10845 synchronized (mPackages) { 10846 PackageSetting ps = mSettings.mPackages.get(packageName); 10847 if (ps == null) { 10848 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10849 return false; 10850 } 10851 return ps.getBlockUninstall(userId); 10852 } 10853 } 10854 10855 /* 10856 * This method handles package deletion in general 10857 */ 10858 private boolean deletePackageLI(String packageName, UserHandle user, 10859 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10860 int flags, PackageRemovedInfo outInfo, 10861 boolean writeSettings) { 10862 if (packageName == null) { 10863 Slog.w(TAG, "Attempt to delete null packageName."); 10864 return false; 10865 } 10866 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10867 PackageSetting ps; 10868 boolean dataOnly = false; 10869 int removeUser = -1; 10870 int appId = -1; 10871 synchronized (mPackages) { 10872 ps = mSettings.mPackages.get(packageName); 10873 if (ps == null) { 10874 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10875 return false; 10876 } 10877 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10878 && user.getIdentifier() != UserHandle.USER_ALL) { 10879 // The caller is asking that the package only be deleted for a single 10880 // user. To do this, we just mark its uninstalled state and delete 10881 // its data. If this is a system app, we only allow this to happen if 10882 // they have set the special DELETE_SYSTEM_APP which requests different 10883 // semantics than normal for uninstalling system apps. 10884 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10885 ps.setUserState(user.getIdentifier(), 10886 COMPONENT_ENABLED_STATE_DEFAULT, 10887 false, //installed 10888 true, //stopped 10889 true, //notLaunched 10890 false, //hidden 10891 null, null, null, 10892 false // blockUninstall 10893 ); 10894 if (!isSystemApp(ps)) { 10895 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10896 // Other user still have this package installed, so all 10897 // we need to do is clear this user's data and save that 10898 // it is uninstalled. 10899 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10900 removeUser = user.getIdentifier(); 10901 appId = ps.appId; 10902 mSettings.writePackageRestrictionsLPr(removeUser); 10903 } else { 10904 // We need to set it back to 'installed' so the uninstall 10905 // broadcasts will be sent correctly. 10906 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10907 ps.setInstalled(true, user.getIdentifier()); 10908 } 10909 } else { 10910 // This is a system app, so we assume that the 10911 // other users still have this package installed, so all 10912 // we need to do is clear this user's data and save that 10913 // it is uninstalled. 10914 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10915 removeUser = user.getIdentifier(); 10916 appId = ps.appId; 10917 mSettings.writePackageRestrictionsLPr(removeUser); 10918 } 10919 } 10920 } 10921 10922 if (removeUser >= 0) { 10923 // From above, we determined that we are deleting this only 10924 // for a single user. Continue the work here. 10925 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10926 if (outInfo != null) { 10927 outInfo.removedPackage = packageName; 10928 outInfo.removedAppId = appId; 10929 outInfo.removedUsers = new int[] {removeUser}; 10930 } 10931 mInstaller.clearUserData(packageName, removeUser); 10932 removeKeystoreDataIfNeeded(removeUser, appId); 10933 schedulePackageCleaning(packageName, removeUser, false); 10934 return true; 10935 } 10936 10937 if (dataOnly) { 10938 // Delete application data first 10939 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10940 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10941 return true; 10942 } 10943 10944 boolean ret = false; 10945 if (isSystemApp(ps)) { 10946 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10947 // When an updated system application is deleted we delete the existing resources as well and 10948 // fall back to existing code in system partition 10949 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10950 flags, outInfo, writeSettings); 10951 } else { 10952 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10953 // Kill application pre-emptively especially for apps on sd. 10954 killApplication(packageName, ps.appId, "uninstall pkg"); 10955 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10956 allUserHandles, perUserInstalled, 10957 outInfo, writeSettings); 10958 } 10959 10960 return ret; 10961 } 10962 10963 private final class ClearStorageConnection implements ServiceConnection { 10964 IMediaContainerService mContainerService; 10965 10966 @Override 10967 public void onServiceConnected(ComponentName name, IBinder service) { 10968 synchronized (this) { 10969 mContainerService = IMediaContainerService.Stub.asInterface(service); 10970 notifyAll(); 10971 } 10972 } 10973 10974 @Override 10975 public void onServiceDisconnected(ComponentName name) { 10976 } 10977 } 10978 10979 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10980 final boolean mounted; 10981 if (Environment.isExternalStorageEmulated()) { 10982 mounted = true; 10983 } else { 10984 final String status = Environment.getExternalStorageState(); 10985 10986 mounted = status.equals(Environment.MEDIA_MOUNTED) 10987 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10988 } 10989 10990 if (!mounted) { 10991 return; 10992 } 10993 10994 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10995 int[] users; 10996 if (userId == UserHandle.USER_ALL) { 10997 users = sUserManager.getUserIds(); 10998 } else { 10999 users = new int[] { userId }; 11000 } 11001 final ClearStorageConnection conn = new ClearStorageConnection(); 11002 if (mContext.bindServiceAsUser( 11003 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11004 try { 11005 for (int curUser : users) { 11006 long timeout = SystemClock.uptimeMillis() + 5000; 11007 synchronized (conn) { 11008 long now = SystemClock.uptimeMillis(); 11009 while (conn.mContainerService == null && now < timeout) { 11010 try { 11011 conn.wait(timeout - now); 11012 } catch (InterruptedException e) { 11013 } 11014 } 11015 } 11016 if (conn.mContainerService == null) { 11017 return; 11018 } 11019 11020 final UserEnvironment userEnv = new UserEnvironment(curUser); 11021 clearDirectory(conn.mContainerService, 11022 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11023 if (allData) { 11024 clearDirectory(conn.mContainerService, 11025 userEnv.buildExternalStorageAppDataDirs(packageName)); 11026 clearDirectory(conn.mContainerService, 11027 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11028 } 11029 } 11030 } finally { 11031 mContext.unbindService(conn); 11032 } 11033 } 11034 } 11035 11036 @Override 11037 public void clearApplicationUserData(final String packageName, 11038 final IPackageDataObserver observer, final int userId) { 11039 mContext.enforceCallingOrSelfPermission( 11040 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11041 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11042 // Queue up an async operation since the package deletion may take a little while. 11043 mHandler.post(new Runnable() { 11044 public void run() { 11045 mHandler.removeCallbacks(this); 11046 final boolean succeeded; 11047 synchronized (mInstallLock) { 11048 succeeded = clearApplicationUserDataLI(packageName, userId); 11049 } 11050 clearExternalStorageDataSync(packageName, userId, true); 11051 if (succeeded) { 11052 // invoke DeviceStorageMonitor's update method to clear any notifications 11053 DeviceStorageMonitorInternal 11054 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11055 if (dsm != null) { 11056 dsm.checkMemory(); 11057 } 11058 } 11059 if(observer != null) { 11060 try { 11061 observer.onRemoveCompleted(packageName, succeeded); 11062 } catch (RemoteException e) { 11063 Log.i(TAG, "Observer no longer exists."); 11064 } 11065 } //end if observer 11066 } //end run 11067 }); 11068 } 11069 11070 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11071 if (packageName == null) { 11072 Slog.w(TAG, "Attempt to delete null packageName."); 11073 return false; 11074 } 11075 11076 // Try finding details about the requested package 11077 PackageParser.Package pkg; 11078 synchronized (mPackages) { 11079 pkg = mPackages.get(packageName); 11080 if (pkg == null) { 11081 final PackageSetting ps = mSettings.mPackages.get(packageName); 11082 if (ps != null) { 11083 pkg = ps.pkg; 11084 } 11085 } 11086 } 11087 11088 if (pkg == null) { 11089 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11090 } 11091 11092 // Always delete data directories for package, even if we found no other 11093 // record of app. This helps users recover from UID mismatches without 11094 // resorting to a full data wipe. 11095 int retCode = mInstaller.clearUserData(packageName, userId); 11096 if (retCode < 0) { 11097 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11098 return false; 11099 } 11100 11101 if (pkg == null) { 11102 return false; 11103 } 11104 11105 if (pkg != null && pkg.applicationInfo != null) { 11106 final int appId = pkg.applicationInfo.uid; 11107 removeKeystoreDataIfNeeded(userId, appId); 11108 } 11109 11110 // Create a native library symlink only if we have native libraries 11111 // and if the native libraries are 32 bit libraries. We do not provide 11112 // this symlink for 64 bit libraries. 11113 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11114 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11115 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11116 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11117 Slog.w(TAG, "Failed linking native library dir"); 11118 return false; 11119 } 11120 } 11121 11122 return true; 11123 } 11124 11125 /** 11126 * Remove entries from the keystore daemon. Will only remove it if the 11127 * {@code appId} is valid. 11128 */ 11129 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11130 if (appId < 0) { 11131 return; 11132 } 11133 11134 final KeyStore keyStore = KeyStore.getInstance(); 11135 if (keyStore != null) { 11136 if (userId == UserHandle.USER_ALL) { 11137 for (final int individual : sUserManager.getUserIds()) { 11138 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11139 } 11140 } else { 11141 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11142 } 11143 } else { 11144 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11145 } 11146 } 11147 11148 @Override 11149 public void deleteApplicationCacheFiles(final String packageName, 11150 final IPackageDataObserver observer) { 11151 mContext.enforceCallingOrSelfPermission( 11152 android.Manifest.permission.DELETE_CACHE_FILES, null); 11153 // Queue up an async operation since the package deletion may take a little while. 11154 final int userId = UserHandle.getCallingUserId(); 11155 mHandler.post(new Runnable() { 11156 public void run() { 11157 mHandler.removeCallbacks(this); 11158 final boolean succeded; 11159 synchronized (mInstallLock) { 11160 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11161 } 11162 clearExternalStorageDataSync(packageName, userId, false); 11163 if(observer != null) { 11164 try { 11165 observer.onRemoveCompleted(packageName, succeded); 11166 } catch (RemoteException e) { 11167 Log.i(TAG, "Observer no longer exists."); 11168 } 11169 } //end if observer 11170 } //end run 11171 }); 11172 } 11173 11174 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11175 if (packageName == null) { 11176 Slog.w(TAG, "Attempt to delete null packageName."); 11177 return false; 11178 } 11179 PackageParser.Package p; 11180 synchronized (mPackages) { 11181 p = mPackages.get(packageName); 11182 } 11183 if (p == null) { 11184 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11185 return false; 11186 } 11187 final ApplicationInfo applicationInfo = p.applicationInfo; 11188 if (applicationInfo == null) { 11189 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11190 return false; 11191 } 11192 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11193 if (retCode < 0) { 11194 Slog.w(TAG, "Couldn't remove cache files for package: " 11195 + packageName + " u" + userId); 11196 return false; 11197 } 11198 return true; 11199 } 11200 11201 @Override 11202 public void getPackageSizeInfo(final String packageName, int userHandle, 11203 final IPackageStatsObserver observer) { 11204 mContext.enforceCallingOrSelfPermission( 11205 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11206 if (packageName == null) { 11207 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11208 } 11209 11210 PackageStats stats = new PackageStats(packageName, userHandle); 11211 11212 /* 11213 * Queue up an async operation since the package measurement may take a 11214 * little while. 11215 */ 11216 Message msg = mHandler.obtainMessage(INIT_COPY); 11217 msg.obj = new MeasureParams(stats, observer); 11218 mHandler.sendMessage(msg); 11219 } 11220 11221 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11222 PackageStats pStats) { 11223 if (packageName == null) { 11224 Slog.w(TAG, "Attempt to get size of null packageName."); 11225 return false; 11226 } 11227 PackageParser.Package p; 11228 boolean dataOnly = false; 11229 String libDirRoot = null; 11230 String asecPath = null; 11231 PackageSetting ps = null; 11232 synchronized (mPackages) { 11233 p = mPackages.get(packageName); 11234 ps = mSettings.mPackages.get(packageName); 11235 if(p == null) { 11236 dataOnly = true; 11237 if((ps == null) || (ps.pkg == null)) { 11238 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11239 return false; 11240 } 11241 p = ps.pkg; 11242 } 11243 if (ps != null) { 11244 libDirRoot = ps.legacyNativeLibraryPathString; 11245 } 11246 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11247 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11248 if (secureContainerId != null) { 11249 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11250 } 11251 } 11252 } 11253 String publicSrcDir = null; 11254 if(!dataOnly) { 11255 final ApplicationInfo applicationInfo = p.applicationInfo; 11256 if (applicationInfo == null) { 11257 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11258 return false; 11259 } 11260 if (isForwardLocked(p)) { 11261 publicSrcDir = applicationInfo.getBaseResourcePath(); 11262 } 11263 } 11264 // TODO: extend to measure size of split APKs 11265 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11266 // not just the first level. 11267 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11268 // just the primary. 11269 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11270 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11271 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11272 if (res < 0) { 11273 return false; 11274 } 11275 11276 // Fix-up for forward-locked applications in ASEC containers. 11277 if (!isExternal(p)) { 11278 pStats.codeSize += pStats.externalCodeSize; 11279 pStats.externalCodeSize = 0L; 11280 } 11281 11282 return true; 11283 } 11284 11285 11286 @Override 11287 public void addPackageToPreferred(String packageName) { 11288 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11289 } 11290 11291 @Override 11292 public void removePackageFromPreferred(String packageName) { 11293 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11294 } 11295 11296 @Override 11297 public List<PackageInfo> getPreferredPackages(int flags) { 11298 return new ArrayList<PackageInfo>(); 11299 } 11300 11301 private int getUidTargetSdkVersionLockedLPr(int uid) { 11302 Object obj = mSettings.getUserIdLPr(uid); 11303 if (obj instanceof SharedUserSetting) { 11304 final SharedUserSetting sus = (SharedUserSetting) obj; 11305 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11306 final Iterator<PackageSetting> it = sus.packages.iterator(); 11307 while (it.hasNext()) { 11308 final PackageSetting ps = it.next(); 11309 if (ps.pkg != null) { 11310 int v = ps.pkg.applicationInfo.targetSdkVersion; 11311 if (v < vers) vers = v; 11312 } 11313 } 11314 return vers; 11315 } else if (obj instanceof PackageSetting) { 11316 final PackageSetting ps = (PackageSetting) obj; 11317 if (ps.pkg != null) { 11318 return ps.pkg.applicationInfo.targetSdkVersion; 11319 } 11320 } 11321 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11322 } 11323 11324 @Override 11325 public void addPreferredActivity(IntentFilter filter, int match, 11326 ComponentName[] set, ComponentName activity, int userId) { 11327 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11328 "Adding preferred"); 11329 } 11330 11331 private void addPreferredActivityInternal(IntentFilter filter, int match, 11332 ComponentName[] set, ComponentName activity, boolean always, int userId, 11333 String opname) { 11334 // writer 11335 int callingUid = Binder.getCallingUid(); 11336 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11337 if (filter.countActions() == 0) { 11338 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11339 return; 11340 } 11341 synchronized (mPackages) { 11342 if (mContext.checkCallingOrSelfPermission( 11343 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11344 != PackageManager.PERMISSION_GRANTED) { 11345 if (getUidTargetSdkVersionLockedLPr(callingUid) 11346 < Build.VERSION_CODES.FROYO) { 11347 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11348 + callingUid); 11349 return; 11350 } 11351 mContext.enforceCallingOrSelfPermission( 11352 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11353 } 11354 11355 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11356 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11357 + userId + ":"); 11358 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11359 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11360 mSettings.writePackageRestrictionsLPr(userId); 11361 } 11362 } 11363 11364 @Override 11365 public void replacePreferredActivity(IntentFilter filter, int match, 11366 ComponentName[] set, ComponentName activity, int userId) { 11367 if (filter.countActions() != 1) { 11368 throw new IllegalArgumentException( 11369 "replacePreferredActivity expects filter to have only 1 action."); 11370 } 11371 if (filter.countDataAuthorities() != 0 11372 || filter.countDataPaths() != 0 11373 || filter.countDataSchemes() > 1 11374 || filter.countDataTypes() != 0) { 11375 throw new IllegalArgumentException( 11376 "replacePreferredActivity expects filter to have no data authorities, " + 11377 "paths, or types; and at most one scheme."); 11378 } 11379 11380 final int callingUid = Binder.getCallingUid(); 11381 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11382 synchronized (mPackages) { 11383 if (mContext.checkCallingOrSelfPermission( 11384 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11385 != PackageManager.PERMISSION_GRANTED) { 11386 if (getUidTargetSdkVersionLockedLPr(callingUid) 11387 < Build.VERSION_CODES.FROYO) { 11388 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11389 + Binder.getCallingUid()); 11390 return; 11391 } 11392 mContext.enforceCallingOrSelfPermission( 11393 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11394 } 11395 11396 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11397 if (pir != null) { 11398 // Get all of the existing entries that exactly match this filter. 11399 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11400 if (existing != null && existing.size() == 1) { 11401 PreferredActivity cur = existing.get(0); 11402 if (DEBUG_PREFERRED) { 11403 Slog.i(TAG, "Checking replace of preferred:"); 11404 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11405 if (!cur.mPref.mAlways) { 11406 Slog.i(TAG, " -- CUR; not mAlways!"); 11407 } else { 11408 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11409 Slog.i(TAG, " -- CUR: mSet=" 11410 + Arrays.toString(cur.mPref.mSetComponents)); 11411 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11412 Slog.i(TAG, " -- NEW: mMatch=" 11413 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11414 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11415 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11416 } 11417 } 11418 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11419 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11420 && cur.mPref.sameSet(set)) { 11421 // Setting the preferred activity to what it happens to be already 11422 if (DEBUG_PREFERRED) { 11423 Slog.i(TAG, "Replacing with same preferred activity " 11424 + cur.mPref.mShortComponent + " for user " 11425 + userId + ":"); 11426 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11427 } 11428 return; 11429 } 11430 } 11431 11432 if (existing != null) { 11433 if (DEBUG_PREFERRED) { 11434 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11435 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11436 } 11437 for (int i = 0; i < existing.size(); i++) { 11438 PreferredActivity pa = existing.get(i); 11439 if (DEBUG_PREFERRED) { 11440 Slog.i(TAG, "Removing existing preferred activity " 11441 + pa.mPref.mComponent + ":"); 11442 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11443 } 11444 pir.removeFilter(pa); 11445 } 11446 } 11447 } 11448 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11449 "Replacing preferred"); 11450 } 11451 } 11452 11453 @Override 11454 public void clearPackagePreferredActivities(String packageName) { 11455 final int uid = Binder.getCallingUid(); 11456 // writer 11457 synchronized (mPackages) { 11458 PackageParser.Package pkg = mPackages.get(packageName); 11459 if (pkg == null || pkg.applicationInfo.uid != uid) { 11460 if (mContext.checkCallingOrSelfPermission( 11461 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11462 != PackageManager.PERMISSION_GRANTED) { 11463 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11464 < Build.VERSION_CODES.FROYO) { 11465 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11466 + Binder.getCallingUid()); 11467 return; 11468 } 11469 mContext.enforceCallingOrSelfPermission( 11470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11471 } 11472 } 11473 11474 int user = UserHandle.getCallingUserId(); 11475 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11476 mSettings.writePackageRestrictionsLPr(user); 11477 scheduleWriteSettingsLocked(); 11478 } 11479 } 11480 } 11481 11482 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11483 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11484 ArrayList<PreferredActivity> removed = null; 11485 boolean changed = false; 11486 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11487 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11488 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11489 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11490 continue; 11491 } 11492 Iterator<PreferredActivity> it = pir.filterIterator(); 11493 while (it.hasNext()) { 11494 PreferredActivity pa = it.next(); 11495 // Mark entry for removal only if it matches the package name 11496 // and the entry is of type "always". 11497 if (packageName == null || 11498 (pa.mPref.mComponent.getPackageName().equals(packageName) 11499 && pa.mPref.mAlways)) { 11500 if (removed == null) { 11501 removed = new ArrayList<PreferredActivity>(); 11502 } 11503 removed.add(pa); 11504 } 11505 } 11506 if (removed != null) { 11507 for (int j=0; j<removed.size(); j++) { 11508 PreferredActivity pa = removed.get(j); 11509 pir.removeFilter(pa); 11510 } 11511 changed = true; 11512 } 11513 } 11514 return changed; 11515 } 11516 11517 @Override 11518 public void resetPreferredActivities(int userId) { 11519 /* TODO: Actually use userId. Why is it being passed in? */ 11520 mContext.enforceCallingOrSelfPermission( 11521 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11522 // writer 11523 synchronized (mPackages) { 11524 int user = UserHandle.getCallingUserId(); 11525 clearPackagePreferredActivitiesLPw(null, user); 11526 mSettings.readDefaultPreferredAppsLPw(this, user); 11527 mSettings.writePackageRestrictionsLPr(user); 11528 scheduleWriteSettingsLocked(); 11529 } 11530 } 11531 11532 @Override 11533 public int getPreferredActivities(List<IntentFilter> outFilters, 11534 List<ComponentName> outActivities, String packageName) { 11535 11536 int num = 0; 11537 final int userId = UserHandle.getCallingUserId(); 11538 // reader 11539 synchronized (mPackages) { 11540 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11541 if (pir != null) { 11542 final Iterator<PreferredActivity> it = pir.filterIterator(); 11543 while (it.hasNext()) { 11544 final PreferredActivity pa = it.next(); 11545 if (packageName == null 11546 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11547 && pa.mPref.mAlways)) { 11548 if (outFilters != null) { 11549 outFilters.add(new IntentFilter(pa)); 11550 } 11551 if (outActivities != null) { 11552 outActivities.add(pa.mPref.mComponent); 11553 } 11554 } 11555 } 11556 } 11557 } 11558 11559 return num; 11560 } 11561 11562 @Override 11563 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11564 int userId) { 11565 int callingUid = Binder.getCallingUid(); 11566 if (callingUid != Process.SYSTEM_UID) { 11567 throw new SecurityException( 11568 "addPersistentPreferredActivity can only be run by the system"); 11569 } 11570 if (filter.countActions() == 0) { 11571 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11572 return; 11573 } 11574 synchronized (mPackages) { 11575 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11576 " :"); 11577 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11578 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11579 new PersistentPreferredActivity(filter, activity)); 11580 mSettings.writePackageRestrictionsLPr(userId); 11581 } 11582 } 11583 11584 @Override 11585 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11586 int callingUid = Binder.getCallingUid(); 11587 if (callingUid != Process.SYSTEM_UID) { 11588 throw new SecurityException( 11589 "clearPackagePersistentPreferredActivities can only be run by the system"); 11590 } 11591 ArrayList<PersistentPreferredActivity> removed = null; 11592 boolean changed = false; 11593 synchronized (mPackages) { 11594 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11595 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11596 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11597 .valueAt(i); 11598 if (userId != thisUserId) { 11599 continue; 11600 } 11601 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11602 while (it.hasNext()) { 11603 PersistentPreferredActivity ppa = it.next(); 11604 // Mark entry for removal only if it matches the package name. 11605 if (ppa.mComponent.getPackageName().equals(packageName)) { 11606 if (removed == null) { 11607 removed = new ArrayList<PersistentPreferredActivity>(); 11608 } 11609 removed.add(ppa); 11610 } 11611 } 11612 if (removed != null) { 11613 for (int j=0; j<removed.size(); j++) { 11614 PersistentPreferredActivity ppa = removed.get(j); 11615 ppir.removeFilter(ppa); 11616 } 11617 changed = true; 11618 } 11619 } 11620 11621 if (changed) { 11622 mSettings.writePackageRestrictionsLPr(userId); 11623 } 11624 } 11625 } 11626 11627 @Override 11628 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11629 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11630 mContext.enforceCallingOrSelfPermission( 11631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11632 int callingUid = Binder.getCallingUid(); 11633 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11634 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11635 if (intentFilter.countActions() == 0) { 11636 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11637 return; 11638 } 11639 synchronized (mPackages) { 11640 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11641 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11642 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11643 mSettings.writePackageRestrictionsLPr(sourceUserId); 11644 } 11645 } 11646 11647 @Override 11648 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11649 int ownerUserId) { 11650 mContext.enforceCallingOrSelfPermission( 11651 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11652 int callingUid = Binder.getCallingUid(); 11653 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11654 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11655 int callingUserId = UserHandle.getUserId(callingUid); 11656 synchronized (mPackages) { 11657 CrossProfileIntentResolver resolver = 11658 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11659 HashSet<CrossProfileIntentFilter> set = 11660 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11661 for (CrossProfileIntentFilter filter : set) { 11662 if (filter.getOwnerPackage().equals(ownerPackage) 11663 && filter.getOwnerUserId() == callingUserId) { 11664 resolver.removeFilter(filter); 11665 } 11666 } 11667 mSettings.writePackageRestrictionsLPr(sourceUserId); 11668 } 11669 } 11670 11671 // Enforcing that callingUid is owning pkg on userId 11672 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11673 // The system owns everything. 11674 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11675 return; 11676 } 11677 int callingUserId = UserHandle.getUserId(callingUid); 11678 if (callingUserId != userId) { 11679 throw new SecurityException("calling uid " + callingUid 11680 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11681 + callingUserId); 11682 } 11683 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11684 if (pi == null) { 11685 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11686 + callingUserId); 11687 } 11688 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11689 throw new SecurityException("Calling uid " + callingUid 11690 + " does not own package " + pkg); 11691 } 11692 } 11693 11694 @Override 11695 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11696 Intent intent = new Intent(Intent.ACTION_MAIN); 11697 intent.addCategory(Intent.CATEGORY_HOME); 11698 11699 final int callingUserId = UserHandle.getCallingUserId(); 11700 List<ResolveInfo> list = queryIntentActivities(intent, null, 11701 PackageManager.GET_META_DATA, callingUserId); 11702 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11703 true, false, false, callingUserId); 11704 11705 allHomeCandidates.clear(); 11706 if (list != null) { 11707 for (ResolveInfo ri : list) { 11708 allHomeCandidates.add(ri); 11709 } 11710 } 11711 return (preferred == null || preferred.activityInfo == null) 11712 ? null 11713 : new ComponentName(preferred.activityInfo.packageName, 11714 preferred.activityInfo.name); 11715 } 11716 11717 @Override 11718 public void setApplicationEnabledSetting(String appPackageName, 11719 int newState, int flags, int userId, String callingPackage) { 11720 if (!sUserManager.exists(userId)) return; 11721 if (callingPackage == null) { 11722 callingPackage = Integer.toString(Binder.getCallingUid()); 11723 } 11724 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11725 } 11726 11727 @Override 11728 public void setComponentEnabledSetting(ComponentName componentName, 11729 int newState, int flags, int userId) { 11730 if (!sUserManager.exists(userId)) return; 11731 setEnabledSetting(componentName.getPackageName(), 11732 componentName.getClassName(), newState, flags, userId, null); 11733 } 11734 11735 private void setEnabledSetting(final String packageName, String className, int newState, 11736 final int flags, int userId, String callingPackage) { 11737 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11738 || newState == COMPONENT_ENABLED_STATE_ENABLED 11739 || newState == COMPONENT_ENABLED_STATE_DISABLED 11740 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11741 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11742 throw new IllegalArgumentException("Invalid new component state: " 11743 + newState); 11744 } 11745 PackageSetting pkgSetting; 11746 final int uid = Binder.getCallingUid(); 11747 final int permission = mContext.checkCallingOrSelfPermission( 11748 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11749 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11750 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11751 boolean sendNow = false; 11752 boolean isApp = (className == null); 11753 String componentName = isApp ? packageName : className; 11754 int packageUid = -1; 11755 ArrayList<String> components; 11756 11757 // writer 11758 synchronized (mPackages) { 11759 pkgSetting = mSettings.mPackages.get(packageName); 11760 if (pkgSetting == null) { 11761 if (className == null) { 11762 throw new IllegalArgumentException( 11763 "Unknown package: " + packageName); 11764 } 11765 throw new IllegalArgumentException( 11766 "Unknown component: " + packageName 11767 + "/" + className); 11768 } 11769 // Allow root and verify that userId is not being specified by a different user 11770 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11771 throw new SecurityException( 11772 "Permission Denial: attempt to change component state from pid=" 11773 + Binder.getCallingPid() 11774 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11775 } 11776 if (className == null) { 11777 // We're dealing with an application/package level state change 11778 if (pkgSetting.getEnabled(userId) == newState) { 11779 // Nothing to do 11780 return; 11781 } 11782 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11783 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11784 // Don't care about who enables an app. 11785 callingPackage = null; 11786 } 11787 pkgSetting.setEnabled(newState, userId, callingPackage); 11788 // pkgSetting.pkg.mSetEnabled = newState; 11789 } else { 11790 // We're dealing with a component level state change 11791 // First, verify that this is a valid class name. 11792 PackageParser.Package pkg = pkgSetting.pkg; 11793 if (pkg == null || !pkg.hasComponentClassName(className)) { 11794 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11795 throw new IllegalArgumentException("Component class " + className 11796 + " does not exist in " + packageName); 11797 } else { 11798 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11799 + className + " does not exist in " + packageName); 11800 } 11801 } 11802 switch (newState) { 11803 case COMPONENT_ENABLED_STATE_ENABLED: 11804 if (!pkgSetting.enableComponentLPw(className, userId)) { 11805 return; 11806 } 11807 break; 11808 case COMPONENT_ENABLED_STATE_DISABLED: 11809 if (!pkgSetting.disableComponentLPw(className, userId)) { 11810 return; 11811 } 11812 break; 11813 case COMPONENT_ENABLED_STATE_DEFAULT: 11814 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11815 return; 11816 } 11817 break; 11818 default: 11819 Slog.e(TAG, "Invalid new component state: " + newState); 11820 return; 11821 } 11822 } 11823 mSettings.writePackageRestrictionsLPr(userId); 11824 components = mPendingBroadcasts.get(userId, packageName); 11825 final boolean newPackage = components == null; 11826 if (newPackage) { 11827 components = new ArrayList<String>(); 11828 } 11829 if (!components.contains(componentName)) { 11830 components.add(componentName); 11831 } 11832 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11833 sendNow = true; 11834 // Purge entry from pending broadcast list if another one exists already 11835 // since we are sending one right away. 11836 mPendingBroadcasts.remove(userId, packageName); 11837 } else { 11838 if (newPackage) { 11839 mPendingBroadcasts.put(userId, packageName, components); 11840 } 11841 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11842 // Schedule a message 11843 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11844 } 11845 } 11846 } 11847 11848 long callingId = Binder.clearCallingIdentity(); 11849 try { 11850 if (sendNow) { 11851 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11852 sendPackageChangedBroadcast(packageName, 11853 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11854 } 11855 } finally { 11856 Binder.restoreCallingIdentity(callingId); 11857 } 11858 } 11859 11860 private void sendPackageChangedBroadcast(String packageName, 11861 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11862 if (DEBUG_INSTALL) 11863 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11864 + componentNames); 11865 Bundle extras = new Bundle(4); 11866 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11867 String nameList[] = new String[componentNames.size()]; 11868 componentNames.toArray(nameList); 11869 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11870 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11871 extras.putInt(Intent.EXTRA_UID, packageUid); 11872 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11873 new int[] {UserHandle.getUserId(packageUid)}); 11874 } 11875 11876 @Override 11877 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11878 if (!sUserManager.exists(userId)) return; 11879 final int uid = Binder.getCallingUid(); 11880 final int permission = mContext.checkCallingOrSelfPermission( 11881 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11882 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11883 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 11884 // writer 11885 synchronized (mPackages) { 11886 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11887 uid, userId)) { 11888 scheduleWritePackageRestrictionsLocked(userId); 11889 } 11890 } 11891 } 11892 11893 @Override 11894 public String getInstallerPackageName(String packageName) { 11895 // reader 11896 synchronized (mPackages) { 11897 return mSettings.getInstallerPackageNameLPr(packageName); 11898 } 11899 } 11900 11901 @Override 11902 public int getApplicationEnabledSetting(String packageName, int userId) { 11903 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11904 int uid = Binder.getCallingUid(); 11905 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 11906 // reader 11907 synchronized (mPackages) { 11908 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11909 } 11910 } 11911 11912 @Override 11913 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11914 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11915 int uid = Binder.getCallingUid(); 11916 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 11917 // reader 11918 synchronized (mPackages) { 11919 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11920 } 11921 } 11922 11923 @Override 11924 public void enterSafeMode() { 11925 enforceSystemOrRoot("Only the system can request entering safe mode"); 11926 11927 if (!mSystemReady) { 11928 mSafeMode = true; 11929 } 11930 } 11931 11932 @Override 11933 public void systemReady() { 11934 mSystemReady = true; 11935 11936 // Read the compatibilty setting when the system is ready. 11937 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11938 mContext.getContentResolver(), 11939 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11940 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11941 if (DEBUG_SETTINGS) { 11942 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11943 } 11944 11945 synchronized (mPackages) { 11946 // Verify that all of the preferred activity components actually 11947 // exist. It is possible for applications to be updated and at 11948 // that point remove a previously declared activity component that 11949 // had been set as a preferred activity. We try to clean this up 11950 // the next time we encounter that preferred activity, but it is 11951 // possible for the user flow to never be able to return to that 11952 // situation so here we do a sanity check to make sure we haven't 11953 // left any junk around. 11954 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11955 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11956 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11957 removed.clear(); 11958 for (PreferredActivity pa : pir.filterSet()) { 11959 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11960 removed.add(pa); 11961 } 11962 } 11963 if (removed.size() > 0) { 11964 for (int r=0; r<removed.size(); r++) { 11965 PreferredActivity pa = removed.get(r); 11966 Slog.w(TAG, "Removing dangling preferred activity: " 11967 + pa.mPref.mComponent); 11968 pir.removeFilter(pa); 11969 } 11970 mSettings.writePackageRestrictionsLPr( 11971 mSettings.mPreferredActivities.keyAt(i)); 11972 } 11973 } 11974 } 11975 sUserManager.systemReady(); 11976 11977 // Kick off any messages waiting for system ready 11978 if (mPostSystemReadyMessages != null) { 11979 for (Message msg : mPostSystemReadyMessages) { 11980 msg.sendToTarget(); 11981 } 11982 mPostSystemReadyMessages = null; 11983 } 11984 } 11985 11986 @Override 11987 public boolean isSafeMode() { 11988 return mSafeMode; 11989 } 11990 11991 @Override 11992 public boolean hasSystemUidErrors() { 11993 return mHasSystemUidErrors; 11994 } 11995 11996 static String arrayToString(int[] array) { 11997 StringBuffer buf = new StringBuffer(128); 11998 buf.append('['); 11999 if (array != null) { 12000 for (int i=0; i<array.length; i++) { 12001 if (i > 0) buf.append(", "); 12002 buf.append(array[i]); 12003 } 12004 } 12005 buf.append(']'); 12006 return buf.toString(); 12007 } 12008 12009 static class DumpState { 12010 public static final int DUMP_LIBS = 1 << 0; 12011 public static final int DUMP_FEATURES = 1 << 1; 12012 public static final int DUMP_RESOLVERS = 1 << 2; 12013 public static final int DUMP_PERMISSIONS = 1 << 3; 12014 public static final int DUMP_PACKAGES = 1 << 4; 12015 public static final int DUMP_SHARED_USERS = 1 << 5; 12016 public static final int DUMP_MESSAGES = 1 << 6; 12017 public static final int DUMP_PROVIDERS = 1 << 7; 12018 public static final int DUMP_VERIFIERS = 1 << 8; 12019 public static final int DUMP_PREFERRED = 1 << 9; 12020 public static final int DUMP_PREFERRED_XML = 1 << 10; 12021 public static final int DUMP_KEYSETS = 1 << 11; 12022 public static final int DUMP_VERSION = 1 << 12; 12023 public static final int DUMP_INSTALLS = 1 << 13; 12024 12025 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12026 12027 private int mTypes; 12028 12029 private int mOptions; 12030 12031 private boolean mTitlePrinted; 12032 12033 private SharedUserSetting mSharedUser; 12034 12035 public boolean isDumping(int type) { 12036 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12037 return true; 12038 } 12039 12040 return (mTypes & type) != 0; 12041 } 12042 12043 public void setDump(int type) { 12044 mTypes |= type; 12045 } 12046 12047 public boolean isOptionEnabled(int option) { 12048 return (mOptions & option) != 0; 12049 } 12050 12051 public void setOptionEnabled(int option) { 12052 mOptions |= option; 12053 } 12054 12055 public boolean onTitlePrinted() { 12056 final boolean printed = mTitlePrinted; 12057 mTitlePrinted = true; 12058 return printed; 12059 } 12060 12061 public boolean getTitlePrinted() { 12062 return mTitlePrinted; 12063 } 12064 12065 public void setTitlePrinted(boolean enabled) { 12066 mTitlePrinted = enabled; 12067 } 12068 12069 public SharedUserSetting getSharedUser() { 12070 return mSharedUser; 12071 } 12072 12073 public void setSharedUser(SharedUserSetting user) { 12074 mSharedUser = user; 12075 } 12076 } 12077 12078 @Override 12079 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12080 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12081 != PackageManager.PERMISSION_GRANTED) { 12082 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12083 + Binder.getCallingPid() 12084 + ", uid=" + Binder.getCallingUid() 12085 + " without permission " 12086 + android.Manifest.permission.DUMP); 12087 return; 12088 } 12089 12090 DumpState dumpState = new DumpState(); 12091 boolean fullPreferred = false; 12092 boolean checkin = false; 12093 12094 String packageName = null; 12095 12096 int opti = 0; 12097 while (opti < args.length) { 12098 String opt = args[opti]; 12099 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12100 break; 12101 } 12102 opti++; 12103 if ("-a".equals(opt)) { 12104 // Right now we only know how to print all. 12105 } else if ("-h".equals(opt)) { 12106 pw.println("Package manager dump options:"); 12107 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12108 pw.println(" --checkin: dump for a checkin"); 12109 pw.println(" -f: print details of intent filters"); 12110 pw.println(" -h: print this help"); 12111 pw.println(" cmd may be one of:"); 12112 pw.println(" l[ibraries]: list known shared libraries"); 12113 pw.println(" f[ibraries]: list device features"); 12114 pw.println(" k[eysets]: print known keysets"); 12115 pw.println(" r[esolvers]: dump intent resolvers"); 12116 pw.println(" perm[issions]: dump permissions"); 12117 pw.println(" pref[erred]: print preferred package settings"); 12118 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12119 pw.println(" prov[iders]: dump content providers"); 12120 pw.println(" p[ackages]: dump installed packages"); 12121 pw.println(" s[hared-users]: dump shared user IDs"); 12122 pw.println(" m[essages]: print collected runtime messages"); 12123 pw.println(" v[erifiers]: print package verifier info"); 12124 pw.println(" version: print database version info"); 12125 pw.println(" write: write current settings now"); 12126 pw.println(" <package.name>: info about given package"); 12127 pw.println(" installs: details about install sessions"); 12128 return; 12129 } else if ("--checkin".equals(opt)) { 12130 checkin = true; 12131 } else if ("-f".equals(opt)) { 12132 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12133 } else { 12134 pw.println("Unknown argument: " + opt + "; use -h for help"); 12135 } 12136 } 12137 12138 // Is the caller requesting to dump a particular piece of data? 12139 if (opti < args.length) { 12140 String cmd = args[opti]; 12141 opti++; 12142 // Is this a package name? 12143 if ("android".equals(cmd) || cmd.contains(".")) { 12144 packageName = cmd; 12145 // When dumping a single package, we always dump all of its 12146 // filter information since the amount of data will be reasonable. 12147 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12148 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12149 dumpState.setDump(DumpState.DUMP_LIBS); 12150 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12151 dumpState.setDump(DumpState.DUMP_FEATURES); 12152 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12153 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12154 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12155 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12156 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12157 dumpState.setDump(DumpState.DUMP_PREFERRED); 12158 } else if ("preferred-xml".equals(cmd)) { 12159 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12160 if (opti < args.length && "--full".equals(args[opti])) { 12161 fullPreferred = true; 12162 opti++; 12163 } 12164 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12165 dumpState.setDump(DumpState.DUMP_PACKAGES); 12166 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12167 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12168 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12169 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12170 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12171 dumpState.setDump(DumpState.DUMP_MESSAGES); 12172 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12173 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12174 } else if ("version".equals(cmd)) { 12175 dumpState.setDump(DumpState.DUMP_VERSION); 12176 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12177 dumpState.setDump(DumpState.DUMP_KEYSETS); 12178 } else if ("installs".equals(cmd)) { 12179 dumpState.setDump(DumpState.DUMP_INSTALLS); 12180 } else if ("write".equals(cmd)) { 12181 synchronized (mPackages) { 12182 mSettings.writeLPr(); 12183 pw.println("Settings written."); 12184 return; 12185 } 12186 } 12187 } 12188 12189 if (checkin) { 12190 pw.println("vers,1"); 12191 } 12192 12193 // reader 12194 synchronized (mPackages) { 12195 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12196 if (!checkin) { 12197 if (dumpState.onTitlePrinted()) 12198 pw.println(); 12199 pw.println("Database versions:"); 12200 pw.print(" SDK Version:"); 12201 pw.print(" internal="); 12202 pw.print(mSettings.mInternalSdkPlatform); 12203 pw.print(" external="); 12204 pw.println(mSettings.mExternalSdkPlatform); 12205 pw.print(" DB Version:"); 12206 pw.print(" internal="); 12207 pw.print(mSettings.mInternalDatabaseVersion); 12208 pw.print(" external="); 12209 pw.println(mSettings.mExternalDatabaseVersion); 12210 } 12211 } 12212 12213 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12214 if (!checkin) { 12215 if (dumpState.onTitlePrinted()) 12216 pw.println(); 12217 pw.println("Verifiers:"); 12218 pw.print(" Required: "); 12219 pw.print(mRequiredVerifierPackage); 12220 pw.print(" (uid="); 12221 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12222 pw.println(")"); 12223 } else if (mRequiredVerifierPackage != null) { 12224 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12225 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12226 } 12227 } 12228 12229 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12230 boolean printedHeader = false; 12231 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12232 while (it.hasNext()) { 12233 String name = it.next(); 12234 SharedLibraryEntry ent = mSharedLibraries.get(name); 12235 if (!checkin) { 12236 if (!printedHeader) { 12237 if (dumpState.onTitlePrinted()) 12238 pw.println(); 12239 pw.println("Libraries:"); 12240 printedHeader = true; 12241 } 12242 pw.print(" "); 12243 } else { 12244 pw.print("lib,"); 12245 } 12246 pw.print(name); 12247 if (!checkin) { 12248 pw.print(" -> "); 12249 } 12250 if (ent.path != null) { 12251 if (!checkin) { 12252 pw.print("(jar) "); 12253 pw.print(ent.path); 12254 } else { 12255 pw.print(",jar,"); 12256 pw.print(ent.path); 12257 } 12258 } else { 12259 if (!checkin) { 12260 pw.print("(apk) "); 12261 pw.print(ent.apk); 12262 } else { 12263 pw.print(",apk,"); 12264 pw.print(ent.apk); 12265 } 12266 } 12267 pw.println(); 12268 } 12269 } 12270 12271 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12272 if (dumpState.onTitlePrinted()) 12273 pw.println(); 12274 if (!checkin) { 12275 pw.println("Features:"); 12276 } 12277 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12278 while (it.hasNext()) { 12279 String name = it.next(); 12280 if (!checkin) { 12281 pw.print(" "); 12282 } else { 12283 pw.print("feat,"); 12284 } 12285 pw.println(name); 12286 } 12287 } 12288 12289 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12290 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12291 : "Activity Resolver Table:", " ", packageName, 12292 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12293 dumpState.setTitlePrinted(true); 12294 } 12295 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12296 : "Receiver Resolver Table:", " ", packageName, 12297 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12298 dumpState.setTitlePrinted(true); 12299 } 12300 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12301 : "Service Resolver Table:", " ", packageName, 12302 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12303 dumpState.setTitlePrinted(true); 12304 } 12305 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12306 : "Provider Resolver Table:", " ", packageName, 12307 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12308 dumpState.setTitlePrinted(true); 12309 } 12310 } 12311 12312 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12313 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12314 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12315 int user = mSettings.mPreferredActivities.keyAt(i); 12316 if (pir.dump(pw, 12317 dumpState.getTitlePrinted() 12318 ? "\nPreferred Activities User " + user + ":" 12319 : "Preferred Activities User " + user + ":", " ", 12320 packageName, true)) { 12321 dumpState.setTitlePrinted(true); 12322 } 12323 } 12324 } 12325 12326 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12327 pw.flush(); 12328 FileOutputStream fout = new FileOutputStream(fd); 12329 BufferedOutputStream str = new BufferedOutputStream(fout); 12330 XmlSerializer serializer = new FastXmlSerializer(); 12331 try { 12332 serializer.setOutput(str, "utf-8"); 12333 serializer.startDocument(null, true); 12334 serializer.setFeature( 12335 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12336 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12337 serializer.endDocument(); 12338 serializer.flush(); 12339 } catch (IllegalArgumentException e) { 12340 pw.println("Failed writing: " + e); 12341 } catch (IllegalStateException e) { 12342 pw.println("Failed writing: " + e); 12343 } catch (IOException e) { 12344 pw.println("Failed writing: " + e); 12345 } 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12349 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12350 if (packageName == null) { 12351 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12352 if (iperm == 0) { 12353 if (dumpState.onTitlePrinted()) 12354 pw.println(); 12355 pw.println("AppOp Permissions:"); 12356 } 12357 pw.print(" AppOp Permission "); 12358 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12359 pw.println(":"); 12360 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12361 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12362 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12363 } 12364 } 12365 } 12366 } 12367 12368 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12369 boolean printedSomething = false; 12370 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12371 if (packageName != null && !packageName.equals(p.info.packageName)) { 12372 continue; 12373 } 12374 if (!printedSomething) { 12375 if (dumpState.onTitlePrinted()) 12376 pw.println(); 12377 pw.println("Registered ContentProviders:"); 12378 printedSomething = true; 12379 } 12380 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12381 pw.print(" "); pw.println(p.toString()); 12382 } 12383 printedSomething = false; 12384 for (Map.Entry<String, PackageParser.Provider> entry : 12385 mProvidersByAuthority.entrySet()) { 12386 PackageParser.Provider p = entry.getValue(); 12387 if (packageName != null && !packageName.equals(p.info.packageName)) { 12388 continue; 12389 } 12390 if (!printedSomething) { 12391 if (dumpState.onTitlePrinted()) 12392 pw.println(); 12393 pw.println("ContentProvider Authorities:"); 12394 printedSomething = true; 12395 } 12396 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12397 pw.print(" "); pw.println(p.toString()); 12398 if (p.info != null && p.info.applicationInfo != null) { 12399 final String appInfo = p.info.applicationInfo.toString(); 12400 pw.print(" applicationInfo="); pw.println(appInfo); 12401 } 12402 } 12403 } 12404 12405 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12406 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12407 } 12408 12409 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12410 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12411 } 12412 12413 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12414 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12415 } 12416 12417 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12418 // XXX should handle packageName != null by dumping only install data that 12419 // the given package is involved with. 12420 if (dumpState.onTitlePrinted()) pw.println(); 12421 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12422 } 12423 12424 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12425 if (dumpState.onTitlePrinted()) pw.println(); 12426 mSettings.dumpReadMessagesLPr(pw, dumpState); 12427 12428 pw.println(); 12429 pw.println("Package warning messages:"); 12430 final File fname = getSettingsProblemFile(); 12431 FileInputStream in = null; 12432 try { 12433 in = new FileInputStream(fname); 12434 final int avail = in.available(); 12435 final byte[] data = new byte[avail]; 12436 in.read(data); 12437 pw.print(new String(data)); 12438 } catch (FileNotFoundException e) { 12439 } catch (IOException e) { 12440 } finally { 12441 if (in != null) { 12442 try { 12443 in.close(); 12444 } catch (IOException e) { 12445 } 12446 } 12447 } 12448 } 12449 } 12450 } 12451 12452 // ------- apps on sdcard specific code ------- 12453 static final boolean DEBUG_SD_INSTALL = false; 12454 12455 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12456 12457 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12458 12459 private boolean mMediaMounted = false; 12460 12461 static String getEncryptKey() { 12462 try { 12463 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12464 SD_ENCRYPTION_KEYSTORE_NAME); 12465 if (sdEncKey == null) { 12466 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12467 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12468 if (sdEncKey == null) { 12469 Slog.e(TAG, "Failed to create encryption keys"); 12470 return null; 12471 } 12472 } 12473 return sdEncKey; 12474 } catch (NoSuchAlgorithmException nsae) { 12475 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12476 return null; 12477 } catch (IOException ioe) { 12478 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12479 return null; 12480 } 12481 } 12482 12483 /* 12484 * Update media status on PackageManager. 12485 */ 12486 @Override 12487 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12488 int callingUid = Binder.getCallingUid(); 12489 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12490 throw new SecurityException("Media status can only be updated by the system"); 12491 } 12492 // reader; this apparently protects mMediaMounted, but should probably 12493 // be a different lock in that case. 12494 synchronized (mPackages) { 12495 Log.i(TAG, "Updating external media status from " 12496 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12497 + (mediaStatus ? "mounted" : "unmounted")); 12498 if (DEBUG_SD_INSTALL) 12499 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12500 + ", mMediaMounted=" + mMediaMounted); 12501 if (mediaStatus == mMediaMounted) { 12502 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12503 : 0, -1); 12504 mHandler.sendMessage(msg); 12505 return; 12506 } 12507 mMediaMounted = mediaStatus; 12508 } 12509 // Queue up an async operation since the package installation may take a 12510 // little while. 12511 mHandler.post(new Runnable() { 12512 public void run() { 12513 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12514 } 12515 }); 12516 } 12517 12518 /** 12519 * Called by MountService when the initial ASECs to scan are available. 12520 * Should block until all the ASEC containers are finished being scanned. 12521 */ 12522 public void scanAvailableAsecs() { 12523 updateExternalMediaStatusInner(true, false, false); 12524 if (mShouldRestoreconData) { 12525 SELinuxMMAC.setRestoreconDone(); 12526 mShouldRestoreconData = false; 12527 } 12528 } 12529 12530 /* 12531 * Collect information of applications on external media, map them against 12532 * existing containers and update information based on current mount status. 12533 * Please note that we always have to report status if reportStatus has been 12534 * set to true especially when unloading packages. 12535 */ 12536 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12537 boolean externalStorage) { 12538 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12539 int[] uidArr = EmptyArray.INT; 12540 12541 final String[] list = PackageHelper.getSecureContainerList(); 12542 if (ArrayUtils.isEmpty(list)) { 12543 Log.i(TAG, "No secure containers found"); 12544 } else { 12545 // Process list of secure containers and categorize them 12546 // as active or stale based on their package internal state. 12547 12548 // reader 12549 synchronized (mPackages) { 12550 for (String cid : list) { 12551 // Leave stages untouched for now; installer service owns them 12552 if (PackageInstallerService.isStageName(cid)) continue; 12553 12554 if (DEBUG_SD_INSTALL) 12555 Log.i(TAG, "Processing container " + cid); 12556 String pkgName = getAsecPackageName(cid); 12557 if (pkgName == null) { 12558 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12559 continue; 12560 } 12561 if (DEBUG_SD_INSTALL) 12562 Log.i(TAG, "Looking for pkg : " + pkgName); 12563 12564 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12565 if (ps == null) { 12566 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12567 continue; 12568 } 12569 12570 /* 12571 * Skip packages that are not external if we're unmounting 12572 * external storage. 12573 */ 12574 if (externalStorage && !isMounted && !isExternal(ps)) { 12575 continue; 12576 } 12577 12578 final AsecInstallArgs args = new AsecInstallArgs(cid, 12579 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12580 // The package status is changed only if the code path 12581 // matches between settings and the container id. 12582 if (ps.codePathString != null 12583 && ps.codePathString.startsWith(args.getCodePath())) { 12584 if (DEBUG_SD_INSTALL) { 12585 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12586 + " at code path: " + ps.codePathString); 12587 } 12588 12589 // We do have a valid package installed on sdcard 12590 processCids.put(args, ps.codePathString); 12591 final int uid = ps.appId; 12592 if (uid != -1) { 12593 uidArr = ArrayUtils.appendInt(uidArr, uid); 12594 } 12595 } else { 12596 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12597 + ps.codePathString); 12598 } 12599 } 12600 } 12601 12602 Arrays.sort(uidArr); 12603 } 12604 12605 // Process packages with valid entries. 12606 if (isMounted) { 12607 if (DEBUG_SD_INSTALL) 12608 Log.i(TAG, "Loading packages"); 12609 loadMediaPackages(processCids, uidArr); 12610 startCleaningPackages(); 12611 mInstallerService.onSecureContainersAvailable(); 12612 } else { 12613 if (DEBUG_SD_INSTALL) 12614 Log.i(TAG, "Unloading packages"); 12615 unloadMediaPackages(processCids, uidArr, reportStatus); 12616 } 12617 } 12618 12619 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12620 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12621 int size = pkgList.size(); 12622 if (size > 0) { 12623 // Send broadcasts here 12624 Bundle extras = new Bundle(); 12625 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12626 .toArray(new String[size])); 12627 if (uidArr != null) { 12628 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12629 } 12630 if (replacing) { 12631 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12632 } 12633 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12634 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12635 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12636 } 12637 } 12638 12639 /* 12640 * Look at potentially valid container ids from processCids If package 12641 * information doesn't match the one on record or package scanning fails, 12642 * the cid is added to list of removeCids. We currently don't delete stale 12643 * containers. 12644 */ 12645 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12646 ArrayList<String> pkgList = new ArrayList<String>(); 12647 Set<AsecInstallArgs> keys = processCids.keySet(); 12648 12649 for (AsecInstallArgs args : keys) { 12650 String codePath = processCids.get(args); 12651 if (DEBUG_SD_INSTALL) 12652 Log.i(TAG, "Loading container : " + args.cid); 12653 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12654 try { 12655 // Make sure there are no container errors first. 12656 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12657 Slog.e(TAG, "Failed to mount cid : " + args.cid 12658 + " when installing from sdcard"); 12659 continue; 12660 } 12661 // Check code path here. 12662 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12663 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12664 + " does not match one in settings " + codePath); 12665 continue; 12666 } 12667 // Parse package 12668 int parseFlags = mDefParseFlags; 12669 if (args.isExternal()) { 12670 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12671 } 12672 if (args.isFwdLocked()) { 12673 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12674 } 12675 12676 synchronized (mInstallLock) { 12677 PackageParser.Package pkg = null; 12678 try { 12679 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12680 } catch (PackageManagerException e) { 12681 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12682 } 12683 // Scan the package 12684 if (pkg != null) { 12685 /* 12686 * TODO why is the lock being held? doPostInstall is 12687 * called in other places without the lock. This needs 12688 * to be straightened out. 12689 */ 12690 // writer 12691 synchronized (mPackages) { 12692 retCode = PackageManager.INSTALL_SUCCEEDED; 12693 pkgList.add(pkg.packageName); 12694 // Post process args 12695 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12696 pkg.applicationInfo.uid); 12697 } 12698 } else { 12699 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12700 } 12701 } 12702 12703 } finally { 12704 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12705 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12706 } 12707 } 12708 } 12709 // writer 12710 synchronized (mPackages) { 12711 // If the platform SDK has changed since the last time we booted, 12712 // we need to re-grant app permission to catch any new ones that 12713 // appear. This is really a hack, and means that apps can in some 12714 // cases get permissions that the user didn't initially explicitly 12715 // allow... it would be nice to have some better way to handle 12716 // this situation. 12717 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12718 if (regrantPermissions) 12719 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12720 + mSdkVersion + "; regranting permissions for external storage"); 12721 mSettings.mExternalSdkPlatform = mSdkVersion; 12722 12723 // Make sure group IDs have been assigned, and any permission 12724 // changes in other apps are accounted for 12725 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12726 | (regrantPermissions 12727 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12728 : 0)); 12729 12730 mSettings.updateExternalDatabaseVersion(); 12731 12732 // can downgrade to reader 12733 // Persist settings 12734 mSettings.writeLPr(); 12735 } 12736 // Send a broadcast to let everyone know we are done processing 12737 if (pkgList.size() > 0) { 12738 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12739 } 12740 } 12741 12742 /* 12743 * Utility method to unload a list of specified containers 12744 */ 12745 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12746 // Just unmount all valid containers. 12747 for (AsecInstallArgs arg : cidArgs) { 12748 synchronized (mInstallLock) { 12749 arg.doPostDeleteLI(false); 12750 } 12751 } 12752 } 12753 12754 /* 12755 * Unload packages mounted on external media. This involves deleting package 12756 * data from internal structures, sending broadcasts about diabled packages, 12757 * gc'ing to free up references, unmounting all secure containers 12758 * corresponding to packages on external media, and posting a 12759 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12760 * that we always have to post this message if status has been requested no 12761 * matter what. 12762 */ 12763 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12764 final boolean reportStatus) { 12765 if (DEBUG_SD_INSTALL) 12766 Log.i(TAG, "unloading media packages"); 12767 ArrayList<String> pkgList = new ArrayList<String>(); 12768 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12769 final Set<AsecInstallArgs> keys = processCids.keySet(); 12770 for (AsecInstallArgs args : keys) { 12771 String pkgName = args.getPackageName(); 12772 if (DEBUG_SD_INSTALL) 12773 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12774 // Delete package internally 12775 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12776 synchronized (mInstallLock) { 12777 boolean res = deletePackageLI(pkgName, null, false, null, null, 12778 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12779 if (res) { 12780 pkgList.add(pkgName); 12781 } else { 12782 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12783 failedList.add(args); 12784 } 12785 } 12786 } 12787 12788 // reader 12789 synchronized (mPackages) { 12790 // We didn't update the settings after removing each package; 12791 // write them now for all packages. 12792 mSettings.writeLPr(); 12793 } 12794 12795 // We have to absolutely send UPDATED_MEDIA_STATUS only 12796 // after confirming that all the receivers processed the ordered 12797 // broadcast when packages get disabled, force a gc to clean things up. 12798 // and unload all the containers. 12799 if (pkgList.size() > 0) { 12800 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12801 new IIntentReceiver.Stub() { 12802 public void performReceive(Intent intent, int resultCode, String data, 12803 Bundle extras, boolean ordered, boolean sticky, 12804 int sendingUser) throws RemoteException { 12805 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12806 reportStatus ? 1 : 0, 1, keys); 12807 mHandler.sendMessage(msg); 12808 } 12809 }); 12810 } else { 12811 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12812 keys); 12813 mHandler.sendMessage(msg); 12814 } 12815 } 12816 12817 /** Binder call */ 12818 @Override 12819 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12820 final int flags) { 12821 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12822 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12823 int returnCode = PackageManager.MOVE_SUCCEEDED; 12824 int currInstallFlags = 0; 12825 int newInstallFlags = 0; 12826 12827 File codeFile = null; 12828 String installerPackageName = null; 12829 String packageAbiOverride = null; 12830 12831 // reader 12832 synchronized (mPackages) { 12833 final PackageParser.Package pkg = mPackages.get(packageName); 12834 final PackageSetting ps = mSettings.mPackages.get(packageName); 12835 if (pkg == null || ps == null) { 12836 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12837 } else { 12838 // Disable moving fwd locked apps and system packages 12839 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12840 Slog.w(TAG, "Cannot move system application"); 12841 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12842 } else if (pkg.mOperationPending) { 12843 Slog.w(TAG, "Attempt to move package which has pending operations"); 12844 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12845 } else { 12846 // Find install location first 12847 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12848 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12849 Slog.w(TAG, "Ambigous flags specified for move location."); 12850 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12851 } else { 12852 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12853 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12854 currInstallFlags = isExternal(pkg) 12855 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12856 12857 if (newInstallFlags == currInstallFlags) { 12858 Slog.w(TAG, "No move required. Trying to move to same location"); 12859 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12860 } else { 12861 if (isForwardLocked(pkg)) { 12862 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12863 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12864 } 12865 } 12866 } 12867 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12868 pkg.mOperationPending = true; 12869 } 12870 } 12871 12872 codeFile = new File(pkg.codePath); 12873 installerPackageName = ps.installerPackageName; 12874 packageAbiOverride = ps.cpuAbiOverrideString; 12875 } 12876 } 12877 12878 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12879 try { 12880 observer.packageMoved(packageName, returnCode); 12881 } catch (RemoteException ignored) { 12882 } 12883 return; 12884 } 12885 12886 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12887 @Override 12888 public void onUserActionRequired(Intent intent) throws RemoteException { 12889 throw new IllegalStateException(); 12890 } 12891 12892 @Override 12893 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12894 Bundle extras) throws RemoteException { 12895 Slog.d(TAG, "Install result for move: " 12896 + PackageManager.installStatusToString(returnCode, msg)); 12897 12898 // We usually have a new package now after the install, but if 12899 // we failed we need to clear the pending flag on the original 12900 // package object. 12901 synchronized (mPackages) { 12902 final PackageParser.Package pkg = mPackages.get(packageName); 12903 if (pkg != null) { 12904 pkg.mOperationPending = false; 12905 } 12906 } 12907 12908 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12909 switch (status) { 12910 case PackageInstaller.STATUS_SUCCESS: 12911 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12912 break; 12913 case PackageInstaller.STATUS_FAILURE_STORAGE: 12914 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12915 break; 12916 default: 12917 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12918 break; 12919 } 12920 } 12921 }; 12922 12923 // Treat a move like reinstalling an existing app, which ensures that we 12924 // process everythign uniformly, like unpacking native libraries. 12925 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12926 12927 final Message msg = mHandler.obtainMessage(INIT_COPY); 12928 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12929 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12930 installerPackageName, null, user, packageAbiOverride); 12931 mHandler.sendMessage(msg); 12932 } 12933 12934 @Override 12935 public boolean setInstallLocation(int loc) { 12936 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12937 null); 12938 if (getInstallLocation() == loc) { 12939 return true; 12940 } 12941 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12942 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12943 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12944 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12945 return true; 12946 } 12947 return false; 12948 } 12949 12950 @Override 12951 public int getInstallLocation() { 12952 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12953 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12954 PackageHelper.APP_INSTALL_AUTO); 12955 } 12956 12957 /** Called by UserManagerService */ 12958 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12959 mDirtyUsers.remove(userHandle); 12960 mSettings.removeUserLPw(userHandle); 12961 mPendingBroadcasts.remove(userHandle); 12962 if (mInstaller != null) { 12963 // Technically, we shouldn't be doing this with the package lock 12964 // held. However, this is very rare, and there is already so much 12965 // other disk I/O going on, that we'll let it slide for now. 12966 mInstaller.removeUserDataDirs(userHandle); 12967 } 12968 mUserNeedsBadging.delete(userHandle); 12969 removeUnusedPackagesLILPw(userManager, userHandle); 12970 } 12971 12972 /** 12973 * We're removing userHandle and would like to remove any downloaded packages 12974 * that are no longer in use by any other user. 12975 * @param userHandle the user being removed 12976 */ 12977 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 12978 final boolean DEBUG_CLEAN_APKS = false; 12979 int [] users = userManager.getUserIdsLPr(); 12980 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 12981 while (psit.hasNext()) { 12982 PackageSetting ps = psit.next(); 12983 if (ps.pkg == null) { 12984 continue; 12985 } 12986 final String packageName = ps.pkg.packageName; 12987 // Skip over if system app 12988 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12989 continue; 12990 } 12991 if (DEBUG_CLEAN_APKS) { 12992 Slog.i(TAG, "Checking package " + packageName); 12993 } 12994 boolean keep = false; 12995 for (int i = 0; i < users.length; i++) { 12996 if (users[i] != userHandle && ps.getInstalled(users[i])) { 12997 keep = true; 12998 if (DEBUG_CLEAN_APKS) { 12999 Slog.i(TAG, " Keeping package " + packageName + " for user " 13000 + users[i]); 13001 } 13002 break; 13003 } 13004 } 13005 if (!keep) { 13006 if (DEBUG_CLEAN_APKS) { 13007 Slog.i(TAG, " Removing package " + packageName); 13008 } 13009 mHandler.post(new Runnable() { 13010 public void run() { 13011 deletePackageX(packageName, userHandle, 0); 13012 } //end run 13013 }); 13014 } 13015 } 13016 } 13017 13018 /** Called by UserManagerService */ 13019 void createNewUserLILPw(int userHandle, File path) { 13020 if (mInstaller != null) { 13021 mInstaller.createUserConfig(userHandle); 13022 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13023 } 13024 } 13025 13026 @Override 13027 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13028 mContext.enforceCallingOrSelfPermission( 13029 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13030 "Only package verification agents can read the verifier device identity"); 13031 13032 synchronized (mPackages) { 13033 return mSettings.getVerifierDeviceIdentityLPw(); 13034 } 13035 } 13036 13037 @Override 13038 public void setPermissionEnforced(String permission, boolean enforced) { 13039 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13040 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13041 synchronized (mPackages) { 13042 if (mSettings.mReadExternalStorageEnforced == null 13043 || mSettings.mReadExternalStorageEnforced != enforced) { 13044 mSettings.mReadExternalStorageEnforced = enforced; 13045 mSettings.writeLPr(); 13046 } 13047 } 13048 // kill any non-foreground processes so we restart them and 13049 // grant/revoke the GID. 13050 final IActivityManager am = ActivityManagerNative.getDefault(); 13051 if (am != null) { 13052 final long token = Binder.clearCallingIdentity(); 13053 try { 13054 am.killProcessesBelowForeground("setPermissionEnforcement"); 13055 } catch (RemoteException e) { 13056 } finally { 13057 Binder.restoreCallingIdentity(token); 13058 } 13059 } 13060 } else { 13061 throw new IllegalArgumentException("No selective enforcement for " + permission); 13062 } 13063 } 13064 13065 @Override 13066 @Deprecated 13067 public boolean isPermissionEnforced(String permission) { 13068 return true; 13069 } 13070 13071 @Override 13072 public boolean isStorageLow() { 13073 final long token = Binder.clearCallingIdentity(); 13074 try { 13075 final DeviceStorageMonitorInternal 13076 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13077 if (dsm != null) { 13078 return dsm.isMemoryLow(); 13079 } else { 13080 return false; 13081 } 13082 } finally { 13083 Binder.restoreCallingIdentity(token); 13084 } 13085 } 13086 13087 @Override 13088 public IPackageInstaller getPackageInstaller() { 13089 return mInstallerService; 13090 } 13091 13092 private boolean userNeedsBadging(int userId) { 13093 int index = mUserNeedsBadging.indexOfKey(userId); 13094 if (index < 0) { 13095 final UserInfo userInfo; 13096 final long token = Binder.clearCallingIdentity(); 13097 try { 13098 userInfo = sUserManager.getUserInfo(userId); 13099 } finally { 13100 Binder.restoreCallingIdentity(token); 13101 } 13102 final boolean b; 13103 if (userInfo != null && userInfo.isManagedProfile()) { 13104 b = true; 13105 } else { 13106 b = false; 13107 } 13108 mUserNeedsBadging.put(userId, b); 13109 return b; 13110 } 13111 return mUserNeedsBadging.valueAt(index); 13112 } 13113 13114 @Override 13115 public KeySet getKeySetByAlias(String packageName, String alias) { 13116 if (packageName == null || alias == null) { 13117 return null; 13118 } 13119 synchronized(mPackages) { 13120 final PackageParser.Package pkg = mPackages.get(packageName); 13121 if (pkg == null) { 13122 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13123 throw new IllegalArgumentException("Unknown package: " + packageName); 13124 } 13125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13126 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13127 } 13128 } 13129 13130 @Override 13131 public KeySet getSigningKeySet(String packageName) { 13132 if (packageName == null) { 13133 return null; 13134 } 13135 synchronized(mPackages) { 13136 final PackageParser.Package pkg = mPackages.get(packageName); 13137 if (pkg == null) { 13138 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13139 throw new IllegalArgumentException("Unknown package: " + packageName); 13140 } 13141 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13142 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13143 throw new SecurityException("May not access signing KeySet of other apps."); 13144 } 13145 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13146 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13147 } 13148 } 13149 13150 @Override 13151 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13152 if (packageName == null || ks == null) { 13153 return false; 13154 } 13155 synchronized(mPackages) { 13156 final PackageParser.Package pkg = mPackages.get(packageName); 13157 if (pkg == null) { 13158 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13159 throw new IllegalArgumentException("Unknown package: " + packageName); 13160 } 13161 IBinder ksh = ks.getToken(); 13162 if (ksh instanceof KeySetHandle) { 13163 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13164 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13165 } 13166 return false; 13167 } 13168 } 13169 13170 @Override 13171 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13172 if (packageName == null || ks == null) { 13173 return false; 13174 } 13175 synchronized(mPackages) { 13176 final PackageParser.Package pkg = mPackages.get(packageName); 13177 if (pkg == null) { 13178 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13179 throw new IllegalArgumentException("Unknown package: " + packageName); 13180 } 13181 IBinder ksh = ks.getToken(); 13182 if (ksh instanceof KeySetHandle) { 13183 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13184 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13185 } 13186 return false; 13187 } 13188 } 13189} 13190