PackageManagerService.java revision 8ad7f2051d722b5a92f0ee0ab46622744b4289ef
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 android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageDeleteObserver2; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstallSessionParams; 111import android.content.pm.InstrumentationInfo; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.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.File; 180import java.io.FileDescriptor; 181import java.io.FileInputStream; 182import java.io.FileNotFoundException; 183import java.io.FileOutputStream; 184import java.io.FilenameFilter; 185import java.io.IOException; 186import java.io.InputStream; 187import java.io.PrintWriter; 188import java.nio.charset.StandardCharsets; 189import java.security.NoSuchAlgorithmException; 190import java.security.PublicKey; 191import java.security.cert.CertificateEncodingException; 192import java.security.cert.CertificateException; 193import java.text.SimpleDateFormat; 194import java.util.ArrayList; 195import java.util.Arrays; 196import java.util.Collection; 197import java.util.Collections; 198import java.util.Comparator; 199import java.util.Date; 200import java.util.HashMap; 201import java.util.HashSet; 202import java.util.Iterator; 203import java.util.List; 204import java.util.Map; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 static final int SCAN_MONITOR = 1<<0; 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 268 static final int REMOVE_CHATTY = 1<<16; 269 270 /** 271 * Timeout (in milliseconds) after which the watchdog should declare that 272 * our handler thread is wedged. The usual default for such things is one 273 * minute but we sometimes do very lengthy I/O operations on this thread, 274 * such as installing multi-gigabyte applications, so ours needs to be longer. 275 */ 276 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 277 278 /** 279 * Whether verification is enabled by default. 280 */ 281 private static final boolean DEFAULT_VERIFY_ENABLE = true; 282 283 /** 284 * The default maximum time to wait for the verification agent to return in 285 * milliseconds. 286 */ 287 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 288 289 /** 290 * The default response for package verification timeout. 291 * 292 * This can be either PackageManager.VERIFICATION_ALLOW or 293 * PackageManager.VERIFICATION_REJECT. 294 */ 295 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 296 297 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 298 299 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 300 DEFAULT_CONTAINER_PACKAGE, 301 "com.android.defcontainer.DefaultContainerService"); 302 303 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 304 305 private static final String LIB_DIR_NAME = "lib"; 306 private static final String LIB64_DIR_NAME = "lib64"; 307 308 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 309 310 static final String mTempContainerPrefix = "smdl2tmp"; 311 312 private static String sPreferredInstructionSet; 313 314 final ServiceThread mHandlerThread; 315 316 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 317 private static final String IDMAP_SUFFIX = "@idmap"; 318 319 final PackageHandler mHandler; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final DisplayMetrics mMetrics; 327 final int mDefParseFlags; 328 final String[] mSeparateProcesses; 329 330 // This is where all application persistent data goes. 331 final File mAppDataDir; 332 333 // This is where all application persistent data goes for secondary users. 334 final File mUserAppDataDir; 335 336 /** The location for ASEC container files on internal storage. */ 337 final String mAsecInternalPath; 338 339 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 340 // LOCK HELD. Can be called with mInstallLock held. 341 final Installer mInstaller; 342 343 /** Directory where installed third-party apps stored */ 344 final File mAppInstallDir; 345 346 /** 347 * Directory to which applications installed internally have their 348 * 32 bit native libraries copied. 349 */ 350 private File mAppLib32InstallDir; 351 352 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 353 // apps. 354 final File mDrmAppPrivateInstallDir; 355 356 // ---------------------------------------------------------------- 357 358 // Lock for state used when installing and doing other long running 359 // operations. Methods that must be called with this lock held have 360 // the suffix "LI". 361 final Object mInstallLock = new Object(); 362 363 // These are the directories in the 3rd party applications installed dir 364 // that we have currently loaded packages from. Keys are the application's 365 // installed zip file (absolute codePath), and values are Package. 366 final HashMap<String, PackageParser.Package> mAppDirs = 367 new HashMap<String, PackageParser.Package>(); 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 boolean mSystemReady; 461 boolean mSafeMode; 462 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.originFile); 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.originFile); 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 mMetrics = new DisplayMetrics(); 1282 mSettings = new Settings(context); 1283 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 1296 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1297 if (separateProcesses != null && separateProcesses.length() > 0) { 1298 if ("*".equals(separateProcesses)) { 1299 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1300 mSeparateProcesses = null; 1301 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1302 } else { 1303 mDefParseFlags = 0; 1304 mSeparateProcesses = separateProcesses.split(","); 1305 Slog.w(TAG, "Running with debug.separate_processes: " 1306 + separateProcesses); 1307 } 1308 } else { 1309 mDefParseFlags = 0; 1310 mSeparateProcesses = null; 1311 } 1312 1313 mInstaller = installer; 1314 1315 getDefaultDisplayMetrics(context, mMetrics); 1316 1317 SystemConfig systemConfig = SystemConfig.getInstance(); 1318 mGlobalGids = systemConfig.getGlobalGids(); 1319 mSystemPermissions = systemConfig.getSystemPermissions(); 1320 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1321 1322 synchronized (mInstallLock) { 1323 // writer 1324 synchronized (mPackages) { 1325 mHandlerThread = new ServiceThread(TAG, 1326 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1327 mHandlerThread.start(); 1328 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1329 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1330 1331 File dataDir = Environment.getDataDirectory(); 1332 mAppDataDir = new File(dataDir, "data"); 1333 mAppInstallDir = new File(dataDir, "app"); 1334 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1335 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1336 mUserAppDataDir = new File(dataDir, "user"); 1337 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1338 1339 sUserManager = new UserManagerService(context, this, 1340 mInstallLock, mPackages); 1341 1342 // Propagate permission configuration in to package manager. 1343 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1344 = systemConfig.getPermissions(); 1345 for (int i=0; i<permConfig.size(); i++) { 1346 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1347 BasePermission bp = mSettings.mPermissions.get(perm.name); 1348 if (bp == null) { 1349 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1350 mSettings.mPermissions.put(perm.name, bp); 1351 } 1352 if (perm.gids != null) { 1353 bp.gids = appendInts(bp.gids, perm.gids); 1354 } 1355 } 1356 1357 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1358 for (int i=0; i<libConfig.size(); i++) { 1359 mSharedLibraries.put(libConfig.keyAt(i), 1360 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1361 } 1362 1363 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1364 1365 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1366 mSdkVersion, mOnlyCore); 1367 1368 String customResolverActivity = Resources.getSystem().getString( 1369 R.string.config_customResolverActivity); 1370 if (TextUtils.isEmpty(customResolverActivity)) { 1371 customResolverActivity = null; 1372 } else { 1373 mCustomResolverComponentName = ComponentName.unflattenFromString( 1374 customResolverActivity); 1375 } 1376 1377 long startTime = SystemClock.uptimeMillis(); 1378 1379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1380 startTime); 1381 1382 // Set flag to monitor and not change apk file paths when 1383 // scanning install directories. 1384 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1385 1386 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1387 1388 /** 1389 * Add everything in the in the boot class path to the 1390 * list of process files because dexopt will have been run 1391 * if necessary during zygote startup. 1392 */ 1393 String bootClassPath = System.getProperty("java.boot.class.path"); 1394 if (bootClassPath != null) { 1395 String[] paths = splitString(bootClassPath, ':'); 1396 for (int i=0; i<paths.length; i++) { 1397 alreadyDexOpted.add(paths[i]); 1398 } 1399 } else { 1400 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1401 } 1402 1403 boolean didDexOptLibraryOrTool = false; 1404 1405 final List<String> allInstructionSets = getAllInstructionSets(); 1406 final String[] dexCodeInstructionSets = 1407 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1408 1409 /** 1410 * Ensure all external libraries have had dexopt run on them. 1411 */ 1412 if (mSharedLibraries.size() > 0) { 1413 // NOTE: For now, we're compiling these system "shared libraries" 1414 // (and framework jars) into all available architectures. It's possible 1415 // to compile them only when we come across an app that uses them (there's 1416 // already logic for that in scanPackageLI) but that adds some complexity. 1417 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1418 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1419 final String lib = libEntry.path; 1420 if (lib == null) { 1421 continue; 1422 } 1423 1424 try { 1425 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1426 dexCodeInstructionSet, 1427 false); 1428 if (dexoptRequired != DexFile.UP_TO_DATE) { 1429 alreadyDexOpted.add(lib); 1430 1431 // The list of "shared libraries" we have at this point is 1432 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1433 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1434 } else { 1435 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1436 } 1437 didDexOptLibraryOrTool = true; 1438 } 1439 } catch (FileNotFoundException e) { 1440 Slog.w(TAG, "Library not found: " + lib); 1441 } catch (IOException e) { 1442 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1443 + e.getMessage()); 1444 } 1445 } 1446 } 1447 } 1448 1449 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1450 1451 // Gross hack for now: we know this file doesn't contain any 1452 // code, so don't dexopt it to avoid the resulting log spew. 1453 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1454 1455 // Gross hack for now: we know this file is only part of 1456 // the boot class path for art, so don't dexopt it to 1457 // avoid the resulting log spew. 1458 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1459 1460 /** 1461 * And there are a number of commands implemented in Java, which 1462 * we currently need to do the dexopt on so that they can be 1463 * run from a non-root shell. 1464 */ 1465 String[] frameworkFiles = frameworkDir.list(); 1466 if (frameworkFiles != null) { 1467 // TODO: We could compile these only for the most preferred ABI. We should 1468 // first double check that the dex files for these commands are not referenced 1469 // by other system apps. 1470 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1471 for (int i=0; i<frameworkFiles.length; i++) { 1472 File libPath = new File(frameworkDir, frameworkFiles[i]); 1473 String path = libPath.getPath(); 1474 // Skip the file if we already did it. 1475 if (alreadyDexOpted.contains(path)) { 1476 continue; 1477 } 1478 // Skip the file if it is not a type we want to dexopt. 1479 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1480 continue; 1481 } 1482 try { 1483 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1484 dexCodeInstructionSet, 1485 false); 1486 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1487 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1488 didDexOptLibraryOrTool = true; 1489 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1490 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1491 didDexOptLibraryOrTool = true; 1492 } 1493 } catch (FileNotFoundException e) { 1494 Slog.w(TAG, "Jar not found: " + path); 1495 } catch (IOException e) { 1496 Slog.w(TAG, "Exception reading jar: " + path, e); 1497 } 1498 } 1499 } 1500 } 1501 1502 if (didDexOptLibraryOrTool) { 1503 // If we dexopted a library or tool, then something on the system has 1504 // changed. Consider this significant, and wipe away all other 1505 // existing dexopt files to ensure we don't leave any dangling around. 1506 // 1507 // TODO: This should be revisited because it isn't as good an indicator 1508 // as it used to be. It used to include the boot classpath but at some point 1509 // DexFile.isDexOptNeeded started returning false for the boot 1510 // class path files in all cases. It is very possible in a 1511 // small maintenance release update that the library and tool 1512 // jars may be unchanged but APK could be removed resulting in 1513 // unused dalvik-cache files. 1514 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1515 mInstaller.pruneDexCache(dexCodeInstructionSet); 1516 } 1517 1518 // Additionally, delete all dex files from the root directory 1519 // since there shouldn't be any there anyway, unless we're upgrading 1520 // from an older OS version or a build that contained the "old" style 1521 // flat scheme. 1522 mInstaller.pruneDexCache("."); 1523 } 1524 1525 // Collect vendor overlay packages. 1526 // (Do this before scanning any apps.) 1527 // For security and version matching reason, only consider 1528 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1529 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1530 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1532 1533 // Find base frameworks (resource packages without code). 1534 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1535 | PackageParser.PARSE_IS_SYSTEM_DIR 1536 | PackageParser.PARSE_IS_PRIVILEGED, 1537 scanMode | SCAN_NO_DEX, 0); 1538 1539 // Collected privileged system packages. 1540 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1541 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1542 | PackageParser.PARSE_IS_SYSTEM_DIR 1543 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1544 1545 // Collect ordinary system packages. 1546 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1547 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1549 1550 // Collect all vendor packages. 1551 File vendorAppDir = new File("/vendor/app"); 1552 try { 1553 vendorAppDir = vendorAppDir.getCanonicalFile(); 1554 } catch (IOException e) { 1555 // failed to look up canonical path, continue with original one 1556 } 1557 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1559 1560 // Collect all OEM packages. 1561 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1562 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1564 1565 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1566 mInstaller.moveFiles(); 1567 1568 // Prune any system packages that no longer exist. 1569 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1570 if (!mOnlyCore) { 1571 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1572 while (psit.hasNext()) { 1573 PackageSetting ps = psit.next(); 1574 1575 /* 1576 * If this is not a system app, it can't be a 1577 * disable system app. 1578 */ 1579 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1580 continue; 1581 } 1582 1583 /* 1584 * If the package is scanned, it's not erased. 1585 */ 1586 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1587 if (scannedPkg != null) { 1588 /* 1589 * If the system app is both scanned and in the 1590 * disabled packages list, then it must have been 1591 * added via OTA. Remove it from the currently 1592 * scanned package so the previously user-installed 1593 * application can be scanned. 1594 */ 1595 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1596 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1597 + "; removing system app"); 1598 removePackageLI(ps, true); 1599 } 1600 1601 continue; 1602 } 1603 1604 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1605 psit.remove(); 1606 String msg = "System package " + ps.name 1607 + " no longer exists; wiping its data"; 1608 reportSettingsProblem(Log.WARN, msg); 1609 removeDataDirsLI(ps.name); 1610 } else { 1611 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1612 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1613 possiblyDeletedUpdatedSystemApps.add(ps.name); 1614 } 1615 } 1616 } 1617 } 1618 1619 //look for any incomplete package installations 1620 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1621 //clean up list 1622 for(int i = 0; i < deletePkgsList.size(); i++) { 1623 //clean up here 1624 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1625 } 1626 //delete tmp files 1627 deleteTempPackageFiles(); 1628 1629 // Remove any shared userIDs that have no associated packages 1630 mSettings.pruneSharedUsersLPw(); 1631 1632 if (!mOnlyCore) { 1633 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1634 SystemClock.uptimeMillis()); 1635 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1636 1637 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1638 scanMode, 0); 1639 1640 /** 1641 * Remove disable package settings for any updated system 1642 * apps that were removed via an OTA. If they're not a 1643 * previously-updated app, remove them completely. 1644 * Otherwise, just revoke their system-level permissions. 1645 */ 1646 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1647 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1648 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1649 1650 String msg; 1651 if (deletedPkg == null) { 1652 msg = "Updated system package " + deletedAppName 1653 + " no longer exists; wiping its data"; 1654 removeDataDirsLI(deletedAppName); 1655 } else { 1656 msg = "Updated system app + " + deletedAppName 1657 + " no longer present; removing system privileges for " 1658 + deletedAppName; 1659 1660 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1661 1662 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1663 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1664 } 1665 reportSettingsProblem(Log.WARN, msg); 1666 } 1667 } 1668 1669 // Now that we know all of the shared libraries, update all clients to have 1670 // the correct library paths. 1671 updateAllSharedLibrariesLPw(); 1672 1673 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1674 // NOTE: We ignore potential failures here during a system scan (like 1675 // the rest of the commands above) because there's precious little we 1676 // can do about it. A settings error is reported, though. 1677 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1678 false /* force dexopt */, false /* defer dexopt */); 1679 } 1680 1681 // Now that we know all the packages we are keeping, 1682 // read and update their last usage times. 1683 mPackageUsage.readLP(); 1684 1685 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1686 SystemClock.uptimeMillis()); 1687 Slog.i(TAG, "Time to scan packages: " 1688 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1689 + " seconds"); 1690 1691 // If the platform SDK has changed since the last time we booted, 1692 // we need to re-grant app permission to catch any new ones that 1693 // appear. This is really a hack, and means that apps can in some 1694 // cases get permissions that the user didn't initially explicitly 1695 // allow... it would be nice to have some better way to handle 1696 // this situation. 1697 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1698 != mSdkVersion; 1699 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1700 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1701 + "; regranting permissions for internal storage"); 1702 mSettings.mInternalSdkPlatform = mSdkVersion; 1703 1704 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1705 | (regrantPermissions 1706 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1707 : 0)); 1708 1709 // If this is the first boot, and it is a normal boot, then 1710 // we need to initialize the default preferred apps. 1711 if (!mRestoredSettings && !onlyCore) { 1712 mSettings.readDefaultPreferredAppsLPw(this, 0); 1713 } 1714 1715 // If this is first boot after an OTA, and a normal boot, then 1716 // we need to clear code cache directories. 1717 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1718 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1719 for (String pkgName : mSettings.mPackages.keySet()) { 1720 deleteCodeCacheDirsLI(pkgName); 1721 } 1722 mSettings.mFingerprint = Build.FINGERPRINT; 1723 } 1724 1725 // All the changes are done during package scanning. 1726 mSettings.updateInternalDatabaseVersion(); 1727 1728 // can downgrade to reader 1729 mSettings.writeLPr(); 1730 1731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1732 SystemClock.uptimeMillis()); 1733 1734 1735 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1736 } // synchronized (mPackages) 1737 } // synchronized (mInstallLock) 1738 1739 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1740 1741 // Now after opening every single application zip, make sure they 1742 // are all flushed. Not really needed, but keeps things nice and 1743 // tidy. 1744 Runtime.getRuntime().gc(); 1745 } 1746 1747 @Override 1748 public boolean isFirstBoot() { 1749 return !mRestoredSettings; 1750 } 1751 1752 @Override 1753 public boolean isOnlyCoreApps() { 1754 return mOnlyCore; 1755 } 1756 1757 private String getRequiredVerifierLPr() { 1758 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1759 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1760 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1761 1762 String requiredVerifier = null; 1763 1764 final int N = receivers.size(); 1765 for (int i = 0; i < N; i++) { 1766 final ResolveInfo info = receivers.get(i); 1767 1768 if (info.activityInfo == null) { 1769 continue; 1770 } 1771 1772 final String packageName = info.activityInfo.packageName; 1773 1774 final PackageSetting ps = mSettings.mPackages.get(packageName); 1775 if (ps == null) { 1776 continue; 1777 } 1778 1779 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1780 if (!gp.grantedPermissions 1781 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1782 continue; 1783 } 1784 1785 if (requiredVerifier != null) { 1786 throw new RuntimeException("There can be only one required verifier"); 1787 } 1788 1789 requiredVerifier = packageName; 1790 } 1791 1792 return requiredVerifier; 1793 } 1794 1795 @Override 1796 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1797 throws RemoteException { 1798 try { 1799 return super.onTransact(code, data, reply, flags); 1800 } catch (RuntimeException e) { 1801 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1802 Slog.wtf(TAG, "Package Manager Crash", e); 1803 } 1804 throw e; 1805 } 1806 } 1807 1808 void cleanupInstallFailedPackage(PackageSetting ps) { 1809 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1810 removeDataDirsLI(ps.name); 1811 1812 // TODO: try cleaning up codePath directory contents first, since it 1813 // might be a cluster 1814 1815 if (ps.codePath != null) { 1816 if (!ps.codePath.delete()) { 1817 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1818 } 1819 } 1820 if (ps.resourcePath != null) { 1821 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1822 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1823 } 1824 } 1825 mSettings.removePackageLPw(ps.name); 1826 } 1827 1828 static int[] appendInts(int[] cur, int[] add) { 1829 if (add == null) return cur; 1830 if (cur == null) return add; 1831 final int N = add.length; 1832 for (int i=0; i<N; i++) { 1833 cur = appendInt(cur, add[i]); 1834 } 1835 return cur; 1836 } 1837 1838 static int[] removeInts(int[] cur, int[] rem) { 1839 if (rem == null) return cur; 1840 if (cur == null) return cur; 1841 final int N = rem.length; 1842 for (int i=0; i<N; i++) { 1843 cur = removeInt(cur, rem[i]); 1844 } 1845 return cur; 1846 } 1847 1848 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1849 if (!sUserManager.exists(userId)) return null; 1850 final PackageSetting ps = (PackageSetting) p.mExtras; 1851 if (ps == null) { 1852 return null; 1853 } 1854 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1855 final PackageUserState state = ps.readUserState(userId); 1856 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1857 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1858 state, userId); 1859 } 1860 1861 @Override 1862 public boolean isPackageAvailable(String packageName, int userId) { 1863 if (!sUserManager.exists(userId)) return false; 1864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1865 synchronized (mPackages) { 1866 PackageParser.Package p = mPackages.get(packageName); 1867 if (p != null) { 1868 final PackageSetting ps = (PackageSetting) p.mExtras; 1869 if (ps != null) { 1870 final PackageUserState state = ps.readUserState(userId); 1871 if (state != null) { 1872 return PackageParser.isAvailable(state); 1873 } 1874 } 1875 } 1876 } 1877 return false; 1878 } 1879 1880 @Override 1881 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1882 if (!sUserManager.exists(userId)) return null; 1883 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1884 // reader 1885 synchronized (mPackages) { 1886 PackageParser.Package p = mPackages.get(packageName); 1887 if (DEBUG_PACKAGE_INFO) 1888 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1889 if (p != null) { 1890 return generatePackageInfo(p, flags, userId); 1891 } 1892 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1893 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1894 } 1895 } 1896 return null; 1897 } 1898 1899 @Override 1900 public String[] currentToCanonicalPackageNames(String[] names) { 1901 String[] out = new String[names.length]; 1902 // reader 1903 synchronized (mPackages) { 1904 for (int i=names.length-1; i>=0; i--) { 1905 PackageSetting ps = mSettings.mPackages.get(names[i]); 1906 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1907 } 1908 } 1909 return out; 1910 } 1911 1912 @Override 1913 public String[] canonicalToCurrentPackageNames(String[] names) { 1914 String[] out = new String[names.length]; 1915 // reader 1916 synchronized (mPackages) { 1917 for (int i=names.length-1; i>=0; i--) { 1918 String cur = mSettings.mRenamedPackages.get(names[i]); 1919 out[i] = cur != null ? cur : names[i]; 1920 } 1921 } 1922 return out; 1923 } 1924 1925 @Override 1926 public int getPackageUid(String packageName, int userId) { 1927 if (!sUserManager.exists(userId)) return -1; 1928 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1929 // reader 1930 synchronized (mPackages) { 1931 PackageParser.Package p = mPackages.get(packageName); 1932 if(p != null) { 1933 return UserHandle.getUid(userId, p.applicationInfo.uid); 1934 } 1935 PackageSetting ps = mSettings.mPackages.get(packageName); 1936 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1937 return -1; 1938 } 1939 p = ps.pkg; 1940 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1941 } 1942 } 1943 1944 @Override 1945 public int[] getPackageGids(String packageName) { 1946 // reader 1947 synchronized (mPackages) { 1948 PackageParser.Package p = mPackages.get(packageName); 1949 if (DEBUG_PACKAGE_INFO) 1950 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1951 if (p != null) { 1952 final PackageSetting ps = (PackageSetting)p.mExtras; 1953 return ps.getGids(); 1954 } 1955 } 1956 // stupid thing to indicate an error. 1957 return new int[0]; 1958 } 1959 1960 static final PermissionInfo generatePermissionInfo( 1961 BasePermission bp, int flags) { 1962 if (bp.perm != null) { 1963 return PackageParser.generatePermissionInfo(bp.perm, flags); 1964 } 1965 PermissionInfo pi = new PermissionInfo(); 1966 pi.name = bp.name; 1967 pi.packageName = bp.sourcePackage; 1968 pi.nonLocalizedLabel = bp.name; 1969 pi.protectionLevel = bp.protectionLevel; 1970 return pi; 1971 } 1972 1973 @Override 1974 public PermissionInfo getPermissionInfo(String name, int flags) { 1975 // reader 1976 synchronized (mPackages) { 1977 final BasePermission p = mSettings.mPermissions.get(name); 1978 if (p != null) { 1979 return generatePermissionInfo(p, flags); 1980 } 1981 return null; 1982 } 1983 } 1984 1985 @Override 1986 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1987 // reader 1988 synchronized (mPackages) { 1989 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1990 for (BasePermission p : mSettings.mPermissions.values()) { 1991 if (group == null) { 1992 if (p.perm == null || p.perm.info.group == null) { 1993 out.add(generatePermissionInfo(p, flags)); 1994 } 1995 } else { 1996 if (p.perm != null && group.equals(p.perm.info.group)) { 1997 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1998 } 1999 } 2000 } 2001 2002 if (out.size() > 0) { 2003 return out; 2004 } 2005 return mPermissionGroups.containsKey(group) ? out : null; 2006 } 2007 } 2008 2009 @Override 2010 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2011 // reader 2012 synchronized (mPackages) { 2013 return PackageParser.generatePermissionGroupInfo( 2014 mPermissionGroups.get(name), flags); 2015 } 2016 } 2017 2018 @Override 2019 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 final int N = mPermissionGroups.size(); 2023 ArrayList<PermissionGroupInfo> out 2024 = new ArrayList<PermissionGroupInfo>(N); 2025 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2026 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2027 } 2028 return out; 2029 } 2030 } 2031 2032 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2033 int userId) { 2034 if (!sUserManager.exists(userId)) return null; 2035 PackageSetting ps = mSettings.mPackages.get(packageName); 2036 if (ps != null) { 2037 if (ps.pkg == null) { 2038 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2039 flags, userId); 2040 if (pInfo != null) { 2041 return pInfo.applicationInfo; 2042 } 2043 return null; 2044 } 2045 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2046 ps.readUserState(userId), userId); 2047 } 2048 return null; 2049 } 2050 2051 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2052 int userId) { 2053 if (!sUserManager.exists(userId)) return null; 2054 PackageSetting ps = mSettings.mPackages.get(packageName); 2055 if (ps != null) { 2056 PackageParser.Package pkg = ps.pkg; 2057 if (pkg == null) { 2058 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2059 return null; 2060 } 2061 // Only data remains, so we aren't worried about code paths 2062 pkg = new PackageParser.Package(packageName); 2063 pkg.applicationInfo.packageName = packageName; 2064 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2065 pkg.applicationInfo.dataDir = 2066 getDataPathForPackage(packageName, 0).getPath(); 2067 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2068 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2069 } 2070 return generatePackageInfo(pkg, flags, userId); 2071 } 2072 return null; 2073 } 2074 2075 @Override 2076 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2077 if (!sUserManager.exists(userId)) return null; 2078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2079 // writer 2080 synchronized (mPackages) { 2081 PackageParser.Package p = mPackages.get(packageName); 2082 if (DEBUG_PACKAGE_INFO) Log.v( 2083 TAG, "getApplicationInfo " + packageName 2084 + ": " + p); 2085 if (p != null) { 2086 PackageSetting ps = mSettings.mPackages.get(packageName); 2087 if (ps == null) return null; 2088 // Note: isEnabledLP() does not apply here - always return info 2089 return PackageParser.generateApplicationInfo( 2090 p, flags, ps.readUserState(userId), userId); 2091 } 2092 if ("android".equals(packageName)||"system".equals(packageName)) { 2093 return mAndroidApplication; 2094 } 2095 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2096 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2097 } 2098 } 2099 return null; 2100 } 2101 2102 2103 @Override 2104 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2105 mContext.enforceCallingOrSelfPermission( 2106 android.Manifest.permission.CLEAR_APP_CACHE, null); 2107 // Queue up an async operation since clearing cache may take a little while. 2108 mHandler.post(new Runnable() { 2109 public void run() { 2110 mHandler.removeCallbacks(this); 2111 int retCode = -1; 2112 synchronized (mInstallLock) { 2113 retCode = mInstaller.freeCache(freeStorageSize); 2114 if (retCode < 0) { 2115 Slog.w(TAG, "Couldn't clear application caches"); 2116 } 2117 } 2118 if (observer != null) { 2119 try { 2120 observer.onRemoveCompleted(null, (retCode >= 0)); 2121 } catch (RemoteException e) { 2122 Slog.w(TAG, "RemoveException when invoking call back"); 2123 } 2124 } 2125 } 2126 }); 2127 } 2128 2129 @Override 2130 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2131 mContext.enforceCallingOrSelfPermission( 2132 android.Manifest.permission.CLEAR_APP_CACHE, null); 2133 // Queue up an async operation since clearing cache may take a little while. 2134 mHandler.post(new Runnable() { 2135 public void run() { 2136 mHandler.removeCallbacks(this); 2137 int retCode = -1; 2138 synchronized (mInstallLock) { 2139 retCode = mInstaller.freeCache(freeStorageSize); 2140 if (retCode < 0) { 2141 Slog.w(TAG, "Couldn't clear application caches"); 2142 } 2143 } 2144 if(pi != null) { 2145 try { 2146 // Callback via pending intent 2147 int code = (retCode >= 0) ? 1 : 0; 2148 pi.sendIntent(null, code, null, 2149 null, null); 2150 } catch (SendIntentException e1) { 2151 Slog.i(TAG, "Failed to send pending intent"); 2152 } 2153 } 2154 } 2155 }); 2156 } 2157 2158 void freeStorage(long freeStorageSize) throws IOException { 2159 synchronized (mInstallLock) { 2160 if (mInstaller.freeCache(freeStorageSize) < 0) { 2161 throw new IOException("Failed to free enough space"); 2162 } 2163 } 2164 } 2165 2166 @Override 2167 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2168 if (!sUserManager.exists(userId)) return null; 2169 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2170 synchronized (mPackages) { 2171 PackageParser.Activity a = mActivities.mActivities.get(component); 2172 2173 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2174 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2175 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2176 if (ps == null) return null; 2177 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2178 userId); 2179 } 2180 if (mResolveComponentName.equals(component)) { 2181 return mResolveActivity; 2182 } 2183 } 2184 return null; 2185 } 2186 2187 @Override 2188 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2189 String resolvedType) { 2190 synchronized (mPackages) { 2191 PackageParser.Activity a = mActivities.mActivities.get(component); 2192 if (a == null) { 2193 return false; 2194 } 2195 for (int i=0; i<a.intents.size(); i++) { 2196 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2197 intent.getData(), intent.getCategories(), TAG) >= 0) { 2198 return true; 2199 } 2200 } 2201 return false; 2202 } 2203 } 2204 2205 @Override 2206 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2207 if (!sUserManager.exists(userId)) return null; 2208 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2209 synchronized (mPackages) { 2210 PackageParser.Activity a = mReceivers.mActivities.get(component); 2211 if (DEBUG_PACKAGE_INFO) Log.v( 2212 TAG, "getReceiverInfo " + component + ": " + a); 2213 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2214 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2215 if (ps == null) return null; 2216 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2217 userId); 2218 } 2219 } 2220 return null; 2221 } 2222 2223 @Override 2224 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2225 if (!sUserManager.exists(userId)) return null; 2226 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2227 synchronized (mPackages) { 2228 PackageParser.Service s = mServices.mServices.get(component); 2229 if (DEBUG_PACKAGE_INFO) Log.v( 2230 TAG, "getServiceInfo " + component + ": " + s); 2231 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2232 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2233 if (ps == null) return null; 2234 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2235 userId); 2236 } 2237 } 2238 return null; 2239 } 2240 2241 @Override 2242 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2243 if (!sUserManager.exists(userId)) return null; 2244 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2245 synchronized (mPackages) { 2246 PackageParser.Provider p = mProviders.mProviders.get(component); 2247 if (DEBUG_PACKAGE_INFO) Log.v( 2248 TAG, "getProviderInfo " + component + ": " + p); 2249 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2250 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2251 if (ps == null) return null; 2252 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2253 userId); 2254 } 2255 } 2256 return null; 2257 } 2258 2259 @Override 2260 public String[] getSystemSharedLibraryNames() { 2261 Set<String> libSet; 2262 synchronized (mPackages) { 2263 libSet = mSharedLibraries.keySet(); 2264 int size = libSet.size(); 2265 if (size > 0) { 2266 String[] libs = new String[size]; 2267 libSet.toArray(libs); 2268 return libs; 2269 } 2270 } 2271 return null; 2272 } 2273 2274 @Override 2275 public FeatureInfo[] getSystemAvailableFeatures() { 2276 Collection<FeatureInfo> featSet; 2277 synchronized (mPackages) { 2278 featSet = mAvailableFeatures.values(); 2279 int size = featSet.size(); 2280 if (size > 0) { 2281 FeatureInfo[] features = new FeatureInfo[size+1]; 2282 featSet.toArray(features); 2283 FeatureInfo fi = new FeatureInfo(); 2284 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2285 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2286 features[size] = fi; 2287 return features; 2288 } 2289 } 2290 return null; 2291 } 2292 2293 @Override 2294 public boolean hasSystemFeature(String name) { 2295 synchronized (mPackages) { 2296 return mAvailableFeatures.containsKey(name); 2297 } 2298 } 2299 2300 private void checkValidCaller(int uid, int userId) { 2301 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2302 return; 2303 2304 throw new SecurityException("Caller uid=" + uid 2305 + " is not privileged to communicate with user=" + userId); 2306 } 2307 2308 @Override 2309 public int checkPermission(String permName, String pkgName) { 2310 synchronized (mPackages) { 2311 PackageParser.Package p = mPackages.get(pkgName); 2312 if (p != null && p.mExtras != null) { 2313 PackageSetting ps = (PackageSetting)p.mExtras; 2314 if (ps.sharedUser != null) { 2315 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } else if (ps.grantedPermissions.contains(permName)) { 2319 return PackageManager.PERMISSION_GRANTED; 2320 } 2321 } 2322 } 2323 return PackageManager.PERMISSION_DENIED; 2324 } 2325 2326 @Override 2327 public int checkUidPermission(String permName, int uid) { 2328 synchronized (mPackages) { 2329 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2330 if (obj != null) { 2331 GrantedPermissions gp = (GrantedPermissions)obj; 2332 if (gp.grantedPermissions.contains(permName)) { 2333 return PackageManager.PERMISSION_GRANTED; 2334 } 2335 } else { 2336 HashSet<String> perms = mSystemPermissions.get(uid); 2337 if (perms != null && perms.contains(permName)) { 2338 return PackageManager.PERMISSION_GRANTED; 2339 } 2340 } 2341 } 2342 return PackageManager.PERMISSION_DENIED; 2343 } 2344 2345 /** 2346 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2347 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2348 * @param message the message to log on security exception 2349 */ 2350 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2351 String message) { 2352 if (userId < 0) { 2353 throw new IllegalArgumentException("Invalid userId " + userId); 2354 } 2355 if (userId == UserHandle.getUserId(callingUid)) return; 2356 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2357 if (requireFullPermission) { 2358 mContext.enforceCallingOrSelfPermission( 2359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2360 } else { 2361 try { 2362 mContext.enforceCallingOrSelfPermission( 2363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2364 } catch (SecurityException se) { 2365 mContext.enforceCallingOrSelfPermission( 2366 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2367 } 2368 } 2369 } 2370 } 2371 2372 private BasePermission findPermissionTreeLP(String permName) { 2373 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2374 if (permName.startsWith(bp.name) && 2375 permName.length() > bp.name.length() && 2376 permName.charAt(bp.name.length()) == '.') { 2377 return bp; 2378 } 2379 } 2380 return null; 2381 } 2382 2383 private BasePermission checkPermissionTreeLP(String permName) { 2384 if (permName != null) { 2385 BasePermission bp = findPermissionTreeLP(permName); 2386 if (bp != null) { 2387 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2388 return bp; 2389 } 2390 throw new SecurityException("Calling uid " 2391 + Binder.getCallingUid() 2392 + " is not allowed to add to permission tree " 2393 + bp.name + " owned by uid " + bp.uid); 2394 } 2395 } 2396 throw new SecurityException("No permission tree found for " + permName); 2397 } 2398 2399 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2400 if (s1 == null) { 2401 return s2 == null; 2402 } 2403 if (s2 == null) { 2404 return false; 2405 } 2406 if (s1.getClass() != s2.getClass()) { 2407 return false; 2408 } 2409 return s1.equals(s2); 2410 } 2411 2412 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2413 if (pi1.icon != pi2.icon) return false; 2414 if (pi1.logo != pi2.logo) return false; 2415 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2416 if (!compareStrings(pi1.name, pi2.name)) return false; 2417 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2418 // We'll take care of setting this one. 2419 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2420 // These are not currently stored in settings. 2421 //if (!compareStrings(pi1.group, pi2.group)) return false; 2422 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2423 //if (pi1.labelRes != pi2.labelRes) return false; 2424 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2425 return true; 2426 } 2427 2428 int permissionInfoFootprint(PermissionInfo info) { 2429 int size = info.name.length(); 2430 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2431 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2432 return size; 2433 } 2434 2435 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2436 int size = 0; 2437 for (BasePermission perm : mSettings.mPermissions.values()) { 2438 if (perm.uid == tree.uid) { 2439 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2440 } 2441 } 2442 return size; 2443 } 2444 2445 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2446 // We calculate the max size of permissions defined by this uid and throw 2447 // if that plus the size of 'info' would exceed our stated maximum. 2448 if (tree.uid != Process.SYSTEM_UID) { 2449 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2450 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2451 throw new SecurityException("Permission tree size cap exceeded"); 2452 } 2453 } 2454 } 2455 2456 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2457 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2458 throw new SecurityException("Label must be specified in permission"); 2459 } 2460 BasePermission tree = checkPermissionTreeLP(info.name); 2461 BasePermission bp = mSettings.mPermissions.get(info.name); 2462 boolean added = bp == null; 2463 boolean changed = true; 2464 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2465 if (added) { 2466 enforcePermissionCapLocked(info, tree); 2467 bp = new BasePermission(info.name, tree.sourcePackage, 2468 BasePermission.TYPE_DYNAMIC); 2469 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2470 throw new SecurityException( 2471 "Not allowed to modify non-dynamic permission " 2472 + info.name); 2473 } else { 2474 if (bp.protectionLevel == fixedLevel 2475 && bp.perm.owner.equals(tree.perm.owner) 2476 && bp.uid == tree.uid 2477 && comparePermissionInfos(bp.perm.info, info)) { 2478 changed = false; 2479 } 2480 } 2481 bp.protectionLevel = fixedLevel; 2482 info = new PermissionInfo(info); 2483 info.protectionLevel = fixedLevel; 2484 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2485 bp.perm.info.packageName = tree.perm.info.packageName; 2486 bp.uid = tree.uid; 2487 if (added) { 2488 mSettings.mPermissions.put(info.name, bp); 2489 } 2490 if (changed) { 2491 if (!async) { 2492 mSettings.writeLPr(); 2493 } else { 2494 scheduleWriteSettingsLocked(); 2495 } 2496 } 2497 return added; 2498 } 2499 2500 @Override 2501 public boolean addPermission(PermissionInfo info) { 2502 synchronized (mPackages) { 2503 return addPermissionLocked(info, false); 2504 } 2505 } 2506 2507 @Override 2508 public boolean addPermissionAsync(PermissionInfo info) { 2509 synchronized (mPackages) { 2510 return addPermissionLocked(info, true); 2511 } 2512 } 2513 2514 @Override 2515 public void removePermission(String name) { 2516 synchronized (mPackages) { 2517 checkPermissionTreeLP(name); 2518 BasePermission bp = mSettings.mPermissions.get(name); 2519 if (bp != null) { 2520 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2521 throw new SecurityException( 2522 "Not allowed to modify non-dynamic permission " 2523 + name); 2524 } 2525 mSettings.mPermissions.remove(name); 2526 mSettings.writeLPr(); 2527 } 2528 } 2529 } 2530 2531 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2532 int index = pkg.requestedPermissions.indexOf(bp.name); 2533 if (index == -1) { 2534 throw new SecurityException("Package " + pkg.packageName 2535 + " has not requested permission " + bp.name); 2536 } 2537 boolean isNormal = 2538 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2539 == PermissionInfo.PROTECTION_NORMAL); 2540 boolean isDangerous = 2541 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2542 == PermissionInfo.PROTECTION_DANGEROUS); 2543 boolean isDevelopment = 2544 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2545 2546 if (!isNormal && !isDangerous && !isDevelopment) { 2547 throw new SecurityException("Permission " + bp.name 2548 + " is not a changeable permission type"); 2549 } 2550 2551 if (isNormal || isDangerous) { 2552 if (pkg.requestedPermissionsRequired.get(index)) { 2553 throw new SecurityException("Can't change " + bp.name 2554 + ". It is required by the application"); 2555 } 2556 } 2557 } 2558 2559 @Override 2560 public void grantPermission(String packageName, String permissionName) { 2561 mContext.enforceCallingOrSelfPermission( 2562 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2563 synchronized (mPackages) { 2564 final PackageParser.Package pkg = mPackages.get(packageName); 2565 if (pkg == null) { 2566 throw new IllegalArgumentException("Unknown package: " + packageName); 2567 } 2568 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2569 if (bp == null) { 2570 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2571 } 2572 2573 checkGrantRevokePermissions(pkg, bp); 2574 2575 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2576 if (ps == null) { 2577 return; 2578 } 2579 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2580 if (gp.grantedPermissions.add(permissionName)) { 2581 if (ps.haveGids) { 2582 gp.gids = appendInts(gp.gids, bp.gids); 2583 } 2584 mSettings.writeLPr(); 2585 } 2586 } 2587 } 2588 2589 @Override 2590 public void revokePermission(String packageName, String permissionName) { 2591 int changedAppId = -1; 2592 2593 synchronized (mPackages) { 2594 final PackageParser.Package pkg = mPackages.get(packageName); 2595 if (pkg == null) { 2596 throw new IllegalArgumentException("Unknown package: " + packageName); 2597 } 2598 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2599 mContext.enforceCallingOrSelfPermission( 2600 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2601 } 2602 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2603 if (bp == null) { 2604 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2605 } 2606 2607 checkGrantRevokePermissions(pkg, bp); 2608 2609 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2610 if (ps == null) { 2611 return; 2612 } 2613 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2614 if (gp.grantedPermissions.remove(permissionName)) { 2615 gp.grantedPermissions.remove(permissionName); 2616 if (ps.haveGids) { 2617 gp.gids = removeInts(gp.gids, bp.gids); 2618 } 2619 mSettings.writeLPr(); 2620 changedAppId = ps.appId; 2621 } 2622 } 2623 2624 if (changedAppId >= 0) { 2625 // We changed the perm on someone, kill its processes. 2626 IActivityManager am = ActivityManagerNative.getDefault(); 2627 if (am != null) { 2628 final int callingUserId = UserHandle.getCallingUserId(); 2629 final long ident = Binder.clearCallingIdentity(); 2630 try { 2631 //XXX we should only revoke for the calling user's app permissions, 2632 // but for now we impact all users. 2633 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2634 // "revoke " + permissionName); 2635 int[] users = sUserManager.getUserIds(); 2636 for (int user : users) { 2637 am.killUid(UserHandle.getUid(user, changedAppId), 2638 "revoke " + permissionName); 2639 } 2640 } catch (RemoteException e) { 2641 } finally { 2642 Binder.restoreCallingIdentity(ident); 2643 } 2644 } 2645 } 2646 } 2647 2648 @Override 2649 public boolean isProtectedBroadcast(String actionName) { 2650 synchronized (mPackages) { 2651 return mProtectedBroadcasts.contains(actionName); 2652 } 2653 } 2654 2655 @Override 2656 public int checkSignatures(String pkg1, String pkg2) { 2657 synchronized (mPackages) { 2658 final PackageParser.Package p1 = mPackages.get(pkg1); 2659 final PackageParser.Package p2 = mPackages.get(pkg2); 2660 if (p1 == null || p1.mExtras == null 2661 || p2 == null || p2.mExtras == null) { 2662 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2663 } 2664 return compareSignatures(p1.mSignatures, p2.mSignatures); 2665 } 2666 } 2667 2668 @Override 2669 public int checkUidSignatures(int uid1, int uid2) { 2670 // Map to base uids. 2671 uid1 = UserHandle.getAppId(uid1); 2672 uid2 = UserHandle.getAppId(uid2); 2673 // reader 2674 synchronized (mPackages) { 2675 Signature[] s1; 2676 Signature[] s2; 2677 Object obj = mSettings.getUserIdLPr(uid1); 2678 if (obj != null) { 2679 if (obj instanceof SharedUserSetting) { 2680 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2681 } else if (obj instanceof PackageSetting) { 2682 s1 = ((PackageSetting)obj).signatures.mSignatures; 2683 } else { 2684 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2685 } 2686 } else { 2687 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2688 } 2689 obj = mSettings.getUserIdLPr(uid2); 2690 if (obj != null) { 2691 if (obj instanceof SharedUserSetting) { 2692 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2693 } else if (obj instanceof PackageSetting) { 2694 s2 = ((PackageSetting)obj).signatures.mSignatures; 2695 } else { 2696 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2697 } 2698 } else { 2699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2700 } 2701 return compareSignatures(s1, s2); 2702 } 2703 } 2704 2705 /** 2706 * Compares two sets of signatures. Returns: 2707 * <br /> 2708 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2709 * <br /> 2710 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2715 * <br /> 2716 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2717 */ 2718 static int compareSignatures(Signature[] s1, Signature[] s2) { 2719 if (s1 == null) { 2720 return s2 == null 2721 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2722 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2723 } 2724 2725 if (s2 == null) { 2726 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2727 } 2728 2729 if (s1.length != s2.length) { 2730 return PackageManager.SIGNATURE_NO_MATCH; 2731 } 2732 2733 // Since both signature sets are of size 1, we can compare without HashSets. 2734 if (s1.length == 1) { 2735 return s1[0].equals(s2[0]) ? 2736 PackageManager.SIGNATURE_MATCH : 2737 PackageManager.SIGNATURE_NO_MATCH; 2738 } 2739 2740 HashSet<Signature> set1 = new HashSet<Signature>(); 2741 for (Signature sig : s1) { 2742 set1.add(sig); 2743 } 2744 HashSet<Signature> set2 = new HashSet<Signature>(); 2745 for (Signature sig : s2) { 2746 set2.add(sig); 2747 } 2748 // Make sure s2 contains all signatures in s1. 2749 if (set1.equals(set2)) { 2750 return PackageManager.SIGNATURE_MATCH; 2751 } 2752 return PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 /** 2756 * If the database version for this type of package (internal storage or 2757 * external storage) is less than the version where package signatures 2758 * were updated, return true. 2759 */ 2760 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2761 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2762 DatabaseVersion.SIGNATURE_END_ENTITY)) 2763 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2764 DatabaseVersion.SIGNATURE_END_ENTITY)); 2765 } 2766 2767 /** 2768 * Used for backward compatibility to make sure any packages with 2769 * certificate chains get upgraded to the new style. {@code existingSigs} 2770 * will be in the old format (since they were stored on disk from before the 2771 * system upgrade) and {@code scannedSigs} will be in the newer format. 2772 */ 2773 private int compareSignaturesCompat(PackageSignatures existingSigs, 2774 PackageParser.Package scannedPkg) { 2775 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2776 return PackageManager.SIGNATURE_NO_MATCH; 2777 } 2778 2779 HashSet<Signature> existingSet = new HashSet<Signature>(); 2780 for (Signature sig : existingSigs.mSignatures) { 2781 existingSet.add(sig); 2782 } 2783 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2784 for (Signature sig : scannedPkg.mSignatures) { 2785 try { 2786 Signature[] chainSignatures = sig.getChainSignatures(); 2787 for (Signature chainSig : chainSignatures) { 2788 scannedCompatSet.add(chainSig); 2789 } 2790 } catch (CertificateEncodingException e) { 2791 scannedCompatSet.add(sig); 2792 } 2793 } 2794 /* 2795 * Make sure the expanded scanned set contains all signatures in the 2796 * existing one. 2797 */ 2798 if (scannedCompatSet.equals(existingSet)) { 2799 // Migrate the old signatures to the new scheme. 2800 existingSigs.assignSignatures(scannedPkg.mSignatures); 2801 // The new KeySets will be re-added later in the scanning process. 2802 synchronized (mPackages) { 2803 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2804 } 2805 return PackageManager.SIGNATURE_MATCH; 2806 } 2807 return PackageManager.SIGNATURE_NO_MATCH; 2808 } 2809 2810 @Override 2811 public String[] getPackagesForUid(int uid) { 2812 uid = UserHandle.getAppId(uid); 2813 // reader 2814 synchronized (mPackages) { 2815 Object obj = mSettings.getUserIdLPr(uid); 2816 if (obj instanceof SharedUserSetting) { 2817 final SharedUserSetting sus = (SharedUserSetting) obj; 2818 final int N = sus.packages.size(); 2819 final String[] res = new String[N]; 2820 final Iterator<PackageSetting> it = sus.packages.iterator(); 2821 int i = 0; 2822 while (it.hasNext()) { 2823 res[i++] = it.next().name; 2824 } 2825 return res; 2826 } else if (obj instanceof PackageSetting) { 2827 final PackageSetting ps = (PackageSetting) obj; 2828 return new String[] { ps.name }; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public String getNameForUid(int uid) { 2836 // reader 2837 synchronized (mPackages) { 2838 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2839 if (obj instanceof SharedUserSetting) { 2840 final SharedUserSetting sus = (SharedUserSetting) obj; 2841 return sus.name + ":" + sus.userId; 2842 } else if (obj instanceof PackageSetting) { 2843 final PackageSetting ps = (PackageSetting) obj; 2844 return ps.name; 2845 } 2846 } 2847 return null; 2848 } 2849 2850 @Override 2851 public int getUidForSharedUser(String sharedUserName) { 2852 if(sharedUserName == null) { 2853 return -1; 2854 } 2855 // reader 2856 synchronized (mPackages) { 2857 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2858 if (suid == null) { 2859 return -1; 2860 } 2861 return suid.userId; 2862 } 2863 } 2864 2865 @Override 2866 public int getFlagsForUid(int uid) { 2867 synchronized (mPackages) { 2868 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2869 if (obj instanceof SharedUserSetting) { 2870 final SharedUserSetting sus = (SharedUserSetting) obj; 2871 return sus.pkgFlags; 2872 } else if (obj instanceof PackageSetting) { 2873 final PackageSetting ps = (PackageSetting) obj; 2874 return ps.pkgFlags; 2875 } 2876 } 2877 return 0; 2878 } 2879 2880 @Override 2881 public String[] getAppOpPermissionPackages(String permissionName) { 2882 synchronized (mPackages) { 2883 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2884 if (pkgs == null) { 2885 return null; 2886 } 2887 return pkgs.toArray(new String[pkgs.size()]); 2888 } 2889 } 2890 2891 @Override 2892 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2893 int flags, int userId) { 2894 if (!sUserManager.exists(userId)) return null; 2895 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2896 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2897 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2898 } 2899 2900 @Override 2901 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2902 IntentFilter filter, int match, ComponentName activity) { 2903 final int userId = UserHandle.getCallingUserId(); 2904 if (DEBUG_PREFERRED) { 2905 Log.v(TAG, "setLastChosenActivity intent=" + intent 2906 + " resolvedType=" + resolvedType 2907 + " flags=" + flags 2908 + " filter=" + filter 2909 + " match=" + match 2910 + " activity=" + activity); 2911 filter.dump(new PrintStreamPrinter(System.out), " "); 2912 } 2913 intent.setComponent(null); 2914 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2915 // Find any earlier preferred or last chosen entries and nuke them 2916 findPreferredActivity(intent, resolvedType, 2917 flags, query, 0, false, true, false, userId); 2918 // Add the new activity as the last chosen for this filter 2919 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2920 } 2921 2922 @Override 2923 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2924 final int userId = UserHandle.getCallingUserId(); 2925 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2926 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2927 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2928 false, false, false, userId); 2929 } 2930 2931 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2932 int flags, List<ResolveInfo> query, int userId) { 2933 if (query != null) { 2934 final int N = query.size(); 2935 if (N == 1) { 2936 return query.get(0); 2937 } else if (N > 1) { 2938 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2939 // If there is more than one activity with the same priority, 2940 // then let the user decide between them. 2941 ResolveInfo r0 = query.get(0); 2942 ResolveInfo r1 = query.get(1); 2943 if (DEBUG_INTENT_MATCHING || debug) { 2944 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2945 + r1.activityInfo.name + "=" + r1.priority); 2946 } 2947 // If the first activity has a higher priority, or a different 2948 // default, then it is always desireable to pick it. 2949 if (r0.priority != r1.priority 2950 || r0.preferredOrder != r1.preferredOrder 2951 || r0.isDefault != r1.isDefault) { 2952 return query.get(0); 2953 } 2954 // If we have saved a preference for a preferred activity for 2955 // this Intent, use that. 2956 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2957 flags, query, r0.priority, true, false, debug, userId); 2958 if (ri != null) { 2959 return ri; 2960 } 2961 if (userId != 0) { 2962 ri = new ResolveInfo(mResolveInfo); 2963 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2964 ri.activityInfo.applicationInfo = new ApplicationInfo( 2965 ri.activityInfo.applicationInfo); 2966 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2967 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2968 return ri; 2969 } 2970 return mResolveInfo; 2971 } 2972 } 2973 return null; 2974 } 2975 2976 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2977 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2978 final int N = query.size(); 2979 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2980 .get(userId); 2981 // Get the list of persistent preferred activities that handle the intent 2982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2983 List<PersistentPreferredActivity> pprefs = ppir != null 2984 ? ppir.queryIntent(intent, resolvedType, 2985 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2986 : null; 2987 if (pprefs != null && pprefs.size() > 0) { 2988 final int M = pprefs.size(); 2989 for (int i=0; i<M; i++) { 2990 final PersistentPreferredActivity ppa = pprefs.get(i); 2991 if (DEBUG_PREFERRED || debug) { 2992 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2993 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2994 + "\n component=" + ppa.mComponent); 2995 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2996 } 2997 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2998 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2999 if (DEBUG_PREFERRED || debug) { 3000 Slog.v(TAG, "Found persistent preferred activity:"); 3001 if (ai != null) { 3002 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3003 } else { 3004 Slog.v(TAG, " null"); 3005 } 3006 } 3007 if (ai == null) { 3008 // This previously registered persistent preferred activity 3009 // component is no longer known. Ignore it and do NOT remove it. 3010 continue; 3011 } 3012 for (int j=0; j<N; j++) { 3013 final ResolveInfo ri = query.get(j); 3014 if (!ri.activityInfo.applicationInfo.packageName 3015 .equals(ai.applicationInfo.packageName)) { 3016 continue; 3017 } 3018 if (!ri.activityInfo.name.equals(ai.name)) { 3019 continue; 3020 } 3021 // Found a persistent preference that can handle the intent. 3022 if (DEBUG_PREFERRED || debug) { 3023 Slog.v(TAG, "Returning persistent preferred activity: " + 3024 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3025 } 3026 return ri; 3027 } 3028 } 3029 } 3030 return null; 3031 } 3032 3033 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3034 List<ResolveInfo> query, int priority, boolean always, 3035 boolean removeMatches, boolean debug, int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 // writer 3038 synchronized (mPackages) { 3039 if (intent.getSelector() != null) { 3040 intent = intent.getSelector(); 3041 } 3042 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3043 3044 // Try to find a matching persistent preferred activity. 3045 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3046 debug, userId); 3047 3048 // If a persistent preferred activity matched, use it. 3049 if (pri != null) { 3050 return pri; 3051 } 3052 3053 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3054 // Get the list of preferred activities that handle the intent 3055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3056 List<PreferredActivity> prefs = pir != null 3057 ? pir.queryIntent(intent, resolvedType, 3058 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3059 : null; 3060 if (prefs != null && prefs.size() > 0) { 3061 // First figure out how good the original match set is. 3062 // We will only allow preferred activities that came 3063 // from the same match quality. 3064 int match = 0; 3065 3066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3067 3068 final int N = query.size(); 3069 for (int j=0; j<N; j++) { 3070 final ResolveInfo ri = query.get(j); 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3072 + ": 0x" + Integer.toHexString(match)); 3073 if (ri.match > match) { 3074 match = ri.match; 3075 } 3076 } 3077 3078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3079 + Integer.toHexString(match)); 3080 3081 match &= IntentFilter.MATCH_CATEGORY_MASK; 3082 final int M = prefs.size(); 3083 for (int i=0; i<M; i++) { 3084 final PreferredActivity pa = prefs.get(i); 3085 if (DEBUG_PREFERRED || debug) { 3086 Slog.v(TAG, "Checking PreferredActivity ds=" 3087 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3088 + "\n component=" + pa.mPref.mComponent); 3089 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3090 } 3091 if (pa.mPref.mMatch != match) { 3092 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3093 + Integer.toHexString(pa.mPref.mMatch)); 3094 continue; 3095 } 3096 // If it's not an "always" type preferred activity and that's what we're 3097 // looking for, skip it. 3098 if (always && !pa.mPref.mAlways) { 3099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3100 continue; 3101 } 3102 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3103 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3104 if (DEBUG_PREFERRED || debug) { 3105 Slog.v(TAG, "Found preferred activity:"); 3106 if (ai != null) { 3107 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3108 } else { 3109 Slog.v(TAG, " null"); 3110 } 3111 } 3112 if (ai == null) { 3113 // This previously registered preferred activity 3114 // component is no longer known. Most likely an update 3115 // to the app was installed and in the new version this 3116 // component no longer exists. Clean it up by removing 3117 // it from the preferred activities list, and skip it. 3118 Slog.w(TAG, "Removing dangling preferred activity: " 3119 + pa.mPref.mComponent); 3120 pir.removeFilter(pa); 3121 continue; 3122 } 3123 for (int j=0; j<N; j++) { 3124 final ResolveInfo ri = query.get(j); 3125 if (!ri.activityInfo.applicationInfo.packageName 3126 .equals(ai.applicationInfo.packageName)) { 3127 continue; 3128 } 3129 if (!ri.activityInfo.name.equals(ai.name)) { 3130 continue; 3131 } 3132 3133 if (removeMatches) { 3134 pir.removeFilter(pa); 3135 if (DEBUG_PREFERRED) { 3136 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3137 } 3138 break; 3139 } 3140 3141 // Okay we found a previously set preferred or last chosen app. 3142 // If the result set is different from when this 3143 // was created, we need to clear it and re-ask the 3144 // user their preference, if we're looking for an "always" type entry. 3145 if (always && !pa.mPref.sameSet(query, priority)) { 3146 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3147 + intent + " type " + resolvedType); 3148 if (DEBUG_PREFERRED) { 3149 Slog.v(TAG, "Removing preferred activity since set changed " 3150 + pa.mPref.mComponent); 3151 } 3152 pir.removeFilter(pa); 3153 // Re-add the filter as a "last chosen" entry (!always) 3154 PreferredActivity lastChosen = new PreferredActivity( 3155 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3156 pir.addFilter(lastChosen); 3157 mSettings.writePackageRestrictionsLPr(userId); 3158 return null; 3159 } 3160 3161 // Yay! Either the set matched or we're looking for the last chosen 3162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3163 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3164 mSettings.writePackageRestrictionsLPr(userId); 3165 return ri; 3166 } 3167 } 3168 } 3169 mSettings.writePackageRestrictionsLPr(userId); 3170 } 3171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3172 return null; 3173 } 3174 3175 /* 3176 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3177 */ 3178 @Override 3179 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3180 int targetUserId) { 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3183 List<CrossProfileIntentFilter> matches = 3184 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3185 if (matches != null) { 3186 int size = matches.size(); 3187 for (int i = 0; i < size; i++) { 3188 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3189 } 3190 } 3191 3192 ArrayList<String> packageNames = null; 3193 SparseArray<ArrayList<String>> fromSource = 3194 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3195 if (fromSource != null) { 3196 packageNames = fromSource.get(targetUserId); 3197 } 3198 if (packageNames.contains(intent.getPackage())) { 3199 return true; 3200 } 3201 // We need the package name, so we try to resolve with the loosest flags possible 3202 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3203 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3204 int count = resolveInfos.size(); 3205 for (int i = 0; i < count; i++) { 3206 ResolveInfo resolveInfo = resolveInfos.get(i); 3207 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3208 return true; 3209 } 3210 } 3211 return false; 3212 } 3213 3214 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3215 String resolvedType, int userId) { 3216 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3217 if (resolver != null) { 3218 return resolver.queryIntent(intent, resolvedType, false, userId); 3219 } 3220 return null; 3221 } 3222 3223 @Override 3224 public List<ResolveInfo> queryIntentActivities(Intent intent, 3225 String resolvedType, int flags, int userId) { 3226 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3228 ComponentName comp = intent.getComponent(); 3229 if (comp == null) { 3230 if (intent.getSelector() != null) { 3231 intent = intent.getSelector(); 3232 comp = intent.getComponent(); 3233 } 3234 } 3235 3236 if (comp != null) { 3237 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3238 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3239 if (ai != null) { 3240 final ResolveInfo ri = new ResolveInfo(); 3241 ri.activityInfo = ai; 3242 list.add(ri); 3243 } 3244 return list; 3245 } 3246 3247 // reader 3248 synchronized (mPackages) { 3249 final String pkgName = intent.getPackage(); 3250 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3251 if (pkgName == null) { 3252 ResolveInfo resolveInfo = null; 3253 if (queryCrossProfile) { 3254 // Check if the intent needs to be forwarded to another user for this package 3255 ArrayList<ResolveInfo> crossProfileResult = 3256 queryIntentActivitiesCrossProfilePackage( 3257 intent, resolvedType, flags, userId); 3258 if (!crossProfileResult.isEmpty()) { 3259 // Skip the current profile 3260 return crossProfileResult; 3261 } 3262 List<CrossProfileIntentFilter> matchingFilters = 3263 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3264 // Check for results that need to skip the current profile. 3265 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3266 resolvedType, flags, userId); 3267 if (resolveInfo != null) { 3268 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3269 result.add(resolveInfo); 3270 return result; 3271 } 3272 // Check for cross profile results. 3273 resolveInfo = queryCrossProfileIntents( 3274 matchingFilters, intent, resolvedType, flags, userId); 3275 } 3276 // Check for results in the current profile. 3277 List<ResolveInfo> result = mActivities.queryIntent( 3278 intent, resolvedType, flags, userId); 3279 if (resolveInfo != null) { 3280 result.add(resolveInfo); 3281 } 3282 return result; 3283 } 3284 final PackageParser.Package pkg = mPackages.get(pkgName); 3285 if (pkg != null) { 3286 if (queryCrossProfile) { 3287 ArrayList<ResolveInfo> crossProfileResult = 3288 queryIntentActivitiesCrossProfilePackage( 3289 intent, resolvedType, flags, userId, pkg, pkgName); 3290 if (!crossProfileResult.isEmpty()) { 3291 // Skip the current profile 3292 return crossProfileResult; 3293 } 3294 } 3295 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3296 pkg.activities, userId); 3297 } 3298 return new ArrayList<ResolveInfo>(); 3299 } 3300 } 3301 3302 private ResolveInfo querySkipCurrentProfileIntents( 3303 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3304 int flags, int sourceUserId) { 3305 if (matchingFilters != null) { 3306 int size = matchingFilters.size(); 3307 for (int i = 0; i < size; i ++) { 3308 CrossProfileIntentFilter filter = matchingFilters.get(i); 3309 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3310 // Checking if there are activities in the target user that can handle the 3311 // intent. 3312 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3313 flags, sourceUserId); 3314 if (resolveInfo != null) { 3315 return resolveInfo; 3316 } 3317 } 3318 } 3319 } 3320 return null; 3321 } 3322 3323 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3324 Intent intent, String resolvedType, int flags, int userId) { 3325 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3326 SparseArray<ArrayList<String>> sourceForwardingInfo = 3327 mSettings.mCrossProfilePackageInfo.get(userId); 3328 if (sourceForwardingInfo != null) { 3329 int NI = sourceForwardingInfo.size(); 3330 for (int i = 0; i < NI; i++) { 3331 int targetUserId = sourceForwardingInfo.keyAt(i); 3332 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3333 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3334 intent, resolvedType, flags, targetUserId); 3335 int NJ = resolveInfos.size(); 3336 for (int j = 0; j < NJ; j++) { 3337 ResolveInfo resolveInfo = resolveInfos.get(j); 3338 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3339 matchingResolveInfos.add(createForwardingResolveInfo( 3340 resolveInfo.filter, userId, targetUserId)); 3341 } 3342 } 3343 } 3344 } 3345 return matchingResolveInfos; 3346 } 3347 3348 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3349 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3350 String packageName) { 3351 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3352 SparseArray<ArrayList<String>> sourceForwardingInfo = 3353 mSettings.mCrossProfilePackageInfo.get(userId); 3354 if (sourceForwardingInfo != null) { 3355 int NI = sourceForwardingInfo.size(); 3356 for (int i = 0; i < NI; i++) { 3357 int targetUserId = sourceForwardingInfo.keyAt(i); 3358 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3359 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3360 intent, resolvedType, flags, pkg.activities, targetUserId); 3361 int NJ = resolveInfos.size(); 3362 for (int j = 0; j < NJ; j++) { 3363 ResolveInfo resolveInfo = resolveInfos.get(j); 3364 matchingResolveInfos.add(createForwardingResolveInfo( 3365 resolveInfo.filter, userId, targetUserId)); 3366 } 3367 } 3368 } 3369 } 3370 return matchingResolveInfos; 3371 } 3372 3373 // Return matching ResolveInfo if any for skip current profile intent filters. 3374 private ResolveInfo queryCrossProfileIntents( 3375 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3376 int flags, int sourceUserId) { 3377 if (matchingFilters != null) { 3378 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3379 // match the same intent. For performance reasons, it is better not to 3380 // run queryIntent twice for the same userId 3381 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3382 int size = matchingFilters.size(); 3383 for (int i = 0; i < size; i++) { 3384 CrossProfileIntentFilter filter = matchingFilters.get(i); 3385 int targetUserId = filter.getTargetUserId(); 3386 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3387 && !alreadyTriedUserIds.get(targetUserId)) { 3388 // Checking if there are activities in the target user that can handle the 3389 // intent. 3390 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3391 flags, sourceUserId); 3392 if (resolveInfo != null) return resolveInfo; 3393 alreadyTriedUserIds.put(targetUserId, true); 3394 } 3395 } 3396 } 3397 return null; 3398 } 3399 3400 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3401 String resolvedType, int flags, int sourceUserId) { 3402 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3403 resolvedType, flags, filter.getTargetUserId()); 3404 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3405 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3406 } 3407 return null; 3408 } 3409 3410 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3411 int sourceUserId, int targetUserId) { 3412 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3413 String className; 3414 if (targetUserId == UserHandle.USER_OWNER) { 3415 className = FORWARD_INTENT_TO_USER_OWNER; 3416 } else { 3417 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3418 } 3419 ComponentName forwardingActivityComponentName = new ComponentName( 3420 mAndroidApplication.packageName, className); 3421 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3422 sourceUserId); 3423 if (targetUserId == UserHandle.USER_OWNER) { 3424 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3425 forwardingResolveInfo.noResourceId = true; 3426 } 3427 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3428 forwardingResolveInfo.priority = 0; 3429 forwardingResolveInfo.preferredOrder = 0; 3430 forwardingResolveInfo.match = 0; 3431 forwardingResolveInfo.isDefault = true; 3432 forwardingResolveInfo.filter = filter; 3433 forwardingResolveInfo.targetUserId = targetUserId; 3434 return forwardingResolveInfo; 3435 } 3436 3437 @Override 3438 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3439 Intent[] specifics, String[] specificTypes, Intent intent, 3440 String resolvedType, int flags, int userId) { 3441 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3442 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3443 "query intent activity options"); 3444 final String resultsAction = intent.getAction(); 3445 3446 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3447 | PackageManager.GET_RESOLVED_FILTER, userId); 3448 3449 if (DEBUG_INTENT_MATCHING) { 3450 Log.v(TAG, "Query " + intent + ": " + results); 3451 } 3452 3453 int specificsPos = 0; 3454 int N; 3455 3456 // todo: note that the algorithm used here is O(N^2). This 3457 // isn't a problem in our current environment, but if we start running 3458 // into situations where we have more than 5 or 10 matches then this 3459 // should probably be changed to something smarter... 3460 3461 // First we go through and resolve each of the specific items 3462 // that were supplied, taking care of removing any corresponding 3463 // duplicate items in the generic resolve list. 3464 if (specifics != null) { 3465 for (int i=0; i<specifics.length; i++) { 3466 final Intent sintent = specifics[i]; 3467 if (sintent == null) { 3468 continue; 3469 } 3470 3471 if (DEBUG_INTENT_MATCHING) { 3472 Log.v(TAG, "Specific #" + i + ": " + sintent); 3473 } 3474 3475 String action = sintent.getAction(); 3476 if (resultsAction != null && resultsAction.equals(action)) { 3477 // If this action was explicitly requested, then don't 3478 // remove things that have it. 3479 action = null; 3480 } 3481 3482 ResolveInfo ri = null; 3483 ActivityInfo ai = null; 3484 3485 ComponentName comp = sintent.getComponent(); 3486 if (comp == null) { 3487 ri = resolveIntent( 3488 sintent, 3489 specificTypes != null ? specificTypes[i] : null, 3490 flags, userId); 3491 if (ri == null) { 3492 continue; 3493 } 3494 if (ri == mResolveInfo) { 3495 // ACK! Must do something better with this. 3496 } 3497 ai = ri.activityInfo; 3498 comp = new ComponentName(ai.applicationInfo.packageName, 3499 ai.name); 3500 } else { 3501 ai = getActivityInfo(comp, flags, userId); 3502 if (ai == null) { 3503 continue; 3504 } 3505 } 3506 3507 // Look for any generic query activities that are duplicates 3508 // of this specific one, and remove them from the results. 3509 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3510 N = results.size(); 3511 int j; 3512 for (j=specificsPos; j<N; j++) { 3513 ResolveInfo sri = results.get(j); 3514 if ((sri.activityInfo.name.equals(comp.getClassName()) 3515 && sri.activityInfo.applicationInfo.packageName.equals( 3516 comp.getPackageName())) 3517 || (action != null && sri.filter.matchAction(action))) { 3518 results.remove(j); 3519 if (DEBUG_INTENT_MATCHING) Log.v( 3520 TAG, "Removing duplicate item from " + j 3521 + " due to specific " + specificsPos); 3522 if (ri == null) { 3523 ri = sri; 3524 } 3525 j--; 3526 N--; 3527 } 3528 } 3529 3530 // Add this specific item to its proper place. 3531 if (ri == null) { 3532 ri = new ResolveInfo(); 3533 ri.activityInfo = ai; 3534 } 3535 results.add(specificsPos, ri); 3536 ri.specificIndex = i; 3537 specificsPos++; 3538 } 3539 } 3540 3541 // Now we go through the remaining generic results and remove any 3542 // duplicate actions that are found here. 3543 N = results.size(); 3544 for (int i=specificsPos; i<N-1; i++) { 3545 final ResolveInfo rii = results.get(i); 3546 if (rii.filter == null) { 3547 continue; 3548 } 3549 3550 // Iterate over all of the actions of this result's intent 3551 // filter... typically this should be just one. 3552 final Iterator<String> it = rii.filter.actionsIterator(); 3553 if (it == null) { 3554 continue; 3555 } 3556 while (it.hasNext()) { 3557 final String action = it.next(); 3558 if (resultsAction != null && resultsAction.equals(action)) { 3559 // If this action was explicitly requested, then don't 3560 // remove things that have it. 3561 continue; 3562 } 3563 for (int j=i+1; j<N; j++) { 3564 final ResolveInfo rij = results.get(j); 3565 if (rij.filter != null && rij.filter.hasAction(action)) { 3566 results.remove(j); 3567 if (DEBUG_INTENT_MATCHING) Log.v( 3568 TAG, "Removing duplicate item from " + j 3569 + " due to action " + action + " at " + i); 3570 j--; 3571 N--; 3572 } 3573 } 3574 } 3575 3576 // If the caller didn't request filter information, drop it now 3577 // so we don't have to marshall/unmarshall it. 3578 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3579 rii.filter = null; 3580 } 3581 } 3582 3583 // Filter out the caller activity if so requested. 3584 if (caller != null) { 3585 N = results.size(); 3586 for (int i=0; i<N; i++) { 3587 ActivityInfo ainfo = results.get(i).activityInfo; 3588 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3589 && caller.getClassName().equals(ainfo.name)) { 3590 results.remove(i); 3591 break; 3592 } 3593 } 3594 } 3595 3596 // If the caller didn't request filter information, 3597 // drop them now so we don't have to 3598 // marshall/unmarshall it. 3599 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3600 N = results.size(); 3601 for (int i=0; i<N; i++) { 3602 results.get(i).filter = null; 3603 } 3604 } 3605 3606 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3607 return results; 3608 } 3609 3610 @Override 3611 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3612 int userId) { 3613 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3614 ComponentName comp = intent.getComponent(); 3615 if (comp == null) { 3616 if (intent.getSelector() != null) { 3617 intent = intent.getSelector(); 3618 comp = intent.getComponent(); 3619 } 3620 } 3621 if (comp != null) { 3622 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3623 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3624 if (ai != null) { 3625 ResolveInfo ri = new ResolveInfo(); 3626 ri.activityInfo = ai; 3627 list.add(ri); 3628 } 3629 return list; 3630 } 3631 3632 // reader 3633 synchronized (mPackages) { 3634 String pkgName = intent.getPackage(); 3635 if (pkgName == null) { 3636 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3637 } 3638 final PackageParser.Package pkg = mPackages.get(pkgName); 3639 if (pkg != null) { 3640 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3641 userId); 3642 } 3643 return null; 3644 } 3645 } 3646 3647 @Override 3648 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3649 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3650 if (!sUserManager.exists(userId)) return null; 3651 if (query != null) { 3652 if (query.size() >= 1) { 3653 // If there is more than one service with the same priority, 3654 // just arbitrarily pick the first one. 3655 return query.get(0); 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3663 int userId) { 3664 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3665 ComponentName comp = intent.getComponent(); 3666 if (comp == null) { 3667 if (intent.getSelector() != null) { 3668 intent = intent.getSelector(); 3669 comp = intent.getComponent(); 3670 } 3671 } 3672 if (comp != null) { 3673 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3674 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3675 if (si != null) { 3676 final ResolveInfo ri = new ResolveInfo(); 3677 ri.serviceInfo = si; 3678 list.add(ri); 3679 } 3680 return list; 3681 } 3682 3683 // reader 3684 synchronized (mPackages) { 3685 String pkgName = intent.getPackage(); 3686 if (pkgName == null) { 3687 return mServices.queryIntent(intent, resolvedType, flags, userId); 3688 } 3689 final PackageParser.Package pkg = mPackages.get(pkgName); 3690 if (pkg != null) { 3691 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3692 userId); 3693 } 3694 return null; 3695 } 3696 } 3697 3698 @Override 3699 public List<ResolveInfo> queryIntentContentProviders( 3700 Intent intent, String resolvedType, int flags, int userId) { 3701 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3702 ComponentName comp = intent.getComponent(); 3703 if (comp == null) { 3704 if (intent.getSelector() != null) { 3705 intent = intent.getSelector(); 3706 comp = intent.getComponent(); 3707 } 3708 } 3709 if (comp != null) { 3710 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3711 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3712 if (pi != null) { 3713 final ResolveInfo ri = new ResolveInfo(); 3714 ri.providerInfo = pi; 3715 list.add(ri); 3716 } 3717 return list; 3718 } 3719 3720 // reader 3721 synchronized (mPackages) { 3722 String pkgName = intent.getPackage(); 3723 if (pkgName == null) { 3724 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3725 } 3726 final PackageParser.Package pkg = mPackages.get(pkgName); 3727 if (pkg != null) { 3728 return mProviders.queryIntentForPackage( 3729 intent, resolvedType, flags, pkg.providers, userId); 3730 } 3731 return null; 3732 } 3733 } 3734 3735 @Override 3736 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3737 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3738 3739 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3740 3741 // writer 3742 synchronized (mPackages) { 3743 ArrayList<PackageInfo> list; 3744 if (listUninstalled) { 3745 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3746 for (PackageSetting ps : mSettings.mPackages.values()) { 3747 PackageInfo pi; 3748 if (ps.pkg != null) { 3749 pi = generatePackageInfo(ps.pkg, flags, userId); 3750 } else { 3751 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3752 } 3753 if (pi != null) { 3754 list.add(pi); 3755 } 3756 } 3757 } else { 3758 list = new ArrayList<PackageInfo>(mPackages.size()); 3759 for (PackageParser.Package p : mPackages.values()) { 3760 PackageInfo pi = generatePackageInfo(p, flags, userId); 3761 if (pi != null) { 3762 list.add(pi); 3763 } 3764 } 3765 } 3766 3767 return new ParceledListSlice<PackageInfo>(list); 3768 } 3769 } 3770 3771 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3772 String[] permissions, boolean[] tmp, int flags, int userId) { 3773 int numMatch = 0; 3774 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3775 for (int i=0; i<permissions.length; i++) { 3776 if (gp.grantedPermissions.contains(permissions[i])) { 3777 tmp[i] = true; 3778 numMatch++; 3779 } else { 3780 tmp[i] = false; 3781 } 3782 } 3783 if (numMatch == 0) { 3784 return; 3785 } 3786 PackageInfo pi; 3787 if (ps.pkg != null) { 3788 pi = generatePackageInfo(ps.pkg, flags, userId); 3789 } else { 3790 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3791 } 3792 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3793 if (numMatch == permissions.length) { 3794 pi.requestedPermissions = permissions; 3795 } else { 3796 pi.requestedPermissions = new String[numMatch]; 3797 numMatch = 0; 3798 for (int i=0; i<permissions.length; i++) { 3799 if (tmp[i]) { 3800 pi.requestedPermissions[numMatch] = permissions[i]; 3801 numMatch++; 3802 } 3803 } 3804 } 3805 } 3806 list.add(pi); 3807 } 3808 3809 @Override 3810 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3811 String[] permissions, int flags, int userId) { 3812 if (!sUserManager.exists(userId)) return null; 3813 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3814 3815 // writer 3816 synchronized (mPackages) { 3817 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3818 boolean[] tmpBools = new boolean[permissions.length]; 3819 if (listUninstalled) { 3820 for (PackageSetting ps : mSettings.mPackages.values()) { 3821 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3822 } 3823 } else { 3824 for (PackageParser.Package pkg : mPackages.values()) { 3825 PackageSetting ps = (PackageSetting)pkg.mExtras; 3826 if (ps != null) { 3827 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3828 userId); 3829 } 3830 } 3831 } 3832 3833 return new ParceledListSlice<PackageInfo>(list); 3834 } 3835 } 3836 3837 @Override 3838 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3839 if (!sUserManager.exists(userId)) return null; 3840 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3841 3842 // writer 3843 synchronized (mPackages) { 3844 ArrayList<ApplicationInfo> list; 3845 if (listUninstalled) { 3846 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3847 for (PackageSetting ps : mSettings.mPackages.values()) { 3848 ApplicationInfo ai; 3849 if (ps.pkg != null) { 3850 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3851 ps.readUserState(userId), userId); 3852 } else { 3853 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3854 } 3855 if (ai != null) { 3856 list.add(ai); 3857 } 3858 } 3859 } else { 3860 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3861 for (PackageParser.Package p : mPackages.values()) { 3862 if (p.mExtras != null) { 3863 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3864 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3865 if (ai != null) { 3866 list.add(ai); 3867 } 3868 } 3869 } 3870 } 3871 3872 return new ParceledListSlice<ApplicationInfo>(list); 3873 } 3874 } 3875 3876 public List<ApplicationInfo> getPersistentApplications(int flags) { 3877 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3878 3879 // reader 3880 synchronized (mPackages) { 3881 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3882 final int userId = UserHandle.getCallingUserId(); 3883 while (i.hasNext()) { 3884 final PackageParser.Package p = i.next(); 3885 if (p.applicationInfo != null 3886 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3887 && (!mSafeMode || isSystemApp(p))) { 3888 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3889 if (ps != null) { 3890 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3891 ps.readUserState(userId), userId); 3892 if (ai != null) { 3893 finalList.add(ai); 3894 } 3895 } 3896 } 3897 } 3898 } 3899 3900 return finalList; 3901 } 3902 3903 @Override 3904 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3905 if (!sUserManager.exists(userId)) return null; 3906 // reader 3907 synchronized (mPackages) { 3908 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3909 PackageSetting ps = provider != null 3910 ? mSettings.mPackages.get(provider.owner.packageName) 3911 : null; 3912 return ps != null 3913 && mSettings.isEnabledLPr(provider.info, flags, userId) 3914 && (!mSafeMode || (provider.info.applicationInfo.flags 3915 &ApplicationInfo.FLAG_SYSTEM) != 0) 3916 ? PackageParser.generateProviderInfo(provider, flags, 3917 ps.readUserState(userId), userId) 3918 : null; 3919 } 3920 } 3921 3922 /** 3923 * @deprecated 3924 */ 3925 @Deprecated 3926 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3927 // reader 3928 synchronized (mPackages) { 3929 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3930 .entrySet().iterator(); 3931 final int userId = UserHandle.getCallingUserId(); 3932 while (i.hasNext()) { 3933 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3934 PackageParser.Provider p = entry.getValue(); 3935 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3936 3937 if (ps != null && p.syncable 3938 && (!mSafeMode || (p.info.applicationInfo.flags 3939 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3940 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3941 ps.readUserState(userId), userId); 3942 if (info != null) { 3943 outNames.add(entry.getKey()); 3944 outInfo.add(info); 3945 } 3946 } 3947 } 3948 } 3949 } 3950 3951 @Override 3952 public List<ProviderInfo> queryContentProviders(String processName, 3953 int uid, int flags) { 3954 ArrayList<ProviderInfo> finalList = null; 3955 // reader 3956 synchronized (mPackages) { 3957 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3958 final int userId = processName != null ? 3959 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3960 while (i.hasNext()) { 3961 final PackageParser.Provider p = i.next(); 3962 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3963 if (ps != null && p.info.authority != null 3964 && (processName == null 3965 || (p.info.processName.equals(processName) 3966 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3967 && mSettings.isEnabledLPr(p.info, flags, userId) 3968 && (!mSafeMode 3969 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3970 if (finalList == null) { 3971 finalList = new ArrayList<ProviderInfo>(3); 3972 } 3973 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3974 ps.readUserState(userId), userId); 3975 if (info != null) { 3976 finalList.add(info); 3977 } 3978 } 3979 } 3980 } 3981 3982 if (finalList != null) { 3983 Collections.sort(finalList, mProviderInitOrderSorter); 3984 } 3985 3986 return finalList; 3987 } 3988 3989 @Override 3990 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3991 int flags) { 3992 // reader 3993 synchronized (mPackages) { 3994 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3995 return PackageParser.generateInstrumentationInfo(i, flags); 3996 } 3997 } 3998 3999 @Override 4000 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4001 int flags) { 4002 ArrayList<InstrumentationInfo> finalList = 4003 new ArrayList<InstrumentationInfo>(); 4004 4005 // reader 4006 synchronized (mPackages) { 4007 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4008 while (i.hasNext()) { 4009 final PackageParser.Instrumentation p = i.next(); 4010 if (targetPackage == null 4011 || targetPackage.equals(p.info.targetPackage)) { 4012 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4013 flags); 4014 if (ii != null) { 4015 finalList.add(ii); 4016 } 4017 } 4018 } 4019 } 4020 4021 return finalList; 4022 } 4023 4024 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4025 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4026 if (overlays == null) { 4027 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4028 return; 4029 } 4030 for (PackageParser.Package opkg : overlays.values()) { 4031 // Not much to do if idmap fails: we already logged the error 4032 // and we certainly don't want to abort installation of pkg simply 4033 // because an overlay didn't fit properly. For these reasons, 4034 // ignore the return value of createIdmapForPackagePairLI. 4035 createIdmapForPackagePairLI(pkg, opkg); 4036 } 4037 } 4038 4039 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4040 PackageParser.Package opkg) { 4041 if (!opkg.mTrustedOverlay) { 4042 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4043 opkg.baseCodePath + ": overlay not trusted"); 4044 return false; 4045 } 4046 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4047 if (overlaySet == null) { 4048 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4049 opkg.baseCodePath + " but target package has no known overlays"); 4050 return false; 4051 } 4052 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4053 // TODO: generate idmap for split APKs 4054 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4055 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4056 + opkg.baseCodePath); 4057 return false; 4058 } 4059 PackageParser.Package[] overlayArray = 4060 overlaySet.values().toArray(new PackageParser.Package[0]); 4061 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4062 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4063 return p1.mOverlayPriority - p2.mOverlayPriority; 4064 } 4065 }; 4066 Arrays.sort(overlayArray, cmp); 4067 4068 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4069 int i = 0; 4070 for (PackageParser.Package p : overlayArray) { 4071 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4072 } 4073 return true; 4074 } 4075 4076 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4077 final File[] files = dir.listFiles(); 4078 if (ArrayUtils.isEmpty(files)) { 4079 Log.d(TAG, "No files in app dir " + dir); 4080 return; 4081 } 4082 4083 if (DEBUG_PACKAGE_SCANNING) { 4084 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4085 + " flags=0x" + Integer.toHexString(flags)); 4086 } 4087 4088 for (File file : files) { 4089 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4090 && !PackageInstallerService.isStageFile(file); 4091 if (!isPackage) { 4092 // Ignore entries which are not apk's 4093 continue; 4094 } 4095 try { 4096 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4097 null, null); 4098 } catch (PackageManagerException e) { 4099 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4100 4101 // Don't mess around with apps in system partition. 4102 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4103 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4104 // Delete the apk 4105 Slog.w(TAG, "Cleaning up failed install of " + file); 4106 file.delete(); 4107 } 4108 } 4109 } 4110 } 4111 4112 private static File getSettingsProblemFile() { 4113 File dataDir = Environment.getDataDirectory(); 4114 File systemDir = new File(dataDir, "system"); 4115 File fname = new File(systemDir, "uiderrors.txt"); 4116 return fname; 4117 } 4118 4119 static void reportSettingsProblem(int priority, String msg) { 4120 try { 4121 File fname = getSettingsProblemFile(); 4122 FileOutputStream out = new FileOutputStream(fname, true); 4123 PrintWriter pw = new FastPrintWriter(out); 4124 SimpleDateFormat formatter = new SimpleDateFormat(); 4125 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4126 pw.println(dateString + ": " + msg); 4127 pw.close(); 4128 FileUtils.setPermissions( 4129 fname.toString(), 4130 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4131 -1, -1); 4132 } catch (java.io.IOException e) { 4133 } 4134 Slog.println(priority, TAG, msg); 4135 } 4136 4137 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4138 PackageParser.Package pkg, File srcFile, int parseFlags) 4139 throws PackageManagerException { 4140 if (ps != null 4141 && ps.codePath.equals(srcFile) 4142 && ps.timeStamp == srcFile.lastModified() 4143 && !isCompatSignatureUpdateNeeded(pkg)) { 4144 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4145 if (ps.signatures.mSignatures != null 4146 && ps.signatures.mSignatures.length != 0 4147 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4148 // Optimization: reuse the existing cached certificates 4149 // if the package appears to be unchanged. 4150 pkg.mSignatures = ps.signatures.mSignatures; 4151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4152 synchronized (mPackages) { 4153 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4154 } 4155 return; 4156 } 4157 4158 Slog.w(TAG, "PackageSetting for " + ps.name 4159 + " is missing signatures. Collecting certs again to recover them."); 4160 } else { 4161 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4162 } 4163 4164 try { 4165 pp.collectCertificates(pkg, parseFlags); 4166 pp.collectManifestDigest(pkg); 4167 } catch (PackageParserException e) { 4168 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4169 + pkg.packageName + ": " + e.getMessage()); 4170 } 4171 } 4172 4173 /* 4174 * Scan a package and return the newly parsed package. 4175 * Returns null in case of errors and the error code is stored in mLastScanError 4176 */ 4177 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4178 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4179 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4180 parseFlags |= mDefParseFlags; 4181 PackageParser pp = new PackageParser(); 4182 pp.setSeparateProcesses(mSeparateProcesses); 4183 pp.setOnlyCoreApps(mOnlyCore); 4184 pp.setDisplayMetrics(mMetrics); 4185 4186 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4187 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4188 } 4189 4190 final PackageParser.Package pkg; 4191 try { 4192 pkg = pp.parsePackage(scanFile, parseFlags); 4193 } catch (PackageParserException e) { 4194 throw new PackageManagerException(e.error, 4195 "Failed to scan " + scanFile + ": " + e.getMessage()); 4196 } 4197 4198 PackageSetting ps = null; 4199 PackageSetting updatedPkg; 4200 // reader 4201 synchronized (mPackages) { 4202 // Look to see if we already know about this package. 4203 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4204 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4205 // This package has been renamed to its original name. Let's 4206 // use that. 4207 ps = mSettings.peekPackageLPr(oldName); 4208 } 4209 // If there was no original package, see one for the real package name. 4210 if (ps == null) { 4211 ps = mSettings.peekPackageLPr(pkg.packageName); 4212 } 4213 // Check to see if this package could be hiding/updating a system 4214 // package. Must look for it either under the original or real 4215 // package name depending on our state. 4216 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4217 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4218 } 4219 boolean updatedPkgBetter = false; 4220 // First check if this is a system package that may involve an update 4221 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4222 if (ps != null && !ps.codePath.equals(scanFile)) { 4223 // The path has changed from what was last scanned... check the 4224 // version of the new path against what we have stored to determine 4225 // what to do. 4226 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4227 if (pkg.mVersionCode < ps.versionCode) { 4228 // The system package has been updated and the code path does not match 4229 // Ignore entry. Skip it. 4230 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4231 + " ignored: updated version " + ps.versionCode 4232 + " better than this " + pkg.mVersionCode); 4233 if (!updatedPkg.codePath.equals(scanFile)) { 4234 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4235 + ps.name + " changing from " + updatedPkg.codePathString 4236 + " to " + scanFile); 4237 updatedPkg.codePath = scanFile; 4238 updatedPkg.codePathString = scanFile.toString(); 4239 // This is the point at which we know that the system-disk APK 4240 // for this package has moved during a reboot (e.g. due to an OTA), 4241 // so we need to reevaluate it for privilege policy. 4242 if (locationIsPrivileged(scanFile)) { 4243 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4244 } 4245 } 4246 updatedPkg.pkg = pkg; 4247 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4248 } else { 4249 // The current app on the system partition is better than 4250 // what we have updated to on the data partition; switch 4251 // back to the system partition version. 4252 // At this point, its safely assumed that package installation for 4253 // apps in system partition will go through. If not there won't be a working 4254 // version of the app 4255 // writer 4256 synchronized (mPackages) { 4257 // Just remove the loaded entries from package lists. 4258 mPackages.remove(ps.name); 4259 } 4260 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4261 + "reverting from " + ps.codePathString 4262 + ": new version " + pkg.mVersionCode 4263 + " better than installed " + ps.versionCode); 4264 4265 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4266 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4267 getAppDexInstructionSets(ps), isMultiArch(ps)); 4268 synchronized (mInstallLock) { 4269 args.cleanUpResourcesLI(); 4270 } 4271 synchronized (mPackages) { 4272 mSettings.enableSystemPackageLPw(ps.name); 4273 } 4274 updatedPkgBetter = true; 4275 } 4276 } 4277 } 4278 4279 if (updatedPkg != null) { 4280 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4281 // initially 4282 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4283 4284 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4285 // flag set initially 4286 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4287 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4288 } 4289 } 4290 4291 // Verify certificates against what was last scanned 4292 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps), isMultiArch(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4405 throws PackageManagerException { 4406 if (pkgSetting.signatures.mSignatures != null) { 4407 // Already existing package. Make sure signatures match 4408 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4409 == PackageManager.SIGNATURE_MATCH; 4410 if (!match) { 4411 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4412 == PackageManager.SIGNATURE_MATCH; 4413 } 4414 if (!match) { 4415 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4416 + pkg.packageName + " signatures do not match the " 4417 + "previously installed version; ignoring!"); 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4432 "Package " + pkg.packageName 4433 + " has no signatures that match those in shared user " 4434 + pkgSetting.sharedUser.name + "; ignoring!"); 4435 } 4436 } 4437 } 4438 4439 /** 4440 * Enforces that only the system UID or root's UID can call a method exposed 4441 * via Binder. 4442 * 4443 * @param message used as message if SecurityException is thrown 4444 * @throws SecurityException if the caller is not system or root 4445 */ 4446 private static final void enforceSystemOrRoot(String message) { 4447 final int uid = Binder.getCallingUid(); 4448 if (uid != Process.SYSTEM_UID && uid != 0) { 4449 throw new SecurityException(message); 4450 } 4451 } 4452 4453 @Override 4454 public void performBootDexOpt() { 4455 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4456 4457 final HashSet<PackageParser.Package> pkgs; 4458 synchronized (mPackages) { 4459 pkgs = mDeferredDexOpt; 4460 mDeferredDexOpt = null; 4461 } 4462 4463 if (pkgs != null) { 4464 // Filter out packages that aren't recently used. 4465 // 4466 // The exception is first boot of a non-eng device, which 4467 // should do a full dexopt. 4468 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4469 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4470 // TODO: add a property to control this? 4471 long dexOptLRUThresholdInMinutes; 4472 if (eng) { 4473 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4474 } else { 4475 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4476 } 4477 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4478 4479 int total = pkgs.size(); 4480 int skipped = 0; 4481 long now = System.currentTimeMillis(); 4482 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4483 PackageParser.Package pkg = i.next(); 4484 long then = pkg.mLastPackageUsageTimeInMills; 4485 if (then + dexOptLRUThresholdInMills < now) { 4486 if (DEBUG_DEXOPT) { 4487 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4488 ((then == 0) ? "never" : new Date(then))); 4489 } 4490 i.remove(); 4491 skipped++; 4492 } 4493 } 4494 if (DEBUG_DEXOPT) { 4495 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4496 } 4497 } 4498 4499 int i = 0; 4500 for (PackageParser.Package pkg : pkgs) { 4501 i++; 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4504 + ": " + pkg.packageName); 4505 } 4506 if (!isFirstBoot()) { 4507 try { 4508 ActivityManagerNative.getDefault().showBootMessage( 4509 mContext.getResources().getString( 4510 R.string.android_upgrading_apk, 4511 i, pkgs.size()), true); 4512 } catch (RemoteException e) { 4513 } 4514 } 4515 PackageParser.Package p = pkg; 4516 synchronized (mInstallLock) { 4517 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4518 true /* include dependencies */); 4519 } 4520 } 4521 } 4522 } 4523 4524 @Override 4525 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4526 return performDexOpt(packageName, instructionSet, true); 4527 } 4528 4529 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4530 if (info.primaryCpuAbi == null) { 4531 return getPreferredInstructionSet(); 4532 } 4533 4534 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4535 } 4536 4537 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4538 PackageParser.Package p; 4539 final String targetInstructionSet; 4540 synchronized (mPackages) { 4541 p = mPackages.get(packageName); 4542 if (p == null) { 4543 return false; 4544 } 4545 if (updateUsage) { 4546 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4547 } 4548 mPackageUsage.write(false); 4549 4550 targetInstructionSet = instructionSet != null ? instructionSet : 4551 getPrimaryInstructionSet(p.applicationInfo); 4552 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4553 return false; 4554 } 4555 } 4556 4557 synchronized (mInstallLock) { 4558 final String[] instructionSets = new String[] { targetInstructionSet }; 4559 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4560 true /* include dependencies */) == DEX_OPT_PERFORMED; 4561 } 4562 } 4563 4564 public HashSet<String> getPackagesThatNeedDexOpt() { 4565 HashSet<String> pkgs = null; 4566 synchronized (mPackages) { 4567 for (PackageParser.Package p : mPackages.values()) { 4568 if (DEBUG_DEXOPT) { 4569 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4570 } 4571 if (!p.mDexOptPerformed.isEmpty()) { 4572 continue; 4573 } 4574 if (pkgs == null) { 4575 pkgs = new HashSet<String>(); 4576 } 4577 pkgs.add(p.packageName); 4578 } 4579 } 4580 return pkgs; 4581 } 4582 4583 public void shutdown() { 4584 mPackageUsage.write(true); 4585 } 4586 4587 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4588 boolean forceDex, boolean defer, HashSet<String> done) { 4589 for (int i=0; i<libs.size(); i++) { 4590 PackageParser.Package libPkg; 4591 String libName; 4592 synchronized (mPackages) { 4593 libName = libs.get(i); 4594 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4595 if (lib != null && lib.apk != null) { 4596 libPkg = mPackages.get(lib.apk); 4597 } else { 4598 libPkg = null; 4599 } 4600 } 4601 if (libPkg != null && !done.contains(libName)) { 4602 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4603 } 4604 } 4605 } 4606 4607 static final int DEX_OPT_SKIPPED = 0; 4608 static final int DEX_OPT_PERFORMED = 1; 4609 static final int DEX_OPT_DEFERRED = 2; 4610 static final int DEX_OPT_FAILED = -1; 4611 4612 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4613 boolean forceDex, boolean defer, HashSet<String> done) { 4614 final String[] instructionSets = targetInstructionSets != null ? 4615 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4616 4617 if (done != null) { 4618 done.add(pkg.packageName); 4619 if (pkg.usesLibraries != null) { 4620 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4621 } 4622 if (pkg.usesOptionalLibraries != null) { 4623 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4624 } 4625 } 4626 4627 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4628 return DEX_OPT_SKIPPED; 4629 } 4630 4631 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4632 boolean performedDexOpt = false; 4633 // There are three basic cases here: 4634 // 1.) we need to dexopt, either because we are forced or it is needed 4635 // 2.) we are defering a needed dexopt 4636 // 3.) we are skipping an unneeded dexopt 4637 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4638 for (String path : paths) { 4639 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4640 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4641 continue; 4642 } 4643 4644 try { 4645 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4646 // patckage or the one we find does not match the image checksum (i.e. it was 4647 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4648 // odex file and it matches the checksum of the image but not its base address, 4649 // meaning we need to move it. 4650 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4651 pkg.packageName, dexCodeInstructionSet, defer); 4652 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4653 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4654 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4655 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4656 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4657 pkg.packageName, dexCodeInstructionSet); 4658 4659 if (ret < 0) { 4660 // Don't bother running dexopt again if we failed, it will probably 4661 // just result in an error again. Also, don't bother dexopting for other 4662 // paths & ISAs. 4663 return DEX_OPT_FAILED; 4664 } else { 4665 performedDexOpt = true; 4666 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4667 } 4668 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4669 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4670 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4671 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4672 pkg.packageName, dexCodeInstructionSet); 4673 4674 if (ret < 0) { 4675 // Don't bother running patchoat again if we failed, it will probably 4676 // just result in an error again. Also, don't bother dexopting for other 4677 // paths & ISAs. 4678 return DEX_OPT_FAILED; 4679 } else { 4680 performedDexOpt = true; 4681 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4682 } 4683 } 4684 4685 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4686 // paths and instruction sets. We'll deal with them all together when we process 4687 // our list of deferred dexopts. 4688 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4689 if (mDeferredDexOpt == null) { 4690 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4691 } 4692 mDeferredDexOpt.add(pkg); 4693 return DEX_OPT_DEFERRED; 4694 } 4695 } catch (FileNotFoundException e) { 4696 Slog.w(TAG, "Apk not found for dexopt: " + path); 4697 return DEX_OPT_FAILED; 4698 } catch (IOException e) { 4699 Slog.w(TAG, "IOException reading apk: " + path, e); 4700 return DEX_OPT_FAILED; 4701 } catch (StaleDexCacheError e) { 4702 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4703 return DEX_OPT_FAILED; 4704 } catch (Exception e) { 4705 Slog.w(TAG, "Exception when doing dexopt : ", e); 4706 return DEX_OPT_FAILED; 4707 } 4708 } 4709 } 4710 4711 // If we've gotten here, we're sure that no error occurred and that we haven't 4712 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4713 // we've skipped all of them because they are up to date. In both cases this 4714 // package doesn't need dexopt any longer. 4715 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4716 } 4717 4718 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4719 if (info.primaryCpuAbi != null) { 4720 if (info.secondaryCpuAbi != null) { 4721 return new String[] { 4722 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4723 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4724 } else { 4725 return new String[] { 4726 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4727 } 4728 } 4729 4730 return new String[] { getPreferredInstructionSet() }; 4731 } 4732 4733 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4734 if (ps.primaryCpuAbiString != null) { 4735 if (ps.secondaryCpuAbiString != null) { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4738 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4739 } else { 4740 return new String[] { 4741 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4742 } 4743 } 4744 4745 return new String[] { getPreferredInstructionSet() }; 4746 } 4747 4748 private static String getPreferredInstructionSet() { 4749 if (sPreferredInstructionSet == null) { 4750 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4751 } 4752 4753 return sPreferredInstructionSet; 4754 } 4755 4756 private static List<String> getAllInstructionSets() { 4757 final String[] allAbis = Build.SUPPORTED_ABIS; 4758 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4759 4760 for (String abi : allAbis) { 4761 final String instructionSet = VMRuntime.getInstructionSet(abi); 4762 if (!allInstructionSets.contains(instructionSet)) { 4763 allInstructionSets.add(instructionSet); 4764 } 4765 } 4766 4767 return allInstructionSets; 4768 } 4769 4770 /** 4771 * Returns the instruction set that should be used to compile dex code. In the presence of 4772 * a native bridge this might be different than the one shared libraries use. 4773 */ 4774 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4775 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4776 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4777 } 4778 4779 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4780 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4781 for (String instructionSet : instructionSets) { 4782 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4783 } 4784 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4785 } 4786 4787 @Override 4788 public void forceDexOpt(String packageName) { 4789 enforceSystemOrRoot("forceDexOpt"); 4790 4791 PackageParser.Package pkg; 4792 synchronized (mPackages) { 4793 pkg = mPackages.get(packageName); 4794 if (pkg == null) { 4795 throw new IllegalArgumentException("Missing package: " + packageName); 4796 } 4797 } 4798 4799 synchronized (mInstallLock) { 4800 final String[] instructionSets = new String[] { 4801 getPrimaryInstructionSet(pkg.applicationInfo) }; 4802 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4803 if (res != DEX_OPT_PERFORMED) { 4804 throw new IllegalStateException("Failed to dexopt: " + res); 4805 } 4806 } 4807 } 4808 4809 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4810 boolean forceDex, boolean defer, boolean inclDependencies) { 4811 HashSet<String> done; 4812 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4813 done = new HashSet<String>(); 4814 done.add(pkg.packageName); 4815 } else { 4816 done = null; 4817 } 4818 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4819 } 4820 4821 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4822 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4823 Slog.w(TAG, "Unable to update from " + oldPkg.name 4824 + " to " + newPkg.packageName 4825 + ": old package not in system partition"); 4826 return false; 4827 } else if (mPackages.get(oldPkg.name) != null) { 4828 Slog.w(TAG, "Unable to update from " + oldPkg.name 4829 + " to " + newPkg.packageName 4830 + ": old package still exists"); 4831 return false; 4832 } 4833 return true; 4834 } 4835 4836 File getDataPathForUser(int userId) { 4837 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4838 } 4839 4840 private File getDataPathForPackage(String packageName, int userId) { 4841 /* 4842 * Until we fully support multiple users, return the directory we 4843 * previously would have. The PackageManagerTests will need to be 4844 * revised when this is changed back.. 4845 */ 4846 if (userId == 0) { 4847 return new File(mAppDataDir, packageName); 4848 } else { 4849 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4850 + File.separator + packageName); 4851 } 4852 } 4853 4854 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4855 int[] users = sUserManager.getUserIds(); 4856 int res = mInstaller.install(packageName, uid, uid, seinfo); 4857 if (res < 0) { 4858 return res; 4859 } 4860 for (int user : users) { 4861 if (user != 0) { 4862 res = mInstaller.createUserData(packageName, 4863 UserHandle.getUid(user, uid), user, seinfo); 4864 if (res < 0) { 4865 return res; 4866 } 4867 } 4868 } 4869 return res; 4870 } 4871 4872 private int removeDataDirsLI(String packageName) { 4873 int[] users = sUserManager.getUserIds(); 4874 int res = 0; 4875 for (int user : users) { 4876 int resInner = mInstaller.remove(packageName, user); 4877 if (resInner < 0) { 4878 res = resInner; 4879 } 4880 } 4881 4882 return res; 4883 } 4884 4885 private int deleteCodeCacheDirsLI(String packageName) { 4886 int[] users = sUserManager.getUserIds(); 4887 int res = 0; 4888 for (int user : users) { 4889 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4890 if (resInner < 0) { 4891 res = resInner; 4892 } 4893 } 4894 return res; 4895 } 4896 4897 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4898 PackageParser.Package changingLib) { 4899 if (file.path != null) { 4900 usesLibraryFiles.add(file.path); 4901 return; 4902 } 4903 PackageParser.Package p = mPackages.get(file.apk); 4904 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4905 // If we are doing this while in the middle of updating a library apk, 4906 // then we need to make sure to use that new apk for determining the 4907 // dependencies here. (We haven't yet finished committing the new apk 4908 // to the package manager state.) 4909 if (p == null || p.packageName.equals(changingLib.packageName)) { 4910 p = changingLib; 4911 } 4912 } 4913 if (p != null) { 4914 usesLibraryFiles.addAll(p.getAllCodePaths()); 4915 } 4916 } 4917 4918 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4919 PackageParser.Package changingLib) throws PackageManagerException { 4920 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4921 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4922 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4923 for (int i=0; i<N; i++) { 4924 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4925 if (file == null) { 4926 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4927 "Package " + pkg.packageName + " requires unavailable shared library " 4928 + pkg.usesLibraries.get(i) + "; failing!"); 4929 } 4930 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4931 } 4932 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4933 for (int i=0; i<N; i++) { 4934 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4935 if (file == null) { 4936 Slog.w(TAG, "Package " + pkg.packageName 4937 + " desires unavailable shared library " 4938 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4939 } else { 4940 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4941 } 4942 } 4943 N = usesLibraryFiles.size(); 4944 if (N > 0) { 4945 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4946 } else { 4947 pkg.usesLibraryFiles = null; 4948 } 4949 } 4950 } 4951 4952 private static boolean hasString(List<String> list, List<String> which) { 4953 if (list == null) { 4954 return false; 4955 } 4956 for (int i=list.size()-1; i>=0; i--) { 4957 for (int j=which.size()-1; j>=0; j--) { 4958 if (which.get(j).equals(list.get(i))) { 4959 return true; 4960 } 4961 } 4962 } 4963 return false; 4964 } 4965 4966 private void updateAllSharedLibrariesLPw() { 4967 for (PackageParser.Package pkg : mPackages.values()) { 4968 try { 4969 updateSharedLibrariesLPw(pkg, null); 4970 } catch (PackageManagerException e) { 4971 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4972 } 4973 } 4974 } 4975 4976 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4977 PackageParser.Package changingPkg) { 4978 ArrayList<PackageParser.Package> res = null; 4979 for (PackageParser.Package pkg : mPackages.values()) { 4980 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4981 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4982 if (res == null) { 4983 res = new ArrayList<PackageParser.Package>(); 4984 } 4985 res.add(pkg); 4986 try { 4987 updateSharedLibrariesLPw(pkg, changingPkg); 4988 } catch (PackageManagerException e) { 4989 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4990 } 4991 } 4992 } 4993 return res; 4994 } 4995 4996 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4997 int scanMode, long currentTime, UserHandle user, String abiOverride) 4998 throws PackageManagerException { 4999 final File scanFile = new File(pkg.codePath); 5000 if (pkg.applicationInfo.getCodePath() == null || 5001 pkg.applicationInfo.getResourcePath() == null) { 5002 // Bail out. The resource and code paths haven't been set. 5003 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5004 "Code and resource paths haven't been set correctly"); 5005 } 5006 5007 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5008 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5009 } 5010 5011 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5013 } 5014 5015 if (mCustomResolverComponentName != null && 5016 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5017 setUpCustomResolverActivity(pkg); 5018 } 5019 5020 if (pkg.packageName.equals("android")) { 5021 synchronized (mPackages) { 5022 if (mAndroidApplication != null) { 5023 Slog.w(TAG, "*************************************************"); 5024 Slog.w(TAG, "Core android package being redefined. Skipping."); 5025 Slog.w(TAG, " file=" + scanFile); 5026 Slog.w(TAG, "*************************************************"); 5027 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5028 "Core android package being redefined. Skipping."); 5029 } 5030 5031 // Set up information for our fall-back user intent resolution activity. 5032 mPlatformPackage = pkg; 5033 pkg.mVersionCode = mSdkVersion; 5034 mAndroidApplication = pkg.applicationInfo; 5035 5036 if (!mResolverReplaced) { 5037 mResolveActivity.applicationInfo = mAndroidApplication; 5038 mResolveActivity.name = ResolverActivity.class.getName(); 5039 mResolveActivity.packageName = mAndroidApplication.packageName; 5040 mResolveActivity.processName = "system:ui"; 5041 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5042 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5043 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5044 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5045 mResolveActivity.exported = true; 5046 mResolveActivity.enabled = true; 5047 mResolveInfo.activityInfo = mResolveActivity; 5048 mResolveInfo.priority = 0; 5049 mResolveInfo.preferredOrder = 0; 5050 mResolveInfo.match = 0; 5051 mResolveComponentName = new ComponentName( 5052 mAndroidApplication.packageName, mResolveActivity.name); 5053 } 5054 } 5055 } 5056 5057 if (DEBUG_PACKAGE_SCANNING) { 5058 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5059 Log.d(TAG, "Scanning package " + pkg.packageName); 5060 } 5061 5062 if (mPackages.containsKey(pkg.packageName) 5063 || mSharedLibraries.containsKey(pkg.packageName)) { 5064 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5065 "Application package " + pkg.packageName 5066 + " already installed. Skipping duplicate."); 5067 } 5068 5069 // Initialize package source and resource directories 5070 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5071 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5072 5073 SharedUserSetting suid = null; 5074 PackageSetting pkgSetting = null; 5075 5076 if (!isSystemApp(pkg)) { 5077 // Only system apps can use these features. 5078 pkg.mOriginalPackages = null; 5079 pkg.mRealPackage = null; 5080 pkg.mAdoptPermissions = null; 5081 } 5082 5083 // writer 5084 synchronized (mPackages) { 5085 if (pkg.mSharedUserId != null) { 5086 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5087 if (suid == null) { 5088 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5089 "Creating application package " + pkg.packageName 5090 + " for shared user failed"); 5091 } 5092 if (DEBUG_PACKAGE_SCANNING) { 5093 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5094 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5095 + "): packages=" + suid.packages); 5096 } 5097 } 5098 5099 // Check if we are renaming from an original package name. 5100 PackageSetting origPackage = null; 5101 String realName = null; 5102 if (pkg.mOriginalPackages != null) { 5103 // This package may need to be renamed to a previously 5104 // installed name. Let's check on that... 5105 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5106 if (pkg.mOriginalPackages.contains(renamed)) { 5107 // This package had originally been installed as the 5108 // original name, and we have already taken care of 5109 // transitioning to the new one. Just update the new 5110 // one to continue using the old name. 5111 realName = pkg.mRealPackage; 5112 if (!pkg.packageName.equals(renamed)) { 5113 // Callers into this function may have already taken 5114 // care of renaming the package; only do it here if 5115 // it is not already done. 5116 pkg.setPackageName(renamed); 5117 } 5118 5119 } else { 5120 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5121 if ((origPackage = mSettings.peekPackageLPr( 5122 pkg.mOriginalPackages.get(i))) != null) { 5123 // We do have the package already installed under its 5124 // original name... should we use it? 5125 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5126 // New package is not compatible with original. 5127 origPackage = null; 5128 continue; 5129 } else if (origPackage.sharedUser != null) { 5130 // Make sure uid is compatible between packages. 5131 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5132 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5133 + " to " + pkg.packageName + ": old uid " 5134 + origPackage.sharedUser.name 5135 + " differs from " + pkg.mSharedUserId); 5136 origPackage = null; 5137 continue; 5138 } 5139 } else { 5140 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5141 + pkg.packageName + " to old name " + origPackage.name); 5142 } 5143 break; 5144 } 5145 } 5146 } 5147 } 5148 5149 if (mTransferedPackages.contains(pkg.packageName)) { 5150 Slog.w(TAG, "Package " + pkg.packageName 5151 + " was transferred to another, but its .apk remains"); 5152 } 5153 5154 // Just create the setting, don't add it yet. For already existing packages 5155 // the PkgSetting exists already and doesn't have to be created. 5156 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5157 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5158 pkg.applicationInfo.primaryCpuAbi, 5159 pkg.applicationInfo.secondaryCpuAbi, 5160 pkg.applicationInfo.flags, user, false); 5161 if (pkgSetting == null) { 5162 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5163 "Creating application package " + pkg.packageName + " failed"); 5164 } 5165 5166 if (pkgSetting.origPackage != null) { 5167 // If we are first transitioning from an original package, 5168 // fix up the new package's name now. We need to do this after 5169 // looking up the package under its new name, so getPackageLP 5170 // can take care of fiddling things correctly. 5171 pkg.setPackageName(origPackage.name); 5172 5173 // File a report about this. 5174 String msg = "New package " + pkgSetting.realName 5175 + " renamed to replace old package " + pkgSetting.name; 5176 reportSettingsProblem(Log.WARN, msg); 5177 5178 // Make a note of it. 5179 mTransferedPackages.add(origPackage.name); 5180 5181 // No longer need to retain this. 5182 pkgSetting.origPackage = null; 5183 } 5184 5185 if (realName != null) { 5186 // Make a note of it. 5187 mTransferedPackages.add(pkg.packageName); 5188 } 5189 5190 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5191 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5192 } 5193 5194 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5195 // Check all shared libraries and map to their actual file path. 5196 // We only do this here for apps not on a system dir, because those 5197 // are the only ones that can fail an install due to this. We 5198 // will take care of the system apps by updating all of their 5199 // library paths after the scan is done. 5200 updateSharedLibrariesLPw(pkg, null); 5201 } 5202 5203 if (mFoundPolicyFile) { 5204 SELinuxMMAC.assignSeinfoValue(pkg); 5205 } 5206 5207 pkg.applicationInfo.uid = pkgSetting.appId; 5208 pkg.mExtras = pkgSetting; 5209 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5210 try { 5211 verifySignaturesLP(pkgSetting, pkg); 5212 } catch (PackageManagerException e) { 5213 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5214 throw e; 5215 } 5216 // The signature has changed, but this package is in the system 5217 // image... let's recover! 5218 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5219 // However... if this package is part of a shared user, but it 5220 // doesn't match the signature of the shared user, let's fail. 5221 // What this means is that you can't change the signatures 5222 // associated with an overall shared user, which doesn't seem all 5223 // that unreasonable. 5224 if (pkgSetting.sharedUser != null) { 5225 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5226 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5227 throw new PackageManagerException( 5228 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5229 "Signature mismatch for shared user : " 5230 + pkgSetting.sharedUser); 5231 } 5232 } 5233 // File a report about this. 5234 String msg = "System package " + pkg.packageName 5235 + " signature changed; retaining data."; 5236 reportSettingsProblem(Log.WARN, msg); 5237 } 5238 } else { 5239 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5240 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5241 + pkg.packageName + " upgrade keys do not match the " 5242 + "previously installed version"); 5243 } else { 5244 // signatures may have changed as result of upgrade 5245 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5246 } 5247 } 5248 // Verify that this new package doesn't have any content providers 5249 // that conflict with existing packages. Only do this if the 5250 // package isn't already installed, since we don't want to break 5251 // things that are installed. 5252 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5253 final int N = pkg.providers.size(); 5254 int i; 5255 for (i=0; i<N; i++) { 5256 PackageParser.Provider p = pkg.providers.get(i); 5257 if (p.info.authority != null) { 5258 String names[] = p.info.authority.split(";"); 5259 for (int j = 0; j < names.length; j++) { 5260 if (mProvidersByAuthority.containsKey(names[j])) { 5261 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5262 final String otherPackageName = 5263 ((other != null && other.getComponentName() != null) ? 5264 other.getComponentName().getPackageName() : "?"); 5265 throw new PackageManagerException( 5266 INSTALL_FAILED_CONFLICTING_PROVIDER, 5267 "Can't install because provider name " + names[j] 5268 + " (in package " + pkg.applicationInfo.packageName 5269 + ") is already used by " + otherPackageName); 5270 } 5271 } 5272 } 5273 } 5274 } 5275 5276 if (pkg.mAdoptPermissions != null) { 5277 // This package wants to adopt ownership of permissions from 5278 // another package. 5279 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5280 final String origName = pkg.mAdoptPermissions.get(i); 5281 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5282 if (orig != null) { 5283 if (verifyPackageUpdateLPr(orig, pkg)) { 5284 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5285 + pkg.packageName); 5286 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5287 } 5288 } 5289 } 5290 } 5291 } 5292 5293 final String pkgName = pkg.packageName; 5294 5295 final long scanFileTime = scanFile.lastModified(); 5296 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5297 pkg.applicationInfo.processName = fixProcessName( 5298 pkg.applicationInfo.packageName, 5299 pkg.applicationInfo.processName, 5300 pkg.applicationInfo.uid); 5301 5302 File dataPath; 5303 if (mPlatformPackage == pkg) { 5304 // The system package is special. 5305 dataPath = new File (Environment.getDataDirectory(), "system"); 5306 pkg.applicationInfo.dataDir = dataPath.getPath(); 5307 5308 } else { 5309 // This is a normal package, need to make its data directory. 5310 dataPath = getDataPathForPackage(pkg.packageName, 0); 5311 5312 boolean uidError = false; 5313 5314 if (dataPath.exists()) { 5315 int currentUid = 0; 5316 try { 5317 StructStat stat = Os.stat(dataPath.getPath()); 5318 currentUid = stat.st_uid; 5319 } catch (ErrnoException e) { 5320 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5321 } 5322 5323 // If we have mismatched owners for the data path, we have a problem. 5324 if (currentUid != pkg.applicationInfo.uid) { 5325 boolean recovered = false; 5326 if (currentUid == 0) { 5327 // The directory somehow became owned by root. Wow. 5328 // This is probably because the system was stopped while 5329 // installd was in the middle of messing with its libs 5330 // directory. Ask installd to fix that. 5331 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5332 pkg.applicationInfo.uid); 5333 if (ret >= 0) { 5334 recovered = true; 5335 String msg = "Package " + pkg.packageName 5336 + " unexpectedly changed to uid 0; recovered to " + 5337 + pkg.applicationInfo.uid; 5338 reportSettingsProblem(Log.WARN, msg); 5339 } 5340 } 5341 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5342 || (scanMode&SCAN_BOOTING) != 0)) { 5343 // If this is a system app, we can at least delete its 5344 // current data so the application will still work. 5345 int ret = removeDataDirsLI(pkgName); 5346 if (ret >= 0) { 5347 // TODO: Kill the processes first 5348 // Old data gone! 5349 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5350 ? "System package " : "Third party package "; 5351 String msg = prefix + pkg.packageName 5352 + " has changed from uid: " 5353 + currentUid + " to " 5354 + pkg.applicationInfo.uid + "; old data erased"; 5355 reportSettingsProblem(Log.WARN, msg); 5356 recovered = true; 5357 5358 // And now re-install the app. 5359 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5360 pkg.applicationInfo.seinfo); 5361 if (ret == -1) { 5362 // Ack should not happen! 5363 msg = prefix + pkg.packageName 5364 + " could not have data directory re-created after delete."; 5365 reportSettingsProblem(Log.WARN, msg); 5366 throw new PackageManagerException( 5367 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5368 } 5369 } 5370 if (!recovered) { 5371 mHasSystemUidErrors = true; 5372 } 5373 } else if (!recovered) { 5374 // If we allow this install to proceed, we will be broken. 5375 // Abort, abort! 5376 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5377 "scanPackageLI"); 5378 } 5379 if (!recovered) { 5380 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5381 + pkg.applicationInfo.uid + "/fs_" 5382 + currentUid; 5383 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5384 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5385 String msg = "Package " + pkg.packageName 5386 + " has mismatched uid: " 5387 + currentUid + " on disk, " 5388 + pkg.applicationInfo.uid + " in settings"; 5389 // writer 5390 synchronized (mPackages) { 5391 mSettings.mReadMessages.append(msg); 5392 mSettings.mReadMessages.append('\n'); 5393 uidError = true; 5394 if (!pkgSetting.uidError) { 5395 reportSettingsProblem(Log.ERROR, msg); 5396 } 5397 } 5398 } 5399 } 5400 pkg.applicationInfo.dataDir = dataPath.getPath(); 5401 if (mShouldRestoreconData) { 5402 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5403 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5404 pkg.applicationInfo.uid); 5405 } 5406 } else { 5407 if (DEBUG_PACKAGE_SCANNING) { 5408 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5409 Log.v(TAG, "Want this data dir: " + dataPath); 5410 } 5411 //invoke installer to do the actual installation 5412 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5413 pkg.applicationInfo.seinfo); 5414 if (ret < 0) { 5415 // Error from installer 5416 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5417 "Unable to create data dirs [errorCode=" + ret + "]"); 5418 } 5419 5420 if (dataPath.exists()) { 5421 pkg.applicationInfo.dataDir = dataPath.getPath(); 5422 } else { 5423 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5424 pkg.applicationInfo.dataDir = null; 5425 } 5426 } 5427 5428 pkgSetting.uidError = uidError; 5429 } 5430 5431 final String path = scanFile.getPath(); 5432 final String codePath = pkg.applicationInfo.getCodePath(); 5433 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5434 // For the case where we had previously uninstalled an update, get rid 5435 // of any native binaries we might have unpackaged. Note that this assumes 5436 // that system app updates were not installed via ASEC. 5437 // 5438 // TODO(multiArch): Is this cleanup really necessary ? 5439 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5440 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5441 setBundledAppAbisAndRoots(pkg, pkgSetting); 5442 5443 // If we haven't found any native libraries for the app, check if it has 5444 // renderscript code. We'll need to force the app to 32 bit if it has 5445 // renderscript bitcode. 5446 if (pkg.applicationInfo.primaryCpuAbi == null 5447 && pkg.applicationInfo.secondaryCpuAbi == null 5448 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5449 NativeLibraryHelper.Handle handle = null; 5450 try { 5451 handle = NativeLibraryHelper.Handle.create(scanFile); 5452 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5453 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5454 } 5455 } catch (IOException ioe) { 5456 Slog.w(TAG, "Error scanning system app : " + ioe); 5457 } finally { 5458 IoUtils.closeQuietly(handle); 5459 } 5460 } 5461 5462 setNativeLibraryPaths(pkg); 5463 } else { 5464 // TODO: We can probably be smarter about this stuff. For installed apps, 5465 // we can calculate this information at install time once and for all. For 5466 // system apps, we can probably assume that this information doesn't change 5467 // after the first boot scan. As things stand, we do lots of unnecessary work. 5468 5469 // Give ourselves some initial paths; we'll come back for another 5470 // pass once we've determined ABI below. 5471 setNativeLibraryPaths(pkg); 5472 5473 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5474 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5475 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5476 5477 NativeLibraryHelper.Handle handle = null; 5478 try { 5479 handle = NativeLibraryHelper.Handle.create(scanFile); 5480 // TODO(multiArch): This can be null for apps that didn't go through the 5481 // usual installation process. We can calculate it again, like we 5482 // do during install time. 5483 // 5484 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5485 // unnecessary. 5486 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5487 5488 // Null out the abis so that they can be recalculated. 5489 pkg.applicationInfo.primaryCpuAbi = null; 5490 pkg.applicationInfo.secondaryCpuAbi = null; 5491 if (isMultiArch(pkg.applicationInfo)) { 5492 // Warn if we've set an abiOverride for multi-lib packages.. 5493 // By definition, we need to copy both 32 and 64 bit libraries for 5494 // such packages. 5495 if (abiOverride != null) { 5496 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5497 } 5498 5499 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5500 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5501 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5502 if (isAsec) { 5503 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5504 } else { 5505 abi32 = copyNativeLibrariesForInternalApp(handle, 5506 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5507 } 5508 } 5509 5510 maybeThrowExceptionForMultiArchCopy( 5511 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5512 5513 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5514 if (isAsec) { 5515 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5516 } else { 5517 abi64 = copyNativeLibrariesForInternalApp(handle, 5518 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5519 } 5520 } 5521 5522 maybeThrowExceptionForMultiArchCopy( 5523 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5524 5525 if (abi64 >= 0) { 5526 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5527 } 5528 5529 if (abi32 >= 0) { 5530 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5531 if (abi64 >= 0) { 5532 pkg.applicationInfo.secondaryCpuAbi = abi; 5533 } else { 5534 pkg.applicationInfo.primaryCpuAbi = abi; 5535 } 5536 } 5537 } else { 5538 String[] abiList = (abiOverride != null) ? 5539 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5540 5541 // Enable gross and lame hacks for apps that are built with old 5542 // SDK tools. We must scan their APKs for renderscript bitcode and 5543 // not launch them if it's present. Don't bother checking on devices 5544 // that don't have 64 bit support. 5545 boolean needsRenderScriptOverride = false; 5546 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5547 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5548 abiList = Build.SUPPORTED_32_BIT_ABIS; 5549 needsRenderScriptOverride = true; 5550 } 5551 5552 final int copyRet; 5553 if (isAsec) { 5554 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5555 } else { 5556 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5557 useIsaSpecificSubdirs); 5558 } 5559 5560 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5561 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5562 "Error unpackaging native libs for app, errorCode=" + copyRet); 5563 } 5564 5565 if (copyRet >= 0) { 5566 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5567 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5568 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5569 } else if (needsRenderScriptOverride) { 5570 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5571 } 5572 } 5573 } catch (IOException ioe) { 5574 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5575 } finally { 5576 IoUtils.closeQuietly(handle); 5577 } 5578 5579 // Now that we've calculated the ABIs and determined if it's an internal app, 5580 // we will go ahead and populate the nativeLibraryPath. 5581 setNativeLibraryPaths(pkg); 5582 5583 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5584 final int[] userIds = sUserManager.getUserIds(); 5585 synchronized (mInstallLock) { 5586 // Create a native library symlink only if we have native libraries 5587 // and if the native libraries are 32 bit libraries. We do not provide 5588 // this symlink for 64 bit libraries. 5589 if (pkg.applicationInfo.primaryCpuAbi != null && 5590 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5591 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5592 for (int userId : userIds) { 5593 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5594 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5595 "Failed linking native library dir (user=" + userId + ")"); 5596 } 5597 } 5598 } 5599 } 5600 } 5601 5602 // This is a special case for the "system" package, where the ABI is 5603 // dictated by the zygote configuration (and init.rc). We should keep track 5604 // of this ABI so that we can deal with "normal" applications that run under 5605 // the same UID correctly. 5606 if (mPlatformPackage == pkg) { 5607 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5608 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5609 } 5610 5611 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5612 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5613 5614 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5615 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5616 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5617 5618 // Push the derived path down into PackageSettings so we know what to 5619 // clean up at uninstall time. 5620 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5621 5622 if (DEBUG_ABI_SELECTION) { 5623 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5624 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5625 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5626 } 5627 5628 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5629 // We don't do this here during boot because we can do it all 5630 // at once after scanning all existing packages. 5631 // 5632 // We also do this *before* we perform dexopt on this package, so that 5633 // we can avoid redundant dexopts, and also to make sure we've got the 5634 // code and package path correct. 5635 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5636 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5637 } 5638 5639 if ((scanMode&SCAN_NO_DEX) == 0) { 5640 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5641 == DEX_OPT_FAILED) { 5642 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5643 removeDataDirsLI(pkg.packageName); 5644 } 5645 5646 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5647 } 5648 } 5649 5650 if (mFactoryTest && pkg.requestedPermissions.contains( 5651 android.Manifest.permission.FACTORY_TEST)) { 5652 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5653 } 5654 5655 ArrayList<PackageParser.Package> clientLibPkgs = null; 5656 5657 // writer 5658 synchronized (mPackages) { 5659 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5660 // Only system apps can add new shared libraries. 5661 if (pkg.libraryNames != null) { 5662 for (int i=0; i<pkg.libraryNames.size(); i++) { 5663 String name = pkg.libraryNames.get(i); 5664 boolean allowed = false; 5665 if (isUpdatedSystemApp(pkg)) { 5666 // New library entries can only be added through the 5667 // system image. This is important to get rid of a lot 5668 // of nasty edge cases: for example if we allowed a non- 5669 // system update of the app to add a library, then uninstalling 5670 // the update would make the library go away, and assumptions 5671 // we made such as through app install filtering would now 5672 // have allowed apps on the device which aren't compatible 5673 // with it. Better to just have the restriction here, be 5674 // conservative, and create many fewer cases that can negatively 5675 // impact the user experience. 5676 final PackageSetting sysPs = mSettings 5677 .getDisabledSystemPkgLPr(pkg.packageName); 5678 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5679 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5680 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5681 allowed = true; 5682 allowed = true; 5683 break; 5684 } 5685 } 5686 } 5687 } else { 5688 allowed = true; 5689 } 5690 if (allowed) { 5691 if (!mSharedLibraries.containsKey(name)) { 5692 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5693 } else if (!name.equals(pkg.packageName)) { 5694 Slog.w(TAG, "Package " + pkg.packageName + " library " 5695 + name + " already exists; skipping"); 5696 } 5697 } else { 5698 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5699 + name + " that is not declared on system image; skipping"); 5700 } 5701 } 5702 if ((scanMode&SCAN_BOOTING) == 0) { 5703 // If we are not booting, we need to update any applications 5704 // that are clients of our shared library. If we are booting, 5705 // this will all be done once the scan is complete. 5706 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5707 } 5708 } 5709 } 5710 } 5711 5712 // We also need to dexopt any apps that are dependent on this library. Note that 5713 // if these fail, we should abort the install since installing the library will 5714 // result in some apps being broken. 5715 if (clientLibPkgs != null) { 5716 if ((scanMode&SCAN_NO_DEX) == 0) { 5717 for (int i=0; i<clientLibPkgs.size(); i++) { 5718 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5719 if (performDexOptLI(clientPkg, null /* instruction sets */, 5720 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5721 == DEX_OPT_FAILED) { 5722 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5723 removeDataDirsLI(pkg.packageName); 5724 } 5725 5726 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5727 "scanPackageLI failed to dexopt clientLibPkgs"); 5728 } 5729 } 5730 } 5731 } 5732 5733 // Request the ActivityManager to kill the process(only for existing packages) 5734 // so that we do not end up in a confused state while the user is still using the older 5735 // version of the application while the new one gets installed. 5736 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5737 // If the package lives in an asec, tell everyone that the container is going 5738 // away so they can clean up any references to its resources (which would prevent 5739 // vold from being able to unmount the asec) 5740 if (isForwardLocked(pkg) || isExternal(pkg)) { 5741 if (DEBUG_INSTALL) { 5742 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5743 } 5744 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5745 final ArrayList<String> pkgList = new ArrayList<String>(1); 5746 pkgList.add(pkg.applicationInfo.packageName); 5747 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5748 } 5749 5750 // Post the request that it be killed now that the going-away broadcast is en route 5751 killApplication(pkg.applicationInfo.packageName, 5752 pkg.applicationInfo.uid, "update pkg"); 5753 } 5754 5755 // Also need to kill any apps that are dependent on the library. 5756 if (clientLibPkgs != null) { 5757 for (int i=0; i<clientLibPkgs.size(); i++) { 5758 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5759 killApplication(clientPkg.applicationInfo.packageName, 5760 clientPkg.applicationInfo.uid, "update lib"); 5761 } 5762 } 5763 5764 // writer 5765 synchronized (mPackages) { 5766 // We don't expect installation to fail beyond this point, 5767 if ((scanMode&SCAN_MONITOR) != 0) { 5768 mAppDirs.put(pkg.codePath, pkg); 5769 } 5770 // Add the new setting to mSettings 5771 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5772 // Add the new setting to mPackages 5773 mPackages.put(pkg.applicationInfo.packageName, pkg); 5774 // Make sure we don't accidentally delete its data. 5775 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5776 while (iter.hasNext()) { 5777 PackageCleanItem item = iter.next(); 5778 if (pkgName.equals(item.packageName)) { 5779 iter.remove(); 5780 } 5781 } 5782 5783 // Take care of first install / last update times. 5784 if (currentTime != 0) { 5785 if (pkgSetting.firstInstallTime == 0) { 5786 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5787 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5788 pkgSetting.lastUpdateTime = currentTime; 5789 } 5790 } else if (pkgSetting.firstInstallTime == 0) { 5791 // We need *something*. Take time time stamp of the file. 5792 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5793 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5794 if (scanFileTime != pkgSetting.timeStamp) { 5795 // A package on the system image has changed; consider this 5796 // to be an update. 5797 pkgSetting.lastUpdateTime = scanFileTime; 5798 } 5799 } 5800 5801 // Add the package's KeySets to the global KeySetManagerService 5802 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5803 try { 5804 // Old KeySetData no longer valid. 5805 ksms.removeAppKeySetDataLPw(pkg.packageName); 5806 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5807 if (pkg.mKeySetMapping != null) { 5808 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5809 pkg.mKeySetMapping.entrySet()) { 5810 if (entry.getValue() != null) { 5811 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5812 entry.getValue(), entry.getKey()); 5813 } 5814 } 5815 if (pkg.mUpgradeKeySets != null) { 5816 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5817 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5818 } 5819 } 5820 } 5821 } catch (NullPointerException e) { 5822 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5823 } catch (IllegalArgumentException e) { 5824 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5825 } 5826 5827 int N = pkg.providers.size(); 5828 StringBuilder r = null; 5829 int i; 5830 for (i=0; i<N; i++) { 5831 PackageParser.Provider p = pkg.providers.get(i); 5832 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5833 p.info.processName, pkg.applicationInfo.uid); 5834 mProviders.addProvider(p); 5835 p.syncable = p.info.isSyncable; 5836 if (p.info.authority != null) { 5837 String names[] = p.info.authority.split(";"); 5838 p.info.authority = null; 5839 for (int j = 0; j < names.length; j++) { 5840 if (j == 1 && p.syncable) { 5841 // We only want the first authority for a provider to possibly be 5842 // syncable, so if we already added this provider using a different 5843 // authority clear the syncable flag. We copy the provider before 5844 // changing it because the mProviders object contains a reference 5845 // to a provider that we don't want to change. 5846 // Only do this for the second authority since the resulting provider 5847 // object can be the same for all future authorities for this provider. 5848 p = new PackageParser.Provider(p); 5849 p.syncable = false; 5850 } 5851 if (!mProvidersByAuthority.containsKey(names[j])) { 5852 mProvidersByAuthority.put(names[j], p); 5853 if (p.info.authority == null) { 5854 p.info.authority = names[j]; 5855 } else { 5856 p.info.authority = p.info.authority + ";" + names[j]; 5857 } 5858 if (DEBUG_PACKAGE_SCANNING) { 5859 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5860 Log.d(TAG, "Registered content provider: " + names[j] 5861 + ", className = " + p.info.name + ", isSyncable = " 5862 + p.info.isSyncable); 5863 } 5864 } else { 5865 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5866 Slog.w(TAG, "Skipping provider name " + names[j] + 5867 " (in package " + pkg.applicationInfo.packageName + 5868 "): name already used by " 5869 + ((other != null && other.getComponentName() != null) 5870 ? other.getComponentName().getPackageName() : "?")); 5871 } 5872 } 5873 } 5874 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5875 if (r == null) { 5876 r = new StringBuilder(256); 5877 } else { 5878 r.append(' '); 5879 } 5880 r.append(p.info.name); 5881 } 5882 } 5883 if (r != null) { 5884 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5885 } 5886 5887 N = pkg.services.size(); 5888 r = null; 5889 for (i=0; i<N; i++) { 5890 PackageParser.Service s = pkg.services.get(i); 5891 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5892 s.info.processName, pkg.applicationInfo.uid); 5893 mServices.addService(s); 5894 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5895 if (r == null) { 5896 r = new StringBuilder(256); 5897 } else { 5898 r.append(' '); 5899 } 5900 r.append(s.info.name); 5901 } 5902 } 5903 if (r != null) { 5904 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5905 } 5906 5907 N = pkg.receivers.size(); 5908 r = null; 5909 for (i=0; i<N; i++) { 5910 PackageParser.Activity a = pkg.receivers.get(i); 5911 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5912 a.info.processName, pkg.applicationInfo.uid); 5913 mReceivers.addActivity(a, "receiver"); 5914 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5915 if (r == null) { 5916 r = new StringBuilder(256); 5917 } else { 5918 r.append(' '); 5919 } 5920 r.append(a.info.name); 5921 } 5922 } 5923 if (r != null) { 5924 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5925 } 5926 5927 N = pkg.activities.size(); 5928 r = null; 5929 for (i=0; i<N; i++) { 5930 PackageParser.Activity a = pkg.activities.get(i); 5931 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5932 a.info.processName, pkg.applicationInfo.uid); 5933 mActivities.addActivity(a, "activity"); 5934 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5935 if (r == null) { 5936 r = new StringBuilder(256); 5937 } else { 5938 r.append(' '); 5939 } 5940 r.append(a.info.name); 5941 } 5942 } 5943 if (r != null) { 5944 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5945 } 5946 5947 N = pkg.permissionGroups.size(); 5948 r = null; 5949 for (i=0; i<N; i++) { 5950 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5951 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5952 if (cur == null) { 5953 mPermissionGroups.put(pg.info.name, pg); 5954 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5955 if (r == null) { 5956 r = new StringBuilder(256); 5957 } else { 5958 r.append(' '); 5959 } 5960 r.append(pg.info.name); 5961 } 5962 } else { 5963 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5964 + pg.info.packageName + " ignored: original from " 5965 + cur.info.packageName); 5966 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5967 if (r == null) { 5968 r = new StringBuilder(256); 5969 } else { 5970 r.append(' '); 5971 } 5972 r.append("DUP:"); 5973 r.append(pg.info.name); 5974 } 5975 } 5976 } 5977 if (r != null) { 5978 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5979 } 5980 5981 N = pkg.permissions.size(); 5982 r = null; 5983 for (i=0; i<N; i++) { 5984 PackageParser.Permission p = pkg.permissions.get(i); 5985 HashMap<String, BasePermission> permissionMap = 5986 p.tree ? mSettings.mPermissionTrees 5987 : mSettings.mPermissions; 5988 p.group = mPermissionGroups.get(p.info.group); 5989 if (p.info.group == null || p.group != null) { 5990 BasePermission bp = permissionMap.get(p.info.name); 5991 if (bp == null) { 5992 bp = new BasePermission(p.info.name, p.info.packageName, 5993 BasePermission.TYPE_NORMAL); 5994 permissionMap.put(p.info.name, bp); 5995 } 5996 if (bp.perm == null) { 5997 if (bp.sourcePackage != null 5998 && !bp.sourcePackage.equals(p.info.packageName)) { 5999 // If this is a permission that was formerly defined by a non-system 6000 // app, but is now defined by a system app (following an upgrade), 6001 // discard the previous declaration and consider the system's to be 6002 // canonical. 6003 if (isSystemApp(p.owner)) { 6004 String msg = "New decl " + p.owner + " of permission " 6005 + p.info.name + " is system"; 6006 reportSettingsProblem(Log.WARN, msg); 6007 bp.sourcePackage = null; 6008 } 6009 } 6010 if (bp.sourcePackage == null 6011 || bp.sourcePackage.equals(p.info.packageName)) { 6012 BasePermission tree = findPermissionTreeLP(p.info.name); 6013 if (tree == null 6014 || tree.sourcePackage.equals(p.info.packageName)) { 6015 bp.packageSetting = pkgSetting; 6016 bp.perm = p; 6017 bp.uid = pkg.applicationInfo.uid; 6018 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6019 if (r == null) { 6020 r = new StringBuilder(256); 6021 } else { 6022 r.append(' '); 6023 } 6024 r.append(p.info.name); 6025 } 6026 } else { 6027 Slog.w(TAG, "Permission " + p.info.name + " from package " 6028 + p.info.packageName + " ignored: base tree " 6029 + tree.name + " is from package " 6030 + tree.sourcePackage); 6031 } 6032 } else { 6033 Slog.w(TAG, "Permission " + p.info.name + " from package " 6034 + p.info.packageName + " ignored: original from " 6035 + bp.sourcePackage); 6036 } 6037 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6038 if (r == null) { 6039 r = new StringBuilder(256); 6040 } else { 6041 r.append(' '); 6042 } 6043 r.append("DUP:"); 6044 r.append(p.info.name); 6045 } 6046 if (bp.perm == p) { 6047 bp.protectionLevel = p.info.protectionLevel; 6048 } 6049 } else { 6050 Slog.w(TAG, "Permission " + p.info.name + " from package " 6051 + p.info.packageName + " ignored: no group " 6052 + p.group); 6053 } 6054 } 6055 if (r != null) { 6056 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6057 } 6058 6059 N = pkg.instrumentation.size(); 6060 r = null; 6061 for (i=0; i<N; i++) { 6062 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6063 a.info.packageName = pkg.applicationInfo.packageName; 6064 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6065 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6066 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6067 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6068 a.info.dataDir = pkg.applicationInfo.dataDir; 6069 6070 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6071 // need other information about the application, like the ABI and what not ? 6072 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6073 mInstrumentation.put(a.getComponentName(), a); 6074 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6075 if (r == null) { 6076 r = new StringBuilder(256); 6077 } else { 6078 r.append(' '); 6079 } 6080 r.append(a.info.name); 6081 } 6082 } 6083 if (r != null) { 6084 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6085 } 6086 6087 if (pkg.protectedBroadcasts != null) { 6088 N = pkg.protectedBroadcasts.size(); 6089 for (i=0; i<N; i++) { 6090 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6091 } 6092 } 6093 6094 pkgSetting.setTimeStamp(scanFileTime); 6095 6096 // Create idmap files for pairs of (packages, overlay packages). 6097 // Note: "android", ie framework-res.apk, is handled by native layers. 6098 if (pkg.mOverlayTarget != null) { 6099 // This is an overlay package. 6100 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6101 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6102 mOverlays.put(pkg.mOverlayTarget, 6103 new HashMap<String, PackageParser.Package>()); 6104 } 6105 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6106 map.put(pkg.packageName, pkg); 6107 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6108 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6109 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6110 "scanPackageLI failed to createIdmap"); 6111 } 6112 } 6113 } else if (mOverlays.containsKey(pkg.packageName) && 6114 !pkg.packageName.equals("android")) { 6115 // This is a regular package, with one or more known overlay packages. 6116 createIdmapsForPackageLI(pkg); 6117 } 6118 } 6119 6120 return pkg; 6121 } 6122 6123 /** 6124 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6125 * i.e, so that all packages can be run inside a single process if required. 6126 * 6127 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6128 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6129 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6130 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6131 * updating a package that belongs to a shared user. 6132 * 6133 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6134 * adds unnecessary complexity. 6135 */ 6136 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6137 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6138 String requiredInstructionSet = null; 6139 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6140 requiredInstructionSet = VMRuntime.getInstructionSet( 6141 scannedPackage.applicationInfo.primaryCpuAbi); 6142 } 6143 6144 PackageSetting requirer = null; 6145 for (PackageSetting ps : packagesForUser) { 6146 // If packagesForUser contains scannedPackage, we skip it. This will happen 6147 // when scannedPackage is an update of an existing package. Without this check, 6148 // we will never be able to change the ABI of any package belonging to a shared 6149 // user, even if it's compatible with other packages. 6150 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6151 if (ps.primaryCpuAbiString == null) { 6152 continue; 6153 } 6154 6155 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6156 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6157 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6158 // this but there's not much we can do. 6159 String errorMessage = "Instruction set mismatch, " 6160 + ((requirer == null) ? "[caller]" : requirer) 6161 + " requires " + requiredInstructionSet + " whereas " + ps 6162 + " requires " + instructionSet; 6163 Slog.w(TAG, errorMessage); 6164 } 6165 6166 if (requiredInstructionSet == null) { 6167 requiredInstructionSet = instructionSet; 6168 requirer = ps; 6169 } 6170 } 6171 } 6172 6173 if (requiredInstructionSet != null) { 6174 String adjustedAbi; 6175 if (requirer != null) { 6176 // requirer != null implies that either scannedPackage was null or that scannedPackage 6177 // did not require an ABI, in which case we have to adjust scannedPackage to match 6178 // the ABI of the set (which is the same as requirer's ABI) 6179 adjustedAbi = requirer.primaryCpuAbiString; 6180 if (scannedPackage != null) { 6181 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6182 } 6183 } else { 6184 // requirer == null implies that we're updating all ABIs in the set to 6185 // match scannedPackage. 6186 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6187 } 6188 6189 for (PackageSetting ps : packagesForUser) { 6190 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6191 if (ps.primaryCpuAbiString != null) { 6192 continue; 6193 } 6194 6195 ps.primaryCpuAbiString = adjustedAbi; 6196 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6197 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6198 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6199 6200 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6201 deferDexOpt, true) == DEX_OPT_FAILED) { 6202 ps.primaryCpuAbiString = null; 6203 ps.pkg.applicationInfo.primaryCpuAbi = null; 6204 return; 6205 } else { 6206 mInstaller.rmdex(ps.codePathString, 6207 getDexCodeInstructionSet(getPreferredInstructionSet())); 6208 } 6209 } 6210 } 6211 } 6212 } 6213 } 6214 6215 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6216 synchronized (mPackages) { 6217 mResolverReplaced = true; 6218 // Set up information for custom user intent resolution activity. 6219 mResolveActivity.applicationInfo = pkg.applicationInfo; 6220 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6221 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6222 mResolveActivity.processName = null; 6223 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6224 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6225 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6226 mResolveActivity.theme = 0; 6227 mResolveActivity.exported = true; 6228 mResolveActivity.enabled = true; 6229 mResolveInfo.activityInfo = mResolveActivity; 6230 mResolveInfo.priority = 0; 6231 mResolveInfo.preferredOrder = 0; 6232 mResolveInfo.match = 0; 6233 mResolveComponentName = mCustomResolverComponentName; 6234 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6235 mResolveComponentName); 6236 } 6237 } 6238 6239 private static String calculateApkRoot(final String codePathString) { 6240 final File codePath = new File(codePathString); 6241 final File codeRoot; 6242 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6243 codeRoot = Environment.getRootDirectory(); 6244 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6245 codeRoot = Environment.getOemDirectory(); 6246 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6247 codeRoot = Environment.getVendorDirectory(); 6248 } else { 6249 // Unrecognized code path; take its top real segment as the apk root: 6250 // e.g. /something/app/blah.apk => /something 6251 try { 6252 File f = codePath.getCanonicalFile(); 6253 File parent = f.getParentFile(); // non-null because codePath is a file 6254 File tmp; 6255 while ((tmp = parent.getParentFile()) != null) { 6256 f = parent; 6257 parent = tmp; 6258 } 6259 codeRoot = f; 6260 Slog.w(TAG, "Unrecognized code path " 6261 + codePath + " - using " + codeRoot); 6262 } catch (IOException e) { 6263 // Can't canonicalize the code path -- shenanigans? 6264 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6265 return Environment.getRootDirectory().getPath(); 6266 } 6267 } 6268 return codeRoot.getPath(); 6269 } 6270 6271 /** 6272 * Derive and set the location of native libraries for the given package, 6273 * which varies depending on where and how the package was installed. 6274 */ 6275 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6276 final ApplicationInfo info = pkg.applicationInfo; 6277 final String codePath = pkg.codePath; 6278 final File codeFile = new File(codePath); 6279 // If "/system/lib64/apkname" exists, assume that is the per-package 6280 // native library directory to use; otherwise use "/system/lib/apkname". 6281 final String apkRoot = calculateApkRoot(info.sourceDir); 6282 6283 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6284 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6285 6286 6287 info.nativeLibraryRootDir = null; 6288 info.nativeLibraryRootRequiresIsa = false; 6289 info.nativeLibraryDir = null; 6290 info.secondaryNativeLibraryDir = null; 6291 6292 if (isApkFile(codeFile)) { 6293 // Monolithic install 6294 if (bundledApp) { 6295 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6296 getPrimaryInstructionSet(info)); 6297 6298 // This is a bundled system app so choose the path based on the ABI. 6299 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6300 // is just the default path. 6301 final String apkName = deriveCodePathName(codePath); 6302 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6303 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6304 apkName).getAbsolutePath(); 6305 6306 if (info.secondaryCpuAbi != null) { 6307 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6308 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6309 secondaryLibDir, apkName).getAbsolutePath(); 6310 } 6311 } else if (asecApp) { 6312 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6313 .getAbsolutePath(); 6314 } else { 6315 final String apkName = deriveCodePathName(codePath); 6316 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6317 .getAbsolutePath(); 6318 } 6319 6320 info.nativeLibraryRootRequiresIsa = false; 6321 info.nativeLibraryDir = info.nativeLibraryRootDir; 6322 } else { 6323 // Cluster install 6324 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6325 info.nativeLibraryRootRequiresIsa = true; 6326 6327 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6328 getPrimaryInstructionSet(info)).getAbsolutePath(); 6329 6330 if (info.secondaryCpuAbi != null) { 6331 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6332 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6333 } 6334 } 6335 } 6336 6337 /** 6338 * Calculate the abis and roots for a bundled app. These can uniquely 6339 * be determined from the contents of the system partition, i.e whether 6340 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6341 * of this information, and instead assume that the system was built 6342 * sensibly. 6343 */ 6344 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6345 PackageSetting pkgSetting) { 6346 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6347 6348 // If "/system/lib64/apkname" exists, assume that is the per-package 6349 // native library directory to use; otherwise use "/system/lib/apkname". 6350 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6351 setBundledAppAbi(pkg, apkRoot, apkName); 6352 // pkgSetting might be null during rescan following uninstall of updates 6353 // to a bundled app, so accommodate that possibility. The settings in 6354 // that case will be established later from the parsed package. 6355 // 6356 // If the settings aren't null, sync them up with what we've just derived. 6357 // note that apkRoot isn't stored in the package settings. 6358 if (pkgSetting != null) { 6359 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6360 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6361 } 6362 } 6363 6364 /** 6365 * Deduces the ABI of a bundled app and sets the relevant fields on the 6366 * parsed pkg object. 6367 * 6368 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6369 * under which system libraries are installed. 6370 * @param apkName the name of the installed package. 6371 */ 6372 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6373 final File codeFile = new File(pkg.codePath); 6374 6375 final boolean has64BitLibs; 6376 final boolean has32BitLibs; 6377 if (isApkFile(codeFile)) { 6378 // Monolithic install 6379 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6380 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6381 } else { 6382 // Cluster install 6383 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6384 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6385 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6386 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6387 has64BitLibs = (new File(rootDir, isa)).exists(); 6388 } else { 6389 has64BitLibs = false; 6390 } 6391 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6392 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6393 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6394 has32BitLibs = (new File(rootDir, isa)).exists(); 6395 } else { 6396 has32BitLibs = false; 6397 } 6398 } 6399 6400 if (has64BitLibs && !has32BitLibs) { 6401 // The package has 64 bit libs, but not 32 bit libs. Its primary 6402 // ABI should be 64 bit. We can safely assume here that the bundled 6403 // native libraries correspond to the most preferred ABI in the list. 6404 6405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6406 pkg.applicationInfo.secondaryCpuAbi = null; 6407 } else if (has32BitLibs && !has64BitLibs) { 6408 // The package has 32 bit libs but not 64 bit libs. Its primary 6409 // ABI should be 32 bit. 6410 6411 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6412 pkg.applicationInfo.secondaryCpuAbi = null; 6413 } else if (has32BitLibs && has64BitLibs) { 6414 // The application has both 64 and 32 bit bundled libraries. We check 6415 // here that the app declares multiArch support, and warn if it doesn't. 6416 // 6417 // We will be lenient here and record both ABIs. The primary will be the 6418 // ABI that's higher on the list, i.e, a device that's configured to prefer 6419 // 64 bit apps will see a 64 bit primary ABI, 6420 6421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6422 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6423 } 6424 6425 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6426 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6427 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6428 } else { 6429 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6430 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6431 } 6432 } else { 6433 pkg.applicationInfo.primaryCpuAbi = null; 6434 pkg.applicationInfo.secondaryCpuAbi = null; 6435 } 6436 } 6437 6438 private static void createNativeLibrarySubdir(File path) throws IOException { 6439 if (!path.isDirectory()) { 6440 path.delete(); 6441 6442 if (!path.mkdir()) { 6443 throw new IOException("Cannot create " + path.getPath()); 6444 } 6445 6446 try { 6447 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6448 } catch (ErrnoException e) { 6449 throw new IOException("Cannot chmod native library directory " 6450 + path.getPath(), e); 6451 } 6452 } else if (!SELinux.restorecon(path)) { 6453 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6454 } 6455 } 6456 6457 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6458 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6459 createNativeLibrarySubdir(nativeLibraryRoot); 6460 6461 /* 6462 * If this is an internal application or our nativeLibraryPath points to 6463 * the app-lib directory, unpack the libraries if necessary. 6464 */ 6465 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6466 if (abi >= 0) { 6467 /* 6468 * If we have a matching instruction set, construct a subdir under the native 6469 * library root that corresponds to this instruction set. 6470 */ 6471 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6472 final File subDir; 6473 if (useIsaSubdir) { 6474 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6475 createNativeLibrarySubdir(isaSubdir); 6476 subDir = isaSubdir; 6477 } else { 6478 subDir = nativeLibraryRoot; 6479 } 6480 6481 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6482 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6483 return copyRet; 6484 } 6485 } 6486 6487 return abi; 6488 } 6489 6490 private void killApplication(String pkgName, int appId, String reason) { 6491 // Request the ActivityManager to kill the process(only for existing packages) 6492 // so that we do not end up in a confused state while the user is still using the older 6493 // version of the application while the new one gets installed. 6494 IActivityManager am = ActivityManagerNative.getDefault(); 6495 if (am != null) { 6496 try { 6497 am.killApplicationWithAppId(pkgName, appId, reason); 6498 } catch (RemoteException e) { 6499 } 6500 } 6501 } 6502 6503 void removePackageLI(PackageSetting ps, boolean chatty) { 6504 if (DEBUG_INSTALL) { 6505 if (chatty) 6506 Log.d(TAG, "Removing package " + ps.name); 6507 } 6508 6509 // writer 6510 synchronized (mPackages) { 6511 mPackages.remove(ps.name); 6512 if (ps.codePathString != null) { 6513 mAppDirs.remove(ps.codePathString); 6514 } 6515 6516 final PackageParser.Package pkg = ps.pkg; 6517 if (pkg != null) { 6518 cleanPackageDataStructuresLILPw(pkg, chatty); 6519 } 6520 } 6521 } 6522 6523 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6524 if (DEBUG_INSTALL) { 6525 if (chatty) 6526 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6527 } 6528 6529 // writer 6530 synchronized (mPackages) { 6531 mPackages.remove(pkg.applicationInfo.packageName); 6532 if (pkg.codePath != null) { 6533 mAppDirs.remove(pkg.codePath); 6534 } 6535 cleanPackageDataStructuresLILPw(pkg, chatty); 6536 } 6537 } 6538 6539 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6540 int N = pkg.providers.size(); 6541 StringBuilder r = null; 6542 int i; 6543 for (i=0; i<N; i++) { 6544 PackageParser.Provider p = pkg.providers.get(i); 6545 mProviders.removeProvider(p); 6546 if (p.info.authority == null) { 6547 6548 /* There was another ContentProvider with this authority when 6549 * this app was installed so this authority is null, 6550 * Ignore it as we don't have to unregister the provider. 6551 */ 6552 continue; 6553 } 6554 String names[] = p.info.authority.split(";"); 6555 for (int j = 0; j < names.length; j++) { 6556 if (mProvidersByAuthority.get(names[j]) == p) { 6557 mProvidersByAuthority.remove(names[j]); 6558 if (DEBUG_REMOVE) { 6559 if (chatty) 6560 Log.d(TAG, "Unregistered content provider: " + names[j] 6561 + ", className = " + p.info.name + ", isSyncable = " 6562 + p.info.isSyncable); 6563 } 6564 } 6565 } 6566 if (DEBUG_REMOVE && chatty) { 6567 if (r == null) { 6568 r = new StringBuilder(256); 6569 } else { 6570 r.append(' '); 6571 } 6572 r.append(p.info.name); 6573 } 6574 } 6575 if (r != null) { 6576 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6577 } 6578 6579 N = pkg.services.size(); 6580 r = null; 6581 for (i=0; i<N; i++) { 6582 PackageParser.Service s = pkg.services.get(i); 6583 mServices.removeService(s); 6584 if (chatty) { 6585 if (r == null) { 6586 r = new StringBuilder(256); 6587 } else { 6588 r.append(' '); 6589 } 6590 r.append(s.info.name); 6591 } 6592 } 6593 if (r != null) { 6594 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6595 } 6596 6597 N = pkg.receivers.size(); 6598 r = null; 6599 for (i=0; i<N; i++) { 6600 PackageParser.Activity a = pkg.receivers.get(i); 6601 mReceivers.removeActivity(a, "receiver"); 6602 if (DEBUG_REMOVE && chatty) { 6603 if (r == null) { 6604 r = new StringBuilder(256); 6605 } else { 6606 r.append(' '); 6607 } 6608 r.append(a.info.name); 6609 } 6610 } 6611 if (r != null) { 6612 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6613 } 6614 6615 N = pkg.activities.size(); 6616 r = null; 6617 for (i=0; i<N; i++) { 6618 PackageParser.Activity a = pkg.activities.get(i); 6619 mActivities.removeActivity(a, "activity"); 6620 if (DEBUG_REMOVE && chatty) { 6621 if (r == null) { 6622 r = new StringBuilder(256); 6623 } else { 6624 r.append(' '); 6625 } 6626 r.append(a.info.name); 6627 } 6628 } 6629 if (r != null) { 6630 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6631 } 6632 6633 N = pkg.permissions.size(); 6634 r = null; 6635 for (i=0; i<N; i++) { 6636 PackageParser.Permission p = pkg.permissions.get(i); 6637 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6638 if (bp == null) { 6639 bp = mSettings.mPermissionTrees.get(p.info.name); 6640 } 6641 if (bp != null && bp.perm == p) { 6642 bp.perm = null; 6643 if (DEBUG_REMOVE && chatty) { 6644 if (r == null) { 6645 r = new StringBuilder(256); 6646 } else { 6647 r.append(' '); 6648 } 6649 r.append(p.info.name); 6650 } 6651 } 6652 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6653 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6654 if (appOpPerms != null) { 6655 appOpPerms.remove(pkg.packageName); 6656 } 6657 } 6658 } 6659 if (r != null) { 6660 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6661 } 6662 6663 N = pkg.requestedPermissions.size(); 6664 r = null; 6665 for (i=0; i<N; i++) { 6666 String perm = pkg.requestedPermissions.get(i); 6667 BasePermission bp = mSettings.mPermissions.get(perm); 6668 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6669 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6670 if (appOpPerms != null) { 6671 appOpPerms.remove(pkg.packageName); 6672 if (appOpPerms.isEmpty()) { 6673 mAppOpPermissionPackages.remove(perm); 6674 } 6675 } 6676 } 6677 } 6678 if (r != null) { 6679 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6680 } 6681 6682 N = pkg.instrumentation.size(); 6683 r = null; 6684 for (i=0; i<N; i++) { 6685 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6686 mInstrumentation.remove(a.getComponentName()); 6687 if (DEBUG_REMOVE && chatty) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(a.info.name); 6694 } 6695 } 6696 if (r != null) { 6697 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6698 } 6699 6700 r = null; 6701 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6702 // Only system apps can hold shared libraries. 6703 if (pkg.libraryNames != null) { 6704 for (i=0; i<pkg.libraryNames.size(); i++) { 6705 String name = pkg.libraryNames.get(i); 6706 SharedLibraryEntry cur = mSharedLibraries.get(name); 6707 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6708 mSharedLibraries.remove(name); 6709 if (DEBUG_REMOVE && chatty) { 6710 if (r == null) { 6711 r = new StringBuilder(256); 6712 } else { 6713 r.append(' '); 6714 } 6715 r.append(name); 6716 } 6717 } 6718 } 6719 } 6720 } 6721 if (r != null) { 6722 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6723 } 6724 } 6725 6726 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6727 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6728 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6729 return true; 6730 } 6731 } 6732 return false; 6733 } 6734 6735 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6736 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6737 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6738 6739 private void updatePermissionsLPw(String changingPkg, 6740 PackageParser.Package pkgInfo, int flags) { 6741 // Make sure there are no dangling permission trees. 6742 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6743 while (it.hasNext()) { 6744 final BasePermission bp = it.next(); 6745 if (bp.packageSetting == null) { 6746 // We may not yet have parsed the package, so just see if 6747 // we still know about its settings. 6748 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6749 } 6750 if (bp.packageSetting == null) { 6751 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6752 + " from package " + bp.sourcePackage); 6753 it.remove(); 6754 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6755 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6756 Slog.i(TAG, "Removing old permission tree: " + bp.name 6757 + " from package " + bp.sourcePackage); 6758 flags |= UPDATE_PERMISSIONS_ALL; 6759 it.remove(); 6760 } 6761 } 6762 } 6763 6764 // Make sure all dynamic permissions have been assigned to a package, 6765 // and make sure there are no dangling permissions. 6766 it = mSettings.mPermissions.values().iterator(); 6767 while (it.hasNext()) { 6768 final BasePermission bp = it.next(); 6769 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6770 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6771 + bp.name + " pkg=" + bp.sourcePackage 6772 + " info=" + bp.pendingInfo); 6773 if (bp.packageSetting == null && bp.pendingInfo != null) { 6774 final BasePermission tree = findPermissionTreeLP(bp.name); 6775 if (tree != null && tree.perm != null) { 6776 bp.packageSetting = tree.packageSetting; 6777 bp.perm = new PackageParser.Permission(tree.perm.owner, 6778 new PermissionInfo(bp.pendingInfo)); 6779 bp.perm.info.packageName = tree.perm.info.packageName; 6780 bp.perm.info.name = bp.name; 6781 bp.uid = tree.uid; 6782 } 6783 } 6784 } 6785 if (bp.packageSetting == null) { 6786 // We may not yet have parsed the package, so just see if 6787 // we still know about its settings. 6788 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6789 } 6790 if (bp.packageSetting == null) { 6791 Slog.w(TAG, "Removing dangling permission: " + bp.name 6792 + " from package " + bp.sourcePackage); 6793 it.remove(); 6794 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6795 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6796 Slog.i(TAG, "Removing old permission: " + bp.name 6797 + " from package " + bp.sourcePackage); 6798 flags |= UPDATE_PERMISSIONS_ALL; 6799 it.remove(); 6800 } 6801 } 6802 } 6803 6804 // Now update the permissions for all packages, in particular 6805 // replace the granted permissions of the system packages. 6806 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6807 for (PackageParser.Package pkg : mPackages.values()) { 6808 if (pkg != pkgInfo) { 6809 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6810 } 6811 } 6812 } 6813 6814 if (pkgInfo != null) { 6815 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6816 } 6817 } 6818 6819 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6820 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6821 if (ps == null) { 6822 return; 6823 } 6824 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6825 HashSet<String> origPermissions = gp.grantedPermissions; 6826 boolean changedPermission = false; 6827 6828 if (replace) { 6829 ps.permissionsFixed = false; 6830 if (gp == ps) { 6831 origPermissions = new HashSet<String>(gp.grantedPermissions); 6832 gp.grantedPermissions.clear(); 6833 gp.gids = mGlobalGids; 6834 } 6835 } 6836 6837 if (gp.gids == null) { 6838 gp.gids = mGlobalGids; 6839 } 6840 6841 final int N = pkg.requestedPermissions.size(); 6842 for (int i=0; i<N; i++) { 6843 final String name = pkg.requestedPermissions.get(i); 6844 final boolean required = pkg.requestedPermissionsRequired.get(i); 6845 final BasePermission bp = mSettings.mPermissions.get(name); 6846 if (DEBUG_INSTALL) { 6847 if (gp != ps) { 6848 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6849 } 6850 } 6851 6852 if (bp == null || bp.packageSetting == null) { 6853 Slog.w(TAG, "Unknown permission " + name 6854 + " in package " + pkg.packageName); 6855 continue; 6856 } 6857 6858 final String perm = bp.name; 6859 boolean allowed; 6860 boolean allowedSig = false; 6861 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6862 // Keep track of app op permissions. 6863 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6864 if (pkgs == null) { 6865 pkgs = new ArraySet<>(); 6866 mAppOpPermissionPackages.put(bp.name, pkgs); 6867 } 6868 pkgs.add(pkg.packageName); 6869 } 6870 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6871 if (level == PermissionInfo.PROTECTION_NORMAL 6872 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6873 // We grant a normal or dangerous permission if any of the following 6874 // are true: 6875 // 1) The permission is required 6876 // 2) The permission is optional, but was granted in the past 6877 // 3) The permission is optional, but was requested by an 6878 // app in /system (not /data) 6879 // 6880 // Otherwise, reject the permission. 6881 allowed = (required || origPermissions.contains(perm) 6882 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6883 } else if (bp.packageSetting == null) { 6884 // This permission is invalid; skip it. 6885 allowed = false; 6886 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6887 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6888 if (allowed) { 6889 allowedSig = true; 6890 } 6891 } else { 6892 allowed = false; 6893 } 6894 if (DEBUG_INSTALL) { 6895 if (gp != ps) { 6896 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6897 } 6898 } 6899 if (allowed) { 6900 if (!isSystemApp(ps) && ps.permissionsFixed) { 6901 // If this is an existing, non-system package, then 6902 // we can't add any new permissions to it. 6903 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6904 // Except... if this is a permission that was added 6905 // to the platform (note: need to only do this when 6906 // updating the platform). 6907 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6908 } 6909 } 6910 if (allowed) { 6911 if (!gp.grantedPermissions.contains(perm)) { 6912 changedPermission = true; 6913 gp.grantedPermissions.add(perm); 6914 gp.gids = appendInts(gp.gids, bp.gids); 6915 } else if (!ps.haveGids) { 6916 gp.gids = appendInts(gp.gids, bp.gids); 6917 } 6918 } else { 6919 Slog.w(TAG, "Not granting permission " + perm 6920 + " to package " + pkg.packageName 6921 + " because it was previously installed without"); 6922 } 6923 } else { 6924 if (gp.grantedPermissions.remove(perm)) { 6925 changedPermission = true; 6926 gp.gids = removeInts(gp.gids, bp.gids); 6927 Slog.i(TAG, "Un-granting permission " + perm 6928 + " from package " + pkg.packageName 6929 + " (protectionLevel=" + bp.protectionLevel 6930 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6931 + ")"); 6932 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6933 // Don't print warning for app op permissions, since it is fine for them 6934 // not to be granted, there is a UI for the user to decide. 6935 Slog.w(TAG, "Not granting permission " + perm 6936 + " to package " + pkg.packageName 6937 + " (protectionLevel=" + bp.protectionLevel 6938 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6939 + ")"); 6940 } 6941 } 6942 } 6943 6944 if ((changedPermission || replace) && !ps.permissionsFixed && 6945 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6946 // This is the first that we have heard about this package, so the 6947 // permissions we have now selected are fixed until explicitly 6948 // changed. 6949 ps.permissionsFixed = true; 6950 } 6951 ps.haveGids = true; 6952 } 6953 6954 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6955 boolean allowed = false; 6956 final int NP = PackageParser.NEW_PERMISSIONS.length; 6957 for (int ip=0; ip<NP; ip++) { 6958 final PackageParser.NewPermissionInfo npi 6959 = PackageParser.NEW_PERMISSIONS[ip]; 6960 if (npi.name.equals(perm) 6961 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6962 allowed = true; 6963 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6964 + pkg.packageName); 6965 break; 6966 } 6967 } 6968 return allowed; 6969 } 6970 6971 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6972 BasePermission bp, HashSet<String> origPermissions) { 6973 boolean allowed; 6974 allowed = (compareSignatures( 6975 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6976 == PackageManager.SIGNATURE_MATCH) 6977 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6978 == PackageManager.SIGNATURE_MATCH); 6979 if (!allowed && (bp.protectionLevel 6980 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6981 if (isSystemApp(pkg)) { 6982 // For updated system applications, a system permission 6983 // is granted only if it had been defined by the original application. 6984 if (isUpdatedSystemApp(pkg)) { 6985 final PackageSetting sysPs = mSettings 6986 .getDisabledSystemPkgLPr(pkg.packageName); 6987 final GrantedPermissions origGp = sysPs.sharedUser != null 6988 ? sysPs.sharedUser : sysPs; 6989 6990 if (origGp.grantedPermissions.contains(perm)) { 6991 // If the original was granted this permission, we take 6992 // that grant decision as read and propagate it to the 6993 // update. 6994 allowed = true; 6995 } else { 6996 // The system apk may have been updated with an older 6997 // version of the one on the data partition, but which 6998 // granted a new system permission that it didn't have 6999 // before. In this case we do want to allow the app to 7000 // now get the new permission if the ancestral apk is 7001 // privileged to get it. 7002 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7003 for (int j=0; 7004 j<sysPs.pkg.requestedPermissions.size(); j++) { 7005 if (perm.equals( 7006 sysPs.pkg.requestedPermissions.get(j))) { 7007 allowed = true; 7008 break; 7009 } 7010 } 7011 } 7012 } 7013 } else { 7014 allowed = isPrivilegedApp(pkg); 7015 } 7016 } 7017 } 7018 if (!allowed && (bp.protectionLevel 7019 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7020 // For development permissions, a development permission 7021 // is granted only if it was already granted. 7022 allowed = origPermissions.contains(perm); 7023 } 7024 return allowed; 7025 } 7026 7027 final class ActivityIntentResolver 7028 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7029 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7030 boolean defaultOnly, int userId) { 7031 if (!sUserManager.exists(userId)) return null; 7032 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7033 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7034 } 7035 7036 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7037 int userId) { 7038 if (!sUserManager.exists(userId)) return null; 7039 mFlags = flags; 7040 return super.queryIntent(intent, resolvedType, 7041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7042 } 7043 7044 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7045 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7046 if (!sUserManager.exists(userId)) return null; 7047 if (packageActivities == null) { 7048 return null; 7049 } 7050 mFlags = flags; 7051 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7052 final int N = packageActivities.size(); 7053 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7054 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7055 7056 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7057 for (int i = 0; i < N; ++i) { 7058 intentFilters = packageActivities.get(i).intents; 7059 if (intentFilters != null && intentFilters.size() > 0) { 7060 PackageParser.ActivityIntentInfo[] array = 7061 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7062 intentFilters.toArray(array); 7063 listCut.add(array); 7064 } 7065 } 7066 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7067 } 7068 7069 public final void addActivity(PackageParser.Activity a, String type) { 7070 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7071 mActivities.put(a.getComponentName(), a); 7072 if (DEBUG_SHOW_INFO) 7073 Log.v( 7074 TAG, " " + type + " " + 7075 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7076 if (DEBUG_SHOW_INFO) 7077 Log.v(TAG, " Class=" + a.info.name); 7078 final int NI = a.intents.size(); 7079 for (int j=0; j<NI; j++) { 7080 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7081 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7082 intent.setPriority(0); 7083 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7084 + a.className + " with priority > 0, forcing to 0"); 7085 } 7086 if (DEBUG_SHOW_INFO) { 7087 Log.v(TAG, " IntentFilter:"); 7088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7089 } 7090 if (!intent.debugCheck()) { 7091 Log.w(TAG, "==> For Activity " + a.info.name); 7092 } 7093 addFilter(intent); 7094 } 7095 } 7096 7097 public final void removeActivity(PackageParser.Activity a, String type) { 7098 mActivities.remove(a.getComponentName()); 7099 if (DEBUG_SHOW_INFO) { 7100 Log.v(TAG, " " + type + " " 7101 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7102 : a.info.name) + ":"); 7103 Log.v(TAG, " Class=" + a.info.name); 7104 } 7105 final int NI = a.intents.size(); 7106 for (int j=0; j<NI; j++) { 7107 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7108 if (DEBUG_SHOW_INFO) { 7109 Log.v(TAG, " IntentFilter:"); 7110 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7111 } 7112 removeFilter(intent); 7113 } 7114 } 7115 7116 @Override 7117 protected boolean allowFilterResult( 7118 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7119 ActivityInfo filterAi = filter.activity.info; 7120 for (int i=dest.size()-1; i>=0; i--) { 7121 ActivityInfo destAi = dest.get(i).activityInfo; 7122 if (destAi.name == filterAi.name 7123 && destAi.packageName == filterAi.packageName) { 7124 return false; 7125 } 7126 } 7127 return true; 7128 } 7129 7130 @Override 7131 protected ActivityIntentInfo[] newArray(int size) { 7132 return new ActivityIntentInfo[size]; 7133 } 7134 7135 @Override 7136 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7137 if (!sUserManager.exists(userId)) return true; 7138 PackageParser.Package p = filter.activity.owner; 7139 if (p != null) { 7140 PackageSetting ps = (PackageSetting)p.mExtras; 7141 if (ps != null) { 7142 // System apps are never considered stopped for purposes of 7143 // filtering, because there may be no way for the user to 7144 // actually re-launch them. 7145 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7146 && ps.getStopped(userId); 7147 } 7148 } 7149 return false; 7150 } 7151 7152 @Override 7153 protected boolean isPackageForFilter(String packageName, 7154 PackageParser.ActivityIntentInfo info) { 7155 return packageName.equals(info.activity.owner.packageName); 7156 } 7157 7158 @Override 7159 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7160 int match, int userId) { 7161 if (!sUserManager.exists(userId)) return null; 7162 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7163 return null; 7164 } 7165 final PackageParser.Activity activity = info.activity; 7166 if (mSafeMode && (activity.info.applicationInfo.flags 7167 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7168 return null; 7169 } 7170 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7171 if (ps == null) { 7172 return null; 7173 } 7174 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7175 ps.readUserState(userId), userId); 7176 if (ai == null) { 7177 return null; 7178 } 7179 final ResolveInfo res = new ResolveInfo(); 7180 res.activityInfo = ai; 7181 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7182 res.filter = info; 7183 } 7184 res.priority = info.getPriority(); 7185 res.preferredOrder = activity.owner.mPreferredOrder; 7186 //System.out.println("Result: " + res.activityInfo.className + 7187 // " = " + res.priority); 7188 res.match = match; 7189 res.isDefault = info.hasDefault; 7190 res.labelRes = info.labelRes; 7191 res.nonLocalizedLabel = info.nonLocalizedLabel; 7192 if (userNeedsBadging(userId)) { 7193 res.noResourceId = true; 7194 } else { 7195 res.icon = info.icon; 7196 } 7197 res.system = isSystemApp(res.activityInfo.applicationInfo); 7198 return res; 7199 } 7200 7201 @Override 7202 protected void sortResults(List<ResolveInfo> results) { 7203 Collections.sort(results, mResolvePrioritySorter); 7204 } 7205 7206 @Override 7207 protected void dumpFilter(PrintWriter out, String prefix, 7208 PackageParser.ActivityIntentInfo filter) { 7209 out.print(prefix); out.print( 7210 Integer.toHexString(System.identityHashCode(filter.activity))); 7211 out.print(' '); 7212 filter.activity.printComponentShortName(out); 7213 out.print(" filter "); 7214 out.println(Integer.toHexString(System.identityHashCode(filter))); 7215 } 7216 7217// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7218// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7219// final List<ResolveInfo> retList = Lists.newArrayList(); 7220// while (i.hasNext()) { 7221// final ResolveInfo resolveInfo = i.next(); 7222// if (isEnabledLP(resolveInfo.activityInfo)) { 7223// retList.add(resolveInfo); 7224// } 7225// } 7226// return retList; 7227// } 7228 7229 // Keys are String (activity class name), values are Activity. 7230 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7231 = new HashMap<ComponentName, PackageParser.Activity>(); 7232 private int mFlags; 7233 } 7234 7235 private final class ServiceIntentResolver 7236 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7237 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7238 boolean defaultOnly, int userId) { 7239 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7240 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7241 } 7242 7243 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7244 int userId) { 7245 if (!sUserManager.exists(userId)) return null; 7246 mFlags = flags; 7247 return super.queryIntent(intent, resolvedType, 7248 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7249 } 7250 7251 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7252 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7253 if (!sUserManager.exists(userId)) return null; 7254 if (packageServices == null) { 7255 return null; 7256 } 7257 mFlags = flags; 7258 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7259 final int N = packageServices.size(); 7260 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7261 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7262 7263 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7264 for (int i = 0; i < N; ++i) { 7265 intentFilters = packageServices.get(i).intents; 7266 if (intentFilters != null && intentFilters.size() > 0) { 7267 PackageParser.ServiceIntentInfo[] array = 7268 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7269 intentFilters.toArray(array); 7270 listCut.add(array); 7271 } 7272 } 7273 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7274 } 7275 7276 public final void addService(PackageParser.Service s) { 7277 mServices.put(s.getComponentName(), s); 7278 if (DEBUG_SHOW_INFO) { 7279 Log.v(TAG, " " 7280 + (s.info.nonLocalizedLabel != null 7281 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7282 Log.v(TAG, " Class=" + s.info.name); 7283 } 7284 final int NI = s.intents.size(); 7285 int j; 7286 for (j=0; j<NI; j++) { 7287 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7288 if (DEBUG_SHOW_INFO) { 7289 Log.v(TAG, " IntentFilter:"); 7290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7291 } 7292 if (!intent.debugCheck()) { 7293 Log.w(TAG, "==> For Service " + s.info.name); 7294 } 7295 addFilter(intent); 7296 } 7297 } 7298 7299 public final void removeService(PackageParser.Service s) { 7300 mServices.remove(s.getComponentName()); 7301 if (DEBUG_SHOW_INFO) { 7302 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7303 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7304 Log.v(TAG, " Class=" + s.info.name); 7305 } 7306 final int NI = s.intents.size(); 7307 int j; 7308 for (j=0; j<NI; j++) { 7309 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7310 if (DEBUG_SHOW_INFO) { 7311 Log.v(TAG, " IntentFilter:"); 7312 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7313 } 7314 removeFilter(intent); 7315 } 7316 } 7317 7318 @Override 7319 protected boolean allowFilterResult( 7320 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7321 ServiceInfo filterSi = filter.service.info; 7322 for (int i=dest.size()-1; i>=0; i--) { 7323 ServiceInfo destAi = dest.get(i).serviceInfo; 7324 if (destAi.name == filterSi.name 7325 && destAi.packageName == filterSi.packageName) { 7326 return false; 7327 } 7328 } 7329 return true; 7330 } 7331 7332 @Override 7333 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7334 return new PackageParser.ServiceIntentInfo[size]; 7335 } 7336 7337 @Override 7338 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7339 if (!sUserManager.exists(userId)) return true; 7340 PackageParser.Package p = filter.service.owner; 7341 if (p != null) { 7342 PackageSetting ps = (PackageSetting)p.mExtras; 7343 if (ps != null) { 7344 // System apps are never considered stopped for purposes of 7345 // filtering, because there may be no way for the user to 7346 // actually re-launch them. 7347 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7348 && ps.getStopped(userId); 7349 } 7350 } 7351 return false; 7352 } 7353 7354 @Override 7355 protected boolean isPackageForFilter(String packageName, 7356 PackageParser.ServiceIntentInfo info) { 7357 return packageName.equals(info.service.owner.packageName); 7358 } 7359 7360 @Override 7361 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7362 int match, int userId) { 7363 if (!sUserManager.exists(userId)) return null; 7364 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7365 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7366 return null; 7367 } 7368 final PackageParser.Service service = info.service; 7369 if (mSafeMode && (service.info.applicationInfo.flags 7370 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7371 return null; 7372 } 7373 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7374 if (ps == null) { 7375 return null; 7376 } 7377 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7378 ps.readUserState(userId), userId); 7379 if (si == null) { 7380 return null; 7381 } 7382 final ResolveInfo res = new ResolveInfo(); 7383 res.serviceInfo = si; 7384 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7385 res.filter = filter; 7386 } 7387 res.priority = info.getPriority(); 7388 res.preferredOrder = service.owner.mPreferredOrder; 7389 //System.out.println("Result: " + res.activityInfo.className + 7390 // " = " + res.priority); 7391 res.match = match; 7392 res.isDefault = info.hasDefault; 7393 res.labelRes = info.labelRes; 7394 res.nonLocalizedLabel = info.nonLocalizedLabel; 7395 res.icon = info.icon; 7396 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7397 return res; 7398 } 7399 7400 @Override 7401 protected void sortResults(List<ResolveInfo> results) { 7402 Collections.sort(results, mResolvePrioritySorter); 7403 } 7404 7405 @Override 7406 protected void dumpFilter(PrintWriter out, String prefix, 7407 PackageParser.ServiceIntentInfo filter) { 7408 out.print(prefix); out.print( 7409 Integer.toHexString(System.identityHashCode(filter.service))); 7410 out.print(' '); 7411 filter.service.printComponentShortName(out); 7412 out.print(" filter "); 7413 out.println(Integer.toHexString(System.identityHashCode(filter))); 7414 } 7415 7416// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7417// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7418// final List<ResolveInfo> retList = Lists.newArrayList(); 7419// while (i.hasNext()) { 7420// final ResolveInfo resolveInfo = (ResolveInfo) i; 7421// if (isEnabledLP(resolveInfo.serviceInfo)) { 7422// retList.add(resolveInfo); 7423// } 7424// } 7425// return retList; 7426// } 7427 7428 // Keys are String (activity class name), values are Activity. 7429 private final HashMap<ComponentName, PackageParser.Service> mServices 7430 = new HashMap<ComponentName, PackageParser.Service>(); 7431 private int mFlags; 7432 }; 7433 7434 private final class ProviderIntentResolver 7435 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7436 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7437 boolean defaultOnly, int userId) { 7438 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7439 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7440 } 7441 7442 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7443 int userId) { 7444 if (!sUserManager.exists(userId)) 7445 return null; 7446 mFlags = flags; 7447 return super.queryIntent(intent, resolvedType, 7448 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7449 } 7450 7451 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7452 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7453 if (!sUserManager.exists(userId)) 7454 return null; 7455 if (packageProviders == null) { 7456 return null; 7457 } 7458 mFlags = flags; 7459 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7460 final int N = packageProviders.size(); 7461 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7462 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7463 7464 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7465 for (int i = 0; i < N; ++i) { 7466 intentFilters = packageProviders.get(i).intents; 7467 if (intentFilters != null && intentFilters.size() > 0) { 7468 PackageParser.ProviderIntentInfo[] array = 7469 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7470 intentFilters.toArray(array); 7471 listCut.add(array); 7472 } 7473 } 7474 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7475 } 7476 7477 public final void addProvider(PackageParser.Provider p) { 7478 if (mProviders.containsKey(p.getComponentName())) { 7479 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7480 return; 7481 } 7482 7483 mProviders.put(p.getComponentName(), p); 7484 if (DEBUG_SHOW_INFO) { 7485 Log.v(TAG, " " 7486 + (p.info.nonLocalizedLabel != null 7487 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7488 Log.v(TAG, " Class=" + p.info.name); 7489 } 7490 final int NI = p.intents.size(); 7491 int j; 7492 for (j = 0; j < NI; j++) { 7493 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7494 if (DEBUG_SHOW_INFO) { 7495 Log.v(TAG, " IntentFilter:"); 7496 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7497 } 7498 if (!intent.debugCheck()) { 7499 Log.w(TAG, "==> For Provider " + p.info.name); 7500 } 7501 addFilter(intent); 7502 } 7503 } 7504 7505 public final void removeProvider(PackageParser.Provider p) { 7506 mProviders.remove(p.getComponentName()); 7507 if (DEBUG_SHOW_INFO) { 7508 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7509 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7510 Log.v(TAG, " Class=" + p.info.name); 7511 } 7512 final int NI = p.intents.size(); 7513 int j; 7514 for (j = 0; j < NI; j++) { 7515 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7516 if (DEBUG_SHOW_INFO) { 7517 Log.v(TAG, " IntentFilter:"); 7518 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7519 } 7520 removeFilter(intent); 7521 } 7522 } 7523 7524 @Override 7525 protected boolean allowFilterResult( 7526 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7527 ProviderInfo filterPi = filter.provider.info; 7528 for (int i = dest.size() - 1; i >= 0; i--) { 7529 ProviderInfo destPi = dest.get(i).providerInfo; 7530 if (destPi.name == filterPi.name 7531 && destPi.packageName == filterPi.packageName) { 7532 return false; 7533 } 7534 } 7535 return true; 7536 } 7537 7538 @Override 7539 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7540 return new PackageParser.ProviderIntentInfo[size]; 7541 } 7542 7543 @Override 7544 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7545 if (!sUserManager.exists(userId)) 7546 return true; 7547 PackageParser.Package p = filter.provider.owner; 7548 if (p != null) { 7549 PackageSetting ps = (PackageSetting) p.mExtras; 7550 if (ps != null) { 7551 // System apps are never considered stopped for purposes of 7552 // filtering, because there may be no way for the user to 7553 // actually re-launch them. 7554 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7555 && ps.getStopped(userId); 7556 } 7557 } 7558 return false; 7559 } 7560 7561 @Override 7562 protected boolean isPackageForFilter(String packageName, 7563 PackageParser.ProviderIntentInfo info) { 7564 return packageName.equals(info.provider.owner.packageName); 7565 } 7566 7567 @Override 7568 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7569 int match, int userId) { 7570 if (!sUserManager.exists(userId)) 7571 return null; 7572 final PackageParser.ProviderIntentInfo info = filter; 7573 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7574 return null; 7575 } 7576 final PackageParser.Provider provider = info.provider; 7577 if (mSafeMode && (provider.info.applicationInfo.flags 7578 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7579 return null; 7580 } 7581 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7582 if (ps == null) { 7583 return null; 7584 } 7585 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7586 ps.readUserState(userId), userId); 7587 if (pi == null) { 7588 return null; 7589 } 7590 final ResolveInfo res = new ResolveInfo(); 7591 res.providerInfo = pi; 7592 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7593 res.filter = filter; 7594 } 7595 res.priority = info.getPriority(); 7596 res.preferredOrder = provider.owner.mPreferredOrder; 7597 res.match = match; 7598 res.isDefault = info.hasDefault; 7599 res.labelRes = info.labelRes; 7600 res.nonLocalizedLabel = info.nonLocalizedLabel; 7601 res.icon = info.icon; 7602 res.system = isSystemApp(res.providerInfo.applicationInfo); 7603 return res; 7604 } 7605 7606 @Override 7607 protected void sortResults(List<ResolveInfo> results) { 7608 Collections.sort(results, mResolvePrioritySorter); 7609 } 7610 7611 @Override 7612 protected void dumpFilter(PrintWriter out, String prefix, 7613 PackageParser.ProviderIntentInfo filter) { 7614 out.print(prefix); 7615 out.print( 7616 Integer.toHexString(System.identityHashCode(filter.provider))); 7617 out.print(' '); 7618 filter.provider.printComponentShortName(out); 7619 out.print(" filter "); 7620 out.println(Integer.toHexString(System.identityHashCode(filter))); 7621 } 7622 7623 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7624 = new HashMap<ComponentName, PackageParser.Provider>(); 7625 private int mFlags; 7626 }; 7627 7628 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7629 new Comparator<ResolveInfo>() { 7630 public int compare(ResolveInfo r1, ResolveInfo r2) { 7631 int v1 = r1.priority; 7632 int v2 = r2.priority; 7633 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7634 if (v1 != v2) { 7635 return (v1 > v2) ? -1 : 1; 7636 } 7637 v1 = r1.preferredOrder; 7638 v2 = r2.preferredOrder; 7639 if (v1 != v2) { 7640 return (v1 > v2) ? -1 : 1; 7641 } 7642 if (r1.isDefault != r2.isDefault) { 7643 return r1.isDefault ? -1 : 1; 7644 } 7645 v1 = r1.match; 7646 v2 = r2.match; 7647 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7648 if (v1 != v2) { 7649 return (v1 > v2) ? -1 : 1; 7650 } 7651 if (r1.system != r2.system) { 7652 return r1.system ? -1 : 1; 7653 } 7654 return 0; 7655 } 7656 }; 7657 7658 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7659 new Comparator<ProviderInfo>() { 7660 public int compare(ProviderInfo p1, ProviderInfo p2) { 7661 final int v1 = p1.initOrder; 7662 final int v2 = p2.initOrder; 7663 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7664 } 7665 }; 7666 7667 static final void sendPackageBroadcast(String action, String pkg, 7668 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7669 int[] userIds) { 7670 IActivityManager am = ActivityManagerNative.getDefault(); 7671 if (am != null) { 7672 try { 7673 if (userIds == null) { 7674 userIds = am.getRunningUserIds(); 7675 } 7676 for (int id : userIds) { 7677 final Intent intent = new Intent(action, 7678 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7679 if (extras != null) { 7680 intent.putExtras(extras); 7681 } 7682 if (targetPkg != null) { 7683 intent.setPackage(targetPkg); 7684 } 7685 // Modify the UID when posting to other users 7686 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7687 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7688 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7689 intent.putExtra(Intent.EXTRA_UID, uid); 7690 } 7691 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7692 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7693 if (DEBUG_BROADCASTS) { 7694 RuntimeException here = new RuntimeException("here"); 7695 here.fillInStackTrace(); 7696 Slog.d(TAG, "Sending to user " + id + ": " 7697 + intent.toShortString(false, true, false, false) 7698 + " " + intent.getExtras(), here); 7699 } 7700 am.broadcastIntent(null, intent, null, finishedReceiver, 7701 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7702 finishedReceiver != null, false, id); 7703 } 7704 } catch (RemoteException ex) { 7705 } 7706 } 7707 } 7708 7709 /** 7710 * Check if the external storage media is available. This is true if there 7711 * is a mounted external storage medium or if the external storage is 7712 * emulated. 7713 */ 7714 private boolean isExternalMediaAvailable() { 7715 return mMediaMounted || Environment.isExternalStorageEmulated(); 7716 } 7717 7718 @Override 7719 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7720 // writer 7721 synchronized (mPackages) { 7722 if (!isExternalMediaAvailable()) { 7723 // If the external storage is no longer mounted at this point, 7724 // the caller may not have been able to delete all of this 7725 // packages files and can not delete any more. Bail. 7726 return null; 7727 } 7728 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7729 if (lastPackage != null) { 7730 pkgs.remove(lastPackage); 7731 } 7732 if (pkgs.size() > 0) { 7733 return pkgs.get(0); 7734 } 7735 } 7736 return null; 7737 } 7738 7739 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7740 if (false) { 7741 RuntimeException here = new RuntimeException("here"); 7742 here.fillInStackTrace(); 7743 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7744 + " andCode=" + andCode, here); 7745 } 7746 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7747 userId, andCode ? 1 : 0, packageName)); 7748 } 7749 7750 void startCleaningPackages() { 7751 // reader 7752 synchronized (mPackages) { 7753 if (!isExternalMediaAvailable()) { 7754 return; 7755 } 7756 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7757 return; 7758 } 7759 } 7760 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7761 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7762 IActivityManager am = ActivityManagerNative.getDefault(); 7763 if (am != null) { 7764 try { 7765 am.startService(null, intent, null, UserHandle.USER_OWNER); 7766 } catch (RemoteException e) { 7767 } 7768 } 7769 } 7770 7771 @Override 7772 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7773 String installerPackageName, VerificationParams verificationParams, 7774 String packageAbiOverride) { 7775 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7776 null); 7777 7778 final File originFile = new File(originPath); 7779 final int uid = Binder.getCallingUid(); 7780 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7781 try { 7782 if (observer != null) { 7783 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7784 } 7785 } catch (RemoteException re) { 7786 } 7787 return; 7788 } 7789 7790 UserHandle user; 7791 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7792 user = UserHandle.ALL; 7793 } else { 7794 user = new UserHandle(UserHandle.getUserId(uid)); 7795 } 7796 7797 final int filteredFlags; 7798 if (uid == Process.SHELL_UID || uid == 0) { 7799 if (DEBUG_INSTALL) { 7800 Slog.v(TAG, "Install from ADB"); 7801 } 7802 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7803 } else { 7804 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7805 } 7806 7807 verificationParams.setInstallerUid(uid); 7808 7809 final Message msg = mHandler.obtainMessage(INIT_COPY); 7810 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7811 installerPackageName, verificationParams, user, packageAbiOverride); 7812 mHandler.sendMessage(msg); 7813 } 7814 7815 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7816 InstallSessionParams params, String installerPackageName, int installerUid, 7817 UserHandle user) { 7818 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7819 params.referrerUri, installerUid, null); 7820 7821 final Message msg = mHandler.obtainMessage(INIT_COPY); 7822 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7823 installerPackageName, verifParams, user, params.abiOverride); 7824 mHandler.sendMessage(msg); 7825 } 7826 7827 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7828 Bundle extras = new Bundle(1); 7829 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7830 7831 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7832 packageName, extras, null, null, new int[] {userId}); 7833 try { 7834 IActivityManager am = ActivityManagerNative.getDefault(); 7835 final boolean isSystem = 7836 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7837 if (isSystem && am.isUserRunning(userId, false)) { 7838 // The just-installed/enabled app is bundled on the system, so presumed 7839 // to be able to run automatically without needing an explicit launch. 7840 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7841 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7842 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7843 .setPackage(packageName); 7844 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7845 android.app.AppOpsManager.OP_NONE, false, false, userId); 7846 } 7847 } catch (RemoteException e) { 7848 // shouldn't happen 7849 Slog.w(TAG, "Unable to bootstrap installed package", e); 7850 } 7851 } 7852 7853 @Override 7854 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7855 int userId) { 7856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7857 PackageSetting pkgSetting; 7858 final int uid = Binder.getCallingUid(); 7859 if (UserHandle.getUserId(uid) != userId) { 7860 mContext.enforceCallingOrSelfPermission( 7861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7862 "setApplicationHiddenSetting for user " + userId); 7863 } 7864 7865 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7866 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7867 return false; 7868 } 7869 7870 long callingId = Binder.clearCallingIdentity(); 7871 try { 7872 boolean sendAdded = false; 7873 boolean sendRemoved = false; 7874 // writer 7875 synchronized (mPackages) { 7876 pkgSetting = mSettings.mPackages.get(packageName); 7877 if (pkgSetting == null) { 7878 return false; 7879 } 7880 if (pkgSetting.getHidden(userId) != hidden) { 7881 pkgSetting.setHidden(hidden, userId); 7882 mSettings.writePackageRestrictionsLPr(userId); 7883 if (hidden) { 7884 sendRemoved = true; 7885 } else { 7886 sendAdded = true; 7887 } 7888 } 7889 } 7890 if (sendAdded) { 7891 sendPackageAddedForUser(packageName, pkgSetting, userId); 7892 return true; 7893 } 7894 if (sendRemoved) { 7895 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7896 "hiding pkg"); 7897 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7898 } 7899 } finally { 7900 Binder.restoreCallingIdentity(callingId); 7901 } 7902 return false; 7903 } 7904 7905 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7906 int userId) { 7907 final PackageRemovedInfo info = new PackageRemovedInfo(); 7908 info.removedPackage = packageName; 7909 info.removedUsers = new int[] {userId}; 7910 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7911 info.sendBroadcast(false, false, false); 7912 } 7913 7914 /** 7915 * Returns true if application is not found or there was an error. Otherwise it returns 7916 * the hidden state of the package for the given user. 7917 */ 7918 @Override 7919 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7921 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7922 "getApplicationHidden for user " + userId); 7923 PackageSetting pkgSetting; 7924 long callingId = Binder.clearCallingIdentity(); 7925 try { 7926 // writer 7927 synchronized (mPackages) { 7928 pkgSetting = mSettings.mPackages.get(packageName); 7929 if (pkgSetting == null) { 7930 return true; 7931 } 7932 return pkgSetting.getHidden(userId); 7933 } 7934 } finally { 7935 Binder.restoreCallingIdentity(callingId); 7936 } 7937 } 7938 7939 /** 7940 * @hide 7941 */ 7942 @Override 7943 public int installExistingPackageAsUser(String packageName, int userId) { 7944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7945 null); 7946 PackageSetting pkgSetting; 7947 final int uid = Binder.getCallingUid(); 7948 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7949 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7950 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7951 } 7952 7953 long callingId = Binder.clearCallingIdentity(); 7954 try { 7955 boolean sendAdded = false; 7956 Bundle extras = new Bundle(1); 7957 7958 // writer 7959 synchronized (mPackages) { 7960 pkgSetting = mSettings.mPackages.get(packageName); 7961 if (pkgSetting == null) { 7962 return PackageManager.INSTALL_FAILED_INVALID_URI; 7963 } 7964 if (!pkgSetting.getInstalled(userId)) { 7965 pkgSetting.setInstalled(true, userId); 7966 pkgSetting.setHidden(false, userId); 7967 mSettings.writePackageRestrictionsLPr(userId); 7968 sendAdded = true; 7969 } 7970 } 7971 7972 if (sendAdded) { 7973 sendPackageAddedForUser(packageName, pkgSetting, userId); 7974 } 7975 } finally { 7976 Binder.restoreCallingIdentity(callingId); 7977 } 7978 7979 return PackageManager.INSTALL_SUCCEEDED; 7980 } 7981 7982 boolean isUserRestricted(int userId, String restrictionKey) { 7983 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7984 if (restrictions.getBoolean(restrictionKey, false)) { 7985 Log.w(TAG, "User is restricted: " + restrictionKey); 7986 return true; 7987 } 7988 return false; 7989 } 7990 7991 @Override 7992 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7993 mContext.enforceCallingOrSelfPermission( 7994 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7995 "Only package verification agents can verify applications"); 7996 7997 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7998 final PackageVerificationResponse response = new PackageVerificationResponse( 7999 verificationCode, Binder.getCallingUid()); 8000 msg.arg1 = id; 8001 msg.obj = response; 8002 mHandler.sendMessage(msg); 8003 } 8004 8005 @Override 8006 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8007 long millisecondsToDelay) { 8008 mContext.enforceCallingOrSelfPermission( 8009 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8010 "Only package verification agents can extend verification timeouts"); 8011 8012 final PackageVerificationState state = mPendingVerification.get(id); 8013 final PackageVerificationResponse response = new PackageVerificationResponse( 8014 verificationCodeAtTimeout, Binder.getCallingUid()); 8015 8016 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8017 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8018 } 8019 if (millisecondsToDelay < 0) { 8020 millisecondsToDelay = 0; 8021 } 8022 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8023 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8024 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8025 } 8026 8027 if ((state != null) && !state.timeoutExtended()) { 8028 state.extendTimeout(); 8029 8030 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8031 msg.arg1 = id; 8032 msg.obj = response; 8033 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8034 } 8035 } 8036 8037 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8038 int verificationCode, UserHandle user) { 8039 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8040 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8041 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8042 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8043 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8044 8045 mContext.sendBroadcastAsUser(intent, user, 8046 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8047 } 8048 8049 private ComponentName matchComponentForVerifier(String packageName, 8050 List<ResolveInfo> receivers) { 8051 ActivityInfo targetReceiver = null; 8052 8053 final int NR = receivers.size(); 8054 for (int i = 0; i < NR; i++) { 8055 final ResolveInfo info = receivers.get(i); 8056 if (info.activityInfo == null) { 8057 continue; 8058 } 8059 8060 if (packageName.equals(info.activityInfo.packageName)) { 8061 targetReceiver = info.activityInfo; 8062 break; 8063 } 8064 } 8065 8066 if (targetReceiver == null) { 8067 return null; 8068 } 8069 8070 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8071 } 8072 8073 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8074 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8075 if (pkgInfo.verifiers.length == 0) { 8076 return null; 8077 } 8078 8079 final int N = pkgInfo.verifiers.length; 8080 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8081 for (int i = 0; i < N; i++) { 8082 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8083 8084 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8085 receivers); 8086 if (comp == null) { 8087 continue; 8088 } 8089 8090 final int verifierUid = getUidForVerifier(verifierInfo); 8091 if (verifierUid == -1) { 8092 continue; 8093 } 8094 8095 if (DEBUG_VERIFY) { 8096 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8097 + " with the correct signature"); 8098 } 8099 sufficientVerifiers.add(comp); 8100 verificationState.addSufficientVerifier(verifierUid); 8101 } 8102 8103 return sufficientVerifiers; 8104 } 8105 8106 private int getUidForVerifier(VerifierInfo verifierInfo) { 8107 synchronized (mPackages) { 8108 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8109 if (pkg == null) { 8110 return -1; 8111 } else if (pkg.mSignatures.length != 1) { 8112 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8113 + " has more than one signature; ignoring"); 8114 return -1; 8115 } 8116 8117 /* 8118 * If the public key of the package's signature does not match 8119 * our expected public key, then this is a different package and 8120 * we should skip. 8121 */ 8122 8123 final byte[] expectedPublicKey; 8124 try { 8125 final Signature verifierSig = pkg.mSignatures[0]; 8126 final PublicKey publicKey = verifierSig.getPublicKey(); 8127 expectedPublicKey = publicKey.getEncoded(); 8128 } catch (CertificateException e) { 8129 return -1; 8130 } 8131 8132 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8133 8134 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8135 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8136 + " does not have the expected public key; ignoring"); 8137 return -1; 8138 } 8139 8140 return pkg.applicationInfo.uid; 8141 } 8142 } 8143 8144 @Override 8145 public void finishPackageInstall(int token) { 8146 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8147 8148 if (DEBUG_INSTALL) { 8149 Slog.v(TAG, "BM finishing package install for " + token); 8150 } 8151 8152 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8153 mHandler.sendMessage(msg); 8154 } 8155 8156 /** 8157 * Get the verification agent timeout. 8158 * 8159 * @return verification timeout in milliseconds 8160 */ 8161 private long getVerificationTimeout() { 8162 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8163 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8164 DEFAULT_VERIFICATION_TIMEOUT); 8165 } 8166 8167 /** 8168 * Get the default verification agent response code. 8169 * 8170 * @return default verification response code 8171 */ 8172 private int getDefaultVerificationResponse() { 8173 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8174 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8175 DEFAULT_VERIFICATION_RESPONSE); 8176 } 8177 8178 /** 8179 * Check whether or not package verification has been enabled. 8180 * 8181 * @return true if verification should be performed 8182 */ 8183 private boolean isVerificationEnabled(int userId, int flags) { 8184 if (!DEFAULT_VERIFY_ENABLE) { 8185 return false; 8186 } 8187 8188 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8189 8190 // Check if installing from ADB 8191 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8192 // Do not run verification in a test harness environment 8193 if (ActivityManager.isRunningInTestHarness()) { 8194 return false; 8195 } 8196 if (ensureVerifyAppsEnabled) { 8197 return true; 8198 } 8199 // Check if the developer does not want package verification for ADB installs 8200 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8201 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8202 return false; 8203 } 8204 } 8205 8206 if (ensureVerifyAppsEnabled) { 8207 return true; 8208 } 8209 8210 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8211 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8212 } 8213 8214 /** 8215 * Get the "allow unknown sources" setting. 8216 * 8217 * @return the current "allow unknown sources" setting 8218 */ 8219 private int getUnknownSourcesSettings() { 8220 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8221 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8222 -1); 8223 } 8224 8225 @Override 8226 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8227 final int uid = Binder.getCallingUid(); 8228 // writer 8229 synchronized (mPackages) { 8230 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8231 if (targetPackageSetting == null) { 8232 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8233 } 8234 8235 PackageSetting installerPackageSetting; 8236 if (installerPackageName != null) { 8237 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8238 if (installerPackageSetting == null) { 8239 throw new IllegalArgumentException("Unknown installer package: " 8240 + installerPackageName); 8241 } 8242 } else { 8243 installerPackageSetting = null; 8244 } 8245 8246 Signature[] callerSignature; 8247 Object obj = mSettings.getUserIdLPr(uid); 8248 if (obj != null) { 8249 if (obj instanceof SharedUserSetting) { 8250 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8251 } else if (obj instanceof PackageSetting) { 8252 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8253 } else { 8254 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8255 } 8256 } else { 8257 throw new SecurityException("Unknown calling uid " + uid); 8258 } 8259 8260 // Verify: can't set installerPackageName to a package that is 8261 // not signed with the same cert as the caller. 8262 if (installerPackageSetting != null) { 8263 if (compareSignatures(callerSignature, 8264 installerPackageSetting.signatures.mSignatures) 8265 != PackageManager.SIGNATURE_MATCH) { 8266 throw new SecurityException( 8267 "Caller does not have same cert as new installer package " 8268 + installerPackageName); 8269 } 8270 } 8271 8272 // Verify: if target already has an installer package, it must 8273 // be signed with the same cert as the caller. 8274 if (targetPackageSetting.installerPackageName != null) { 8275 PackageSetting setting = mSettings.mPackages.get( 8276 targetPackageSetting.installerPackageName); 8277 // If the currently set package isn't valid, then it's always 8278 // okay to change it. 8279 if (setting != null) { 8280 if (compareSignatures(callerSignature, 8281 setting.signatures.mSignatures) 8282 != PackageManager.SIGNATURE_MATCH) { 8283 throw new SecurityException( 8284 "Caller does not have same cert as old installer package " 8285 + targetPackageSetting.installerPackageName); 8286 } 8287 } 8288 } 8289 8290 // Okay! 8291 targetPackageSetting.installerPackageName = installerPackageName; 8292 scheduleWriteSettingsLocked(); 8293 } 8294 } 8295 8296 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8297 // Queue up an async operation since the package installation may take a little while. 8298 mHandler.post(new Runnable() { 8299 public void run() { 8300 mHandler.removeCallbacks(this); 8301 // Result object to be returned 8302 PackageInstalledInfo res = new PackageInstalledInfo(); 8303 res.returnCode = currentStatus; 8304 res.uid = -1; 8305 res.pkg = null; 8306 res.removedInfo = new PackageRemovedInfo(); 8307 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8308 args.doPreInstall(res.returnCode); 8309 synchronized (mInstallLock) { 8310 installPackageLI(args, true, res); 8311 } 8312 args.doPostInstall(res.returnCode, res.uid); 8313 } 8314 8315 // A restore should be performed at this point if (a) the install 8316 // succeeded, (b) the operation is not an update, and (c) the new 8317 // package has not opted out of backup participation. 8318 final boolean update = res.removedInfo.removedPackage != null; 8319 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8320 boolean doRestore = !update 8321 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8322 8323 // Set up the post-install work request bookkeeping. This will be used 8324 // and cleaned up by the post-install event handling regardless of whether 8325 // there's a restore pass performed. Token values are >= 1. 8326 int token; 8327 if (mNextInstallToken < 0) mNextInstallToken = 1; 8328 token = mNextInstallToken++; 8329 8330 PostInstallData data = new PostInstallData(args, res); 8331 mRunningInstalls.put(token, data); 8332 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8333 8334 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8335 // Pass responsibility to the Backup Manager. It will perform a 8336 // restore if appropriate, then pass responsibility back to the 8337 // Package Manager to run the post-install observer callbacks 8338 // and broadcasts. 8339 IBackupManager bm = IBackupManager.Stub.asInterface( 8340 ServiceManager.getService(Context.BACKUP_SERVICE)); 8341 if (bm != null) { 8342 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8343 + " to BM for possible restore"); 8344 try { 8345 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8346 } catch (RemoteException e) { 8347 // can't happen; the backup manager is local 8348 } catch (Exception e) { 8349 Slog.e(TAG, "Exception trying to enqueue restore", e); 8350 doRestore = false; 8351 } 8352 } else { 8353 Slog.e(TAG, "Backup Manager not found!"); 8354 doRestore = false; 8355 } 8356 } 8357 8358 if (!doRestore) { 8359 // No restore possible, or the Backup Manager was mysteriously not 8360 // available -- just fire the post-install work request directly. 8361 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8362 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8363 mHandler.sendMessage(msg); 8364 } 8365 } 8366 }); 8367 } 8368 8369 private abstract class HandlerParams { 8370 private static final int MAX_RETRIES = 4; 8371 8372 /** 8373 * Number of times startCopy() has been attempted and had a non-fatal 8374 * error. 8375 */ 8376 private int mRetries = 0; 8377 8378 /** User handle for the user requesting the information or installation. */ 8379 private final UserHandle mUser; 8380 8381 HandlerParams(UserHandle user) { 8382 mUser = user; 8383 } 8384 8385 UserHandle getUser() { 8386 return mUser; 8387 } 8388 8389 final boolean startCopy() { 8390 boolean res; 8391 try { 8392 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8393 8394 if (++mRetries > MAX_RETRIES) { 8395 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8396 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8397 handleServiceError(); 8398 return false; 8399 } else { 8400 handleStartCopy(); 8401 res = true; 8402 } 8403 } catch (RemoteException e) { 8404 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8405 mHandler.sendEmptyMessage(MCS_RECONNECT); 8406 res = false; 8407 } 8408 handleReturnCode(); 8409 return res; 8410 } 8411 8412 final void serviceError() { 8413 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8414 handleServiceError(); 8415 handleReturnCode(); 8416 } 8417 8418 abstract void handleStartCopy() throws RemoteException; 8419 abstract void handleServiceError(); 8420 abstract void handleReturnCode(); 8421 } 8422 8423 class MeasureParams extends HandlerParams { 8424 private final PackageStats mStats; 8425 private boolean mSuccess; 8426 8427 private final IPackageStatsObserver mObserver; 8428 8429 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8430 super(new UserHandle(stats.userHandle)); 8431 mObserver = observer; 8432 mStats = stats; 8433 } 8434 8435 @Override 8436 public String toString() { 8437 return "MeasureParams{" 8438 + Integer.toHexString(System.identityHashCode(this)) 8439 + " " + mStats.packageName + "}"; 8440 } 8441 8442 @Override 8443 void handleStartCopy() throws RemoteException { 8444 synchronized (mInstallLock) { 8445 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8446 } 8447 8448 if (mSuccess) { 8449 final boolean mounted; 8450 if (Environment.isExternalStorageEmulated()) { 8451 mounted = true; 8452 } else { 8453 final String status = Environment.getExternalStorageState(); 8454 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8455 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8456 } 8457 8458 if (mounted) { 8459 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8460 8461 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8462 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8463 8464 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8465 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8466 8467 // Always subtract cache size, since it's a subdirectory 8468 mStats.externalDataSize -= mStats.externalCacheSize; 8469 8470 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8471 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8472 8473 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8474 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8475 } 8476 } 8477 } 8478 8479 @Override 8480 void handleReturnCode() { 8481 if (mObserver != null) { 8482 try { 8483 mObserver.onGetStatsCompleted(mStats, mSuccess); 8484 } catch (RemoteException e) { 8485 Slog.i(TAG, "Observer no longer exists."); 8486 } 8487 } 8488 } 8489 8490 @Override 8491 void handleServiceError() { 8492 Slog.e(TAG, "Could not measure application " + mStats.packageName 8493 + " external storage"); 8494 } 8495 } 8496 8497 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8498 throws RemoteException { 8499 long result = 0; 8500 for (File path : paths) { 8501 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8502 } 8503 return result; 8504 } 8505 8506 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8507 for (File path : paths) { 8508 try { 8509 mcs.clearDirectory(path.getAbsolutePath()); 8510 } catch (RemoteException e) { 8511 } 8512 } 8513 } 8514 8515 class InstallParams extends HandlerParams { 8516 /** 8517 * Location where install is coming from, before it has been 8518 * copied/renamed into place. This could be a single monolithic APK 8519 * file, or a cluster directory. This location may be untrusted. 8520 */ 8521 final File originFile; 8522 8523 /** 8524 * Flag indicating that {@link #originFile} has already been staged, 8525 * meaning downstream users don't need to defensively copy the contents. 8526 */ 8527 boolean originStaged; 8528 8529 final IPackageInstallObserver2 observer; 8530 int flags; 8531 final String installerPackageName; 8532 final VerificationParams verificationParams; 8533 private InstallArgs mArgs; 8534 private int mRet; 8535 final String packageAbiOverride; 8536 boolean multiArch; 8537 8538 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8539 int flags, String installerPackageName, VerificationParams verificationParams, 8540 UserHandle user, String packageAbiOverride) { 8541 super(user); 8542 this.originFile = Preconditions.checkNotNull(originFile); 8543 this.originStaged = originStaged; 8544 this.observer = observer; 8545 this.flags = flags; 8546 this.installerPackageName = installerPackageName; 8547 this.verificationParams = verificationParams; 8548 this.packageAbiOverride = packageAbiOverride; 8549 } 8550 8551 @Override 8552 public String toString() { 8553 return "InstallParams{" 8554 + Integer.toHexString(System.identityHashCode(this)) 8555 + " " + originFile + "}"; 8556 } 8557 8558 public ManifestDigest getManifestDigest() { 8559 if (verificationParams == null) { 8560 return null; 8561 } 8562 return verificationParams.getManifestDigest(); 8563 } 8564 8565 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8566 String packageName = pkgLite.packageName; 8567 int installLocation = pkgLite.installLocation; 8568 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8569 // reader 8570 synchronized (mPackages) { 8571 PackageParser.Package pkg = mPackages.get(packageName); 8572 if (pkg != null) { 8573 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8574 // Check for downgrading. 8575 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8576 if (pkgLite.versionCode < pkg.mVersionCode) { 8577 Slog.w(TAG, "Can't install update of " + packageName 8578 + " update version " + pkgLite.versionCode 8579 + " is older than installed version " 8580 + pkg.mVersionCode); 8581 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8582 } 8583 } 8584 // Check for updated system application. 8585 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8586 if (onSd) { 8587 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8588 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8589 } 8590 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8591 } else { 8592 if (onSd) { 8593 // Install flag overrides everything. 8594 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8595 } 8596 // If current upgrade specifies particular preference 8597 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8598 // Application explicitly specified internal. 8599 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8600 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8601 // App explictly prefers external. Let policy decide 8602 } else { 8603 // Prefer previous location 8604 if (isExternal(pkg)) { 8605 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8606 } 8607 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8608 } 8609 } 8610 } else { 8611 // Invalid install. Return error code 8612 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8613 } 8614 } 8615 } 8616 // All the special cases have been taken care of. 8617 // Return result based on recommended install location. 8618 if (onSd) { 8619 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8620 } 8621 return pkgLite.recommendedInstallLocation; 8622 } 8623 8624 private long getMemoryLowThreshold() { 8625 final DeviceStorageMonitorInternal 8626 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8627 if (dsm == null) { 8628 return 0L; 8629 } 8630 return dsm.getMemoryLowThreshold(); 8631 } 8632 8633 /* 8634 * Invoke remote method to get package information and install 8635 * location values. Override install location based on default 8636 * policy if needed and then create install arguments based 8637 * on the install location. 8638 */ 8639 public void handleStartCopy() throws RemoteException { 8640 int ret = PackageManager.INSTALL_SUCCEEDED; 8641 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8642 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8643 PackageInfoLite pkgLite = null; 8644 8645 if (onInt && onSd) { 8646 // Check if both bits are set. 8647 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8648 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8649 } else { 8650 final long lowThreshold = getMemoryLowThreshold(); 8651 if (lowThreshold == 0L) { 8652 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8653 } 8654 8655 // Remote call to find out default install location 8656 final String originPath = originFile.getAbsolutePath(); 8657 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8658 packageAbiOverride); 8659 // Keep track of whether this package is a multiArch package until 8660 // we perform a full scan of it. We need to do this because we might 8661 // end up extracting the package shared libraries before we perform 8662 // a full scan. 8663 multiArch = pkgLite.multiArch; 8664 8665 /* 8666 * If we have too little free space, try to free cache 8667 * before giving up. 8668 */ 8669 if (pkgLite.recommendedInstallLocation 8670 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8671 final long size = mContainerService.calculateInstalledSize( 8672 originPath, isForwardLocked(), packageAbiOverride); 8673 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8674 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8675 lowThreshold, packageAbiOverride); 8676 } 8677 /* 8678 * The cache free must have deleted the file we 8679 * downloaded to install. 8680 * 8681 * TODO: fix the "freeCache" call to not delete 8682 * the file we care about. 8683 */ 8684 if (pkgLite.recommendedInstallLocation 8685 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8686 pkgLite.recommendedInstallLocation 8687 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8688 } 8689 } 8690 } 8691 8692 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8693 int loc = pkgLite.recommendedInstallLocation; 8694 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8695 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8696 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8697 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8698 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8699 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8700 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8701 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8702 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8703 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8704 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8705 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8706 } else { 8707 // Override with defaults if needed. 8708 loc = installLocationPolicy(pkgLite, flags); 8709 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8710 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8711 } else if (!onSd && !onInt) { 8712 // Override install location with flags 8713 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8714 // Set the flag to install on external media. 8715 flags |= PackageManager.INSTALL_EXTERNAL; 8716 flags &= ~PackageManager.INSTALL_INTERNAL; 8717 } else { 8718 // Make sure the flag for installing on external 8719 // media is unset 8720 flags |= PackageManager.INSTALL_INTERNAL; 8721 flags &= ~PackageManager.INSTALL_EXTERNAL; 8722 } 8723 } 8724 } 8725 } 8726 8727 final InstallArgs args = createInstallArgs(this); 8728 mArgs = args; 8729 8730 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8731 /* 8732 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8733 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8734 */ 8735 int userIdentifier = getUser().getIdentifier(); 8736 if (userIdentifier == UserHandle.USER_ALL 8737 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8738 userIdentifier = UserHandle.USER_OWNER; 8739 } 8740 8741 /* 8742 * Determine if we have any installed package verifiers. If we 8743 * do, then we'll defer to them to verify the packages. 8744 */ 8745 final int requiredUid = mRequiredVerifierPackage == null ? -1 8746 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8747 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8748 // TODO: send verifier the install session instead of uri 8749 final Intent verification = new Intent( 8750 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8751 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8752 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8753 8754 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8755 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8756 0 /* TODO: Which userId? */); 8757 8758 if (DEBUG_VERIFY) { 8759 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8760 + verification.toString() + " with " + pkgLite.verifiers.length 8761 + " optional verifiers"); 8762 } 8763 8764 final int verificationId = mPendingVerificationToken++; 8765 8766 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8767 8768 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8769 installerPackageName); 8770 8771 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8772 8773 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8774 pkgLite.packageName); 8775 8776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8777 pkgLite.versionCode); 8778 8779 if (verificationParams != null) { 8780 if (verificationParams.getVerificationURI() != null) { 8781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8782 verificationParams.getVerificationURI()); 8783 } 8784 if (verificationParams.getOriginatingURI() != null) { 8785 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8786 verificationParams.getOriginatingURI()); 8787 } 8788 if (verificationParams.getReferrer() != null) { 8789 verification.putExtra(Intent.EXTRA_REFERRER, 8790 verificationParams.getReferrer()); 8791 } 8792 if (verificationParams.getOriginatingUid() >= 0) { 8793 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8794 verificationParams.getOriginatingUid()); 8795 } 8796 if (verificationParams.getInstallerUid() >= 0) { 8797 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8798 verificationParams.getInstallerUid()); 8799 } 8800 } 8801 8802 final PackageVerificationState verificationState = new PackageVerificationState( 8803 requiredUid, args); 8804 8805 mPendingVerification.append(verificationId, verificationState); 8806 8807 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8808 receivers, verificationState); 8809 8810 /* 8811 * If any sufficient verifiers were listed in the package 8812 * manifest, attempt to ask them. 8813 */ 8814 if (sufficientVerifiers != null) { 8815 final int N = sufficientVerifiers.size(); 8816 if (N == 0) { 8817 Slog.i(TAG, "Additional verifiers required, but none installed."); 8818 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8819 } else { 8820 for (int i = 0; i < N; i++) { 8821 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8822 8823 final Intent sufficientIntent = new Intent(verification); 8824 sufficientIntent.setComponent(verifierComponent); 8825 8826 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8827 } 8828 } 8829 } 8830 8831 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8832 mRequiredVerifierPackage, receivers); 8833 if (ret == PackageManager.INSTALL_SUCCEEDED 8834 && mRequiredVerifierPackage != null) { 8835 /* 8836 * Send the intent to the required verification agent, 8837 * but only start the verification timeout after the 8838 * target BroadcastReceivers have run. 8839 */ 8840 verification.setComponent(requiredVerifierComponent); 8841 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8842 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8843 new BroadcastReceiver() { 8844 @Override 8845 public void onReceive(Context context, Intent intent) { 8846 final Message msg = mHandler 8847 .obtainMessage(CHECK_PENDING_VERIFICATION); 8848 msg.arg1 = verificationId; 8849 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8850 } 8851 }, null, 0, null, null); 8852 8853 /* 8854 * We don't want the copy to proceed until verification 8855 * succeeds, so null out this field. 8856 */ 8857 mArgs = null; 8858 } 8859 } else { 8860 /* 8861 * No package verification is enabled, so immediately start 8862 * the remote call to initiate copy using temporary file. 8863 */ 8864 ret = args.copyApk(mContainerService, true); 8865 } 8866 } 8867 8868 mRet = ret; 8869 } 8870 8871 @Override 8872 void handleReturnCode() { 8873 // If mArgs is null, then MCS couldn't be reached. When it 8874 // reconnects, it will try again to install. At that point, this 8875 // will succeed. 8876 if (mArgs != null) { 8877 processPendingInstall(mArgs, mRet); 8878 } 8879 } 8880 8881 @Override 8882 void handleServiceError() { 8883 mArgs = createInstallArgs(this); 8884 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8885 } 8886 8887 public boolean isForwardLocked() { 8888 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8889 } 8890 } 8891 8892 /* 8893 * Utility class used in movePackage api. 8894 * srcArgs and targetArgs are not set for invalid flags and make 8895 * sure to do null checks when invoking methods on them. 8896 * We probably want to return ErrorPrams for both failed installs 8897 * and moves. 8898 */ 8899 class MoveParams extends HandlerParams { 8900 final IPackageMoveObserver observer; 8901 final int flags; 8902 final String packageName; 8903 final InstallArgs srcArgs; 8904 final InstallArgs targetArgs; 8905 int uid; 8906 int mRet; 8907 8908 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8909 String packageName, String[] instructionSets, int uid, UserHandle user, 8910 boolean isMultiArch) { 8911 super(user); 8912 this.srcArgs = srcArgs; 8913 this.observer = observer; 8914 this.flags = flags; 8915 this.packageName = packageName; 8916 this.uid = uid; 8917 if (srcArgs != null) { 8918 final String codePath = srcArgs.getCodePath(); 8919 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8920 instructionSets, isMultiArch); 8921 } else { 8922 targetArgs = null; 8923 } 8924 } 8925 8926 @Override 8927 public String toString() { 8928 return "MoveParams{" 8929 + Integer.toHexString(System.identityHashCode(this)) 8930 + " " + packageName + "}"; 8931 } 8932 8933 public void handleStartCopy() throws RemoteException { 8934 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8935 // Check for storage space on target medium 8936 if (!targetArgs.checkFreeStorage(mContainerService)) { 8937 Log.w(TAG, "Insufficient storage to install"); 8938 return; 8939 } 8940 8941 mRet = srcArgs.doPreCopy(); 8942 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8943 return; 8944 } 8945 8946 mRet = targetArgs.copyApk(mContainerService, false); 8947 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8948 srcArgs.doPostCopy(uid); 8949 return; 8950 } 8951 8952 mRet = srcArgs.doPostCopy(uid); 8953 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8954 return; 8955 } 8956 8957 mRet = targetArgs.doPreInstall(mRet); 8958 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8959 return; 8960 } 8961 8962 if (DEBUG_SD_INSTALL) { 8963 StringBuilder builder = new StringBuilder(); 8964 if (srcArgs != null) { 8965 builder.append("src: "); 8966 builder.append(srcArgs.getCodePath()); 8967 } 8968 if (targetArgs != null) { 8969 builder.append(" target : "); 8970 builder.append(targetArgs.getCodePath()); 8971 } 8972 Log.i(TAG, builder.toString()); 8973 } 8974 } 8975 8976 @Override 8977 void handleReturnCode() { 8978 targetArgs.doPostInstall(mRet, uid); 8979 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8980 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8981 currentStatus = PackageManager.MOVE_SUCCEEDED; 8982 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8983 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8984 } 8985 processPendingMove(this, currentStatus); 8986 } 8987 8988 @Override 8989 void handleServiceError() { 8990 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8991 } 8992 } 8993 8994 /** 8995 * Used during creation of InstallArgs 8996 * 8997 * @param flags package installation flags 8998 * @return true if should be installed on external storage 8999 */ 9000 private static boolean installOnSd(int flags) { 9001 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9002 return false; 9003 } 9004 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9005 return true; 9006 } 9007 return false; 9008 } 9009 9010 /** 9011 * Used during creation of InstallArgs 9012 * 9013 * @param flags package installation flags 9014 * @return true if should be installed as forward locked 9015 */ 9016 private static boolean installForwardLocked(int flags) { 9017 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9018 } 9019 9020 private InstallArgs createInstallArgs(InstallParams params) { 9021 // TODO: extend to support incoming zero-copy locations 9022 9023 if (installOnSd(params.flags) || params.isForwardLocked()) { 9024 return new AsecInstallArgs(params); 9025 } else { 9026 return new FileInstallArgs(params); 9027 } 9028 } 9029 9030 /** 9031 * Create args that describe an existing installed package. Typically used 9032 * when cleaning up old installs, or used as a move source. 9033 */ 9034 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9035 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9036 boolean isMultiArch) { 9037 final boolean isInAsec; 9038 if (installOnSd(flags)) { 9039 /* Apps on SD card are always in ASEC containers. */ 9040 isInAsec = true; 9041 } else if (installForwardLocked(flags) 9042 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9043 /* 9044 * Forward-locked apps are only in ASEC containers if they're the 9045 * new style 9046 */ 9047 isInAsec = true; 9048 } else { 9049 isInAsec = false; 9050 } 9051 9052 if (isInAsec) { 9053 return new AsecInstallArgs(codePath, instructionSets, 9054 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9055 } else { 9056 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9057 instructionSets, isMultiArch); 9058 } 9059 } 9060 9061 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9062 String[] instructionSets, boolean isMultiArch) { 9063 final File codeFile = new File(codePath); 9064 if (installOnSd(flags) || installForwardLocked(flags)) { 9065 String cid = getNextCodePath(codePath, pkgName, "/" 9066 + AsecInstallArgs.RES_FILE_NAME); 9067 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9068 installForwardLocked(flags), isMultiArch); 9069 } else { 9070 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9071 } 9072 } 9073 9074 static abstract class InstallArgs { 9075 /** @see InstallParams#originFile */ 9076 final File originFile; 9077 /** @see InstallParams#originStaged */ 9078 final boolean originStaged; 9079 9080 // TODO: define inherit location 9081 9082 final IPackageInstallObserver2 observer; 9083 // Always refers to PackageManager flags only 9084 final int flags; 9085 final String installerPackageName; 9086 final ManifestDigest manifestDigest; 9087 final UserHandle user; 9088 final String abiOverride; 9089 final boolean multiArch; 9090 9091 // The list of instruction sets supported by this app. This is currently 9092 // only used during the rmdex() phase to clean up resources. We can get rid of this 9093 // if we move dex files under the common app path. 9094 /* nullable */ String[] instructionSets; 9095 9096 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9097 int flags, String installerPackageName, ManifestDigest manifestDigest, 9098 UserHandle user, String[] instructionSets, 9099 String abiOverride, boolean multiArch) { 9100 this.originFile = originFile; 9101 this.originStaged = originStaged; 9102 this.flags = flags; 9103 this.observer = observer; 9104 this.installerPackageName = installerPackageName; 9105 this.manifestDigest = manifestDigest; 9106 this.user = user; 9107 this.instructionSets = instructionSets; 9108 this.abiOverride = abiOverride; 9109 this.multiArch = multiArch; 9110 } 9111 9112 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9113 abstract int doPreInstall(int status); 9114 9115 /** 9116 * Rename package into final resting place. All paths on the given 9117 * scanned package should be updated to reflect the rename. 9118 */ 9119 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9120 abstract int doPostInstall(int status, int uid); 9121 9122 /** @see PackageSettingBase#codePathString */ 9123 abstract String getCodePath(); 9124 /** @see PackageSettingBase#resourcePathString */ 9125 abstract String getResourcePath(); 9126 abstract String getLegacyNativeLibraryPath(); 9127 9128 // Need installer lock especially for dex file removal. 9129 abstract void cleanUpResourcesLI(); 9130 abstract boolean doPostDeleteLI(boolean delete); 9131 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9132 9133 /** 9134 * Called before the source arguments are copied. This is used mostly 9135 * for MoveParams when it needs to read the source file to put it in the 9136 * destination. 9137 */ 9138 int doPreCopy() { 9139 return PackageManager.INSTALL_SUCCEEDED; 9140 } 9141 9142 /** 9143 * Called after the source arguments are copied. This is used mostly for 9144 * MoveParams when it needs to read the source file to put it in the 9145 * destination. 9146 * 9147 * @return 9148 */ 9149 int doPostCopy(int uid) { 9150 return PackageManager.INSTALL_SUCCEEDED; 9151 } 9152 9153 protected boolean isFwdLocked() { 9154 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9155 } 9156 9157 UserHandle getUser() { 9158 return user; 9159 } 9160 } 9161 9162 /** 9163 * Logic to handle installation of non-ASEC applications, including copying 9164 * and renaming logic. 9165 */ 9166 class FileInstallArgs extends InstallArgs { 9167 private File codeFile; 9168 private File resourceFile; 9169 private File legacyNativeLibraryPath; 9170 9171 // Example topology: 9172 // /data/app/com.example/base.apk 9173 // /data/app/com.example/split_foo.apk 9174 // /data/app/com.example/lib/arm/libfoo.so 9175 // /data/app/com.example/lib/arm64/libfoo.so 9176 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9177 9178 /** New install */ 9179 FileInstallArgs(InstallParams params) { 9180 super(params.originFile, params.originStaged, params.observer, params.flags, 9181 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9182 null /* instruction sets */, params.packageAbiOverride, 9183 params.multiArch); 9184 if (isFwdLocked()) { 9185 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9186 } 9187 } 9188 9189 /** Existing install */ 9190 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9191 String[] instructionSets, boolean isMultiArch) { 9192 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9193 this.codeFile = (codePath != null) ? new File(codePath) : null; 9194 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9195 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9196 new File(legacyNativeLibraryPath) : null; 9197 } 9198 9199 /** New install from existing */ 9200 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9201 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9202 isMultiArch); 9203 } 9204 9205 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9206 final long lowThreshold; 9207 9208 final DeviceStorageMonitorInternal 9209 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9210 if (dsm == null) { 9211 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9212 lowThreshold = 0L; 9213 } else { 9214 if (dsm.isMemoryLow()) { 9215 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9216 return false; 9217 } 9218 9219 lowThreshold = dsm.getMemoryLowThreshold(); 9220 } 9221 9222 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9223 lowThreshold); 9224 } 9225 9226 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9227 int ret = PackageManager.INSTALL_SUCCEEDED; 9228 9229 if (originStaged) { 9230 Slog.d(TAG, originFile + " already staged; skipping copy"); 9231 codeFile = originFile; 9232 resourceFile = originFile; 9233 } else { 9234 try { 9235 final File tempDir = mInstallerService.allocateSessionDir(); 9236 codeFile = tempDir; 9237 resourceFile = tempDir; 9238 } catch (IOException e) { 9239 Slog.w(TAG, "Failed to create copy file: " + e); 9240 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9241 } 9242 9243 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9244 @Override 9245 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9246 if (!FileUtils.isValidExtFilename(name)) { 9247 throw new IllegalArgumentException("Invalid filename: " + name); 9248 } 9249 try { 9250 final File file = new File(codeFile, name); 9251 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9252 O_RDWR | O_CREAT, 0644); 9253 Os.chmod(file.getAbsolutePath(), 0644); 9254 return new ParcelFileDescriptor(fd); 9255 } catch (ErrnoException e) { 9256 throw new RemoteException("Failed to open: " + e.getMessage()); 9257 } 9258 } 9259 }; 9260 9261 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9262 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9263 Slog.e(TAG, "Failed to copy package"); 9264 return ret; 9265 } 9266 } 9267 9268 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9269 NativeLibraryHelper.Handle handle = null; 9270 try { 9271 handle = NativeLibraryHelper.Handle.create(codeFile); 9272 if (multiArch) { 9273 // Warn if we've set an abiOverride for multi-lib packages.. 9274 // By definition, we need to copy both 32 and 64 bit libraries for 9275 // such packages. 9276 if (abiOverride != null) { 9277 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9278 } 9279 9280 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9281 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9282 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9283 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9284 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9285 } 9286 9287 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9288 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9289 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9290 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9291 } 9292 } else { 9293 String[] abiList = (abiOverride != null) ? 9294 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9295 9296 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9297 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9298 abiList = Build.SUPPORTED_32_BIT_ABIS; 9299 } 9300 9301 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9302 true /* use isa specific subdirs */); 9303 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9304 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9305 return copyRet; 9306 } 9307 } 9308 } catch (IOException e) { 9309 Slog.e(TAG, "Copying native libraries failed", e); 9310 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9311 } catch (PackageManagerException pme) { 9312 Slog.e(TAG, "Copying native libraries failed", pme); 9313 ret = pme.error; 9314 } finally { 9315 IoUtils.closeQuietly(handle); 9316 } 9317 9318 return ret; 9319 } 9320 9321 int doPreInstall(int status) { 9322 if (status != PackageManager.INSTALL_SUCCEEDED) { 9323 cleanUp(); 9324 } 9325 return status; 9326 } 9327 9328 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9329 if (status != PackageManager.INSTALL_SUCCEEDED) { 9330 cleanUp(); 9331 return false; 9332 } else { 9333 final File beforeCodeFile = codeFile; 9334 final File afterCodeFile = getNextCodePath(pkg.packageName); 9335 9336 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9337 try { 9338 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9339 } catch (ErrnoException e) { 9340 Slog.d(TAG, "Failed to rename", e); 9341 return false; 9342 } 9343 9344 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9345 Slog.d(TAG, "Failed to restorecon"); 9346 return false; 9347 } 9348 9349 // Reflect the rename internally 9350 codeFile = afterCodeFile; 9351 resourceFile = afterCodeFile; 9352 9353 // Reflect the rename in scanned details 9354 pkg.codePath = afterCodeFile.getAbsolutePath(); 9355 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9356 pkg.baseCodePath); 9357 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9358 pkg.splitCodePaths); 9359 9360 // Reflect the rename in app info 9361 pkg.applicationInfo.setCodePath(pkg.codePath); 9362 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9363 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9364 pkg.applicationInfo.setResourcePath(pkg.codePath); 9365 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9366 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9367 9368 return true; 9369 } 9370 } 9371 9372 int doPostInstall(int status, int uid) { 9373 if (status != PackageManager.INSTALL_SUCCEEDED) { 9374 cleanUp(); 9375 } 9376 return status; 9377 } 9378 9379 @Override 9380 String getCodePath() { 9381 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9382 } 9383 9384 @Override 9385 String getResourcePath() { 9386 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9387 } 9388 9389 @Override 9390 String getLegacyNativeLibraryPath() { 9391 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9392 } 9393 9394 private boolean cleanUp() { 9395 if (codeFile == null || !codeFile.exists()) { 9396 return false; 9397 } 9398 9399 if (codeFile.isDirectory()) { 9400 FileUtils.deleteContents(codeFile); 9401 } 9402 codeFile.delete(); 9403 9404 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9405 resourceFile.delete(); 9406 } 9407 9408 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9409 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9410 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9411 } 9412 legacyNativeLibraryPath.delete(); 9413 } 9414 9415 return true; 9416 } 9417 9418 void cleanUpResourcesLI() { 9419 // Try enumerating all code paths before deleting 9420 List<String> allCodePaths = Collections.EMPTY_LIST; 9421 if (codeFile != null && codeFile.exists()) { 9422 try { 9423 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9424 allCodePaths = pkg.getAllCodePaths(); 9425 } catch (PackageParserException e) { 9426 // Ignored; we tried our best 9427 } 9428 } 9429 9430 cleanUp(); 9431 9432 if (!allCodePaths.isEmpty()) { 9433 if (instructionSets == null) { 9434 throw new IllegalStateException("instructionSet == null"); 9435 } 9436 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9437 for (String codePath : allCodePaths) { 9438 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9439 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9440 if (retCode < 0) { 9441 Slog.w(TAG, "Couldn't remove dex file for package: " 9442 + " at location " + codePath + ", retcode=" + retCode); 9443 // we don't consider this to be a failure of the core package deletion 9444 } 9445 } 9446 } 9447 } 9448 } 9449 9450 boolean doPostDeleteLI(boolean delete) { 9451 // XXX err, shouldn't we respect the delete flag? 9452 cleanUpResourcesLI(); 9453 return true; 9454 } 9455 } 9456 9457 private boolean isAsecExternal(String cid) { 9458 final String asecPath = PackageHelper.getSdFilesystem(cid); 9459 return !asecPath.startsWith(mAsecInternalPath); 9460 } 9461 9462 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9463 PackageManagerException { 9464 if (copyRet < 0) { 9465 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9466 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9467 throw new PackageManagerException(copyRet, message); 9468 } 9469 } 9470 } 9471 9472 /** 9473 * Extract the MountService "container ID" from the full code path of an 9474 * .apk. 9475 */ 9476 static String cidFromCodePath(String fullCodePath) { 9477 int eidx = fullCodePath.lastIndexOf("/"); 9478 String subStr1 = fullCodePath.substring(0, eidx); 9479 int sidx = subStr1.lastIndexOf("/"); 9480 return subStr1.substring(sidx+1, eidx); 9481 } 9482 9483 /** 9484 * Logic to handle installation of ASEC applications, including copying and 9485 * renaming logic. 9486 */ 9487 class AsecInstallArgs extends InstallArgs { 9488 // TODO: teach about handling cluster directories 9489 9490 static final String RES_FILE_NAME = "pkg.apk"; 9491 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9492 9493 String cid; 9494 String packagePath; 9495 String resourcePath; 9496 String legacyNativeLibraryDir; 9497 9498 /** New install */ 9499 AsecInstallArgs(InstallParams params) { 9500 super(params.originFile, params.originStaged, params.observer, params.flags, 9501 params.installerPackageName, params.getManifestDigest(), 9502 params.getUser(), null /* instruction sets */, 9503 params.packageAbiOverride, params.multiArch); 9504 } 9505 9506 /** Existing install */ 9507 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9508 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9509 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9510 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9511 instructionSets, null, isMultiArch); 9512 // Extract cid from fullCodePath 9513 int eidx = fullCodePath.lastIndexOf("/"); 9514 String subStr1 = fullCodePath.substring(0, eidx); 9515 int sidx = subStr1.lastIndexOf("/"); 9516 cid = subStr1.substring(sidx+1, eidx); 9517 setCachePath(subStr1); 9518 } 9519 9520 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9521 boolean isMultiArch) { 9522 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9523 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9524 instructionSets, null, isMultiArch); 9525 this.cid = cid; 9526 setCachePath(PackageHelper.getSdDir(cid)); 9527 } 9528 9529 /** New install from existing */ 9530 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9531 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9532 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9533 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9534 instructionSets, null, isMultiArch); 9535 this.cid = cid; 9536 } 9537 9538 void createCopyFile() { 9539 cid = getTempContainerId(); 9540 } 9541 9542 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9543 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9544 abiOverride); 9545 } 9546 9547 private final boolean isExternal() { 9548 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9549 } 9550 9551 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9552 if (temp) { 9553 createCopyFile(); 9554 } else { 9555 /* 9556 * Pre-emptively destroy the container since it's destroyed if 9557 * copying fails due to it existing anyway. 9558 */ 9559 PackageHelper.destroySdDir(cid); 9560 } 9561 9562 final String newCachePath = imcs.copyPackageToContainer( 9563 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9564 isFwdLocked(), abiOverride); 9565 9566 if (newCachePath != null) { 9567 setCachePath(newCachePath); 9568 return PackageManager.INSTALL_SUCCEEDED; 9569 } else { 9570 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9571 } 9572 } 9573 9574 @Override 9575 String getCodePath() { 9576 return packagePath; 9577 } 9578 9579 @Override 9580 String getResourcePath() { 9581 return resourcePath; 9582 } 9583 9584 @Override 9585 String getLegacyNativeLibraryPath() { 9586 return legacyNativeLibraryDir; 9587 } 9588 9589 int doPreInstall(int status) { 9590 if (status != PackageManager.INSTALL_SUCCEEDED) { 9591 // Destroy container 9592 PackageHelper.destroySdDir(cid); 9593 } else { 9594 boolean mounted = PackageHelper.isContainerMounted(cid); 9595 if (!mounted) { 9596 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9597 Process.SYSTEM_UID); 9598 if (newCachePath != null) { 9599 setCachePath(newCachePath); 9600 } else { 9601 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9602 } 9603 } 9604 } 9605 return status; 9606 } 9607 9608 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9609 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9610 String newCachePath = null; 9611 if (PackageHelper.isContainerMounted(cid)) { 9612 // Unmount the container 9613 if (!PackageHelper.unMountSdDir(cid)) { 9614 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9615 return false; 9616 } 9617 } 9618 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9619 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9620 " which might be stale. Will try to clean up."); 9621 // Clean up the stale container and proceed to recreate. 9622 if (!PackageHelper.destroySdDir(newCacheId)) { 9623 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9624 return false; 9625 } 9626 // Successfully cleaned up stale container. Try to rename again. 9627 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9628 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9629 + " inspite of cleaning it up."); 9630 return false; 9631 } 9632 } 9633 if (!PackageHelper.isContainerMounted(newCacheId)) { 9634 Slog.w(TAG, "Mounting container " + newCacheId); 9635 newCachePath = PackageHelper.mountSdDir(newCacheId, 9636 getEncryptKey(), Process.SYSTEM_UID); 9637 } else { 9638 newCachePath = PackageHelper.getSdDir(newCacheId); 9639 } 9640 if (newCachePath == null) { 9641 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9642 return false; 9643 } 9644 Log.i(TAG, "Succesfully renamed " + cid + 9645 " to " + newCacheId + 9646 " at new path: " + newCachePath); 9647 cid = newCacheId; 9648 setCachePath(newCachePath); 9649 9650 // TODO: extend to support split APKs 9651 pkg.codePath = getCodePath(); 9652 pkg.baseCodePath = getCodePath(); 9653 pkg.splitCodePaths = null; 9654 9655 pkg.applicationInfo.setCodePath(getCodePath()); 9656 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9657 pkg.applicationInfo.setSplitCodePaths(null); 9658 pkg.applicationInfo.setResourcePath(getResourcePath()); 9659 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9660 pkg.applicationInfo.setSplitResourcePaths(null); 9661 9662 return true; 9663 } 9664 9665 private void setCachePath(String newCachePath) { 9666 File cachePath = new File(newCachePath); 9667 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9668 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9669 9670 if (isFwdLocked()) { 9671 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9672 } else { 9673 resourcePath = packagePath; 9674 } 9675 } 9676 9677 int doPostInstall(int status, int uid) { 9678 if (status != PackageManager.INSTALL_SUCCEEDED) { 9679 cleanUp(); 9680 } else { 9681 final int groupOwner; 9682 final String protectedFile; 9683 if (isFwdLocked()) { 9684 groupOwner = UserHandle.getSharedAppGid(uid); 9685 protectedFile = RES_FILE_NAME; 9686 } else { 9687 groupOwner = -1; 9688 protectedFile = null; 9689 } 9690 9691 if (uid < Process.FIRST_APPLICATION_UID 9692 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9693 Slog.e(TAG, "Failed to finalize " + cid); 9694 PackageHelper.destroySdDir(cid); 9695 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9696 } 9697 9698 boolean mounted = PackageHelper.isContainerMounted(cid); 9699 if (!mounted) { 9700 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9701 } 9702 } 9703 return status; 9704 } 9705 9706 private void cleanUp() { 9707 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9708 9709 // Destroy secure container 9710 PackageHelper.destroySdDir(cid); 9711 } 9712 9713 void cleanUpResourcesLI() { 9714 String sourceFile = getCodePath(); 9715 // Remove dex file 9716 if (instructionSets == null) { 9717 throw new IllegalStateException("instructionSet == null"); 9718 } 9719 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9720 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9721 int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet); 9722 if (retCode < 0) { 9723 Slog.w(TAG, "Couldn't remove dex file for package: " 9724 + " at location " 9725 + sourceFile.toString() + ", retcode=" + retCode); 9726 // we don't consider this to be a failure of the core package deletion 9727 } 9728 } 9729 cleanUp(); 9730 } 9731 9732 boolean matchContainer(String app) { 9733 if (cid.startsWith(app)) { 9734 return true; 9735 } 9736 return false; 9737 } 9738 9739 String getPackageName() { 9740 return getAsecPackageName(cid); 9741 } 9742 9743 boolean doPostDeleteLI(boolean delete) { 9744 boolean ret = false; 9745 boolean mounted = PackageHelper.isContainerMounted(cid); 9746 if (mounted) { 9747 // Unmount first 9748 ret = PackageHelper.unMountSdDir(cid); 9749 } 9750 if (ret && delete) { 9751 cleanUpResourcesLI(); 9752 } 9753 return ret; 9754 } 9755 9756 @Override 9757 int doPreCopy() { 9758 if (isFwdLocked()) { 9759 if (!PackageHelper.fixSdPermissions(cid, 9760 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9761 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9762 } 9763 } 9764 9765 return PackageManager.INSTALL_SUCCEEDED; 9766 } 9767 9768 @Override 9769 int doPostCopy(int uid) { 9770 if (isFwdLocked()) { 9771 if (uid < Process.FIRST_APPLICATION_UID 9772 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9773 RES_FILE_NAME)) { 9774 Slog.e(TAG, "Failed to finalize " + cid); 9775 PackageHelper.destroySdDir(cid); 9776 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9777 } 9778 } 9779 9780 return PackageManager.INSTALL_SUCCEEDED; 9781 } 9782 } 9783 9784 static String getAsecPackageName(String packageCid) { 9785 int idx = packageCid.lastIndexOf("-"); 9786 if (idx == -1) { 9787 return packageCid; 9788 } 9789 return packageCid.substring(0, idx); 9790 } 9791 9792 // Utility method used to create code paths based on package name and available index. 9793 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9794 String idxStr = ""; 9795 int idx = 1; 9796 // Fall back to default value of idx=1 if prefix is not 9797 // part of oldCodePath 9798 if (oldCodePath != null) { 9799 String subStr = oldCodePath; 9800 // Drop the suffix right away 9801 if (suffix != null && subStr.endsWith(suffix)) { 9802 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9803 } 9804 // If oldCodePath already contains prefix find out the 9805 // ending index to either increment or decrement. 9806 int sidx = subStr.lastIndexOf(prefix); 9807 if (sidx != -1) { 9808 subStr = subStr.substring(sidx + prefix.length()); 9809 if (subStr != null) { 9810 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9811 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9812 } 9813 try { 9814 idx = Integer.parseInt(subStr); 9815 if (idx <= 1) { 9816 idx++; 9817 } else { 9818 idx--; 9819 } 9820 } catch(NumberFormatException e) { 9821 } 9822 } 9823 } 9824 } 9825 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9826 return prefix + idxStr; 9827 } 9828 9829 private File getNextCodePath(String packageName) { 9830 int suffix = 1; 9831 File result; 9832 do { 9833 result = new File(mAppInstallDir, packageName + "-" + suffix); 9834 suffix++; 9835 } while (result.exists()); 9836 return result; 9837 } 9838 9839 // Utility method used to ignore ADD/REMOVE events 9840 // by directory observer. 9841 private static boolean ignoreCodePath(String fullPathStr) { 9842 String apkName = deriveCodePathName(fullPathStr); 9843 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9844 if (idx != -1 && ((idx+1) < apkName.length())) { 9845 // Make sure the package ends with a numeral 9846 String version = apkName.substring(idx+1); 9847 try { 9848 Integer.parseInt(version); 9849 return true; 9850 } catch (NumberFormatException e) {} 9851 } 9852 return false; 9853 } 9854 9855 // Utility method that returns the relative package path with respect 9856 // to the installation directory. Like say for /data/data/com.test-1.apk 9857 // string com.test-1 is returned. 9858 static String deriveCodePathName(String codePath) { 9859 if (codePath == null) { 9860 return null; 9861 } 9862 final File codeFile = new File(codePath); 9863 final String name = codeFile.getName(); 9864 if (codeFile.isDirectory()) { 9865 return name; 9866 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9867 final int lastDot = name.lastIndexOf('.'); 9868 return name.substring(0, lastDot); 9869 } else { 9870 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9871 return null; 9872 } 9873 } 9874 9875 class PackageInstalledInfo { 9876 String name; 9877 int uid; 9878 // The set of users that originally had this package installed. 9879 int[] origUsers; 9880 // The set of users that now have this package installed. 9881 int[] newUsers; 9882 PackageParser.Package pkg; 9883 int returnCode; 9884 String returnMsg; 9885 PackageRemovedInfo removedInfo; 9886 9887 public void setError(int code, String msg) { 9888 returnCode = code; 9889 returnMsg = msg; 9890 Slog.w(TAG, msg); 9891 } 9892 9893 public void setError(String msg, PackageParserException e) { 9894 returnCode = e.error; 9895 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9896 Slog.w(TAG, msg, e); 9897 } 9898 9899 public void setError(String msg, PackageManagerException e) { 9900 returnCode = e.error; 9901 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9902 Slog.w(TAG, msg, e); 9903 } 9904 9905 // In some error cases we want to convey more info back to the observer 9906 String origPackage; 9907 String origPermission; 9908 } 9909 9910 /* 9911 * Install a non-existing package. 9912 */ 9913 private void installNewPackageLI(PackageParser.Package pkg, 9914 int parseFlags, int scanMode, UserHandle user, 9915 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9916 // Remember this for later, in case we need to rollback this install 9917 String pkgName = pkg.packageName; 9918 9919 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9920 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9921 synchronized(mPackages) { 9922 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9923 // A package with the same name is already installed, though 9924 // it has been renamed to an older name. The package we 9925 // are trying to install should be installed as an update to 9926 // the existing one, but that has not been requested, so bail. 9927 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9928 + " without first uninstalling package running as " 9929 + mSettings.mRenamedPackages.get(pkgName)); 9930 return; 9931 } 9932 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9933 // Don't allow installation over an existing package with the same name. 9934 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9935 + " without first uninstalling."); 9936 return; 9937 } 9938 } 9939 9940 try { 9941 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9942 System.currentTimeMillis(), user, abiOverride); 9943 9944 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9945 // delete the partially installed application. the data directory will have to be 9946 // restored if it was already existing 9947 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9948 // remove package from internal structures. Note that we want deletePackageX to 9949 // delete the package data and cache directories that it created in 9950 // scanPackageLocked, unless those directories existed before we even tried to 9951 // install. 9952 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9953 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9954 res.removedInfo, true); 9955 } 9956 9957 } catch (PackageManagerException e) { 9958 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9959 } 9960 } 9961 9962 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9963 // Upgrade keysets are being used. Determine if new package has a superset of the 9964 // required keys. 9965 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9966 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9967 for (int i = 0; i < upgradeKeySets.length; i++) { 9968 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9969 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9970 return true; 9971 } 9972 } 9973 return false; 9974 } 9975 9976 private void replacePackageLI(PackageParser.Package pkg, 9977 int parseFlags, int scanMode, UserHandle user, 9978 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9979 PackageParser.Package oldPackage; 9980 String pkgName = pkg.packageName; 9981 int[] allUsers; 9982 boolean[] perUserInstalled; 9983 9984 // First find the old package info and check signatures 9985 synchronized(mPackages) { 9986 oldPackage = mPackages.get(pkgName); 9987 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9988 PackageSetting ps = mSettings.mPackages.get(pkgName); 9989 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9990 // default to original signature matching 9991 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9992 != PackageManager.SIGNATURE_MATCH) { 9993 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9994 "New package has a different signature: " + pkgName); 9995 return; 9996 } 9997 } else { 9998 if(!checkUpgradeKeySetLP(ps, pkg)) { 9999 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10000 "New package not signed by keys specified by upgrade-keysets: " 10001 + pkgName); 10002 return; 10003 } 10004 } 10005 10006 // In case of rollback, remember per-user/profile install state 10007 allUsers = sUserManager.getUserIds(); 10008 perUserInstalled = new boolean[allUsers.length]; 10009 for (int i = 0; i < allUsers.length; i++) { 10010 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10011 } 10012 } 10013 10014 boolean sysPkg = (isSystemApp(oldPackage)); 10015 if (sysPkg) { 10016 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10017 user, allUsers, perUserInstalled, installerPackageName, res, 10018 abiOverride); 10019 } else { 10020 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10021 user, allUsers, perUserInstalled, installerPackageName, res, 10022 abiOverride); 10023 } 10024 } 10025 10026 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10027 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10028 int[] allUsers, boolean[] perUserInstalled, 10029 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10030 String pkgName = deletedPackage.packageName; 10031 boolean deletedPkg = true; 10032 boolean updatedSettings = false; 10033 10034 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10035 + deletedPackage); 10036 long origUpdateTime; 10037 if (pkg.mExtras != null) { 10038 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10039 } else { 10040 origUpdateTime = 0; 10041 } 10042 10043 // First delete the existing package while retaining the data directory 10044 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10045 res.removedInfo, true)) { 10046 // If the existing package wasn't successfully deleted 10047 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10048 deletedPkg = false; 10049 } else { 10050 // Successfully deleted the old package. Now proceed with re-installation 10051 deleteCodeCacheDirsLI(pkgName); 10052 try { 10053 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10054 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10055 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10056 updatedSettings = true; 10057 } catch (PackageManagerException e) { 10058 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10059 } 10060 } 10061 10062 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10063 // remove package from internal structures. Note that we want deletePackageX to 10064 // delete the package data and cache directories that it created in 10065 // scanPackageLocked, unless those directories existed before we even tried to 10066 // install. 10067 if(updatedSettings) { 10068 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10069 deletePackageLI( 10070 pkgName, null, true, allUsers, perUserInstalled, 10071 PackageManager.DELETE_KEEP_DATA, 10072 res.removedInfo, true); 10073 } 10074 // Since we failed to install the new package we need to restore the old 10075 // package that we deleted. 10076 if (deletedPkg) { 10077 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10078 File restoreFile = new File(deletedPackage.codePath); 10079 // Parse old package 10080 boolean oldOnSd = isExternal(deletedPackage); 10081 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10082 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10083 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10084 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10085 | SCAN_UPDATE_TIME; 10086 try { 10087 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10088 null); 10089 } catch (PackageManagerException e) { 10090 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10091 + e.getMessage()); 10092 return; 10093 } 10094 // Restore of old package succeeded. Update permissions. 10095 // writer 10096 synchronized (mPackages) { 10097 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10098 UPDATE_PERMISSIONS_ALL); 10099 // can downgrade to reader 10100 mSettings.writeLPr(); 10101 } 10102 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10103 } 10104 } 10105 } 10106 10107 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10108 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10109 int[] allUsers, boolean[] perUserInstalled, 10110 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10111 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10112 + ", old=" + deletedPackage); 10113 boolean updatedSettings = false; 10114 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10115 PackageParser.PARSE_IS_SYSTEM; 10116 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10117 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10118 } 10119 String packageName = deletedPackage.packageName; 10120 if (packageName == null) { 10121 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10122 "Attempt to delete null packageName."); 10123 return; 10124 } 10125 PackageParser.Package oldPkg; 10126 PackageSetting oldPkgSetting; 10127 // reader 10128 synchronized (mPackages) { 10129 oldPkg = mPackages.get(packageName); 10130 oldPkgSetting = mSettings.mPackages.get(packageName); 10131 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10132 (oldPkgSetting == null)) { 10133 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10134 "Couldn't find package:" + packageName + " information"); 10135 return; 10136 } 10137 } 10138 10139 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10140 10141 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10142 res.removedInfo.removedPackage = packageName; 10143 // Remove existing system package 10144 removePackageLI(oldPkgSetting, true); 10145 // writer 10146 synchronized (mPackages) { 10147 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10148 // We didn't need to disable the .apk as a current system package, 10149 // which means we are replacing another update that is already 10150 // installed. We need to make sure to delete the older one's .apk. 10151 res.removedInfo.args = createInstallArgsForExisting(0, 10152 deletedPackage.applicationInfo.getCodePath(), 10153 deletedPackage.applicationInfo.getResourcePath(), 10154 deletedPackage.applicationInfo.nativeLibraryRootDir, 10155 getAppDexInstructionSets(deletedPackage.applicationInfo), 10156 isMultiArch(deletedPackage.applicationInfo)); 10157 } else { 10158 res.removedInfo.args = null; 10159 } 10160 } 10161 10162 // Successfully disabled the old package. Now proceed with re-installation 10163 deleteCodeCacheDirsLI(packageName); 10164 10165 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10166 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10167 10168 PackageParser.Package newPackage = null; 10169 try { 10170 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10171 if (newPackage.mExtras != null) { 10172 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10173 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10174 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10175 10176 // is the update attempting to change shared user? that isn't going to work... 10177 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10178 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10179 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10180 + " to " + newPkgSetting.sharedUser); 10181 updatedSettings = true; 10182 } 10183 } 10184 10185 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10186 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10187 updatedSettings = true; 10188 } 10189 10190 } catch (PackageManagerException e) { 10191 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10192 } 10193 10194 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10195 // Re installation failed. Restore old information 10196 // Remove new pkg information 10197 if (newPackage != null) { 10198 removeInstalledPackageLI(newPackage, true); 10199 } 10200 // Add back the old system package 10201 try { 10202 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10203 null); 10204 } catch (PackageManagerException e) { 10205 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10206 } 10207 // Restore the old system information in Settings 10208 synchronized(mPackages) { 10209 if (updatedSettings) { 10210 mSettings.enableSystemPackageLPw(packageName); 10211 mSettings.setInstallerPackageName(packageName, 10212 oldPkgSetting.installerPackageName); 10213 } 10214 mSettings.writeLPr(); 10215 } 10216 } 10217 } 10218 10219 // Utility method used to move dex files during install. 10220 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10221 // TODO: extend to move split APK dex files 10222 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10223 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10224 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10225 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10226 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10227 dexCodeInstructionSet); 10228 if (retCode != 0) { 10229 /* 10230 * Programs may be lazily run through dexopt, so the 10231 * source may not exist. However, something seems to 10232 * have gone wrong, so note that dexopt needs to be 10233 * run again and remove the source file. In addition, 10234 * remove the target to make sure there isn't a stale 10235 * file from a previous version of the package. 10236 */ 10237 newPackage.mDexOptPerformed.clear(); 10238 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10239 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10240 } 10241 } 10242 } 10243 return PackageManager.INSTALL_SUCCEEDED; 10244 } 10245 10246 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10247 int[] allUsers, boolean[] perUserInstalled, 10248 PackageInstalledInfo res) { 10249 String pkgName = newPackage.packageName; 10250 synchronized (mPackages) { 10251 //write settings. the installStatus will be incomplete at this stage. 10252 //note that the new package setting would have already been 10253 //added to mPackages. It hasn't been persisted yet. 10254 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10255 mSettings.writeLPr(); 10256 } 10257 10258 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10259 10260 synchronized (mPackages) { 10261 updatePermissionsLPw(newPackage.packageName, newPackage, 10262 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10263 ? UPDATE_PERMISSIONS_ALL : 0)); 10264 // For system-bundled packages, we assume that installing an upgraded version 10265 // of the package implies that the user actually wants to run that new code, 10266 // so we enable the package. 10267 if (isSystemApp(newPackage)) { 10268 // NB: implicit assumption that system package upgrades apply to all users 10269 if (DEBUG_INSTALL) { 10270 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10271 } 10272 PackageSetting ps = mSettings.mPackages.get(pkgName); 10273 if (ps != null) { 10274 if (res.origUsers != null) { 10275 for (int userHandle : res.origUsers) { 10276 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10277 userHandle, installerPackageName); 10278 } 10279 } 10280 // Also convey the prior install/uninstall state 10281 if (allUsers != null && perUserInstalled != null) { 10282 for (int i = 0; i < allUsers.length; i++) { 10283 if (DEBUG_INSTALL) { 10284 Slog.d(TAG, " user " + allUsers[i] 10285 + " => " + perUserInstalled[i]); 10286 } 10287 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10288 } 10289 // these install state changes will be persisted in the 10290 // upcoming call to mSettings.writeLPr(). 10291 } 10292 } 10293 } 10294 res.name = pkgName; 10295 res.uid = newPackage.applicationInfo.uid; 10296 res.pkg = newPackage; 10297 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10298 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10299 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10300 //to update install status 10301 mSettings.writeLPr(); 10302 } 10303 } 10304 10305 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10306 int pFlags = args.flags; 10307 String installerPackageName = args.installerPackageName; 10308 File tmpPackageFile = new File(args.getCodePath()); 10309 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10310 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10311 boolean replace = false; 10312 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10313 | (newInstall ? SCAN_NEW_INSTALL : 0); 10314 // Result object to be returned 10315 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10316 10317 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10318 // Retrieve PackageSettings and parse package 10319 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10320 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10321 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10322 PackageParser pp = new PackageParser(); 10323 pp.setSeparateProcesses(mSeparateProcesses); 10324 pp.setDisplayMetrics(mMetrics); 10325 10326 final PackageParser.Package pkg; 10327 try { 10328 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10329 } catch (PackageParserException e) { 10330 res.setError("Failed parse during installPackageLI", e); 10331 return; 10332 } 10333 10334 String pkgName = res.name = pkg.packageName; 10335 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10336 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10337 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10338 return; 10339 } 10340 } 10341 10342 try { 10343 pp.collectCertificates(pkg, parseFlags); 10344 pp.collectManifestDigest(pkg); 10345 } catch (PackageParserException e) { 10346 res.setError("Failed collect during installPackageLI", e); 10347 return; 10348 } 10349 10350 /* If the installer passed in a manifest digest, compare it now. */ 10351 if (args.manifestDigest != null) { 10352 if (DEBUG_INSTALL) { 10353 final String parsedManifest = pkg.manifestDigest == null ? "null" 10354 : pkg.manifestDigest.toString(); 10355 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10356 + parsedManifest); 10357 } 10358 10359 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10360 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10361 return; 10362 } 10363 } else if (DEBUG_INSTALL) { 10364 final String parsedManifest = pkg.manifestDigest == null 10365 ? "null" : pkg.manifestDigest.toString(); 10366 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10367 } 10368 10369 // Get rid of all references to package scan path via parser. 10370 pp = null; 10371 String oldCodePath = null; 10372 boolean systemApp = false; 10373 synchronized (mPackages) { 10374 // Check whether the newly-scanned package wants to define an already-defined perm 10375 int N = pkg.permissions.size(); 10376 for (int i = N-1; i >= 0; i--) { 10377 PackageParser.Permission perm = pkg.permissions.get(i); 10378 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10379 if (bp != null) { 10380 // If the defining package is signed with our cert, it's okay. This 10381 // also includes the "updating the same package" case, of course. 10382 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10383 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10384 // If the owning package is the system itself, we log but allow 10385 // install to proceed; we fail the install on all other permission 10386 // redefinitions. 10387 if (!bp.sourcePackage.equals("android")) { 10388 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10389 + pkg.packageName + " attempting to redeclare permission " 10390 + perm.info.name + " already owned by " + bp.sourcePackage); 10391 res.origPermission = perm.info.name; 10392 res.origPackage = bp.sourcePackage; 10393 return; 10394 } else { 10395 Slog.w(TAG, "Package " + pkg.packageName 10396 + " attempting to redeclare system permission " 10397 + perm.info.name + "; ignoring new declaration"); 10398 pkg.permissions.remove(i); 10399 } 10400 } 10401 } 10402 } 10403 10404 // Check if installing already existing package 10405 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10406 String oldName = mSettings.mRenamedPackages.get(pkgName); 10407 if (pkg.mOriginalPackages != null 10408 && pkg.mOriginalPackages.contains(oldName) 10409 && mPackages.containsKey(oldName)) { 10410 // This package is derived from an original package, 10411 // and this device has been updating from that original 10412 // name. We must continue using the original name, so 10413 // rename the new package here. 10414 pkg.setPackageName(oldName); 10415 pkgName = pkg.packageName; 10416 replace = true; 10417 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10418 + oldName + " pkgName=" + pkgName); 10419 } else if (mPackages.containsKey(pkgName)) { 10420 // This package, under its official name, already exists 10421 // on the device; we should replace it. 10422 replace = true; 10423 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10424 } 10425 } 10426 PackageSetting ps = mSettings.mPackages.get(pkgName); 10427 if (ps != null) { 10428 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10429 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10430 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10431 systemApp = (ps.pkg.applicationInfo.flags & 10432 ApplicationInfo.FLAG_SYSTEM) != 0; 10433 } 10434 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10435 } 10436 } 10437 10438 if (systemApp && onSd) { 10439 // Disable updates to system apps on sdcard 10440 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10441 "Cannot install updates to system apps on sdcard"); 10442 return; 10443 } 10444 10445 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10446 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10447 return; 10448 } 10449 10450 if (replace) { 10451 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10452 installerPackageName, res, args.abiOverride); 10453 } else { 10454 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10455 installerPackageName, res, args.abiOverride); 10456 } 10457 synchronized (mPackages) { 10458 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10459 if (ps != null) { 10460 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10461 } 10462 } 10463 } 10464 10465 private static boolean isForwardLocked(PackageParser.Package pkg) { 10466 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10467 } 10468 10469 private static boolean isForwardLocked(ApplicationInfo info) { 10470 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10471 } 10472 10473 private boolean isForwardLocked(PackageSetting ps) { 10474 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10475 } 10476 10477 private static boolean isMultiArch(PackageSetting ps) { 10478 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10479 } 10480 10481 private static boolean isMultiArch(ApplicationInfo info) { 10482 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10483 } 10484 10485 private static boolean isExternal(PackageParser.Package pkg) { 10486 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10487 } 10488 10489 private static boolean isExternal(PackageSetting ps) { 10490 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10491 } 10492 10493 private static boolean isExternal(ApplicationInfo info) { 10494 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10495 } 10496 10497 private static boolean isSystemApp(PackageParser.Package pkg) { 10498 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10499 } 10500 10501 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10502 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10503 } 10504 10505 private static boolean isSystemApp(ApplicationInfo info) { 10506 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10507 } 10508 10509 private static boolean isSystemApp(PackageSetting ps) { 10510 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10511 } 10512 10513 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10514 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10515 } 10516 10517 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10518 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10519 } 10520 10521 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10522 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10523 } 10524 10525 private int packageFlagsToInstallFlags(PackageSetting ps) { 10526 int installFlags = 0; 10527 if (isExternal(ps)) { 10528 installFlags |= PackageManager.INSTALL_EXTERNAL; 10529 } 10530 if (isForwardLocked(ps)) { 10531 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10532 } 10533 return installFlags; 10534 } 10535 10536 private void deleteTempPackageFiles() { 10537 final FilenameFilter filter = new FilenameFilter() { 10538 public boolean accept(File dir, String name) { 10539 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10540 } 10541 }; 10542 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10543 file.delete(); 10544 } 10545 } 10546 10547 @Override 10548 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10549 int flags) { 10550 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10551 flags); 10552 } 10553 10554 @Override 10555 public void deletePackage(final String packageName, 10556 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10557 mContext.enforceCallingOrSelfPermission( 10558 android.Manifest.permission.DELETE_PACKAGES, null); 10559 final int uid = Binder.getCallingUid(); 10560 if (UserHandle.getUserId(uid) != userId) { 10561 mContext.enforceCallingPermission( 10562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10563 "deletePackage for user " + userId); 10564 } 10565 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10566 try { 10567 observer.onPackageDeleted(packageName, 10568 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10569 } catch (RemoteException re) { 10570 } 10571 return; 10572 } 10573 10574 boolean uninstallBlocked = false; 10575 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10576 int[] users = sUserManager.getUserIds(); 10577 for (int i = 0; i < users.length; ++i) { 10578 if (getBlockUninstallForUser(packageName, users[i])) { 10579 uninstallBlocked = true; 10580 break; 10581 } 10582 } 10583 } else { 10584 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10585 } 10586 if (uninstallBlocked) { 10587 try { 10588 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10589 null); 10590 } catch (RemoteException re) { 10591 } 10592 return; 10593 } 10594 10595 if (DEBUG_REMOVE) { 10596 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10597 } 10598 // Queue up an async operation since the package deletion may take a little while. 10599 mHandler.post(new Runnable() { 10600 public void run() { 10601 mHandler.removeCallbacks(this); 10602 final int returnCode = deletePackageX(packageName, userId, flags); 10603 if (observer != null) { 10604 try { 10605 observer.onPackageDeleted(packageName, returnCode, null); 10606 } catch (RemoteException e) { 10607 Log.i(TAG, "Observer no longer exists."); 10608 } //end catch 10609 } //end if 10610 } //end run 10611 }); 10612 } 10613 10614 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10615 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10616 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10617 try { 10618 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10619 || dpm.isDeviceOwner(packageName))) { 10620 return true; 10621 } 10622 } catch (RemoteException e) { 10623 } 10624 return false; 10625 } 10626 10627 /** 10628 * This method is an internal method that could be get invoked either 10629 * to delete an installed package or to clean up a failed installation. 10630 * After deleting an installed package, a broadcast is sent to notify any 10631 * listeners that the package has been installed. For cleaning up a failed 10632 * installation, the broadcast is not necessary since the package's 10633 * installation wouldn't have sent the initial broadcast either 10634 * The key steps in deleting a package are 10635 * deleting the package information in internal structures like mPackages, 10636 * deleting the packages base directories through installd 10637 * updating mSettings to reflect current status 10638 * persisting settings for later use 10639 * sending a broadcast if necessary 10640 */ 10641 private int deletePackageX(String packageName, int userId, int flags) { 10642 final PackageRemovedInfo info = new PackageRemovedInfo(); 10643 final boolean res; 10644 10645 if (isPackageDeviceAdmin(packageName, userId)) { 10646 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10647 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10648 } 10649 10650 boolean removedForAllUsers = false; 10651 boolean systemUpdate = false; 10652 10653 // for the uninstall-updates case and restricted profiles, remember the per- 10654 // userhandle installed state 10655 int[] allUsers; 10656 boolean[] perUserInstalled; 10657 synchronized (mPackages) { 10658 PackageSetting ps = mSettings.mPackages.get(packageName); 10659 allUsers = sUserManager.getUserIds(); 10660 perUserInstalled = new boolean[allUsers.length]; 10661 for (int i = 0; i < allUsers.length; i++) { 10662 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10663 } 10664 } 10665 10666 synchronized (mInstallLock) { 10667 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10668 res = deletePackageLI(packageName, 10669 (flags & PackageManager.DELETE_ALL_USERS) != 0 10670 ? UserHandle.ALL : new UserHandle(userId), 10671 true, allUsers, perUserInstalled, 10672 flags | REMOVE_CHATTY, info, true); 10673 systemUpdate = info.isRemovedPackageSystemUpdate; 10674 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10675 removedForAllUsers = true; 10676 } 10677 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10678 + " removedForAllUsers=" + removedForAllUsers); 10679 } 10680 10681 if (res) { 10682 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10683 10684 // If the removed package was a system update, the old system package 10685 // was re-enabled; we need to broadcast this information 10686 if (systemUpdate) { 10687 Bundle extras = new Bundle(1); 10688 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10689 ? info.removedAppId : info.uid); 10690 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10691 10692 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10693 extras, null, null, null); 10694 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10695 extras, null, null, null); 10696 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10697 null, packageName, null, null); 10698 } 10699 } 10700 // Force a gc here. 10701 Runtime.getRuntime().gc(); 10702 // Delete the resources here after sending the broadcast to let 10703 // other processes clean up before deleting resources. 10704 if (info.args != null) { 10705 synchronized (mInstallLock) { 10706 info.args.doPostDeleteLI(true); 10707 } 10708 } 10709 10710 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10711 } 10712 10713 static class PackageRemovedInfo { 10714 String removedPackage; 10715 int uid = -1; 10716 int removedAppId = -1; 10717 int[] removedUsers = null; 10718 boolean isRemovedPackageSystemUpdate = false; 10719 // Clean up resources deleted packages. 10720 InstallArgs args = null; 10721 10722 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10723 Bundle extras = new Bundle(1); 10724 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10725 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10726 if (replacing) { 10727 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10728 } 10729 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10730 if (removedPackage != null) { 10731 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10732 extras, null, null, removedUsers); 10733 if (fullRemove && !replacing) { 10734 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10735 extras, null, null, removedUsers); 10736 } 10737 } 10738 if (removedAppId >= 0) { 10739 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10740 removedUsers); 10741 } 10742 } 10743 } 10744 10745 /* 10746 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10747 * flag is not set, the data directory is removed as well. 10748 * make sure this flag is set for partially installed apps. If not its meaningless to 10749 * delete a partially installed application. 10750 */ 10751 private void removePackageDataLI(PackageSetting ps, 10752 int[] allUserHandles, boolean[] perUserInstalled, 10753 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10754 String packageName = ps.name; 10755 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10756 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10757 // Retrieve object to delete permissions for shared user later on 10758 final PackageSetting deletedPs; 10759 // reader 10760 synchronized (mPackages) { 10761 deletedPs = mSettings.mPackages.get(packageName); 10762 if (outInfo != null) { 10763 outInfo.removedPackage = packageName; 10764 outInfo.removedUsers = deletedPs != null 10765 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10766 : null; 10767 } 10768 } 10769 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10770 removeDataDirsLI(packageName); 10771 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10772 } 10773 // writer 10774 synchronized (mPackages) { 10775 if (deletedPs != null) { 10776 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10777 if (outInfo != null) { 10778 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10779 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10780 } 10781 if (deletedPs != null) { 10782 updatePermissionsLPw(deletedPs.name, null, 0); 10783 if (deletedPs.sharedUser != null) { 10784 // remove permissions associated with package 10785 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10786 } 10787 } 10788 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10789 } 10790 // make sure to preserve per-user disabled state if this removal was just 10791 // a downgrade of a system app to the factory package 10792 if (allUserHandles != null && perUserInstalled != null) { 10793 if (DEBUG_REMOVE) { 10794 Slog.d(TAG, "Propagating install state across downgrade"); 10795 } 10796 for (int i = 0; i < allUserHandles.length; i++) { 10797 if (DEBUG_REMOVE) { 10798 Slog.d(TAG, " user " + allUserHandles[i] 10799 + " => " + perUserInstalled[i]); 10800 } 10801 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10802 } 10803 } 10804 } 10805 // can downgrade to reader 10806 if (writeSettings) { 10807 // Save settings now 10808 mSettings.writeLPr(); 10809 } 10810 } 10811 if (outInfo != null) { 10812 // A user ID was deleted here. Go through all users and remove it 10813 // from KeyStore. 10814 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10815 } 10816 } 10817 10818 static boolean locationIsPrivileged(File path) { 10819 try { 10820 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10821 .getCanonicalPath(); 10822 return path.getCanonicalPath().startsWith(privilegedAppDir); 10823 } catch (IOException e) { 10824 Slog.e(TAG, "Unable to access code path " + path); 10825 } 10826 return false; 10827 } 10828 10829 /* 10830 * Tries to delete system package. 10831 */ 10832 private boolean deleteSystemPackageLI(PackageSetting newPs, 10833 int[] allUserHandles, boolean[] perUserInstalled, 10834 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10835 final boolean applyUserRestrictions 10836 = (allUserHandles != null) && (perUserInstalled != null); 10837 PackageSetting disabledPs = null; 10838 // Confirm if the system package has been updated 10839 // An updated system app can be deleted. This will also have to restore 10840 // the system pkg from system partition 10841 // reader 10842 synchronized (mPackages) { 10843 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10844 } 10845 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10846 + " disabledPs=" + disabledPs); 10847 if (disabledPs == null) { 10848 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10849 return false; 10850 } else if (DEBUG_REMOVE) { 10851 Slog.d(TAG, "Deleting system pkg from data partition"); 10852 } 10853 if (DEBUG_REMOVE) { 10854 if (applyUserRestrictions) { 10855 Slog.d(TAG, "Remembering install states:"); 10856 for (int i = 0; i < allUserHandles.length; i++) { 10857 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10858 } 10859 } 10860 } 10861 // Delete the updated package 10862 outInfo.isRemovedPackageSystemUpdate = true; 10863 if (disabledPs.versionCode < newPs.versionCode) { 10864 // Delete data for downgrades 10865 flags &= ~PackageManager.DELETE_KEEP_DATA; 10866 } else { 10867 // Preserve data by setting flag 10868 flags |= PackageManager.DELETE_KEEP_DATA; 10869 } 10870 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10871 allUserHandles, perUserInstalled, outInfo, writeSettings); 10872 if (!ret) { 10873 return false; 10874 } 10875 // writer 10876 synchronized (mPackages) { 10877 // Reinstate the old system package 10878 mSettings.enableSystemPackageLPw(newPs.name); 10879 // Remove any native libraries from the upgraded package. 10880 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10881 } 10882 // Install the system package 10883 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10884 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10885 if (locationIsPrivileged(disabledPs.codePath)) { 10886 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10887 } 10888 10889 final PackageParser.Package newPkg; 10890 try { 10891 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10892 null, null); 10893 } catch (PackageManagerException e) { 10894 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10895 return false; 10896 } 10897 10898 // writer 10899 synchronized (mPackages) { 10900 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10901 updatePermissionsLPw(newPkg.packageName, newPkg, 10902 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10903 if (applyUserRestrictions) { 10904 if (DEBUG_REMOVE) { 10905 Slog.d(TAG, "Propagating install state across reinstall"); 10906 } 10907 for (int i = 0; i < allUserHandles.length; i++) { 10908 if (DEBUG_REMOVE) { 10909 Slog.d(TAG, " user " + allUserHandles[i] 10910 + " => " + perUserInstalled[i]); 10911 } 10912 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10913 } 10914 // Regardless of writeSettings we need to ensure that this restriction 10915 // state propagation is persisted 10916 mSettings.writeAllUsersPackageRestrictionsLPr(); 10917 } 10918 // can downgrade to reader here 10919 if (writeSettings) { 10920 mSettings.writeLPr(); 10921 } 10922 } 10923 return true; 10924 } 10925 10926 private boolean deleteInstalledPackageLI(PackageSetting ps, 10927 boolean deleteCodeAndResources, int flags, 10928 int[] allUserHandles, boolean[] perUserInstalled, 10929 PackageRemovedInfo outInfo, boolean writeSettings) { 10930 if (outInfo != null) { 10931 outInfo.uid = ps.appId; 10932 } 10933 10934 // Delete package data from internal structures and also remove data if flag is set 10935 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10936 10937 // Delete application code and resources 10938 if (deleteCodeAndResources && (outInfo != null)) { 10939 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10940 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10941 getAppDexInstructionSets(ps), isMultiArch(ps)); 10942 } 10943 return true; 10944 } 10945 10946 @Override 10947 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10948 int userId) { 10949 mContext.enforceCallingOrSelfPermission( 10950 android.Manifest.permission.DELETE_PACKAGES, null); 10951 synchronized (mPackages) { 10952 PackageSetting ps = mSettings.mPackages.get(packageName); 10953 if (ps == null) { 10954 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10955 return false; 10956 } 10957 if (!ps.getInstalled(userId)) { 10958 // Can't block uninstall for an app that is not installed or enabled. 10959 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10960 return false; 10961 } 10962 ps.setBlockUninstall(blockUninstall, userId); 10963 mSettings.writePackageRestrictionsLPr(userId); 10964 } 10965 return true; 10966 } 10967 10968 @Override 10969 public boolean getBlockUninstallForUser(String packageName, int userId) { 10970 synchronized (mPackages) { 10971 PackageSetting ps = mSettings.mPackages.get(packageName); 10972 if (ps == null) { 10973 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10974 return false; 10975 } 10976 return ps.getBlockUninstall(userId); 10977 } 10978 } 10979 10980 /* 10981 * This method handles package deletion in general 10982 */ 10983 private boolean deletePackageLI(String packageName, UserHandle user, 10984 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10985 int flags, PackageRemovedInfo outInfo, 10986 boolean writeSettings) { 10987 if (packageName == null) { 10988 Slog.w(TAG, "Attempt to delete null packageName."); 10989 return false; 10990 } 10991 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10992 PackageSetting ps; 10993 boolean dataOnly = false; 10994 int removeUser = -1; 10995 int appId = -1; 10996 synchronized (mPackages) { 10997 ps = mSettings.mPackages.get(packageName); 10998 if (ps == null) { 10999 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11000 return false; 11001 } 11002 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11003 && user.getIdentifier() != UserHandle.USER_ALL) { 11004 // The caller is asking that the package only be deleted for a single 11005 // user. To do this, we just mark its uninstalled state and delete 11006 // its data. If this is a system app, we only allow this to happen if 11007 // they have set the special DELETE_SYSTEM_APP which requests different 11008 // semantics than normal for uninstalling system apps. 11009 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11010 ps.setUserState(user.getIdentifier(), 11011 COMPONENT_ENABLED_STATE_DEFAULT, 11012 false, //installed 11013 true, //stopped 11014 true, //notLaunched 11015 false, //hidden 11016 null, null, null, 11017 false // blockUninstall 11018 ); 11019 if (!isSystemApp(ps)) { 11020 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11021 // Other user 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, "Still installed by other users"); 11025 removeUser = user.getIdentifier(); 11026 appId = ps.appId; 11027 mSettings.writePackageRestrictionsLPr(removeUser); 11028 } else { 11029 // We need to set it back to 'installed' so the uninstall 11030 // broadcasts will be sent correctly. 11031 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11032 ps.setInstalled(true, user.getIdentifier()); 11033 } 11034 } else { 11035 // This is a system app, so we assume that the 11036 // other users still have this package installed, so all 11037 // we need to do is clear this user's data and save that 11038 // it is uninstalled. 11039 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11040 removeUser = user.getIdentifier(); 11041 appId = ps.appId; 11042 mSettings.writePackageRestrictionsLPr(removeUser); 11043 } 11044 } 11045 } 11046 11047 if (removeUser >= 0) { 11048 // From above, we determined that we are deleting this only 11049 // for a single user. Continue the work here. 11050 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11051 if (outInfo != null) { 11052 outInfo.removedPackage = packageName; 11053 outInfo.removedAppId = appId; 11054 outInfo.removedUsers = new int[] {removeUser}; 11055 } 11056 mInstaller.clearUserData(packageName, removeUser); 11057 removeKeystoreDataIfNeeded(removeUser, appId); 11058 schedulePackageCleaning(packageName, removeUser, false); 11059 return true; 11060 } 11061 11062 if (dataOnly) { 11063 // Delete application data first 11064 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11065 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11066 return true; 11067 } 11068 11069 boolean ret = false; 11070 if (isSystemApp(ps)) { 11071 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11072 // When an updated system application is deleted we delete the existing resources as well and 11073 // fall back to existing code in system partition 11074 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11075 flags, outInfo, writeSettings); 11076 } else { 11077 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11078 // Kill application pre-emptively especially for apps on sd. 11079 killApplication(packageName, ps.appId, "uninstall pkg"); 11080 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11081 allUserHandles, perUserInstalled, 11082 outInfo, writeSettings); 11083 } 11084 11085 return ret; 11086 } 11087 11088 private final class ClearStorageConnection implements ServiceConnection { 11089 IMediaContainerService mContainerService; 11090 11091 @Override 11092 public void onServiceConnected(ComponentName name, IBinder service) { 11093 synchronized (this) { 11094 mContainerService = IMediaContainerService.Stub.asInterface(service); 11095 notifyAll(); 11096 } 11097 } 11098 11099 @Override 11100 public void onServiceDisconnected(ComponentName name) { 11101 } 11102 } 11103 11104 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11105 final boolean mounted; 11106 if (Environment.isExternalStorageEmulated()) { 11107 mounted = true; 11108 } else { 11109 final String status = Environment.getExternalStorageState(); 11110 11111 mounted = status.equals(Environment.MEDIA_MOUNTED) 11112 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11113 } 11114 11115 if (!mounted) { 11116 return; 11117 } 11118 11119 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11120 int[] users; 11121 if (userId == UserHandle.USER_ALL) { 11122 users = sUserManager.getUserIds(); 11123 } else { 11124 users = new int[] { userId }; 11125 } 11126 final ClearStorageConnection conn = new ClearStorageConnection(); 11127 if (mContext.bindServiceAsUser( 11128 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11129 try { 11130 for (int curUser : users) { 11131 long timeout = SystemClock.uptimeMillis() + 5000; 11132 synchronized (conn) { 11133 long now = SystemClock.uptimeMillis(); 11134 while (conn.mContainerService == null && now < timeout) { 11135 try { 11136 conn.wait(timeout - now); 11137 } catch (InterruptedException e) { 11138 } 11139 } 11140 } 11141 if (conn.mContainerService == null) { 11142 return; 11143 } 11144 11145 final UserEnvironment userEnv = new UserEnvironment(curUser); 11146 clearDirectory(conn.mContainerService, 11147 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11148 if (allData) { 11149 clearDirectory(conn.mContainerService, 11150 userEnv.buildExternalStorageAppDataDirs(packageName)); 11151 clearDirectory(conn.mContainerService, 11152 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11153 } 11154 } 11155 } finally { 11156 mContext.unbindService(conn); 11157 } 11158 } 11159 } 11160 11161 @Override 11162 public void clearApplicationUserData(final String packageName, 11163 final IPackageDataObserver observer, final int userId) { 11164 mContext.enforceCallingOrSelfPermission( 11165 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11166 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11167 // Queue up an async operation since the package deletion may take a little while. 11168 mHandler.post(new Runnable() { 11169 public void run() { 11170 mHandler.removeCallbacks(this); 11171 final boolean succeeded; 11172 synchronized (mInstallLock) { 11173 succeeded = clearApplicationUserDataLI(packageName, userId); 11174 } 11175 clearExternalStorageDataSync(packageName, userId, true); 11176 if (succeeded) { 11177 // invoke DeviceStorageMonitor's update method to clear any notifications 11178 DeviceStorageMonitorInternal 11179 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11180 if (dsm != null) { 11181 dsm.checkMemory(); 11182 } 11183 } 11184 if(observer != null) { 11185 try { 11186 observer.onRemoveCompleted(packageName, succeeded); 11187 } catch (RemoteException e) { 11188 Log.i(TAG, "Observer no longer exists."); 11189 } 11190 } //end if observer 11191 } //end run 11192 }); 11193 } 11194 11195 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11196 if (packageName == null) { 11197 Slog.w(TAG, "Attempt to delete null packageName."); 11198 return false; 11199 } 11200 PackageParser.Package p; 11201 boolean dataOnly = false; 11202 final int appId; 11203 synchronized (mPackages) { 11204 p = mPackages.get(packageName); 11205 if (p == null) { 11206 dataOnly = true; 11207 PackageSetting ps = mSettings.mPackages.get(packageName); 11208 if ((ps == null) || (ps.pkg == null)) { 11209 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11210 return false; 11211 } 11212 p = ps.pkg; 11213 } 11214 if (!dataOnly) { 11215 // need to check this only for fully installed applications 11216 if (p == null) { 11217 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11218 return false; 11219 } 11220 final ApplicationInfo applicationInfo = p.applicationInfo; 11221 if (applicationInfo == null) { 11222 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11223 return false; 11224 } 11225 } 11226 if (p != null && p.applicationInfo != null) { 11227 appId = p.applicationInfo.uid; 11228 } else { 11229 appId = -1; 11230 } 11231 } 11232 int retCode = mInstaller.clearUserData(packageName, userId); 11233 if (retCode < 0) { 11234 Slog.w(TAG, "Couldn't remove cache files for package: " 11235 + packageName); 11236 return false; 11237 } 11238 removeKeystoreDataIfNeeded(userId, appId); 11239 return true; 11240 } 11241 11242 /** 11243 * Remove entries from the keystore daemon. Will only remove it if the 11244 * {@code appId} is valid. 11245 */ 11246 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11247 if (appId < 0) { 11248 return; 11249 } 11250 11251 final KeyStore keyStore = KeyStore.getInstance(); 11252 if (keyStore != null) { 11253 if (userId == UserHandle.USER_ALL) { 11254 for (final int individual : sUserManager.getUserIds()) { 11255 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11256 } 11257 } else { 11258 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11259 } 11260 } else { 11261 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11262 } 11263 } 11264 11265 @Override 11266 public void deleteApplicationCacheFiles(final String packageName, 11267 final IPackageDataObserver observer) { 11268 mContext.enforceCallingOrSelfPermission( 11269 android.Manifest.permission.DELETE_CACHE_FILES, null); 11270 // Queue up an async operation since the package deletion may take a little while. 11271 final int userId = UserHandle.getCallingUserId(); 11272 mHandler.post(new Runnable() { 11273 public void run() { 11274 mHandler.removeCallbacks(this); 11275 final boolean succeded; 11276 synchronized (mInstallLock) { 11277 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11278 } 11279 clearExternalStorageDataSync(packageName, userId, false); 11280 if(observer != null) { 11281 try { 11282 observer.onRemoveCompleted(packageName, succeded); 11283 } catch (RemoteException e) { 11284 Log.i(TAG, "Observer no longer exists."); 11285 } 11286 } //end if observer 11287 } //end run 11288 }); 11289 } 11290 11291 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11292 if (packageName == null) { 11293 Slog.w(TAG, "Attempt to delete null packageName."); 11294 return false; 11295 } 11296 PackageParser.Package p; 11297 synchronized (mPackages) { 11298 p = mPackages.get(packageName); 11299 } 11300 if (p == null) { 11301 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11302 return false; 11303 } 11304 final ApplicationInfo applicationInfo = p.applicationInfo; 11305 if (applicationInfo == null) { 11306 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11307 return false; 11308 } 11309 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11310 if (retCode < 0) { 11311 Slog.w(TAG, "Couldn't remove cache files for package: " 11312 + packageName + " u" + userId); 11313 return false; 11314 } 11315 return true; 11316 } 11317 11318 @Override 11319 public void getPackageSizeInfo(final String packageName, int userHandle, 11320 final IPackageStatsObserver observer) { 11321 mContext.enforceCallingOrSelfPermission( 11322 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11323 if (packageName == null) { 11324 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11325 } 11326 11327 PackageStats stats = new PackageStats(packageName, userHandle); 11328 11329 /* 11330 * Queue up an async operation since the package measurement may take a 11331 * little while. 11332 */ 11333 Message msg = mHandler.obtainMessage(INIT_COPY); 11334 msg.obj = new MeasureParams(stats, observer); 11335 mHandler.sendMessage(msg); 11336 } 11337 11338 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11339 PackageStats pStats) { 11340 if (packageName == null) { 11341 Slog.w(TAG, "Attempt to get size of null packageName."); 11342 return false; 11343 } 11344 PackageParser.Package p; 11345 boolean dataOnly = false; 11346 String libDirRoot = null; 11347 String asecPath = null; 11348 PackageSetting ps = null; 11349 synchronized (mPackages) { 11350 p = mPackages.get(packageName); 11351 ps = mSettings.mPackages.get(packageName); 11352 if(p == null) { 11353 dataOnly = true; 11354 if((ps == null) || (ps.pkg == null)) { 11355 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11356 return false; 11357 } 11358 p = ps.pkg; 11359 } 11360 if (ps != null) { 11361 libDirRoot = ps.legacyNativeLibraryPathString; 11362 } 11363 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11364 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11365 if (secureContainerId != null) { 11366 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11367 } 11368 } 11369 } 11370 String publicSrcDir = null; 11371 if(!dataOnly) { 11372 final ApplicationInfo applicationInfo = p.applicationInfo; 11373 if (applicationInfo == null) { 11374 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11375 return false; 11376 } 11377 if (isForwardLocked(p)) { 11378 publicSrcDir = applicationInfo.getBaseResourcePath(); 11379 } 11380 } 11381 // TODO: extend to measure size of split APKs 11382 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11383 // not just the first level. 11384 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11385 // just the primary. 11386 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11387 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11388 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11389 if (res < 0) { 11390 return false; 11391 } 11392 11393 // Fix-up for forward-locked applications in ASEC containers. 11394 if (!isExternal(p)) { 11395 pStats.codeSize += pStats.externalCodeSize; 11396 pStats.externalCodeSize = 0L; 11397 } 11398 11399 return true; 11400 } 11401 11402 11403 @Override 11404 public void addPackageToPreferred(String packageName) { 11405 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11406 } 11407 11408 @Override 11409 public void removePackageFromPreferred(String packageName) { 11410 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11411 } 11412 11413 @Override 11414 public List<PackageInfo> getPreferredPackages(int flags) { 11415 return new ArrayList<PackageInfo>(); 11416 } 11417 11418 private int getUidTargetSdkVersionLockedLPr(int uid) { 11419 Object obj = mSettings.getUserIdLPr(uid); 11420 if (obj instanceof SharedUserSetting) { 11421 final SharedUserSetting sus = (SharedUserSetting) obj; 11422 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11423 final Iterator<PackageSetting> it = sus.packages.iterator(); 11424 while (it.hasNext()) { 11425 final PackageSetting ps = it.next(); 11426 if (ps.pkg != null) { 11427 int v = ps.pkg.applicationInfo.targetSdkVersion; 11428 if (v < vers) vers = v; 11429 } 11430 } 11431 return vers; 11432 } else if (obj instanceof PackageSetting) { 11433 final PackageSetting ps = (PackageSetting) obj; 11434 if (ps.pkg != null) { 11435 return ps.pkg.applicationInfo.targetSdkVersion; 11436 } 11437 } 11438 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11439 } 11440 11441 @Override 11442 public void addPreferredActivity(IntentFilter filter, int match, 11443 ComponentName[] set, ComponentName activity, int userId) { 11444 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11445 } 11446 11447 private void addPreferredActivityInternal(IntentFilter filter, int match, 11448 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11449 // writer 11450 int callingUid = Binder.getCallingUid(); 11451 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11452 if (filter.countActions() == 0) { 11453 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11454 return; 11455 } 11456 synchronized (mPackages) { 11457 if (mContext.checkCallingOrSelfPermission( 11458 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11459 != PackageManager.PERMISSION_GRANTED) { 11460 if (getUidTargetSdkVersionLockedLPr(callingUid) 11461 < Build.VERSION_CODES.FROYO) { 11462 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11463 + callingUid); 11464 return; 11465 } 11466 mContext.enforceCallingOrSelfPermission( 11467 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11468 } 11469 11470 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11471 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11472 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11473 new PreferredActivity(filter, match, set, activity, always)); 11474 mSettings.writePackageRestrictionsLPr(userId); 11475 } 11476 } 11477 11478 @Override 11479 public void replacePreferredActivity(IntentFilter filter, int match, 11480 ComponentName[] set, ComponentName activity, int userId) { 11481 if (filter.countActions() != 1) { 11482 throw new IllegalArgumentException( 11483 "replacePreferredActivity expects filter to have only 1 action."); 11484 } 11485 if (filter.countDataAuthorities() != 0 11486 || filter.countDataPaths() != 0 11487 || filter.countDataSchemes() > 1 11488 || filter.countDataTypes() != 0) { 11489 throw new IllegalArgumentException( 11490 "replacePreferredActivity expects filter to have no data authorities, " + 11491 "paths, or types; and at most one scheme."); 11492 } 11493 11494 final int callingUid = Binder.getCallingUid(); 11495 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11496 final int callingUserId = UserHandle.getUserId(callingUid); 11497 synchronized (mPackages) { 11498 if (mContext.checkCallingOrSelfPermission( 11499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11500 != PackageManager.PERMISSION_GRANTED) { 11501 if (getUidTargetSdkVersionLockedLPr(callingUid) 11502 < Build.VERSION_CODES.FROYO) { 11503 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11504 + Binder.getCallingUid()); 11505 return; 11506 } 11507 mContext.enforceCallingOrSelfPermission( 11508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11509 } 11510 11511 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11512 if (pir != null) { 11513 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11514 if (filter.countDataSchemes() == 1) { 11515 Uri.Builder builder = new Uri.Builder(); 11516 builder.scheme(filter.getDataScheme(0)); 11517 intent.setData(builder.build()); 11518 } 11519 List<PreferredActivity> matches = pir.queryIntent( 11520 intent, null, true, callingUserId); 11521 if (DEBUG_PREFERRED) { 11522 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11523 } 11524 for (int i = 0; i < matches.size(); i++) { 11525 PreferredActivity pa = matches.get(i); 11526 if (DEBUG_PREFERRED) { 11527 Slog.i(TAG, "Removing preferred activity " 11528 + pa.mPref.mComponent + ":"); 11529 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11530 } 11531 pir.removeFilter(pa); 11532 } 11533 } 11534 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11535 } 11536 } 11537 11538 @Override 11539 public void clearPackagePreferredActivities(String packageName) { 11540 final int uid = Binder.getCallingUid(); 11541 // writer 11542 synchronized (mPackages) { 11543 PackageParser.Package pkg = mPackages.get(packageName); 11544 if (pkg == null || pkg.applicationInfo.uid != uid) { 11545 if (mContext.checkCallingOrSelfPermission( 11546 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11547 != PackageManager.PERMISSION_GRANTED) { 11548 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11549 < Build.VERSION_CODES.FROYO) { 11550 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11551 + Binder.getCallingUid()); 11552 return; 11553 } 11554 mContext.enforceCallingOrSelfPermission( 11555 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11556 } 11557 } 11558 11559 int user = UserHandle.getCallingUserId(); 11560 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11561 mSettings.writePackageRestrictionsLPr(user); 11562 scheduleWriteSettingsLocked(); 11563 } 11564 } 11565 } 11566 11567 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11568 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11569 ArrayList<PreferredActivity> removed = null; 11570 boolean changed = false; 11571 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11572 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11573 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11574 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11575 continue; 11576 } 11577 Iterator<PreferredActivity> it = pir.filterIterator(); 11578 while (it.hasNext()) { 11579 PreferredActivity pa = it.next(); 11580 // Mark entry for removal only if it matches the package name 11581 // and the entry is of type "always". 11582 if (packageName == null || 11583 (pa.mPref.mComponent.getPackageName().equals(packageName) 11584 && pa.mPref.mAlways)) { 11585 if (removed == null) { 11586 removed = new ArrayList<PreferredActivity>(); 11587 } 11588 removed.add(pa); 11589 } 11590 } 11591 if (removed != null) { 11592 for (int j=0; j<removed.size(); j++) { 11593 PreferredActivity pa = removed.get(j); 11594 pir.removeFilter(pa); 11595 } 11596 changed = true; 11597 } 11598 } 11599 return changed; 11600 } 11601 11602 @Override 11603 public void resetPreferredActivities(int userId) { 11604 mContext.enforceCallingOrSelfPermission( 11605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11606 // writer 11607 synchronized (mPackages) { 11608 int user = UserHandle.getCallingUserId(); 11609 clearPackagePreferredActivitiesLPw(null, user); 11610 mSettings.readDefaultPreferredAppsLPw(this, user); 11611 mSettings.writePackageRestrictionsLPr(user); 11612 scheduleWriteSettingsLocked(); 11613 } 11614 } 11615 11616 @Override 11617 public int getPreferredActivities(List<IntentFilter> outFilters, 11618 List<ComponentName> outActivities, String packageName) { 11619 11620 int num = 0; 11621 final int userId = UserHandle.getCallingUserId(); 11622 // reader 11623 synchronized (mPackages) { 11624 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11625 if (pir != null) { 11626 final Iterator<PreferredActivity> it = pir.filterIterator(); 11627 while (it.hasNext()) { 11628 final PreferredActivity pa = it.next(); 11629 if (packageName == null 11630 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11631 && pa.mPref.mAlways)) { 11632 if (outFilters != null) { 11633 outFilters.add(new IntentFilter(pa)); 11634 } 11635 if (outActivities != null) { 11636 outActivities.add(pa.mPref.mComponent); 11637 } 11638 } 11639 } 11640 } 11641 } 11642 11643 return num; 11644 } 11645 11646 @Override 11647 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11648 int userId) { 11649 int callingUid = Binder.getCallingUid(); 11650 if (callingUid != Process.SYSTEM_UID) { 11651 throw new SecurityException( 11652 "addPersistentPreferredActivity can only be run by the system"); 11653 } 11654 if (filter.countActions() == 0) { 11655 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11656 return; 11657 } 11658 synchronized (mPackages) { 11659 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11660 " :"); 11661 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11662 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11663 new PersistentPreferredActivity(filter, activity)); 11664 mSettings.writePackageRestrictionsLPr(userId); 11665 } 11666 } 11667 11668 @Override 11669 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11670 int callingUid = Binder.getCallingUid(); 11671 if (callingUid != Process.SYSTEM_UID) { 11672 throw new SecurityException( 11673 "clearPackagePersistentPreferredActivities can only be run by the system"); 11674 } 11675 ArrayList<PersistentPreferredActivity> removed = null; 11676 boolean changed = false; 11677 synchronized (mPackages) { 11678 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11679 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11680 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11681 .valueAt(i); 11682 if (userId != thisUserId) { 11683 continue; 11684 } 11685 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11686 while (it.hasNext()) { 11687 PersistentPreferredActivity ppa = it.next(); 11688 // Mark entry for removal only if it matches the package name. 11689 if (ppa.mComponent.getPackageName().equals(packageName)) { 11690 if (removed == null) { 11691 removed = new ArrayList<PersistentPreferredActivity>(); 11692 } 11693 removed.add(ppa); 11694 } 11695 } 11696 if (removed != null) { 11697 for (int j=0; j<removed.size(); j++) { 11698 PersistentPreferredActivity ppa = removed.get(j); 11699 ppir.removeFilter(ppa); 11700 } 11701 changed = true; 11702 } 11703 } 11704 11705 if (changed) { 11706 mSettings.writePackageRestrictionsLPr(userId); 11707 } 11708 } 11709 } 11710 11711 @Override 11712 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11713 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11714 mContext.enforceCallingOrSelfPermission( 11715 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11716 int callingUid = Binder.getCallingUid(); 11717 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11718 if (intentFilter.countActions() == 0) { 11719 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11720 return; 11721 } 11722 synchronized (mPackages) { 11723 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11724 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11725 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11726 mSettings.writePackageRestrictionsLPr(sourceUserId); 11727 } 11728 } 11729 11730 @Override 11731 public void addCrossProfileIntentsForPackage(String packageName, 11732 int sourceUserId, int targetUserId) { 11733 mContext.enforceCallingOrSelfPermission( 11734 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11735 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11736 mSettings.writePackageRestrictionsLPr(sourceUserId); 11737 } 11738 11739 @Override 11740 public void removeCrossProfileIntentsForPackage(String packageName, 11741 int sourceUserId, int targetUserId) { 11742 mContext.enforceCallingOrSelfPermission( 11743 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11744 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11745 mSettings.writePackageRestrictionsLPr(sourceUserId); 11746 } 11747 11748 @Override 11749 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11750 int ownerUserId) { 11751 mContext.enforceCallingOrSelfPermission( 11752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11753 int callingUid = Binder.getCallingUid(); 11754 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11755 int callingUserId = UserHandle.getUserId(callingUid); 11756 synchronized (mPackages) { 11757 CrossProfileIntentResolver resolver = 11758 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11759 HashSet<CrossProfileIntentFilter> set = 11760 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11761 for (CrossProfileIntentFilter filter : set) { 11762 if (filter.getOwnerPackage().equals(ownerPackage) 11763 && filter.getOwnerUserId() == callingUserId) { 11764 resolver.removeFilter(filter); 11765 } 11766 } 11767 mSettings.writePackageRestrictionsLPr(sourceUserId); 11768 } 11769 } 11770 11771 // Enforcing that callingUid is owning pkg on userId 11772 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11773 // The system owns everything. 11774 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11775 return; 11776 } 11777 int callingUserId = UserHandle.getUserId(callingUid); 11778 if (callingUserId != userId) { 11779 throw new SecurityException("calling uid " + callingUid 11780 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11781 + callingUserId); 11782 } 11783 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11784 if (pi == null) { 11785 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11786 + callingUserId); 11787 } 11788 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11789 throw new SecurityException("Calling uid " + callingUid 11790 + " does not own package " + pkg); 11791 } 11792 } 11793 11794 @Override 11795 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11796 Intent intent = new Intent(Intent.ACTION_MAIN); 11797 intent.addCategory(Intent.CATEGORY_HOME); 11798 11799 final int callingUserId = UserHandle.getCallingUserId(); 11800 List<ResolveInfo> list = queryIntentActivities(intent, null, 11801 PackageManager.GET_META_DATA, callingUserId); 11802 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11803 true, false, false, callingUserId); 11804 11805 allHomeCandidates.clear(); 11806 if (list != null) { 11807 for (ResolveInfo ri : list) { 11808 allHomeCandidates.add(ri); 11809 } 11810 } 11811 return (preferred == null || preferred.activityInfo == null) 11812 ? null 11813 : new ComponentName(preferred.activityInfo.packageName, 11814 preferred.activityInfo.name); 11815 } 11816 11817 /** 11818 * Check if calling UID is the current home app. This handles both the case 11819 * where the user has selected a specific home app, and where there is only 11820 * one home app. 11821 */ 11822 public boolean checkCallerIsHomeApp() { 11823 final Intent intent = new Intent(Intent.ACTION_MAIN); 11824 intent.addCategory(Intent.CATEGORY_HOME); 11825 11826 final int callingUid = Binder.getCallingUid(); 11827 final int callingUserId = UserHandle.getCallingUserId(); 11828 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11829 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11830 false, false, callingUserId); 11831 11832 if (preferredHome != null) { 11833 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11834 return true; 11835 } 11836 } else { 11837 for (ResolveInfo info : allHomes) { 11838 if (callingUid == info.activityInfo.applicationInfo.uid) { 11839 return true; 11840 } 11841 } 11842 } 11843 11844 return false; 11845 } 11846 11847 /** 11848 * Enforce that calling UID is the current home app. This handles both the 11849 * case where the user has selected a specific home app, and where there is 11850 * only one home app. 11851 */ 11852 public void enforceCallerIsHomeApp() { 11853 if (!checkCallerIsHomeApp()) { 11854 throw new SecurityException("Caller is not currently selected home app"); 11855 } 11856 } 11857 11858 @Override 11859 public void setApplicationEnabledSetting(String appPackageName, 11860 int newState, int flags, int userId, String callingPackage) { 11861 if (!sUserManager.exists(userId)) return; 11862 if (callingPackage == null) { 11863 callingPackage = Integer.toString(Binder.getCallingUid()); 11864 } 11865 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11866 } 11867 11868 @Override 11869 public void setComponentEnabledSetting(ComponentName componentName, 11870 int newState, int flags, int userId) { 11871 if (!sUserManager.exists(userId)) return; 11872 setEnabledSetting(componentName.getPackageName(), 11873 componentName.getClassName(), newState, flags, userId, null); 11874 } 11875 11876 private void setEnabledSetting(final String packageName, String className, int newState, 11877 final int flags, int userId, String callingPackage) { 11878 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11879 || newState == COMPONENT_ENABLED_STATE_ENABLED 11880 || newState == COMPONENT_ENABLED_STATE_DISABLED 11881 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11882 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11883 throw new IllegalArgumentException("Invalid new component state: " 11884 + newState); 11885 } 11886 PackageSetting pkgSetting; 11887 final int uid = Binder.getCallingUid(); 11888 final int permission = mContext.checkCallingOrSelfPermission( 11889 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11890 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11891 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11892 boolean sendNow = false; 11893 boolean isApp = (className == null); 11894 String componentName = isApp ? packageName : className; 11895 int packageUid = -1; 11896 ArrayList<String> components; 11897 11898 // writer 11899 synchronized (mPackages) { 11900 pkgSetting = mSettings.mPackages.get(packageName); 11901 if (pkgSetting == null) { 11902 if (className == null) { 11903 throw new IllegalArgumentException( 11904 "Unknown package: " + packageName); 11905 } 11906 throw new IllegalArgumentException( 11907 "Unknown component: " + packageName 11908 + "/" + className); 11909 } 11910 // Allow root and verify that userId is not being specified by a different user 11911 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11912 throw new SecurityException( 11913 "Permission Denial: attempt to change component state from pid=" 11914 + Binder.getCallingPid() 11915 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11916 } 11917 if (className == null) { 11918 // We're dealing with an application/package level state change 11919 if (pkgSetting.getEnabled(userId) == newState) { 11920 // Nothing to do 11921 return; 11922 } 11923 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11924 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11925 // Don't care about who enables an app. 11926 callingPackage = null; 11927 } 11928 pkgSetting.setEnabled(newState, userId, callingPackage); 11929 // pkgSetting.pkg.mSetEnabled = newState; 11930 } else { 11931 // We're dealing with a component level state change 11932 // First, verify that this is a valid class name. 11933 PackageParser.Package pkg = pkgSetting.pkg; 11934 if (pkg == null || !pkg.hasComponentClassName(className)) { 11935 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11936 throw new IllegalArgumentException("Component class " + className 11937 + " does not exist in " + packageName); 11938 } else { 11939 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11940 + className + " does not exist in " + packageName); 11941 } 11942 } 11943 switch (newState) { 11944 case COMPONENT_ENABLED_STATE_ENABLED: 11945 if (!pkgSetting.enableComponentLPw(className, userId)) { 11946 return; 11947 } 11948 break; 11949 case COMPONENT_ENABLED_STATE_DISABLED: 11950 if (!pkgSetting.disableComponentLPw(className, userId)) { 11951 return; 11952 } 11953 break; 11954 case COMPONENT_ENABLED_STATE_DEFAULT: 11955 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11956 return; 11957 } 11958 break; 11959 default: 11960 Slog.e(TAG, "Invalid new component state: " + newState); 11961 return; 11962 } 11963 } 11964 mSettings.writePackageRestrictionsLPr(userId); 11965 components = mPendingBroadcasts.get(userId, packageName); 11966 final boolean newPackage = components == null; 11967 if (newPackage) { 11968 components = new ArrayList<String>(); 11969 } 11970 if (!components.contains(componentName)) { 11971 components.add(componentName); 11972 } 11973 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11974 sendNow = true; 11975 // Purge entry from pending broadcast list if another one exists already 11976 // since we are sending one right away. 11977 mPendingBroadcasts.remove(userId, packageName); 11978 } else { 11979 if (newPackage) { 11980 mPendingBroadcasts.put(userId, packageName, components); 11981 } 11982 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11983 // Schedule a message 11984 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11985 } 11986 } 11987 } 11988 11989 long callingId = Binder.clearCallingIdentity(); 11990 try { 11991 if (sendNow) { 11992 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11993 sendPackageChangedBroadcast(packageName, 11994 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11995 } 11996 } finally { 11997 Binder.restoreCallingIdentity(callingId); 11998 } 11999 } 12000 12001 private void sendPackageChangedBroadcast(String packageName, 12002 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12003 if (DEBUG_INSTALL) 12004 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12005 + componentNames); 12006 Bundle extras = new Bundle(4); 12007 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12008 String nameList[] = new String[componentNames.size()]; 12009 componentNames.toArray(nameList); 12010 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12011 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12012 extras.putInt(Intent.EXTRA_UID, packageUid); 12013 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12014 new int[] {UserHandle.getUserId(packageUid)}); 12015 } 12016 12017 @Override 12018 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12019 if (!sUserManager.exists(userId)) return; 12020 final int uid = Binder.getCallingUid(); 12021 final int permission = mContext.checkCallingOrSelfPermission( 12022 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12023 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12024 enforceCrossUserPermission(uid, userId, true, "stop package"); 12025 // writer 12026 synchronized (mPackages) { 12027 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12028 uid, userId)) { 12029 scheduleWritePackageRestrictionsLocked(userId); 12030 } 12031 } 12032 } 12033 12034 @Override 12035 public String getInstallerPackageName(String packageName) { 12036 // reader 12037 synchronized (mPackages) { 12038 return mSettings.getInstallerPackageNameLPr(packageName); 12039 } 12040 } 12041 12042 @Override 12043 public int getApplicationEnabledSetting(String packageName, int userId) { 12044 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12045 int uid = Binder.getCallingUid(); 12046 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12047 // reader 12048 synchronized (mPackages) { 12049 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12050 } 12051 } 12052 12053 @Override 12054 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12055 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12056 int uid = Binder.getCallingUid(); 12057 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12058 // reader 12059 synchronized (mPackages) { 12060 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12061 } 12062 } 12063 12064 @Override 12065 public void enterSafeMode() { 12066 enforceSystemOrRoot("Only the system can request entering safe mode"); 12067 12068 if (!mSystemReady) { 12069 mSafeMode = true; 12070 } 12071 } 12072 12073 @Override 12074 public void systemReady() { 12075 mSystemReady = true; 12076 12077 // Read the compatibilty setting when the system is ready. 12078 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12079 mContext.getContentResolver(), 12080 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12081 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12082 if (DEBUG_SETTINGS) { 12083 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12084 } 12085 12086 synchronized (mPackages) { 12087 // Verify that all of the preferred activity components actually 12088 // exist. It is possible for applications to be updated and at 12089 // that point remove a previously declared activity component that 12090 // had been set as a preferred activity. We try to clean this up 12091 // the next time we encounter that preferred activity, but it is 12092 // possible for the user flow to never be able to return to that 12093 // situation so here we do a sanity check to make sure we haven't 12094 // left any junk around. 12095 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12096 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12097 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12098 removed.clear(); 12099 for (PreferredActivity pa : pir.filterSet()) { 12100 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12101 removed.add(pa); 12102 } 12103 } 12104 if (removed.size() > 0) { 12105 for (int r=0; r<removed.size(); r++) { 12106 PreferredActivity pa = removed.get(r); 12107 Slog.w(TAG, "Removing dangling preferred activity: " 12108 + pa.mPref.mComponent); 12109 pir.removeFilter(pa); 12110 } 12111 mSettings.writePackageRestrictionsLPr( 12112 mSettings.mPreferredActivities.keyAt(i)); 12113 } 12114 } 12115 } 12116 sUserManager.systemReady(); 12117 } 12118 12119 @Override 12120 public boolean isSafeMode() { 12121 return mSafeMode; 12122 } 12123 12124 @Override 12125 public boolean hasSystemUidErrors() { 12126 return mHasSystemUidErrors; 12127 } 12128 12129 static String arrayToString(int[] array) { 12130 StringBuffer buf = new StringBuffer(128); 12131 buf.append('['); 12132 if (array != null) { 12133 for (int i=0; i<array.length; i++) { 12134 if (i > 0) buf.append(", "); 12135 buf.append(array[i]); 12136 } 12137 } 12138 buf.append(']'); 12139 return buf.toString(); 12140 } 12141 12142 static class DumpState { 12143 public static final int DUMP_LIBS = 1 << 0; 12144 public static final int DUMP_FEATURES = 1 << 1; 12145 public static final int DUMP_RESOLVERS = 1 << 2; 12146 public static final int DUMP_PERMISSIONS = 1 << 3; 12147 public static final int DUMP_PACKAGES = 1 << 4; 12148 public static final int DUMP_SHARED_USERS = 1 << 5; 12149 public static final int DUMP_MESSAGES = 1 << 6; 12150 public static final int DUMP_PROVIDERS = 1 << 7; 12151 public static final int DUMP_VERIFIERS = 1 << 8; 12152 public static final int DUMP_PREFERRED = 1 << 9; 12153 public static final int DUMP_PREFERRED_XML = 1 << 10; 12154 public static final int DUMP_KEYSETS = 1 << 11; 12155 public static final int DUMP_VERSION = 1 << 12; 12156 public static final int DUMP_INSTALLS = 1 << 13; 12157 12158 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12159 12160 private int mTypes; 12161 12162 private int mOptions; 12163 12164 private boolean mTitlePrinted; 12165 12166 private SharedUserSetting mSharedUser; 12167 12168 public boolean isDumping(int type) { 12169 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12170 return true; 12171 } 12172 12173 return (mTypes & type) != 0; 12174 } 12175 12176 public void setDump(int type) { 12177 mTypes |= type; 12178 } 12179 12180 public boolean isOptionEnabled(int option) { 12181 return (mOptions & option) != 0; 12182 } 12183 12184 public void setOptionEnabled(int option) { 12185 mOptions |= option; 12186 } 12187 12188 public boolean onTitlePrinted() { 12189 final boolean printed = mTitlePrinted; 12190 mTitlePrinted = true; 12191 return printed; 12192 } 12193 12194 public boolean getTitlePrinted() { 12195 return mTitlePrinted; 12196 } 12197 12198 public void setTitlePrinted(boolean enabled) { 12199 mTitlePrinted = enabled; 12200 } 12201 12202 public SharedUserSetting getSharedUser() { 12203 return mSharedUser; 12204 } 12205 12206 public void setSharedUser(SharedUserSetting user) { 12207 mSharedUser = user; 12208 } 12209 } 12210 12211 @Override 12212 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12213 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12214 != PackageManager.PERMISSION_GRANTED) { 12215 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12216 + Binder.getCallingPid() 12217 + ", uid=" + Binder.getCallingUid() 12218 + " without permission " 12219 + android.Manifest.permission.DUMP); 12220 return; 12221 } 12222 12223 DumpState dumpState = new DumpState(); 12224 boolean fullPreferred = false; 12225 boolean checkin = false; 12226 12227 String packageName = null; 12228 12229 int opti = 0; 12230 while (opti < args.length) { 12231 String opt = args[opti]; 12232 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12233 break; 12234 } 12235 opti++; 12236 if ("-a".equals(opt)) { 12237 // Right now we only know how to print all. 12238 } else if ("-h".equals(opt)) { 12239 pw.println("Package manager dump options:"); 12240 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12241 pw.println(" --checkin: dump for a checkin"); 12242 pw.println(" -f: print details of intent filters"); 12243 pw.println(" -h: print this help"); 12244 pw.println(" cmd may be one of:"); 12245 pw.println(" l[ibraries]: list known shared libraries"); 12246 pw.println(" f[ibraries]: list device features"); 12247 pw.println(" k[eysets]: print known keysets"); 12248 pw.println(" r[esolvers]: dump intent resolvers"); 12249 pw.println(" perm[issions]: dump permissions"); 12250 pw.println(" pref[erred]: print preferred package settings"); 12251 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12252 pw.println(" prov[iders]: dump content providers"); 12253 pw.println(" p[ackages]: dump installed packages"); 12254 pw.println(" s[hared-users]: dump shared user IDs"); 12255 pw.println(" m[essages]: print collected runtime messages"); 12256 pw.println(" v[erifiers]: print package verifier info"); 12257 pw.println(" version: print database version info"); 12258 pw.println(" write: write current settings now"); 12259 pw.println(" <package.name>: info about given package"); 12260 pw.println(" installs: details about install sessions"); 12261 return; 12262 } else if ("--checkin".equals(opt)) { 12263 checkin = true; 12264 } else if ("-f".equals(opt)) { 12265 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12266 } else { 12267 pw.println("Unknown argument: " + opt + "; use -h for help"); 12268 } 12269 } 12270 12271 // Is the caller requesting to dump a particular piece of data? 12272 if (opti < args.length) { 12273 String cmd = args[opti]; 12274 opti++; 12275 // Is this a package name? 12276 if ("android".equals(cmd) || cmd.contains(".")) { 12277 packageName = cmd; 12278 // When dumping a single package, we always dump all of its 12279 // filter information since the amount of data will be reasonable. 12280 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12281 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12282 dumpState.setDump(DumpState.DUMP_LIBS); 12283 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12284 dumpState.setDump(DumpState.DUMP_FEATURES); 12285 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12286 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12287 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12288 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12289 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12290 dumpState.setDump(DumpState.DUMP_PREFERRED); 12291 } else if ("preferred-xml".equals(cmd)) { 12292 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12293 if (opti < args.length && "--full".equals(args[opti])) { 12294 fullPreferred = true; 12295 opti++; 12296 } 12297 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12298 dumpState.setDump(DumpState.DUMP_PACKAGES); 12299 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12300 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12301 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12302 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12303 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12304 dumpState.setDump(DumpState.DUMP_MESSAGES); 12305 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12306 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12307 } else if ("version".equals(cmd)) { 12308 dumpState.setDump(DumpState.DUMP_VERSION); 12309 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12310 dumpState.setDump(DumpState.DUMP_KEYSETS); 12311 } else if ("write".equals(cmd)) { 12312 synchronized (mPackages) { 12313 mSettings.writeLPr(); 12314 pw.println("Settings written."); 12315 return; 12316 } 12317 } else if ("installs".equals(cmd)) { 12318 dumpState.setDump(DumpState.DUMP_INSTALLS); 12319 } 12320 } 12321 12322 if (checkin) { 12323 pw.println("vers,1"); 12324 } 12325 12326 // reader 12327 synchronized (mPackages) { 12328 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12329 if (!checkin) { 12330 if (dumpState.onTitlePrinted()) 12331 pw.println(); 12332 pw.println("Database versions:"); 12333 pw.print(" SDK Version:"); 12334 pw.print(" internal="); 12335 pw.print(mSettings.mInternalSdkPlatform); 12336 pw.print(" external="); 12337 pw.println(mSettings.mExternalSdkPlatform); 12338 pw.print(" DB Version:"); 12339 pw.print(" internal="); 12340 pw.print(mSettings.mInternalDatabaseVersion); 12341 pw.print(" external="); 12342 pw.println(mSettings.mExternalDatabaseVersion); 12343 } 12344 } 12345 12346 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12347 if (!checkin) { 12348 if (dumpState.onTitlePrinted()) 12349 pw.println(); 12350 pw.println("Verifiers:"); 12351 pw.print(" Required: "); 12352 pw.print(mRequiredVerifierPackage); 12353 pw.print(" (uid="); 12354 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12355 pw.println(")"); 12356 } else if (mRequiredVerifierPackage != null) { 12357 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12358 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12359 } 12360 } 12361 12362 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12363 boolean printedHeader = false; 12364 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12365 while (it.hasNext()) { 12366 String name = it.next(); 12367 SharedLibraryEntry ent = mSharedLibraries.get(name); 12368 if (!checkin) { 12369 if (!printedHeader) { 12370 if (dumpState.onTitlePrinted()) 12371 pw.println(); 12372 pw.println("Libraries:"); 12373 printedHeader = true; 12374 } 12375 pw.print(" "); 12376 } else { 12377 pw.print("lib,"); 12378 } 12379 pw.print(name); 12380 if (!checkin) { 12381 pw.print(" -> "); 12382 } 12383 if (ent.path != null) { 12384 if (!checkin) { 12385 pw.print("(jar) "); 12386 pw.print(ent.path); 12387 } else { 12388 pw.print(",jar,"); 12389 pw.print(ent.path); 12390 } 12391 } else { 12392 if (!checkin) { 12393 pw.print("(apk) "); 12394 pw.print(ent.apk); 12395 } else { 12396 pw.print(",apk,"); 12397 pw.print(ent.apk); 12398 } 12399 } 12400 pw.println(); 12401 } 12402 } 12403 12404 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12405 if (dumpState.onTitlePrinted()) 12406 pw.println(); 12407 if (!checkin) { 12408 pw.println("Features:"); 12409 } 12410 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12411 while (it.hasNext()) { 12412 String name = it.next(); 12413 if (!checkin) { 12414 pw.print(" "); 12415 } else { 12416 pw.print("feat,"); 12417 } 12418 pw.println(name); 12419 } 12420 } 12421 12422 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12423 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12424 : "Activity Resolver Table:", " ", packageName, 12425 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12426 dumpState.setTitlePrinted(true); 12427 } 12428 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12429 : "Receiver Resolver Table:", " ", packageName, 12430 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12431 dumpState.setTitlePrinted(true); 12432 } 12433 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12434 : "Service Resolver Table:", " ", packageName, 12435 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12436 dumpState.setTitlePrinted(true); 12437 } 12438 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12439 : "Provider Resolver Table:", " ", packageName, 12440 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12441 dumpState.setTitlePrinted(true); 12442 } 12443 } 12444 12445 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12446 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12447 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12448 int user = mSettings.mPreferredActivities.keyAt(i); 12449 if (pir.dump(pw, 12450 dumpState.getTitlePrinted() 12451 ? "\nPreferred Activities User " + user + ":" 12452 : "Preferred Activities User " + user + ":", " ", 12453 packageName, true)) { 12454 dumpState.setTitlePrinted(true); 12455 } 12456 } 12457 } 12458 12459 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12460 pw.flush(); 12461 FileOutputStream fout = new FileOutputStream(fd); 12462 BufferedOutputStream str = new BufferedOutputStream(fout); 12463 XmlSerializer serializer = new FastXmlSerializer(); 12464 try { 12465 serializer.setOutput(str, "utf-8"); 12466 serializer.startDocument(null, true); 12467 serializer.setFeature( 12468 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12469 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12470 serializer.endDocument(); 12471 serializer.flush(); 12472 } catch (IllegalArgumentException e) { 12473 pw.println("Failed writing: " + e); 12474 } catch (IllegalStateException e) { 12475 pw.println("Failed writing: " + e); 12476 } catch (IOException e) { 12477 pw.println("Failed writing: " + e); 12478 } 12479 } 12480 12481 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12482 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12483 if (packageName == null) { 12484 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12485 if (iperm == 0) { 12486 if (dumpState.onTitlePrinted()) 12487 pw.println(); 12488 pw.println("AppOp Permissions:"); 12489 } 12490 pw.print(" AppOp Permission "); 12491 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12492 pw.println(":"); 12493 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12494 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12495 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12496 } 12497 } 12498 } 12499 } 12500 12501 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12502 boolean printedSomething = false; 12503 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12504 if (packageName != null && !packageName.equals(p.info.packageName)) { 12505 continue; 12506 } 12507 if (!printedSomething) { 12508 if (dumpState.onTitlePrinted()) 12509 pw.println(); 12510 pw.println("Registered ContentProviders:"); 12511 printedSomething = true; 12512 } 12513 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12514 pw.print(" "); pw.println(p.toString()); 12515 } 12516 printedSomething = false; 12517 for (Map.Entry<String, PackageParser.Provider> entry : 12518 mProvidersByAuthority.entrySet()) { 12519 PackageParser.Provider p = entry.getValue(); 12520 if (packageName != null && !packageName.equals(p.info.packageName)) { 12521 continue; 12522 } 12523 if (!printedSomething) { 12524 if (dumpState.onTitlePrinted()) 12525 pw.println(); 12526 pw.println("ContentProvider Authorities:"); 12527 printedSomething = true; 12528 } 12529 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12530 pw.print(" "); pw.println(p.toString()); 12531 if (p.info != null && p.info.applicationInfo != null) { 12532 final String appInfo = p.info.applicationInfo.toString(); 12533 pw.print(" applicationInfo="); pw.println(appInfo); 12534 } 12535 } 12536 } 12537 12538 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12539 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12540 } 12541 12542 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12543 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12544 } 12545 12546 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12547 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12548 } 12549 12550 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12551 if (dumpState.onTitlePrinted()) pw.println(); 12552 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12553 } 12554 12555 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12556 if (dumpState.onTitlePrinted()) pw.println(); 12557 mSettings.dumpReadMessagesLPr(pw, dumpState); 12558 12559 pw.println(); 12560 pw.println("Package warning messages:"); 12561 final File fname = getSettingsProblemFile(); 12562 FileInputStream in = null; 12563 try { 12564 in = new FileInputStream(fname); 12565 final int avail = in.available(); 12566 final byte[] data = new byte[avail]; 12567 in.read(data); 12568 pw.print(new String(data)); 12569 } catch (FileNotFoundException e) { 12570 } catch (IOException e) { 12571 } finally { 12572 if (in != null) { 12573 try { 12574 in.close(); 12575 } catch (IOException e) { 12576 } 12577 } 12578 } 12579 } 12580 } 12581 } 12582 12583 // ------- apps on sdcard specific code ------- 12584 static final boolean DEBUG_SD_INSTALL = false; 12585 12586 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12587 12588 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12589 12590 private boolean mMediaMounted = false; 12591 12592 private String getEncryptKey() { 12593 try { 12594 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12595 SD_ENCRYPTION_KEYSTORE_NAME); 12596 if (sdEncKey == null) { 12597 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12598 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12599 if (sdEncKey == null) { 12600 Slog.e(TAG, "Failed to create encryption keys"); 12601 return null; 12602 } 12603 } 12604 return sdEncKey; 12605 } catch (NoSuchAlgorithmException nsae) { 12606 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12607 return null; 12608 } catch (IOException ioe) { 12609 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12610 return null; 12611 } 12612 12613 } 12614 12615 /* package */static String getTempContainerId() { 12616 int tmpIdx = 1; 12617 String list[] = PackageHelper.getSecureContainerList(); 12618 if (list != null) { 12619 for (final String name : list) { 12620 // Ignore null and non-temporary container entries 12621 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12622 continue; 12623 } 12624 12625 String subStr = name.substring(mTempContainerPrefix.length()); 12626 try { 12627 int cid = Integer.parseInt(subStr); 12628 if (cid >= tmpIdx) { 12629 tmpIdx = cid + 1; 12630 } 12631 } catch (NumberFormatException e) { 12632 } 12633 } 12634 } 12635 return mTempContainerPrefix + tmpIdx; 12636 } 12637 12638 /* 12639 * Update media status on PackageManager. 12640 */ 12641 @Override 12642 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12643 int callingUid = Binder.getCallingUid(); 12644 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12645 throw new SecurityException("Media status can only be updated by the system"); 12646 } 12647 // reader; this apparently protects mMediaMounted, but should probably 12648 // be a different lock in that case. 12649 synchronized (mPackages) { 12650 Log.i(TAG, "Updating external media status from " 12651 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12652 + (mediaStatus ? "mounted" : "unmounted")); 12653 if (DEBUG_SD_INSTALL) 12654 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12655 + ", mMediaMounted=" + mMediaMounted); 12656 if (mediaStatus == mMediaMounted) { 12657 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12658 : 0, -1); 12659 mHandler.sendMessage(msg); 12660 return; 12661 } 12662 mMediaMounted = mediaStatus; 12663 } 12664 // Queue up an async operation since the package installation may take a 12665 // little while. 12666 mHandler.post(new Runnable() { 12667 public void run() { 12668 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12669 } 12670 }); 12671 } 12672 12673 /** 12674 * Called by MountService when the initial ASECs to scan are available. 12675 * Should block until all the ASEC containers are finished being scanned. 12676 */ 12677 public void scanAvailableAsecs() { 12678 updateExternalMediaStatusInner(true, false, false); 12679 if (mShouldRestoreconData) { 12680 SELinuxMMAC.setRestoreconDone(); 12681 mShouldRestoreconData = false; 12682 } 12683 } 12684 12685 /* 12686 * Collect information of applications on external media, map them against 12687 * existing containers and update information based on current mount status. 12688 * Please note that we always have to report status if reportStatus has been 12689 * set to true especially when unloading packages. 12690 */ 12691 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12692 boolean externalStorage) { 12693 // Collection of uids 12694 int uidArr[] = null; 12695 // Collection of stale containers 12696 HashSet<String> removeCids = new HashSet<String>(); 12697 // Collection of packages on external media with valid containers. 12698 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12699 // Get list of secure containers. 12700 final String list[] = PackageHelper.getSecureContainerList(); 12701 if (list == null || list.length == 0) { 12702 Log.i(TAG, "No secure containers on sdcard"); 12703 } else { 12704 // Process list of secure containers and categorize them 12705 // as active or stale based on their package internal state. 12706 int uidList[] = new int[list.length]; 12707 int num = 0; 12708 // reader 12709 synchronized (mPackages) { 12710 for (String cid : list) { 12711 if (DEBUG_SD_INSTALL) 12712 Log.i(TAG, "Processing container " + cid); 12713 String pkgName = getAsecPackageName(cid); 12714 if (pkgName == null) { 12715 if (DEBUG_SD_INSTALL) 12716 Log.i(TAG, "Container : " + cid + " stale"); 12717 removeCids.add(cid); 12718 continue; 12719 } 12720 if (DEBUG_SD_INSTALL) 12721 Log.i(TAG, "Looking for pkg : " + pkgName); 12722 12723 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12724 if (ps == null) { 12725 Log.i(TAG, "Deleting container with no matching settings " + cid); 12726 removeCids.add(cid); 12727 continue; 12728 } 12729 12730 /* 12731 * Skip packages that are not external if we're unmounting 12732 * external storage. 12733 */ 12734 if (externalStorage && !isMounted && !isExternal(ps)) { 12735 continue; 12736 } 12737 12738 final AsecInstallArgs args = new AsecInstallArgs(cid, 12739 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12740 // The package status is changed only if the code path 12741 // matches between settings and the container id. 12742 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12743 if (DEBUG_SD_INSTALL) { 12744 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12745 + " at code path: " + ps.codePathString); 12746 } 12747 12748 // We do have a valid package installed on sdcard 12749 processCids.put(args, ps.codePathString); 12750 final int uid = ps.appId; 12751 if (uid != -1) { 12752 uidList[num++] = uid; 12753 } 12754 } else { 12755 Log.i(TAG, "Deleting stale container for " + cid); 12756 removeCids.add(cid); 12757 } 12758 } 12759 } 12760 12761 if (num > 0) { 12762 // Sort uid list 12763 Arrays.sort(uidList, 0, num); 12764 // Throw away duplicates 12765 uidArr = new int[num]; 12766 uidArr[0] = uidList[0]; 12767 int di = 0; 12768 for (int i = 1; i < num; i++) { 12769 if (uidList[i - 1] != uidList[i]) { 12770 uidArr[di++] = uidList[i]; 12771 } 12772 } 12773 } 12774 } 12775 // Process packages with valid entries. 12776 if (isMounted) { 12777 if (DEBUG_SD_INSTALL) 12778 Log.i(TAG, "Loading packages"); 12779 loadMediaPackages(processCids, uidArr, removeCids); 12780 startCleaningPackages(); 12781 } else { 12782 if (DEBUG_SD_INSTALL) 12783 Log.i(TAG, "Unloading packages"); 12784 unloadMediaPackages(processCids, uidArr, reportStatus); 12785 } 12786 } 12787 12788 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12789 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12790 int size = pkgList.size(); 12791 if (size > 0) { 12792 // Send broadcasts here 12793 Bundle extras = new Bundle(); 12794 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12795 .toArray(new String[size])); 12796 if (uidArr != null) { 12797 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12798 } 12799 if (replacing) { 12800 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12801 } 12802 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12803 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12804 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12805 } 12806 } 12807 12808 /* 12809 * Look at potentially valid container ids from processCids If package 12810 * information doesn't match the one on record or package scanning fails, 12811 * the cid is added to list of removeCids. We currently don't delete stale 12812 * containers. 12813 */ 12814 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12815 HashSet<String> removeCids) { 12816 ArrayList<String> pkgList = new ArrayList<String>(); 12817 Set<AsecInstallArgs> keys = processCids.keySet(); 12818 boolean doGc = false; 12819 for (AsecInstallArgs args : keys) { 12820 String codePath = processCids.get(args); 12821 if (DEBUG_SD_INSTALL) 12822 Log.i(TAG, "Loading container : " + args.cid); 12823 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12824 try { 12825 // Make sure there are no container errors first. 12826 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12827 Slog.e(TAG, "Failed to mount cid : " + args.cid 12828 + " when installing from sdcard"); 12829 continue; 12830 } 12831 // Check code path here. 12832 if (codePath == null || !codePath.equals(args.getCodePath())) { 12833 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12834 + " does not match one in settings " + codePath); 12835 continue; 12836 } 12837 // Parse package 12838 int parseFlags = mDefParseFlags; 12839 if (args.isExternal()) { 12840 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12841 } 12842 if (args.isFwdLocked()) { 12843 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12844 } 12845 12846 doGc = true; 12847 synchronized (mInstallLock) { 12848 PackageParser.Package pkg = null; 12849 try { 12850 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12851 } catch (PackageManagerException e) { 12852 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12853 } 12854 // Scan the package 12855 if (pkg != null) { 12856 /* 12857 * TODO why is the lock being held? doPostInstall is 12858 * called in other places without the lock. This needs 12859 * to be straightened out. 12860 */ 12861 // writer 12862 synchronized (mPackages) { 12863 retCode = PackageManager.INSTALL_SUCCEEDED; 12864 pkgList.add(pkg.packageName); 12865 // Post process args 12866 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12867 pkg.applicationInfo.uid); 12868 } 12869 } else { 12870 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12871 } 12872 } 12873 12874 } finally { 12875 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12876 // Don't destroy container here. Wait till gc clears things 12877 // up. 12878 removeCids.add(args.cid); 12879 } 12880 } 12881 } 12882 // writer 12883 synchronized (mPackages) { 12884 // If the platform SDK has changed since the last time we booted, 12885 // we need to re-grant app permission to catch any new ones that 12886 // appear. This is really a hack, and means that apps can in some 12887 // cases get permissions that the user didn't initially explicitly 12888 // allow... it would be nice to have some better way to handle 12889 // this situation. 12890 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12891 if (regrantPermissions) 12892 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12893 + mSdkVersion + "; regranting permissions for external storage"); 12894 mSettings.mExternalSdkPlatform = mSdkVersion; 12895 12896 // Make sure group IDs have been assigned, and any permission 12897 // changes in other apps are accounted for 12898 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12899 | (regrantPermissions 12900 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12901 : 0)); 12902 12903 mSettings.updateExternalDatabaseVersion(); 12904 12905 // can downgrade to reader 12906 // Persist settings 12907 mSettings.writeLPr(); 12908 } 12909 // Send a broadcast to let everyone know we are done processing 12910 if (pkgList.size() > 0) { 12911 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12912 } 12913 // Force gc to avoid any stale parser references that we might have. 12914 if (doGc) { 12915 Runtime.getRuntime().gc(); 12916 } 12917 // List stale containers and destroy stale temporary containers. 12918 if (removeCids != null) { 12919 for (String cid : removeCids) { 12920 if (cid.startsWith(mTempContainerPrefix)) { 12921 Log.i(TAG, "Destroying stale temporary container " + cid); 12922 PackageHelper.destroySdDir(cid); 12923 } else { 12924 Log.w(TAG, "Container " + cid + " is stale"); 12925 } 12926 } 12927 } 12928 } 12929 12930 /* 12931 * Utility method to unload a list of specified containers 12932 */ 12933 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12934 // Just unmount all valid containers. 12935 for (AsecInstallArgs arg : cidArgs) { 12936 synchronized (mInstallLock) { 12937 arg.doPostDeleteLI(false); 12938 } 12939 } 12940 } 12941 12942 /* 12943 * Unload packages mounted on external media. This involves deleting package 12944 * data from internal structures, sending broadcasts about diabled packages, 12945 * gc'ing to free up references, unmounting all secure containers 12946 * corresponding to packages on external media, and posting a 12947 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12948 * that we always have to post this message if status has been requested no 12949 * matter what. 12950 */ 12951 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12952 final boolean reportStatus) { 12953 if (DEBUG_SD_INSTALL) 12954 Log.i(TAG, "unloading media packages"); 12955 ArrayList<String> pkgList = new ArrayList<String>(); 12956 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12957 final Set<AsecInstallArgs> keys = processCids.keySet(); 12958 for (AsecInstallArgs args : keys) { 12959 String pkgName = args.getPackageName(); 12960 if (DEBUG_SD_INSTALL) 12961 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12962 // Delete package internally 12963 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12964 synchronized (mInstallLock) { 12965 boolean res = deletePackageLI(pkgName, null, false, null, null, 12966 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12967 if (res) { 12968 pkgList.add(pkgName); 12969 } else { 12970 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12971 failedList.add(args); 12972 } 12973 } 12974 } 12975 12976 // reader 12977 synchronized (mPackages) { 12978 // We didn't update the settings after removing each package; 12979 // write them now for all packages. 12980 mSettings.writeLPr(); 12981 } 12982 12983 // We have to absolutely send UPDATED_MEDIA_STATUS only 12984 // after confirming that all the receivers processed the ordered 12985 // broadcast when packages get disabled, force a gc to clean things up. 12986 // and unload all the containers. 12987 if (pkgList.size() > 0) { 12988 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12989 new IIntentReceiver.Stub() { 12990 public void performReceive(Intent intent, int resultCode, String data, 12991 Bundle extras, boolean ordered, boolean sticky, 12992 int sendingUser) throws RemoteException { 12993 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12994 reportStatus ? 1 : 0, 1, keys); 12995 mHandler.sendMessage(msg); 12996 } 12997 }); 12998 } else { 12999 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13000 keys); 13001 mHandler.sendMessage(msg); 13002 } 13003 } 13004 13005 /** Binder call */ 13006 @Override 13007 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13008 final int flags) { 13009 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13010 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13011 int returnCode = PackageManager.MOVE_SUCCEEDED; 13012 int currFlags = 0; 13013 int newFlags = 0; 13014 // reader 13015 synchronized (mPackages) { 13016 PackageParser.Package pkg = mPackages.get(packageName); 13017 if (pkg == null) { 13018 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13019 } else { 13020 // Disable moving fwd locked apps and system packages 13021 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13022 Slog.w(TAG, "Cannot move system application"); 13023 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13024 } else if (pkg.mOperationPending) { 13025 Slog.w(TAG, "Attempt to move package which has pending operations"); 13026 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13027 } else { 13028 // Find install location first 13029 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13030 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13031 Slog.w(TAG, "Ambigous flags specified for move location."); 13032 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13033 } else { 13034 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13035 : PackageManager.INSTALL_INTERNAL; 13036 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13037 : PackageManager.INSTALL_INTERNAL; 13038 13039 if (newFlags == currFlags) { 13040 Slog.w(TAG, "No move required. Trying to move to same location"); 13041 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13042 } else { 13043 if (isForwardLocked(pkg)) { 13044 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13045 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13046 } 13047 } 13048 } 13049 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13050 pkg.mOperationPending = true; 13051 } 13052 } 13053 } 13054 13055 /* 13056 * TODO this next block probably shouldn't be inside the lock. We 13057 * can't guarantee these won't change after this is fired off 13058 * anyway. 13059 */ 13060 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13061 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13062 returnCode); 13063 } else { 13064 Message msg = mHandler.obtainMessage(INIT_COPY); 13065 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13066 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13067 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13068 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13069 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13070 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13071 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13072 msg.obj = mp; 13073 mHandler.sendMessage(msg); 13074 } 13075 } 13076 } 13077 13078 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13079 // Queue up an async operation since the package deletion may take a 13080 // little while. 13081 mHandler.post(new Runnable() { 13082 public void run() { 13083 // TODO fix this; this does nothing. 13084 mHandler.removeCallbacks(this); 13085 int returnCode = currentStatus; 13086 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13087 int uidArr[] = null; 13088 ArrayList<String> pkgList = null; 13089 synchronized (mPackages) { 13090 PackageParser.Package pkg = mPackages.get(mp.packageName); 13091 if (pkg == null) { 13092 Slog.w(TAG, " Package " + mp.packageName 13093 + " doesn't exist. Aborting move"); 13094 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13095 } else if (!mp.srcArgs.getCodePath().equals( 13096 pkg.applicationInfo.getCodePath())) { 13097 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13098 + mp.srcArgs.getCodePath() + " to " 13099 + pkg.applicationInfo.getCodePath() 13100 + " Aborting move and returning error"); 13101 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13102 } else { 13103 uidArr = new int[] { 13104 pkg.applicationInfo.uid 13105 }; 13106 pkgList = new ArrayList<String>(); 13107 pkgList.add(mp.packageName); 13108 } 13109 } 13110 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13111 // Send resources unavailable broadcast 13112 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13113 // Update package code and resource paths 13114 synchronized (mInstallLock) { 13115 synchronized (mPackages) { 13116 PackageParser.Package pkg = mPackages.get(mp.packageName); 13117 // Recheck for package again. 13118 if (pkg == null) { 13119 Slog.w(TAG, " Package " + mp.packageName 13120 + " doesn't exist. Aborting move"); 13121 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13122 } else if (!mp.srcArgs.getCodePath().equals( 13123 pkg.applicationInfo.getCodePath())) { 13124 Slog.w(TAG, "Package " + mp.packageName 13125 + " code path changed from " + mp.srcArgs.getCodePath() 13126 + " to " + pkg.applicationInfo.getCodePath() 13127 + " Aborting move and returning error"); 13128 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13129 } else { 13130 final String oldCodePath = pkg.codePath; 13131 final String newCodePath = mp.targetArgs.getCodePath(); 13132 final String newResPath = mp.targetArgs.getResourcePath(); 13133 // TODO: This assumes the new style of installation. 13134 // should we look at legacyNativeLibraryPath ? 13135 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13136 final File newNativeDir = new File(newNativeRoot); 13137 13138 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13139 // TODO(multiArch): Fix this so that it looks at the existing 13140 // recorded CPU abis from the package. There's no need for a separate 13141 // round of ABI scanning here. 13142 NativeLibraryHelper.Handle handle = null; 13143 try { 13144 handle = NativeLibraryHelper.Handle.create( 13145 new File(newCodePath)); 13146 final int abi = NativeLibraryHelper.findSupportedAbi( 13147 handle, Build.SUPPORTED_ABIS); 13148 if (abi >= 0) { 13149 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13150 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13151 } 13152 } catch (IOException ioe) { 13153 Slog.w(TAG, "Unable to extract native libs for package :" 13154 + mp.packageName, ioe); 13155 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13156 } finally { 13157 IoUtils.closeQuietly(handle); 13158 } 13159 } 13160 13161 final int[] users = sUserManager.getUserIds(); 13162 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13163 for (int user : users) { 13164 // TODO(multiArch): Fix this so that it links to the 13165 // correct directory. We're currently pointing to root. but we 13166 // must point to the arch specific subdirectory (if applicable). 13167 // 13168 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13169 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13170 newNativeRoot, user) < 0) { 13171 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13172 } 13173 } 13174 } 13175 13176 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13177 pkg.codePath = newCodePath; 13178 pkg.baseCodePath = newCodePath; 13179 // Move dex files around 13180 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13181 // Moving of dex files failed. Set 13182 // error code and abort move. 13183 pkg.codePath = oldCodePath; 13184 pkg.baseCodePath = oldCodePath; 13185 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13186 } 13187 } 13188 13189 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13190 pkg.applicationInfo.setCodePath(newCodePath); 13191 pkg.applicationInfo.setBaseCodePath(newCodePath); 13192 pkg.applicationInfo.setSplitCodePaths(null); 13193 pkg.applicationInfo.setResourcePath(newResPath); 13194 pkg.applicationInfo.setBaseResourcePath(newResPath); 13195 pkg.applicationInfo.setSplitResourcePaths(null); 13196 13197 PackageSetting ps = (PackageSetting) pkg.mExtras; 13198 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13199 ps.codePathString = ps.codePath.getPath(); 13200 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13201 ps.resourcePathString = ps.resourcePath.getPath(); 13202 13203 // Note that we don't have to recalculate the primary and secondary 13204 // CPU ABIs because they must already have been calculated during the 13205 // initial install of the app. 13206 ps.legacyNativeLibraryPathString = null; 13207 13208 // Set the application info flag 13209 // correctly. 13210 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13211 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13212 } else { 13213 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13214 } 13215 ps.setFlags(pkg.applicationInfo.flags); 13216 mAppDirs.remove(oldCodePath); 13217 mAppDirs.put(newCodePath, pkg); 13218 // Persist settings 13219 mSettings.writeLPr(); 13220 } 13221 } 13222 } 13223 } 13224 // Send resources available broadcast 13225 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13226 } 13227 } 13228 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13229 // Clean up failed installation 13230 if (mp.targetArgs != null) { 13231 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13232 -1); 13233 } 13234 } else { 13235 // Force a gc to clear things up. 13236 Runtime.getRuntime().gc(); 13237 // Delete older code 13238 synchronized (mInstallLock) { 13239 mp.srcArgs.doPostDeleteLI(true); 13240 } 13241 } 13242 13243 // Allow more operations on this file if we didn't fail because 13244 // an operation was already pending for this package. 13245 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13246 synchronized (mPackages) { 13247 PackageParser.Package pkg = mPackages.get(mp.packageName); 13248 if (pkg != null) { 13249 pkg.mOperationPending = false; 13250 } 13251 } 13252 } 13253 13254 IPackageMoveObserver observer = mp.observer; 13255 if (observer != null) { 13256 try { 13257 observer.packageMoved(mp.packageName, returnCode); 13258 } catch (RemoteException e) { 13259 Log.i(TAG, "Observer no longer exists."); 13260 } 13261 } 13262 } 13263 }); 13264 } 13265 13266 @Override 13267 public boolean setInstallLocation(int loc) { 13268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13269 null); 13270 if (getInstallLocation() == loc) { 13271 return true; 13272 } 13273 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13274 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13275 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13276 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13277 return true; 13278 } 13279 return false; 13280 } 13281 13282 @Override 13283 public int getInstallLocation() { 13284 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13285 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13286 PackageHelper.APP_INSTALL_AUTO); 13287 } 13288 13289 /** Called by UserManagerService */ 13290 void cleanUpUserLILPw(int userHandle) { 13291 mDirtyUsers.remove(userHandle); 13292 mSettings.removeUserLPw(userHandle); 13293 mPendingBroadcasts.remove(userHandle); 13294 if (mInstaller != null) { 13295 // Technically, we shouldn't be doing this with the package lock 13296 // held. However, this is very rare, and there is already so much 13297 // other disk I/O going on, that we'll let it slide for now. 13298 mInstaller.removeUserDataDirs(userHandle); 13299 } 13300 mUserNeedsBadging.delete(userHandle); 13301 } 13302 13303 /** Called by UserManagerService */ 13304 void createNewUserLILPw(int userHandle, File path) { 13305 if (mInstaller != null) { 13306 mInstaller.createUserConfig(userHandle); 13307 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13308 } 13309 } 13310 13311 @Override 13312 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13313 mContext.enforceCallingOrSelfPermission( 13314 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13315 "Only package verification agents can read the verifier device identity"); 13316 13317 synchronized (mPackages) { 13318 return mSettings.getVerifierDeviceIdentityLPw(); 13319 } 13320 } 13321 13322 @Override 13323 public void setPermissionEnforced(String permission, boolean enforced) { 13324 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13325 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13326 synchronized (mPackages) { 13327 if (mSettings.mReadExternalStorageEnforced == null 13328 || mSettings.mReadExternalStorageEnforced != enforced) { 13329 mSettings.mReadExternalStorageEnforced = enforced; 13330 mSettings.writeLPr(); 13331 } 13332 } 13333 // kill any non-foreground processes so we restart them and 13334 // grant/revoke the GID. 13335 final IActivityManager am = ActivityManagerNative.getDefault(); 13336 if (am != null) { 13337 final long token = Binder.clearCallingIdentity(); 13338 try { 13339 am.killProcessesBelowForeground("setPermissionEnforcement"); 13340 } catch (RemoteException e) { 13341 } finally { 13342 Binder.restoreCallingIdentity(token); 13343 } 13344 } 13345 } else { 13346 throw new IllegalArgumentException("No selective enforcement for " + permission); 13347 } 13348 } 13349 13350 @Override 13351 @Deprecated 13352 public boolean isPermissionEnforced(String permission) { 13353 return true; 13354 } 13355 13356 @Override 13357 public boolean isStorageLow() { 13358 final long token = Binder.clearCallingIdentity(); 13359 try { 13360 final DeviceStorageMonitorInternal 13361 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13362 if (dsm != null) { 13363 return dsm.isMemoryLow(); 13364 } else { 13365 return false; 13366 } 13367 } finally { 13368 Binder.restoreCallingIdentity(token); 13369 } 13370 } 13371 13372 @Override 13373 public IPackageInstaller getPackageInstaller() { 13374 return mInstallerService; 13375 } 13376 13377 private boolean userNeedsBadging(int userId) { 13378 int index = mUserNeedsBadging.indexOfKey(userId); 13379 if (index < 0) { 13380 final UserInfo userInfo; 13381 final long token = Binder.clearCallingIdentity(); 13382 try { 13383 userInfo = sUserManager.getUserInfo(userId); 13384 } finally { 13385 Binder.restoreCallingIdentity(token); 13386 } 13387 final boolean b; 13388 if (userInfo != null && userInfo.isManagedProfile()) { 13389 b = true; 13390 } else { 13391 b = false; 13392 } 13393 mUserNeedsBadging.put(userId, b); 13394 return b; 13395 } 13396 return mUserNeedsBadging.valueAt(index); 13397 } 13398 13399 @Override 13400 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13401 if (packageName == null || alias == null) { 13402 return null; 13403 } 13404 synchronized(mPackages) { 13405 final PackageParser.Package pkg = mPackages.get(packageName); 13406 if (pkg == null) { 13407 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13408 throw new IllegalArgumentException("Unknown package: " + packageName); 13409 } 13410 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13411 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13412 throw new SecurityException("May not access KeySets defined by" 13413 + " aliases in other applications."); 13414 } 13415 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13416 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13417 } 13418 } 13419 13420 @Override 13421 public KeySetHandle getSigningKeySet(String packageName) { 13422 if (packageName == null) { 13423 return null; 13424 } 13425 synchronized(mPackages) { 13426 final PackageParser.Package pkg = mPackages.get(packageName); 13427 if (pkg == null) { 13428 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13429 throw new IllegalArgumentException("Unknown package: " + packageName); 13430 } 13431 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13432 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13433 throw new SecurityException("May not access signing KeySet of other apps."); 13434 } 13435 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13436 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13437 } 13438 } 13439 13440 @Override 13441 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13442 if (packageName == null || ks == null) { 13443 return false; 13444 } 13445 synchronized(mPackages) { 13446 final PackageParser.Package pkg = mPackages.get(packageName); 13447 if (pkg == null) { 13448 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13449 throw new IllegalArgumentException("Unknown package: " + packageName); 13450 } 13451 if (ks instanceof KeySetHandle) { 13452 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13453 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13454 } 13455 return false; 13456 } 13457 } 13458 13459 @Override 13460 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13461 if (packageName == null || ks == null) { 13462 return false; 13463 } 13464 synchronized(mPackages) { 13465 final PackageParser.Package pkg = mPackages.get(packageName); 13466 if (pkg == null) { 13467 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13468 throw new IllegalArgumentException("Unknown package: " + packageName); 13469 } 13470 if (ks instanceof KeySetHandle) { 13471 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13472 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13473 } 13474 return false; 13475 } 13476 } 13477} 13478