PackageManagerService.java revision ce85d7f44f5c88dcc18a19738bfcd20d9dbb4a78
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.AppGlobals; 84import android.app.IActivityManager; 85import android.app.admin.IDevicePolicyManager; 86import android.app.backup.IBackupManager; 87import android.content.BroadcastReceiver; 88import android.content.ComponentName; 89import android.content.Context; 90import android.content.IIntentReceiver; 91import android.content.Intent; 92import android.content.IntentFilter; 93import android.content.IntentSender; 94import android.content.IntentSender.SendIntentException; 95import android.content.ServiceConnection; 96import android.content.pm.ActivityInfo; 97import android.content.pm.ApplicationInfo; 98import android.content.pm.FeatureInfo; 99import android.content.pm.IPackageDataObserver; 100import android.content.pm.IPackageDeleteObserver; 101import android.content.pm.IPackageDeleteObserver2; 102import android.content.pm.IPackageInstallObserver2; 103import android.content.pm.IPackageInstaller; 104import android.content.pm.IPackageManager; 105import android.content.pm.IPackageMoveObserver; 106import android.content.pm.IPackageStatsObserver; 107import android.content.pm.InstrumentationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.storage.StorageManager; 142import android.os.Debug; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.util.ArraySet; 165import android.util.AtomicFile; 166import android.util.DisplayMetrics; 167import android.util.EventLog; 168import android.util.ExceptionUtils; 169import android.util.Log; 170import android.util.LogPrinter; 171import android.util.PrintStreamPrinter; 172import android.util.Slog; 173import android.util.SparseArray; 174import android.util.SparseBooleanArray; 175import android.view.Display; 176 177import java.io.BufferedInputStream; 178import java.io.BufferedOutputStream; 179import java.io.BufferedReader; 180import java.io.File; 181import java.io.FileDescriptor; 182import java.io.FileInputStream; 183import java.io.FileNotFoundException; 184import java.io.FileOutputStream; 185import java.io.FileReader; 186import java.io.FilenameFilter; 187import java.io.IOException; 188import java.io.InputStream; 189import java.io.PrintWriter; 190import java.nio.charset.StandardCharsets; 191import java.security.NoSuchAlgorithmException; 192import java.security.PublicKey; 193import java.security.cert.CertificateEncodingException; 194import java.security.cert.CertificateException; 195import java.text.SimpleDateFormat; 196import java.util.ArrayList; 197import java.util.Arrays; 198import java.util.Collection; 199import java.util.Collections; 200import java.util.Comparator; 201import java.util.Date; 202import java.util.HashMap; 203import java.util.HashSet; 204import java.util.Iterator; 205import java.util.List; 206import java.util.Map; 207import java.util.Objects; 208import java.util.Set; 209import java.util.concurrent.atomic.AtomicBoolean; 210import java.util.concurrent.atomic.AtomicLong; 211 212import dalvik.system.DexFile; 213import dalvik.system.StaleDexCacheError; 214import dalvik.system.VMRuntime; 215 216import libcore.io.IoUtils; 217import libcore.util.EmptyArray; 218 219/** 220 * Keep track of all those .apks everywhere. 221 * 222 * This is very central to the platform's security; please run the unit 223 * tests whenever making modifications here: 224 * 225mmm frameworks/base/tests/AndroidTests 226adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 227adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 228 * 229 * {@hide} 230 */ 231public class PackageManagerService extends IPackageManager.Stub { 232 static final String TAG = "PackageManager"; 233 static final boolean DEBUG_SETTINGS = false; 234 static final boolean DEBUG_PREFERRED = false; 235 static final boolean DEBUG_UPGRADE = false; 236 private static final boolean DEBUG_INSTALL = false; 237 private static final boolean DEBUG_REMOVE = false; 238 private static final boolean DEBUG_BROADCASTS = false; 239 private static final boolean DEBUG_SHOW_INFO = false; 240 private static final boolean DEBUG_PACKAGE_INFO = false; 241 private static final boolean DEBUG_INTENT_MATCHING = false; 242 private static final boolean DEBUG_PACKAGE_SCANNING = false; 243 private static final boolean DEBUG_VERIFY = false; 244 private static final boolean DEBUG_DEXOPT = false; 245 private static final boolean DEBUG_ABI_SELECTION = false; 246 247 private static final int RADIO_UID = Process.PHONE_UID; 248 private static final int LOG_UID = Process.LOG_UID; 249 private static final int NFC_UID = Process.NFC_UID; 250 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 251 private static final int SHELL_UID = Process.SHELL_UID; 252 253 // Cap the size of permission trees that 3rd party apps can define 254 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 255 256 // Suffix used during package installation when copying/moving 257 // package apks to install directory. 258 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 259 260 static final int SCAN_NO_DEX = 1<<1; 261 static final int SCAN_FORCE_DEX = 1<<2; 262 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 263 static final int SCAN_NEW_INSTALL = 1<<4; 264 static final int SCAN_NO_PATHS = 1<<5; 265 static final int SCAN_UPDATE_TIME = 1<<6; 266 static final int SCAN_DEFER_DEX = 1<<7; 267 static final int SCAN_BOOTING = 1<<8; 268 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 269 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 270 static final int SCAN_REPLACING = 1<<11; 271 272 static final int REMOVE_CHATTY = 1<<16; 273 274 /** 275 * Timeout (in milliseconds) after which the watchdog should declare that 276 * our handler thread is wedged. The usual default for such things is one 277 * minute but we sometimes do very lengthy I/O operations on this thread, 278 * such as installing multi-gigabyte applications, so ours needs to be longer. 279 */ 280 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 281 282 /** 283 * Whether verification is enabled by default. 284 */ 285 private static final boolean DEFAULT_VERIFY_ENABLE = true; 286 287 /** 288 * The default maximum time to wait for the verification agent to return in 289 * milliseconds. 290 */ 291 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 292 293 /** 294 * The default response for package verification timeout. 295 * 296 * This can be either PackageManager.VERIFICATION_ALLOW or 297 * PackageManager.VERIFICATION_REJECT. 298 */ 299 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 300 301 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 302 303 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 304 DEFAULT_CONTAINER_PACKAGE, 305 "com.android.defcontainer.DefaultContainerService"); 306 307 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 308 309 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 310 311 private static String sPreferredInstructionSet; 312 313 final ServiceThread mHandlerThread; 314 315 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 316 private static final String IDMAP_SUFFIX = "@idmap"; 317 318 final PackageHandler mHandler; 319 320 /** 321 * Messages for {@link #mHandler} that need to wait for system ready before 322 * being dispatched. 323 */ 324 private ArrayList<Message> mPostSystemReadyMessages; 325 326 final int mSdkVersion = Build.VERSION.SDK_INT; 327 328 final Context mContext; 329 final boolean mFactoryTest; 330 final boolean mOnlyCore; 331 final boolean mLazyDexOpt; 332 final DisplayMetrics mMetrics; 333 final int mDefParseFlags; 334 final String[] mSeparateProcesses; 335 336 // This is where all application persistent data goes. 337 final File mAppDataDir; 338 339 // This is where all application persistent data goes for secondary users. 340 final File mUserAppDataDir; 341 342 /** The location for ASEC container files on internal storage. */ 343 final String mAsecInternalPath; 344 345 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 346 // LOCK HELD. Can be called with mInstallLock held. 347 final Installer mInstaller; 348 349 /** Directory where installed third-party apps stored */ 350 final File mAppInstallDir; 351 352 /** 353 * Directory to which applications installed internally have their 354 * 32 bit native libraries copied. 355 */ 356 private File mAppLib32InstallDir; 357 358 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 359 // apps. 360 final File mDrmAppPrivateInstallDir; 361 362 // ---------------------------------------------------------------- 363 364 // Lock for state used when installing and doing other long running 365 // operations. Methods that must be called with this lock held have 366 // the suffix "LI". 367 final Object mInstallLock = new Object(); 368 369 // ---------------------------------------------------------------- 370 371 // Keys are String (package name), values are Package. This also serves 372 // as the lock for the global state. Methods that must be called with 373 // this lock held have the prefix "LP". 374 final HashMap<String, PackageParser.Package> mPackages = 375 new HashMap<String, PackageParser.Package>(); 376 377 // Tracks available target package names -> overlay package paths. 378 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 379 new HashMap<String, HashMap<String, PackageParser.Package>>(); 380 381 final Settings mSettings; 382 boolean mRestoredSettings; 383 384 // System configuration read by SystemConfig. 385 final int[] mGlobalGids; 386 final SparseArray<HashSet<String>> mSystemPermissions; 387 final HashMap<String, FeatureInfo> mAvailableFeatures; 388 389 // If mac_permissions.xml was found for seinfo labeling. 390 boolean mFoundPolicyFile; 391 392 // If a recursive restorecon of /data/data/<pkg> is needed. 393 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 394 395 public static final class SharedLibraryEntry { 396 public final String path; 397 public final String apk; 398 399 SharedLibraryEntry(String _path, String _apk) { 400 path = _path; 401 apk = _apk; 402 } 403 } 404 405 // Currently known shared libraries. 406 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 407 new HashMap<String, SharedLibraryEntry>(); 408 409 // All available activities, for your resolving pleasure. 410 final ActivityIntentResolver mActivities = 411 new ActivityIntentResolver(); 412 413 // All available receivers, for your resolving pleasure. 414 final ActivityIntentResolver mReceivers = 415 new ActivityIntentResolver(); 416 417 // All available services, for your resolving pleasure. 418 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 419 420 // All available providers, for your resolving pleasure. 421 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 422 423 // Mapping from provider base names (first directory in content URI codePath) 424 // to the provider information. 425 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 426 new HashMap<String, PackageParser.Provider>(); 427 428 // Mapping from instrumentation class names to info about them. 429 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 430 new HashMap<ComponentName, PackageParser.Instrumentation>(); 431 432 // Mapping from permission names to info about them. 433 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 434 new HashMap<String, PackageParser.PermissionGroup>(); 435 436 // Packages whose data we have transfered into another package, thus 437 // should no longer exist. 438 final HashSet<String> mTransferedPackages = new HashSet<String>(); 439 440 // Broadcast actions that are only available to the system. 441 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 442 443 /** List of packages waiting for verification. */ 444 final SparseArray<PackageVerificationState> mPendingVerification 445 = new SparseArray<PackageVerificationState>(); 446 447 /** Set of packages associated with each app op permission. */ 448 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 449 450 final PackageInstallerService mInstallerService; 451 452 HashSet<PackageParser.Package> mDeferredDexOpt = null; 453 454 // Cache of users who need badging. 455 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 456 457 /** Token for keys in mPendingVerification. */ 458 private int mPendingVerificationToken = 0; 459 460 volatile boolean mSystemReady; 461 volatile boolean mSafeMode; 462 volatile boolean mHasSystemUidErrors; 463 464 ApplicationInfo mAndroidApplication; 465 final ActivityInfo mResolveActivity = new ActivityInfo(); 466 final ResolveInfo mResolveInfo = new ResolveInfo(); 467 ComponentName mResolveComponentName; 468 PackageParser.Package mPlatformPackage; 469 ComponentName mCustomResolverComponentName; 470 471 boolean mResolverReplaced = false; 472 473 // Set of pending broadcasts for aggregating enable/disable of components. 474 static class PendingPackageBroadcasts { 475 // for each user id, a map of <package name -> components within that package> 476 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 477 478 public PendingPackageBroadcasts() { 479 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 480 } 481 482 public ArrayList<String> get(int userId, String packageName) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 return packages.get(packageName); 485 } 486 487 public void put(int userId, String packageName, ArrayList<String> components) { 488 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 489 packages.put(packageName, components); 490 } 491 492 public void remove(int userId, String packageName) { 493 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 494 if (packages != null) { 495 packages.remove(packageName); 496 } 497 } 498 499 public void remove(int userId) { 500 mUidMap.remove(userId); 501 } 502 503 public int userIdCount() { 504 return mUidMap.size(); 505 } 506 507 public int userIdAt(int n) { 508 return mUidMap.keyAt(n); 509 } 510 511 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 512 return mUidMap.get(userId); 513 } 514 515 public int size() { 516 // total number of pending broadcast entries across all userIds 517 int num = 0; 518 for (int i = 0; i< mUidMap.size(); i++) { 519 num += mUidMap.valueAt(i).size(); 520 } 521 return num; 522 } 523 524 public void clear() { 525 mUidMap.clear(); 526 } 527 528 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 529 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 530 if (map == null) { 531 map = new HashMap<String, ArrayList<String>>(); 532 mUidMap.put(userId, map); 533 } 534 return map; 535 } 536 } 537 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 538 539 // Service Connection to remote media container service to copy 540 // package uri's from external media onto secure containers 541 // or internal storage. 542 private IMediaContainerService mContainerService = null; 543 544 static final int SEND_PENDING_BROADCAST = 1; 545 static final int MCS_BOUND = 3; 546 static final int END_COPY = 4; 547 static final int INIT_COPY = 5; 548 static final int MCS_UNBIND = 6; 549 static final int START_CLEANING_PACKAGE = 7; 550 static final int FIND_INSTALL_LOC = 8; 551 static final int POST_INSTALL = 9; 552 static final int MCS_RECONNECT = 10; 553 static final int MCS_GIVE_UP = 11; 554 static final int UPDATED_MEDIA_STATUS = 12; 555 static final int WRITE_SETTINGS = 13; 556 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 557 static final int PACKAGE_VERIFIED = 15; 558 static final int CHECK_PENDING_VERIFICATION = 16; 559 560 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 561 562 // Delay time in millisecs 563 static final int BROADCAST_DELAY = 10 * 1000; 564 565 static UserManagerService sUserManager; 566 567 // Stores a list of users whose package restrictions file needs to be updated 568 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 569 570 final private DefaultContainerConnection mDefContainerConn = 571 new DefaultContainerConnection(); 572 class DefaultContainerConnection implements ServiceConnection { 573 public void onServiceConnected(ComponentName name, IBinder service) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 575 IMediaContainerService imcs = 576 IMediaContainerService.Stub.asInterface(service); 577 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 578 } 579 580 public void onServiceDisconnected(ComponentName name) { 581 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 582 } 583 }; 584 585 // Recordkeeping of restore-after-install operations that are currently in flight 586 // between the Package Manager and the Backup Manager 587 class PostInstallData { 588 public InstallArgs args; 589 public PackageInstalledInfo res; 590 591 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 592 args = _a; 593 res = _r; 594 } 595 }; 596 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 597 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 598 599 private final String mRequiredVerifierPackage; 600 601 private final PackageUsage mPackageUsage = new PackageUsage(); 602 603 private class PackageUsage { 604 private static final int WRITE_INTERVAL 605 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 606 607 private final Object mFileLock = new Object(); 608 private final AtomicLong mLastWritten = new AtomicLong(0); 609 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 610 611 private boolean mIsHistoricalPackageUsageAvailable = true; 612 613 boolean isHistoricalPackageUsageAvailable() { 614 return mIsHistoricalPackageUsageAvailable; 615 } 616 617 void write(boolean force) { 618 if (force) { 619 writeInternal(); 620 return; 621 } 622 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 623 && !DEBUG_DEXOPT) { 624 return; 625 } 626 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 627 new Thread("PackageUsage_DiskWriter") { 628 @Override 629 public void run() { 630 try { 631 writeInternal(); 632 } finally { 633 mBackgroundWriteRunning.set(false); 634 } 635 } 636 }.start(); 637 } 638 } 639 640 private void writeInternal() { 641 synchronized (mPackages) { 642 synchronized (mFileLock) { 643 AtomicFile file = getFile(); 644 FileOutputStream f = null; 645 try { 646 f = file.startWrite(); 647 BufferedOutputStream out = new BufferedOutputStream(f); 648 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 649 StringBuilder sb = new StringBuilder(); 650 for (PackageParser.Package pkg : mPackages.values()) { 651 if (pkg.mLastPackageUsageTimeInMills == 0) { 652 continue; 653 } 654 sb.setLength(0); 655 sb.append(pkg.packageName); 656 sb.append(' '); 657 sb.append((long)pkg.mLastPackageUsageTimeInMills); 658 sb.append('\n'); 659 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 660 } 661 out.flush(); 662 file.finishWrite(f); 663 } catch (IOException e) { 664 if (f != null) { 665 file.failWrite(f); 666 } 667 Log.e(TAG, "Failed to write package usage times", e); 668 } 669 } 670 } 671 mLastWritten.set(SystemClock.elapsedRealtime()); 672 } 673 674 void readLP() { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 BufferedInputStream in = null; 678 try { 679 in = new BufferedInputStream(file.openRead()); 680 StringBuffer sb = new StringBuffer(); 681 while (true) { 682 String packageName = readToken(in, sb, ' '); 683 if (packageName == null) { 684 break; 685 } 686 String timeInMillisString = readToken(in, sb, '\n'); 687 if (timeInMillisString == null) { 688 throw new IOException("Failed to find last usage time for package " 689 + packageName); 690 } 691 PackageParser.Package pkg = mPackages.get(packageName); 692 if (pkg == null) { 693 continue; 694 } 695 long timeInMillis; 696 try { 697 timeInMillis = Long.parseLong(timeInMillisString.toString()); 698 } catch (NumberFormatException e) { 699 throw new IOException("Failed to parse " + timeInMillisString 700 + " as a long.", e); 701 } 702 pkg.mLastPackageUsageTimeInMills = timeInMillis; 703 } 704 } catch (FileNotFoundException expected) { 705 mIsHistoricalPackageUsageAvailable = false; 706 } catch (IOException e) { 707 Log.w(TAG, "Failed to read package usage times", e); 708 } finally { 709 IoUtils.closeQuietly(in); 710 } 711 } 712 mLastWritten.set(SystemClock.elapsedRealtime()); 713 } 714 715 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 716 throws IOException { 717 sb.setLength(0); 718 while (true) { 719 int ch = in.read(); 720 if (ch == -1) { 721 if (sb.length() == 0) { 722 return null; 723 } 724 throw new IOException("Unexpected EOF"); 725 } 726 if (ch == endOfToken) { 727 return sb.toString(); 728 } 729 sb.append((char)ch); 730 } 731 } 732 733 private AtomicFile getFile() { 734 File dataDir = Environment.getDataDirectory(); 735 File systemDir = new File(dataDir, "system"); 736 File fname = new File(systemDir, "package-usage.list"); 737 return new AtomicFile(fname); 738 } 739 } 740 741 class PackageHandler extends Handler { 742 private boolean mBound = false; 743 final ArrayList<HandlerParams> mPendingInstalls = 744 new ArrayList<HandlerParams>(); 745 746 private boolean connectToService() { 747 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 748 " DefaultContainerService"); 749 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 750 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 751 if (mContext.bindServiceAsUser(service, mDefContainerConn, 752 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 mBound = true; 755 return true; 756 } 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 return false; 759 } 760 761 private void disconnectService() { 762 mContainerService = null; 763 mBound = false; 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 mContext.unbindService(mDefContainerConn); 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 769 PackageHandler(Looper looper) { 770 super(looper); 771 } 772 773 public void handleMessage(Message msg) { 774 try { 775 doHandleMessage(msg); 776 } finally { 777 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 778 } 779 } 780 781 void doHandleMessage(Message msg) { 782 switch (msg.what) { 783 case INIT_COPY: { 784 HandlerParams params = (HandlerParams) msg.obj; 785 int idx = mPendingInstalls.size(); 786 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 787 // If a bind was already initiated we dont really 788 // need to do anything. The pending install 789 // will be processed later on. 790 if (!mBound) { 791 // If this is the only one pending we might 792 // have to bind to the service again. 793 if (!connectToService()) { 794 Slog.e(TAG, "Failed to bind to media container service"); 795 params.serviceError(); 796 return; 797 } else { 798 // Once we bind to the service, the first 799 // pending request will be processed. 800 mPendingInstalls.add(idx, params); 801 } 802 } else { 803 mPendingInstalls.add(idx, params); 804 // Already bound to the service. Just make 805 // sure we trigger off processing the first request. 806 if (idx == 0) { 807 mHandler.sendEmptyMessage(MCS_BOUND); 808 } 809 } 810 break; 811 } 812 case MCS_BOUND: { 813 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 814 if (msg.obj != null) { 815 mContainerService = (IMediaContainerService) msg.obj; 816 } 817 if (mContainerService == null) { 818 // Something seriously wrong. Bail out 819 Slog.e(TAG, "Cannot bind to media container service"); 820 for (HandlerParams params : mPendingInstalls) { 821 // Indicate service bind error 822 params.serviceError(); 823 } 824 mPendingInstalls.clear(); 825 } else if (mPendingInstalls.size() > 0) { 826 HandlerParams params = mPendingInstalls.get(0); 827 if (params != null) { 828 if (params.startCopy()) { 829 // We are done... look for more work or to 830 // go idle. 831 if (DEBUG_SD_INSTALL) Log.i(TAG, 832 "Checking for more work or unbind..."); 833 // Delete pending install 834 if (mPendingInstalls.size() > 0) { 835 mPendingInstalls.remove(0); 836 } 837 if (mPendingInstalls.size() == 0) { 838 if (mBound) { 839 if (DEBUG_SD_INSTALL) Log.i(TAG, 840 "Posting delayed MCS_UNBIND"); 841 removeMessages(MCS_UNBIND); 842 Message ubmsg = obtainMessage(MCS_UNBIND); 843 // Unbind after a little delay, to avoid 844 // continual thrashing. 845 sendMessageDelayed(ubmsg, 10000); 846 } 847 } else { 848 // There are more pending requests in queue. 849 // Just post MCS_BOUND message to trigger processing 850 // of next pending install. 851 if (DEBUG_SD_INSTALL) Log.i(TAG, 852 "Posting MCS_BOUND for next work"); 853 mHandler.sendEmptyMessage(MCS_BOUND); 854 } 855 } 856 } 857 } else { 858 // Should never happen ideally. 859 Slog.w(TAG, "Empty queue"); 860 } 861 break; 862 } 863 case MCS_RECONNECT: { 864 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 865 if (mPendingInstalls.size() > 0) { 866 if (mBound) { 867 disconnectService(); 868 } 869 if (!connectToService()) { 870 Slog.e(TAG, "Failed to bind to media container service"); 871 for (HandlerParams params : mPendingInstalls) { 872 // Indicate service bind error 873 params.serviceError(); 874 } 875 mPendingInstalls.clear(); 876 } 877 } 878 break; 879 } 880 case MCS_UNBIND: { 881 // If there is no actual work left, then time to unbind. 882 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 883 884 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 885 if (mBound) { 886 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 887 888 disconnectService(); 889 } 890 } else if (mPendingInstalls.size() > 0) { 891 // There are more pending requests in queue. 892 // Just post MCS_BOUND message to trigger processing 893 // of next pending install. 894 mHandler.sendEmptyMessage(MCS_BOUND); 895 } 896 897 break; 898 } 899 case MCS_GIVE_UP: { 900 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 901 mPendingInstalls.remove(0); 902 break; 903 } 904 case SEND_PENDING_BROADCAST: { 905 String packages[]; 906 ArrayList<String> components[]; 907 int size = 0; 908 int uids[]; 909 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 910 synchronized (mPackages) { 911 if (mPendingBroadcasts == null) { 912 return; 913 } 914 size = mPendingBroadcasts.size(); 915 if (size <= 0) { 916 // Nothing to be done. Just return 917 return; 918 } 919 packages = new String[size]; 920 components = new ArrayList[size]; 921 uids = new int[size]; 922 int i = 0; // filling out the above arrays 923 924 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 925 int packageUserId = mPendingBroadcasts.userIdAt(n); 926 Iterator<Map.Entry<String, ArrayList<String>>> it 927 = mPendingBroadcasts.packagesForUserId(packageUserId) 928 .entrySet().iterator(); 929 while (it.hasNext() && i < size) { 930 Map.Entry<String, ArrayList<String>> ent = it.next(); 931 packages[i] = ent.getKey(); 932 components[i] = ent.getValue(); 933 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 934 uids[i] = (ps != null) 935 ? UserHandle.getUid(packageUserId, ps.appId) 936 : -1; 937 i++; 938 } 939 } 940 size = i; 941 mPendingBroadcasts.clear(); 942 } 943 // Send broadcasts 944 for (int i = 0; i < size; i++) { 945 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 946 } 947 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 948 break; 949 } 950 case START_CLEANING_PACKAGE: { 951 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 952 final String packageName = (String)msg.obj; 953 final int userId = msg.arg1; 954 final boolean andCode = msg.arg2 != 0; 955 synchronized (mPackages) { 956 if (userId == UserHandle.USER_ALL) { 957 int[] users = sUserManager.getUserIds(); 958 for (int user : users) { 959 mSettings.addPackageToCleanLPw( 960 new PackageCleanItem(user, packageName, andCode)); 961 } 962 } else { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(userId, packageName, andCode)); 965 } 966 } 967 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 968 startCleaningPackages(); 969 } break; 970 case POST_INSTALL: { 971 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 972 PostInstallData data = mRunningInstalls.get(msg.arg1); 973 mRunningInstalls.delete(msg.arg1); 974 boolean deleteOld = false; 975 976 if (data != null) { 977 InstallArgs args = data.args; 978 PackageInstalledInfo res = data.res; 979 980 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 981 res.removedInfo.sendBroadcast(false, true, false); 982 Bundle extras = new Bundle(1); 983 extras.putInt(Intent.EXTRA_UID, res.uid); 984 // Determine the set of users who are adding this 985 // package for the first time vs. those who are seeing 986 // an update. 987 int[] firstUsers; 988 int[] updateUsers = new int[0]; 989 if (res.origUsers == null || res.origUsers.length == 0) { 990 firstUsers = res.newUsers; 991 } else { 992 firstUsers = new int[0]; 993 for (int i=0; i<res.newUsers.length; i++) { 994 int user = res.newUsers[i]; 995 boolean isNew = true; 996 for (int j=0; j<res.origUsers.length; j++) { 997 if (res.origUsers[j] == user) { 998 isNew = false; 999 break; 1000 } 1001 } 1002 if (isNew) { 1003 int[] newFirst = new int[firstUsers.length+1]; 1004 System.arraycopy(firstUsers, 0, newFirst, 0, 1005 firstUsers.length); 1006 newFirst[firstUsers.length] = user; 1007 firstUsers = newFirst; 1008 } else { 1009 int[] newUpdate = new int[updateUsers.length+1]; 1010 System.arraycopy(updateUsers, 0, newUpdate, 0, 1011 updateUsers.length); 1012 newUpdate[updateUsers.length] = user; 1013 updateUsers = newUpdate; 1014 } 1015 } 1016 } 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, firstUsers); 1020 final boolean update = res.removedInfo.removedPackage != null; 1021 if (update) { 1022 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1023 } 1024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1025 res.pkg.applicationInfo.packageName, 1026 extras, null, null, updateUsers); 1027 if (update) { 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1032 null, null, 1033 res.pkg.applicationInfo.packageName, null, updateUsers); 1034 1035 // treat asec-hosted packages like removable media on upgrade 1036 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1037 if (DEBUG_INSTALL) { 1038 Slog.i(TAG, "upgrading pkg " + res.pkg 1039 + " is ASEC-hosted -> AVAILABLE"); 1040 } 1041 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1042 ArrayList<String> pkgList = new ArrayList<String>(1); 1043 pkgList.add(res.pkg.applicationInfo.packageName); 1044 sendResourcesChangedBroadcast(true, true, 1045 pkgList,uidArray, null); 1046 } 1047 } 1048 if (res.removedInfo.args != null) { 1049 // Remove the replaced package's older resources safely now 1050 deleteOld = true; 1051 } 1052 1053 // Log current value of "unknown sources" setting 1054 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1055 getUnknownSourcesSettings()); 1056 } 1057 // Force a gc to clear up things 1058 Runtime.getRuntime().gc(); 1059 // We delete after a gc for applications on sdcard. 1060 if (deleteOld) { 1061 synchronized (mInstallLock) { 1062 res.removedInfo.args.doPostDeleteLI(true); 1063 } 1064 } 1065 if (args.observer != null) { 1066 try { 1067 Bundle extras = extrasForInstallResult(res); 1068 args.observer.onPackageInstalled(res.name, res.returnCode, 1069 res.returnMsg, extras); 1070 } catch (RemoteException e) { 1071 Slog.i(TAG, "Observer no longer exists."); 1072 } 1073 } 1074 } else { 1075 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1076 } 1077 } break; 1078 case UPDATED_MEDIA_STATUS: { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1080 boolean reportStatus = msg.arg1 == 1; 1081 boolean doGc = msg.arg2 == 1; 1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1083 if (doGc) { 1084 // Force a gc to clear up stale containers. 1085 Runtime.getRuntime().gc(); 1086 } 1087 if (msg.obj != null) { 1088 @SuppressWarnings("unchecked") 1089 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1090 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1091 // Unload containers 1092 unloadAllContainers(args); 1093 } 1094 if (reportStatus) { 1095 try { 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1097 PackageHelper.getMountService().finishMediaUpdate(); 1098 } catch (RemoteException e) { 1099 Log.e(TAG, "MountService not running?"); 1100 } 1101 } 1102 } break; 1103 case WRITE_SETTINGS: { 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1105 synchronized (mPackages) { 1106 removeMessages(WRITE_SETTINGS); 1107 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1108 mSettings.writeLPr(); 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case WRITE_PACKAGE_RESTRICTIONS: { 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1115 synchronized (mPackages) { 1116 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1117 for (int userId : mDirtyUsers) { 1118 mSettings.writePackageRestrictionsLPr(userId); 1119 } 1120 mDirtyUsers.clear(); 1121 } 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } break; 1124 case CHECK_PENDING_VERIFICATION: { 1125 final int verificationId = msg.arg1; 1126 final PackageVerificationState state = mPendingVerification.get(verificationId); 1127 1128 if ((state != null) && !state.timeoutExtended()) { 1129 final InstallArgs args = state.getInstallArgs(); 1130 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1131 1132 Slog.i(TAG, "Verification timed out for " + originUri); 1133 mPendingVerification.remove(verificationId); 1134 1135 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1136 1137 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1138 Slog.i(TAG, "Continuing with installation of " + originUri); 1139 state.setVerifierResponse(Binder.getCallingUid(), 1140 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1141 broadcastPackageVerified(verificationId, originUri, 1142 PackageManager.VERIFICATION_ALLOW, 1143 state.getInstallArgs().getUser()); 1144 try { 1145 ret = args.copyApk(mContainerService, true); 1146 } catch (RemoteException e) { 1147 Slog.e(TAG, "Could not contact the ContainerService"); 1148 } 1149 } else { 1150 broadcastPackageVerified(verificationId, originUri, 1151 PackageManager.VERIFICATION_REJECT, 1152 state.getInstallArgs().getUser()); 1153 } 1154 1155 processPendingInstall(args, ret); 1156 mHandler.sendEmptyMessage(MCS_UNBIND); 1157 } 1158 break; 1159 } 1160 case PACKAGE_VERIFIED: { 1161 final int verificationId = msg.arg1; 1162 1163 final PackageVerificationState state = mPendingVerification.get(verificationId); 1164 if (state == null) { 1165 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1166 break; 1167 } 1168 1169 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1170 1171 state.setVerifierResponse(response.callerUid, response.code); 1172 1173 if (state.isVerificationComplete()) { 1174 mPendingVerification.remove(verificationId); 1175 1176 final InstallArgs args = state.getInstallArgs(); 1177 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1178 1179 int ret; 1180 if (state.isInstallAllowed()) { 1181 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1182 broadcastPackageVerified(verificationId, originUri, 1183 response.code, state.getInstallArgs().getUser()); 1184 try { 1185 ret = args.copyApk(mContainerService, true); 1186 } catch (RemoteException e) { 1187 Slog.e(TAG, "Could not contact the ContainerService"); 1188 } 1189 } else { 1190 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1191 } 1192 1193 processPendingInstall(args, ret); 1194 1195 mHandler.sendEmptyMessage(MCS_UNBIND); 1196 } 1197 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1205 Bundle extras = null; 1206 switch (res.returnCode) { 1207 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1208 extras = new Bundle(); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1210 res.origPermission); 1211 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1212 res.origPackage); 1213 break; 1214 } 1215 } 1216 return extras; 1217 } 1218 1219 void scheduleWriteSettingsLocked() { 1220 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1221 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1222 } 1223 } 1224 1225 void scheduleWritePackageRestrictionsLocked(int userId) { 1226 if (!sUserManager.exists(userId)) return; 1227 mDirtyUsers.add(userId); 1228 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1229 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1230 } 1231 } 1232 1233 public static final PackageManagerService main(Context context, Installer installer, 1234 boolean factoryTest, boolean onlyCore) { 1235 PackageManagerService m = new PackageManagerService(context, installer, 1236 factoryTest, onlyCore); 1237 ServiceManager.addService("package", m); 1238 return m; 1239 } 1240 1241 static String[] splitString(String str, char sep) { 1242 int count = 1; 1243 int i = 0; 1244 while ((i=str.indexOf(sep, i)) >= 0) { 1245 count++; 1246 i++; 1247 } 1248 1249 String[] res = new String[count]; 1250 i=0; 1251 count = 0; 1252 int lastI=0; 1253 while ((i=str.indexOf(sep, i)) >= 0) { 1254 res[count] = str.substring(lastI, i); 1255 count++; 1256 i++; 1257 lastI = i; 1258 } 1259 res[count] = str.substring(lastI, str.length()); 1260 return res; 1261 } 1262 1263 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1264 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1265 Context.DISPLAY_SERVICE); 1266 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1267 } 1268 1269 public PackageManagerService(Context context, Installer installer, 1270 boolean factoryTest, boolean onlyCore) { 1271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1272 SystemClock.uptimeMillis()); 1273 1274 if (mSdkVersion <= 0) { 1275 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1276 } 1277 1278 mContext = context; 1279 mFactoryTest = factoryTest; 1280 mOnlyCore = onlyCore; 1281 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1282 mMetrics = new DisplayMetrics(); 1283 mSettings = new Settings(context); 1284 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1285 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1286 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1287 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1288 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1289 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1290 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1291 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1292 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1293 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1294 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1295 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1296 1297 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1298 if (separateProcesses != null && separateProcesses.length() > 0) { 1299 if ("*".equals(separateProcesses)) { 1300 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1301 mSeparateProcesses = null; 1302 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1303 } else { 1304 mDefParseFlags = 0; 1305 mSeparateProcesses = separateProcesses.split(","); 1306 Slog.w(TAG, "Running with debug.separate_processes: " 1307 + separateProcesses); 1308 } 1309 } else { 1310 mDefParseFlags = 0; 1311 mSeparateProcesses = null; 1312 } 1313 1314 mInstaller = installer; 1315 1316 getDefaultDisplayMetrics(context, mMetrics); 1317 1318 SystemConfig systemConfig = SystemConfig.getInstance(); 1319 mGlobalGids = systemConfig.getGlobalGids(); 1320 mSystemPermissions = systemConfig.getSystemPermissions(); 1321 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1322 1323 synchronized (mInstallLock) { 1324 // writer 1325 synchronized (mPackages) { 1326 mHandlerThread = new ServiceThread(TAG, 1327 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1328 mHandlerThread.start(); 1329 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1330 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1331 1332 File dataDir = Environment.getDataDirectory(); 1333 mAppDataDir = new File(dataDir, "data"); 1334 mAppInstallDir = new File(dataDir, "app"); 1335 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1336 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1337 mUserAppDataDir = new File(dataDir, "user"); 1338 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1339 1340 sUserManager = new UserManagerService(context, this, 1341 mInstallLock, mPackages); 1342 1343 // Propagate permission configuration in to package manager. 1344 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1345 = systemConfig.getPermissions(); 1346 for (int i=0; i<permConfig.size(); i++) { 1347 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1348 BasePermission bp = mSettings.mPermissions.get(perm.name); 1349 if (bp == null) { 1350 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1351 mSettings.mPermissions.put(perm.name, bp); 1352 } 1353 if (perm.gids != null) { 1354 bp.gids = appendInts(bp.gids, perm.gids); 1355 } 1356 } 1357 1358 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1359 for (int i=0; i<libConfig.size(); i++) { 1360 mSharedLibraries.put(libConfig.keyAt(i), 1361 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1362 } 1363 1364 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1365 1366 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1367 mSdkVersion, mOnlyCore); 1368 1369 String customResolverActivity = Resources.getSystem().getString( 1370 R.string.config_customResolverActivity); 1371 if (TextUtils.isEmpty(customResolverActivity)) { 1372 customResolverActivity = null; 1373 } else { 1374 mCustomResolverComponentName = ComponentName.unflattenFromString( 1375 customResolverActivity); 1376 } 1377 1378 long startTime = SystemClock.uptimeMillis(); 1379 1380 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1381 startTime); 1382 1383 // Set flag to monitor and not change apk file paths when 1384 // scanning install directories. 1385 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1386 1387 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1388 1389 /** 1390 * Add everything in the in the boot class path to the 1391 * list of process files because dexopt will have been run 1392 * if necessary during zygote startup. 1393 */ 1394 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1395 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1396 1397 if (bootClassPath != null) { 1398 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1399 for (String element : bootClassPathElements) { 1400 alreadyDexOpted.add(element); 1401 } 1402 } else { 1403 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1404 } 1405 1406 if (systemServerClassPath != null) { 1407 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1408 for (String element : systemServerClassPathElements) { 1409 alreadyDexOpted.add(element); 1410 } 1411 } else { 1412 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1413 } 1414 1415 boolean didDexOptLibraryOrTool = false; 1416 1417 final List<String> allInstructionSets = getAllInstructionSets(); 1418 final String[] dexCodeInstructionSets = 1419 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1420 1421 /** 1422 * Ensure all external libraries have had dexopt run on them. 1423 */ 1424 if (mSharedLibraries.size() > 0) { 1425 // NOTE: For now, we're compiling these system "shared libraries" 1426 // (and framework jars) into all available architectures. It's possible 1427 // to compile them only when we come across an app that uses them (there's 1428 // already logic for that in scanPackageLI) but that adds some complexity. 1429 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1430 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1431 final String lib = libEntry.path; 1432 if (lib == null) { 1433 continue; 1434 } 1435 1436 try { 1437 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1438 dexCodeInstructionSet, 1439 false); 1440 if (dexoptRequired != DexFile.UP_TO_DATE) { 1441 alreadyDexOpted.add(lib); 1442 1443 // The list of "shared libraries" we have at this point is 1444 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1445 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1446 } else { 1447 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1448 } 1449 didDexOptLibraryOrTool = true; 1450 } 1451 } catch (FileNotFoundException e) { 1452 Slog.w(TAG, "Library not found: " + lib); 1453 } catch (IOException e) { 1454 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1455 + e.getMessage()); 1456 } 1457 } 1458 } 1459 } 1460 1461 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1462 1463 // Gross hack for now: we know this file doesn't contain any 1464 // code, so don't dexopt it to avoid the resulting log spew. 1465 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1466 1467 // Gross hack for now: we know this file is only part of 1468 // the boot class path for art, so don't dexopt it to 1469 // avoid the resulting log spew. 1470 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1471 1472 /** 1473 * And there are a number of commands implemented in Java, which 1474 * we currently need to do the dexopt on so that they can be 1475 * run from a non-root shell. 1476 */ 1477 String[] frameworkFiles = frameworkDir.list(); 1478 if (frameworkFiles != null) { 1479 // TODO: We could compile these only for the most preferred ABI. We should 1480 // first double check that the dex files for these commands are not referenced 1481 // by other system apps. 1482 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1483 for (int i=0; i<frameworkFiles.length; i++) { 1484 File libPath = new File(frameworkDir, frameworkFiles[i]); 1485 String path = libPath.getPath(); 1486 // Skip the file if we already did it. 1487 if (alreadyDexOpted.contains(path)) { 1488 continue; 1489 } 1490 // Skip the file if it is not a type we want to dexopt. 1491 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1492 continue; 1493 } 1494 try { 1495 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1496 dexCodeInstructionSet, 1497 false); 1498 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1499 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1500 didDexOptLibraryOrTool = true; 1501 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1502 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1503 didDexOptLibraryOrTool = true; 1504 } 1505 } catch (FileNotFoundException e) { 1506 Slog.w(TAG, "Jar not found: " + path); 1507 } catch (IOException e) { 1508 Slog.w(TAG, "Exception reading jar: " + path, e); 1509 } 1510 } 1511 } 1512 } 1513 1514 // Collect vendor overlay packages. 1515 // (Do this before scanning any apps.) 1516 // For security and version matching reason, only consider 1517 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1518 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1519 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1521 1522 // Find base frameworks (resource packages without code). 1523 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1524 | PackageParser.PARSE_IS_SYSTEM_DIR 1525 | PackageParser.PARSE_IS_PRIVILEGED, 1526 scanFlags | SCAN_NO_DEX, 0); 1527 1528 // Collected privileged system packages. 1529 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1530 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR 1532 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1533 1534 // Collect ordinary system packages. 1535 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1536 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1537 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1538 1539 // Collect all vendor packages. 1540 File vendorAppDir = new File("/vendor/app"); 1541 try { 1542 vendorAppDir = vendorAppDir.getCanonicalFile(); 1543 } catch (IOException e) { 1544 // failed to look up canonical path, continue with original one 1545 } 1546 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1548 1549 // Collect all OEM packages. 1550 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1551 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1553 1554 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1555 mInstaller.moveFiles(); 1556 1557 // Prune any system packages that no longer exist. 1558 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1559 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1560 if (!mOnlyCore) { 1561 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1562 while (psit.hasNext()) { 1563 PackageSetting ps = psit.next(); 1564 1565 /* 1566 * If this is not a system app, it can't be a 1567 * disable system app. 1568 */ 1569 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1570 continue; 1571 } 1572 1573 /* 1574 * If the package is scanned, it's not erased. 1575 */ 1576 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1577 if (scannedPkg != null) { 1578 /* 1579 * If the system app is both scanned and in the 1580 * disabled packages list, then it must have been 1581 * added via OTA. Remove it from the currently 1582 * scanned package so the previously user-installed 1583 * application can be scanned. 1584 */ 1585 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1586 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1587 + ps.name + "; removing system app. Last known codePath=" 1588 + ps.codePathString + ", installStatus=" + ps.installStatus 1589 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1590 + scannedPkg.mVersionCode); 1591 removePackageLI(ps, true); 1592 expectingBetter.put(ps.name, ps.codePath); 1593 } 1594 1595 continue; 1596 } 1597 1598 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1599 psit.remove(); 1600 logCriticalInfo(Log.WARN, "System package " + ps.name 1601 + " no longer exists; wiping its data"); 1602 removeDataDirsLI(ps.name); 1603 } else { 1604 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1605 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1606 possiblyDeletedUpdatedSystemApps.add(ps.name); 1607 } 1608 } 1609 } 1610 } 1611 1612 //look for any incomplete package installations 1613 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1614 //clean up list 1615 for(int i = 0; i < deletePkgsList.size(); i++) { 1616 //clean up here 1617 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1618 } 1619 //delete tmp files 1620 deleteTempPackageFiles(); 1621 1622 // Remove any shared userIDs that have no associated packages 1623 mSettings.pruneSharedUsersLPw(); 1624 1625 if (!mOnlyCore) { 1626 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1627 SystemClock.uptimeMillis()); 1628 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1629 1630 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1631 scanFlags, 0); 1632 1633 /** 1634 * Remove disable package settings for any updated system 1635 * apps that were removed via an OTA. If they're not a 1636 * previously-updated app, remove them completely. 1637 * Otherwise, just revoke their system-level permissions. 1638 */ 1639 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1640 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1641 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1642 1643 String msg; 1644 if (deletedPkg == null) { 1645 msg = "Updated system package " + deletedAppName 1646 + " no longer exists; wiping its data"; 1647 removeDataDirsLI(deletedAppName); 1648 } else { 1649 msg = "Updated system app + " + deletedAppName 1650 + " no longer present; removing system privileges for " 1651 + deletedAppName; 1652 1653 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1654 1655 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1656 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1657 } 1658 logCriticalInfo(Log.WARN, msg); 1659 } 1660 1661 /** 1662 * Make sure all system apps that we expected to appear on 1663 * the userdata partition actually showed up. If they never 1664 * appeared, crawl back and revive the system version. 1665 */ 1666 for (int i = 0; i < expectingBetter.size(); i++) { 1667 final String packageName = expectingBetter.keyAt(i); 1668 if (!mPackages.containsKey(packageName)) { 1669 final File scanFile = expectingBetter.valueAt(i); 1670 1671 logCriticalInfo(Log.WARN, "Expected better " + packageName 1672 + " but never showed up; reverting to system"); 1673 1674 final int reparseFlags; 1675 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1676 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1677 | PackageParser.PARSE_IS_SYSTEM_DIR 1678 | PackageParser.PARSE_IS_PRIVILEGED; 1679 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1680 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1681 | PackageParser.PARSE_IS_SYSTEM_DIR; 1682 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1683 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1684 | PackageParser.PARSE_IS_SYSTEM_DIR; 1685 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1686 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1687 | PackageParser.PARSE_IS_SYSTEM_DIR; 1688 } else { 1689 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1690 continue; 1691 } 1692 1693 mSettings.enableSystemPackageLPw(packageName); 1694 1695 try { 1696 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1697 } catch (PackageManagerException e) { 1698 Slog.e(TAG, "Failed to parse original system package: " 1699 + e.getMessage()); 1700 } 1701 } 1702 } 1703 } 1704 1705 // Now that we know all of the shared libraries, update all clients to have 1706 // the correct library paths. 1707 updateAllSharedLibrariesLPw(); 1708 1709 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1710 // NOTE: We ignore potential failures here during a system scan (like 1711 // the rest of the commands above) because there's precious little we 1712 // can do about it. A settings error is reported, though. 1713 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1714 false /* force dexopt */, false /* defer dexopt */); 1715 } 1716 1717 // Now that we know all the packages we are keeping, 1718 // read and update their last usage times. 1719 mPackageUsage.readLP(); 1720 1721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1722 SystemClock.uptimeMillis()); 1723 Slog.i(TAG, "Time to scan packages: " 1724 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1725 + " seconds"); 1726 1727 // If the platform SDK has changed since the last time we booted, 1728 // we need to re-grant app permission to catch any new ones that 1729 // appear. This is really a hack, and means that apps can in some 1730 // cases get permissions that the user didn't initially explicitly 1731 // allow... it would be nice to have some better way to handle 1732 // this situation. 1733 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1734 != mSdkVersion; 1735 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1736 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1737 + "; regranting permissions for internal storage"); 1738 mSettings.mInternalSdkPlatform = mSdkVersion; 1739 1740 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1741 | (regrantPermissions 1742 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1743 : 0)); 1744 1745 // If this is the first boot, and it is a normal boot, then 1746 // we need to initialize the default preferred apps. 1747 if (!mRestoredSettings && !onlyCore) { 1748 mSettings.readDefaultPreferredAppsLPw(this, 0); 1749 } 1750 1751 // If this is first boot after an OTA, and a normal boot, then 1752 // we need to clear code cache directories. 1753 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1754 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1755 for (String pkgName : mSettings.mPackages.keySet()) { 1756 deleteCodeCacheDirsLI(pkgName); 1757 } 1758 mSettings.mFingerprint = Build.FINGERPRINT; 1759 } 1760 1761 // All the changes are done during package scanning. 1762 mSettings.updateInternalDatabaseVersion(); 1763 1764 // can downgrade to reader 1765 mSettings.writeLPr(); 1766 1767 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1768 SystemClock.uptimeMillis()); 1769 1770 1771 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1772 } // synchronized (mPackages) 1773 } // synchronized (mInstallLock) 1774 1775 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1776 1777 // Now after opening every single application zip, make sure they 1778 // are all flushed. Not really needed, but keeps things nice and 1779 // tidy. 1780 Runtime.getRuntime().gc(); 1781 } 1782 1783 @Override 1784 public boolean isFirstBoot() { 1785 return !mRestoredSettings; 1786 } 1787 1788 @Override 1789 public boolean isOnlyCoreApps() { 1790 return mOnlyCore; 1791 } 1792 1793 private String getRequiredVerifierLPr() { 1794 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1795 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1796 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1797 1798 String requiredVerifier = null; 1799 1800 final int N = receivers.size(); 1801 for (int i = 0; i < N; i++) { 1802 final ResolveInfo info = receivers.get(i); 1803 1804 if (info.activityInfo == null) { 1805 continue; 1806 } 1807 1808 final String packageName = info.activityInfo.packageName; 1809 1810 final PackageSetting ps = mSettings.mPackages.get(packageName); 1811 if (ps == null) { 1812 continue; 1813 } 1814 1815 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1816 if (!gp.grantedPermissions 1817 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1818 continue; 1819 } 1820 1821 if (requiredVerifier != null) { 1822 throw new RuntimeException("There can be only one required verifier"); 1823 } 1824 1825 requiredVerifier = packageName; 1826 } 1827 1828 return requiredVerifier; 1829 } 1830 1831 @Override 1832 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1833 throws RemoteException { 1834 try { 1835 return super.onTransact(code, data, reply, flags); 1836 } catch (RuntimeException e) { 1837 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1838 Slog.wtf(TAG, "Package Manager Crash", e); 1839 } 1840 throw e; 1841 } 1842 } 1843 1844 void cleanupInstallFailedPackage(PackageSetting ps) { 1845 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1846 1847 removeDataDirsLI(ps.name); 1848 if (ps.codePath != null) { 1849 if (ps.codePath.isDirectory()) { 1850 FileUtils.deleteContents(ps.codePath); 1851 } 1852 ps.codePath.delete(); 1853 } 1854 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1855 if (ps.resourcePath.isDirectory()) { 1856 FileUtils.deleteContents(ps.resourcePath); 1857 } 1858 ps.resourcePath.delete(); 1859 } 1860 mSettings.removePackageLPw(ps.name); 1861 } 1862 1863 static int[] appendInts(int[] cur, int[] add) { 1864 if (add == null) return cur; 1865 if (cur == null) return add; 1866 final int N = add.length; 1867 for (int i=0; i<N; i++) { 1868 cur = appendInt(cur, add[i]); 1869 } 1870 return cur; 1871 } 1872 1873 static int[] removeInts(int[] cur, int[] rem) { 1874 if (rem == null) return cur; 1875 if (cur == null) return cur; 1876 final int N = rem.length; 1877 for (int i=0; i<N; i++) { 1878 cur = removeInt(cur, rem[i]); 1879 } 1880 return cur; 1881 } 1882 1883 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1884 if (!sUserManager.exists(userId)) return null; 1885 final PackageSetting ps = (PackageSetting) p.mExtras; 1886 if (ps == null) { 1887 return null; 1888 } 1889 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1890 final PackageUserState state = ps.readUserState(userId); 1891 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1892 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1893 state, userId); 1894 } 1895 1896 @Override 1897 public boolean isPackageAvailable(String packageName, int userId) { 1898 if (!sUserManager.exists(userId)) return false; 1899 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1900 synchronized (mPackages) { 1901 PackageParser.Package p = mPackages.get(packageName); 1902 if (p != null) { 1903 final PackageSetting ps = (PackageSetting) p.mExtras; 1904 if (ps != null) { 1905 final PackageUserState state = ps.readUserState(userId); 1906 if (state != null) { 1907 return PackageParser.isAvailable(state); 1908 } 1909 } 1910 } 1911 } 1912 return false; 1913 } 1914 1915 @Override 1916 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1917 if (!sUserManager.exists(userId)) return null; 1918 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1919 // reader 1920 synchronized (mPackages) { 1921 PackageParser.Package p = mPackages.get(packageName); 1922 if (DEBUG_PACKAGE_INFO) 1923 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1924 if (p != null) { 1925 return generatePackageInfo(p, flags, userId); 1926 } 1927 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1928 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1929 } 1930 } 1931 return null; 1932 } 1933 1934 @Override 1935 public String[] currentToCanonicalPackageNames(String[] names) { 1936 String[] out = new String[names.length]; 1937 // reader 1938 synchronized (mPackages) { 1939 for (int i=names.length-1; i>=0; i--) { 1940 PackageSetting ps = mSettings.mPackages.get(names[i]); 1941 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1942 } 1943 } 1944 return out; 1945 } 1946 1947 @Override 1948 public String[] canonicalToCurrentPackageNames(String[] names) { 1949 String[] out = new String[names.length]; 1950 // reader 1951 synchronized (mPackages) { 1952 for (int i=names.length-1; i>=0; i--) { 1953 String cur = mSettings.mRenamedPackages.get(names[i]); 1954 out[i] = cur != null ? cur : names[i]; 1955 } 1956 } 1957 return out; 1958 } 1959 1960 @Override 1961 public int getPackageUid(String packageName, int userId) { 1962 if (!sUserManager.exists(userId)) return -1; 1963 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1964 // reader 1965 synchronized (mPackages) { 1966 PackageParser.Package p = mPackages.get(packageName); 1967 if(p != null) { 1968 return UserHandle.getUid(userId, p.applicationInfo.uid); 1969 } 1970 PackageSetting ps = mSettings.mPackages.get(packageName); 1971 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1972 return -1; 1973 } 1974 p = ps.pkg; 1975 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1976 } 1977 } 1978 1979 @Override 1980 public int[] getPackageGids(String packageName) { 1981 // reader 1982 synchronized (mPackages) { 1983 PackageParser.Package p = mPackages.get(packageName); 1984 if (DEBUG_PACKAGE_INFO) 1985 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1986 if (p != null) { 1987 final PackageSetting ps = (PackageSetting)p.mExtras; 1988 return ps.getGids(); 1989 } 1990 } 1991 // stupid thing to indicate an error. 1992 return new int[0]; 1993 } 1994 1995 static final PermissionInfo generatePermissionInfo( 1996 BasePermission bp, int flags) { 1997 if (bp.perm != null) { 1998 return PackageParser.generatePermissionInfo(bp.perm, flags); 1999 } 2000 PermissionInfo pi = new PermissionInfo(); 2001 pi.name = bp.name; 2002 pi.packageName = bp.sourcePackage; 2003 pi.nonLocalizedLabel = bp.name; 2004 pi.protectionLevel = bp.protectionLevel; 2005 return pi; 2006 } 2007 2008 @Override 2009 public PermissionInfo getPermissionInfo(String name, int flags) { 2010 // reader 2011 synchronized (mPackages) { 2012 final BasePermission p = mSettings.mPermissions.get(name); 2013 if (p != null) { 2014 return generatePermissionInfo(p, flags); 2015 } 2016 return null; 2017 } 2018 } 2019 2020 @Override 2021 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2022 // reader 2023 synchronized (mPackages) { 2024 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2025 for (BasePermission p : mSettings.mPermissions.values()) { 2026 if (group == null) { 2027 if (p.perm == null || p.perm.info.group == null) { 2028 out.add(generatePermissionInfo(p, flags)); 2029 } 2030 } else { 2031 if (p.perm != null && group.equals(p.perm.info.group)) { 2032 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2033 } 2034 } 2035 } 2036 2037 if (out.size() > 0) { 2038 return out; 2039 } 2040 return mPermissionGroups.containsKey(group) ? out : null; 2041 } 2042 } 2043 2044 @Override 2045 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2046 // reader 2047 synchronized (mPackages) { 2048 return PackageParser.generatePermissionGroupInfo( 2049 mPermissionGroups.get(name), flags); 2050 } 2051 } 2052 2053 @Override 2054 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2055 // reader 2056 synchronized (mPackages) { 2057 final int N = mPermissionGroups.size(); 2058 ArrayList<PermissionGroupInfo> out 2059 = new ArrayList<PermissionGroupInfo>(N); 2060 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2061 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2062 } 2063 return out; 2064 } 2065 } 2066 2067 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2068 int userId) { 2069 if (!sUserManager.exists(userId)) return null; 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps != null) { 2072 if (ps.pkg == null) { 2073 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2074 flags, userId); 2075 if (pInfo != null) { 2076 return pInfo.applicationInfo; 2077 } 2078 return null; 2079 } 2080 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2081 ps.readUserState(userId), userId); 2082 } 2083 return null; 2084 } 2085 2086 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2087 int userId) { 2088 if (!sUserManager.exists(userId)) return null; 2089 PackageSetting ps = mSettings.mPackages.get(packageName); 2090 if (ps != null) { 2091 PackageParser.Package pkg = ps.pkg; 2092 if (pkg == null) { 2093 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2094 return null; 2095 } 2096 // Only data remains, so we aren't worried about code paths 2097 pkg = new PackageParser.Package(packageName); 2098 pkg.applicationInfo.packageName = packageName; 2099 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2100 pkg.applicationInfo.dataDir = 2101 getDataPathForPackage(packageName, 0).getPath(); 2102 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2103 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2104 } 2105 return generatePackageInfo(pkg, flags, userId); 2106 } 2107 return null; 2108 } 2109 2110 @Override 2111 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2112 if (!sUserManager.exists(userId)) return null; 2113 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2114 // writer 2115 synchronized (mPackages) { 2116 PackageParser.Package p = mPackages.get(packageName); 2117 if (DEBUG_PACKAGE_INFO) Log.v( 2118 TAG, "getApplicationInfo " + packageName 2119 + ": " + p); 2120 if (p != null) { 2121 PackageSetting ps = mSettings.mPackages.get(packageName); 2122 if (ps == null) return null; 2123 // Note: isEnabledLP() does not apply here - always return info 2124 return PackageParser.generateApplicationInfo( 2125 p, flags, ps.readUserState(userId), userId); 2126 } 2127 if ("android".equals(packageName)||"system".equals(packageName)) { 2128 return mAndroidApplication; 2129 } 2130 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2131 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2132 } 2133 } 2134 return null; 2135 } 2136 2137 2138 @Override 2139 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2140 mContext.enforceCallingOrSelfPermission( 2141 android.Manifest.permission.CLEAR_APP_CACHE, null); 2142 // Queue up an async operation since clearing cache may take a little while. 2143 mHandler.post(new Runnable() { 2144 public void run() { 2145 mHandler.removeCallbacks(this); 2146 int retCode = -1; 2147 synchronized (mInstallLock) { 2148 retCode = mInstaller.freeCache(freeStorageSize); 2149 if (retCode < 0) { 2150 Slog.w(TAG, "Couldn't clear application caches"); 2151 } 2152 } 2153 if (observer != null) { 2154 try { 2155 observer.onRemoveCompleted(null, (retCode >= 0)); 2156 } catch (RemoteException e) { 2157 Slog.w(TAG, "RemoveException when invoking call back"); 2158 } 2159 } 2160 } 2161 }); 2162 } 2163 2164 @Override 2165 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2166 mContext.enforceCallingOrSelfPermission( 2167 android.Manifest.permission.CLEAR_APP_CACHE, null); 2168 // Queue up an async operation since clearing cache may take a little while. 2169 mHandler.post(new Runnable() { 2170 public void run() { 2171 mHandler.removeCallbacks(this); 2172 int retCode = -1; 2173 synchronized (mInstallLock) { 2174 retCode = mInstaller.freeCache(freeStorageSize); 2175 if (retCode < 0) { 2176 Slog.w(TAG, "Couldn't clear application caches"); 2177 } 2178 } 2179 if(pi != null) { 2180 try { 2181 // Callback via pending intent 2182 int code = (retCode >= 0) ? 1 : 0; 2183 pi.sendIntent(null, code, null, 2184 null, null); 2185 } catch (SendIntentException e1) { 2186 Slog.i(TAG, "Failed to send pending intent"); 2187 } 2188 } 2189 } 2190 }); 2191 } 2192 2193 void freeStorage(long freeStorageSize) throws IOException { 2194 synchronized (mInstallLock) { 2195 if (mInstaller.freeCache(freeStorageSize) < 0) { 2196 throw new IOException("Failed to free enough space"); 2197 } 2198 } 2199 } 2200 2201 @Override 2202 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2203 if (!sUserManager.exists(userId)) return null; 2204 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2205 synchronized (mPackages) { 2206 PackageParser.Activity a = mActivities.mActivities.get(component); 2207 2208 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2209 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2210 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2211 if (ps == null) return null; 2212 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2213 userId); 2214 } 2215 if (mResolveComponentName.equals(component)) { 2216 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2217 new PackageUserState(), userId); 2218 } 2219 } 2220 return null; 2221 } 2222 2223 @Override 2224 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2225 String resolvedType) { 2226 synchronized (mPackages) { 2227 PackageParser.Activity a = mActivities.mActivities.get(component); 2228 if (a == null) { 2229 return false; 2230 } 2231 for (int i=0; i<a.intents.size(); i++) { 2232 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2233 intent.getData(), intent.getCategories(), TAG) >= 0) { 2234 return true; 2235 } 2236 } 2237 return false; 2238 } 2239 } 2240 2241 @Override 2242 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2243 if (!sUserManager.exists(userId)) return null; 2244 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2245 synchronized (mPackages) { 2246 PackageParser.Activity a = mReceivers.mActivities.get(component); 2247 if (DEBUG_PACKAGE_INFO) Log.v( 2248 TAG, "getReceiverInfo " + component + ": " + a); 2249 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2250 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2251 if (ps == null) return null; 2252 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2253 userId); 2254 } 2255 } 2256 return null; 2257 } 2258 2259 @Override 2260 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2261 if (!sUserManager.exists(userId)) return null; 2262 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2263 synchronized (mPackages) { 2264 PackageParser.Service s = mServices.mServices.get(component); 2265 if (DEBUG_PACKAGE_INFO) Log.v( 2266 TAG, "getServiceInfo " + component + ": " + s); 2267 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2268 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2269 if (ps == null) return null; 2270 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2271 userId); 2272 } 2273 } 2274 return null; 2275 } 2276 2277 @Override 2278 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2279 if (!sUserManager.exists(userId)) return null; 2280 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2281 synchronized (mPackages) { 2282 PackageParser.Provider p = mProviders.mProviders.get(component); 2283 if (DEBUG_PACKAGE_INFO) Log.v( 2284 TAG, "getProviderInfo " + component + ": " + p); 2285 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2286 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2287 if (ps == null) return null; 2288 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2289 userId); 2290 } 2291 } 2292 return null; 2293 } 2294 2295 @Override 2296 public String[] getSystemSharedLibraryNames() { 2297 Set<String> libSet; 2298 synchronized (mPackages) { 2299 libSet = mSharedLibraries.keySet(); 2300 int size = libSet.size(); 2301 if (size > 0) { 2302 String[] libs = new String[size]; 2303 libSet.toArray(libs); 2304 return libs; 2305 } 2306 } 2307 return null; 2308 } 2309 2310 @Override 2311 public FeatureInfo[] getSystemAvailableFeatures() { 2312 Collection<FeatureInfo> featSet; 2313 synchronized (mPackages) { 2314 featSet = mAvailableFeatures.values(); 2315 int size = featSet.size(); 2316 if (size > 0) { 2317 FeatureInfo[] features = new FeatureInfo[size+1]; 2318 featSet.toArray(features); 2319 FeatureInfo fi = new FeatureInfo(); 2320 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2321 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2322 features[size] = fi; 2323 return features; 2324 } 2325 } 2326 return null; 2327 } 2328 2329 @Override 2330 public boolean hasSystemFeature(String name) { 2331 synchronized (mPackages) { 2332 return mAvailableFeatures.containsKey(name); 2333 } 2334 } 2335 2336 private void checkValidCaller(int uid, int userId) { 2337 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2338 return; 2339 2340 throw new SecurityException("Caller uid=" + uid 2341 + " is not privileged to communicate with user=" + userId); 2342 } 2343 2344 @Override 2345 public int checkPermission(String permName, String pkgName) { 2346 synchronized (mPackages) { 2347 PackageParser.Package p = mPackages.get(pkgName); 2348 if (p != null && p.mExtras != null) { 2349 PackageSetting ps = (PackageSetting)p.mExtras; 2350 if (ps.sharedUser != null) { 2351 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2352 return PackageManager.PERMISSION_GRANTED; 2353 } 2354 } else if (ps.grantedPermissions.contains(permName)) { 2355 return PackageManager.PERMISSION_GRANTED; 2356 } 2357 } 2358 } 2359 return PackageManager.PERMISSION_DENIED; 2360 } 2361 2362 @Override 2363 public int checkUidPermission(String permName, int uid) { 2364 synchronized (mPackages) { 2365 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2366 if (obj != null) { 2367 GrantedPermissions gp = (GrantedPermissions)obj; 2368 if (gp.grantedPermissions.contains(permName)) { 2369 return PackageManager.PERMISSION_GRANTED; 2370 } 2371 } else { 2372 HashSet<String> perms = mSystemPermissions.get(uid); 2373 if (perms != null && perms.contains(permName)) { 2374 return PackageManager.PERMISSION_GRANTED; 2375 } 2376 } 2377 } 2378 return PackageManager.PERMISSION_DENIED; 2379 } 2380 2381 /** 2382 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2383 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2384 * @param checkShell TODO(yamasani): 2385 * @param message the message to log on security exception 2386 */ 2387 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2388 boolean checkShell, String message) { 2389 if (userId < 0) { 2390 throw new IllegalArgumentException("Invalid userId " + userId); 2391 } 2392 if (checkShell) { 2393 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2394 } 2395 if (userId == UserHandle.getUserId(callingUid)) return; 2396 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2397 if (requireFullPermission) { 2398 mContext.enforceCallingOrSelfPermission( 2399 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2400 } else { 2401 try { 2402 mContext.enforceCallingOrSelfPermission( 2403 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2404 } catch (SecurityException se) { 2405 mContext.enforceCallingOrSelfPermission( 2406 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2407 } 2408 } 2409 } 2410 } 2411 2412 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2413 if (callingUid == Process.SHELL_UID) { 2414 if (userHandle >= 0 2415 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2416 throw new SecurityException("Shell does not have permission to access user " 2417 + userHandle); 2418 } else if (userHandle < 0) { 2419 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2420 + Debug.getCallers(3)); 2421 } 2422 } 2423 } 2424 2425 private BasePermission findPermissionTreeLP(String permName) { 2426 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2427 if (permName.startsWith(bp.name) && 2428 permName.length() > bp.name.length() && 2429 permName.charAt(bp.name.length()) == '.') { 2430 return bp; 2431 } 2432 } 2433 return null; 2434 } 2435 2436 private BasePermission checkPermissionTreeLP(String permName) { 2437 if (permName != null) { 2438 BasePermission bp = findPermissionTreeLP(permName); 2439 if (bp != null) { 2440 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2441 return bp; 2442 } 2443 throw new SecurityException("Calling uid " 2444 + Binder.getCallingUid() 2445 + " is not allowed to add to permission tree " 2446 + bp.name + " owned by uid " + bp.uid); 2447 } 2448 } 2449 throw new SecurityException("No permission tree found for " + permName); 2450 } 2451 2452 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2453 if (s1 == null) { 2454 return s2 == null; 2455 } 2456 if (s2 == null) { 2457 return false; 2458 } 2459 if (s1.getClass() != s2.getClass()) { 2460 return false; 2461 } 2462 return s1.equals(s2); 2463 } 2464 2465 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2466 if (pi1.icon != pi2.icon) return false; 2467 if (pi1.logo != pi2.logo) return false; 2468 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2469 if (!compareStrings(pi1.name, pi2.name)) return false; 2470 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2471 // We'll take care of setting this one. 2472 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2473 // These are not currently stored in settings. 2474 //if (!compareStrings(pi1.group, pi2.group)) return false; 2475 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2476 //if (pi1.labelRes != pi2.labelRes) return false; 2477 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2478 return true; 2479 } 2480 2481 int permissionInfoFootprint(PermissionInfo info) { 2482 int size = info.name.length(); 2483 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2484 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2485 return size; 2486 } 2487 2488 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2489 int size = 0; 2490 for (BasePermission perm : mSettings.mPermissions.values()) { 2491 if (perm.uid == tree.uid) { 2492 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2493 } 2494 } 2495 return size; 2496 } 2497 2498 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2499 // We calculate the max size of permissions defined by this uid and throw 2500 // if that plus the size of 'info' would exceed our stated maximum. 2501 if (tree.uid != Process.SYSTEM_UID) { 2502 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2503 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2504 throw new SecurityException("Permission tree size cap exceeded"); 2505 } 2506 } 2507 } 2508 2509 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2510 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2511 throw new SecurityException("Label must be specified in permission"); 2512 } 2513 BasePermission tree = checkPermissionTreeLP(info.name); 2514 BasePermission bp = mSettings.mPermissions.get(info.name); 2515 boolean added = bp == null; 2516 boolean changed = true; 2517 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2518 if (added) { 2519 enforcePermissionCapLocked(info, tree); 2520 bp = new BasePermission(info.name, tree.sourcePackage, 2521 BasePermission.TYPE_DYNAMIC); 2522 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2523 throw new SecurityException( 2524 "Not allowed to modify non-dynamic permission " 2525 + info.name); 2526 } else { 2527 if (bp.protectionLevel == fixedLevel 2528 && bp.perm.owner.equals(tree.perm.owner) 2529 && bp.uid == tree.uid 2530 && comparePermissionInfos(bp.perm.info, info)) { 2531 changed = false; 2532 } 2533 } 2534 bp.protectionLevel = fixedLevel; 2535 info = new PermissionInfo(info); 2536 info.protectionLevel = fixedLevel; 2537 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2538 bp.perm.info.packageName = tree.perm.info.packageName; 2539 bp.uid = tree.uid; 2540 if (added) { 2541 mSettings.mPermissions.put(info.name, bp); 2542 } 2543 if (changed) { 2544 if (!async) { 2545 mSettings.writeLPr(); 2546 } else { 2547 scheduleWriteSettingsLocked(); 2548 } 2549 } 2550 return added; 2551 } 2552 2553 @Override 2554 public boolean addPermission(PermissionInfo info) { 2555 synchronized (mPackages) { 2556 return addPermissionLocked(info, false); 2557 } 2558 } 2559 2560 @Override 2561 public boolean addPermissionAsync(PermissionInfo info) { 2562 synchronized (mPackages) { 2563 return addPermissionLocked(info, true); 2564 } 2565 } 2566 2567 @Override 2568 public void removePermission(String name) { 2569 synchronized (mPackages) { 2570 checkPermissionTreeLP(name); 2571 BasePermission bp = mSettings.mPermissions.get(name); 2572 if (bp != null) { 2573 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2574 throw new SecurityException( 2575 "Not allowed to modify non-dynamic permission " 2576 + name); 2577 } 2578 mSettings.mPermissions.remove(name); 2579 mSettings.writeLPr(); 2580 } 2581 } 2582 } 2583 2584 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2585 int index = pkg.requestedPermissions.indexOf(bp.name); 2586 if (index == -1) { 2587 throw new SecurityException("Package " + pkg.packageName 2588 + " has not requested permission " + bp.name); 2589 } 2590 boolean isNormal = 2591 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2592 == PermissionInfo.PROTECTION_NORMAL); 2593 boolean isDangerous = 2594 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2595 == PermissionInfo.PROTECTION_DANGEROUS); 2596 boolean isDevelopment = 2597 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2598 2599 if (!isNormal && !isDangerous && !isDevelopment) { 2600 throw new SecurityException("Permission " + bp.name 2601 + " is not a changeable permission type"); 2602 } 2603 2604 if (isNormal || isDangerous) { 2605 if (pkg.requestedPermissionsRequired.get(index)) { 2606 throw new SecurityException("Can't change " + bp.name 2607 + ". It is required by the application"); 2608 } 2609 } 2610 } 2611 2612 @Override 2613 public void grantPermission(String packageName, String permissionName) { 2614 mContext.enforceCallingOrSelfPermission( 2615 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2616 synchronized (mPackages) { 2617 final PackageParser.Package pkg = mPackages.get(packageName); 2618 if (pkg == null) { 2619 throw new IllegalArgumentException("Unknown package: " + packageName); 2620 } 2621 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2622 if (bp == null) { 2623 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2624 } 2625 2626 checkGrantRevokePermissions(pkg, bp); 2627 2628 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2629 if (ps == null) { 2630 return; 2631 } 2632 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2633 if (gp.grantedPermissions.add(permissionName)) { 2634 if (ps.haveGids) { 2635 gp.gids = appendInts(gp.gids, bp.gids); 2636 } 2637 mSettings.writeLPr(); 2638 } 2639 } 2640 } 2641 2642 @Override 2643 public void revokePermission(String packageName, String permissionName) { 2644 int changedAppId = -1; 2645 2646 synchronized (mPackages) { 2647 final PackageParser.Package pkg = mPackages.get(packageName); 2648 if (pkg == null) { 2649 throw new IllegalArgumentException("Unknown package: " + packageName); 2650 } 2651 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2652 mContext.enforceCallingOrSelfPermission( 2653 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2654 } 2655 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2656 if (bp == null) { 2657 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2658 } 2659 2660 checkGrantRevokePermissions(pkg, bp); 2661 2662 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2663 if (ps == null) { 2664 return; 2665 } 2666 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2667 if (gp.grantedPermissions.remove(permissionName)) { 2668 gp.grantedPermissions.remove(permissionName); 2669 if (ps.haveGids) { 2670 gp.gids = removeInts(gp.gids, bp.gids); 2671 } 2672 mSettings.writeLPr(); 2673 changedAppId = ps.appId; 2674 } 2675 } 2676 2677 if (changedAppId >= 0) { 2678 // We changed the perm on someone, kill its processes. 2679 IActivityManager am = ActivityManagerNative.getDefault(); 2680 if (am != null) { 2681 final int callingUserId = UserHandle.getCallingUserId(); 2682 final long ident = Binder.clearCallingIdentity(); 2683 try { 2684 //XXX we should only revoke for the calling user's app permissions, 2685 // but for now we impact all users. 2686 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2687 // "revoke " + permissionName); 2688 int[] users = sUserManager.getUserIds(); 2689 for (int user : users) { 2690 am.killUid(UserHandle.getUid(user, changedAppId), 2691 "revoke " + permissionName); 2692 } 2693 } catch (RemoteException e) { 2694 } finally { 2695 Binder.restoreCallingIdentity(ident); 2696 } 2697 } 2698 } 2699 } 2700 2701 @Override 2702 public boolean isProtectedBroadcast(String actionName) { 2703 synchronized (mPackages) { 2704 return mProtectedBroadcasts.contains(actionName); 2705 } 2706 } 2707 2708 @Override 2709 public int checkSignatures(String pkg1, String pkg2) { 2710 synchronized (mPackages) { 2711 final PackageParser.Package p1 = mPackages.get(pkg1); 2712 final PackageParser.Package p2 = mPackages.get(pkg2); 2713 if (p1 == null || p1.mExtras == null 2714 || p2 == null || p2.mExtras == null) { 2715 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2716 } 2717 return compareSignatures(p1.mSignatures, p2.mSignatures); 2718 } 2719 } 2720 2721 @Override 2722 public int checkUidSignatures(int uid1, int uid2) { 2723 // Map to base uids. 2724 uid1 = UserHandle.getAppId(uid1); 2725 uid2 = UserHandle.getAppId(uid2); 2726 // reader 2727 synchronized (mPackages) { 2728 Signature[] s1; 2729 Signature[] s2; 2730 Object obj = mSettings.getUserIdLPr(uid1); 2731 if (obj != null) { 2732 if (obj instanceof SharedUserSetting) { 2733 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2734 } else if (obj instanceof PackageSetting) { 2735 s1 = ((PackageSetting)obj).signatures.mSignatures; 2736 } else { 2737 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2738 } 2739 } else { 2740 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2741 } 2742 obj = mSettings.getUserIdLPr(uid2); 2743 if (obj != null) { 2744 if (obj instanceof SharedUserSetting) { 2745 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2746 } else if (obj instanceof PackageSetting) { 2747 s2 = ((PackageSetting)obj).signatures.mSignatures; 2748 } else { 2749 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2750 } 2751 } else { 2752 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2753 } 2754 return compareSignatures(s1, s2); 2755 } 2756 } 2757 2758 /** 2759 * Compares two sets of signatures. Returns: 2760 * <br /> 2761 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2762 * <br /> 2763 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2764 * <br /> 2765 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2766 * <br /> 2767 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2768 * <br /> 2769 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2770 */ 2771 static int compareSignatures(Signature[] s1, Signature[] s2) { 2772 if (s1 == null) { 2773 return s2 == null 2774 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2775 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2776 } 2777 2778 if (s2 == null) { 2779 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2780 } 2781 2782 if (s1.length != s2.length) { 2783 return PackageManager.SIGNATURE_NO_MATCH; 2784 } 2785 2786 // Since both signature sets are of size 1, we can compare without HashSets. 2787 if (s1.length == 1) { 2788 return s1[0].equals(s2[0]) ? 2789 PackageManager.SIGNATURE_MATCH : 2790 PackageManager.SIGNATURE_NO_MATCH; 2791 } 2792 2793 HashSet<Signature> set1 = new HashSet<Signature>(); 2794 for (Signature sig : s1) { 2795 set1.add(sig); 2796 } 2797 HashSet<Signature> set2 = new HashSet<Signature>(); 2798 for (Signature sig : s2) { 2799 set2.add(sig); 2800 } 2801 // Make sure s2 contains all signatures in s1. 2802 if (set1.equals(set2)) { 2803 return PackageManager.SIGNATURE_MATCH; 2804 } 2805 return PackageManager.SIGNATURE_NO_MATCH; 2806 } 2807 2808 /** 2809 * If the database version for this type of package (internal storage or 2810 * external storage) is less than the version where package signatures 2811 * were updated, return true. 2812 */ 2813 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2814 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2815 DatabaseVersion.SIGNATURE_END_ENTITY)) 2816 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2817 DatabaseVersion.SIGNATURE_END_ENTITY)); 2818 } 2819 2820 /** 2821 * Used for backward compatibility to make sure any packages with 2822 * certificate chains get upgraded to the new style. {@code existingSigs} 2823 * will be in the old format (since they were stored on disk from before the 2824 * system upgrade) and {@code scannedSigs} will be in the newer format. 2825 */ 2826 private int compareSignaturesCompat(PackageSignatures existingSigs, 2827 PackageParser.Package scannedPkg) { 2828 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2829 return PackageManager.SIGNATURE_NO_MATCH; 2830 } 2831 2832 HashSet<Signature> existingSet = new HashSet<Signature>(); 2833 for (Signature sig : existingSigs.mSignatures) { 2834 existingSet.add(sig); 2835 } 2836 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2837 for (Signature sig : scannedPkg.mSignatures) { 2838 try { 2839 Signature[] chainSignatures = sig.getChainSignatures(); 2840 for (Signature chainSig : chainSignatures) { 2841 scannedCompatSet.add(chainSig); 2842 } 2843 } catch (CertificateEncodingException e) { 2844 scannedCompatSet.add(sig); 2845 } 2846 } 2847 /* 2848 * Make sure the expanded scanned set contains all signatures in the 2849 * existing one. 2850 */ 2851 if (scannedCompatSet.equals(existingSet)) { 2852 // Migrate the old signatures to the new scheme. 2853 existingSigs.assignSignatures(scannedPkg.mSignatures); 2854 // The new KeySets will be re-added later in the scanning process. 2855 synchronized (mPackages) { 2856 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2857 } 2858 return PackageManager.SIGNATURE_MATCH; 2859 } 2860 return PackageManager.SIGNATURE_NO_MATCH; 2861 } 2862 2863 @Override 2864 public String[] getPackagesForUid(int uid) { 2865 uid = UserHandle.getAppId(uid); 2866 // reader 2867 synchronized (mPackages) { 2868 Object obj = mSettings.getUserIdLPr(uid); 2869 if (obj instanceof SharedUserSetting) { 2870 final SharedUserSetting sus = (SharedUserSetting) obj; 2871 final int N = sus.packages.size(); 2872 final String[] res = new String[N]; 2873 final Iterator<PackageSetting> it = sus.packages.iterator(); 2874 int i = 0; 2875 while (it.hasNext()) { 2876 res[i++] = it.next().name; 2877 } 2878 return res; 2879 } else if (obj instanceof PackageSetting) { 2880 final PackageSetting ps = (PackageSetting) obj; 2881 return new String[] { ps.name }; 2882 } 2883 } 2884 return null; 2885 } 2886 2887 @Override 2888 public String getNameForUid(int uid) { 2889 // reader 2890 synchronized (mPackages) { 2891 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2892 if (obj instanceof SharedUserSetting) { 2893 final SharedUserSetting sus = (SharedUserSetting) obj; 2894 return sus.name + ":" + sus.userId; 2895 } else if (obj instanceof PackageSetting) { 2896 final PackageSetting ps = (PackageSetting) obj; 2897 return ps.name; 2898 } 2899 } 2900 return null; 2901 } 2902 2903 @Override 2904 public int getUidForSharedUser(String sharedUserName) { 2905 if(sharedUserName == null) { 2906 return -1; 2907 } 2908 // reader 2909 synchronized (mPackages) { 2910 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2911 if (suid == null) { 2912 return -1; 2913 } 2914 return suid.userId; 2915 } 2916 } 2917 2918 @Override 2919 public int getFlagsForUid(int uid) { 2920 synchronized (mPackages) { 2921 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2922 if (obj instanceof SharedUserSetting) { 2923 final SharedUserSetting sus = (SharedUserSetting) obj; 2924 return sus.pkgFlags; 2925 } else if (obj instanceof PackageSetting) { 2926 final PackageSetting ps = (PackageSetting) obj; 2927 return ps.pkgFlags; 2928 } 2929 } 2930 return 0; 2931 } 2932 2933 @Override 2934 public String[] getAppOpPermissionPackages(String permissionName) { 2935 synchronized (mPackages) { 2936 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2937 if (pkgs == null) { 2938 return null; 2939 } 2940 return pkgs.toArray(new String[pkgs.size()]); 2941 } 2942 } 2943 2944 @Override 2945 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2946 int flags, int userId) { 2947 if (!sUserManager.exists(userId)) return null; 2948 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2949 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2950 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2951 } 2952 2953 @Override 2954 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2955 IntentFilter filter, int match, ComponentName activity) { 2956 final int userId = UserHandle.getCallingUserId(); 2957 if (DEBUG_PREFERRED) { 2958 Log.v(TAG, "setLastChosenActivity intent=" + intent 2959 + " resolvedType=" + resolvedType 2960 + " flags=" + flags 2961 + " filter=" + filter 2962 + " match=" + match 2963 + " activity=" + activity); 2964 filter.dump(new PrintStreamPrinter(System.out), " "); 2965 } 2966 intent.setComponent(null); 2967 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2968 // Find any earlier preferred or last chosen entries and nuke them 2969 findPreferredActivity(intent, resolvedType, 2970 flags, query, 0, false, true, false, userId); 2971 // Add the new activity as the last chosen for this filter 2972 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2973 "Setting last chosen"); 2974 } 2975 2976 @Override 2977 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2978 final int userId = UserHandle.getCallingUserId(); 2979 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2980 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2981 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2982 false, false, false, userId); 2983 } 2984 2985 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2986 int flags, List<ResolveInfo> query, int userId) { 2987 if (query != null) { 2988 final int N = query.size(); 2989 if (N == 1) { 2990 return query.get(0); 2991 } else if (N > 1) { 2992 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2993 // If there is more than one activity with the same priority, 2994 // then let the user decide between them. 2995 ResolveInfo r0 = query.get(0); 2996 ResolveInfo r1 = query.get(1); 2997 if (DEBUG_INTENT_MATCHING || debug) { 2998 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2999 + r1.activityInfo.name + "=" + r1.priority); 3000 } 3001 // If the first activity has a higher priority, or a different 3002 // default, then it is always desireable to pick it. 3003 if (r0.priority != r1.priority 3004 || r0.preferredOrder != r1.preferredOrder 3005 || r0.isDefault != r1.isDefault) { 3006 return query.get(0); 3007 } 3008 // If we have saved a preference for a preferred activity for 3009 // this Intent, use that. 3010 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3011 flags, query, r0.priority, true, false, debug, userId); 3012 if (ri != null) { 3013 return ri; 3014 } 3015 if (userId != 0) { 3016 ri = new ResolveInfo(mResolveInfo); 3017 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3018 ri.activityInfo.applicationInfo = new ApplicationInfo( 3019 ri.activityInfo.applicationInfo); 3020 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3021 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3022 return ri; 3023 } 3024 return mResolveInfo; 3025 } 3026 } 3027 return null; 3028 } 3029 3030 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3031 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3032 final int N = query.size(); 3033 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3034 .get(userId); 3035 // Get the list of persistent preferred activities that handle the intent 3036 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3037 List<PersistentPreferredActivity> pprefs = ppir != null 3038 ? ppir.queryIntent(intent, resolvedType, 3039 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3040 : null; 3041 if (pprefs != null && pprefs.size() > 0) { 3042 final int M = pprefs.size(); 3043 for (int i=0; i<M; i++) { 3044 final PersistentPreferredActivity ppa = pprefs.get(i); 3045 if (DEBUG_PREFERRED || debug) { 3046 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3047 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3048 + "\n component=" + ppa.mComponent); 3049 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3050 } 3051 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3052 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3053 if (DEBUG_PREFERRED || debug) { 3054 Slog.v(TAG, "Found persistent preferred activity:"); 3055 if (ai != null) { 3056 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3057 } else { 3058 Slog.v(TAG, " null"); 3059 } 3060 } 3061 if (ai == null) { 3062 // This previously registered persistent preferred activity 3063 // component is no longer known. Ignore it and do NOT remove it. 3064 continue; 3065 } 3066 for (int j=0; j<N; j++) { 3067 final ResolveInfo ri = query.get(j); 3068 if (!ri.activityInfo.applicationInfo.packageName 3069 .equals(ai.applicationInfo.packageName)) { 3070 continue; 3071 } 3072 if (!ri.activityInfo.name.equals(ai.name)) { 3073 continue; 3074 } 3075 // Found a persistent preference that can handle the intent. 3076 if (DEBUG_PREFERRED || debug) { 3077 Slog.v(TAG, "Returning persistent preferred activity: " + 3078 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3079 } 3080 return ri; 3081 } 3082 } 3083 } 3084 return null; 3085 } 3086 3087 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3088 List<ResolveInfo> query, int priority, boolean always, 3089 boolean removeMatches, boolean debug, int userId) { 3090 if (!sUserManager.exists(userId)) return null; 3091 // writer 3092 synchronized (mPackages) { 3093 if (intent.getSelector() != null) { 3094 intent = intent.getSelector(); 3095 } 3096 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3097 3098 // Try to find a matching persistent preferred activity. 3099 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3100 debug, userId); 3101 3102 // If a persistent preferred activity matched, use it. 3103 if (pri != null) { 3104 return pri; 3105 } 3106 3107 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3108 // Get the list of preferred activities that handle the intent 3109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3110 List<PreferredActivity> prefs = pir != null 3111 ? pir.queryIntent(intent, resolvedType, 3112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3113 : null; 3114 if (prefs != null && prefs.size() > 0) { 3115 boolean changed = false; 3116 try { 3117 // First figure out how good the original match set is. 3118 // We will only allow preferred activities that came 3119 // from the same match quality. 3120 int match = 0; 3121 3122 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3123 3124 final int N = query.size(); 3125 for (int j=0; j<N; j++) { 3126 final ResolveInfo ri = query.get(j); 3127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3128 + ": 0x" + Integer.toHexString(match)); 3129 if (ri.match > match) { 3130 match = ri.match; 3131 } 3132 } 3133 3134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3135 + Integer.toHexString(match)); 3136 3137 match &= IntentFilter.MATCH_CATEGORY_MASK; 3138 final int M = prefs.size(); 3139 for (int i=0; i<M; i++) { 3140 final PreferredActivity pa = prefs.get(i); 3141 if (DEBUG_PREFERRED || debug) { 3142 Slog.v(TAG, "Checking PreferredActivity ds=" 3143 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3144 + "\n component=" + pa.mPref.mComponent); 3145 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3146 } 3147 if (pa.mPref.mMatch != match) { 3148 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3149 + Integer.toHexString(pa.mPref.mMatch)); 3150 continue; 3151 } 3152 // If it's not an "always" type preferred activity and that's what we're 3153 // looking for, skip it. 3154 if (always && !pa.mPref.mAlways) { 3155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3156 continue; 3157 } 3158 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3159 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3160 if (DEBUG_PREFERRED || debug) { 3161 Slog.v(TAG, "Found preferred activity:"); 3162 if (ai != null) { 3163 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3164 } else { 3165 Slog.v(TAG, " null"); 3166 } 3167 } 3168 if (ai == null) { 3169 // This previously registered preferred activity 3170 // component is no longer known. Most likely an update 3171 // to the app was installed and in the new version this 3172 // component no longer exists. Clean it up by removing 3173 // it from the preferred activities list, and skip it. 3174 Slog.w(TAG, "Removing dangling preferred activity: " 3175 + pa.mPref.mComponent); 3176 pir.removeFilter(pa); 3177 changed = true; 3178 continue; 3179 } 3180 for (int j=0; j<N; j++) { 3181 final ResolveInfo ri = query.get(j); 3182 if (!ri.activityInfo.applicationInfo.packageName 3183 .equals(ai.applicationInfo.packageName)) { 3184 continue; 3185 } 3186 if (!ri.activityInfo.name.equals(ai.name)) { 3187 continue; 3188 } 3189 3190 if (removeMatches) { 3191 pir.removeFilter(pa); 3192 changed = true; 3193 if (DEBUG_PREFERRED) { 3194 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3195 } 3196 break; 3197 } 3198 3199 // Okay we found a previously set preferred or last chosen app. 3200 // If the result set is different from when this 3201 // was created, we need to clear it and re-ask the 3202 // user their preference, if we're looking for an "always" type entry. 3203 if (always && !pa.mPref.sameSet(query, priority)) { 3204 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3205 + intent + " type " + resolvedType); 3206 if (DEBUG_PREFERRED) { 3207 Slog.v(TAG, "Removing preferred activity since set changed " 3208 + pa.mPref.mComponent); 3209 } 3210 pir.removeFilter(pa); 3211 // Re-add the filter as a "last chosen" entry (!always) 3212 PreferredActivity lastChosen = new PreferredActivity( 3213 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3214 pir.addFilter(lastChosen); 3215 changed = true; 3216 return null; 3217 } 3218 3219 // Yay! Either the set matched or we're looking for the last chosen 3220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3221 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3222 return ri; 3223 } 3224 } 3225 } finally { 3226 if (changed) { 3227 if (DEBUG_PREFERRED) { 3228 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3229 } 3230 mSettings.writePackageRestrictionsLPr(userId); 3231 } 3232 } 3233 } 3234 } 3235 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3236 return null; 3237 } 3238 3239 /* 3240 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3241 */ 3242 @Override 3243 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3244 int targetUserId) { 3245 mContext.enforceCallingOrSelfPermission( 3246 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3247 List<CrossProfileIntentFilter> matches = 3248 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3249 if (matches != null) { 3250 int size = matches.size(); 3251 for (int i = 0; i < size; i++) { 3252 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3253 } 3254 } 3255 return false; 3256 } 3257 3258 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3259 String resolvedType, int userId) { 3260 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3261 if (resolver != null) { 3262 return resolver.queryIntent(intent, resolvedType, false, userId); 3263 } 3264 return null; 3265 } 3266 3267 @Override 3268 public List<ResolveInfo> queryIntentActivities(Intent intent, 3269 String resolvedType, int flags, int userId) { 3270 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3271 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3272 ComponentName comp = intent.getComponent(); 3273 if (comp == null) { 3274 if (intent.getSelector() != null) { 3275 intent = intent.getSelector(); 3276 comp = intent.getComponent(); 3277 } 3278 } 3279 3280 if (comp != null) { 3281 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3282 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3283 if (ai != null) { 3284 final ResolveInfo ri = new ResolveInfo(); 3285 ri.activityInfo = ai; 3286 list.add(ri); 3287 } 3288 return list; 3289 } 3290 3291 // reader 3292 synchronized (mPackages) { 3293 final String pkgName = intent.getPackage(); 3294 if (pkgName == null) { 3295 List<CrossProfileIntentFilter> matchingFilters = 3296 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3297 // Check for results that need to skip the current profile. 3298 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3299 resolvedType, flags, userId); 3300 if (resolveInfo != null) { 3301 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3302 result.add(resolveInfo); 3303 return result; 3304 } 3305 // Check for cross profile results. 3306 resolveInfo = queryCrossProfileIntents( 3307 matchingFilters, intent, resolvedType, flags, userId); 3308 3309 // Check for results in the current profile. 3310 List<ResolveInfo> result = mActivities.queryIntent( 3311 intent, resolvedType, flags, userId); 3312 if (resolveInfo != null) { 3313 result.add(resolveInfo); 3314 Collections.sort(result, mResolvePrioritySorter); 3315 } 3316 return result; 3317 } 3318 final PackageParser.Package pkg = mPackages.get(pkgName); 3319 if (pkg != null) { 3320 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3321 pkg.activities, userId); 3322 } 3323 return new ArrayList<ResolveInfo>(); 3324 } 3325 } 3326 3327 private ResolveInfo querySkipCurrentProfileIntents( 3328 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3329 int flags, int sourceUserId) { 3330 if (matchingFilters != null) { 3331 int size = matchingFilters.size(); 3332 for (int i = 0; i < size; i ++) { 3333 CrossProfileIntentFilter filter = matchingFilters.get(i); 3334 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3335 // Checking if there are activities in the target user that can handle the 3336 // intent. 3337 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3338 flags, sourceUserId); 3339 if (resolveInfo != null) { 3340 return resolveInfo; 3341 } 3342 } 3343 } 3344 } 3345 return null; 3346 } 3347 3348 // Return matching ResolveInfo if any for skip current profile intent filters. 3349 private ResolveInfo queryCrossProfileIntents( 3350 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3351 int flags, int sourceUserId) { 3352 if (matchingFilters != null) { 3353 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3354 // match the same intent. For performance reasons, it is better not to 3355 // run queryIntent twice for the same userId 3356 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3357 int size = matchingFilters.size(); 3358 for (int i = 0; i < size; i++) { 3359 CrossProfileIntentFilter filter = matchingFilters.get(i); 3360 int targetUserId = filter.getTargetUserId(); 3361 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3362 && !alreadyTriedUserIds.get(targetUserId)) { 3363 // Checking if there are activities in the target user that can handle the 3364 // intent. 3365 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3366 flags, sourceUserId); 3367 if (resolveInfo != null) return resolveInfo; 3368 alreadyTriedUserIds.put(targetUserId, true); 3369 } 3370 } 3371 } 3372 return null; 3373 } 3374 3375 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3376 String resolvedType, int flags, int sourceUserId) { 3377 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3378 resolvedType, flags, filter.getTargetUserId()); 3379 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3380 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3381 } 3382 return null; 3383 } 3384 3385 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3386 int sourceUserId, int targetUserId) { 3387 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3388 String className; 3389 if (targetUserId == UserHandle.USER_OWNER) { 3390 className = FORWARD_INTENT_TO_USER_OWNER; 3391 } else { 3392 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3393 } 3394 ComponentName forwardingActivityComponentName = new ComponentName( 3395 mAndroidApplication.packageName, className); 3396 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3397 sourceUserId); 3398 if (targetUserId == UserHandle.USER_OWNER) { 3399 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3400 forwardingResolveInfo.noResourceId = true; 3401 } 3402 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3403 forwardingResolveInfo.priority = 0; 3404 forwardingResolveInfo.preferredOrder = 0; 3405 forwardingResolveInfo.match = 0; 3406 forwardingResolveInfo.isDefault = true; 3407 forwardingResolveInfo.filter = filter; 3408 forwardingResolveInfo.targetUserId = targetUserId; 3409 return forwardingResolveInfo; 3410 } 3411 3412 @Override 3413 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3414 Intent[] specifics, String[] specificTypes, Intent intent, 3415 String resolvedType, int flags, int userId) { 3416 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3417 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3418 false, "query intent activity options"); 3419 final String resultsAction = intent.getAction(); 3420 3421 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3422 | PackageManager.GET_RESOLVED_FILTER, userId); 3423 3424 if (DEBUG_INTENT_MATCHING) { 3425 Log.v(TAG, "Query " + intent + ": " + results); 3426 } 3427 3428 int specificsPos = 0; 3429 int N; 3430 3431 // todo: note that the algorithm used here is O(N^2). This 3432 // isn't a problem in our current environment, but if we start running 3433 // into situations where we have more than 5 or 10 matches then this 3434 // should probably be changed to something smarter... 3435 3436 // First we go through and resolve each of the specific items 3437 // that were supplied, taking care of removing any corresponding 3438 // duplicate items in the generic resolve list. 3439 if (specifics != null) { 3440 for (int i=0; i<specifics.length; i++) { 3441 final Intent sintent = specifics[i]; 3442 if (sintent == null) { 3443 continue; 3444 } 3445 3446 if (DEBUG_INTENT_MATCHING) { 3447 Log.v(TAG, "Specific #" + i + ": " + sintent); 3448 } 3449 3450 String action = sintent.getAction(); 3451 if (resultsAction != null && resultsAction.equals(action)) { 3452 // If this action was explicitly requested, then don't 3453 // remove things that have it. 3454 action = null; 3455 } 3456 3457 ResolveInfo ri = null; 3458 ActivityInfo ai = null; 3459 3460 ComponentName comp = sintent.getComponent(); 3461 if (comp == null) { 3462 ri = resolveIntent( 3463 sintent, 3464 specificTypes != null ? specificTypes[i] : null, 3465 flags, userId); 3466 if (ri == null) { 3467 continue; 3468 } 3469 if (ri == mResolveInfo) { 3470 // ACK! Must do something better with this. 3471 } 3472 ai = ri.activityInfo; 3473 comp = new ComponentName(ai.applicationInfo.packageName, 3474 ai.name); 3475 } else { 3476 ai = getActivityInfo(comp, flags, userId); 3477 if (ai == null) { 3478 continue; 3479 } 3480 } 3481 3482 // Look for any generic query activities that are duplicates 3483 // of this specific one, and remove them from the results. 3484 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3485 N = results.size(); 3486 int j; 3487 for (j=specificsPos; j<N; j++) { 3488 ResolveInfo sri = results.get(j); 3489 if ((sri.activityInfo.name.equals(comp.getClassName()) 3490 && sri.activityInfo.applicationInfo.packageName.equals( 3491 comp.getPackageName())) 3492 || (action != null && sri.filter.matchAction(action))) { 3493 results.remove(j); 3494 if (DEBUG_INTENT_MATCHING) Log.v( 3495 TAG, "Removing duplicate item from " + j 3496 + " due to specific " + specificsPos); 3497 if (ri == null) { 3498 ri = sri; 3499 } 3500 j--; 3501 N--; 3502 } 3503 } 3504 3505 // Add this specific item to its proper place. 3506 if (ri == null) { 3507 ri = new ResolveInfo(); 3508 ri.activityInfo = ai; 3509 } 3510 results.add(specificsPos, ri); 3511 ri.specificIndex = i; 3512 specificsPos++; 3513 } 3514 } 3515 3516 // Now we go through the remaining generic results and remove any 3517 // duplicate actions that are found here. 3518 N = results.size(); 3519 for (int i=specificsPos; i<N-1; i++) { 3520 final ResolveInfo rii = results.get(i); 3521 if (rii.filter == null) { 3522 continue; 3523 } 3524 3525 // Iterate over all of the actions of this result's intent 3526 // filter... typically this should be just one. 3527 final Iterator<String> it = rii.filter.actionsIterator(); 3528 if (it == null) { 3529 continue; 3530 } 3531 while (it.hasNext()) { 3532 final String action = it.next(); 3533 if (resultsAction != null && resultsAction.equals(action)) { 3534 // If this action was explicitly requested, then don't 3535 // remove things that have it. 3536 continue; 3537 } 3538 for (int j=i+1; j<N; j++) { 3539 final ResolveInfo rij = results.get(j); 3540 if (rij.filter != null && rij.filter.hasAction(action)) { 3541 results.remove(j); 3542 if (DEBUG_INTENT_MATCHING) Log.v( 3543 TAG, "Removing duplicate item from " + j 3544 + " due to action " + action + " at " + i); 3545 j--; 3546 N--; 3547 } 3548 } 3549 } 3550 3551 // If the caller didn't request filter information, drop it now 3552 // so we don't have to marshall/unmarshall it. 3553 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3554 rii.filter = null; 3555 } 3556 } 3557 3558 // Filter out the caller activity if so requested. 3559 if (caller != null) { 3560 N = results.size(); 3561 for (int i=0; i<N; i++) { 3562 ActivityInfo ainfo = results.get(i).activityInfo; 3563 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3564 && caller.getClassName().equals(ainfo.name)) { 3565 results.remove(i); 3566 break; 3567 } 3568 } 3569 } 3570 3571 // If the caller didn't request filter information, 3572 // drop them now so we don't have to 3573 // marshall/unmarshall it. 3574 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3575 N = results.size(); 3576 for (int i=0; i<N; i++) { 3577 results.get(i).filter = null; 3578 } 3579 } 3580 3581 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3582 return results; 3583 } 3584 3585 @Override 3586 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3587 int userId) { 3588 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3589 ComponentName comp = intent.getComponent(); 3590 if (comp == null) { 3591 if (intent.getSelector() != null) { 3592 intent = intent.getSelector(); 3593 comp = intent.getComponent(); 3594 } 3595 } 3596 if (comp != null) { 3597 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3598 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3599 if (ai != null) { 3600 ResolveInfo ri = new ResolveInfo(); 3601 ri.activityInfo = ai; 3602 list.add(ri); 3603 } 3604 return list; 3605 } 3606 3607 // reader 3608 synchronized (mPackages) { 3609 String pkgName = intent.getPackage(); 3610 if (pkgName == null) { 3611 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3612 } 3613 final PackageParser.Package pkg = mPackages.get(pkgName); 3614 if (pkg != null) { 3615 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3616 userId); 3617 } 3618 return null; 3619 } 3620 } 3621 3622 @Override 3623 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3624 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3625 if (!sUserManager.exists(userId)) return null; 3626 if (query != null) { 3627 if (query.size() >= 1) { 3628 // If there is more than one service with the same priority, 3629 // just arbitrarily pick the first one. 3630 return query.get(0); 3631 } 3632 } 3633 return null; 3634 } 3635 3636 @Override 3637 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3638 int userId) { 3639 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3640 ComponentName comp = intent.getComponent(); 3641 if (comp == null) { 3642 if (intent.getSelector() != null) { 3643 intent = intent.getSelector(); 3644 comp = intent.getComponent(); 3645 } 3646 } 3647 if (comp != null) { 3648 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3649 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3650 if (si != null) { 3651 final ResolveInfo ri = new ResolveInfo(); 3652 ri.serviceInfo = si; 3653 list.add(ri); 3654 } 3655 return list; 3656 } 3657 3658 // reader 3659 synchronized (mPackages) { 3660 String pkgName = intent.getPackage(); 3661 if (pkgName == null) { 3662 return mServices.queryIntent(intent, resolvedType, flags, userId); 3663 } 3664 final PackageParser.Package pkg = mPackages.get(pkgName); 3665 if (pkg != null) { 3666 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3667 userId); 3668 } 3669 return null; 3670 } 3671 } 3672 3673 @Override 3674 public List<ResolveInfo> queryIntentContentProviders( 3675 Intent intent, String resolvedType, int flags, int userId) { 3676 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3677 ComponentName comp = intent.getComponent(); 3678 if (comp == null) { 3679 if (intent.getSelector() != null) { 3680 intent = intent.getSelector(); 3681 comp = intent.getComponent(); 3682 } 3683 } 3684 if (comp != null) { 3685 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3686 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3687 if (pi != null) { 3688 final ResolveInfo ri = new ResolveInfo(); 3689 ri.providerInfo = pi; 3690 list.add(ri); 3691 } 3692 return list; 3693 } 3694 3695 // reader 3696 synchronized (mPackages) { 3697 String pkgName = intent.getPackage(); 3698 if (pkgName == null) { 3699 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3700 } 3701 final PackageParser.Package pkg = mPackages.get(pkgName); 3702 if (pkg != null) { 3703 return mProviders.queryIntentForPackage( 3704 intent, resolvedType, flags, pkg.providers, userId); 3705 } 3706 return null; 3707 } 3708 } 3709 3710 @Override 3711 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3712 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3713 3714 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3715 3716 // writer 3717 synchronized (mPackages) { 3718 ArrayList<PackageInfo> list; 3719 if (listUninstalled) { 3720 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3721 for (PackageSetting ps : mSettings.mPackages.values()) { 3722 PackageInfo pi; 3723 if (ps.pkg != null) { 3724 pi = generatePackageInfo(ps.pkg, flags, userId); 3725 } else { 3726 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3727 } 3728 if (pi != null) { 3729 list.add(pi); 3730 } 3731 } 3732 } else { 3733 list = new ArrayList<PackageInfo>(mPackages.size()); 3734 for (PackageParser.Package p : mPackages.values()) { 3735 PackageInfo pi = generatePackageInfo(p, flags, userId); 3736 if (pi != null) { 3737 list.add(pi); 3738 } 3739 } 3740 } 3741 3742 return new ParceledListSlice<PackageInfo>(list); 3743 } 3744 } 3745 3746 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3747 String[] permissions, boolean[] tmp, int flags, int userId) { 3748 int numMatch = 0; 3749 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3750 for (int i=0; i<permissions.length; i++) { 3751 if (gp.grantedPermissions.contains(permissions[i])) { 3752 tmp[i] = true; 3753 numMatch++; 3754 } else { 3755 tmp[i] = false; 3756 } 3757 } 3758 if (numMatch == 0) { 3759 return; 3760 } 3761 PackageInfo pi; 3762 if (ps.pkg != null) { 3763 pi = generatePackageInfo(ps.pkg, flags, userId); 3764 } else { 3765 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3766 } 3767 // The above might return null in cases of uninstalled apps or install-state 3768 // skew across users/profiles. 3769 if (pi != null) { 3770 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3771 if (numMatch == permissions.length) { 3772 pi.requestedPermissions = permissions; 3773 } else { 3774 pi.requestedPermissions = new String[numMatch]; 3775 numMatch = 0; 3776 for (int i=0; i<permissions.length; i++) { 3777 if (tmp[i]) { 3778 pi.requestedPermissions[numMatch] = permissions[i]; 3779 numMatch++; 3780 } 3781 } 3782 } 3783 } 3784 list.add(pi); 3785 } 3786 } 3787 3788 @Override 3789 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3790 String[] permissions, int flags, int userId) { 3791 if (!sUserManager.exists(userId)) return null; 3792 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3793 3794 // writer 3795 synchronized (mPackages) { 3796 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3797 boolean[] tmpBools = new boolean[permissions.length]; 3798 if (listUninstalled) { 3799 for (PackageSetting ps : mSettings.mPackages.values()) { 3800 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3801 } 3802 } else { 3803 for (PackageParser.Package pkg : mPackages.values()) { 3804 PackageSetting ps = (PackageSetting)pkg.mExtras; 3805 if (ps != null) { 3806 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3807 userId); 3808 } 3809 } 3810 } 3811 3812 return new ParceledListSlice<PackageInfo>(list); 3813 } 3814 } 3815 3816 @Override 3817 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3818 if (!sUserManager.exists(userId)) return null; 3819 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3820 3821 // writer 3822 synchronized (mPackages) { 3823 ArrayList<ApplicationInfo> list; 3824 if (listUninstalled) { 3825 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3826 for (PackageSetting ps : mSettings.mPackages.values()) { 3827 ApplicationInfo ai; 3828 if (ps.pkg != null) { 3829 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3830 ps.readUserState(userId), userId); 3831 } else { 3832 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3833 } 3834 if (ai != null) { 3835 list.add(ai); 3836 } 3837 } 3838 } else { 3839 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3840 for (PackageParser.Package p : mPackages.values()) { 3841 if (p.mExtras != null) { 3842 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3843 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3844 if (ai != null) { 3845 list.add(ai); 3846 } 3847 } 3848 } 3849 } 3850 3851 return new ParceledListSlice<ApplicationInfo>(list); 3852 } 3853 } 3854 3855 public List<ApplicationInfo> getPersistentApplications(int flags) { 3856 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3857 3858 // reader 3859 synchronized (mPackages) { 3860 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3861 final int userId = UserHandle.getCallingUserId(); 3862 while (i.hasNext()) { 3863 final PackageParser.Package p = i.next(); 3864 if (p.applicationInfo != null 3865 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3866 && (!mSafeMode || isSystemApp(p))) { 3867 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3868 if (ps != null) { 3869 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3870 ps.readUserState(userId), userId); 3871 if (ai != null) { 3872 finalList.add(ai); 3873 } 3874 } 3875 } 3876 } 3877 } 3878 3879 return finalList; 3880 } 3881 3882 @Override 3883 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3884 if (!sUserManager.exists(userId)) return null; 3885 // reader 3886 synchronized (mPackages) { 3887 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3888 PackageSetting ps = provider != null 3889 ? mSettings.mPackages.get(provider.owner.packageName) 3890 : null; 3891 return ps != null 3892 && mSettings.isEnabledLPr(provider.info, flags, userId) 3893 && (!mSafeMode || (provider.info.applicationInfo.flags 3894 &ApplicationInfo.FLAG_SYSTEM) != 0) 3895 ? PackageParser.generateProviderInfo(provider, flags, 3896 ps.readUserState(userId), userId) 3897 : null; 3898 } 3899 } 3900 3901 /** 3902 * @deprecated 3903 */ 3904 @Deprecated 3905 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3906 // reader 3907 synchronized (mPackages) { 3908 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3909 .entrySet().iterator(); 3910 final int userId = UserHandle.getCallingUserId(); 3911 while (i.hasNext()) { 3912 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3913 PackageParser.Provider p = entry.getValue(); 3914 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3915 3916 if (ps != null && p.syncable 3917 && (!mSafeMode || (p.info.applicationInfo.flags 3918 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3919 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3920 ps.readUserState(userId), userId); 3921 if (info != null) { 3922 outNames.add(entry.getKey()); 3923 outInfo.add(info); 3924 } 3925 } 3926 } 3927 } 3928 } 3929 3930 @Override 3931 public List<ProviderInfo> queryContentProviders(String processName, 3932 int uid, int flags) { 3933 ArrayList<ProviderInfo> finalList = null; 3934 // reader 3935 synchronized (mPackages) { 3936 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3937 final int userId = processName != null ? 3938 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3939 while (i.hasNext()) { 3940 final PackageParser.Provider p = i.next(); 3941 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3942 if (ps != null && p.info.authority != null 3943 && (processName == null 3944 || (p.info.processName.equals(processName) 3945 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3946 && mSettings.isEnabledLPr(p.info, flags, userId) 3947 && (!mSafeMode 3948 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3949 if (finalList == null) { 3950 finalList = new ArrayList<ProviderInfo>(3); 3951 } 3952 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3953 ps.readUserState(userId), userId); 3954 if (info != null) { 3955 finalList.add(info); 3956 } 3957 } 3958 } 3959 } 3960 3961 if (finalList != null) { 3962 Collections.sort(finalList, mProviderInitOrderSorter); 3963 } 3964 3965 return finalList; 3966 } 3967 3968 @Override 3969 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3970 int flags) { 3971 // reader 3972 synchronized (mPackages) { 3973 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3974 return PackageParser.generateInstrumentationInfo(i, flags); 3975 } 3976 } 3977 3978 @Override 3979 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3980 int flags) { 3981 ArrayList<InstrumentationInfo> finalList = 3982 new ArrayList<InstrumentationInfo>(); 3983 3984 // reader 3985 synchronized (mPackages) { 3986 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3987 while (i.hasNext()) { 3988 final PackageParser.Instrumentation p = i.next(); 3989 if (targetPackage == null 3990 || targetPackage.equals(p.info.targetPackage)) { 3991 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3992 flags); 3993 if (ii != null) { 3994 finalList.add(ii); 3995 } 3996 } 3997 } 3998 } 3999 4000 return finalList; 4001 } 4002 4003 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4004 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4005 if (overlays == null) { 4006 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4007 return; 4008 } 4009 for (PackageParser.Package opkg : overlays.values()) { 4010 // Not much to do if idmap fails: we already logged the error 4011 // and we certainly don't want to abort installation of pkg simply 4012 // because an overlay didn't fit properly. For these reasons, 4013 // ignore the return value of createIdmapForPackagePairLI. 4014 createIdmapForPackagePairLI(pkg, opkg); 4015 } 4016 } 4017 4018 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4019 PackageParser.Package opkg) { 4020 if (!opkg.mTrustedOverlay) { 4021 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4022 opkg.baseCodePath + ": overlay not trusted"); 4023 return false; 4024 } 4025 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4026 if (overlaySet == null) { 4027 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4028 opkg.baseCodePath + " but target package has no known overlays"); 4029 return false; 4030 } 4031 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4032 // TODO: generate idmap for split APKs 4033 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4034 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4035 + opkg.baseCodePath); 4036 return false; 4037 } 4038 PackageParser.Package[] overlayArray = 4039 overlaySet.values().toArray(new PackageParser.Package[0]); 4040 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4041 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4042 return p1.mOverlayPriority - p2.mOverlayPriority; 4043 } 4044 }; 4045 Arrays.sort(overlayArray, cmp); 4046 4047 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4048 int i = 0; 4049 for (PackageParser.Package p : overlayArray) { 4050 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4051 } 4052 return true; 4053 } 4054 4055 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4056 final File[] files = dir.listFiles(); 4057 if (ArrayUtils.isEmpty(files)) { 4058 Log.d(TAG, "No files in app dir " + dir); 4059 return; 4060 } 4061 4062 if (DEBUG_PACKAGE_SCANNING) { 4063 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4064 + " flags=0x" + Integer.toHexString(parseFlags)); 4065 } 4066 4067 for (File file : files) { 4068 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4069 && !PackageInstallerService.isStageName(file.getName()); 4070 if (!isPackage) { 4071 // Ignore entries which are not packages 4072 continue; 4073 } 4074 try { 4075 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4076 scanFlags, currentTime, null); 4077 } catch (PackageManagerException e) { 4078 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4079 4080 // Delete invalid userdata apps 4081 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4082 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4083 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4084 if (file.isDirectory()) { 4085 FileUtils.deleteContents(file); 4086 } 4087 file.delete(); 4088 } 4089 } 4090 } 4091 } 4092 4093 private static File getSettingsProblemFile() { 4094 File dataDir = Environment.getDataDirectory(); 4095 File systemDir = new File(dataDir, "system"); 4096 File fname = new File(systemDir, "uiderrors.txt"); 4097 return fname; 4098 } 4099 4100 static void reportSettingsProblem(int priority, String msg) { 4101 logCriticalInfo(priority, msg); 4102 } 4103 4104 static void logCriticalInfo(int priority, String msg) { 4105 Slog.println(priority, TAG, msg); 4106 EventLogTags.writePmCriticalInfo(msg); 4107 try { 4108 File fname = getSettingsProblemFile(); 4109 FileOutputStream out = new FileOutputStream(fname, true); 4110 PrintWriter pw = new FastPrintWriter(out); 4111 SimpleDateFormat formatter = new SimpleDateFormat(); 4112 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4113 pw.println(dateString + ": " + msg); 4114 pw.close(); 4115 FileUtils.setPermissions( 4116 fname.toString(), 4117 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4118 -1, -1); 4119 } catch (java.io.IOException e) { 4120 } 4121 } 4122 4123 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4124 PackageParser.Package pkg, File srcFile, int parseFlags) 4125 throws PackageManagerException { 4126 if (ps != null 4127 && ps.codePath.equals(srcFile) 4128 && ps.timeStamp == srcFile.lastModified() 4129 && !isCompatSignatureUpdateNeeded(pkg)) { 4130 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4131 if (ps.signatures.mSignatures != null 4132 && ps.signatures.mSignatures.length != 0 4133 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4134 // Optimization: reuse the existing cached certificates 4135 // if the package appears to be unchanged. 4136 pkg.mSignatures = ps.signatures.mSignatures; 4137 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4138 synchronized (mPackages) { 4139 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4140 } 4141 return; 4142 } 4143 4144 Slog.w(TAG, "PackageSetting for " + ps.name 4145 + " is missing signatures. Collecting certs again to recover them."); 4146 } else { 4147 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4148 } 4149 4150 try { 4151 pp.collectCertificates(pkg, parseFlags); 4152 pp.collectManifestDigest(pkg); 4153 } catch (PackageParserException e) { 4154 throw PackageManagerException.from(e); 4155 } 4156 } 4157 4158 /* 4159 * Scan a package and return the newly parsed package. 4160 * Returns null in case of errors and the error code is stored in mLastScanError 4161 */ 4162 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4163 long currentTime, UserHandle user) throws PackageManagerException { 4164 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4165 parseFlags |= mDefParseFlags; 4166 PackageParser pp = new PackageParser(); 4167 pp.setSeparateProcesses(mSeparateProcesses); 4168 pp.setOnlyCoreApps(mOnlyCore); 4169 pp.setDisplayMetrics(mMetrics); 4170 4171 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4172 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4173 } 4174 4175 final PackageParser.Package pkg; 4176 try { 4177 pkg = pp.parsePackage(scanFile, parseFlags); 4178 } catch (PackageParserException e) { 4179 throw PackageManagerException.from(e); 4180 } 4181 4182 PackageSetting ps = null; 4183 PackageSetting updatedPkg; 4184 // reader 4185 synchronized (mPackages) { 4186 // Look to see if we already know about this package. 4187 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4188 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4189 // This package has been renamed to its original name. Let's 4190 // use that. 4191 ps = mSettings.peekPackageLPr(oldName); 4192 } 4193 // If there was no original package, see one for the real package name. 4194 if (ps == null) { 4195 ps = mSettings.peekPackageLPr(pkg.packageName); 4196 } 4197 // Check to see if this package could be hiding/updating a system 4198 // package. Must look for it either under the original or real 4199 // package name depending on our state. 4200 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4201 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4202 } 4203 boolean updatedPkgBetter = false; 4204 // First check if this is a system package that may involve an update 4205 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4206 if (ps != null && !ps.codePath.equals(scanFile)) { 4207 // The path has changed from what was last scanned... check the 4208 // version of the new path against what we have stored to determine 4209 // what to do. 4210 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4211 if (pkg.mVersionCode < ps.versionCode) { 4212 // The system package has been updated and the code path does not match 4213 // Ignore entry. Skip it. 4214 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4215 + " ignored: updated version " + ps.versionCode 4216 + " better than this " + pkg.mVersionCode); 4217 if (!updatedPkg.codePath.equals(scanFile)) { 4218 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4219 + ps.name + " changing from " + updatedPkg.codePathString 4220 + " to " + scanFile); 4221 updatedPkg.codePath = scanFile; 4222 updatedPkg.codePathString = scanFile.toString(); 4223 // This is the point at which we know that the system-disk APK 4224 // for this package has moved during a reboot (e.g. due to an OTA), 4225 // so we need to reevaluate it for privilege policy. 4226 if (locationIsPrivileged(scanFile)) { 4227 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4228 } 4229 } 4230 updatedPkg.pkg = pkg; 4231 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4232 } else { 4233 // The current app on the system partition is better than 4234 // what we have updated to on the data partition; switch 4235 // back to the system partition version. 4236 // At this point, its safely assumed that package installation for 4237 // apps in system partition will go through. If not there won't be a working 4238 // version of the app 4239 // writer 4240 synchronized (mPackages) { 4241 // Just remove the loaded entries from package lists. 4242 mPackages.remove(ps.name); 4243 } 4244 4245 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4246 + " reverting from " + ps.codePathString 4247 + ": new version " + pkg.mVersionCode 4248 + " better than installed " + ps.versionCode); 4249 4250 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4251 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4252 getAppDexInstructionSets(ps)); 4253 synchronized (mInstallLock) { 4254 args.cleanUpResourcesLI(); 4255 } 4256 synchronized (mPackages) { 4257 mSettings.enableSystemPackageLPw(ps.name); 4258 } 4259 updatedPkgBetter = true; 4260 } 4261 } 4262 } 4263 4264 if (updatedPkg != null) { 4265 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4266 // initially 4267 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4268 4269 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4270 // flag set initially 4271 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4272 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4273 } 4274 } 4275 4276 // Verify certificates against what was last scanned 4277 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4278 4279 /* 4280 * A new system app appeared, but we already had a non-system one of the 4281 * same name installed earlier. 4282 */ 4283 boolean shouldHideSystemApp = false; 4284 if (updatedPkg == null && ps != null 4285 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4286 /* 4287 * Check to make sure the signatures match first. If they don't, 4288 * wipe the installed application and its data. 4289 */ 4290 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4291 != PackageManager.SIGNATURE_MATCH) { 4292 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4293 + " signatures don't match existing userdata copy; removing"); 4294 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4295 ps = null; 4296 } else { 4297 /* 4298 * If the newly-added system app is an older version than the 4299 * already installed version, hide it. It will be scanned later 4300 * and re-added like an update. 4301 */ 4302 if (pkg.mVersionCode < ps.versionCode) { 4303 shouldHideSystemApp = true; 4304 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4305 + " but new version " + pkg.mVersionCode + " better than installed " 4306 + ps.versionCode + "; hiding system"); 4307 } else { 4308 /* 4309 * The newly found system app is a newer version that the 4310 * one previously installed. Simply remove the 4311 * already-installed application and replace it with our own 4312 * while keeping the application data. 4313 */ 4314 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4315 + " reverting from " + ps.codePathString + ": new version " 4316 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4317 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4318 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4319 getAppDexInstructionSets(ps)); 4320 synchronized (mInstallLock) { 4321 args.cleanUpResourcesLI(); 4322 } 4323 } 4324 } 4325 } 4326 4327 // The apk is forward locked (not public) if its code and resources 4328 // are kept in different files. (except for app in either system or 4329 // vendor path). 4330 // TODO grab this value from PackageSettings 4331 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4332 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4333 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4334 } 4335 } 4336 4337 // TODO: extend to support forward-locked splits 4338 String resourcePath = null; 4339 String baseResourcePath = null; 4340 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4341 if (ps != null && ps.resourcePathString != null) { 4342 resourcePath = ps.resourcePathString; 4343 baseResourcePath = ps.resourcePathString; 4344 } else { 4345 // Should not happen at all. Just log an error. 4346 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4347 } 4348 } else { 4349 resourcePath = pkg.codePath; 4350 baseResourcePath = pkg.baseCodePath; 4351 } 4352 4353 // Set application objects path explicitly. 4354 pkg.applicationInfo.setCodePath(pkg.codePath); 4355 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4356 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4357 pkg.applicationInfo.setResourcePath(resourcePath); 4358 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4359 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4360 4361 // Note that we invoke the following method only if we are about to unpack an application 4362 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4363 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4364 4365 /* 4366 * If the system app should be overridden by a previously installed 4367 * data, hide the system app now and let the /data/app scan pick it up 4368 * again. 4369 */ 4370 if (shouldHideSystemApp) { 4371 synchronized (mPackages) { 4372 /* 4373 * We have to grant systems permissions before we hide, because 4374 * grantPermissions will assume the package update is trying to 4375 * expand its permissions. 4376 */ 4377 grantPermissionsLPw(pkg, true, pkg.packageName); 4378 mSettings.disableSystemPackageLPw(pkg.packageName); 4379 } 4380 } 4381 4382 return scannedPkg; 4383 } 4384 4385 private static String fixProcessName(String defProcessName, 4386 String processName, int uid) { 4387 if (processName == null) { 4388 return defProcessName; 4389 } 4390 return processName; 4391 } 4392 4393 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4394 throws PackageManagerException { 4395 if (pkgSetting.signatures.mSignatures != null) { 4396 // Already existing package. Make sure signatures match 4397 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4398 == PackageManager.SIGNATURE_MATCH; 4399 if (!match) { 4400 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4401 == PackageManager.SIGNATURE_MATCH; 4402 } 4403 if (!match) { 4404 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4405 + pkg.packageName + " signatures do not match the " 4406 + "previously installed version; ignoring!"); 4407 } 4408 } 4409 4410 // Check for shared user signatures 4411 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4412 // Already existing package. Make sure signatures match 4413 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4414 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4415 if (!match) { 4416 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4417 == PackageManager.SIGNATURE_MATCH; 4418 } 4419 if (!match) { 4420 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4421 "Package " + pkg.packageName 4422 + " has no signatures that match those in shared user " 4423 + pkgSetting.sharedUser.name + "; ignoring!"); 4424 } 4425 } 4426 } 4427 4428 /** 4429 * Enforces that only the system UID or root's UID can call a method exposed 4430 * via Binder. 4431 * 4432 * @param message used as message if SecurityException is thrown 4433 * @throws SecurityException if the caller is not system or root 4434 */ 4435 private static final void enforceSystemOrRoot(String message) { 4436 final int uid = Binder.getCallingUid(); 4437 if (uid != Process.SYSTEM_UID && uid != 0) { 4438 throw new SecurityException(message); 4439 } 4440 } 4441 4442 @Override 4443 public void performBootDexOpt() { 4444 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4445 4446 final HashSet<PackageParser.Package> pkgs; 4447 synchronized (mPackages) { 4448 pkgs = mDeferredDexOpt; 4449 mDeferredDexOpt = null; 4450 } 4451 4452 if (pkgs != null) { 4453 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4454 // in case the device runs out of space. 4455 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4456 // Give priority to system apps that listen for pre boot complete. 4457 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4458 HashSet<String> pkgNames = getPackageNamesForIntent(intent); 4459 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4460 PackageParser.Package pkg = it.next(); 4461 if (pkgNames.contains(pkg.packageName)) { 4462 sortedPkgs.add(pkg); 4463 it.remove(); 4464 } 4465 } 4466 // Give priority to system apps. 4467 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4468 PackageParser.Package pkg = it.next(); 4469 if (isSystemApp(pkg)) { 4470 sortedPkgs.add(pkg); 4471 it.remove(); 4472 } 4473 } 4474 // Give priority to apps that listen for boot complete. 4475 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4476 pkgNames = getPackageNamesForIntent(intent); 4477 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4478 PackageParser.Package pkg = it.next(); 4479 if (pkgNames.contains(pkg.packageName)) { 4480 sortedPkgs.add(pkg); 4481 it.remove(); 4482 } 4483 } 4484 // Filter out packages that aren't recently used. 4485 filterRecentlyUsedApps(pkgs); 4486 // Add all remaining apps. 4487 for (PackageParser.Package pkg : pkgs) { 4488 sortedPkgs.add(pkg); 4489 } 4490 4491 int i = 0; 4492 int total = sortedPkgs.size(); 4493 for (PackageParser.Package pkg : sortedPkgs) { 4494 performBootDexOpt(pkg, ++i, total); 4495 } 4496 } 4497 } 4498 4499 private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) { 4500 // Filter out packages that aren't recently used. 4501 // 4502 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4503 // should do a full dexopt. 4504 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4505 // TODO: add a property to control this? 4506 long dexOptLRUThresholdInMinutes; 4507 if (mLazyDexOpt) { 4508 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4509 } else { 4510 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4511 } 4512 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4513 4514 int total = pkgs.size(); 4515 int skipped = 0; 4516 long now = System.currentTimeMillis(); 4517 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4518 PackageParser.Package pkg = i.next(); 4519 long then = pkg.mLastPackageUsageTimeInMills; 4520 if (then + dexOptLRUThresholdInMills < now) { 4521 if (DEBUG_DEXOPT) { 4522 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4523 ((then == 0) ? "never" : new Date(then))); 4524 } 4525 i.remove(); 4526 skipped++; 4527 } 4528 } 4529 if (DEBUG_DEXOPT) { 4530 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4531 } 4532 } 4533 } 4534 4535 private HashSet<String> getPackageNamesForIntent(Intent intent) { 4536 List<ResolveInfo> ris = null; 4537 try { 4538 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4539 intent, null, 0, UserHandle.USER_OWNER); 4540 } catch (RemoteException e) { 4541 } 4542 HashSet<String> pkgNames = new HashSet<String>(); 4543 if (ris != null) { 4544 for (ResolveInfo ri : ris) { 4545 pkgNames.add(ri.activityInfo.packageName); 4546 } 4547 } 4548 return pkgNames; 4549 } 4550 4551 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4552 if (DEBUG_DEXOPT) { 4553 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4554 } 4555 if (!isFirstBoot()) { 4556 try { 4557 ActivityManagerNative.getDefault().showBootMessage( 4558 mContext.getResources().getString(R.string.android_upgrading_apk, 4559 curr, total), true); 4560 } catch (RemoteException e) { 4561 } 4562 } 4563 PackageParser.Package p = pkg; 4564 synchronized (mInstallLock) { 4565 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4566 false /* defer */, true /* include dependencies */); 4567 } 4568 } 4569 4570 @Override 4571 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4572 return performDexOpt(packageName, instructionSet, false); 4573 } 4574 4575 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4576 if (info.primaryCpuAbi == null) { 4577 return getPreferredInstructionSet(); 4578 } 4579 4580 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4581 } 4582 4583 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4584 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4585 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4586 if (!dexopt && !updateUsage) { 4587 // We aren't going to dexopt or update usage, so bail early. 4588 return false; 4589 } 4590 PackageParser.Package p; 4591 final String targetInstructionSet; 4592 synchronized (mPackages) { 4593 p = mPackages.get(packageName); 4594 if (p == null) { 4595 return false; 4596 } 4597 if (updateUsage) { 4598 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4599 } 4600 mPackageUsage.write(false); 4601 if (!dexopt) { 4602 // We aren't going to dexopt, so bail early. 4603 return false; 4604 } 4605 4606 targetInstructionSet = instructionSet != null ? instructionSet : 4607 getPrimaryInstructionSet(p.applicationInfo); 4608 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4609 return false; 4610 } 4611 } 4612 4613 synchronized (mInstallLock) { 4614 final String[] instructionSets = new String[] { targetInstructionSet }; 4615 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4616 true /* include dependencies */) == DEX_OPT_PERFORMED; 4617 } 4618 } 4619 4620 public HashSet<String> getPackagesThatNeedDexOpt() { 4621 HashSet<String> pkgs = null; 4622 synchronized (mPackages) { 4623 for (PackageParser.Package p : mPackages.values()) { 4624 if (DEBUG_DEXOPT) { 4625 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4626 } 4627 if (!p.mDexOptPerformed.isEmpty()) { 4628 continue; 4629 } 4630 if (pkgs == null) { 4631 pkgs = new HashSet<String>(); 4632 } 4633 pkgs.add(p.packageName); 4634 } 4635 } 4636 return pkgs; 4637 } 4638 4639 public void shutdown() { 4640 mPackageUsage.write(true); 4641 } 4642 4643 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4644 boolean forceDex, boolean defer, HashSet<String> done) { 4645 for (int i=0; i<libs.size(); i++) { 4646 PackageParser.Package libPkg; 4647 String libName; 4648 synchronized (mPackages) { 4649 libName = libs.get(i); 4650 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4651 if (lib != null && lib.apk != null) { 4652 libPkg = mPackages.get(lib.apk); 4653 } else { 4654 libPkg = null; 4655 } 4656 } 4657 if (libPkg != null && !done.contains(libName)) { 4658 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4659 } 4660 } 4661 } 4662 4663 static final int DEX_OPT_SKIPPED = 0; 4664 static final int DEX_OPT_PERFORMED = 1; 4665 static final int DEX_OPT_DEFERRED = 2; 4666 static final int DEX_OPT_FAILED = -1; 4667 4668 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4669 boolean forceDex, boolean defer, HashSet<String> done) { 4670 final String[] instructionSets = targetInstructionSets != null ? 4671 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4672 4673 if (done != null) { 4674 done.add(pkg.packageName); 4675 if (pkg.usesLibraries != null) { 4676 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4677 } 4678 if (pkg.usesOptionalLibraries != null) { 4679 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4680 } 4681 } 4682 4683 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4684 return DEX_OPT_SKIPPED; 4685 } 4686 4687 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4688 4689 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4690 boolean performedDexOpt = false; 4691 // There are three basic cases here: 4692 // 1.) we need to dexopt, either because we are forced or it is needed 4693 // 2.) we are defering a needed dexopt 4694 // 3.) we are skipping an unneeded dexopt 4695 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4696 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4697 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4698 continue; 4699 } 4700 4701 for (String path : paths) { 4702 try { 4703 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4704 // patckage or the one we find does not match the image checksum (i.e. it was 4705 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4706 // odex file and it matches the checksum of the image but not its base address, 4707 // meaning we need to move it. 4708 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4709 pkg.packageName, dexCodeInstructionSet, defer); 4710 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4711 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4712 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4713 + " vmSafeMode=" + vmSafeMode); 4714 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4715 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4716 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4717 4718 if (ret < 0) { 4719 // Don't bother running dexopt again if we failed, it will probably 4720 // just result in an error again. Also, don't bother dexopting for other 4721 // paths & ISAs. 4722 return DEX_OPT_FAILED; 4723 } 4724 4725 performedDexOpt = true; 4726 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4727 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4728 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4729 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4730 pkg.packageName, dexCodeInstructionSet); 4731 4732 if (ret < 0) { 4733 // Don't bother running patchoat again if we failed, it will probably 4734 // just result in an error again. Also, don't bother dexopting for other 4735 // paths & ISAs. 4736 return DEX_OPT_FAILED; 4737 } 4738 4739 performedDexOpt = true; 4740 } 4741 4742 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4743 // paths and instruction sets. We'll deal with them all together when we process 4744 // our list of deferred dexopts. 4745 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4746 if (mDeferredDexOpt == null) { 4747 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4748 } 4749 mDeferredDexOpt.add(pkg); 4750 return DEX_OPT_DEFERRED; 4751 } 4752 } catch (FileNotFoundException e) { 4753 Slog.w(TAG, "Apk not found for dexopt: " + path); 4754 return DEX_OPT_FAILED; 4755 } catch (IOException e) { 4756 Slog.w(TAG, "IOException reading apk: " + path, e); 4757 return DEX_OPT_FAILED; 4758 } catch (StaleDexCacheError e) { 4759 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4760 return DEX_OPT_FAILED; 4761 } catch (Exception e) { 4762 Slog.w(TAG, "Exception when doing dexopt : ", e); 4763 return DEX_OPT_FAILED; 4764 } 4765 } 4766 4767 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4768 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4769 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4770 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4771 // it. 4772 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4773 } 4774 4775 // If we've gotten here, we're sure that no error occurred and that we haven't 4776 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4777 // we've skipped all of them because they are up to date. In both cases this 4778 // package doesn't need dexopt any longer. 4779 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4780 } 4781 4782 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4783 if (info.primaryCpuAbi != null) { 4784 if (info.secondaryCpuAbi != null) { 4785 return new String[] { 4786 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4787 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4788 } else { 4789 return new String[] { 4790 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4791 } 4792 } 4793 4794 return new String[] { getPreferredInstructionSet() }; 4795 } 4796 4797 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4798 if (ps.primaryCpuAbiString != null) { 4799 if (ps.secondaryCpuAbiString != null) { 4800 return new String[] { 4801 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4802 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4803 } else { 4804 return new String[] { 4805 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4806 } 4807 } 4808 4809 return new String[] { getPreferredInstructionSet() }; 4810 } 4811 4812 private static String getPreferredInstructionSet() { 4813 if (sPreferredInstructionSet == null) { 4814 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4815 } 4816 4817 return sPreferredInstructionSet; 4818 } 4819 4820 private static List<String> getAllInstructionSets() { 4821 final String[] allAbis = Build.SUPPORTED_ABIS; 4822 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4823 4824 for (String abi : allAbis) { 4825 final String instructionSet = VMRuntime.getInstructionSet(abi); 4826 if (!allInstructionSets.contains(instructionSet)) { 4827 allInstructionSets.add(instructionSet); 4828 } 4829 } 4830 4831 return allInstructionSets; 4832 } 4833 4834 /** 4835 * Returns the instruction set that should be used to compile dex code. In the presence of 4836 * a native bridge this might be different than the one shared libraries use. 4837 */ 4838 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4839 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4840 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4841 } 4842 4843 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4844 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4845 for (String instructionSet : instructionSets) { 4846 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4847 } 4848 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4849 } 4850 4851 /** 4852 * Returns deduplicated list of supported instructions for dex code. 4853 */ 4854 public static String[] getAllDexCodeInstructionSets() { 4855 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 4856 for (int i = 0; i < supportedInstructionSets.length; i++) { 4857 String abi = Build.SUPPORTED_ABIS[i]; 4858 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 4859 } 4860 return getDexCodeInstructionSets(supportedInstructionSets); 4861 } 4862 4863 @Override 4864 public void forceDexOpt(String packageName) { 4865 enforceSystemOrRoot("forceDexOpt"); 4866 4867 PackageParser.Package pkg; 4868 synchronized (mPackages) { 4869 pkg = mPackages.get(packageName); 4870 if (pkg == null) { 4871 throw new IllegalArgumentException("Missing package: " + packageName); 4872 } 4873 } 4874 4875 synchronized (mInstallLock) { 4876 final String[] instructionSets = new String[] { 4877 getPrimaryInstructionSet(pkg.applicationInfo) }; 4878 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4879 if (res != DEX_OPT_PERFORMED) { 4880 throw new IllegalStateException("Failed to dexopt: " + res); 4881 } 4882 } 4883 } 4884 4885 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4886 boolean forceDex, boolean defer, boolean inclDependencies) { 4887 HashSet<String> done; 4888 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4889 done = new HashSet<String>(); 4890 done.add(pkg.packageName); 4891 } else { 4892 done = null; 4893 } 4894 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4895 } 4896 4897 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4898 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4899 Slog.w(TAG, "Unable to update from " + oldPkg.name 4900 + " to " + newPkg.packageName 4901 + ": old package not in system partition"); 4902 return false; 4903 } else if (mPackages.get(oldPkg.name) != null) { 4904 Slog.w(TAG, "Unable to update from " + oldPkg.name 4905 + " to " + newPkg.packageName 4906 + ": old package still exists"); 4907 return false; 4908 } 4909 return true; 4910 } 4911 4912 File getDataPathForUser(int userId) { 4913 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4914 } 4915 4916 private File getDataPathForPackage(String packageName, int userId) { 4917 /* 4918 * Until we fully support multiple users, return the directory we 4919 * previously would have. The PackageManagerTests will need to be 4920 * revised when this is changed back.. 4921 */ 4922 if (userId == 0) { 4923 return new File(mAppDataDir, packageName); 4924 } else { 4925 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4926 + File.separator + packageName); 4927 } 4928 } 4929 4930 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4931 int[] users = sUserManager.getUserIds(); 4932 int res = mInstaller.install(packageName, uid, uid, seinfo); 4933 if (res < 0) { 4934 return res; 4935 } 4936 for (int user : users) { 4937 if (user != 0) { 4938 res = mInstaller.createUserData(packageName, 4939 UserHandle.getUid(user, uid), user, seinfo); 4940 if (res < 0) { 4941 return res; 4942 } 4943 } 4944 } 4945 return res; 4946 } 4947 4948 private int removeDataDirsLI(String packageName) { 4949 int[] users = sUserManager.getUserIds(); 4950 int res = 0; 4951 for (int user : users) { 4952 int resInner = mInstaller.remove(packageName, user); 4953 if (resInner < 0) { 4954 res = resInner; 4955 } 4956 } 4957 4958 return res; 4959 } 4960 4961 private int deleteCodeCacheDirsLI(String packageName) { 4962 int[] users = sUserManager.getUserIds(); 4963 int res = 0; 4964 for (int user : users) { 4965 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4966 if (resInner < 0) { 4967 res = resInner; 4968 } 4969 } 4970 return res; 4971 } 4972 4973 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4974 PackageParser.Package changingLib) { 4975 if (file.path != null) { 4976 usesLibraryFiles.add(file.path); 4977 return; 4978 } 4979 PackageParser.Package p = mPackages.get(file.apk); 4980 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4981 // If we are doing this while in the middle of updating a library apk, 4982 // then we need to make sure to use that new apk for determining the 4983 // dependencies here. (We haven't yet finished committing the new apk 4984 // to the package manager state.) 4985 if (p == null || p.packageName.equals(changingLib.packageName)) { 4986 p = changingLib; 4987 } 4988 } 4989 if (p != null) { 4990 usesLibraryFiles.addAll(p.getAllCodePaths()); 4991 } 4992 } 4993 4994 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4995 PackageParser.Package changingLib) throws PackageManagerException { 4996 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4997 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4998 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4999 for (int i=0; i<N; i++) { 5000 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5001 if (file == null) { 5002 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5003 "Package " + pkg.packageName + " requires unavailable shared library " 5004 + pkg.usesLibraries.get(i) + "; failing!"); 5005 } 5006 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5007 } 5008 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5009 for (int i=0; i<N; i++) { 5010 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5011 if (file == null) { 5012 Slog.w(TAG, "Package " + pkg.packageName 5013 + " desires unavailable shared library " 5014 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5015 } else { 5016 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5017 } 5018 } 5019 N = usesLibraryFiles.size(); 5020 if (N > 0) { 5021 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5022 } else { 5023 pkg.usesLibraryFiles = null; 5024 } 5025 } 5026 } 5027 5028 private static boolean hasString(List<String> list, List<String> which) { 5029 if (list == null) { 5030 return false; 5031 } 5032 for (int i=list.size()-1; i>=0; i--) { 5033 for (int j=which.size()-1; j>=0; j--) { 5034 if (which.get(j).equals(list.get(i))) { 5035 return true; 5036 } 5037 } 5038 } 5039 return false; 5040 } 5041 5042 private void updateAllSharedLibrariesLPw() { 5043 for (PackageParser.Package pkg : mPackages.values()) { 5044 try { 5045 updateSharedLibrariesLPw(pkg, null); 5046 } catch (PackageManagerException e) { 5047 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5048 } 5049 } 5050 } 5051 5052 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5053 PackageParser.Package changingPkg) { 5054 ArrayList<PackageParser.Package> res = null; 5055 for (PackageParser.Package pkg : mPackages.values()) { 5056 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5057 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5058 if (res == null) { 5059 res = new ArrayList<PackageParser.Package>(); 5060 } 5061 res.add(pkg); 5062 try { 5063 updateSharedLibrariesLPw(pkg, changingPkg); 5064 } catch (PackageManagerException e) { 5065 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5066 } 5067 } 5068 } 5069 return res; 5070 } 5071 5072 /** 5073 * Derive the value of the {@code cpuAbiOverride} based on the provided 5074 * value and an optional stored value from the package settings. 5075 */ 5076 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5077 String cpuAbiOverride = null; 5078 5079 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5080 cpuAbiOverride = null; 5081 } else if (abiOverride != null) { 5082 cpuAbiOverride = abiOverride; 5083 } else if (settings != null) { 5084 cpuAbiOverride = settings.cpuAbiOverrideString; 5085 } 5086 5087 return cpuAbiOverride; 5088 } 5089 5090 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5091 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5092 boolean success = false; 5093 try { 5094 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5095 currentTime, user); 5096 success = true; 5097 return res; 5098 } finally { 5099 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5100 removeDataDirsLI(pkg.packageName); 5101 } 5102 } 5103 } 5104 5105 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5106 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5107 final File scanFile = new File(pkg.codePath); 5108 if (pkg.applicationInfo.getCodePath() == null || 5109 pkg.applicationInfo.getResourcePath() == null) { 5110 // Bail out. The resource and code paths haven't been set. 5111 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5112 "Code and resource paths haven't been set correctly"); 5113 } 5114 5115 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5116 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5117 } 5118 5119 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5120 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5121 } 5122 5123 if (mCustomResolverComponentName != null && 5124 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5125 setUpCustomResolverActivity(pkg); 5126 } 5127 5128 if (pkg.packageName.equals("android")) { 5129 synchronized (mPackages) { 5130 if (mAndroidApplication != null) { 5131 Slog.w(TAG, "*************************************************"); 5132 Slog.w(TAG, "Core android package being redefined. Skipping."); 5133 Slog.w(TAG, " file=" + scanFile); 5134 Slog.w(TAG, "*************************************************"); 5135 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5136 "Core android package being redefined. Skipping."); 5137 } 5138 5139 // Set up information for our fall-back user intent resolution activity. 5140 mPlatformPackage = pkg; 5141 pkg.mVersionCode = mSdkVersion; 5142 mAndroidApplication = pkg.applicationInfo; 5143 5144 if (!mResolverReplaced) { 5145 mResolveActivity.applicationInfo = mAndroidApplication; 5146 mResolveActivity.name = ResolverActivity.class.getName(); 5147 mResolveActivity.packageName = mAndroidApplication.packageName; 5148 mResolveActivity.processName = "system:ui"; 5149 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5150 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5151 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5152 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5153 mResolveActivity.exported = true; 5154 mResolveActivity.enabled = true; 5155 mResolveInfo.activityInfo = mResolveActivity; 5156 mResolveInfo.priority = 0; 5157 mResolveInfo.preferredOrder = 0; 5158 mResolveInfo.match = 0; 5159 mResolveComponentName = new ComponentName( 5160 mAndroidApplication.packageName, mResolveActivity.name); 5161 } 5162 } 5163 } 5164 5165 if (DEBUG_PACKAGE_SCANNING) { 5166 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5167 Log.d(TAG, "Scanning package " + pkg.packageName); 5168 } 5169 5170 if (mPackages.containsKey(pkg.packageName) 5171 || mSharedLibraries.containsKey(pkg.packageName)) { 5172 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5173 "Application package " + pkg.packageName 5174 + " already installed. Skipping duplicate."); 5175 } 5176 5177 // Initialize package source and resource directories 5178 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5179 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5180 5181 SharedUserSetting suid = null; 5182 PackageSetting pkgSetting = null; 5183 5184 if (!isSystemApp(pkg)) { 5185 // Only system apps can use these features. 5186 pkg.mOriginalPackages = null; 5187 pkg.mRealPackage = null; 5188 pkg.mAdoptPermissions = null; 5189 } 5190 5191 // writer 5192 synchronized (mPackages) { 5193 if (pkg.mSharedUserId != null) { 5194 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5195 if (suid == null) { 5196 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5197 "Creating application package " + pkg.packageName 5198 + " for shared user failed"); 5199 } 5200 if (DEBUG_PACKAGE_SCANNING) { 5201 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5202 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5203 + "): packages=" + suid.packages); 5204 } 5205 } 5206 5207 // Check if we are renaming from an original package name. 5208 PackageSetting origPackage = null; 5209 String realName = null; 5210 if (pkg.mOriginalPackages != null) { 5211 // This package may need to be renamed to a previously 5212 // installed name. Let's check on that... 5213 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5214 if (pkg.mOriginalPackages.contains(renamed)) { 5215 // This package had originally been installed as the 5216 // original name, and we have already taken care of 5217 // transitioning to the new one. Just update the new 5218 // one to continue using the old name. 5219 realName = pkg.mRealPackage; 5220 if (!pkg.packageName.equals(renamed)) { 5221 // Callers into this function may have already taken 5222 // care of renaming the package; only do it here if 5223 // it is not already done. 5224 pkg.setPackageName(renamed); 5225 } 5226 5227 } else { 5228 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5229 if ((origPackage = mSettings.peekPackageLPr( 5230 pkg.mOriginalPackages.get(i))) != null) { 5231 // We do have the package already installed under its 5232 // original name... should we use it? 5233 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5234 // New package is not compatible with original. 5235 origPackage = null; 5236 continue; 5237 } else if (origPackage.sharedUser != null) { 5238 // Make sure uid is compatible between packages. 5239 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5240 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5241 + " to " + pkg.packageName + ": old uid " 5242 + origPackage.sharedUser.name 5243 + " differs from " + pkg.mSharedUserId); 5244 origPackage = null; 5245 continue; 5246 } 5247 } else { 5248 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5249 + pkg.packageName + " to old name " + origPackage.name); 5250 } 5251 break; 5252 } 5253 } 5254 } 5255 } 5256 5257 if (mTransferedPackages.contains(pkg.packageName)) { 5258 Slog.w(TAG, "Package " + pkg.packageName 5259 + " was transferred to another, but its .apk remains"); 5260 } 5261 5262 // Just create the setting, don't add it yet. For already existing packages 5263 // the PkgSetting exists already and doesn't have to be created. 5264 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5265 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5266 pkg.applicationInfo.primaryCpuAbi, 5267 pkg.applicationInfo.secondaryCpuAbi, 5268 pkg.applicationInfo.flags, user, false); 5269 if (pkgSetting == null) { 5270 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5271 "Creating application package " + pkg.packageName + " failed"); 5272 } 5273 5274 if (pkgSetting.origPackage != null) { 5275 // If we are first transitioning from an original package, 5276 // fix up the new package's name now. We need to do this after 5277 // looking up the package under its new name, so getPackageLP 5278 // can take care of fiddling things correctly. 5279 pkg.setPackageName(origPackage.name); 5280 5281 // File a report about this. 5282 String msg = "New package " + pkgSetting.realName 5283 + " renamed to replace old package " + pkgSetting.name; 5284 reportSettingsProblem(Log.WARN, msg); 5285 5286 // Make a note of it. 5287 mTransferedPackages.add(origPackage.name); 5288 5289 // No longer need to retain this. 5290 pkgSetting.origPackage = null; 5291 } 5292 5293 if (realName != null) { 5294 // Make a note of it. 5295 mTransferedPackages.add(pkg.packageName); 5296 } 5297 5298 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5299 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5300 } 5301 5302 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5303 // Check all shared libraries and map to their actual file path. 5304 // We only do this here for apps not on a system dir, because those 5305 // are the only ones that can fail an install due to this. We 5306 // will take care of the system apps by updating all of their 5307 // library paths after the scan is done. 5308 updateSharedLibrariesLPw(pkg, null); 5309 } 5310 5311 if (mFoundPolicyFile) { 5312 SELinuxMMAC.assignSeinfoValue(pkg); 5313 } 5314 5315 pkg.applicationInfo.uid = pkgSetting.appId; 5316 pkg.mExtras = pkgSetting; 5317 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5318 try { 5319 verifySignaturesLP(pkgSetting, pkg); 5320 } catch (PackageManagerException e) { 5321 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5322 throw e; 5323 } 5324 // The signature has changed, but this package is in the system 5325 // image... let's recover! 5326 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5327 // However... if this package is part of a shared user, but it 5328 // doesn't match the signature of the shared user, let's fail. 5329 // What this means is that you can't change the signatures 5330 // associated with an overall shared user, which doesn't seem all 5331 // that unreasonable. 5332 if (pkgSetting.sharedUser != null) { 5333 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5334 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5335 throw new PackageManagerException( 5336 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5337 "Signature mismatch for shared user : " 5338 + pkgSetting.sharedUser); 5339 } 5340 } 5341 // File a report about this. 5342 String msg = "System package " + pkg.packageName 5343 + " signature changed; retaining data."; 5344 reportSettingsProblem(Log.WARN, msg); 5345 } 5346 } else { 5347 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5348 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5349 + pkg.packageName + " upgrade keys do not match the " 5350 + "previously installed version"); 5351 } else { 5352 // signatures may have changed as result of upgrade 5353 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5354 } 5355 } 5356 // Verify that this new package doesn't have any content providers 5357 // that conflict with existing packages. Only do this if the 5358 // package isn't already installed, since we don't want to break 5359 // things that are installed. 5360 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5361 final int N = pkg.providers.size(); 5362 int i; 5363 for (i=0; i<N; i++) { 5364 PackageParser.Provider p = pkg.providers.get(i); 5365 if (p.info.authority != null) { 5366 String names[] = p.info.authority.split(";"); 5367 for (int j = 0; j < names.length; j++) { 5368 if (mProvidersByAuthority.containsKey(names[j])) { 5369 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5370 final String otherPackageName = 5371 ((other != null && other.getComponentName() != null) ? 5372 other.getComponentName().getPackageName() : "?"); 5373 throw new PackageManagerException( 5374 INSTALL_FAILED_CONFLICTING_PROVIDER, 5375 "Can't install because provider name " + names[j] 5376 + " (in package " + pkg.applicationInfo.packageName 5377 + ") is already used by " + otherPackageName); 5378 } 5379 } 5380 } 5381 } 5382 } 5383 5384 if (pkg.mAdoptPermissions != null) { 5385 // This package wants to adopt ownership of permissions from 5386 // another package. 5387 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5388 final String origName = pkg.mAdoptPermissions.get(i); 5389 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5390 if (orig != null) { 5391 if (verifyPackageUpdateLPr(orig, pkg)) { 5392 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5393 + pkg.packageName); 5394 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5395 } 5396 } 5397 } 5398 } 5399 } 5400 5401 final String pkgName = pkg.packageName; 5402 5403 final long scanFileTime = scanFile.lastModified(); 5404 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5405 pkg.applicationInfo.processName = fixProcessName( 5406 pkg.applicationInfo.packageName, 5407 pkg.applicationInfo.processName, 5408 pkg.applicationInfo.uid); 5409 5410 File dataPath; 5411 if (mPlatformPackage == pkg) { 5412 // The system package is special. 5413 dataPath = new File(Environment.getDataDirectory(), "system"); 5414 5415 pkg.applicationInfo.dataDir = dataPath.getPath(); 5416 5417 } else { 5418 // This is a normal package, need to make its data directory. 5419 dataPath = getDataPathForPackage(pkg.packageName, 0); 5420 5421 boolean uidError = false; 5422 if (dataPath.exists()) { 5423 int currentUid = 0; 5424 try { 5425 StructStat stat = Os.stat(dataPath.getPath()); 5426 currentUid = stat.st_uid; 5427 } catch (ErrnoException e) { 5428 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5429 } 5430 5431 // If we have mismatched owners for the data path, we have a problem. 5432 if (currentUid != pkg.applicationInfo.uid) { 5433 boolean recovered = false; 5434 if (currentUid == 0) { 5435 // The directory somehow became owned by root. Wow. 5436 // This is probably because the system was stopped while 5437 // installd was in the middle of messing with its libs 5438 // directory. Ask installd to fix that. 5439 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5440 pkg.applicationInfo.uid); 5441 if (ret >= 0) { 5442 recovered = true; 5443 String msg = "Package " + pkg.packageName 5444 + " unexpectedly changed to uid 0; recovered to " + 5445 + pkg.applicationInfo.uid; 5446 reportSettingsProblem(Log.WARN, msg); 5447 } 5448 } 5449 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5450 || (scanFlags&SCAN_BOOTING) != 0)) { 5451 // If this is a system app, we can at least delete its 5452 // current data so the application will still work. 5453 int ret = removeDataDirsLI(pkgName); 5454 if (ret >= 0) { 5455 // TODO: Kill the processes first 5456 // Old data gone! 5457 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5458 ? "System package " : "Third party package "; 5459 String msg = prefix + pkg.packageName 5460 + " has changed from uid: " 5461 + currentUid + " to " 5462 + pkg.applicationInfo.uid + "; old data erased"; 5463 reportSettingsProblem(Log.WARN, msg); 5464 recovered = true; 5465 5466 // And now re-install the app. 5467 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5468 pkg.applicationInfo.seinfo); 5469 if (ret == -1) { 5470 // Ack should not happen! 5471 msg = prefix + pkg.packageName 5472 + " could not have data directory re-created after delete."; 5473 reportSettingsProblem(Log.WARN, msg); 5474 throw new PackageManagerException( 5475 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5476 } 5477 } 5478 if (!recovered) { 5479 mHasSystemUidErrors = true; 5480 } 5481 } else if (!recovered) { 5482 // If we allow this install to proceed, we will be broken. 5483 // Abort, abort! 5484 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5485 "scanPackageLI"); 5486 } 5487 if (!recovered) { 5488 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5489 + pkg.applicationInfo.uid + "/fs_" 5490 + currentUid; 5491 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5492 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5493 String msg = "Package " + pkg.packageName 5494 + " has mismatched uid: " 5495 + currentUid + " on disk, " 5496 + pkg.applicationInfo.uid + " in settings"; 5497 // writer 5498 synchronized (mPackages) { 5499 mSettings.mReadMessages.append(msg); 5500 mSettings.mReadMessages.append('\n'); 5501 uidError = true; 5502 if (!pkgSetting.uidError) { 5503 reportSettingsProblem(Log.ERROR, msg); 5504 } 5505 } 5506 } 5507 } 5508 pkg.applicationInfo.dataDir = dataPath.getPath(); 5509 if (mShouldRestoreconData) { 5510 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5511 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5512 pkg.applicationInfo.uid); 5513 } 5514 } else { 5515 if (DEBUG_PACKAGE_SCANNING) { 5516 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5517 Log.v(TAG, "Want this data dir: " + dataPath); 5518 } 5519 //invoke installer to do the actual installation 5520 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5521 pkg.applicationInfo.seinfo); 5522 if (ret < 0) { 5523 // Error from installer 5524 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5525 "Unable to create data dirs [errorCode=" + ret + "]"); 5526 } 5527 5528 if (dataPath.exists()) { 5529 pkg.applicationInfo.dataDir = dataPath.getPath(); 5530 } else { 5531 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5532 pkg.applicationInfo.dataDir = null; 5533 } 5534 } 5535 5536 pkgSetting.uidError = uidError; 5537 } 5538 5539 final String path = scanFile.getPath(); 5540 final String codePath = pkg.applicationInfo.getCodePath(); 5541 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5542 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5543 setBundledAppAbisAndRoots(pkg, pkgSetting); 5544 5545 // If we haven't found any native libraries for the app, check if it has 5546 // renderscript code. We'll need to force the app to 32 bit if it has 5547 // renderscript bitcode. 5548 if (pkg.applicationInfo.primaryCpuAbi == null 5549 && pkg.applicationInfo.secondaryCpuAbi == null 5550 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5551 NativeLibraryHelper.Handle handle = null; 5552 try { 5553 handle = NativeLibraryHelper.Handle.create(scanFile); 5554 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5555 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5556 } 5557 } catch (IOException ioe) { 5558 Slog.w(TAG, "Error scanning system app : " + ioe); 5559 } finally { 5560 IoUtils.closeQuietly(handle); 5561 } 5562 } 5563 5564 setNativeLibraryPaths(pkg); 5565 } else { 5566 // TODO: We can probably be smarter about this stuff. For installed apps, 5567 // we can calculate this information at install time once and for all. For 5568 // system apps, we can probably assume that this information doesn't change 5569 // after the first boot scan. As things stand, we do lots of unnecessary work. 5570 5571 // Give ourselves some initial paths; we'll come back for another 5572 // pass once we've determined ABI below. 5573 setNativeLibraryPaths(pkg); 5574 5575 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5576 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5577 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5578 5579 NativeLibraryHelper.Handle handle = null; 5580 try { 5581 handle = NativeLibraryHelper.Handle.create(scanFile); 5582 // TODO(multiArch): This can be null for apps that didn't go through the 5583 // usual installation process. We can calculate it again, like we 5584 // do during install time. 5585 // 5586 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5587 // unnecessary. 5588 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5589 5590 // Null out the abis so that they can be recalculated. 5591 pkg.applicationInfo.primaryCpuAbi = null; 5592 pkg.applicationInfo.secondaryCpuAbi = null; 5593 if (isMultiArch(pkg.applicationInfo)) { 5594 // Warn if we've set an abiOverride for multi-lib packages.. 5595 // By definition, we need to copy both 32 and 64 bit libraries for 5596 // such packages. 5597 if (pkg.cpuAbiOverride != null 5598 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5599 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5600 } 5601 5602 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5603 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5604 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5605 if (isAsec) { 5606 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5607 } else { 5608 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5609 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5610 useIsaSpecificSubdirs); 5611 } 5612 } 5613 5614 maybeThrowExceptionForMultiArchCopy( 5615 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5616 5617 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5618 if (isAsec) { 5619 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5620 } else { 5621 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5622 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5623 useIsaSpecificSubdirs); 5624 } 5625 } 5626 5627 maybeThrowExceptionForMultiArchCopy( 5628 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5629 5630 if (abi64 >= 0) { 5631 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5632 } 5633 5634 if (abi32 >= 0) { 5635 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5636 if (abi64 >= 0) { 5637 pkg.applicationInfo.secondaryCpuAbi = abi; 5638 } else { 5639 pkg.applicationInfo.primaryCpuAbi = abi; 5640 } 5641 } 5642 } else { 5643 String[] abiList = (cpuAbiOverride != null) ? 5644 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5645 5646 // Enable gross and lame hacks for apps that are built with old 5647 // SDK tools. We must scan their APKs for renderscript bitcode and 5648 // not launch them if it's present. Don't bother checking on devices 5649 // that don't have 64 bit support. 5650 boolean needsRenderScriptOverride = false; 5651 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5652 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5653 abiList = Build.SUPPORTED_32_BIT_ABIS; 5654 needsRenderScriptOverride = true; 5655 } 5656 5657 final int copyRet; 5658 if (isAsec) { 5659 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5660 } else { 5661 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5662 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5663 } 5664 5665 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5666 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5667 "Error unpackaging native libs for app, errorCode=" + copyRet); 5668 } 5669 5670 if (copyRet >= 0) { 5671 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5672 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5673 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5674 } else if (needsRenderScriptOverride) { 5675 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5676 } 5677 } 5678 } catch (IOException ioe) { 5679 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5680 } finally { 5681 IoUtils.closeQuietly(handle); 5682 } 5683 5684 // Now that we've calculated the ABIs and determined if it's an internal app, 5685 // we will go ahead and populate the nativeLibraryPath. 5686 setNativeLibraryPaths(pkg); 5687 5688 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5689 final int[] userIds = sUserManager.getUserIds(); 5690 synchronized (mInstallLock) { 5691 // Create a native library symlink only if we have native libraries 5692 // and if the native libraries are 32 bit libraries. We do not provide 5693 // this symlink for 64 bit libraries. 5694 if (pkg.applicationInfo.primaryCpuAbi != null && 5695 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5696 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5697 for (int userId : userIds) { 5698 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5699 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5700 "Failed linking native library dir (user=" + userId + ")"); 5701 } 5702 } 5703 } 5704 } 5705 } 5706 5707 // This is a special case for the "system" package, where the ABI is 5708 // dictated by the zygote configuration (and init.rc). We should keep track 5709 // of this ABI so that we can deal with "normal" applications that run under 5710 // the same UID correctly. 5711 if (mPlatformPackage == pkg) { 5712 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5713 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5714 } 5715 5716 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5717 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5718 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5719 // Copy the derived override back to the parsed package, so that we can 5720 // update the package settings accordingly. 5721 pkg.cpuAbiOverride = cpuAbiOverride; 5722 5723 if (DEBUG_ABI_SELECTION) { 5724 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5725 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5726 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5727 } 5728 5729 // Push the derived path down into PackageSettings so we know what to 5730 // clean up at uninstall time. 5731 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5732 5733 if (DEBUG_ABI_SELECTION) { 5734 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5735 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5736 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5737 } 5738 5739 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5740 // We don't do this here during boot because we can do it all 5741 // at once after scanning all existing packages. 5742 // 5743 // We also do this *before* we perform dexopt on this package, so that 5744 // we can avoid redundant dexopts, and also to make sure we've got the 5745 // code and package path correct. 5746 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5747 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5748 } 5749 5750 if ((scanFlags & SCAN_NO_DEX) == 0) { 5751 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5752 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5753 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5754 } 5755 } 5756 5757 if (mFactoryTest && pkg.requestedPermissions.contains( 5758 android.Manifest.permission.FACTORY_TEST)) { 5759 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5760 } 5761 5762 ArrayList<PackageParser.Package> clientLibPkgs = null; 5763 5764 // writer 5765 synchronized (mPackages) { 5766 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5767 // Only system apps can add new shared libraries. 5768 if (pkg.libraryNames != null) { 5769 for (int i=0; i<pkg.libraryNames.size(); i++) { 5770 String name = pkg.libraryNames.get(i); 5771 boolean allowed = false; 5772 if (isUpdatedSystemApp(pkg)) { 5773 // New library entries can only be added through the 5774 // system image. This is important to get rid of a lot 5775 // of nasty edge cases: for example if we allowed a non- 5776 // system update of the app to add a library, then uninstalling 5777 // the update would make the library go away, and assumptions 5778 // we made such as through app install filtering would now 5779 // have allowed apps on the device which aren't compatible 5780 // with it. Better to just have the restriction here, be 5781 // conservative, and create many fewer cases that can negatively 5782 // impact the user experience. 5783 final PackageSetting sysPs = mSettings 5784 .getDisabledSystemPkgLPr(pkg.packageName); 5785 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5786 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5787 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5788 allowed = true; 5789 allowed = true; 5790 break; 5791 } 5792 } 5793 } 5794 } else { 5795 allowed = true; 5796 } 5797 if (allowed) { 5798 if (!mSharedLibraries.containsKey(name)) { 5799 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5800 } else if (!name.equals(pkg.packageName)) { 5801 Slog.w(TAG, "Package " + pkg.packageName + " library " 5802 + name + " already exists; skipping"); 5803 } 5804 } else { 5805 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5806 + name + " that is not declared on system image; skipping"); 5807 } 5808 } 5809 if ((scanFlags&SCAN_BOOTING) == 0) { 5810 // If we are not booting, we need to update any applications 5811 // that are clients of our shared library. If we are booting, 5812 // this will all be done once the scan is complete. 5813 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5814 } 5815 } 5816 } 5817 } 5818 5819 // We also need to dexopt any apps that are dependent on this library. Note that 5820 // if these fail, we should abort the install since installing the library will 5821 // result in some apps being broken. 5822 if (clientLibPkgs != null) { 5823 if ((scanFlags & SCAN_NO_DEX) == 0) { 5824 for (int i = 0; i < clientLibPkgs.size(); i++) { 5825 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5826 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5827 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5828 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5829 "scanPackageLI failed to dexopt clientLibPkgs"); 5830 } 5831 } 5832 } 5833 } 5834 5835 // Request the ActivityManager to kill the process(only for existing packages) 5836 // so that we do not end up in a confused state while the user is still using the older 5837 // version of the application while the new one gets installed. 5838 if ((scanFlags & SCAN_REPLACING) != 0) { 5839 killApplication(pkg.applicationInfo.packageName, 5840 pkg.applicationInfo.uid, "update pkg"); 5841 } 5842 5843 // Also need to kill any apps that are dependent on the library. 5844 if (clientLibPkgs != null) { 5845 for (int i=0; i<clientLibPkgs.size(); i++) { 5846 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5847 killApplication(clientPkg.applicationInfo.packageName, 5848 clientPkg.applicationInfo.uid, "update lib"); 5849 } 5850 } 5851 5852 // writer 5853 synchronized (mPackages) { 5854 // We don't expect installation to fail beyond this point 5855 5856 // Add the new setting to mSettings 5857 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5858 // Add the new setting to mPackages 5859 mPackages.put(pkg.applicationInfo.packageName, pkg); 5860 // Make sure we don't accidentally delete its data. 5861 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5862 while (iter.hasNext()) { 5863 PackageCleanItem item = iter.next(); 5864 if (pkgName.equals(item.packageName)) { 5865 iter.remove(); 5866 } 5867 } 5868 5869 // Take care of first install / last update times. 5870 if (currentTime != 0) { 5871 if (pkgSetting.firstInstallTime == 0) { 5872 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5873 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5874 pkgSetting.lastUpdateTime = currentTime; 5875 } 5876 } else if (pkgSetting.firstInstallTime == 0) { 5877 // We need *something*. Take time time stamp of the file. 5878 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5879 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5880 if (scanFileTime != pkgSetting.timeStamp) { 5881 // A package on the system image has changed; consider this 5882 // to be an update. 5883 pkgSetting.lastUpdateTime = scanFileTime; 5884 } 5885 } 5886 5887 // Add the package's KeySets to the global KeySetManagerService 5888 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5889 try { 5890 // Old KeySetData no longer valid. 5891 ksms.removeAppKeySetDataLPw(pkg.packageName); 5892 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5893 if (pkg.mKeySetMapping != null) { 5894 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5895 pkg.mKeySetMapping.entrySet()) { 5896 if (entry.getValue() != null) { 5897 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5898 entry.getValue(), entry.getKey()); 5899 } 5900 } 5901 if (pkg.mUpgradeKeySets != null) { 5902 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5903 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5904 } 5905 } 5906 } 5907 } catch (NullPointerException e) { 5908 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5909 } catch (IllegalArgumentException e) { 5910 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5911 } 5912 5913 int N = pkg.providers.size(); 5914 StringBuilder r = null; 5915 int i; 5916 for (i=0; i<N; i++) { 5917 PackageParser.Provider p = pkg.providers.get(i); 5918 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5919 p.info.processName, pkg.applicationInfo.uid); 5920 mProviders.addProvider(p); 5921 p.syncable = p.info.isSyncable; 5922 if (p.info.authority != null) { 5923 String names[] = p.info.authority.split(";"); 5924 p.info.authority = null; 5925 for (int j = 0; j < names.length; j++) { 5926 if (j == 1 && p.syncable) { 5927 // We only want the first authority for a provider to possibly be 5928 // syncable, so if we already added this provider using a different 5929 // authority clear the syncable flag. We copy the provider before 5930 // changing it because the mProviders object contains a reference 5931 // to a provider that we don't want to change. 5932 // Only do this for the second authority since the resulting provider 5933 // object can be the same for all future authorities for this provider. 5934 p = new PackageParser.Provider(p); 5935 p.syncable = false; 5936 } 5937 if (!mProvidersByAuthority.containsKey(names[j])) { 5938 mProvidersByAuthority.put(names[j], p); 5939 if (p.info.authority == null) { 5940 p.info.authority = names[j]; 5941 } else { 5942 p.info.authority = p.info.authority + ";" + names[j]; 5943 } 5944 if (DEBUG_PACKAGE_SCANNING) { 5945 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5946 Log.d(TAG, "Registered content provider: " + names[j] 5947 + ", className = " + p.info.name + ", isSyncable = " 5948 + p.info.isSyncable); 5949 } 5950 } else { 5951 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5952 Slog.w(TAG, "Skipping provider name " + names[j] + 5953 " (in package " + pkg.applicationInfo.packageName + 5954 "): name already used by " 5955 + ((other != null && other.getComponentName() != null) 5956 ? other.getComponentName().getPackageName() : "?")); 5957 } 5958 } 5959 } 5960 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5961 if (r == null) { 5962 r = new StringBuilder(256); 5963 } else { 5964 r.append(' '); 5965 } 5966 r.append(p.info.name); 5967 } 5968 } 5969 if (r != null) { 5970 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5971 } 5972 5973 N = pkg.services.size(); 5974 r = null; 5975 for (i=0; i<N; i++) { 5976 PackageParser.Service s = pkg.services.get(i); 5977 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5978 s.info.processName, pkg.applicationInfo.uid); 5979 mServices.addService(s); 5980 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5981 if (r == null) { 5982 r = new StringBuilder(256); 5983 } else { 5984 r.append(' '); 5985 } 5986 r.append(s.info.name); 5987 } 5988 } 5989 if (r != null) { 5990 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5991 } 5992 5993 N = pkg.receivers.size(); 5994 r = null; 5995 for (i=0; i<N; i++) { 5996 PackageParser.Activity a = pkg.receivers.get(i); 5997 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5998 a.info.processName, pkg.applicationInfo.uid); 5999 mReceivers.addActivity(a, "receiver"); 6000 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6001 if (r == null) { 6002 r = new StringBuilder(256); 6003 } else { 6004 r.append(' '); 6005 } 6006 r.append(a.info.name); 6007 } 6008 } 6009 if (r != null) { 6010 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6011 } 6012 6013 N = pkg.activities.size(); 6014 r = null; 6015 for (i=0; i<N; i++) { 6016 PackageParser.Activity a = pkg.activities.get(i); 6017 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6018 a.info.processName, pkg.applicationInfo.uid); 6019 mActivities.addActivity(a, "activity"); 6020 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6021 if (r == null) { 6022 r = new StringBuilder(256); 6023 } else { 6024 r.append(' '); 6025 } 6026 r.append(a.info.name); 6027 } 6028 } 6029 if (r != null) { 6030 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6031 } 6032 6033 N = pkg.permissionGroups.size(); 6034 r = null; 6035 for (i=0; i<N; i++) { 6036 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6037 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6038 if (cur == null) { 6039 mPermissionGroups.put(pg.info.name, pg); 6040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6041 if (r == null) { 6042 r = new StringBuilder(256); 6043 } else { 6044 r.append(' '); 6045 } 6046 r.append(pg.info.name); 6047 } 6048 } else { 6049 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6050 + pg.info.packageName + " ignored: original from " 6051 + cur.info.packageName); 6052 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6053 if (r == null) { 6054 r = new StringBuilder(256); 6055 } else { 6056 r.append(' '); 6057 } 6058 r.append("DUP:"); 6059 r.append(pg.info.name); 6060 } 6061 } 6062 } 6063 if (r != null) { 6064 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6065 } 6066 6067 N = pkg.permissions.size(); 6068 r = null; 6069 for (i=0; i<N; i++) { 6070 PackageParser.Permission p = pkg.permissions.get(i); 6071 HashMap<String, BasePermission> permissionMap = 6072 p.tree ? mSettings.mPermissionTrees 6073 : mSettings.mPermissions; 6074 p.group = mPermissionGroups.get(p.info.group); 6075 if (p.info.group == null || p.group != null) { 6076 BasePermission bp = permissionMap.get(p.info.name); 6077 6078 // Allow system apps to redefine non-system permissions 6079 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6080 final boolean currentOwnerIsSystem = (bp.perm != null 6081 && isSystemApp(bp.perm.owner)); 6082 if (isSystemApp(p.owner)) { 6083 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6084 // It's a built-in permission and no owner, take ownership now 6085 bp.packageSetting = pkgSetting; 6086 bp.perm = p; 6087 bp.uid = pkg.applicationInfo.uid; 6088 bp.sourcePackage = p.info.packageName; 6089 } else if (!currentOwnerIsSystem) { 6090 String msg = "New decl " + p.owner + " of permission " 6091 + p.info.name + " is system; overriding " + bp.sourcePackage; 6092 reportSettingsProblem(Log.WARN, msg); 6093 bp = null; 6094 } 6095 } 6096 } 6097 6098 if (bp == null) { 6099 bp = new BasePermission(p.info.name, p.info.packageName, 6100 BasePermission.TYPE_NORMAL); 6101 permissionMap.put(p.info.name, bp); 6102 } 6103 6104 if (bp.perm == null) { 6105 if (bp.sourcePackage == null 6106 || bp.sourcePackage.equals(p.info.packageName)) { 6107 BasePermission tree = findPermissionTreeLP(p.info.name); 6108 if (tree == null 6109 || tree.sourcePackage.equals(p.info.packageName)) { 6110 bp.packageSetting = pkgSetting; 6111 bp.perm = p; 6112 bp.uid = pkg.applicationInfo.uid; 6113 bp.sourcePackage = p.info.packageName; 6114 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6115 if (r == null) { 6116 r = new StringBuilder(256); 6117 } else { 6118 r.append(' '); 6119 } 6120 r.append(p.info.name); 6121 } 6122 } else { 6123 Slog.w(TAG, "Permission " + p.info.name + " from package " 6124 + p.info.packageName + " ignored: base tree " 6125 + tree.name + " is from package " 6126 + tree.sourcePackage); 6127 } 6128 } else { 6129 Slog.w(TAG, "Permission " + p.info.name + " from package " 6130 + p.info.packageName + " ignored: original from " 6131 + bp.sourcePackage); 6132 } 6133 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6134 if (r == null) { 6135 r = new StringBuilder(256); 6136 } else { 6137 r.append(' '); 6138 } 6139 r.append("DUP:"); 6140 r.append(p.info.name); 6141 } 6142 if (bp.perm == p) { 6143 bp.protectionLevel = p.info.protectionLevel; 6144 } 6145 } else { 6146 Slog.w(TAG, "Permission " + p.info.name + " from package " 6147 + p.info.packageName + " ignored: no group " 6148 + p.group); 6149 } 6150 } 6151 if (r != null) { 6152 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6153 } 6154 6155 N = pkg.instrumentation.size(); 6156 r = null; 6157 for (i=0; i<N; i++) { 6158 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6159 a.info.packageName = pkg.applicationInfo.packageName; 6160 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6161 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6162 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6163 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6164 a.info.dataDir = pkg.applicationInfo.dataDir; 6165 6166 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6167 // need other information about the application, like the ABI and what not ? 6168 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6169 mInstrumentation.put(a.getComponentName(), a); 6170 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6171 if (r == null) { 6172 r = new StringBuilder(256); 6173 } else { 6174 r.append(' '); 6175 } 6176 r.append(a.info.name); 6177 } 6178 } 6179 if (r != null) { 6180 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6181 } 6182 6183 if (pkg.protectedBroadcasts != null) { 6184 N = pkg.protectedBroadcasts.size(); 6185 for (i=0; i<N; i++) { 6186 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6187 } 6188 } 6189 6190 pkgSetting.setTimeStamp(scanFileTime); 6191 6192 // Create idmap files for pairs of (packages, overlay packages). 6193 // Note: "android", ie framework-res.apk, is handled by native layers. 6194 if (pkg.mOverlayTarget != null) { 6195 // This is an overlay package. 6196 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6197 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6198 mOverlays.put(pkg.mOverlayTarget, 6199 new HashMap<String, PackageParser.Package>()); 6200 } 6201 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6202 map.put(pkg.packageName, pkg); 6203 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6204 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6205 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6206 "scanPackageLI failed to createIdmap"); 6207 } 6208 } 6209 } else if (mOverlays.containsKey(pkg.packageName) && 6210 !pkg.packageName.equals("android")) { 6211 // This is a regular package, with one or more known overlay packages. 6212 createIdmapsForPackageLI(pkg); 6213 } 6214 } 6215 6216 return pkg; 6217 } 6218 6219 /** 6220 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6221 * i.e, so that all packages can be run inside a single process if required. 6222 * 6223 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6224 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6225 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6226 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6227 * updating a package that belongs to a shared user. 6228 * 6229 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6230 * adds unnecessary complexity. 6231 */ 6232 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6233 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6234 String requiredInstructionSet = null; 6235 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6236 requiredInstructionSet = VMRuntime.getInstructionSet( 6237 scannedPackage.applicationInfo.primaryCpuAbi); 6238 } 6239 6240 PackageSetting requirer = null; 6241 for (PackageSetting ps : packagesForUser) { 6242 // If packagesForUser contains scannedPackage, we skip it. This will happen 6243 // when scannedPackage is an update of an existing package. Without this check, 6244 // we will never be able to change the ABI of any package belonging to a shared 6245 // user, even if it's compatible with other packages. 6246 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6247 if (ps.primaryCpuAbiString == null) { 6248 continue; 6249 } 6250 6251 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6252 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6253 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6254 // this but there's not much we can do. 6255 String errorMessage = "Instruction set mismatch, " 6256 + ((requirer == null) ? "[caller]" : requirer) 6257 + " requires " + requiredInstructionSet + " whereas " + ps 6258 + " requires " + instructionSet; 6259 Slog.w(TAG, errorMessage); 6260 } 6261 6262 if (requiredInstructionSet == null) { 6263 requiredInstructionSet = instructionSet; 6264 requirer = ps; 6265 } 6266 } 6267 } 6268 6269 if (requiredInstructionSet != null) { 6270 String adjustedAbi; 6271 if (requirer != null) { 6272 // requirer != null implies that either scannedPackage was null or that scannedPackage 6273 // did not require an ABI, in which case we have to adjust scannedPackage to match 6274 // the ABI of the set (which is the same as requirer's ABI) 6275 adjustedAbi = requirer.primaryCpuAbiString; 6276 if (scannedPackage != null) { 6277 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6278 } 6279 } else { 6280 // requirer == null implies that we're updating all ABIs in the set to 6281 // match scannedPackage. 6282 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6283 } 6284 6285 for (PackageSetting ps : packagesForUser) { 6286 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6287 if (ps.primaryCpuAbiString != null) { 6288 continue; 6289 } 6290 6291 ps.primaryCpuAbiString = adjustedAbi; 6292 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6293 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6294 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6295 6296 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6297 deferDexOpt, true) == DEX_OPT_FAILED) { 6298 ps.primaryCpuAbiString = null; 6299 ps.pkg.applicationInfo.primaryCpuAbi = null; 6300 return; 6301 } else { 6302 mInstaller.rmdex(ps.codePathString, 6303 getDexCodeInstructionSet(getPreferredInstructionSet())); 6304 } 6305 } 6306 } 6307 } 6308 } 6309 } 6310 6311 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6312 synchronized (mPackages) { 6313 mResolverReplaced = true; 6314 // Set up information for custom user intent resolution activity. 6315 mResolveActivity.applicationInfo = pkg.applicationInfo; 6316 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6317 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6318 mResolveActivity.processName = null; 6319 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6320 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6321 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6322 mResolveActivity.theme = 0; 6323 mResolveActivity.exported = true; 6324 mResolveActivity.enabled = true; 6325 mResolveInfo.activityInfo = mResolveActivity; 6326 mResolveInfo.priority = 0; 6327 mResolveInfo.preferredOrder = 0; 6328 mResolveInfo.match = 0; 6329 mResolveComponentName = mCustomResolverComponentName; 6330 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6331 mResolveComponentName); 6332 } 6333 } 6334 6335 private static String calculateBundledApkRoot(final String codePathString) { 6336 final File codePath = new File(codePathString); 6337 final File codeRoot; 6338 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6339 codeRoot = Environment.getRootDirectory(); 6340 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6341 codeRoot = Environment.getOemDirectory(); 6342 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6343 codeRoot = Environment.getVendorDirectory(); 6344 } else { 6345 // Unrecognized code path; take its top real segment as the apk root: 6346 // e.g. /something/app/blah.apk => /something 6347 try { 6348 File f = codePath.getCanonicalFile(); 6349 File parent = f.getParentFile(); // non-null because codePath is a file 6350 File tmp; 6351 while ((tmp = parent.getParentFile()) != null) { 6352 f = parent; 6353 parent = tmp; 6354 } 6355 codeRoot = f; 6356 Slog.w(TAG, "Unrecognized code path " 6357 + codePath + " - using " + codeRoot); 6358 } catch (IOException e) { 6359 // Can't canonicalize the code path -- shenanigans? 6360 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6361 return Environment.getRootDirectory().getPath(); 6362 } 6363 } 6364 return codeRoot.getPath(); 6365 } 6366 6367 /** 6368 * Derive and set the location of native libraries for the given package, 6369 * which varies depending on where and how the package was installed. 6370 */ 6371 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6372 final ApplicationInfo info = pkg.applicationInfo; 6373 final String codePath = pkg.codePath; 6374 final File codeFile = new File(codePath); 6375 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6376 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6377 6378 info.nativeLibraryRootDir = null; 6379 info.nativeLibraryRootRequiresIsa = false; 6380 info.nativeLibraryDir = null; 6381 info.secondaryNativeLibraryDir = null; 6382 6383 if (isApkFile(codeFile)) { 6384 // Monolithic install 6385 if (bundledApp) { 6386 // If "/system/lib64/apkname" exists, assume that is the per-package 6387 // native library directory to use; otherwise use "/system/lib/apkname". 6388 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6389 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6390 getPrimaryInstructionSet(info)); 6391 6392 // This is a bundled system app so choose the path based on the ABI. 6393 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6394 // is just the default path. 6395 final String apkName = deriveCodePathName(codePath); 6396 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6397 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6398 apkName).getAbsolutePath(); 6399 6400 if (info.secondaryCpuAbi != null) { 6401 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6402 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6403 secondaryLibDir, apkName).getAbsolutePath(); 6404 } 6405 } else if (asecApp) { 6406 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6407 .getAbsolutePath(); 6408 } else { 6409 final String apkName = deriveCodePathName(codePath); 6410 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6411 .getAbsolutePath(); 6412 } 6413 6414 info.nativeLibraryRootRequiresIsa = false; 6415 info.nativeLibraryDir = info.nativeLibraryRootDir; 6416 } else { 6417 // Cluster install 6418 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6419 info.nativeLibraryRootRequiresIsa = true; 6420 6421 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6422 getPrimaryInstructionSet(info)).getAbsolutePath(); 6423 6424 if (info.secondaryCpuAbi != null) { 6425 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6426 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6427 } 6428 } 6429 } 6430 6431 /** 6432 * Calculate the abis and roots for a bundled app. These can uniquely 6433 * be determined from the contents of the system partition, i.e whether 6434 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6435 * of this information, and instead assume that the system was built 6436 * sensibly. 6437 */ 6438 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6439 PackageSetting pkgSetting) { 6440 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6441 6442 // If "/system/lib64/apkname" exists, assume that is the per-package 6443 // native library directory to use; otherwise use "/system/lib/apkname". 6444 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6445 setBundledAppAbi(pkg, apkRoot, apkName); 6446 // pkgSetting might be null during rescan following uninstall of updates 6447 // to a bundled app, so accommodate that possibility. The settings in 6448 // that case will be established later from the parsed package. 6449 // 6450 // If the settings aren't null, sync them up with what we've just derived. 6451 // note that apkRoot isn't stored in the package settings. 6452 if (pkgSetting != null) { 6453 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6454 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6455 } 6456 } 6457 6458 /** 6459 * Deduces the ABI of a bundled app and sets the relevant fields on the 6460 * parsed pkg object. 6461 * 6462 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6463 * under which system libraries are installed. 6464 * @param apkName the name of the installed package. 6465 */ 6466 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6467 final File codeFile = new File(pkg.codePath); 6468 6469 final boolean has64BitLibs; 6470 final boolean has32BitLibs; 6471 if (isApkFile(codeFile)) { 6472 // Monolithic install 6473 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6474 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6475 } else { 6476 // Cluster install 6477 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6478 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6479 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6480 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6481 has64BitLibs = (new File(rootDir, isa)).exists(); 6482 } else { 6483 has64BitLibs = false; 6484 } 6485 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6486 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6487 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6488 has32BitLibs = (new File(rootDir, isa)).exists(); 6489 } else { 6490 has32BitLibs = false; 6491 } 6492 } 6493 6494 if (has64BitLibs && !has32BitLibs) { 6495 // The package has 64 bit libs, but not 32 bit libs. Its primary 6496 // ABI should be 64 bit. We can safely assume here that the bundled 6497 // native libraries correspond to the most preferred ABI in the list. 6498 6499 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6500 pkg.applicationInfo.secondaryCpuAbi = null; 6501 } else if (has32BitLibs && !has64BitLibs) { 6502 // The package has 32 bit libs but not 64 bit libs. Its primary 6503 // ABI should be 32 bit. 6504 6505 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6506 pkg.applicationInfo.secondaryCpuAbi = null; 6507 } else if (has32BitLibs && has64BitLibs) { 6508 // The application has both 64 and 32 bit bundled libraries. We check 6509 // here that the app declares multiArch support, and warn if it doesn't. 6510 // 6511 // We will be lenient here and record both ABIs. The primary will be the 6512 // ABI that's higher on the list, i.e, a device that's configured to prefer 6513 // 64 bit apps will see a 64 bit primary ABI, 6514 6515 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6516 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6517 } 6518 6519 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6520 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6521 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6522 } else { 6523 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6524 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6525 } 6526 } else { 6527 pkg.applicationInfo.primaryCpuAbi = null; 6528 pkg.applicationInfo.secondaryCpuAbi = null; 6529 } 6530 } 6531 6532 private void killApplication(String pkgName, int appId, String reason) { 6533 // Request the ActivityManager to kill the process(only for existing packages) 6534 // so that we do not end up in a confused state while the user is still using the older 6535 // version of the application while the new one gets installed. 6536 IActivityManager am = ActivityManagerNative.getDefault(); 6537 if (am != null) { 6538 try { 6539 am.killApplicationWithAppId(pkgName, appId, reason); 6540 } catch (RemoteException e) { 6541 } 6542 } 6543 } 6544 6545 void removePackageLI(PackageSetting ps, boolean chatty) { 6546 if (DEBUG_INSTALL) { 6547 if (chatty) 6548 Log.d(TAG, "Removing package " + ps.name); 6549 } 6550 6551 // writer 6552 synchronized (mPackages) { 6553 mPackages.remove(ps.name); 6554 final PackageParser.Package pkg = ps.pkg; 6555 if (pkg != null) { 6556 cleanPackageDataStructuresLILPw(pkg, chatty); 6557 } 6558 } 6559 } 6560 6561 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6562 if (DEBUG_INSTALL) { 6563 if (chatty) 6564 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6565 } 6566 6567 // writer 6568 synchronized (mPackages) { 6569 mPackages.remove(pkg.applicationInfo.packageName); 6570 cleanPackageDataStructuresLILPw(pkg, chatty); 6571 } 6572 } 6573 6574 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6575 int N = pkg.providers.size(); 6576 StringBuilder r = null; 6577 int i; 6578 for (i=0; i<N; i++) { 6579 PackageParser.Provider p = pkg.providers.get(i); 6580 mProviders.removeProvider(p); 6581 if (p.info.authority == null) { 6582 6583 /* There was another ContentProvider with this authority when 6584 * this app was installed so this authority is null, 6585 * Ignore it as we don't have to unregister the provider. 6586 */ 6587 continue; 6588 } 6589 String names[] = p.info.authority.split(";"); 6590 for (int j = 0; j < names.length; j++) { 6591 if (mProvidersByAuthority.get(names[j]) == p) { 6592 mProvidersByAuthority.remove(names[j]); 6593 if (DEBUG_REMOVE) { 6594 if (chatty) 6595 Log.d(TAG, "Unregistered content provider: " + names[j] 6596 + ", className = " + p.info.name + ", isSyncable = " 6597 + p.info.isSyncable); 6598 } 6599 } 6600 } 6601 if (DEBUG_REMOVE && chatty) { 6602 if (r == null) { 6603 r = new StringBuilder(256); 6604 } else { 6605 r.append(' '); 6606 } 6607 r.append(p.info.name); 6608 } 6609 } 6610 if (r != null) { 6611 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6612 } 6613 6614 N = pkg.services.size(); 6615 r = null; 6616 for (i=0; i<N; i++) { 6617 PackageParser.Service s = pkg.services.get(i); 6618 mServices.removeService(s); 6619 if (chatty) { 6620 if (r == null) { 6621 r = new StringBuilder(256); 6622 } else { 6623 r.append(' '); 6624 } 6625 r.append(s.info.name); 6626 } 6627 } 6628 if (r != null) { 6629 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6630 } 6631 6632 N = pkg.receivers.size(); 6633 r = null; 6634 for (i=0; i<N; i++) { 6635 PackageParser.Activity a = pkg.receivers.get(i); 6636 mReceivers.removeActivity(a, "receiver"); 6637 if (DEBUG_REMOVE && chatty) { 6638 if (r == null) { 6639 r = new StringBuilder(256); 6640 } else { 6641 r.append(' '); 6642 } 6643 r.append(a.info.name); 6644 } 6645 } 6646 if (r != null) { 6647 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6648 } 6649 6650 N = pkg.activities.size(); 6651 r = null; 6652 for (i=0; i<N; i++) { 6653 PackageParser.Activity a = pkg.activities.get(i); 6654 mActivities.removeActivity(a, "activity"); 6655 if (DEBUG_REMOVE && chatty) { 6656 if (r == null) { 6657 r = new StringBuilder(256); 6658 } else { 6659 r.append(' '); 6660 } 6661 r.append(a.info.name); 6662 } 6663 } 6664 if (r != null) { 6665 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6666 } 6667 6668 N = pkg.permissions.size(); 6669 r = null; 6670 for (i=0; i<N; i++) { 6671 PackageParser.Permission p = pkg.permissions.get(i); 6672 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6673 if (bp == null) { 6674 bp = mSettings.mPermissionTrees.get(p.info.name); 6675 } 6676 if (bp != null && bp.perm == p) { 6677 bp.perm = null; 6678 if (DEBUG_REMOVE && chatty) { 6679 if (r == null) { 6680 r = new StringBuilder(256); 6681 } else { 6682 r.append(' '); 6683 } 6684 r.append(p.info.name); 6685 } 6686 } 6687 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6688 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6689 if (appOpPerms != null) { 6690 appOpPerms.remove(pkg.packageName); 6691 } 6692 } 6693 } 6694 if (r != null) { 6695 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6696 } 6697 6698 N = pkg.requestedPermissions.size(); 6699 r = null; 6700 for (i=0; i<N; i++) { 6701 String perm = pkg.requestedPermissions.get(i); 6702 BasePermission bp = mSettings.mPermissions.get(perm); 6703 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6704 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6705 if (appOpPerms != null) { 6706 appOpPerms.remove(pkg.packageName); 6707 if (appOpPerms.isEmpty()) { 6708 mAppOpPermissionPackages.remove(perm); 6709 } 6710 } 6711 } 6712 } 6713 if (r != null) { 6714 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6715 } 6716 6717 N = pkg.instrumentation.size(); 6718 r = null; 6719 for (i=0; i<N; i++) { 6720 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6721 mInstrumentation.remove(a.getComponentName()); 6722 if (DEBUG_REMOVE && chatty) { 6723 if (r == null) { 6724 r = new StringBuilder(256); 6725 } else { 6726 r.append(' '); 6727 } 6728 r.append(a.info.name); 6729 } 6730 } 6731 if (r != null) { 6732 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6733 } 6734 6735 r = null; 6736 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6737 // Only system apps can hold shared libraries. 6738 if (pkg.libraryNames != null) { 6739 for (i=0; i<pkg.libraryNames.size(); i++) { 6740 String name = pkg.libraryNames.get(i); 6741 SharedLibraryEntry cur = mSharedLibraries.get(name); 6742 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6743 mSharedLibraries.remove(name); 6744 if (DEBUG_REMOVE && chatty) { 6745 if (r == null) { 6746 r = new StringBuilder(256); 6747 } else { 6748 r.append(' '); 6749 } 6750 r.append(name); 6751 } 6752 } 6753 } 6754 } 6755 } 6756 if (r != null) { 6757 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6758 } 6759 } 6760 6761 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6762 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6763 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6764 return true; 6765 } 6766 } 6767 return false; 6768 } 6769 6770 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6771 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6772 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6773 6774 private void updatePermissionsLPw(String changingPkg, 6775 PackageParser.Package pkgInfo, int flags) { 6776 // Make sure there are no dangling permission trees. 6777 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6778 while (it.hasNext()) { 6779 final BasePermission bp = it.next(); 6780 if (bp.packageSetting == null) { 6781 // We may not yet have parsed the package, so just see if 6782 // we still know about its settings. 6783 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6784 } 6785 if (bp.packageSetting == null) { 6786 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6787 + " from package " + bp.sourcePackage); 6788 it.remove(); 6789 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6790 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6791 Slog.i(TAG, "Removing old permission tree: " + bp.name 6792 + " from package " + bp.sourcePackage); 6793 flags |= UPDATE_PERMISSIONS_ALL; 6794 it.remove(); 6795 } 6796 } 6797 } 6798 6799 // Make sure all dynamic permissions have been assigned to a package, 6800 // and make sure there are no dangling permissions. 6801 it = mSettings.mPermissions.values().iterator(); 6802 while (it.hasNext()) { 6803 final BasePermission bp = it.next(); 6804 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6805 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6806 + bp.name + " pkg=" + bp.sourcePackage 6807 + " info=" + bp.pendingInfo); 6808 if (bp.packageSetting == null && bp.pendingInfo != null) { 6809 final BasePermission tree = findPermissionTreeLP(bp.name); 6810 if (tree != null && tree.perm != null) { 6811 bp.packageSetting = tree.packageSetting; 6812 bp.perm = new PackageParser.Permission(tree.perm.owner, 6813 new PermissionInfo(bp.pendingInfo)); 6814 bp.perm.info.packageName = tree.perm.info.packageName; 6815 bp.perm.info.name = bp.name; 6816 bp.uid = tree.uid; 6817 } 6818 } 6819 } 6820 if (bp.packageSetting == null) { 6821 // We may not yet have parsed the package, so just see if 6822 // we still know about its settings. 6823 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6824 } 6825 if (bp.packageSetting == null) { 6826 Slog.w(TAG, "Removing dangling permission: " + bp.name 6827 + " from package " + bp.sourcePackage); 6828 it.remove(); 6829 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6830 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6831 Slog.i(TAG, "Removing old permission: " + bp.name 6832 + " from package " + bp.sourcePackage); 6833 flags |= UPDATE_PERMISSIONS_ALL; 6834 it.remove(); 6835 } 6836 } 6837 } 6838 6839 // Now update the permissions for all packages, in particular 6840 // replace the granted permissions of the system packages. 6841 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6842 for (PackageParser.Package pkg : mPackages.values()) { 6843 if (pkg != pkgInfo) { 6844 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6845 changingPkg); 6846 } 6847 } 6848 } 6849 6850 if (pkgInfo != null) { 6851 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6852 } 6853 } 6854 6855 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6856 String packageOfInterest) { 6857 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6858 if (ps == null) { 6859 return; 6860 } 6861 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6862 HashSet<String> origPermissions = gp.grantedPermissions; 6863 boolean changedPermission = false; 6864 6865 if (replace) { 6866 ps.permissionsFixed = false; 6867 if (gp == ps) { 6868 origPermissions = new HashSet<String>(gp.grantedPermissions); 6869 gp.grantedPermissions.clear(); 6870 gp.gids = mGlobalGids; 6871 } 6872 } 6873 6874 if (gp.gids == null) { 6875 gp.gids = mGlobalGids; 6876 } 6877 6878 final int N = pkg.requestedPermissions.size(); 6879 for (int i=0; i<N; i++) { 6880 final String name = pkg.requestedPermissions.get(i); 6881 final boolean required = pkg.requestedPermissionsRequired.get(i); 6882 final BasePermission bp = mSettings.mPermissions.get(name); 6883 if (DEBUG_INSTALL) { 6884 if (gp != ps) { 6885 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6886 } 6887 } 6888 6889 if (bp == null || bp.packageSetting == null) { 6890 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6891 Slog.w(TAG, "Unknown permission " + name 6892 + " in package " + pkg.packageName); 6893 } 6894 continue; 6895 } 6896 6897 final String perm = bp.name; 6898 boolean allowed; 6899 boolean allowedSig = false; 6900 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6901 // Keep track of app op permissions. 6902 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6903 if (pkgs == null) { 6904 pkgs = new ArraySet<>(); 6905 mAppOpPermissionPackages.put(bp.name, pkgs); 6906 } 6907 pkgs.add(pkg.packageName); 6908 } 6909 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6910 if (level == PermissionInfo.PROTECTION_NORMAL 6911 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6912 // We grant a normal or dangerous permission if any of the following 6913 // are true: 6914 // 1) The permission is required 6915 // 2) The permission is optional, but was granted in the past 6916 // 3) The permission is optional, but was requested by an 6917 // app in /system (not /data) 6918 // 6919 // Otherwise, reject the permission. 6920 allowed = (required || origPermissions.contains(perm) 6921 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6922 } else if (bp.packageSetting == null) { 6923 // This permission is invalid; skip it. 6924 allowed = false; 6925 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6926 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6927 if (allowed) { 6928 allowedSig = true; 6929 } 6930 } else { 6931 allowed = false; 6932 } 6933 if (DEBUG_INSTALL) { 6934 if (gp != ps) { 6935 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6936 } 6937 } 6938 if (allowed) { 6939 if (!isSystemApp(ps) && ps.permissionsFixed) { 6940 // If this is an existing, non-system package, then 6941 // we can't add any new permissions to it. 6942 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6943 // Except... if this is a permission that was added 6944 // to the platform (note: need to only do this when 6945 // updating the platform). 6946 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6947 } 6948 } 6949 if (allowed) { 6950 if (!gp.grantedPermissions.contains(perm)) { 6951 changedPermission = true; 6952 gp.grantedPermissions.add(perm); 6953 gp.gids = appendInts(gp.gids, bp.gids); 6954 } else if (!ps.haveGids) { 6955 gp.gids = appendInts(gp.gids, bp.gids); 6956 } 6957 } else { 6958 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6959 Slog.w(TAG, "Not granting permission " + perm 6960 + " to package " + pkg.packageName 6961 + " because it was previously installed without"); 6962 } 6963 } 6964 } else { 6965 if (gp.grantedPermissions.remove(perm)) { 6966 changedPermission = true; 6967 gp.gids = removeInts(gp.gids, bp.gids); 6968 Slog.i(TAG, "Un-granting permission " + perm 6969 + " from package " + pkg.packageName 6970 + " (protectionLevel=" + bp.protectionLevel 6971 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6972 + ")"); 6973 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6974 // Don't print warning for app op permissions, since it is fine for them 6975 // not to be granted, there is a UI for the user to decide. 6976 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6977 Slog.w(TAG, "Not granting permission " + perm 6978 + " to package " + pkg.packageName 6979 + " (protectionLevel=" + bp.protectionLevel 6980 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6981 + ")"); 6982 } 6983 } 6984 } 6985 } 6986 6987 if ((changedPermission || replace) && !ps.permissionsFixed && 6988 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6989 // This is the first that we have heard about this package, so the 6990 // permissions we have now selected are fixed until explicitly 6991 // changed. 6992 ps.permissionsFixed = true; 6993 } 6994 ps.haveGids = true; 6995 } 6996 6997 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6998 boolean allowed = false; 6999 final int NP = PackageParser.NEW_PERMISSIONS.length; 7000 for (int ip=0; ip<NP; ip++) { 7001 final PackageParser.NewPermissionInfo npi 7002 = PackageParser.NEW_PERMISSIONS[ip]; 7003 if (npi.name.equals(perm) 7004 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7005 allowed = true; 7006 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7007 + pkg.packageName); 7008 break; 7009 } 7010 } 7011 return allowed; 7012 } 7013 7014 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7015 BasePermission bp, HashSet<String> origPermissions) { 7016 boolean allowed; 7017 allowed = (compareSignatures( 7018 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7019 == PackageManager.SIGNATURE_MATCH) 7020 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7021 == PackageManager.SIGNATURE_MATCH); 7022 if (!allowed && (bp.protectionLevel 7023 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7024 if (isSystemApp(pkg)) { 7025 // For updated system applications, a system permission 7026 // is granted only if it had been defined by the original application. 7027 if (isUpdatedSystemApp(pkg)) { 7028 final PackageSetting sysPs = mSettings 7029 .getDisabledSystemPkgLPr(pkg.packageName); 7030 final GrantedPermissions origGp = sysPs.sharedUser != null 7031 ? sysPs.sharedUser : sysPs; 7032 7033 if (origGp.grantedPermissions.contains(perm)) { 7034 // If the original was granted this permission, we take 7035 // that grant decision as read and propagate it to the 7036 // update. 7037 allowed = true; 7038 } else { 7039 // The system apk may have been updated with an older 7040 // version of the one on the data partition, but which 7041 // granted a new system permission that it didn't have 7042 // before. In this case we do want to allow the app to 7043 // now get the new permission if the ancestral apk is 7044 // privileged to get it. 7045 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7046 for (int j=0; 7047 j<sysPs.pkg.requestedPermissions.size(); j++) { 7048 if (perm.equals( 7049 sysPs.pkg.requestedPermissions.get(j))) { 7050 allowed = true; 7051 break; 7052 } 7053 } 7054 } 7055 } 7056 } else { 7057 allowed = isPrivilegedApp(pkg); 7058 } 7059 } 7060 } 7061 if (!allowed && (bp.protectionLevel 7062 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7063 // For development permissions, a development permission 7064 // is granted only if it was already granted. 7065 allowed = origPermissions.contains(perm); 7066 } 7067 return allowed; 7068 } 7069 7070 final class ActivityIntentResolver 7071 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7072 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7073 boolean defaultOnly, int userId) { 7074 if (!sUserManager.exists(userId)) return null; 7075 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7076 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7077 } 7078 7079 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7080 int userId) { 7081 if (!sUserManager.exists(userId)) return null; 7082 mFlags = flags; 7083 return super.queryIntent(intent, resolvedType, 7084 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7085 } 7086 7087 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7088 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7089 if (!sUserManager.exists(userId)) return null; 7090 if (packageActivities == null) { 7091 return null; 7092 } 7093 mFlags = flags; 7094 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7095 final int N = packageActivities.size(); 7096 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7097 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7098 7099 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7100 for (int i = 0; i < N; ++i) { 7101 intentFilters = packageActivities.get(i).intents; 7102 if (intentFilters != null && intentFilters.size() > 0) { 7103 PackageParser.ActivityIntentInfo[] array = 7104 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7105 intentFilters.toArray(array); 7106 listCut.add(array); 7107 } 7108 } 7109 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7110 } 7111 7112 public final void addActivity(PackageParser.Activity a, String type) { 7113 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7114 mActivities.put(a.getComponentName(), a); 7115 if (DEBUG_SHOW_INFO) 7116 Log.v( 7117 TAG, " " + type + " " + 7118 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7119 if (DEBUG_SHOW_INFO) 7120 Log.v(TAG, " Class=" + a.info.name); 7121 final int NI = a.intents.size(); 7122 for (int j=0; j<NI; j++) { 7123 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7124 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7125 intent.setPriority(0); 7126 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7127 + a.className + " with priority > 0, forcing to 0"); 7128 } 7129 if (DEBUG_SHOW_INFO) { 7130 Log.v(TAG, " IntentFilter:"); 7131 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7132 } 7133 if (!intent.debugCheck()) { 7134 Log.w(TAG, "==> For Activity " + a.info.name); 7135 } 7136 addFilter(intent); 7137 } 7138 } 7139 7140 public final void removeActivity(PackageParser.Activity a, String type) { 7141 mActivities.remove(a.getComponentName()); 7142 if (DEBUG_SHOW_INFO) { 7143 Log.v(TAG, " " + type + " " 7144 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7145 : a.info.name) + ":"); 7146 Log.v(TAG, " Class=" + a.info.name); 7147 } 7148 final int NI = a.intents.size(); 7149 for (int j=0; j<NI; j++) { 7150 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7151 if (DEBUG_SHOW_INFO) { 7152 Log.v(TAG, " IntentFilter:"); 7153 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7154 } 7155 removeFilter(intent); 7156 } 7157 } 7158 7159 @Override 7160 protected boolean allowFilterResult( 7161 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7162 ActivityInfo filterAi = filter.activity.info; 7163 for (int i=dest.size()-1; i>=0; i--) { 7164 ActivityInfo destAi = dest.get(i).activityInfo; 7165 if (destAi.name == filterAi.name 7166 && destAi.packageName == filterAi.packageName) { 7167 return false; 7168 } 7169 } 7170 return true; 7171 } 7172 7173 @Override 7174 protected ActivityIntentInfo[] newArray(int size) { 7175 return new ActivityIntentInfo[size]; 7176 } 7177 7178 @Override 7179 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7180 if (!sUserManager.exists(userId)) return true; 7181 PackageParser.Package p = filter.activity.owner; 7182 if (p != null) { 7183 PackageSetting ps = (PackageSetting)p.mExtras; 7184 if (ps != null) { 7185 // System apps are never considered stopped for purposes of 7186 // filtering, because there may be no way for the user to 7187 // actually re-launch them. 7188 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7189 && ps.getStopped(userId); 7190 } 7191 } 7192 return false; 7193 } 7194 7195 @Override 7196 protected boolean isPackageForFilter(String packageName, 7197 PackageParser.ActivityIntentInfo info) { 7198 return packageName.equals(info.activity.owner.packageName); 7199 } 7200 7201 @Override 7202 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7203 int match, int userId) { 7204 if (!sUserManager.exists(userId)) return null; 7205 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7206 return null; 7207 } 7208 final PackageParser.Activity activity = info.activity; 7209 if (mSafeMode && (activity.info.applicationInfo.flags 7210 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7211 return null; 7212 } 7213 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7214 if (ps == null) { 7215 return null; 7216 } 7217 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7218 ps.readUserState(userId), userId); 7219 if (ai == null) { 7220 return null; 7221 } 7222 final ResolveInfo res = new ResolveInfo(); 7223 res.activityInfo = ai; 7224 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7225 res.filter = info; 7226 } 7227 res.priority = info.getPriority(); 7228 res.preferredOrder = activity.owner.mPreferredOrder; 7229 //System.out.println("Result: " + res.activityInfo.className + 7230 // " = " + res.priority); 7231 res.match = match; 7232 res.isDefault = info.hasDefault; 7233 res.labelRes = info.labelRes; 7234 res.nonLocalizedLabel = info.nonLocalizedLabel; 7235 if (userNeedsBadging(userId)) { 7236 res.noResourceId = true; 7237 } else { 7238 res.icon = info.icon; 7239 } 7240 res.system = isSystemApp(res.activityInfo.applicationInfo); 7241 return res; 7242 } 7243 7244 @Override 7245 protected void sortResults(List<ResolveInfo> results) { 7246 Collections.sort(results, mResolvePrioritySorter); 7247 } 7248 7249 @Override 7250 protected void dumpFilter(PrintWriter out, String prefix, 7251 PackageParser.ActivityIntentInfo filter) { 7252 out.print(prefix); out.print( 7253 Integer.toHexString(System.identityHashCode(filter.activity))); 7254 out.print(' '); 7255 filter.activity.printComponentShortName(out); 7256 out.print(" filter "); 7257 out.println(Integer.toHexString(System.identityHashCode(filter))); 7258 } 7259 7260// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7261// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7262// final List<ResolveInfo> retList = Lists.newArrayList(); 7263// while (i.hasNext()) { 7264// final ResolveInfo resolveInfo = i.next(); 7265// if (isEnabledLP(resolveInfo.activityInfo)) { 7266// retList.add(resolveInfo); 7267// } 7268// } 7269// return retList; 7270// } 7271 7272 // Keys are String (activity class name), values are Activity. 7273 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7274 = new HashMap<ComponentName, PackageParser.Activity>(); 7275 private int mFlags; 7276 } 7277 7278 private final class ServiceIntentResolver 7279 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7280 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7281 boolean defaultOnly, int userId) { 7282 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7283 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7284 } 7285 7286 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7287 int userId) { 7288 if (!sUserManager.exists(userId)) return null; 7289 mFlags = flags; 7290 return super.queryIntent(intent, resolvedType, 7291 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7292 } 7293 7294 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7295 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7296 if (!sUserManager.exists(userId)) return null; 7297 if (packageServices == null) { 7298 return null; 7299 } 7300 mFlags = flags; 7301 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7302 final int N = packageServices.size(); 7303 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7304 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7305 7306 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7307 for (int i = 0; i < N; ++i) { 7308 intentFilters = packageServices.get(i).intents; 7309 if (intentFilters != null && intentFilters.size() > 0) { 7310 PackageParser.ServiceIntentInfo[] array = 7311 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7312 intentFilters.toArray(array); 7313 listCut.add(array); 7314 } 7315 } 7316 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7317 } 7318 7319 public final void addService(PackageParser.Service s) { 7320 mServices.put(s.getComponentName(), s); 7321 if (DEBUG_SHOW_INFO) { 7322 Log.v(TAG, " " 7323 + (s.info.nonLocalizedLabel != null 7324 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7325 Log.v(TAG, " Class=" + s.info.name); 7326 } 7327 final int NI = s.intents.size(); 7328 int j; 7329 for (j=0; j<NI; j++) { 7330 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7331 if (DEBUG_SHOW_INFO) { 7332 Log.v(TAG, " IntentFilter:"); 7333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7334 } 7335 if (!intent.debugCheck()) { 7336 Log.w(TAG, "==> For Service " + s.info.name); 7337 } 7338 addFilter(intent); 7339 } 7340 } 7341 7342 public final void removeService(PackageParser.Service s) { 7343 mServices.remove(s.getComponentName()); 7344 if (DEBUG_SHOW_INFO) { 7345 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7346 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7347 Log.v(TAG, " Class=" + s.info.name); 7348 } 7349 final int NI = s.intents.size(); 7350 int j; 7351 for (j=0; j<NI; j++) { 7352 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7353 if (DEBUG_SHOW_INFO) { 7354 Log.v(TAG, " IntentFilter:"); 7355 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7356 } 7357 removeFilter(intent); 7358 } 7359 } 7360 7361 @Override 7362 protected boolean allowFilterResult( 7363 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7364 ServiceInfo filterSi = filter.service.info; 7365 for (int i=dest.size()-1; i>=0; i--) { 7366 ServiceInfo destAi = dest.get(i).serviceInfo; 7367 if (destAi.name == filterSi.name 7368 && destAi.packageName == filterSi.packageName) { 7369 return false; 7370 } 7371 } 7372 return true; 7373 } 7374 7375 @Override 7376 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7377 return new PackageParser.ServiceIntentInfo[size]; 7378 } 7379 7380 @Override 7381 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7382 if (!sUserManager.exists(userId)) return true; 7383 PackageParser.Package p = filter.service.owner; 7384 if (p != null) { 7385 PackageSetting ps = (PackageSetting)p.mExtras; 7386 if (ps != null) { 7387 // System apps are never considered stopped for purposes of 7388 // filtering, because there may be no way for the user to 7389 // actually re-launch them. 7390 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7391 && ps.getStopped(userId); 7392 } 7393 } 7394 return false; 7395 } 7396 7397 @Override 7398 protected boolean isPackageForFilter(String packageName, 7399 PackageParser.ServiceIntentInfo info) { 7400 return packageName.equals(info.service.owner.packageName); 7401 } 7402 7403 @Override 7404 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7405 int match, int userId) { 7406 if (!sUserManager.exists(userId)) return null; 7407 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7408 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7409 return null; 7410 } 7411 final PackageParser.Service service = info.service; 7412 if (mSafeMode && (service.info.applicationInfo.flags 7413 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7414 return null; 7415 } 7416 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7417 if (ps == null) { 7418 return null; 7419 } 7420 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7421 ps.readUserState(userId), userId); 7422 if (si == null) { 7423 return null; 7424 } 7425 final ResolveInfo res = new ResolveInfo(); 7426 res.serviceInfo = si; 7427 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7428 res.filter = filter; 7429 } 7430 res.priority = info.getPriority(); 7431 res.preferredOrder = service.owner.mPreferredOrder; 7432 //System.out.println("Result: " + res.activityInfo.className + 7433 // " = " + res.priority); 7434 res.match = match; 7435 res.isDefault = info.hasDefault; 7436 res.labelRes = info.labelRes; 7437 res.nonLocalizedLabel = info.nonLocalizedLabel; 7438 res.icon = info.icon; 7439 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7440 return res; 7441 } 7442 7443 @Override 7444 protected void sortResults(List<ResolveInfo> results) { 7445 Collections.sort(results, mResolvePrioritySorter); 7446 } 7447 7448 @Override 7449 protected void dumpFilter(PrintWriter out, String prefix, 7450 PackageParser.ServiceIntentInfo filter) { 7451 out.print(prefix); out.print( 7452 Integer.toHexString(System.identityHashCode(filter.service))); 7453 out.print(' '); 7454 filter.service.printComponentShortName(out); 7455 out.print(" filter "); 7456 out.println(Integer.toHexString(System.identityHashCode(filter))); 7457 } 7458 7459// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7460// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7461// final List<ResolveInfo> retList = Lists.newArrayList(); 7462// while (i.hasNext()) { 7463// final ResolveInfo resolveInfo = (ResolveInfo) i; 7464// if (isEnabledLP(resolveInfo.serviceInfo)) { 7465// retList.add(resolveInfo); 7466// } 7467// } 7468// return retList; 7469// } 7470 7471 // Keys are String (activity class name), values are Activity. 7472 private final HashMap<ComponentName, PackageParser.Service> mServices 7473 = new HashMap<ComponentName, PackageParser.Service>(); 7474 private int mFlags; 7475 }; 7476 7477 private final class ProviderIntentResolver 7478 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7479 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7480 boolean defaultOnly, int userId) { 7481 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7482 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7483 } 7484 7485 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7486 int userId) { 7487 if (!sUserManager.exists(userId)) 7488 return null; 7489 mFlags = flags; 7490 return super.queryIntent(intent, resolvedType, 7491 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7492 } 7493 7494 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7495 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7496 if (!sUserManager.exists(userId)) 7497 return null; 7498 if (packageProviders == null) { 7499 return null; 7500 } 7501 mFlags = flags; 7502 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7503 final int N = packageProviders.size(); 7504 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7505 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7506 7507 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7508 for (int i = 0; i < N; ++i) { 7509 intentFilters = packageProviders.get(i).intents; 7510 if (intentFilters != null && intentFilters.size() > 0) { 7511 PackageParser.ProviderIntentInfo[] array = 7512 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7513 intentFilters.toArray(array); 7514 listCut.add(array); 7515 } 7516 } 7517 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7518 } 7519 7520 public final void addProvider(PackageParser.Provider p) { 7521 if (mProviders.containsKey(p.getComponentName())) { 7522 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7523 return; 7524 } 7525 7526 mProviders.put(p.getComponentName(), p); 7527 if (DEBUG_SHOW_INFO) { 7528 Log.v(TAG, " " 7529 + (p.info.nonLocalizedLabel != null 7530 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7531 Log.v(TAG, " Class=" + p.info.name); 7532 } 7533 final int NI = p.intents.size(); 7534 int j; 7535 for (j = 0; j < NI; j++) { 7536 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7537 if (DEBUG_SHOW_INFO) { 7538 Log.v(TAG, " IntentFilter:"); 7539 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7540 } 7541 if (!intent.debugCheck()) { 7542 Log.w(TAG, "==> For Provider " + p.info.name); 7543 } 7544 addFilter(intent); 7545 } 7546 } 7547 7548 public final void removeProvider(PackageParser.Provider p) { 7549 mProviders.remove(p.getComponentName()); 7550 if (DEBUG_SHOW_INFO) { 7551 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7552 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7553 Log.v(TAG, " Class=" + p.info.name); 7554 } 7555 final int NI = p.intents.size(); 7556 int j; 7557 for (j = 0; j < NI; j++) { 7558 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7559 if (DEBUG_SHOW_INFO) { 7560 Log.v(TAG, " IntentFilter:"); 7561 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7562 } 7563 removeFilter(intent); 7564 } 7565 } 7566 7567 @Override 7568 protected boolean allowFilterResult( 7569 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7570 ProviderInfo filterPi = filter.provider.info; 7571 for (int i = dest.size() - 1; i >= 0; i--) { 7572 ProviderInfo destPi = dest.get(i).providerInfo; 7573 if (destPi.name == filterPi.name 7574 && destPi.packageName == filterPi.packageName) { 7575 return false; 7576 } 7577 } 7578 return true; 7579 } 7580 7581 @Override 7582 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7583 return new PackageParser.ProviderIntentInfo[size]; 7584 } 7585 7586 @Override 7587 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7588 if (!sUserManager.exists(userId)) 7589 return true; 7590 PackageParser.Package p = filter.provider.owner; 7591 if (p != null) { 7592 PackageSetting ps = (PackageSetting) p.mExtras; 7593 if (ps != null) { 7594 // System apps are never considered stopped for purposes of 7595 // filtering, because there may be no way for the user to 7596 // actually re-launch them. 7597 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7598 && ps.getStopped(userId); 7599 } 7600 } 7601 return false; 7602 } 7603 7604 @Override 7605 protected boolean isPackageForFilter(String packageName, 7606 PackageParser.ProviderIntentInfo info) { 7607 return packageName.equals(info.provider.owner.packageName); 7608 } 7609 7610 @Override 7611 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7612 int match, int userId) { 7613 if (!sUserManager.exists(userId)) 7614 return null; 7615 final PackageParser.ProviderIntentInfo info = filter; 7616 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7617 return null; 7618 } 7619 final PackageParser.Provider provider = info.provider; 7620 if (mSafeMode && (provider.info.applicationInfo.flags 7621 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7622 return null; 7623 } 7624 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7625 if (ps == null) { 7626 return null; 7627 } 7628 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7629 ps.readUserState(userId), userId); 7630 if (pi == null) { 7631 return null; 7632 } 7633 final ResolveInfo res = new ResolveInfo(); 7634 res.providerInfo = pi; 7635 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7636 res.filter = filter; 7637 } 7638 res.priority = info.getPriority(); 7639 res.preferredOrder = provider.owner.mPreferredOrder; 7640 res.match = match; 7641 res.isDefault = info.hasDefault; 7642 res.labelRes = info.labelRes; 7643 res.nonLocalizedLabel = info.nonLocalizedLabel; 7644 res.icon = info.icon; 7645 res.system = isSystemApp(res.providerInfo.applicationInfo); 7646 return res; 7647 } 7648 7649 @Override 7650 protected void sortResults(List<ResolveInfo> results) { 7651 Collections.sort(results, mResolvePrioritySorter); 7652 } 7653 7654 @Override 7655 protected void dumpFilter(PrintWriter out, String prefix, 7656 PackageParser.ProviderIntentInfo filter) { 7657 out.print(prefix); 7658 out.print( 7659 Integer.toHexString(System.identityHashCode(filter.provider))); 7660 out.print(' '); 7661 filter.provider.printComponentShortName(out); 7662 out.print(" filter "); 7663 out.println(Integer.toHexString(System.identityHashCode(filter))); 7664 } 7665 7666 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7667 = new HashMap<ComponentName, PackageParser.Provider>(); 7668 private int mFlags; 7669 }; 7670 7671 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7672 new Comparator<ResolveInfo>() { 7673 public int compare(ResolveInfo r1, ResolveInfo r2) { 7674 int v1 = r1.priority; 7675 int v2 = r2.priority; 7676 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7677 if (v1 != v2) { 7678 return (v1 > v2) ? -1 : 1; 7679 } 7680 v1 = r1.preferredOrder; 7681 v2 = r2.preferredOrder; 7682 if (v1 != v2) { 7683 return (v1 > v2) ? -1 : 1; 7684 } 7685 if (r1.isDefault != r2.isDefault) { 7686 return r1.isDefault ? -1 : 1; 7687 } 7688 v1 = r1.match; 7689 v2 = r2.match; 7690 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7691 if (v1 != v2) { 7692 return (v1 > v2) ? -1 : 1; 7693 } 7694 if (r1.system != r2.system) { 7695 return r1.system ? -1 : 1; 7696 } 7697 return 0; 7698 } 7699 }; 7700 7701 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7702 new Comparator<ProviderInfo>() { 7703 public int compare(ProviderInfo p1, ProviderInfo p2) { 7704 final int v1 = p1.initOrder; 7705 final int v2 = p2.initOrder; 7706 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7707 } 7708 }; 7709 7710 static final void sendPackageBroadcast(String action, String pkg, 7711 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7712 int[] userIds) { 7713 IActivityManager am = ActivityManagerNative.getDefault(); 7714 if (am != null) { 7715 try { 7716 if (userIds == null) { 7717 userIds = am.getRunningUserIds(); 7718 } 7719 for (int id : userIds) { 7720 final Intent intent = new Intent(action, 7721 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7722 if (extras != null) { 7723 intent.putExtras(extras); 7724 } 7725 if (targetPkg != null) { 7726 intent.setPackage(targetPkg); 7727 } 7728 // Modify the UID when posting to other users 7729 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7730 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7731 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7732 intent.putExtra(Intent.EXTRA_UID, uid); 7733 } 7734 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7735 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7736 if (DEBUG_BROADCASTS) { 7737 RuntimeException here = new RuntimeException("here"); 7738 here.fillInStackTrace(); 7739 Slog.d(TAG, "Sending to user " + id + ": " 7740 + intent.toShortString(false, true, false, false) 7741 + " " + intent.getExtras(), here); 7742 } 7743 am.broadcastIntent(null, intent, null, finishedReceiver, 7744 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7745 finishedReceiver != null, false, id); 7746 } 7747 } catch (RemoteException ex) { 7748 } 7749 } 7750 } 7751 7752 /** 7753 * Check if the external storage media is available. This is true if there 7754 * is a mounted external storage medium or if the external storage is 7755 * emulated. 7756 */ 7757 private boolean isExternalMediaAvailable() { 7758 return mMediaMounted || Environment.isExternalStorageEmulated(); 7759 } 7760 7761 @Override 7762 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7763 // writer 7764 synchronized (mPackages) { 7765 if (!isExternalMediaAvailable()) { 7766 // If the external storage is no longer mounted at this point, 7767 // the caller may not have been able to delete all of this 7768 // packages files and can not delete any more. Bail. 7769 return null; 7770 } 7771 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7772 if (lastPackage != null) { 7773 pkgs.remove(lastPackage); 7774 } 7775 if (pkgs.size() > 0) { 7776 return pkgs.get(0); 7777 } 7778 } 7779 return null; 7780 } 7781 7782 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7783 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7784 userId, andCode ? 1 : 0, packageName); 7785 if (mSystemReady) { 7786 msg.sendToTarget(); 7787 } else { 7788 if (mPostSystemReadyMessages == null) { 7789 mPostSystemReadyMessages = new ArrayList<>(); 7790 } 7791 mPostSystemReadyMessages.add(msg); 7792 } 7793 } 7794 7795 void startCleaningPackages() { 7796 // reader 7797 synchronized (mPackages) { 7798 if (!isExternalMediaAvailable()) { 7799 return; 7800 } 7801 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7802 return; 7803 } 7804 } 7805 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7806 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7807 IActivityManager am = ActivityManagerNative.getDefault(); 7808 if (am != null) { 7809 try { 7810 am.startService(null, intent, null, UserHandle.USER_OWNER); 7811 } catch (RemoteException e) { 7812 } 7813 } 7814 } 7815 7816 @Override 7817 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7818 int installFlags, String installerPackageName, VerificationParams verificationParams, 7819 String packageAbiOverride) { 7820 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7821 packageAbiOverride, UserHandle.getCallingUserId()); 7822 } 7823 7824 @Override 7825 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7826 int installFlags, String installerPackageName, VerificationParams verificationParams, 7827 String packageAbiOverride, int userId) { 7828 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7829 7830 final int callingUid = Binder.getCallingUid(); 7831 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7832 7833 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7834 try { 7835 if (observer != null) { 7836 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7837 } 7838 } catch (RemoteException re) { 7839 } 7840 return; 7841 } 7842 7843 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7844 installFlags |= PackageManager.INSTALL_FROM_ADB; 7845 7846 } else { 7847 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7848 // about installerPackageName. 7849 7850 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7851 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7852 } 7853 7854 UserHandle user; 7855 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7856 user = UserHandle.ALL; 7857 } else { 7858 user = new UserHandle(userId); 7859 } 7860 7861 verificationParams.setInstallerUid(callingUid); 7862 7863 final File originFile = new File(originPath); 7864 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7865 7866 final Message msg = mHandler.obtainMessage(INIT_COPY); 7867 msg.obj = new InstallParams(origin, observer, installFlags, 7868 installerPackageName, verificationParams, user, packageAbiOverride); 7869 mHandler.sendMessage(msg); 7870 } 7871 7872 void installStage(String packageName, File stagedDir, String stagedCid, 7873 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7874 String installerPackageName, int installerUid, UserHandle user) { 7875 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7876 params.referrerUri, installerUid, null); 7877 7878 final OriginInfo origin; 7879 if (stagedDir != null) { 7880 origin = OriginInfo.fromStagedFile(stagedDir); 7881 } else { 7882 origin = OriginInfo.fromStagedContainer(stagedCid); 7883 } 7884 7885 final Message msg = mHandler.obtainMessage(INIT_COPY); 7886 msg.obj = new InstallParams(origin, observer, params.installFlags, 7887 installerPackageName, verifParams, user, params.abiOverride); 7888 mHandler.sendMessage(msg); 7889 } 7890 7891 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7892 Bundle extras = new Bundle(1); 7893 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7894 7895 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7896 packageName, extras, null, null, new int[] {userId}); 7897 try { 7898 IActivityManager am = ActivityManagerNative.getDefault(); 7899 final boolean isSystem = 7900 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7901 if (isSystem && am.isUserRunning(userId, false)) { 7902 // The just-installed/enabled app is bundled on the system, so presumed 7903 // to be able to run automatically without needing an explicit launch. 7904 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7905 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7906 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7907 .setPackage(packageName); 7908 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7909 android.app.AppOpsManager.OP_NONE, false, false, userId); 7910 } 7911 } catch (RemoteException e) { 7912 // shouldn't happen 7913 Slog.w(TAG, "Unable to bootstrap installed package", e); 7914 } 7915 } 7916 7917 @Override 7918 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7919 int userId) { 7920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7921 PackageSetting pkgSetting; 7922 final int uid = Binder.getCallingUid(); 7923 enforceCrossUserPermission(uid, userId, true, true, 7924 "setApplicationHiddenSetting for user " + userId); 7925 7926 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7927 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7928 return false; 7929 } 7930 7931 long callingId = Binder.clearCallingIdentity(); 7932 try { 7933 boolean sendAdded = false; 7934 boolean sendRemoved = false; 7935 // writer 7936 synchronized (mPackages) { 7937 pkgSetting = mSettings.mPackages.get(packageName); 7938 if (pkgSetting == null) { 7939 return false; 7940 } 7941 if (pkgSetting.getHidden(userId) != hidden) { 7942 pkgSetting.setHidden(hidden, userId); 7943 mSettings.writePackageRestrictionsLPr(userId); 7944 if (hidden) { 7945 sendRemoved = true; 7946 } else { 7947 sendAdded = true; 7948 } 7949 } 7950 } 7951 if (sendAdded) { 7952 sendPackageAddedForUser(packageName, pkgSetting, userId); 7953 return true; 7954 } 7955 if (sendRemoved) { 7956 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7957 "hiding pkg"); 7958 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7959 } 7960 } finally { 7961 Binder.restoreCallingIdentity(callingId); 7962 } 7963 return false; 7964 } 7965 7966 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7967 int userId) { 7968 final PackageRemovedInfo info = new PackageRemovedInfo(); 7969 info.removedPackage = packageName; 7970 info.removedUsers = new int[] {userId}; 7971 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7972 info.sendBroadcast(false, false, false); 7973 } 7974 7975 /** 7976 * Returns true if application is not found or there was an error. Otherwise it returns 7977 * the hidden state of the package for the given user. 7978 */ 7979 @Override 7980 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7982 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7983 false, "getApplicationHidden for user " + userId); 7984 PackageSetting pkgSetting; 7985 long callingId = Binder.clearCallingIdentity(); 7986 try { 7987 // writer 7988 synchronized (mPackages) { 7989 pkgSetting = mSettings.mPackages.get(packageName); 7990 if (pkgSetting == null) { 7991 return true; 7992 } 7993 return pkgSetting.getHidden(userId); 7994 } 7995 } finally { 7996 Binder.restoreCallingIdentity(callingId); 7997 } 7998 } 7999 8000 /** 8001 * @hide 8002 */ 8003 @Override 8004 public int installExistingPackageAsUser(String packageName, int userId) { 8005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8006 null); 8007 PackageSetting pkgSetting; 8008 final int uid = Binder.getCallingUid(); 8009 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8010 + userId); 8011 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8012 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8013 } 8014 8015 long callingId = Binder.clearCallingIdentity(); 8016 try { 8017 boolean sendAdded = false; 8018 Bundle extras = new Bundle(1); 8019 8020 // writer 8021 synchronized (mPackages) { 8022 pkgSetting = mSettings.mPackages.get(packageName); 8023 if (pkgSetting == null) { 8024 return PackageManager.INSTALL_FAILED_INVALID_URI; 8025 } 8026 if (!pkgSetting.getInstalled(userId)) { 8027 pkgSetting.setInstalled(true, userId); 8028 pkgSetting.setHidden(false, userId); 8029 mSettings.writePackageRestrictionsLPr(userId); 8030 sendAdded = true; 8031 } 8032 } 8033 8034 if (sendAdded) { 8035 sendPackageAddedForUser(packageName, pkgSetting, userId); 8036 } 8037 } finally { 8038 Binder.restoreCallingIdentity(callingId); 8039 } 8040 8041 return PackageManager.INSTALL_SUCCEEDED; 8042 } 8043 8044 boolean isUserRestricted(int userId, String restrictionKey) { 8045 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8046 if (restrictions.getBoolean(restrictionKey, false)) { 8047 Log.w(TAG, "User is restricted: " + restrictionKey); 8048 return true; 8049 } 8050 return false; 8051 } 8052 8053 @Override 8054 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8055 mContext.enforceCallingOrSelfPermission( 8056 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8057 "Only package verification agents can verify applications"); 8058 8059 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8060 final PackageVerificationResponse response = new PackageVerificationResponse( 8061 verificationCode, Binder.getCallingUid()); 8062 msg.arg1 = id; 8063 msg.obj = response; 8064 mHandler.sendMessage(msg); 8065 } 8066 8067 @Override 8068 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8069 long millisecondsToDelay) { 8070 mContext.enforceCallingOrSelfPermission( 8071 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8072 "Only package verification agents can extend verification timeouts"); 8073 8074 final PackageVerificationState state = mPendingVerification.get(id); 8075 final PackageVerificationResponse response = new PackageVerificationResponse( 8076 verificationCodeAtTimeout, Binder.getCallingUid()); 8077 8078 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8079 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8080 } 8081 if (millisecondsToDelay < 0) { 8082 millisecondsToDelay = 0; 8083 } 8084 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8085 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8086 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8087 } 8088 8089 if ((state != null) && !state.timeoutExtended()) { 8090 state.extendTimeout(); 8091 8092 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8093 msg.arg1 = id; 8094 msg.obj = response; 8095 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8096 } 8097 } 8098 8099 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8100 int verificationCode, UserHandle user) { 8101 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8102 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8103 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8104 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8105 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8106 8107 mContext.sendBroadcastAsUser(intent, user, 8108 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8109 } 8110 8111 private ComponentName matchComponentForVerifier(String packageName, 8112 List<ResolveInfo> receivers) { 8113 ActivityInfo targetReceiver = null; 8114 8115 final int NR = receivers.size(); 8116 for (int i = 0; i < NR; i++) { 8117 final ResolveInfo info = receivers.get(i); 8118 if (info.activityInfo == null) { 8119 continue; 8120 } 8121 8122 if (packageName.equals(info.activityInfo.packageName)) { 8123 targetReceiver = info.activityInfo; 8124 break; 8125 } 8126 } 8127 8128 if (targetReceiver == null) { 8129 return null; 8130 } 8131 8132 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8133 } 8134 8135 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8136 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8137 if (pkgInfo.verifiers.length == 0) { 8138 return null; 8139 } 8140 8141 final int N = pkgInfo.verifiers.length; 8142 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8143 for (int i = 0; i < N; i++) { 8144 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8145 8146 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8147 receivers); 8148 if (comp == null) { 8149 continue; 8150 } 8151 8152 final int verifierUid = getUidForVerifier(verifierInfo); 8153 if (verifierUid == -1) { 8154 continue; 8155 } 8156 8157 if (DEBUG_VERIFY) { 8158 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8159 + " with the correct signature"); 8160 } 8161 sufficientVerifiers.add(comp); 8162 verificationState.addSufficientVerifier(verifierUid); 8163 } 8164 8165 return sufficientVerifiers; 8166 } 8167 8168 private int getUidForVerifier(VerifierInfo verifierInfo) { 8169 synchronized (mPackages) { 8170 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8171 if (pkg == null) { 8172 return -1; 8173 } else if (pkg.mSignatures.length != 1) { 8174 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8175 + " has more than one signature; ignoring"); 8176 return -1; 8177 } 8178 8179 /* 8180 * If the public key of the package's signature does not match 8181 * our expected public key, then this is a different package and 8182 * we should skip. 8183 */ 8184 8185 final byte[] expectedPublicKey; 8186 try { 8187 final Signature verifierSig = pkg.mSignatures[0]; 8188 final PublicKey publicKey = verifierSig.getPublicKey(); 8189 expectedPublicKey = publicKey.getEncoded(); 8190 } catch (CertificateException e) { 8191 return -1; 8192 } 8193 8194 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8195 8196 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8197 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8198 + " does not have the expected public key; ignoring"); 8199 return -1; 8200 } 8201 8202 return pkg.applicationInfo.uid; 8203 } 8204 } 8205 8206 @Override 8207 public void finishPackageInstall(int token) { 8208 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8209 8210 if (DEBUG_INSTALL) { 8211 Slog.v(TAG, "BM finishing package install for " + token); 8212 } 8213 8214 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8215 mHandler.sendMessage(msg); 8216 } 8217 8218 /** 8219 * Get the verification agent timeout. 8220 * 8221 * @return verification timeout in milliseconds 8222 */ 8223 private long getVerificationTimeout() { 8224 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8225 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8226 DEFAULT_VERIFICATION_TIMEOUT); 8227 } 8228 8229 /** 8230 * Get the default verification agent response code. 8231 * 8232 * @return default verification response code 8233 */ 8234 private int getDefaultVerificationResponse() { 8235 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8236 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8237 DEFAULT_VERIFICATION_RESPONSE); 8238 } 8239 8240 /** 8241 * Check whether or not package verification has been enabled. 8242 * 8243 * @return true if verification should be performed 8244 */ 8245 private boolean isVerificationEnabled(int userId, int installFlags) { 8246 if (!DEFAULT_VERIFY_ENABLE) { 8247 return false; 8248 } 8249 8250 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8251 8252 // Check if installing from ADB 8253 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8254 // Do not run verification in a test harness environment 8255 if (ActivityManager.isRunningInTestHarness()) { 8256 return false; 8257 } 8258 if (ensureVerifyAppsEnabled) { 8259 return true; 8260 } 8261 // Check if the developer does not want package verification for ADB installs 8262 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8263 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8264 return false; 8265 } 8266 } 8267 8268 if (ensureVerifyAppsEnabled) { 8269 return true; 8270 } 8271 8272 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8273 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8274 } 8275 8276 /** 8277 * Get the "allow unknown sources" setting. 8278 * 8279 * @return the current "allow unknown sources" setting 8280 */ 8281 private int getUnknownSourcesSettings() { 8282 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8283 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8284 -1); 8285 } 8286 8287 @Override 8288 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8289 final int uid = Binder.getCallingUid(); 8290 // writer 8291 synchronized (mPackages) { 8292 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8293 if (targetPackageSetting == null) { 8294 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8295 } 8296 8297 PackageSetting installerPackageSetting; 8298 if (installerPackageName != null) { 8299 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8300 if (installerPackageSetting == null) { 8301 throw new IllegalArgumentException("Unknown installer package: " 8302 + installerPackageName); 8303 } 8304 } else { 8305 installerPackageSetting = null; 8306 } 8307 8308 Signature[] callerSignature; 8309 Object obj = mSettings.getUserIdLPr(uid); 8310 if (obj != null) { 8311 if (obj instanceof SharedUserSetting) { 8312 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8313 } else if (obj instanceof PackageSetting) { 8314 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8315 } else { 8316 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8317 } 8318 } else { 8319 throw new SecurityException("Unknown calling uid " + uid); 8320 } 8321 8322 // Verify: can't set installerPackageName to a package that is 8323 // not signed with the same cert as the caller. 8324 if (installerPackageSetting != null) { 8325 if (compareSignatures(callerSignature, 8326 installerPackageSetting.signatures.mSignatures) 8327 != PackageManager.SIGNATURE_MATCH) { 8328 throw new SecurityException( 8329 "Caller does not have same cert as new installer package " 8330 + installerPackageName); 8331 } 8332 } 8333 8334 // Verify: if target already has an installer package, it must 8335 // be signed with the same cert as the caller. 8336 if (targetPackageSetting.installerPackageName != null) { 8337 PackageSetting setting = mSettings.mPackages.get( 8338 targetPackageSetting.installerPackageName); 8339 // If the currently set package isn't valid, then it's always 8340 // okay to change it. 8341 if (setting != null) { 8342 if (compareSignatures(callerSignature, 8343 setting.signatures.mSignatures) 8344 != PackageManager.SIGNATURE_MATCH) { 8345 throw new SecurityException( 8346 "Caller does not have same cert as old installer package " 8347 + targetPackageSetting.installerPackageName); 8348 } 8349 } 8350 } 8351 8352 // Okay! 8353 targetPackageSetting.installerPackageName = installerPackageName; 8354 scheduleWriteSettingsLocked(); 8355 } 8356 } 8357 8358 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8359 // Queue up an async operation since the package installation may take a little while. 8360 mHandler.post(new Runnable() { 8361 public void run() { 8362 mHandler.removeCallbacks(this); 8363 // Result object to be returned 8364 PackageInstalledInfo res = new PackageInstalledInfo(); 8365 res.returnCode = currentStatus; 8366 res.uid = -1; 8367 res.pkg = null; 8368 res.removedInfo = new PackageRemovedInfo(); 8369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8370 args.doPreInstall(res.returnCode); 8371 synchronized (mInstallLock) { 8372 installPackageLI(args, res); 8373 } 8374 args.doPostInstall(res.returnCode, res.uid); 8375 } 8376 8377 // A restore should be performed at this point if (a) the install 8378 // succeeded, (b) the operation is not an update, and (c) the new 8379 // package has not opted out of backup participation. 8380 final boolean update = res.removedInfo.removedPackage != null; 8381 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8382 boolean doRestore = !update 8383 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8384 8385 // Set up the post-install work request bookkeeping. This will be used 8386 // and cleaned up by the post-install event handling regardless of whether 8387 // there's a restore pass performed. Token values are >= 1. 8388 int token; 8389 if (mNextInstallToken < 0) mNextInstallToken = 1; 8390 token = mNextInstallToken++; 8391 8392 PostInstallData data = new PostInstallData(args, res); 8393 mRunningInstalls.put(token, data); 8394 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8395 8396 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8397 // Pass responsibility to the Backup Manager. It will perform a 8398 // restore if appropriate, then pass responsibility back to the 8399 // Package Manager to run the post-install observer callbacks 8400 // and broadcasts. 8401 IBackupManager bm = IBackupManager.Stub.asInterface( 8402 ServiceManager.getService(Context.BACKUP_SERVICE)); 8403 if (bm != null) { 8404 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8405 + " to BM for possible restore"); 8406 try { 8407 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8408 } catch (RemoteException e) { 8409 // can't happen; the backup manager is local 8410 } catch (Exception e) { 8411 Slog.e(TAG, "Exception trying to enqueue restore", e); 8412 doRestore = false; 8413 } 8414 } else { 8415 Slog.e(TAG, "Backup Manager not found!"); 8416 doRestore = false; 8417 } 8418 } 8419 8420 if (!doRestore) { 8421 // No restore possible, or the Backup Manager was mysteriously not 8422 // available -- just fire the post-install work request directly. 8423 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8424 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8425 mHandler.sendMessage(msg); 8426 } 8427 } 8428 }); 8429 } 8430 8431 private abstract class HandlerParams { 8432 private static final int MAX_RETRIES = 4; 8433 8434 /** 8435 * Number of times startCopy() has been attempted and had a non-fatal 8436 * error. 8437 */ 8438 private int mRetries = 0; 8439 8440 /** User handle for the user requesting the information or installation. */ 8441 private final UserHandle mUser; 8442 8443 HandlerParams(UserHandle user) { 8444 mUser = user; 8445 } 8446 8447 UserHandle getUser() { 8448 return mUser; 8449 } 8450 8451 final boolean startCopy() { 8452 boolean res; 8453 try { 8454 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8455 8456 if (++mRetries > MAX_RETRIES) { 8457 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8458 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8459 handleServiceError(); 8460 return false; 8461 } else { 8462 handleStartCopy(); 8463 res = true; 8464 } 8465 } catch (RemoteException e) { 8466 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8467 mHandler.sendEmptyMessage(MCS_RECONNECT); 8468 res = false; 8469 } 8470 handleReturnCode(); 8471 return res; 8472 } 8473 8474 final void serviceError() { 8475 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8476 handleServiceError(); 8477 handleReturnCode(); 8478 } 8479 8480 abstract void handleStartCopy() throws RemoteException; 8481 abstract void handleServiceError(); 8482 abstract void handleReturnCode(); 8483 } 8484 8485 class MeasureParams extends HandlerParams { 8486 private final PackageStats mStats; 8487 private boolean mSuccess; 8488 8489 private final IPackageStatsObserver mObserver; 8490 8491 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8492 super(new UserHandle(stats.userHandle)); 8493 mObserver = observer; 8494 mStats = stats; 8495 } 8496 8497 @Override 8498 public String toString() { 8499 return "MeasureParams{" 8500 + Integer.toHexString(System.identityHashCode(this)) 8501 + " " + mStats.packageName + "}"; 8502 } 8503 8504 @Override 8505 void handleStartCopy() throws RemoteException { 8506 synchronized (mInstallLock) { 8507 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8508 } 8509 8510 if (mSuccess) { 8511 final boolean mounted; 8512 if (Environment.isExternalStorageEmulated()) { 8513 mounted = true; 8514 } else { 8515 final String status = Environment.getExternalStorageState(); 8516 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8517 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8518 } 8519 8520 if (mounted) { 8521 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8522 8523 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8524 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8525 8526 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8527 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8528 8529 // Always subtract cache size, since it's a subdirectory 8530 mStats.externalDataSize -= mStats.externalCacheSize; 8531 8532 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8533 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8534 8535 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8536 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8537 } 8538 } 8539 } 8540 8541 @Override 8542 void handleReturnCode() { 8543 if (mObserver != null) { 8544 try { 8545 mObserver.onGetStatsCompleted(mStats, mSuccess); 8546 } catch (RemoteException e) { 8547 Slog.i(TAG, "Observer no longer exists."); 8548 } 8549 } 8550 } 8551 8552 @Override 8553 void handleServiceError() { 8554 Slog.e(TAG, "Could not measure application " + mStats.packageName 8555 + " external storage"); 8556 } 8557 } 8558 8559 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8560 throws RemoteException { 8561 long result = 0; 8562 for (File path : paths) { 8563 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8564 } 8565 return result; 8566 } 8567 8568 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8569 for (File path : paths) { 8570 try { 8571 mcs.clearDirectory(path.getAbsolutePath()); 8572 } catch (RemoteException e) { 8573 } 8574 } 8575 } 8576 8577 static class OriginInfo { 8578 /** 8579 * Location where install is coming from, before it has been 8580 * copied/renamed into place. This could be a single monolithic APK 8581 * file, or a cluster directory. This location may be untrusted. 8582 */ 8583 final File file; 8584 final String cid; 8585 8586 /** 8587 * Flag indicating that {@link #file} or {@link #cid} has already been 8588 * staged, meaning downstream users don't need to defensively copy the 8589 * contents. 8590 */ 8591 final boolean staged; 8592 8593 /** 8594 * Flag indicating that {@link #file} or {@link #cid} is an already 8595 * installed app that is being moved. 8596 */ 8597 final boolean existing; 8598 8599 final String resolvedPath; 8600 final File resolvedFile; 8601 8602 static OriginInfo fromNothing() { 8603 return new OriginInfo(null, null, false, false); 8604 } 8605 8606 static OriginInfo fromUntrustedFile(File file) { 8607 return new OriginInfo(file, null, false, false); 8608 } 8609 8610 static OriginInfo fromExistingFile(File file) { 8611 return new OriginInfo(file, null, false, true); 8612 } 8613 8614 static OriginInfo fromStagedFile(File file) { 8615 return new OriginInfo(file, null, true, false); 8616 } 8617 8618 static OriginInfo fromStagedContainer(String cid) { 8619 return new OriginInfo(null, cid, true, false); 8620 } 8621 8622 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8623 this.file = file; 8624 this.cid = cid; 8625 this.staged = staged; 8626 this.existing = existing; 8627 8628 if (cid != null) { 8629 resolvedPath = PackageHelper.getSdDir(cid); 8630 resolvedFile = new File(resolvedPath); 8631 } else if (file != null) { 8632 resolvedPath = file.getAbsolutePath(); 8633 resolvedFile = file; 8634 } else { 8635 resolvedPath = null; 8636 resolvedFile = null; 8637 } 8638 } 8639 } 8640 8641 class InstallParams extends HandlerParams { 8642 final OriginInfo origin; 8643 final IPackageInstallObserver2 observer; 8644 int installFlags; 8645 final String installerPackageName; 8646 final VerificationParams verificationParams; 8647 private InstallArgs mArgs; 8648 private int mRet; 8649 final String packageAbiOverride; 8650 8651 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8652 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8653 String packageAbiOverride) { 8654 super(user); 8655 this.origin = origin; 8656 this.observer = observer; 8657 this.installFlags = installFlags; 8658 this.installerPackageName = installerPackageName; 8659 this.verificationParams = verificationParams; 8660 this.packageAbiOverride = packageAbiOverride; 8661 } 8662 8663 @Override 8664 public String toString() { 8665 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8666 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8667 } 8668 8669 public ManifestDigest getManifestDigest() { 8670 if (verificationParams == null) { 8671 return null; 8672 } 8673 return verificationParams.getManifestDigest(); 8674 } 8675 8676 private int installLocationPolicy(PackageInfoLite pkgLite) { 8677 String packageName = pkgLite.packageName; 8678 int installLocation = pkgLite.installLocation; 8679 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8680 // reader 8681 synchronized (mPackages) { 8682 PackageParser.Package pkg = mPackages.get(packageName); 8683 if (pkg != null) { 8684 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8685 // Check for downgrading. 8686 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8687 if (pkgLite.versionCode < pkg.mVersionCode) { 8688 Slog.w(TAG, "Can't install update of " + packageName 8689 + " update version " + pkgLite.versionCode 8690 + " is older than installed version " 8691 + pkg.mVersionCode); 8692 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8693 } 8694 } 8695 // Check for updated system application. 8696 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8697 if (onSd) { 8698 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8699 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8700 } 8701 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8702 } else { 8703 if (onSd) { 8704 // Install flag overrides everything. 8705 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8706 } 8707 // If current upgrade specifies particular preference 8708 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8709 // Application explicitly specified internal. 8710 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8711 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8712 // App explictly prefers external. Let policy decide 8713 } else { 8714 // Prefer previous location 8715 if (isExternal(pkg)) { 8716 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8717 } 8718 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8719 } 8720 } 8721 } else { 8722 // Invalid install. Return error code 8723 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8724 } 8725 } 8726 } 8727 // All the special cases have been taken care of. 8728 // Return result based on recommended install location. 8729 if (onSd) { 8730 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8731 } 8732 return pkgLite.recommendedInstallLocation; 8733 } 8734 8735 /* 8736 * Invoke remote method to get package information and install 8737 * location values. Override install location based on default 8738 * policy if needed and then create install arguments based 8739 * on the install location. 8740 */ 8741 public void handleStartCopy() throws RemoteException { 8742 int ret = PackageManager.INSTALL_SUCCEEDED; 8743 8744 // If we're already staged, we've firmly committed to an install location 8745 if (origin.staged) { 8746 if (origin.file != null) { 8747 installFlags |= PackageManager.INSTALL_INTERNAL; 8748 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8749 } else if (origin.cid != null) { 8750 installFlags |= PackageManager.INSTALL_EXTERNAL; 8751 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8752 } else { 8753 throw new IllegalStateException("Invalid stage location"); 8754 } 8755 } 8756 8757 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8758 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8759 8760 PackageInfoLite pkgLite = null; 8761 8762 if (onInt && onSd) { 8763 // Check if both bits are set. 8764 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8765 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8766 } else { 8767 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8768 packageAbiOverride); 8769 8770 /* 8771 * If we have too little free space, try to free cache 8772 * before giving up. 8773 */ 8774 if (!origin.staged && pkgLite.recommendedInstallLocation 8775 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8776 // TODO: focus freeing disk space on the target device 8777 final StorageManager storage = StorageManager.from(mContext); 8778 final long lowThreshold = storage.getStorageLowBytes( 8779 Environment.getDataDirectory()); 8780 8781 final long sizeBytes = mContainerService.calculateInstalledSize( 8782 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8783 8784 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8785 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8786 installFlags, packageAbiOverride); 8787 } 8788 8789 /* 8790 * The cache free must have deleted the file we 8791 * downloaded to install. 8792 * 8793 * TODO: fix the "freeCache" call to not delete 8794 * the file we care about. 8795 */ 8796 if (pkgLite.recommendedInstallLocation 8797 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8798 pkgLite.recommendedInstallLocation 8799 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8800 } 8801 } 8802 } 8803 8804 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8805 int loc = pkgLite.recommendedInstallLocation; 8806 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8807 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8808 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8809 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8810 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8811 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8812 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8813 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8814 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8815 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8816 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8817 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8818 } else { 8819 // Override with defaults if needed. 8820 loc = installLocationPolicy(pkgLite); 8821 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8822 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8823 } else if (!onSd && !onInt) { 8824 // Override install location with flags 8825 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8826 // Set the flag to install on external media. 8827 installFlags |= PackageManager.INSTALL_EXTERNAL; 8828 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8829 } else { 8830 // Make sure the flag for installing on external 8831 // media is unset 8832 installFlags |= PackageManager.INSTALL_INTERNAL; 8833 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8834 } 8835 } 8836 } 8837 } 8838 8839 final InstallArgs args = createInstallArgs(this); 8840 mArgs = args; 8841 8842 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8843 /* 8844 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8845 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8846 */ 8847 int userIdentifier = getUser().getIdentifier(); 8848 if (userIdentifier == UserHandle.USER_ALL 8849 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8850 userIdentifier = UserHandle.USER_OWNER; 8851 } 8852 8853 /* 8854 * Determine if we have any installed package verifiers. If we 8855 * do, then we'll defer to them to verify the packages. 8856 */ 8857 final int requiredUid = mRequiredVerifierPackage == null ? -1 8858 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8859 if (!origin.existing && requiredUid != -1 8860 && isVerificationEnabled(userIdentifier, installFlags)) { 8861 final Intent verification = new Intent( 8862 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8863 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8864 PACKAGE_MIME_TYPE); 8865 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8866 8867 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8868 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8869 0 /* TODO: Which userId? */); 8870 8871 if (DEBUG_VERIFY) { 8872 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8873 + verification.toString() + " with " + pkgLite.verifiers.length 8874 + " optional verifiers"); 8875 } 8876 8877 final int verificationId = mPendingVerificationToken++; 8878 8879 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8880 8881 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8882 installerPackageName); 8883 8884 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8885 installFlags); 8886 8887 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8888 pkgLite.packageName); 8889 8890 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8891 pkgLite.versionCode); 8892 8893 if (verificationParams != null) { 8894 if (verificationParams.getVerificationURI() != null) { 8895 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8896 verificationParams.getVerificationURI()); 8897 } 8898 if (verificationParams.getOriginatingURI() != null) { 8899 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8900 verificationParams.getOriginatingURI()); 8901 } 8902 if (verificationParams.getReferrer() != null) { 8903 verification.putExtra(Intent.EXTRA_REFERRER, 8904 verificationParams.getReferrer()); 8905 } 8906 if (verificationParams.getOriginatingUid() >= 0) { 8907 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8908 verificationParams.getOriginatingUid()); 8909 } 8910 if (verificationParams.getInstallerUid() >= 0) { 8911 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8912 verificationParams.getInstallerUid()); 8913 } 8914 } 8915 8916 final PackageVerificationState verificationState = new PackageVerificationState( 8917 requiredUid, args); 8918 8919 mPendingVerification.append(verificationId, verificationState); 8920 8921 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8922 receivers, verificationState); 8923 8924 /* 8925 * If any sufficient verifiers were listed in the package 8926 * manifest, attempt to ask them. 8927 */ 8928 if (sufficientVerifiers != null) { 8929 final int N = sufficientVerifiers.size(); 8930 if (N == 0) { 8931 Slog.i(TAG, "Additional verifiers required, but none installed."); 8932 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8933 } else { 8934 for (int i = 0; i < N; i++) { 8935 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8936 8937 final Intent sufficientIntent = new Intent(verification); 8938 sufficientIntent.setComponent(verifierComponent); 8939 8940 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8941 } 8942 } 8943 } 8944 8945 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8946 mRequiredVerifierPackage, receivers); 8947 if (ret == PackageManager.INSTALL_SUCCEEDED 8948 && mRequiredVerifierPackage != null) { 8949 /* 8950 * Send the intent to the required verification agent, 8951 * but only start the verification timeout after the 8952 * target BroadcastReceivers have run. 8953 */ 8954 verification.setComponent(requiredVerifierComponent); 8955 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8956 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8957 new BroadcastReceiver() { 8958 @Override 8959 public void onReceive(Context context, Intent intent) { 8960 final Message msg = mHandler 8961 .obtainMessage(CHECK_PENDING_VERIFICATION); 8962 msg.arg1 = verificationId; 8963 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8964 } 8965 }, null, 0, null, null); 8966 8967 /* 8968 * We don't want the copy to proceed until verification 8969 * succeeds, so null out this field. 8970 */ 8971 mArgs = null; 8972 } 8973 } else { 8974 /* 8975 * No package verification is enabled, so immediately start 8976 * the remote call to initiate copy using temporary file. 8977 */ 8978 ret = args.copyApk(mContainerService, true); 8979 } 8980 } 8981 8982 mRet = ret; 8983 } 8984 8985 @Override 8986 void handleReturnCode() { 8987 // If mArgs is null, then MCS couldn't be reached. When it 8988 // reconnects, it will try again to install. At that point, this 8989 // will succeed. 8990 if (mArgs != null) { 8991 processPendingInstall(mArgs, mRet); 8992 } 8993 } 8994 8995 @Override 8996 void handleServiceError() { 8997 mArgs = createInstallArgs(this); 8998 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8999 } 9000 9001 public boolean isForwardLocked() { 9002 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9003 } 9004 } 9005 9006 /** 9007 * Used during creation of InstallArgs 9008 * 9009 * @param installFlags package installation flags 9010 * @return true if should be installed on external storage 9011 */ 9012 private static boolean installOnSd(int installFlags) { 9013 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9014 return false; 9015 } 9016 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9017 return true; 9018 } 9019 return false; 9020 } 9021 9022 /** 9023 * Used during creation of InstallArgs 9024 * 9025 * @param installFlags package installation flags 9026 * @return true if should be installed as forward locked 9027 */ 9028 private static boolean installForwardLocked(int installFlags) { 9029 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9030 } 9031 9032 private InstallArgs createInstallArgs(InstallParams params) { 9033 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9034 return new AsecInstallArgs(params); 9035 } else { 9036 return new FileInstallArgs(params); 9037 } 9038 } 9039 9040 /** 9041 * Create args that describe an existing installed package. Typically used 9042 * when cleaning up old installs, or used as a move source. 9043 */ 9044 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9045 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9046 final boolean isInAsec; 9047 if (installOnSd(installFlags)) { 9048 /* Apps on SD card are always in ASEC containers. */ 9049 isInAsec = true; 9050 } else if (installForwardLocked(installFlags) 9051 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9052 /* 9053 * Forward-locked apps are only in ASEC containers if they're the 9054 * new style 9055 */ 9056 isInAsec = true; 9057 } else { 9058 isInAsec = false; 9059 } 9060 9061 if (isInAsec) { 9062 return new AsecInstallArgs(codePath, instructionSets, 9063 installOnSd(installFlags), installForwardLocked(installFlags)); 9064 } else { 9065 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9066 instructionSets); 9067 } 9068 } 9069 9070 static abstract class InstallArgs { 9071 /** @see InstallParams#origin */ 9072 final OriginInfo origin; 9073 9074 final IPackageInstallObserver2 observer; 9075 // Always refers to PackageManager flags only 9076 final int installFlags; 9077 final String installerPackageName; 9078 final ManifestDigest manifestDigest; 9079 final UserHandle user; 9080 final String abiOverride; 9081 9082 // The list of instruction sets supported by this app. This is currently 9083 // only used during the rmdex() phase to clean up resources. We can get rid of this 9084 // if we move dex files under the common app path. 9085 /* nullable */ String[] instructionSets; 9086 9087 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9088 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9089 String[] instructionSets, String abiOverride) { 9090 this.origin = origin; 9091 this.installFlags = installFlags; 9092 this.observer = observer; 9093 this.installerPackageName = installerPackageName; 9094 this.manifestDigest = manifestDigest; 9095 this.user = user; 9096 this.instructionSets = instructionSets; 9097 this.abiOverride = abiOverride; 9098 } 9099 9100 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9101 abstract int doPreInstall(int status); 9102 9103 /** 9104 * Rename package into final resting place. All paths on the given 9105 * scanned package should be updated to reflect the rename. 9106 */ 9107 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9108 abstract int doPostInstall(int status, int uid); 9109 9110 /** @see PackageSettingBase#codePathString */ 9111 abstract String getCodePath(); 9112 /** @see PackageSettingBase#resourcePathString */ 9113 abstract String getResourcePath(); 9114 abstract String getLegacyNativeLibraryPath(); 9115 9116 // Need installer lock especially for dex file removal. 9117 abstract void cleanUpResourcesLI(); 9118 abstract boolean doPostDeleteLI(boolean delete); 9119 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9120 9121 /** 9122 * Called before the source arguments are copied. This is used mostly 9123 * for MoveParams when it needs to read the source file to put it in the 9124 * destination. 9125 */ 9126 int doPreCopy() { 9127 return PackageManager.INSTALL_SUCCEEDED; 9128 } 9129 9130 /** 9131 * Called after the source arguments are copied. This is used mostly for 9132 * MoveParams when it needs to read the source file to put it in the 9133 * destination. 9134 * 9135 * @return 9136 */ 9137 int doPostCopy(int uid) { 9138 return PackageManager.INSTALL_SUCCEEDED; 9139 } 9140 9141 protected boolean isFwdLocked() { 9142 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9143 } 9144 9145 protected boolean isExternal() { 9146 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9147 } 9148 9149 UserHandle getUser() { 9150 return user; 9151 } 9152 } 9153 9154 /** 9155 * Logic to handle installation of non-ASEC applications, including copying 9156 * and renaming logic. 9157 */ 9158 class FileInstallArgs extends InstallArgs { 9159 private File codeFile; 9160 private File resourceFile; 9161 private File legacyNativeLibraryPath; 9162 9163 // Example topology: 9164 // /data/app/com.example/base.apk 9165 // /data/app/com.example/split_foo.apk 9166 // /data/app/com.example/lib/arm/libfoo.so 9167 // /data/app/com.example/lib/arm64/libfoo.so 9168 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9169 9170 /** New install */ 9171 FileInstallArgs(InstallParams params) { 9172 super(params.origin, params.observer, params.installFlags, 9173 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9174 null /* instruction sets */, params.packageAbiOverride); 9175 if (isFwdLocked()) { 9176 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9177 } 9178 } 9179 9180 /** Existing install */ 9181 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9182 String[] instructionSets) { 9183 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9184 this.codeFile = (codePath != null) ? new File(codePath) : null; 9185 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9186 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9187 new File(legacyNativeLibraryPath) : null; 9188 } 9189 9190 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9191 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9192 isFwdLocked(), abiOverride); 9193 9194 final StorageManager storage = StorageManager.from(mContext); 9195 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9196 } 9197 9198 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9199 if (origin.staged) { 9200 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9201 codeFile = origin.file; 9202 resourceFile = origin.file; 9203 return PackageManager.INSTALL_SUCCEEDED; 9204 } 9205 9206 try { 9207 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9208 codeFile = tempDir; 9209 resourceFile = tempDir; 9210 } catch (IOException e) { 9211 Slog.w(TAG, "Failed to create copy file: " + e); 9212 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9213 } 9214 9215 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9216 @Override 9217 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9218 if (!FileUtils.isValidExtFilename(name)) { 9219 throw new IllegalArgumentException("Invalid filename: " + name); 9220 } 9221 try { 9222 final File file = new File(codeFile, name); 9223 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9224 O_RDWR | O_CREAT, 0644); 9225 Os.chmod(file.getAbsolutePath(), 0644); 9226 return new ParcelFileDescriptor(fd); 9227 } catch (ErrnoException e) { 9228 throw new RemoteException("Failed to open: " + e.getMessage()); 9229 } 9230 } 9231 }; 9232 9233 int ret = PackageManager.INSTALL_SUCCEEDED; 9234 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9235 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9236 Slog.e(TAG, "Failed to copy package"); 9237 return ret; 9238 } 9239 9240 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9241 NativeLibraryHelper.Handle handle = null; 9242 try { 9243 handle = NativeLibraryHelper.Handle.create(codeFile); 9244 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9245 abiOverride); 9246 } catch (IOException e) { 9247 Slog.e(TAG, "Copying native libraries failed", e); 9248 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9249 } finally { 9250 IoUtils.closeQuietly(handle); 9251 } 9252 9253 return ret; 9254 } 9255 9256 int doPreInstall(int status) { 9257 if (status != PackageManager.INSTALL_SUCCEEDED) { 9258 cleanUp(); 9259 } 9260 return status; 9261 } 9262 9263 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9264 if (status != PackageManager.INSTALL_SUCCEEDED) { 9265 cleanUp(); 9266 return false; 9267 } else { 9268 final File beforeCodeFile = codeFile; 9269 final File afterCodeFile = getNextCodePath(pkg.packageName); 9270 9271 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9272 try { 9273 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9274 } catch (ErrnoException e) { 9275 Slog.d(TAG, "Failed to rename", e); 9276 return false; 9277 } 9278 9279 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9280 Slog.d(TAG, "Failed to restorecon"); 9281 return false; 9282 } 9283 9284 // Reflect the rename internally 9285 codeFile = afterCodeFile; 9286 resourceFile = afterCodeFile; 9287 9288 // Reflect the rename in scanned details 9289 pkg.codePath = afterCodeFile.getAbsolutePath(); 9290 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9291 pkg.baseCodePath); 9292 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9293 pkg.splitCodePaths); 9294 9295 // Reflect the rename in app info 9296 pkg.applicationInfo.setCodePath(pkg.codePath); 9297 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9298 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9299 pkg.applicationInfo.setResourcePath(pkg.codePath); 9300 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9301 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9302 9303 return true; 9304 } 9305 } 9306 9307 int doPostInstall(int status, int uid) { 9308 if (status != PackageManager.INSTALL_SUCCEEDED) { 9309 cleanUp(); 9310 } 9311 return status; 9312 } 9313 9314 @Override 9315 String getCodePath() { 9316 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9317 } 9318 9319 @Override 9320 String getResourcePath() { 9321 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9322 } 9323 9324 @Override 9325 String getLegacyNativeLibraryPath() { 9326 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9327 } 9328 9329 private boolean cleanUp() { 9330 if (codeFile == null || !codeFile.exists()) { 9331 return false; 9332 } 9333 9334 if (codeFile.isDirectory()) { 9335 FileUtils.deleteContents(codeFile); 9336 } 9337 codeFile.delete(); 9338 9339 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9340 resourceFile.delete(); 9341 } 9342 9343 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9344 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9345 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9346 } 9347 legacyNativeLibraryPath.delete(); 9348 } 9349 9350 return true; 9351 } 9352 9353 void cleanUpResourcesLI() { 9354 // Try enumerating all code paths before deleting 9355 List<String> allCodePaths = Collections.EMPTY_LIST; 9356 if (codeFile != null && codeFile.exists()) { 9357 try { 9358 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9359 allCodePaths = pkg.getAllCodePaths(); 9360 } catch (PackageParserException e) { 9361 // Ignored; we tried our best 9362 } 9363 } 9364 9365 cleanUp(); 9366 9367 if (!allCodePaths.isEmpty()) { 9368 if (instructionSets == null) { 9369 throw new IllegalStateException("instructionSet == null"); 9370 } 9371 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9372 for (String codePath : allCodePaths) { 9373 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9374 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9375 if (retCode < 0) { 9376 Slog.w(TAG, "Couldn't remove dex file for package: " 9377 + " at location " + codePath + ", retcode=" + retCode); 9378 // we don't consider this to be a failure of the core package deletion 9379 } 9380 } 9381 } 9382 } 9383 } 9384 9385 boolean doPostDeleteLI(boolean delete) { 9386 // XXX err, shouldn't we respect the delete flag? 9387 cleanUpResourcesLI(); 9388 return true; 9389 } 9390 } 9391 9392 private boolean isAsecExternal(String cid) { 9393 final String asecPath = PackageHelper.getSdFilesystem(cid); 9394 return !asecPath.startsWith(mAsecInternalPath); 9395 } 9396 9397 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9398 PackageManagerException { 9399 if (copyRet < 0) { 9400 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9401 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9402 throw new PackageManagerException(copyRet, message); 9403 } 9404 } 9405 } 9406 9407 /** 9408 * Extract the MountService "container ID" from the full code path of an 9409 * .apk. 9410 */ 9411 static String cidFromCodePath(String fullCodePath) { 9412 int eidx = fullCodePath.lastIndexOf("/"); 9413 String subStr1 = fullCodePath.substring(0, eidx); 9414 int sidx = subStr1.lastIndexOf("/"); 9415 return subStr1.substring(sidx+1, eidx); 9416 } 9417 9418 /** 9419 * Logic to handle installation of ASEC applications, including copying and 9420 * renaming logic. 9421 */ 9422 class AsecInstallArgs extends InstallArgs { 9423 static final String RES_FILE_NAME = "pkg.apk"; 9424 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9425 9426 String cid; 9427 String packagePath; 9428 String resourcePath; 9429 String legacyNativeLibraryDir; 9430 9431 /** New install */ 9432 AsecInstallArgs(InstallParams params) { 9433 super(params.origin, params.observer, params.installFlags, 9434 params.installerPackageName, params.getManifestDigest(), 9435 params.getUser(), null /* instruction sets */, 9436 params.packageAbiOverride); 9437 } 9438 9439 /** Existing install */ 9440 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9441 boolean isExternal, boolean isForwardLocked) { 9442 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9443 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9444 instructionSets, null); 9445 // Hackily pretend we're still looking at a full code path 9446 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9447 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9448 } 9449 9450 // Extract cid from fullCodePath 9451 int eidx = fullCodePath.lastIndexOf("/"); 9452 String subStr1 = fullCodePath.substring(0, eidx); 9453 int sidx = subStr1.lastIndexOf("/"); 9454 cid = subStr1.substring(sidx+1, eidx); 9455 setMountPath(subStr1); 9456 } 9457 9458 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9459 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9460 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9461 instructionSets, null); 9462 this.cid = cid; 9463 setMountPath(PackageHelper.getSdDir(cid)); 9464 } 9465 9466 void createCopyFile() { 9467 cid = mInstallerService.allocateExternalStageCidLegacy(); 9468 } 9469 9470 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9471 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9472 abiOverride); 9473 9474 final File target; 9475 if (isExternal()) { 9476 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9477 } else { 9478 target = Environment.getDataDirectory(); 9479 } 9480 9481 final StorageManager storage = StorageManager.from(mContext); 9482 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9483 } 9484 9485 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9486 if (origin.staged) { 9487 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9488 cid = origin.cid; 9489 setMountPath(PackageHelper.getSdDir(cid)); 9490 return PackageManager.INSTALL_SUCCEEDED; 9491 } 9492 9493 if (temp) { 9494 createCopyFile(); 9495 } else { 9496 /* 9497 * Pre-emptively destroy the container since it's destroyed if 9498 * copying fails due to it existing anyway. 9499 */ 9500 PackageHelper.destroySdDir(cid); 9501 } 9502 9503 final String newMountPath = imcs.copyPackageToContainer( 9504 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9505 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9506 9507 if (newMountPath != null) { 9508 setMountPath(newMountPath); 9509 return PackageManager.INSTALL_SUCCEEDED; 9510 } else { 9511 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9512 } 9513 } 9514 9515 @Override 9516 String getCodePath() { 9517 return packagePath; 9518 } 9519 9520 @Override 9521 String getResourcePath() { 9522 return resourcePath; 9523 } 9524 9525 @Override 9526 String getLegacyNativeLibraryPath() { 9527 return legacyNativeLibraryDir; 9528 } 9529 9530 int doPreInstall(int status) { 9531 if (status != PackageManager.INSTALL_SUCCEEDED) { 9532 // Destroy container 9533 PackageHelper.destroySdDir(cid); 9534 } else { 9535 boolean mounted = PackageHelper.isContainerMounted(cid); 9536 if (!mounted) { 9537 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9538 Process.SYSTEM_UID); 9539 if (newMountPath != null) { 9540 setMountPath(newMountPath); 9541 } else { 9542 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9543 } 9544 } 9545 } 9546 return status; 9547 } 9548 9549 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9550 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9551 String newMountPath = null; 9552 if (PackageHelper.isContainerMounted(cid)) { 9553 // Unmount the container 9554 if (!PackageHelper.unMountSdDir(cid)) { 9555 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9556 return false; 9557 } 9558 } 9559 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9560 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9561 " which might be stale. Will try to clean up."); 9562 // Clean up the stale container and proceed to recreate. 9563 if (!PackageHelper.destroySdDir(newCacheId)) { 9564 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9565 return false; 9566 } 9567 // Successfully cleaned up stale container. Try to rename again. 9568 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9569 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9570 + " inspite of cleaning it up."); 9571 return false; 9572 } 9573 } 9574 if (!PackageHelper.isContainerMounted(newCacheId)) { 9575 Slog.w(TAG, "Mounting container " + newCacheId); 9576 newMountPath = PackageHelper.mountSdDir(newCacheId, 9577 getEncryptKey(), Process.SYSTEM_UID); 9578 } else { 9579 newMountPath = PackageHelper.getSdDir(newCacheId); 9580 } 9581 if (newMountPath == null) { 9582 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9583 return false; 9584 } 9585 Log.i(TAG, "Succesfully renamed " + cid + 9586 " to " + newCacheId + 9587 " at new path: " + newMountPath); 9588 cid = newCacheId; 9589 9590 final File beforeCodeFile = new File(packagePath); 9591 setMountPath(newMountPath); 9592 final File afterCodeFile = new File(packagePath); 9593 9594 // Reflect the rename in scanned details 9595 pkg.codePath = afterCodeFile.getAbsolutePath(); 9596 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9597 pkg.baseCodePath); 9598 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9599 pkg.splitCodePaths); 9600 9601 // Reflect the rename in app info 9602 pkg.applicationInfo.setCodePath(pkg.codePath); 9603 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9604 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9605 pkg.applicationInfo.setResourcePath(pkg.codePath); 9606 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9607 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9608 9609 return true; 9610 } 9611 9612 private void setMountPath(String mountPath) { 9613 final File mountFile = new File(mountPath); 9614 9615 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9616 if (monolithicFile.exists()) { 9617 packagePath = monolithicFile.getAbsolutePath(); 9618 if (isFwdLocked()) { 9619 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9620 } else { 9621 resourcePath = packagePath; 9622 } 9623 } else { 9624 packagePath = mountFile.getAbsolutePath(); 9625 resourcePath = packagePath; 9626 } 9627 9628 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9629 } 9630 9631 int doPostInstall(int status, int uid) { 9632 if (status != PackageManager.INSTALL_SUCCEEDED) { 9633 cleanUp(); 9634 } else { 9635 final int groupOwner; 9636 final String protectedFile; 9637 if (isFwdLocked()) { 9638 groupOwner = UserHandle.getSharedAppGid(uid); 9639 protectedFile = RES_FILE_NAME; 9640 } else { 9641 groupOwner = -1; 9642 protectedFile = null; 9643 } 9644 9645 if (uid < Process.FIRST_APPLICATION_UID 9646 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9647 Slog.e(TAG, "Failed to finalize " + cid); 9648 PackageHelper.destroySdDir(cid); 9649 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9650 } 9651 9652 boolean mounted = PackageHelper.isContainerMounted(cid); 9653 if (!mounted) { 9654 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9655 } 9656 } 9657 return status; 9658 } 9659 9660 private void cleanUp() { 9661 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9662 9663 // Destroy secure container 9664 PackageHelper.destroySdDir(cid); 9665 } 9666 9667 private List<String> getAllCodePaths() { 9668 final File codeFile = new File(getCodePath()); 9669 if (codeFile != null && codeFile.exists()) { 9670 try { 9671 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9672 return pkg.getAllCodePaths(); 9673 } catch (PackageParserException e) { 9674 // Ignored; we tried our best 9675 } 9676 } 9677 return Collections.EMPTY_LIST; 9678 } 9679 9680 void cleanUpResourcesLI() { 9681 // Enumerate all code paths before deleting 9682 cleanUpResourcesLI(getAllCodePaths()); 9683 } 9684 9685 private void cleanUpResourcesLI(List<String> allCodePaths) { 9686 cleanUp(); 9687 9688 if (!allCodePaths.isEmpty()) { 9689 if (instructionSets == null) { 9690 throw new IllegalStateException("instructionSet == null"); 9691 } 9692 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9693 for (String codePath : allCodePaths) { 9694 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9695 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9696 if (retCode < 0) { 9697 Slog.w(TAG, "Couldn't remove dex file for package: " 9698 + " at location " + codePath + ", retcode=" + retCode); 9699 // we don't consider this to be a failure of the core package deletion 9700 } 9701 } 9702 } 9703 } 9704 } 9705 9706 boolean matchContainer(String app) { 9707 if (cid.startsWith(app)) { 9708 return true; 9709 } 9710 return false; 9711 } 9712 9713 String getPackageName() { 9714 return getAsecPackageName(cid); 9715 } 9716 9717 boolean doPostDeleteLI(boolean delete) { 9718 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9719 final List<String> allCodePaths = getAllCodePaths(); 9720 boolean mounted = PackageHelper.isContainerMounted(cid); 9721 if (mounted) { 9722 // Unmount first 9723 if (PackageHelper.unMountSdDir(cid)) { 9724 mounted = false; 9725 } 9726 } 9727 if (!mounted && delete) { 9728 cleanUpResourcesLI(allCodePaths); 9729 } 9730 return !mounted; 9731 } 9732 9733 @Override 9734 int doPreCopy() { 9735 if (isFwdLocked()) { 9736 if (!PackageHelper.fixSdPermissions(cid, 9737 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9738 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9739 } 9740 } 9741 9742 return PackageManager.INSTALL_SUCCEEDED; 9743 } 9744 9745 @Override 9746 int doPostCopy(int uid) { 9747 if (isFwdLocked()) { 9748 if (uid < Process.FIRST_APPLICATION_UID 9749 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9750 RES_FILE_NAME)) { 9751 Slog.e(TAG, "Failed to finalize " + cid); 9752 PackageHelper.destroySdDir(cid); 9753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9754 } 9755 } 9756 9757 return PackageManager.INSTALL_SUCCEEDED; 9758 } 9759 } 9760 9761 static String getAsecPackageName(String packageCid) { 9762 int idx = packageCid.lastIndexOf("-"); 9763 if (idx == -1) { 9764 return packageCid; 9765 } 9766 return packageCid.substring(0, idx); 9767 } 9768 9769 // Utility method used to create code paths based on package name and available index. 9770 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9771 String idxStr = ""; 9772 int idx = 1; 9773 // Fall back to default value of idx=1 if prefix is not 9774 // part of oldCodePath 9775 if (oldCodePath != null) { 9776 String subStr = oldCodePath; 9777 // Drop the suffix right away 9778 if (suffix != null && subStr.endsWith(suffix)) { 9779 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9780 } 9781 // If oldCodePath already contains prefix find out the 9782 // ending index to either increment or decrement. 9783 int sidx = subStr.lastIndexOf(prefix); 9784 if (sidx != -1) { 9785 subStr = subStr.substring(sidx + prefix.length()); 9786 if (subStr != null) { 9787 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9788 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9789 } 9790 try { 9791 idx = Integer.parseInt(subStr); 9792 if (idx <= 1) { 9793 idx++; 9794 } else { 9795 idx--; 9796 } 9797 } catch(NumberFormatException e) { 9798 } 9799 } 9800 } 9801 } 9802 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9803 return prefix + idxStr; 9804 } 9805 9806 private File getNextCodePath(String packageName) { 9807 int suffix = 1; 9808 File result; 9809 do { 9810 result = new File(mAppInstallDir, packageName + "-" + suffix); 9811 suffix++; 9812 } while (result.exists()); 9813 return result; 9814 } 9815 9816 // Utility method used to ignore ADD/REMOVE events 9817 // by directory observer. 9818 private static boolean ignoreCodePath(String fullPathStr) { 9819 String apkName = deriveCodePathName(fullPathStr); 9820 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9821 if (idx != -1 && ((idx+1) < apkName.length())) { 9822 // Make sure the package ends with a numeral 9823 String version = apkName.substring(idx+1); 9824 try { 9825 Integer.parseInt(version); 9826 return true; 9827 } catch (NumberFormatException e) {} 9828 } 9829 return false; 9830 } 9831 9832 // Utility method that returns the relative package path with respect 9833 // to the installation directory. Like say for /data/data/com.test-1.apk 9834 // string com.test-1 is returned. 9835 static String deriveCodePathName(String codePath) { 9836 if (codePath == null) { 9837 return null; 9838 } 9839 final File codeFile = new File(codePath); 9840 final String name = codeFile.getName(); 9841 if (codeFile.isDirectory()) { 9842 return name; 9843 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9844 final int lastDot = name.lastIndexOf('.'); 9845 return name.substring(0, lastDot); 9846 } else { 9847 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9848 return null; 9849 } 9850 } 9851 9852 class PackageInstalledInfo { 9853 String name; 9854 int uid; 9855 // The set of users that originally had this package installed. 9856 int[] origUsers; 9857 // The set of users that now have this package installed. 9858 int[] newUsers; 9859 PackageParser.Package pkg; 9860 int returnCode; 9861 String returnMsg; 9862 PackageRemovedInfo removedInfo; 9863 9864 public void setError(int code, String msg) { 9865 returnCode = code; 9866 returnMsg = msg; 9867 Slog.w(TAG, msg); 9868 } 9869 9870 public void setError(String msg, PackageParserException e) { 9871 returnCode = e.error; 9872 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9873 Slog.w(TAG, msg, e); 9874 } 9875 9876 public void setError(String msg, PackageManagerException e) { 9877 returnCode = e.error; 9878 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9879 Slog.w(TAG, msg, e); 9880 } 9881 9882 // In some error cases we want to convey more info back to the observer 9883 String origPackage; 9884 String origPermission; 9885 } 9886 9887 /* 9888 * Install a non-existing package. 9889 */ 9890 private void installNewPackageLI(PackageParser.Package pkg, 9891 int parseFlags, int scanFlags, UserHandle user, 9892 String installerPackageName, PackageInstalledInfo res) { 9893 // Remember this for later, in case we need to rollback this install 9894 String pkgName = pkg.packageName; 9895 9896 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9897 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9898 synchronized(mPackages) { 9899 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9900 // A package with the same name is already installed, though 9901 // it has been renamed to an older name. The package we 9902 // are trying to install should be installed as an update to 9903 // the existing one, but that has not been requested, so bail. 9904 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9905 + " without first uninstalling package running as " 9906 + mSettings.mRenamedPackages.get(pkgName)); 9907 return; 9908 } 9909 if (mPackages.containsKey(pkgName)) { 9910 // Don't allow installation over an existing package with the same name. 9911 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9912 + " without first uninstalling."); 9913 return; 9914 } 9915 } 9916 9917 try { 9918 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9919 System.currentTimeMillis(), user); 9920 9921 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9922 // delete the partially installed application. the data directory will have to be 9923 // restored if it was already existing 9924 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9925 // remove package from internal structures. Note that we want deletePackageX to 9926 // delete the package data and cache directories that it created in 9927 // scanPackageLocked, unless those directories existed before we even tried to 9928 // install. 9929 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9930 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9931 res.removedInfo, true); 9932 } 9933 9934 } catch (PackageManagerException e) { 9935 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9936 } 9937 } 9938 9939 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9940 // Upgrade keysets are being used. Determine if new package has a superset of the 9941 // required keys. 9942 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9944 for (int i = 0; i < upgradeKeySets.length; i++) { 9945 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9946 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9947 return true; 9948 } 9949 } 9950 return false; 9951 } 9952 9953 private void replacePackageLI(PackageParser.Package pkg, 9954 int parseFlags, int scanFlags, UserHandle user, 9955 String installerPackageName, PackageInstalledInfo res) { 9956 PackageParser.Package oldPackage; 9957 String pkgName = pkg.packageName; 9958 int[] allUsers; 9959 boolean[] perUserInstalled; 9960 9961 // First find the old package info and check signatures 9962 synchronized(mPackages) { 9963 oldPackage = mPackages.get(pkgName); 9964 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9965 PackageSetting ps = mSettings.mPackages.get(pkgName); 9966 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9967 // default to original signature matching 9968 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9969 != PackageManager.SIGNATURE_MATCH) { 9970 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9971 "New package has a different signature: " + pkgName); 9972 return; 9973 } 9974 } else { 9975 if(!checkUpgradeKeySetLP(ps, pkg)) { 9976 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9977 "New package not signed by keys specified by upgrade-keysets: " 9978 + pkgName); 9979 return; 9980 } 9981 } 9982 9983 // In case of rollback, remember per-user/profile install state 9984 allUsers = sUserManager.getUserIds(); 9985 perUserInstalled = new boolean[allUsers.length]; 9986 for (int i = 0; i < allUsers.length; i++) { 9987 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9988 } 9989 } 9990 9991 boolean sysPkg = (isSystemApp(oldPackage)); 9992 if (sysPkg) { 9993 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9994 user, allUsers, perUserInstalled, installerPackageName, res); 9995 } else { 9996 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9997 user, allUsers, perUserInstalled, installerPackageName, res); 9998 } 9999 } 10000 10001 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10002 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10003 int[] allUsers, boolean[] perUserInstalled, 10004 String installerPackageName, PackageInstalledInfo res) { 10005 String pkgName = deletedPackage.packageName; 10006 boolean deletedPkg = true; 10007 boolean updatedSettings = false; 10008 10009 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10010 + deletedPackage); 10011 long origUpdateTime; 10012 if (pkg.mExtras != null) { 10013 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10014 } else { 10015 origUpdateTime = 0; 10016 } 10017 10018 // First delete the existing package while retaining the data directory 10019 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10020 res.removedInfo, true)) { 10021 // If the existing package wasn't successfully deleted 10022 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10023 deletedPkg = false; 10024 } else { 10025 // Successfully deleted the old package; proceed with replace. 10026 10027 // If deleted package lived in a container, give users a chance to 10028 // relinquish resources before killing. 10029 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10030 if (DEBUG_INSTALL) { 10031 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10032 } 10033 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10034 final ArrayList<String> pkgList = new ArrayList<String>(1); 10035 pkgList.add(deletedPackage.applicationInfo.packageName); 10036 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10037 } 10038 10039 deleteCodeCacheDirsLI(pkgName); 10040 try { 10041 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10042 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10043 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10044 updatedSettings = true; 10045 } catch (PackageManagerException e) { 10046 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10047 } 10048 } 10049 10050 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10051 // remove package from internal structures. Note that we want deletePackageX to 10052 // delete the package data and cache directories that it created in 10053 // scanPackageLocked, unless those directories existed before we even tried to 10054 // install. 10055 if(updatedSettings) { 10056 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10057 deletePackageLI( 10058 pkgName, null, true, allUsers, perUserInstalled, 10059 PackageManager.DELETE_KEEP_DATA, 10060 res.removedInfo, true); 10061 } 10062 // Since we failed to install the new package we need to restore the old 10063 // package that we deleted. 10064 if (deletedPkg) { 10065 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10066 File restoreFile = new File(deletedPackage.codePath); 10067 // Parse old package 10068 boolean oldOnSd = isExternal(deletedPackage); 10069 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10070 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10071 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10072 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10073 try { 10074 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10075 } catch (PackageManagerException e) { 10076 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10077 + e.getMessage()); 10078 return; 10079 } 10080 // Restore of old package succeeded. Update permissions. 10081 // writer 10082 synchronized (mPackages) { 10083 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10084 UPDATE_PERMISSIONS_ALL); 10085 // can downgrade to reader 10086 mSettings.writeLPr(); 10087 } 10088 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10089 } 10090 } 10091 } 10092 10093 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10094 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10095 int[] allUsers, boolean[] perUserInstalled, 10096 String installerPackageName, PackageInstalledInfo res) { 10097 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10098 + ", old=" + deletedPackage); 10099 boolean disabledSystem = false; 10100 boolean updatedSettings = false; 10101 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10102 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10103 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10104 } 10105 String packageName = deletedPackage.packageName; 10106 if (packageName == null) { 10107 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10108 "Attempt to delete null packageName."); 10109 return; 10110 } 10111 PackageParser.Package oldPkg; 10112 PackageSetting oldPkgSetting; 10113 // reader 10114 synchronized (mPackages) { 10115 oldPkg = mPackages.get(packageName); 10116 oldPkgSetting = mSettings.mPackages.get(packageName); 10117 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10118 (oldPkgSetting == null)) { 10119 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10120 "Couldn't find package:" + packageName + " information"); 10121 return; 10122 } 10123 } 10124 10125 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10126 10127 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10128 res.removedInfo.removedPackage = packageName; 10129 // Remove existing system package 10130 removePackageLI(oldPkgSetting, true); 10131 // writer 10132 synchronized (mPackages) { 10133 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10134 if (!disabledSystem && deletedPackage != null) { 10135 // We didn't need to disable the .apk as a current system package, 10136 // which means we are replacing another update that is already 10137 // installed. We need to make sure to delete the older one's .apk. 10138 res.removedInfo.args = createInstallArgsForExisting(0, 10139 deletedPackage.applicationInfo.getCodePath(), 10140 deletedPackage.applicationInfo.getResourcePath(), 10141 deletedPackage.applicationInfo.nativeLibraryRootDir, 10142 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10143 } else { 10144 res.removedInfo.args = null; 10145 } 10146 } 10147 10148 // Successfully disabled the old package. Now proceed with re-installation 10149 deleteCodeCacheDirsLI(packageName); 10150 10151 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10152 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10153 10154 PackageParser.Package newPackage = null; 10155 try { 10156 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10157 if (newPackage.mExtras != null) { 10158 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10159 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10160 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10161 10162 // is the update attempting to change shared user? that isn't going to work... 10163 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10164 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10165 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10166 + " to " + newPkgSetting.sharedUser); 10167 updatedSettings = true; 10168 } 10169 } 10170 10171 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10172 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10173 updatedSettings = true; 10174 } 10175 10176 } catch (PackageManagerException e) { 10177 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10178 } 10179 10180 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10181 // Re installation failed. Restore old information 10182 // Remove new pkg information 10183 if (newPackage != null) { 10184 removeInstalledPackageLI(newPackage, true); 10185 } 10186 // Add back the old system package 10187 try { 10188 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10189 } catch (PackageManagerException e) { 10190 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10191 } 10192 // Restore the old system information in Settings 10193 synchronized (mPackages) { 10194 if (disabledSystem) { 10195 mSettings.enableSystemPackageLPw(packageName); 10196 } 10197 if (updatedSettings) { 10198 mSettings.setInstallerPackageName(packageName, 10199 oldPkgSetting.installerPackageName); 10200 } 10201 mSettings.writeLPr(); 10202 } 10203 } 10204 } 10205 10206 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10207 int[] allUsers, boolean[] perUserInstalled, 10208 PackageInstalledInfo res) { 10209 String pkgName = newPackage.packageName; 10210 synchronized (mPackages) { 10211 //write settings. the installStatus will be incomplete at this stage. 10212 //note that the new package setting would have already been 10213 //added to mPackages. It hasn't been persisted yet. 10214 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10215 mSettings.writeLPr(); 10216 } 10217 10218 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10219 10220 synchronized (mPackages) { 10221 updatePermissionsLPw(newPackage.packageName, newPackage, 10222 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10223 ? UPDATE_PERMISSIONS_ALL : 0)); 10224 // For system-bundled packages, we assume that installing an upgraded version 10225 // of the package implies that the user actually wants to run that new code, 10226 // so we enable the package. 10227 if (isSystemApp(newPackage)) { 10228 // NB: implicit assumption that system package upgrades apply to all users 10229 if (DEBUG_INSTALL) { 10230 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10231 } 10232 PackageSetting ps = mSettings.mPackages.get(pkgName); 10233 if (ps != null) { 10234 if (res.origUsers != null) { 10235 for (int userHandle : res.origUsers) { 10236 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10237 userHandle, installerPackageName); 10238 } 10239 } 10240 // Also convey the prior install/uninstall state 10241 if (allUsers != null && perUserInstalled != null) { 10242 for (int i = 0; i < allUsers.length; i++) { 10243 if (DEBUG_INSTALL) { 10244 Slog.d(TAG, " user " + allUsers[i] 10245 + " => " + perUserInstalled[i]); 10246 } 10247 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10248 } 10249 // these install state changes will be persisted in the 10250 // upcoming call to mSettings.writeLPr(). 10251 } 10252 } 10253 } 10254 res.name = pkgName; 10255 res.uid = newPackage.applicationInfo.uid; 10256 res.pkg = newPackage; 10257 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10258 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10259 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10260 //to update install status 10261 mSettings.writeLPr(); 10262 } 10263 } 10264 10265 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10266 final int installFlags = args.installFlags; 10267 String installerPackageName = args.installerPackageName; 10268 File tmpPackageFile = new File(args.getCodePath()); 10269 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10270 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10271 boolean replace = false; 10272 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10273 // Result object to be returned 10274 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10275 10276 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10277 // Retrieve PackageSettings and parse package 10278 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10279 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10280 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10281 PackageParser pp = new PackageParser(); 10282 pp.setSeparateProcesses(mSeparateProcesses); 10283 pp.setDisplayMetrics(mMetrics); 10284 10285 final PackageParser.Package pkg; 10286 try { 10287 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10288 } catch (PackageParserException e) { 10289 res.setError("Failed parse during installPackageLI", e); 10290 return; 10291 } 10292 10293 // Mark that we have an install time CPU ABI override. 10294 pkg.cpuAbiOverride = args.abiOverride; 10295 10296 String pkgName = res.name = pkg.packageName; 10297 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10298 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10299 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10300 return; 10301 } 10302 } 10303 10304 try { 10305 pp.collectCertificates(pkg, parseFlags); 10306 pp.collectManifestDigest(pkg); 10307 } catch (PackageParserException e) { 10308 res.setError("Failed collect during installPackageLI", e); 10309 return; 10310 } 10311 10312 /* If the installer passed in a manifest digest, compare it now. */ 10313 if (args.manifestDigest != null) { 10314 if (DEBUG_INSTALL) { 10315 final String parsedManifest = pkg.manifestDigest == null ? "null" 10316 : pkg.manifestDigest.toString(); 10317 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10318 + parsedManifest); 10319 } 10320 10321 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10322 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10323 return; 10324 } 10325 } else if (DEBUG_INSTALL) { 10326 final String parsedManifest = pkg.manifestDigest == null 10327 ? "null" : pkg.manifestDigest.toString(); 10328 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10329 } 10330 10331 // Get rid of all references to package scan path via parser. 10332 pp = null; 10333 String oldCodePath = null; 10334 boolean systemApp = false; 10335 synchronized (mPackages) { 10336 // Check whether the newly-scanned package wants to define an already-defined perm 10337 int N = pkg.permissions.size(); 10338 for (int i = N-1; i >= 0; i--) { 10339 PackageParser.Permission perm = pkg.permissions.get(i); 10340 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10341 if (bp != null) { 10342 // If the defining package is signed with our cert, it's okay. This 10343 // also includes the "updating the same package" case, of course. 10344 // "updating same package" could also involve key-rotation. 10345 final boolean sigsOk; 10346 if (!bp.sourcePackage.equals(pkg.packageName) 10347 || !(bp.packageSetting instanceof PackageSetting) 10348 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10349 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10350 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10351 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10352 } else { 10353 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10354 } 10355 if (!sigsOk) { 10356 // If the owning package is the system itself, we log but allow 10357 // install to proceed; we fail the install on all other permission 10358 // redefinitions. 10359 if (!bp.sourcePackage.equals("android")) { 10360 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10361 + pkg.packageName + " attempting to redeclare permission " 10362 + perm.info.name + " already owned by " + bp.sourcePackage); 10363 res.origPermission = perm.info.name; 10364 res.origPackage = bp.sourcePackage; 10365 return; 10366 } else { 10367 Slog.w(TAG, "Package " + pkg.packageName 10368 + " attempting to redeclare system permission " 10369 + perm.info.name + "; ignoring new declaration"); 10370 pkg.permissions.remove(i); 10371 } 10372 } 10373 } 10374 } 10375 10376 // Check if installing already existing package 10377 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10378 String oldName = mSettings.mRenamedPackages.get(pkgName); 10379 if (pkg.mOriginalPackages != null 10380 && pkg.mOriginalPackages.contains(oldName) 10381 && mPackages.containsKey(oldName)) { 10382 // This package is derived from an original package, 10383 // and this device has been updating from that original 10384 // name. We must continue using the original name, so 10385 // rename the new package here. 10386 pkg.setPackageName(oldName); 10387 pkgName = pkg.packageName; 10388 replace = true; 10389 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10390 + oldName + " pkgName=" + pkgName); 10391 } else if (mPackages.containsKey(pkgName)) { 10392 // This package, under its official name, already exists 10393 // on the device; we should replace it. 10394 replace = true; 10395 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10396 } 10397 } 10398 PackageSetting ps = mSettings.mPackages.get(pkgName); 10399 if (ps != null) { 10400 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10401 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10402 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10403 systemApp = (ps.pkg.applicationInfo.flags & 10404 ApplicationInfo.FLAG_SYSTEM) != 0; 10405 } 10406 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10407 } 10408 } 10409 10410 if (systemApp && onSd) { 10411 // Disable updates to system apps on sdcard 10412 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10413 "Cannot install updates to system apps on sdcard"); 10414 return; 10415 } 10416 10417 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10418 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10419 return; 10420 } 10421 10422 if (replace) { 10423 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10424 installerPackageName, res); 10425 } else { 10426 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10427 args.user, installerPackageName, res); 10428 } 10429 synchronized (mPackages) { 10430 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10431 if (ps != null) { 10432 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10433 } 10434 } 10435 } 10436 10437 private static boolean isForwardLocked(PackageParser.Package pkg) { 10438 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10439 } 10440 10441 private static boolean isForwardLocked(ApplicationInfo info) { 10442 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10443 } 10444 10445 private boolean isForwardLocked(PackageSetting ps) { 10446 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10447 } 10448 10449 private static boolean isMultiArch(PackageSetting ps) { 10450 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10451 } 10452 10453 private static boolean isMultiArch(ApplicationInfo info) { 10454 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10455 } 10456 10457 private static boolean isExternal(PackageParser.Package pkg) { 10458 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10459 } 10460 10461 private static boolean isExternal(PackageSetting ps) { 10462 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10463 } 10464 10465 private static boolean isExternal(ApplicationInfo info) { 10466 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10467 } 10468 10469 private static boolean isSystemApp(PackageParser.Package pkg) { 10470 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10471 } 10472 10473 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10474 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10475 } 10476 10477 private static boolean isSystemApp(ApplicationInfo info) { 10478 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10479 } 10480 10481 private static boolean isSystemApp(PackageSetting ps) { 10482 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10483 } 10484 10485 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10486 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10487 } 10488 10489 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10490 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10491 } 10492 10493 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10494 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10495 } 10496 10497 private int packageFlagsToInstallFlags(PackageSetting ps) { 10498 int installFlags = 0; 10499 if (isExternal(ps)) { 10500 installFlags |= PackageManager.INSTALL_EXTERNAL; 10501 } 10502 if (isForwardLocked(ps)) { 10503 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10504 } 10505 return installFlags; 10506 } 10507 10508 private void deleteTempPackageFiles() { 10509 final FilenameFilter filter = new FilenameFilter() { 10510 public boolean accept(File dir, String name) { 10511 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10512 } 10513 }; 10514 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10515 file.delete(); 10516 } 10517 } 10518 10519 @Override 10520 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10521 int flags) { 10522 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10523 flags); 10524 } 10525 10526 @Override 10527 public void deletePackage(final String packageName, 10528 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10529 mContext.enforceCallingOrSelfPermission( 10530 android.Manifest.permission.DELETE_PACKAGES, null); 10531 final int uid = Binder.getCallingUid(); 10532 if (UserHandle.getUserId(uid) != userId) { 10533 mContext.enforceCallingPermission( 10534 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10535 "deletePackage for user " + userId); 10536 } 10537 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10538 try { 10539 observer.onPackageDeleted(packageName, 10540 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10541 } catch (RemoteException re) { 10542 } 10543 return; 10544 } 10545 10546 boolean uninstallBlocked = false; 10547 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10548 int[] users = sUserManager.getUserIds(); 10549 for (int i = 0; i < users.length; ++i) { 10550 if (getBlockUninstallForUser(packageName, users[i])) { 10551 uninstallBlocked = true; 10552 break; 10553 } 10554 } 10555 } else { 10556 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10557 } 10558 if (uninstallBlocked) { 10559 try { 10560 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10561 null); 10562 } catch (RemoteException re) { 10563 } 10564 return; 10565 } 10566 10567 if (DEBUG_REMOVE) { 10568 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10569 } 10570 // Queue up an async operation since the package deletion may take a little while. 10571 mHandler.post(new Runnable() { 10572 public void run() { 10573 mHandler.removeCallbacks(this); 10574 final int returnCode = deletePackageX(packageName, userId, flags); 10575 if (observer != null) { 10576 try { 10577 observer.onPackageDeleted(packageName, returnCode, null); 10578 } catch (RemoteException e) { 10579 Log.i(TAG, "Observer no longer exists."); 10580 } //end catch 10581 } //end if 10582 } //end run 10583 }); 10584 } 10585 10586 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10587 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10588 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10589 try { 10590 if (dpm != null) { 10591 if (dpm.isDeviceOwner(packageName)) { 10592 return true; 10593 } 10594 int[] users; 10595 if (userId == UserHandle.USER_ALL) { 10596 users = sUserManager.getUserIds(); 10597 } else { 10598 users = new int[]{userId}; 10599 } 10600 for (int i = 0; i < users.length; ++i) { 10601 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10602 return true; 10603 } 10604 } 10605 } 10606 } catch (RemoteException e) { 10607 } 10608 return false; 10609 } 10610 10611 /** 10612 * This method is an internal method that could be get invoked either 10613 * to delete an installed package or to clean up a failed installation. 10614 * After deleting an installed package, a broadcast is sent to notify any 10615 * listeners that the package has been installed. For cleaning up a failed 10616 * installation, the broadcast is not necessary since the package's 10617 * installation wouldn't have sent the initial broadcast either 10618 * The key steps in deleting a package are 10619 * deleting the package information in internal structures like mPackages, 10620 * deleting the packages base directories through installd 10621 * updating mSettings to reflect current status 10622 * persisting settings for later use 10623 * sending a broadcast if necessary 10624 */ 10625 private int deletePackageX(String packageName, int userId, int flags) { 10626 final PackageRemovedInfo info = new PackageRemovedInfo(); 10627 final boolean res; 10628 10629 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10630 ? UserHandle.ALL : new UserHandle(userId); 10631 10632 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10633 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10634 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10635 } 10636 10637 boolean removedForAllUsers = false; 10638 boolean systemUpdate = false; 10639 10640 // for the uninstall-updates case and restricted profiles, remember the per- 10641 // userhandle installed state 10642 int[] allUsers; 10643 boolean[] perUserInstalled; 10644 synchronized (mPackages) { 10645 PackageSetting ps = mSettings.mPackages.get(packageName); 10646 allUsers = sUserManager.getUserIds(); 10647 perUserInstalled = new boolean[allUsers.length]; 10648 for (int i = 0; i < allUsers.length; i++) { 10649 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10650 } 10651 } 10652 10653 synchronized (mInstallLock) { 10654 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10655 res = deletePackageLI(packageName, removeForUser, 10656 true, allUsers, perUserInstalled, 10657 flags | REMOVE_CHATTY, info, true); 10658 systemUpdate = info.isRemovedPackageSystemUpdate; 10659 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10660 removedForAllUsers = true; 10661 } 10662 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10663 + " removedForAllUsers=" + removedForAllUsers); 10664 } 10665 10666 if (res) { 10667 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10668 10669 // If the removed package was a system update, the old system package 10670 // was re-enabled; we need to broadcast this information 10671 if (systemUpdate) { 10672 Bundle extras = new Bundle(1); 10673 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10674 ? info.removedAppId : info.uid); 10675 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10676 10677 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10678 extras, null, null, null); 10679 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10680 extras, null, null, null); 10681 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10682 null, packageName, null, null); 10683 } 10684 } 10685 // Force a gc here. 10686 Runtime.getRuntime().gc(); 10687 // Delete the resources here after sending the broadcast to let 10688 // other processes clean up before deleting resources. 10689 if (info.args != null) { 10690 synchronized (mInstallLock) { 10691 info.args.doPostDeleteLI(true); 10692 } 10693 } 10694 10695 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10696 } 10697 10698 static class PackageRemovedInfo { 10699 String removedPackage; 10700 int uid = -1; 10701 int removedAppId = -1; 10702 int[] removedUsers = null; 10703 boolean isRemovedPackageSystemUpdate = false; 10704 // Clean up resources deleted packages. 10705 InstallArgs args = null; 10706 10707 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10708 Bundle extras = new Bundle(1); 10709 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10710 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10711 if (replacing) { 10712 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10713 } 10714 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10715 if (removedPackage != null) { 10716 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10717 extras, null, null, removedUsers); 10718 if (fullRemove && !replacing) { 10719 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10720 extras, null, null, removedUsers); 10721 } 10722 } 10723 if (removedAppId >= 0) { 10724 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10725 removedUsers); 10726 } 10727 } 10728 } 10729 10730 /* 10731 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10732 * flag is not set, the data directory is removed as well. 10733 * make sure this flag is set for partially installed apps. If not its meaningless to 10734 * delete a partially installed application. 10735 */ 10736 private void removePackageDataLI(PackageSetting ps, 10737 int[] allUserHandles, boolean[] perUserInstalled, 10738 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10739 String packageName = ps.name; 10740 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10741 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10742 // Retrieve object to delete permissions for shared user later on 10743 final PackageSetting deletedPs; 10744 // reader 10745 synchronized (mPackages) { 10746 deletedPs = mSettings.mPackages.get(packageName); 10747 if (outInfo != null) { 10748 outInfo.removedPackage = packageName; 10749 outInfo.removedUsers = deletedPs != null 10750 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10751 : null; 10752 } 10753 } 10754 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10755 removeDataDirsLI(packageName); 10756 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10757 } 10758 // writer 10759 synchronized (mPackages) { 10760 if (deletedPs != null) { 10761 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10762 if (outInfo != null) { 10763 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10764 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10765 } 10766 if (deletedPs != null) { 10767 updatePermissionsLPw(deletedPs.name, null, 0); 10768 if (deletedPs.sharedUser != null) { 10769 // remove permissions associated with package 10770 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10771 } 10772 } 10773 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10774 } 10775 // make sure to preserve per-user disabled state if this removal was just 10776 // a downgrade of a system app to the factory package 10777 if (allUserHandles != null && perUserInstalled != null) { 10778 if (DEBUG_REMOVE) { 10779 Slog.d(TAG, "Propagating install state across downgrade"); 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 } 10789 } 10790 // can downgrade to reader 10791 if (writeSettings) { 10792 // Save settings now 10793 mSettings.writeLPr(); 10794 } 10795 } 10796 if (outInfo != null) { 10797 // A user ID was deleted here. Go through all users and remove it 10798 // from KeyStore. 10799 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10800 } 10801 } 10802 10803 static boolean locationIsPrivileged(File path) { 10804 try { 10805 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10806 .getCanonicalPath(); 10807 return path.getCanonicalPath().startsWith(privilegedAppDir); 10808 } catch (IOException e) { 10809 Slog.e(TAG, "Unable to access code path " + path); 10810 } 10811 return false; 10812 } 10813 10814 /* 10815 * Tries to delete system package. 10816 */ 10817 private boolean deleteSystemPackageLI(PackageSetting newPs, 10818 int[] allUserHandles, boolean[] perUserInstalled, 10819 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10820 final boolean applyUserRestrictions 10821 = (allUserHandles != null) && (perUserInstalled != null); 10822 PackageSetting disabledPs = null; 10823 // Confirm if the system package has been updated 10824 // An updated system app can be deleted. This will also have to restore 10825 // the system pkg from system partition 10826 // reader 10827 synchronized (mPackages) { 10828 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10829 } 10830 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10831 + " disabledPs=" + disabledPs); 10832 if (disabledPs == null) { 10833 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10834 return false; 10835 } else if (DEBUG_REMOVE) { 10836 Slog.d(TAG, "Deleting system pkg from data partition"); 10837 } 10838 if (DEBUG_REMOVE) { 10839 if (applyUserRestrictions) { 10840 Slog.d(TAG, "Remembering install states:"); 10841 for (int i = 0; i < allUserHandles.length; i++) { 10842 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10843 } 10844 } 10845 } 10846 // Delete the updated package 10847 outInfo.isRemovedPackageSystemUpdate = true; 10848 if (disabledPs.versionCode < newPs.versionCode) { 10849 // Delete data for downgrades 10850 flags &= ~PackageManager.DELETE_KEEP_DATA; 10851 } else { 10852 // Preserve data by setting flag 10853 flags |= PackageManager.DELETE_KEEP_DATA; 10854 } 10855 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10856 allUserHandles, perUserInstalled, outInfo, writeSettings); 10857 if (!ret) { 10858 return false; 10859 } 10860 // writer 10861 synchronized (mPackages) { 10862 // Reinstate the old system package 10863 mSettings.enableSystemPackageLPw(newPs.name); 10864 // Remove any native libraries from the upgraded package. 10865 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10866 } 10867 // Install the system package 10868 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10869 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10870 if (locationIsPrivileged(disabledPs.codePath)) { 10871 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10872 } 10873 10874 final PackageParser.Package newPkg; 10875 try { 10876 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10877 } catch (PackageManagerException e) { 10878 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10879 return false; 10880 } 10881 10882 // writer 10883 synchronized (mPackages) { 10884 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10885 updatePermissionsLPw(newPkg.packageName, newPkg, 10886 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10887 if (applyUserRestrictions) { 10888 if (DEBUG_REMOVE) { 10889 Slog.d(TAG, "Propagating install state across reinstall"); 10890 } 10891 for (int i = 0; i < allUserHandles.length; i++) { 10892 if (DEBUG_REMOVE) { 10893 Slog.d(TAG, " user " + allUserHandles[i] 10894 + " => " + perUserInstalled[i]); 10895 } 10896 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10897 } 10898 // Regardless of writeSettings we need to ensure that this restriction 10899 // state propagation is persisted 10900 mSettings.writeAllUsersPackageRestrictionsLPr(); 10901 } 10902 // can downgrade to reader here 10903 if (writeSettings) { 10904 mSettings.writeLPr(); 10905 } 10906 } 10907 return true; 10908 } 10909 10910 private boolean deleteInstalledPackageLI(PackageSetting ps, 10911 boolean deleteCodeAndResources, int flags, 10912 int[] allUserHandles, boolean[] perUserInstalled, 10913 PackageRemovedInfo outInfo, boolean writeSettings) { 10914 if (outInfo != null) { 10915 outInfo.uid = ps.appId; 10916 } 10917 10918 // Delete package data from internal structures and also remove data if flag is set 10919 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10920 10921 // Delete application code and resources 10922 if (deleteCodeAndResources && (outInfo != null)) { 10923 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10924 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10925 getAppDexInstructionSets(ps)); 10926 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10927 } 10928 return true; 10929 } 10930 10931 @Override 10932 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10933 int userId) { 10934 mContext.enforceCallingOrSelfPermission( 10935 android.Manifest.permission.DELETE_PACKAGES, null); 10936 synchronized (mPackages) { 10937 PackageSetting ps = mSettings.mPackages.get(packageName); 10938 if (ps == null) { 10939 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10940 return false; 10941 } 10942 if (!ps.getInstalled(userId)) { 10943 // Can't block uninstall for an app that is not installed or enabled. 10944 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10945 return false; 10946 } 10947 ps.setBlockUninstall(blockUninstall, userId); 10948 mSettings.writePackageRestrictionsLPr(userId); 10949 } 10950 return true; 10951 } 10952 10953 @Override 10954 public boolean getBlockUninstallForUser(String packageName, int userId) { 10955 synchronized (mPackages) { 10956 PackageSetting ps = mSettings.mPackages.get(packageName); 10957 if (ps == null) { 10958 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10959 return false; 10960 } 10961 return ps.getBlockUninstall(userId); 10962 } 10963 } 10964 10965 /* 10966 * This method handles package deletion in general 10967 */ 10968 private boolean deletePackageLI(String packageName, UserHandle user, 10969 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10970 int flags, PackageRemovedInfo outInfo, 10971 boolean writeSettings) { 10972 if (packageName == null) { 10973 Slog.w(TAG, "Attempt to delete null packageName."); 10974 return false; 10975 } 10976 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10977 PackageSetting ps; 10978 boolean dataOnly = false; 10979 int removeUser = -1; 10980 int appId = -1; 10981 synchronized (mPackages) { 10982 ps = mSettings.mPackages.get(packageName); 10983 if (ps == null) { 10984 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10985 return false; 10986 } 10987 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10988 && user.getIdentifier() != UserHandle.USER_ALL) { 10989 // The caller is asking that the package only be deleted for a single 10990 // user. To do this, we just mark its uninstalled state and delete 10991 // its data. If this is a system app, we only allow this to happen if 10992 // they have set the special DELETE_SYSTEM_APP which requests different 10993 // semantics than normal for uninstalling system apps. 10994 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10995 ps.setUserState(user.getIdentifier(), 10996 COMPONENT_ENABLED_STATE_DEFAULT, 10997 false, //installed 10998 true, //stopped 10999 true, //notLaunched 11000 false, //hidden 11001 null, null, null, 11002 false // blockUninstall 11003 ); 11004 if (!isSystemApp(ps)) { 11005 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11006 // Other user still have this package installed, so all 11007 // we need to do is clear this user's data and save that 11008 // it is uninstalled. 11009 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11010 removeUser = user.getIdentifier(); 11011 appId = ps.appId; 11012 mSettings.writePackageRestrictionsLPr(removeUser); 11013 } else { 11014 // We need to set it back to 'installed' so the uninstall 11015 // broadcasts will be sent correctly. 11016 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11017 ps.setInstalled(true, user.getIdentifier()); 11018 } 11019 } else { 11020 // This is a system app, so we assume that the 11021 // other users still have this package installed, so all 11022 // we need to do is clear this user's data and save that 11023 // it is uninstalled. 11024 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11025 removeUser = user.getIdentifier(); 11026 appId = ps.appId; 11027 mSettings.writePackageRestrictionsLPr(removeUser); 11028 } 11029 } 11030 } 11031 11032 if (removeUser >= 0) { 11033 // From above, we determined that we are deleting this only 11034 // for a single user. Continue the work here. 11035 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11036 if (outInfo != null) { 11037 outInfo.removedPackage = packageName; 11038 outInfo.removedAppId = appId; 11039 outInfo.removedUsers = new int[] {removeUser}; 11040 } 11041 mInstaller.clearUserData(packageName, removeUser); 11042 removeKeystoreDataIfNeeded(removeUser, appId); 11043 schedulePackageCleaning(packageName, removeUser, false); 11044 return true; 11045 } 11046 11047 if (dataOnly) { 11048 // Delete application data first 11049 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11050 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11051 return true; 11052 } 11053 11054 boolean ret = false; 11055 if (isSystemApp(ps)) { 11056 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11057 // When an updated system application is deleted we delete the existing resources as well and 11058 // fall back to existing code in system partition 11059 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11060 flags, outInfo, writeSettings); 11061 } else { 11062 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11063 // Kill application pre-emptively especially for apps on sd. 11064 killApplication(packageName, ps.appId, "uninstall pkg"); 11065 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11066 allUserHandles, perUserInstalled, 11067 outInfo, writeSettings); 11068 } 11069 11070 return ret; 11071 } 11072 11073 private final class ClearStorageConnection implements ServiceConnection { 11074 IMediaContainerService mContainerService; 11075 11076 @Override 11077 public void onServiceConnected(ComponentName name, IBinder service) { 11078 synchronized (this) { 11079 mContainerService = IMediaContainerService.Stub.asInterface(service); 11080 notifyAll(); 11081 } 11082 } 11083 11084 @Override 11085 public void onServiceDisconnected(ComponentName name) { 11086 } 11087 } 11088 11089 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11090 final boolean mounted; 11091 if (Environment.isExternalStorageEmulated()) { 11092 mounted = true; 11093 } else { 11094 final String status = Environment.getExternalStorageState(); 11095 11096 mounted = status.equals(Environment.MEDIA_MOUNTED) 11097 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11098 } 11099 11100 if (!mounted) { 11101 return; 11102 } 11103 11104 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11105 int[] users; 11106 if (userId == UserHandle.USER_ALL) { 11107 users = sUserManager.getUserIds(); 11108 } else { 11109 users = new int[] { userId }; 11110 } 11111 final ClearStorageConnection conn = new ClearStorageConnection(); 11112 if (mContext.bindServiceAsUser( 11113 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11114 try { 11115 for (int curUser : users) { 11116 long timeout = SystemClock.uptimeMillis() + 5000; 11117 synchronized (conn) { 11118 long now = SystemClock.uptimeMillis(); 11119 while (conn.mContainerService == null && now < timeout) { 11120 try { 11121 conn.wait(timeout - now); 11122 } catch (InterruptedException e) { 11123 } 11124 } 11125 } 11126 if (conn.mContainerService == null) { 11127 return; 11128 } 11129 11130 final UserEnvironment userEnv = new UserEnvironment(curUser); 11131 clearDirectory(conn.mContainerService, 11132 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11133 if (allData) { 11134 clearDirectory(conn.mContainerService, 11135 userEnv.buildExternalStorageAppDataDirs(packageName)); 11136 clearDirectory(conn.mContainerService, 11137 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11138 } 11139 } 11140 } finally { 11141 mContext.unbindService(conn); 11142 } 11143 } 11144 } 11145 11146 @Override 11147 public void clearApplicationUserData(final String packageName, 11148 final IPackageDataObserver observer, final int userId) { 11149 mContext.enforceCallingOrSelfPermission( 11150 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11151 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11152 // Queue up an async operation since the package deletion may take a little while. 11153 mHandler.post(new Runnable() { 11154 public void run() { 11155 mHandler.removeCallbacks(this); 11156 final boolean succeeded; 11157 synchronized (mInstallLock) { 11158 succeeded = clearApplicationUserDataLI(packageName, userId); 11159 } 11160 clearExternalStorageDataSync(packageName, userId, true); 11161 if (succeeded) { 11162 // invoke DeviceStorageMonitor's update method to clear any notifications 11163 DeviceStorageMonitorInternal 11164 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11165 if (dsm != null) { 11166 dsm.checkMemory(); 11167 } 11168 } 11169 if(observer != null) { 11170 try { 11171 observer.onRemoveCompleted(packageName, succeeded); 11172 } catch (RemoteException e) { 11173 Log.i(TAG, "Observer no longer exists."); 11174 } 11175 } //end if observer 11176 } //end run 11177 }); 11178 } 11179 11180 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11181 if (packageName == null) { 11182 Slog.w(TAG, "Attempt to delete null packageName."); 11183 return false; 11184 } 11185 11186 // Try finding details about the requested package 11187 PackageParser.Package pkg; 11188 synchronized (mPackages) { 11189 pkg = mPackages.get(packageName); 11190 if (pkg == null) { 11191 final PackageSetting ps = mSettings.mPackages.get(packageName); 11192 if (ps != null) { 11193 pkg = ps.pkg; 11194 } 11195 } 11196 } 11197 11198 if (pkg == null) { 11199 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11200 } 11201 11202 // Always delete data directories for package, even if we found no other 11203 // record of app. This helps users recover from UID mismatches without 11204 // resorting to a full data wipe. 11205 int retCode = mInstaller.clearUserData(packageName, userId); 11206 if (retCode < 0) { 11207 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11208 return false; 11209 } 11210 11211 if (pkg == null) { 11212 return false; 11213 } 11214 11215 if (pkg != null && pkg.applicationInfo != null) { 11216 final int appId = pkg.applicationInfo.uid; 11217 removeKeystoreDataIfNeeded(userId, appId); 11218 } 11219 11220 // Create a native library symlink only if we have native libraries 11221 // and if the native libraries are 32 bit libraries. We do not provide 11222 // this symlink for 64 bit libraries. 11223 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11224 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11225 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11226 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11227 Slog.w(TAG, "Failed linking native library dir"); 11228 return false; 11229 } 11230 } 11231 11232 return true; 11233 } 11234 11235 /** 11236 * Remove entries from the keystore daemon. Will only remove it if the 11237 * {@code appId} is valid. 11238 */ 11239 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11240 if (appId < 0) { 11241 return; 11242 } 11243 11244 final KeyStore keyStore = KeyStore.getInstance(); 11245 if (keyStore != null) { 11246 if (userId == UserHandle.USER_ALL) { 11247 for (final int individual : sUserManager.getUserIds()) { 11248 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11249 } 11250 } else { 11251 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11252 } 11253 } else { 11254 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11255 } 11256 } 11257 11258 @Override 11259 public void deleteApplicationCacheFiles(final String packageName, 11260 final IPackageDataObserver observer) { 11261 mContext.enforceCallingOrSelfPermission( 11262 android.Manifest.permission.DELETE_CACHE_FILES, null); 11263 // Queue up an async operation since the package deletion may take a little while. 11264 final int userId = UserHandle.getCallingUserId(); 11265 mHandler.post(new Runnable() { 11266 public void run() { 11267 mHandler.removeCallbacks(this); 11268 final boolean succeded; 11269 synchronized (mInstallLock) { 11270 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11271 } 11272 clearExternalStorageDataSync(packageName, userId, false); 11273 if(observer != null) { 11274 try { 11275 observer.onRemoveCompleted(packageName, succeded); 11276 } catch (RemoteException e) { 11277 Log.i(TAG, "Observer no longer exists."); 11278 } 11279 } //end if observer 11280 } //end run 11281 }); 11282 } 11283 11284 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11285 if (packageName == null) { 11286 Slog.w(TAG, "Attempt to delete null packageName."); 11287 return false; 11288 } 11289 PackageParser.Package p; 11290 synchronized (mPackages) { 11291 p = mPackages.get(packageName); 11292 } 11293 if (p == null) { 11294 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11295 return false; 11296 } 11297 final ApplicationInfo applicationInfo = p.applicationInfo; 11298 if (applicationInfo == null) { 11299 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11300 return false; 11301 } 11302 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11303 if (retCode < 0) { 11304 Slog.w(TAG, "Couldn't remove cache files for package: " 11305 + packageName + " u" + userId); 11306 return false; 11307 } 11308 return true; 11309 } 11310 11311 @Override 11312 public void getPackageSizeInfo(final String packageName, int userHandle, 11313 final IPackageStatsObserver observer) { 11314 mContext.enforceCallingOrSelfPermission( 11315 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11316 if (packageName == null) { 11317 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11318 } 11319 11320 PackageStats stats = new PackageStats(packageName, userHandle); 11321 11322 /* 11323 * Queue up an async operation since the package measurement may take a 11324 * little while. 11325 */ 11326 Message msg = mHandler.obtainMessage(INIT_COPY); 11327 msg.obj = new MeasureParams(stats, observer); 11328 mHandler.sendMessage(msg); 11329 } 11330 11331 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11332 PackageStats pStats) { 11333 if (packageName == null) { 11334 Slog.w(TAG, "Attempt to get size of null packageName."); 11335 return false; 11336 } 11337 PackageParser.Package p; 11338 boolean dataOnly = false; 11339 String libDirRoot = null; 11340 String asecPath = null; 11341 PackageSetting ps = null; 11342 synchronized (mPackages) { 11343 p = mPackages.get(packageName); 11344 ps = mSettings.mPackages.get(packageName); 11345 if(p == null) { 11346 dataOnly = true; 11347 if((ps == null) || (ps.pkg == null)) { 11348 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11349 return false; 11350 } 11351 p = ps.pkg; 11352 } 11353 if (ps != null) { 11354 libDirRoot = ps.legacyNativeLibraryPathString; 11355 } 11356 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11357 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11358 if (secureContainerId != null) { 11359 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11360 } 11361 } 11362 } 11363 String publicSrcDir = null; 11364 if(!dataOnly) { 11365 final ApplicationInfo applicationInfo = p.applicationInfo; 11366 if (applicationInfo == null) { 11367 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11368 return false; 11369 } 11370 if (isForwardLocked(p)) { 11371 publicSrcDir = applicationInfo.getBaseResourcePath(); 11372 } 11373 } 11374 // TODO: extend to measure size of split APKs 11375 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11376 // not just the first level. 11377 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11378 // just the primary. 11379 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11380 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11381 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11382 if (res < 0) { 11383 return false; 11384 } 11385 11386 // Fix-up for forward-locked applications in ASEC containers. 11387 if (!isExternal(p)) { 11388 pStats.codeSize += pStats.externalCodeSize; 11389 pStats.externalCodeSize = 0L; 11390 } 11391 11392 return true; 11393 } 11394 11395 11396 @Override 11397 public void addPackageToPreferred(String packageName) { 11398 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11399 } 11400 11401 @Override 11402 public void removePackageFromPreferred(String packageName) { 11403 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11404 } 11405 11406 @Override 11407 public List<PackageInfo> getPreferredPackages(int flags) { 11408 return new ArrayList<PackageInfo>(); 11409 } 11410 11411 private int getUidTargetSdkVersionLockedLPr(int uid) { 11412 Object obj = mSettings.getUserIdLPr(uid); 11413 if (obj instanceof SharedUserSetting) { 11414 final SharedUserSetting sus = (SharedUserSetting) obj; 11415 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11416 final Iterator<PackageSetting> it = sus.packages.iterator(); 11417 while (it.hasNext()) { 11418 final PackageSetting ps = it.next(); 11419 if (ps.pkg != null) { 11420 int v = ps.pkg.applicationInfo.targetSdkVersion; 11421 if (v < vers) vers = v; 11422 } 11423 } 11424 return vers; 11425 } else if (obj instanceof PackageSetting) { 11426 final PackageSetting ps = (PackageSetting) obj; 11427 if (ps.pkg != null) { 11428 return ps.pkg.applicationInfo.targetSdkVersion; 11429 } 11430 } 11431 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11432 } 11433 11434 @Override 11435 public void addPreferredActivity(IntentFilter filter, int match, 11436 ComponentName[] set, ComponentName activity, int userId) { 11437 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11438 "Adding preferred"); 11439 } 11440 11441 private void addPreferredActivityInternal(IntentFilter filter, int match, 11442 ComponentName[] set, ComponentName activity, boolean always, int userId, 11443 String opname) { 11444 // writer 11445 int callingUid = Binder.getCallingUid(); 11446 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11447 if (filter.countActions() == 0) { 11448 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11449 return; 11450 } 11451 synchronized (mPackages) { 11452 if (mContext.checkCallingOrSelfPermission( 11453 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11454 != PackageManager.PERMISSION_GRANTED) { 11455 if (getUidTargetSdkVersionLockedLPr(callingUid) 11456 < Build.VERSION_CODES.FROYO) { 11457 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11458 + callingUid); 11459 return; 11460 } 11461 mContext.enforceCallingOrSelfPermission( 11462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11463 } 11464 11465 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11466 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11467 + userId + ":"); 11468 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11469 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11470 mSettings.writePackageRestrictionsLPr(userId); 11471 } 11472 } 11473 11474 @Override 11475 public void replacePreferredActivity(IntentFilter filter, int match, 11476 ComponentName[] set, ComponentName activity, int userId) { 11477 if (filter.countActions() != 1) { 11478 throw new IllegalArgumentException( 11479 "replacePreferredActivity expects filter to have only 1 action."); 11480 } 11481 if (filter.countDataAuthorities() != 0 11482 || filter.countDataPaths() != 0 11483 || filter.countDataSchemes() > 1 11484 || filter.countDataTypes() != 0) { 11485 throw new IllegalArgumentException( 11486 "replacePreferredActivity expects filter to have no data authorities, " + 11487 "paths, or types; and at most one scheme."); 11488 } 11489 11490 final int callingUid = Binder.getCallingUid(); 11491 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11492 synchronized (mPackages) { 11493 if (mContext.checkCallingOrSelfPermission( 11494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11495 != PackageManager.PERMISSION_GRANTED) { 11496 if (getUidTargetSdkVersionLockedLPr(callingUid) 11497 < Build.VERSION_CODES.FROYO) { 11498 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11499 + Binder.getCallingUid()); 11500 return; 11501 } 11502 mContext.enforceCallingOrSelfPermission( 11503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11504 } 11505 11506 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11507 if (pir != null) { 11508 // Get all of the existing entries that exactly match this filter. 11509 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11510 if (existing != null && existing.size() == 1) { 11511 PreferredActivity cur = existing.get(0); 11512 if (DEBUG_PREFERRED) { 11513 Slog.i(TAG, "Checking replace of preferred:"); 11514 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11515 if (!cur.mPref.mAlways) { 11516 Slog.i(TAG, " -- CUR; not mAlways!"); 11517 } else { 11518 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11519 Slog.i(TAG, " -- CUR: mSet=" 11520 + Arrays.toString(cur.mPref.mSetComponents)); 11521 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11522 Slog.i(TAG, " -- NEW: mMatch=" 11523 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11524 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11525 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11526 } 11527 } 11528 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11529 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11530 && cur.mPref.sameSet(set)) { 11531 // Setting the preferred activity to what it happens to be already 11532 if (DEBUG_PREFERRED) { 11533 Slog.i(TAG, "Replacing with same preferred activity " 11534 + cur.mPref.mShortComponent + " for user " 11535 + userId + ":"); 11536 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11537 } 11538 return; 11539 } 11540 } 11541 11542 if (existing != null) { 11543 if (DEBUG_PREFERRED) { 11544 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11546 } 11547 for (int i = 0; i < existing.size(); i++) { 11548 PreferredActivity pa = existing.get(i); 11549 if (DEBUG_PREFERRED) { 11550 Slog.i(TAG, "Removing existing preferred activity " 11551 + pa.mPref.mComponent + ":"); 11552 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11553 } 11554 pir.removeFilter(pa); 11555 } 11556 } 11557 } 11558 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11559 "Replacing preferred"); 11560 } 11561 } 11562 11563 @Override 11564 public void clearPackagePreferredActivities(String packageName) { 11565 final int uid = Binder.getCallingUid(); 11566 // writer 11567 synchronized (mPackages) { 11568 PackageParser.Package pkg = mPackages.get(packageName); 11569 if (pkg == null || pkg.applicationInfo.uid != uid) { 11570 if (mContext.checkCallingOrSelfPermission( 11571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11572 != PackageManager.PERMISSION_GRANTED) { 11573 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11574 < Build.VERSION_CODES.FROYO) { 11575 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11576 + Binder.getCallingUid()); 11577 return; 11578 } 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11581 } 11582 } 11583 11584 int user = UserHandle.getCallingUserId(); 11585 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11586 mSettings.writePackageRestrictionsLPr(user); 11587 scheduleWriteSettingsLocked(); 11588 } 11589 } 11590 } 11591 11592 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11593 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11594 ArrayList<PreferredActivity> removed = null; 11595 boolean changed = false; 11596 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11597 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11598 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11599 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11600 continue; 11601 } 11602 Iterator<PreferredActivity> it = pir.filterIterator(); 11603 while (it.hasNext()) { 11604 PreferredActivity pa = it.next(); 11605 // Mark entry for removal only if it matches the package name 11606 // and the entry is of type "always". 11607 if (packageName == null || 11608 (pa.mPref.mComponent.getPackageName().equals(packageName) 11609 && pa.mPref.mAlways)) { 11610 if (removed == null) { 11611 removed = new ArrayList<PreferredActivity>(); 11612 } 11613 removed.add(pa); 11614 } 11615 } 11616 if (removed != null) { 11617 for (int j=0; j<removed.size(); j++) { 11618 PreferredActivity pa = removed.get(j); 11619 pir.removeFilter(pa); 11620 } 11621 changed = true; 11622 } 11623 } 11624 return changed; 11625 } 11626 11627 @Override 11628 public void resetPreferredActivities(int userId) { 11629 /* TODO: Actually use userId. Why is it being passed in? */ 11630 mContext.enforceCallingOrSelfPermission( 11631 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11632 // writer 11633 synchronized (mPackages) { 11634 int user = UserHandle.getCallingUserId(); 11635 clearPackagePreferredActivitiesLPw(null, user); 11636 mSettings.readDefaultPreferredAppsLPw(this, user); 11637 mSettings.writePackageRestrictionsLPr(user); 11638 scheduleWriteSettingsLocked(); 11639 } 11640 } 11641 11642 @Override 11643 public int getPreferredActivities(List<IntentFilter> outFilters, 11644 List<ComponentName> outActivities, String packageName) { 11645 11646 int num = 0; 11647 final int userId = UserHandle.getCallingUserId(); 11648 // reader 11649 synchronized (mPackages) { 11650 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11651 if (pir != null) { 11652 final Iterator<PreferredActivity> it = pir.filterIterator(); 11653 while (it.hasNext()) { 11654 final PreferredActivity pa = it.next(); 11655 if (packageName == null 11656 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11657 && pa.mPref.mAlways)) { 11658 if (outFilters != null) { 11659 outFilters.add(new IntentFilter(pa)); 11660 } 11661 if (outActivities != null) { 11662 outActivities.add(pa.mPref.mComponent); 11663 } 11664 } 11665 } 11666 } 11667 } 11668 11669 return num; 11670 } 11671 11672 @Override 11673 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11674 int userId) { 11675 int callingUid = Binder.getCallingUid(); 11676 if (callingUid != Process.SYSTEM_UID) { 11677 throw new SecurityException( 11678 "addPersistentPreferredActivity can only be run by the system"); 11679 } 11680 if (filter.countActions() == 0) { 11681 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11682 return; 11683 } 11684 synchronized (mPackages) { 11685 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11686 " :"); 11687 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11688 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11689 new PersistentPreferredActivity(filter, activity)); 11690 mSettings.writePackageRestrictionsLPr(userId); 11691 } 11692 } 11693 11694 @Override 11695 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11696 int callingUid = Binder.getCallingUid(); 11697 if (callingUid != Process.SYSTEM_UID) { 11698 throw new SecurityException( 11699 "clearPackagePersistentPreferredActivities can only be run by the system"); 11700 } 11701 ArrayList<PersistentPreferredActivity> removed = null; 11702 boolean changed = false; 11703 synchronized (mPackages) { 11704 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11705 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11706 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11707 .valueAt(i); 11708 if (userId != thisUserId) { 11709 continue; 11710 } 11711 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11712 while (it.hasNext()) { 11713 PersistentPreferredActivity ppa = it.next(); 11714 // Mark entry for removal only if it matches the package name. 11715 if (ppa.mComponent.getPackageName().equals(packageName)) { 11716 if (removed == null) { 11717 removed = new ArrayList<PersistentPreferredActivity>(); 11718 } 11719 removed.add(ppa); 11720 } 11721 } 11722 if (removed != null) { 11723 for (int j=0; j<removed.size(); j++) { 11724 PersistentPreferredActivity ppa = removed.get(j); 11725 ppir.removeFilter(ppa); 11726 } 11727 changed = true; 11728 } 11729 } 11730 11731 if (changed) { 11732 mSettings.writePackageRestrictionsLPr(userId); 11733 } 11734 } 11735 } 11736 11737 @Override 11738 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11739 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11740 mContext.enforceCallingOrSelfPermission( 11741 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11742 int callingUid = Binder.getCallingUid(); 11743 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11744 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11745 if (intentFilter.countActions() == 0) { 11746 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11747 return; 11748 } 11749 synchronized (mPackages) { 11750 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11751 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11752 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11753 mSettings.writePackageRestrictionsLPr(sourceUserId); 11754 } 11755 } 11756 11757 @Override 11758 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11759 int ownerUserId) { 11760 mContext.enforceCallingOrSelfPermission( 11761 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11762 int callingUid = Binder.getCallingUid(); 11763 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11764 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11765 int callingUserId = UserHandle.getUserId(callingUid); 11766 synchronized (mPackages) { 11767 CrossProfileIntentResolver resolver = 11768 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11769 HashSet<CrossProfileIntentFilter> set = 11770 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11771 for (CrossProfileIntentFilter filter : set) { 11772 if (filter.getOwnerPackage().equals(ownerPackage) 11773 && filter.getOwnerUserId() == callingUserId) { 11774 resolver.removeFilter(filter); 11775 } 11776 } 11777 mSettings.writePackageRestrictionsLPr(sourceUserId); 11778 } 11779 } 11780 11781 // Enforcing that callingUid is owning pkg on userId 11782 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11783 // The system owns everything. 11784 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11785 return; 11786 } 11787 int callingUserId = UserHandle.getUserId(callingUid); 11788 if (callingUserId != userId) { 11789 throw new SecurityException("calling uid " + callingUid 11790 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11791 + callingUserId); 11792 } 11793 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11794 if (pi == null) { 11795 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11796 + callingUserId); 11797 } 11798 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11799 throw new SecurityException("Calling uid " + callingUid 11800 + " does not own package " + pkg); 11801 } 11802 } 11803 11804 @Override 11805 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11806 Intent intent = new Intent(Intent.ACTION_MAIN); 11807 intent.addCategory(Intent.CATEGORY_HOME); 11808 11809 final int callingUserId = UserHandle.getCallingUserId(); 11810 List<ResolveInfo> list = queryIntentActivities(intent, null, 11811 PackageManager.GET_META_DATA, callingUserId); 11812 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11813 true, false, false, callingUserId); 11814 11815 allHomeCandidates.clear(); 11816 if (list != null) { 11817 for (ResolveInfo ri : list) { 11818 allHomeCandidates.add(ri); 11819 } 11820 } 11821 return (preferred == null || preferred.activityInfo == null) 11822 ? null 11823 : new ComponentName(preferred.activityInfo.packageName, 11824 preferred.activityInfo.name); 11825 } 11826 11827 @Override 11828 public void setApplicationEnabledSetting(String appPackageName, 11829 int newState, int flags, int userId, String callingPackage) { 11830 if (!sUserManager.exists(userId)) return; 11831 if (callingPackage == null) { 11832 callingPackage = Integer.toString(Binder.getCallingUid()); 11833 } 11834 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11835 } 11836 11837 @Override 11838 public void setComponentEnabledSetting(ComponentName componentName, 11839 int newState, int flags, int userId) { 11840 if (!sUserManager.exists(userId)) return; 11841 setEnabledSetting(componentName.getPackageName(), 11842 componentName.getClassName(), newState, flags, userId, null); 11843 } 11844 11845 private void setEnabledSetting(final String packageName, String className, int newState, 11846 final int flags, int userId, String callingPackage) { 11847 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11848 || newState == COMPONENT_ENABLED_STATE_ENABLED 11849 || newState == COMPONENT_ENABLED_STATE_DISABLED 11850 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11851 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11852 throw new IllegalArgumentException("Invalid new component state: " 11853 + newState); 11854 } 11855 PackageSetting pkgSetting; 11856 final int uid = Binder.getCallingUid(); 11857 final int permission = mContext.checkCallingOrSelfPermission( 11858 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11859 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11860 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11861 boolean sendNow = false; 11862 boolean isApp = (className == null); 11863 String componentName = isApp ? packageName : className; 11864 int packageUid = -1; 11865 ArrayList<String> components; 11866 11867 // writer 11868 synchronized (mPackages) { 11869 pkgSetting = mSettings.mPackages.get(packageName); 11870 if (pkgSetting == null) { 11871 if (className == null) { 11872 throw new IllegalArgumentException( 11873 "Unknown package: " + packageName); 11874 } 11875 throw new IllegalArgumentException( 11876 "Unknown component: " + packageName 11877 + "/" + className); 11878 } 11879 // Allow root and verify that userId is not being specified by a different user 11880 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11881 throw new SecurityException( 11882 "Permission Denial: attempt to change component state from pid=" 11883 + Binder.getCallingPid() 11884 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11885 } 11886 if (className == null) { 11887 // We're dealing with an application/package level state change 11888 if (pkgSetting.getEnabled(userId) == newState) { 11889 // Nothing to do 11890 return; 11891 } 11892 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11893 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11894 // Don't care about who enables an app. 11895 callingPackage = null; 11896 } 11897 pkgSetting.setEnabled(newState, userId, callingPackage); 11898 // pkgSetting.pkg.mSetEnabled = newState; 11899 } else { 11900 // We're dealing with a component level state change 11901 // First, verify that this is a valid class name. 11902 PackageParser.Package pkg = pkgSetting.pkg; 11903 if (pkg == null || !pkg.hasComponentClassName(className)) { 11904 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11905 throw new IllegalArgumentException("Component class " + className 11906 + " does not exist in " + packageName); 11907 } else { 11908 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11909 + className + " does not exist in " + packageName); 11910 } 11911 } 11912 switch (newState) { 11913 case COMPONENT_ENABLED_STATE_ENABLED: 11914 if (!pkgSetting.enableComponentLPw(className, userId)) { 11915 return; 11916 } 11917 break; 11918 case COMPONENT_ENABLED_STATE_DISABLED: 11919 if (!pkgSetting.disableComponentLPw(className, userId)) { 11920 return; 11921 } 11922 break; 11923 case COMPONENT_ENABLED_STATE_DEFAULT: 11924 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11925 return; 11926 } 11927 break; 11928 default: 11929 Slog.e(TAG, "Invalid new component state: " + newState); 11930 return; 11931 } 11932 } 11933 mSettings.writePackageRestrictionsLPr(userId); 11934 components = mPendingBroadcasts.get(userId, packageName); 11935 final boolean newPackage = components == null; 11936 if (newPackage) { 11937 components = new ArrayList<String>(); 11938 } 11939 if (!components.contains(componentName)) { 11940 components.add(componentName); 11941 } 11942 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11943 sendNow = true; 11944 // Purge entry from pending broadcast list if another one exists already 11945 // since we are sending one right away. 11946 mPendingBroadcasts.remove(userId, packageName); 11947 } else { 11948 if (newPackage) { 11949 mPendingBroadcasts.put(userId, packageName, components); 11950 } 11951 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11952 // Schedule a message 11953 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11954 } 11955 } 11956 } 11957 11958 long callingId = Binder.clearCallingIdentity(); 11959 try { 11960 if (sendNow) { 11961 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11962 sendPackageChangedBroadcast(packageName, 11963 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11964 } 11965 } finally { 11966 Binder.restoreCallingIdentity(callingId); 11967 } 11968 } 11969 11970 private void sendPackageChangedBroadcast(String packageName, 11971 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11972 if (DEBUG_INSTALL) 11973 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11974 + componentNames); 11975 Bundle extras = new Bundle(4); 11976 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11977 String nameList[] = new String[componentNames.size()]; 11978 componentNames.toArray(nameList); 11979 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11980 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11981 extras.putInt(Intent.EXTRA_UID, packageUid); 11982 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11983 new int[] {UserHandle.getUserId(packageUid)}); 11984 } 11985 11986 @Override 11987 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11988 if (!sUserManager.exists(userId)) return; 11989 final int uid = Binder.getCallingUid(); 11990 final int permission = mContext.checkCallingOrSelfPermission( 11991 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11992 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11993 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 11994 // writer 11995 synchronized (mPackages) { 11996 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11997 uid, userId)) { 11998 scheduleWritePackageRestrictionsLocked(userId); 11999 } 12000 } 12001 } 12002 12003 @Override 12004 public String getInstallerPackageName(String packageName) { 12005 // reader 12006 synchronized (mPackages) { 12007 return mSettings.getInstallerPackageNameLPr(packageName); 12008 } 12009 } 12010 12011 @Override 12012 public int getApplicationEnabledSetting(String packageName, int userId) { 12013 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12014 int uid = Binder.getCallingUid(); 12015 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12016 // reader 12017 synchronized (mPackages) { 12018 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12019 } 12020 } 12021 12022 @Override 12023 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12024 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12025 int uid = Binder.getCallingUid(); 12026 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12027 // reader 12028 synchronized (mPackages) { 12029 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12030 } 12031 } 12032 12033 @Override 12034 public void enterSafeMode() { 12035 enforceSystemOrRoot("Only the system can request entering safe mode"); 12036 12037 if (!mSystemReady) { 12038 mSafeMode = true; 12039 } 12040 } 12041 12042 @Override 12043 public void systemReady() { 12044 mSystemReady = true; 12045 12046 // Read the compatibilty setting when the system is ready. 12047 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12048 mContext.getContentResolver(), 12049 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12050 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12051 if (DEBUG_SETTINGS) { 12052 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12053 } 12054 12055 synchronized (mPackages) { 12056 // Verify that all of the preferred activity components actually 12057 // exist. It is possible for applications to be updated and at 12058 // that point remove a previously declared activity component that 12059 // had been set as a preferred activity. We try to clean this up 12060 // the next time we encounter that preferred activity, but it is 12061 // possible for the user flow to never be able to return to that 12062 // situation so here we do a sanity check to make sure we haven't 12063 // left any junk around. 12064 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12065 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12066 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12067 removed.clear(); 12068 for (PreferredActivity pa : pir.filterSet()) { 12069 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12070 removed.add(pa); 12071 } 12072 } 12073 if (removed.size() > 0) { 12074 for (int r=0; r<removed.size(); r++) { 12075 PreferredActivity pa = removed.get(r); 12076 Slog.w(TAG, "Removing dangling preferred activity: " 12077 + pa.mPref.mComponent); 12078 pir.removeFilter(pa); 12079 } 12080 mSettings.writePackageRestrictionsLPr( 12081 mSettings.mPreferredActivities.keyAt(i)); 12082 } 12083 } 12084 } 12085 sUserManager.systemReady(); 12086 12087 // Kick off any messages waiting for system ready 12088 if (mPostSystemReadyMessages != null) { 12089 for (Message msg : mPostSystemReadyMessages) { 12090 msg.sendToTarget(); 12091 } 12092 mPostSystemReadyMessages = null; 12093 } 12094 } 12095 12096 @Override 12097 public boolean isSafeMode() { 12098 return mSafeMode; 12099 } 12100 12101 @Override 12102 public boolean hasSystemUidErrors() { 12103 return mHasSystemUidErrors; 12104 } 12105 12106 static String arrayToString(int[] array) { 12107 StringBuffer buf = new StringBuffer(128); 12108 buf.append('['); 12109 if (array != null) { 12110 for (int i=0; i<array.length; i++) { 12111 if (i > 0) buf.append(", "); 12112 buf.append(array[i]); 12113 } 12114 } 12115 buf.append(']'); 12116 return buf.toString(); 12117 } 12118 12119 static class DumpState { 12120 public static final int DUMP_LIBS = 1 << 0; 12121 public static final int DUMP_FEATURES = 1 << 1; 12122 public static final int DUMP_RESOLVERS = 1 << 2; 12123 public static final int DUMP_PERMISSIONS = 1 << 3; 12124 public static final int DUMP_PACKAGES = 1 << 4; 12125 public static final int DUMP_SHARED_USERS = 1 << 5; 12126 public static final int DUMP_MESSAGES = 1 << 6; 12127 public static final int DUMP_PROVIDERS = 1 << 7; 12128 public static final int DUMP_VERIFIERS = 1 << 8; 12129 public static final int DUMP_PREFERRED = 1 << 9; 12130 public static final int DUMP_PREFERRED_XML = 1 << 10; 12131 public static final int DUMP_KEYSETS = 1 << 11; 12132 public static final int DUMP_VERSION = 1 << 12; 12133 public static final int DUMP_INSTALLS = 1 << 13; 12134 12135 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12136 12137 private int mTypes; 12138 12139 private int mOptions; 12140 12141 private boolean mTitlePrinted; 12142 12143 private SharedUserSetting mSharedUser; 12144 12145 public boolean isDumping(int type) { 12146 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12147 return true; 12148 } 12149 12150 return (mTypes & type) != 0; 12151 } 12152 12153 public void setDump(int type) { 12154 mTypes |= type; 12155 } 12156 12157 public boolean isOptionEnabled(int option) { 12158 return (mOptions & option) != 0; 12159 } 12160 12161 public void setOptionEnabled(int option) { 12162 mOptions |= option; 12163 } 12164 12165 public boolean onTitlePrinted() { 12166 final boolean printed = mTitlePrinted; 12167 mTitlePrinted = true; 12168 return printed; 12169 } 12170 12171 public boolean getTitlePrinted() { 12172 return mTitlePrinted; 12173 } 12174 12175 public void setTitlePrinted(boolean enabled) { 12176 mTitlePrinted = enabled; 12177 } 12178 12179 public SharedUserSetting getSharedUser() { 12180 return mSharedUser; 12181 } 12182 12183 public void setSharedUser(SharedUserSetting user) { 12184 mSharedUser = user; 12185 } 12186 } 12187 12188 @Override 12189 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12190 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12191 != PackageManager.PERMISSION_GRANTED) { 12192 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12193 + Binder.getCallingPid() 12194 + ", uid=" + Binder.getCallingUid() 12195 + " without permission " 12196 + android.Manifest.permission.DUMP); 12197 return; 12198 } 12199 12200 DumpState dumpState = new DumpState(); 12201 boolean fullPreferred = false; 12202 boolean checkin = false; 12203 12204 String packageName = null; 12205 12206 int opti = 0; 12207 while (opti < args.length) { 12208 String opt = args[opti]; 12209 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12210 break; 12211 } 12212 opti++; 12213 12214 if ("-a".equals(opt)) { 12215 // Right now we only know how to print all. 12216 } else if ("-h".equals(opt)) { 12217 pw.println("Package manager dump options:"); 12218 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12219 pw.println(" --checkin: dump for a checkin"); 12220 pw.println(" -f: print details of intent filters"); 12221 pw.println(" -h: print this help"); 12222 pw.println(" cmd may be one of:"); 12223 pw.println(" l[ibraries]: list known shared libraries"); 12224 pw.println(" f[ibraries]: list device features"); 12225 pw.println(" k[eysets]: print known keysets"); 12226 pw.println(" r[esolvers]: dump intent resolvers"); 12227 pw.println(" perm[issions]: dump permissions"); 12228 pw.println(" pref[erred]: print preferred package settings"); 12229 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12230 pw.println(" prov[iders]: dump content providers"); 12231 pw.println(" p[ackages]: dump installed packages"); 12232 pw.println(" s[hared-users]: dump shared user IDs"); 12233 pw.println(" m[essages]: print collected runtime messages"); 12234 pw.println(" v[erifiers]: print package verifier info"); 12235 pw.println(" version: print database version info"); 12236 pw.println(" write: write current settings now"); 12237 pw.println(" <package.name>: info about given package"); 12238 pw.println(" installs: details about install sessions"); 12239 return; 12240 } else if ("--checkin".equals(opt)) { 12241 checkin = true; 12242 } else if ("-f".equals(opt)) { 12243 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12244 } else { 12245 pw.println("Unknown argument: " + opt + "; use -h for help"); 12246 } 12247 } 12248 12249 // Is the caller requesting to dump a particular piece of data? 12250 if (opti < args.length) { 12251 String cmd = args[opti]; 12252 opti++; 12253 // Is this a package name? 12254 if ("android".equals(cmd) || cmd.contains(".")) { 12255 packageName = cmd; 12256 // When dumping a single package, we always dump all of its 12257 // filter information since the amount of data will be reasonable. 12258 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12259 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12260 dumpState.setDump(DumpState.DUMP_LIBS); 12261 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12262 dumpState.setDump(DumpState.DUMP_FEATURES); 12263 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12264 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12265 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12266 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12267 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12268 dumpState.setDump(DumpState.DUMP_PREFERRED); 12269 } else if ("preferred-xml".equals(cmd)) { 12270 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12271 if (opti < args.length && "--full".equals(args[opti])) { 12272 fullPreferred = true; 12273 opti++; 12274 } 12275 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12276 dumpState.setDump(DumpState.DUMP_PACKAGES); 12277 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12278 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12279 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12280 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12281 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12282 dumpState.setDump(DumpState.DUMP_MESSAGES); 12283 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12284 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12285 } else if ("version".equals(cmd)) { 12286 dumpState.setDump(DumpState.DUMP_VERSION); 12287 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12288 dumpState.setDump(DumpState.DUMP_KEYSETS); 12289 } else if ("installs".equals(cmd)) { 12290 dumpState.setDump(DumpState.DUMP_INSTALLS); 12291 } else if ("write".equals(cmd)) { 12292 synchronized (mPackages) { 12293 mSettings.writeLPr(); 12294 pw.println("Settings written."); 12295 return; 12296 } 12297 } 12298 } 12299 12300 if (checkin) { 12301 pw.println("vers,1"); 12302 } 12303 12304 // reader 12305 synchronized (mPackages) { 12306 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12307 if (!checkin) { 12308 if (dumpState.onTitlePrinted()) 12309 pw.println(); 12310 pw.println("Database versions:"); 12311 pw.print(" SDK Version:"); 12312 pw.print(" internal="); 12313 pw.print(mSettings.mInternalSdkPlatform); 12314 pw.print(" external="); 12315 pw.println(mSettings.mExternalSdkPlatform); 12316 pw.print(" DB Version:"); 12317 pw.print(" internal="); 12318 pw.print(mSettings.mInternalDatabaseVersion); 12319 pw.print(" external="); 12320 pw.println(mSettings.mExternalDatabaseVersion); 12321 } 12322 } 12323 12324 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12325 if (!checkin) { 12326 if (dumpState.onTitlePrinted()) 12327 pw.println(); 12328 pw.println("Verifiers:"); 12329 pw.print(" Required: "); 12330 pw.print(mRequiredVerifierPackage); 12331 pw.print(" (uid="); 12332 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12333 pw.println(")"); 12334 } else if (mRequiredVerifierPackage != null) { 12335 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12336 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12337 } 12338 } 12339 12340 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12341 boolean printedHeader = false; 12342 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12343 while (it.hasNext()) { 12344 String name = it.next(); 12345 SharedLibraryEntry ent = mSharedLibraries.get(name); 12346 if (!checkin) { 12347 if (!printedHeader) { 12348 if (dumpState.onTitlePrinted()) 12349 pw.println(); 12350 pw.println("Libraries:"); 12351 printedHeader = true; 12352 } 12353 pw.print(" "); 12354 } else { 12355 pw.print("lib,"); 12356 } 12357 pw.print(name); 12358 if (!checkin) { 12359 pw.print(" -> "); 12360 } 12361 if (ent.path != null) { 12362 if (!checkin) { 12363 pw.print("(jar) "); 12364 pw.print(ent.path); 12365 } else { 12366 pw.print(",jar,"); 12367 pw.print(ent.path); 12368 } 12369 } else { 12370 if (!checkin) { 12371 pw.print("(apk) "); 12372 pw.print(ent.apk); 12373 } else { 12374 pw.print(",apk,"); 12375 pw.print(ent.apk); 12376 } 12377 } 12378 pw.println(); 12379 } 12380 } 12381 12382 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12383 if (dumpState.onTitlePrinted()) 12384 pw.println(); 12385 if (!checkin) { 12386 pw.println("Features:"); 12387 } 12388 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12389 while (it.hasNext()) { 12390 String name = it.next(); 12391 if (!checkin) { 12392 pw.print(" "); 12393 } else { 12394 pw.print("feat,"); 12395 } 12396 pw.println(name); 12397 } 12398 } 12399 12400 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12401 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12402 : "Activity Resolver Table:", " ", packageName, 12403 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12404 dumpState.setTitlePrinted(true); 12405 } 12406 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12407 : "Receiver Resolver Table:", " ", packageName, 12408 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12409 dumpState.setTitlePrinted(true); 12410 } 12411 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12412 : "Service Resolver Table:", " ", packageName, 12413 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12414 dumpState.setTitlePrinted(true); 12415 } 12416 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12417 : "Provider Resolver Table:", " ", packageName, 12418 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12419 dumpState.setTitlePrinted(true); 12420 } 12421 } 12422 12423 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12424 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12425 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12426 int user = mSettings.mPreferredActivities.keyAt(i); 12427 if (pir.dump(pw, 12428 dumpState.getTitlePrinted() 12429 ? "\nPreferred Activities User " + user + ":" 12430 : "Preferred Activities User " + user + ":", " ", 12431 packageName, true)) { 12432 dumpState.setTitlePrinted(true); 12433 } 12434 } 12435 } 12436 12437 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12438 pw.flush(); 12439 FileOutputStream fout = new FileOutputStream(fd); 12440 BufferedOutputStream str = new BufferedOutputStream(fout); 12441 XmlSerializer serializer = new FastXmlSerializer(); 12442 try { 12443 serializer.setOutput(str, "utf-8"); 12444 serializer.startDocument(null, true); 12445 serializer.setFeature( 12446 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12447 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12448 serializer.endDocument(); 12449 serializer.flush(); 12450 } catch (IllegalArgumentException e) { 12451 pw.println("Failed writing: " + e); 12452 } catch (IllegalStateException e) { 12453 pw.println("Failed writing: " + e); 12454 } catch (IOException e) { 12455 pw.println("Failed writing: " + e); 12456 } 12457 } 12458 12459 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12460 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12461 if (packageName == null) { 12462 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12463 if (iperm == 0) { 12464 if (dumpState.onTitlePrinted()) 12465 pw.println(); 12466 pw.println("AppOp Permissions:"); 12467 } 12468 pw.print(" AppOp Permission "); 12469 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12470 pw.println(":"); 12471 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12472 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12473 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12474 } 12475 } 12476 } 12477 } 12478 12479 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12480 boolean printedSomething = false; 12481 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12482 if (packageName != null && !packageName.equals(p.info.packageName)) { 12483 continue; 12484 } 12485 if (!printedSomething) { 12486 if (dumpState.onTitlePrinted()) 12487 pw.println(); 12488 pw.println("Registered ContentProviders:"); 12489 printedSomething = true; 12490 } 12491 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12492 pw.print(" "); pw.println(p.toString()); 12493 } 12494 printedSomething = false; 12495 for (Map.Entry<String, PackageParser.Provider> entry : 12496 mProvidersByAuthority.entrySet()) { 12497 PackageParser.Provider p = entry.getValue(); 12498 if (packageName != null && !packageName.equals(p.info.packageName)) { 12499 continue; 12500 } 12501 if (!printedSomething) { 12502 if (dumpState.onTitlePrinted()) 12503 pw.println(); 12504 pw.println("ContentProvider Authorities:"); 12505 printedSomething = true; 12506 } 12507 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12508 pw.print(" "); pw.println(p.toString()); 12509 if (p.info != null && p.info.applicationInfo != null) { 12510 final String appInfo = p.info.applicationInfo.toString(); 12511 pw.print(" applicationInfo="); pw.println(appInfo); 12512 } 12513 } 12514 } 12515 12516 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12517 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12518 } 12519 12520 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12521 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12522 } 12523 12524 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12525 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12526 } 12527 12528 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12529 // XXX should handle packageName != null by dumping only install data that 12530 // the given package is involved with. 12531 if (dumpState.onTitlePrinted()) pw.println(); 12532 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12533 } 12534 12535 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12536 if (dumpState.onTitlePrinted()) pw.println(); 12537 mSettings.dumpReadMessagesLPr(pw, dumpState); 12538 12539 pw.println(); 12540 pw.println("Package warning messages:"); 12541 final File fname = getSettingsProblemFile(); 12542 FileInputStream in = null; 12543 try { 12544 in = new FileInputStream(fname); 12545 final int avail = in.available(); 12546 final byte[] data = new byte[avail]; 12547 in.read(data); 12548 pw.print(new String(data)); 12549 } catch (FileNotFoundException e) { 12550 } catch (IOException e) { 12551 } finally { 12552 if (in != null) { 12553 try { 12554 in.close(); 12555 } catch (IOException e) { 12556 } 12557 } 12558 } 12559 } 12560 12561 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12562 BufferedReader in = null; 12563 String line = null; 12564 try { 12565 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12566 while ((line = in.readLine()) != null) { 12567 pw.print("msg,"); 12568 pw.println(line); 12569 } 12570 } catch (IOException ignored) { 12571 } finally { 12572 IoUtils.closeQuietly(in); 12573 } 12574 } 12575 } 12576 } 12577 12578 // ------- apps on sdcard specific code ------- 12579 static final boolean DEBUG_SD_INSTALL = false; 12580 12581 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12582 12583 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12584 12585 private boolean mMediaMounted = false; 12586 12587 static String getEncryptKey() { 12588 try { 12589 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12590 SD_ENCRYPTION_KEYSTORE_NAME); 12591 if (sdEncKey == null) { 12592 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12593 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12594 if (sdEncKey == null) { 12595 Slog.e(TAG, "Failed to create encryption keys"); 12596 return null; 12597 } 12598 } 12599 return sdEncKey; 12600 } catch (NoSuchAlgorithmException nsae) { 12601 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12602 return null; 12603 } catch (IOException ioe) { 12604 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12605 return null; 12606 } 12607 } 12608 12609 /* 12610 * Update media status on PackageManager. 12611 */ 12612 @Override 12613 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12614 int callingUid = Binder.getCallingUid(); 12615 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12616 throw new SecurityException("Media status can only be updated by the system"); 12617 } 12618 // reader; this apparently protects mMediaMounted, but should probably 12619 // be a different lock in that case. 12620 synchronized (mPackages) { 12621 Log.i(TAG, "Updating external media status from " 12622 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12623 + (mediaStatus ? "mounted" : "unmounted")); 12624 if (DEBUG_SD_INSTALL) 12625 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12626 + ", mMediaMounted=" + mMediaMounted); 12627 if (mediaStatus == mMediaMounted) { 12628 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12629 : 0, -1); 12630 mHandler.sendMessage(msg); 12631 return; 12632 } 12633 mMediaMounted = mediaStatus; 12634 } 12635 // Queue up an async operation since the package installation may take a 12636 // little while. 12637 mHandler.post(new Runnable() { 12638 public void run() { 12639 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12640 } 12641 }); 12642 } 12643 12644 /** 12645 * Called by MountService when the initial ASECs to scan are available. 12646 * Should block until all the ASEC containers are finished being scanned. 12647 */ 12648 public void scanAvailableAsecs() { 12649 updateExternalMediaStatusInner(true, false, false); 12650 if (mShouldRestoreconData) { 12651 SELinuxMMAC.setRestoreconDone(); 12652 mShouldRestoreconData = false; 12653 } 12654 } 12655 12656 /* 12657 * Collect information of applications on external media, map them against 12658 * existing containers and update information based on current mount status. 12659 * Please note that we always have to report status if reportStatus has been 12660 * set to true especially when unloading packages. 12661 */ 12662 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12663 boolean externalStorage) { 12664 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12665 int[] uidArr = EmptyArray.INT; 12666 12667 final String[] list = PackageHelper.getSecureContainerList(); 12668 if (ArrayUtils.isEmpty(list)) { 12669 Log.i(TAG, "No secure containers found"); 12670 } else { 12671 // Process list of secure containers and categorize them 12672 // as active or stale based on their package internal state. 12673 12674 // reader 12675 synchronized (mPackages) { 12676 for (String cid : list) { 12677 // Leave stages untouched for now; installer service owns them 12678 if (PackageInstallerService.isStageName(cid)) continue; 12679 12680 if (DEBUG_SD_INSTALL) 12681 Log.i(TAG, "Processing container " + cid); 12682 String pkgName = getAsecPackageName(cid); 12683 if (pkgName == null) { 12684 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12685 continue; 12686 } 12687 if (DEBUG_SD_INSTALL) 12688 Log.i(TAG, "Looking for pkg : " + pkgName); 12689 12690 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12691 if (ps == null) { 12692 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12693 continue; 12694 } 12695 12696 /* 12697 * Skip packages that are not external if we're unmounting 12698 * external storage. 12699 */ 12700 if (externalStorage && !isMounted && !isExternal(ps)) { 12701 continue; 12702 } 12703 12704 final AsecInstallArgs args = new AsecInstallArgs(cid, 12705 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12706 // The package status is changed only if the code path 12707 // matches between settings and the container id. 12708 if (ps.codePathString != null 12709 && ps.codePathString.startsWith(args.getCodePath())) { 12710 if (DEBUG_SD_INSTALL) { 12711 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12712 + " at code path: " + ps.codePathString); 12713 } 12714 12715 // We do have a valid package installed on sdcard 12716 processCids.put(args, ps.codePathString); 12717 final int uid = ps.appId; 12718 if (uid != -1) { 12719 uidArr = ArrayUtils.appendInt(uidArr, uid); 12720 } 12721 } else { 12722 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12723 + ps.codePathString); 12724 } 12725 } 12726 } 12727 12728 Arrays.sort(uidArr); 12729 } 12730 12731 // Process packages with valid entries. 12732 if (isMounted) { 12733 if (DEBUG_SD_INSTALL) 12734 Log.i(TAG, "Loading packages"); 12735 loadMediaPackages(processCids, uidArr); 12736 startCleaningPackages(); 12737 mInstallerService.onSecureContainersAvailable(); 12738 } else { 12739 if (DEBUG_SD_INSTALL) 12740 Log.i(TAG, "Unloading packages"); 12741 unloadMediaPackages(processCids, uidArr, reportStatus); 12742 } 12743 } 12744 12745 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12746 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12747 int size = pkgList.size(); 12748 if (size > 0) { 12749 // Send broadcasts here 12750 Bundle extras = new Bundle(); 12751 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12752 .toArray(new String[size])); 12753 if (uidArr != null) { 12754 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12755 } 12756 if (replacing) { 12757 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12758 } 12759 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12760 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12761 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12762 } 12763 } 12764 12765 /* 12766 * Look at potentially valid container ids from processCids If package 12767 * information doesn't match the one on record or package scanning fails, 12768 * the cid is added to list of removeCids. We currently don't delete stale 12769 * containers. 12770 */ 12771 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12772 ArrayList<String> pkgList = new ArrayList<String>(); 12773 Set<AsecInstallArgs> keys = processCids.keySet(); 12774 12775 for (AsecInstallArgs args : keys) { 12776 String codePath = processCids.get(args); 12777 if (DEBUG_SD_INSTALL) 12778 Log.i(TAG, "Loading container : " + args.cid); 12779 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12780 try { 12781 // Make sure there are no container errors first. 12782 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12783 Slog.e(TAG, "Failed to mount cid : " + args.cid 12784 + " when installing from sdcard"); 12785 continue; 12786 } 12787 // Check code path here. 12788 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12789 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12790 + " does not match one in settings " + codePath); 12791 continue; 12792 } 12793 // Parse package 12794 int parseFlags = mDefParseFlags; 12795 if (args.isExternal()) { 12796 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12797 } 12798 if (args.isFwdLocked()) { 12799 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12800 } 12801 12802 synchronized (mInstallLock) { 12803 PackageParser.Package pkg = null; 12804 try { 12805 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12806 } catch (PackageManagerException e) { 12807 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12808 } 12809 // Scan the package 12810 if (pkg != null) { 12811 /* 12812 * TODO why is the lock being held? doPostInstall is 12813 * called in other places without the lock. This needs 12814 * to be straightened out. 12815 */ 12816 // writer 12817 synchronized (mPackages) { 12818 retCode = PackageManager.INSTALL_SUCCEEDED; 12819 pkgList.add(pkg.packageName); 12820 // Post process args 12821 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12822 pkg.applicationInfo.uid); 12823 } 12824 } else { 12825 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12826 } 12827 } 12828 12829 } finally { 12830 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12831 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12832 } 12833 } 12834 } 12835 // writer 12836 synchronized (mPackages) { 12837 // If the platform SDK has changed since the last time we booted, 12838 // we need to re-grant app permission to catch any new ones that 12839 // appear. This is really a hack, and means that apps can in some 12840 // cases get permissions that the user didn't initially explicitly 12841 // allow... it would be nice to have some better way to handle 12842 // this situation. 12843 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12844 if (regrantPermissions) 12845 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12846 + mSdkVersion + "; regranting permissions for external storage"); 12847 mSettings.mExternalSdkPlatform = mSdkVersion; 12848 12849 // Make sure group IDs have been assigned, and any permission 12850 // changes in other apps are accounted for 12851 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12852 | (regrantPermissions 12853 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12854 : 0)); 12855 12856 mSettings.updateExternalDatabaseVersion(); 12857 12858 // can downgrade to reader 12859 // Persist settings 12860 mSettings.writeLPr(); 12861 } 12862 // Send a broadcast to let everyone know we are done processing 12863 if (pkgList.size() > 0) { 12864 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12865 } 12866 } 12867 12868 /* 12869 * Utility method to unload a list of specified containers 12870 */ 12871 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12872 // Just unmount all valid containers. 12873 for (AsecInstallArgs arg : cidArgs) { 12874 synchronized (mInstallLock) { 12875 arg.doPostDeleteLI(false); 12876 } 12877 } 12878 } 12879 12880 /* 12881 * Unload packages mounted on external media. This involves deleting package 12882 * data from internal structures, sending broadcasts about diabled packages, 12883 * gc'ing to free up references, unmounting all secure containers 12884 * corresponding to packages on external media, and posting a 12885 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12886 * that we always have to post this message if status has been requested no 12887 * matter what. 12888 */ 12889 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12890 final boolean reportStatus) { 12891 if (DEBUG_SD_INSTALL) 12892 Log.i(TAG, "unloading media packages"); 12893 ArrayList<String> pkgList = new ArrayList<String>(); 12894 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12895 final Set<AsecInstallArgs> keys = processCids.keySet(); 12896 for (AsecInstallArgs args : keys) { 12897 String pkgName = args.getPackageName(); 12898 if (DEBUG_SD_INSTALL) 12899 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12900 // Delete package internally 12901 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12902 synchronized (mInstallLock) { 12903 boolean res = deletePackageLI(pkgName, null, false, null, null, 12904 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12905 if (res) { 12906 pkgList.add(pkgName); 12907 } else { 12908 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12909 failedList.add(args); 12910 } 12911 } 12912 } 12913 12914 // reader 12915 synchronized (mPackages) { 12916 // We didn't update the settings after removing each package; 12917 // write them now for all packages. 12918 mSettings.writeLPr(); 12919 } 12920 12921 // We have to absolutely send UPDATED_MEDIA_STATUS only 12922 // after confirming that all the receivers processed the ordered 12923 // broadcast when packages get disabled, force a gc to clean things up. 12924 // and unload all the containers. 12925 if (pkgList.size() > 0) { 12926 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12927 new IIntentReceiver.Stub() { 12928 public void performReceive(Intent intent, int resultCode, String data, 12929 Bundle extras, boolean ordered, boolean sticky, 12930 int sendingUser) throws RemoteException { 12931 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12932 reportStatus ? 1 : 0, 1, keys); 12933 mHandler.sendMessage(msg); 12934 } 12935 }); 12936 } else { 12937 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12938 keys); 12939 mHandler.sendMessage(msg); 12940 } 12941 } 12942 12943 /** Binder call */ 12944 @Override 12945 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12946 final int flags) { 12947 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12948 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12949 int returnCode = PackageManager.MOVE_SUCCEEDED; 12950 int currInstallFlags = 0; 12951 int newInstallFlags = 0; 12952 12953 File codeFile = null; 12954 String installerPackageName = null; 12955 String packageAbiOverride = null; 12956 12957 // reader 12958 synchronized (mPackages) { 12959 final PackageParser.Package pkg = mPackages.get(packageName); 12960 final PackageSetting ps = mSettings.mPackages.get(packageName); 12961 if (pkg == null || ps == null) { 12962 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12963 } else { 12964 // Disable moving fwd locked apps and system packages 12965 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12966 Slog.w(TAG, "Cannot move system application"); 12967 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12968 } else if (pkg.mOperationPending) { 12969 Slog.w(TAG, "Attempt to move package which has pending operations"); 12970 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12971 } else { 12972 // Find install location first 12973 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12974 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12975 Slog.w(TAG, "Ambigous flags specified for move location."); 12976 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12977 } else { 12978 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12979 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12980 currInstallFlags = isExternal(pkg) 12981 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12982 12983 if (newInstallFlags == currInstallFlags) { 12984 Slog.w(TAG, "No move required. Trying to move to same location"); 12985 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12986 } else { 12987 if (isForwardLocked(pkg)) { 12988 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12989 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12990 } 12991 } 12992 } 12993 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12994 pkg.mOperationPending = true; 12995 } 12996 } 12997 12998 codeFile = new File(pkg.codePath); 12999 installerPackageName = ps.installerPackageName; 13000 packageAbiOverride = ps.cpuAbiOverrideString; 13001 } 13002 } 13003 13004 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13005 try { 13006 observer.packageMoved(packageName, returnCode); 13007 } catch (RemoteException ignored) { 13008 } 13009 return; 13010 } 13011 13012 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13013 @Override 13014 public void onUserActionRequired(Intent intent) throws RemoteException { 13015 throw new IllegalStateException(); 13016 } 13017 13018 @Override 13019 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13020 Bundle extras) throws RemoteException { 13021 Slog.d(TAG, "Install result for move: " 13022 + PackageManager.installStatusToString(returnCode, msg)); 13023 13024 // We usually have a new package now after the install, but if 13025 // we failed we need to clear the pending flag on the original 13026 // package object. 13027 synchronized (mPackages) { 13028 final PackageParser.Package pkg = mPackages.get(packageName); 13029 if (pkg != null) { 13030 pkg.mOperationPending = false; 13031 } 13032 } 13033 13034 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13035 switch (status) { 13036 case PackageInstaller.STATUS_SUCCESS: 13037 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13038 break; 13039 case PackageInstaller.STATUS_FAILURE_STORAGE: 13040 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13041 break; 13042 default: 13043 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13044 break; 13045 } 13046 } 13047 }; 13048 13049 // Treat a move like reinstalling an existing app, which ensures that we 13050 // process everythign uniformly, like unpacking native libraries. 13051 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13052 13053 final Message msg = mHandler.obtainMessage(INIT_COPY); 13054 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13055 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13056 installerPackageName, null, user, packageAbiOverride); 13057 mHandler.sendMessage(msg); 13058 } 13059 13060 @Override 13061 public boolean setInstallLocation(int loc) { 13062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13063 null); 13064 if (getInstallLocation() == loc) { 13065 return true; 13066 } 13067 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13068 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13069 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13070 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13071 return true; 13072 } 13073 return false; 13074 } 13075 13076 @Override 13077 public int getInstallLocation() { 13078 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13079 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13080 PackageHelper.APP_INSTALL_AUTO); 13081 } 13082 13083 /** Called by UserManagerService */ 13084 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13085 mDirtyUsers.remove(userHandle); 13086 mSettings.removeUserLPw(userHandle); 13087 mPendingBroadcasts.remove(userHandle); 13088 if (mInstaller != null) { 13089 // Technically, we shouldn't be doing this with the package lock 13090 // held. However, this is very rare, and there is already so much 13091 // other disk I/O going on, that we'll let it slide for now. 13092 mInstaller.removeUserDataDirs(userHandle); 13093 } 13094 mUserNeedsBadging.delete(userHandle); 13095 removeUnusedPackagesLILPw(userManager, userHandle); 13096 } 13097 13098 /** 13099 * We're removing userHandle and would like to remove any downloaded packages 13100 * that are no longer in use by any other user. 13101 * @param userHandle the user being removed 13102 */ 13103 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13104 final boolean DEBUG_CLEAN_APKS = false; 13105 int [] users = userManager.getUserIdsLPr(); 13106 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13107 while (psit.hasNext()) { 13108 PackageSetting ps = psit.next(); 13109 if (ps.pkg == null) { 13110 continue; 13111 } 13112 final String packageName = ps.pkg.packageName; 13113 // Skip over if system app 13114 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13115 continue; 13116 } 13117 if (DEBUG_CLEAN_APKS) { 13118 Slog.i(TAG, "Checking package " + packageName); 13119 } 13120 boolean keep = false; 13121 for (int i = 0; i < users.length; i++) { 13122 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13123 keep = true; 13124 if (DEBUG_CLEAN_APKS) { 13125 Slog.i(TAG, " Keeping package " + packageName + " for user " 13126 + users[i]); 13127 } 13128 break; 13129 } 13130 } 13131 if (!keep) { 13132 if (DEBUG_CLEAN_APKS) { 13133 Slog.i(TAG, " Removing package " + packageName); 13134 } 13135 mHandler.post(new Runnable() { 13136 public void run() { 13137 deletePackageX(packageName, userHandle, 0); 13138 } //end run 13139 }); 13140 } 13141 } 13142 } 13143 13144 /** Called by UserManagerService */ 13145 void createNewUserLILPw(int userHandle, File path) { 13146 if (mInstaller != null) { 13147 mInstaller.createUserConfig(userHandle); 13148 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13149 } 13150 } 13151 13152 @Override 13153 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13154 mContext.enforceCallingOrSelfPermission( 13155 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13156 "Only package verification agents can read the verifier device identity"); 13157 13158 synchronized (mPackages) { 13159 return mSettings.getVerifierDeviceIdentityLPw(); 13160 } 13161 } 13162 13163 @Override 13164 public void setPermissionEnforced(String permission, boolean enforced) { 13165 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13166 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13167 synchronized (mPackages) { 13168 if (mSettings.mReadExternalStorageEnforced == null 13169 || mSettings.mReadExternalStorageEnforced != enforced) { 13170 mSettings.mReadExternalStorageEnforced = enforced; 13171 mSettings.writeLPr(); 13172 } 13173 } 13174 // kill any non-foreground processes so we restart them and 13175 // grant/revoke the GID. 13176 final IActivityManager am = ActivityManagerNative.getDefault(); 13177 if (am != null) { 13178 final long token = Binder.clearCallingIdentity(); 13179 try { 13180 am.killProcessesBelowForeground("setPermissionEnforcement"); 13181 } catch (RemoteException e) { 13182 } finally { 13183 Binder.restoreCallingIdentity(token); 13184 } 13185 } 13186 } else { 13187 throw new IllegalArgumentException("No selective enforcement for " + permission); 13188 } 13189 } 13190 13191 @Override 13192 @Deprecated 13193 public boolean isPermissionEnforced(String permission) { 13194 return true; 13195 } 13196 13197 @Override 13198 public boolean isStorageLow() { 13199 final long token = Binder.clearCallingIdentity(); 13200 try { 13201 final DeviceStorageMonitorInternal 13202 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13203 if (dsm != null) { 13204 return dsm.isMemoryLow(); 13205 } else { 13206 return false; 13207 } 13208 } finally { 13209 Binder.restoreCallingIdentity(token); 13210 } 13211 } 13212 13213 @Override 13214 public IPackageInstaller getPackageInstaller() { 13215 return mInstallerService; 13216 } 13217 13218 private boolean userNeedsBadging(int userId) { 13219 int index = mUserNeedsBadging.indexOfKey(userId); 13220 if (index < 0) { 13221 final UserInfo userInfo; 13222 final long token = Binder.clearCallingIdentity(); 13223 try { 13224 userInfo = sUserManager.getUserInfo(userId); 13225 } finally { 13226 Binder.restoreCallingIdentity(token); 13227 } 13228 final boolean b; 13229 if (userInfo != null && userInfo.isManagedProfile()) { 13230 b = true; 13231 } else { 13232 b = false; 13233 } 13234 mUserNeedsBadging.put(userId, b); 13235 return b; 13236 } 13237 return mUserNeedsBadging.valueAt(index); 13238 } 13239 13240 @Override 13241 public KeySet getKeySetByAlias(String packageName, String alias) { 13242 if (packageName == null || alias == null) { 13243 return null; 13244 } 13245 synchronized(mPackages) { 13246 final PackageParser.Package pkg = mPackages.get(packageName); 13247 if (pkg == null) { 13248 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13249 throw new IllegalArgumentException("Unknown package: " + packageName); 13250 } 13251 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13252 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13253 } 13254 } 13255 13256 @Override 13257 public KeySet getSigningKeySet(String packageName) { 13258 if (packageName == null) { 13259 return null; 13260 } 13261 synchronized(mPackages) { 13262 final PackageParser.Package pkg = mPackages.get(packageName); 13263 if (pkg == null) { 13264 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13265 throw new IllegalArgumentException("Unknown package: " + packageName); 13266 } 13267 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13268 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13269 throw new SecurityException("May not access signing KeySet of other apps."); 13270 } 13271 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13272 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13273 } 13274 } 13275 13276 @Override 13277 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13278 if (packageName == null || ks == null) { 13279 return false; 13280 } 13281 synchronized(mPackages) { 13282 final PackageParser.Package pkg = mPackages.get(packageName); 13283 if (pkg == null) { 13284 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13285 throw new IllegalArgumentException("Unknown package: " + packageName); 13286 } 13287 IBinder ksh = ks.getToken(); 13288 if (ksh instanceof KeySetHandle) { 13289 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13290 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13291 } 13292 return false; 13293 } 13294 } 13295 13296 @Override 13297 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13298 if (packageName == null || ks == null) { 13299 return false; 13300 } 13301 synchronized(mPackages) { 13302 final PackageParser.Package pkg = mPackages.get(packageName); 13303 if (pkg == null) { 13304 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13305 throw new IllegalArgumentException("Unknown package: " + packageName); 13306 } 13307 IBinder ksh = ks.getToken(); 13308 if (ksh instanceof KeySetHandle) { 13309 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13310 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13311 } 13312 return false; 13313 } 13314 } 13315} 13316