PackageManagerService.java revision 1e9189a276e967a7a74ff44a44cf627764396954
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.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstallSessionParams; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageManager; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.FileObserver; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.security.KeyStore; 158import android.security.SystemKeyStore; 159import android.system.ErrnoException; 160import android.system.Os; 161import android.system.StructStat; 162import android.text.TextUtils; 163import android.util.ArraySet; 164import android.util.AtomicFile; 165import android.util.DisplayMetrics; 166import android.util.EventLog; 167import android.util.ExceptionUtils; 168import android.util.Log; 169import android.util.LogPrinter; 170import android.util.PrintStreamPrinter; 171import android.util.Slog; 172import android.util.SparseArray; 173import android.util.SparseBooleanArray; 174import android.view.Display; 175 176import java.io.BufferedInputStream; 177import java.io.BufferedOutputStream; 178import java.io.File; 179import java.io.FileDescriptor; 180import java.io.FileInputStream; 181import java.io.FileNotFoundException; 182import java.io.FileOutputStream; 183import java.io.FilenameFilter; 184import java.io.IOException; 185import java.io.InputStream; 186import java.io.PrintWriter; 187import java.nio.charset.StandardCharsets; 188import java.security.NoSuchAlgorithmException; 189import java.security.PublicKey; 190import java.security.cert.CertificateEncodingException; 191import java.security.cert.CertificateException; 192import java.text.SimpleDateFormat; 193import java.util.ArrayList; 194import java.util.Arrays; 195import java.util.Collection; 196import java.util.Collections; 197import java.util.Comparator; 198import java.util.Date; 199import java.util.HashMap; 200import java.util.HashSet; 201import java.util.Iterator; 202import java.util.List; 203import java.util.Map; 204import java.util.Set; 205import java.util.concurrent.atomic.AtomicBoolean; 206import java.util.concurrent.atomic.AtomicLong; 207 208import dalvik.system.DexFile; 209import dalvik.system.StaleDexCacheError; 210import dalvik.system.VMRuntime; 211 212import libcore.io.IoUtils; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_APP_DIR_OBSERVER = 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 private static final int REMOVE_EVENTS = 253 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 254 private static final int ADD_EVENTS = 255 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 256 257 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 258 // Suffix used during package installation when copying/moving 259 // package apks to install directory. 260 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 261 262 static final int SCAN_MONITOR = 1<<0; 263 static final int SCAN_NO_DEX = 1<<1; 264 static final int SCAN_FORCE_DEX = 1<<2; 265 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 266 static final int SCAN_NEW_INSTALL = 1<<4; 267 static final int SCAN_NO_PATHS = 1<<5; 268 static final int SCAN_UPDATE_TIME = 1<<6; 269 static final int SCAN_DEFER_DEX = 1<<7; 270 static final int SCAN_BOOTING = 1<<8; 271 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 272 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 273 274 static final int REMOVE_CHATTY = 1<<16; 275 276 /** 277 * Timeout (in milliseconds) after which the watchdog should declare that 278 * our handler thread is wedged. The usual default for such things is one 279 * minute but we sometimes do very lengthy I/O operations on this thread, 280 * such as installing multi-gigabyte applications, so ours needs to be longer. 281 */ 282 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 283 284 /** 285 * Whether verification is enabled by default. 286 */ 287 private static final boolean DEFAULT_VERIFY_ENABLE = true; 288 289 /** 290 * The default maximum time to wait for the verification agent to return in 291 * milliseconds. 292 */ 293 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 294 295 /** 296 * The default response for package verification timeout. 297 * 298 * This can be either PackageManager.VERIFICATION_ALLOW or 299 * PackageManager.VERIFICATION_REJECT. 300 */ 301 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 302 303 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 304 305 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 306 DEFAULT_CONTAINER_PACKAGE, 307 "com.android.defcontainer.DefaultContainerService"); 308 309 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 310 311 private static final String LIB_DIR_NAME = "lib"; 312 private static final String LIB64_DIR_NAME = "lib64"; 313 314 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 315 316 static final String mTempContainerPrefix = "smdl2tmp"; 317 318 private static String sPreferredInstructionSet; 319 320 final ServiceThread mHandlerThread; 321 322 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 323 private static final String IDMAP_SUFFIX = "@idmap"; 324 325 final PackageHandler mHandler; 326 327 final int mSdkVersion = Build.VERSION.SDK_INT; 328 329 final Context mContext; 330 final boolean mFactoryTest; 331 final boolean mOnlyCore; 332 final DisplayMetrics mMetrics; 333 final int mDefParseFlags; 334 final String[] mSeparateProcesses; 335 336 // This is where all application persistent data goes. 337 final File mAppDataDir; 338 339 // This is where all application persistent data goes for secondary users. 340 final File mUserAppDataDir; 341 342 /** The location for ASEC container files on internal storage. */ 343 final String mAsecInternalPath; 344 345 // This is the object monitoring the framework dir. 346 final FileObserver mFrameworkInstallObserver; 347 348 // This is the object monitoring the system app dir. 349 final FileObserver mSystemInstallObserver; 350 351 // This is the object monitoring the privileged system app dir. 352 final FileObserver mPrivilegedInstallObserver; 353 354 // This is the object monitoring the vendor app dir. 355 final FileObserver mVendorInstallObserver; 356 357 // This is the object monitoring the vendor overlay package dir. 358 final FileObserver mVendorOverlayInstallObserver; 359 360 // This is the object monitoring the OEM app dir. 361 final FileObserver mOemInstallObserver; 362 363 // This is the object monitoring mAppInstallDir. 364 final FileObserver mAppInstallObserver; 365 366 // This is the object monitoring mDrmAppPrivateInstallDir. 367 final FileObserver mDrmAppInstallObserver; 368 369 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 370 // LOCK HELD. Can be called with mInstallLock held. 371 final Installer mInstaller; 372 373 /** Directory where installed third-party apps stored */ 374 final File mAppInstallDir; 375 376 /** 377 * Directory to which applications installed internally have their 378 * 32 bit native libraries copied. 379 */ 380 private File mAppLib32InstallDir; 381 382 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 383 // apps. 384 final File mDrmAppPrivateInstallDir; 385 386 // ---------------------------------------------------------------- 387 388 // Lock for state used when installing and doing other long running 389 // operations. Methods that must be called with this lock held have 390 // the suffix "LI". 391 final Object mInstallLock = new Object(); 392 393 // These are the directories in the 3rd party applications installed dir 394 // that we have currently loaded packages from. Keys are the application's 395 // installed zip file (absolute codePath), and values are Package. 396 final HashMap<String, PackageParser.Package> mAppDirs = 397 new HashMap<String, PackageParser.Package>(); 398 399 // ---------------------------------------------------------------- 400 401 // Keys are String (package name), values are Package. This also serves 402 // as the lock for the global state. Methods that must be called with 403 // this lock held have the prefix "LP". 404 final HashMap<String, PackageParser.Package> mPackages = 405 new HashMap<String, PackageParser.Package>(); 406 407 // Tracks available target package names -> overlay package paths. 408 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 409 new HashMap<String, HashMap<String, PackageParser.Package>>(); 410 411 final Settings mSettings; 412 boolean mRestoredSettings; 413 414 // System configuration read by SystemConfig. 415 final int[] mGlobalGids; 416 final SparseArray<HashSet<String>> mSystemPermissions; 417 final HashMap<String, FeatureInfo> mAvailableFeatures; 418 419 // If mac_permissions.xml was found for seinfo labeling. 420 boolean mFoundPolicyFile; 421 422 // If a recursive restorecon of /data/data/<pkg> is needed. 423 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 424 425 public static final class SharedLibraryEntry { 426 public final String path; 427 public final String apk; 428 429 SharedLibraryEntry(String _path, String _apk) { 430 path = _path; 431 apk = _apk; 432 } 433 } 434 435 // Currently known shared libraries. 436 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 437 new HashMap<String, SharedLibraryEntry>(); 438 439 // All available activities, for your resolving pleasure. 440 final ActivityIntentResolver mActivities = 441 new ActivityIntentResolver(); 442 443 // All available receivers, for your resolving pleasure. 444 final ActivityIntentResolver mReceivers = 445 new ActivityIntentResolver(); 446 447 // All available services, for your resolving pleasure. 448 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 449 450 // All available providers, for your resolving pleasure. 451 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 452 453 // Mapping from provider base names (first directory in content URI codePath) 454 // to the provider information. 455 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 456 new HashMap<String, PackageParser.Provider>(); 457 458 // Mapping from instrumentation class names to info about them. 459 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 460 new HashMap<ComponentName, PackageParser.Instrumentation>(); 461 462 // Mapping from permission names to info about them. 463 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 464 new HashMap<String, PackageParser.PermissionGroup>(); 465 466 // Packages whose data we have transfered into another package, thus 467 // should no longer exist. 468 final HashSet<String> mTransferedPackages = new HashSet<String>(); 469 470 // Broadcast actions that are only available to the system. 471 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 472 473 /** List of packages waiting for verification. */ 474 final SparseArray<PackageVerificationState> mPendingVerification 475 = new SparseArray<PackageVerificationState>(); 476 477 final PackageInstallerService mInstallerService; 478 479 HashSet<PackageParser.Package> mDeferredDexOpt = null; 480 481 // Cache of users who need badging. 482 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 483 484 /** Token for keys in mPendingVerification. */ 485 private int mPendingVerificationToken = 0; 486 487 boolean mSystemReady; 488 boolean mSafeMode; 489 boolean mHasSystemUidErrors; 490 491 ApplicationInfo mAndroidApplication; 492 final ActivityInfo mResolveActivity = new ActivityInfo(); 493 final ResolveInfo mResolveInfo = new ResolveInfo(); 494 ComponentName mResolveComponentName; 495 PackageParser.Package mPlatformPackage; 496 ComponentName mCustomResolverComponentName; 497 498 boolean mResolverReplaced = false; 499 500 // Set of pending broadcasts for aggregating enable/disable of components. 501 static class PendingPackageBroadcasts { 502 // for each user id, a map of <package name -> components within that package> 503 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 504 505 public PendingPackageBroadcasts() { 506 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 507 } 508 509 public ArrayList<String> get(int userId, String packageName) { 510 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 511 return packages.get(packageName); 512 } 513 514 public void put(int userId, String packageName, ArrayList<String> components) { 515 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 516 packages.put(packageName, components); 517 } 518 519 public void remove(int userId, String packageName) { 520 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 521 if (packages != null) { 522 packages.remove(packageName); 523 } 524 } 525 526 public void remove(int userId) { 527 mUidMap.remove(userId); 528 } 529 530 public int userIdCount() { 531 return mUidMap.size(); 532 } 533 534 public int userIdAt(int n) { 535 return mUidMap.keyAt(n); 536 } 537 538 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 539 return mUidMap.get(userId); 540 } 541 542 public int size() { 543 // total number of pending broadcast entries across all userIds 544 int num = 0; 545 for (int i = 0; i< mUidMap.size(); i++) { 546 num += mUidMap.valueAt(i).size(); 547 } 548 return num; 549 } 550 551 public void clear() { 552 mUidMap.clear(); 553 } 554 555 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 556 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 557 if (map == null) { 558 map = new HashMap<String, ArrayList<String>>(); 559 mUidMap.put(userId, map); 560 } 561 return map; 562 } 563 } 564 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 565 566 // Service Connection to remote media container service to copy 567 // package uri's from external media onto secure containers 568 // or internal storage. 569 private IMediaContainerService mContainerService = null; 570 571 static final int SEND_PENDING_BROADCAST = 1; 572 static final int MCS_BOUND = 3; 573 static final int END_COPY = 4; 574 static final int INIT_COPY = 5; 575 static final int MCS_UNBIND = 6; 576 static final int START_CLEANING_PACKAGE = 7; 577 static final int FIND_INSTALL_LOC = 8; 578 static final int POST_INSTALL = 9; 579 static final int MCS_RECONNECT = 10; 580 static final int MCS_GIVE_UP = 11; 581 static final int UPDATED_MEDIA_STATUS = 12; 582 static final int WRITE_SETTINGS = 13; 583 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 584 static final int PACKAGE_VERIFIED = 15; 585 static final int CHECK_PENDING_VERIFICATION = 16; 586 587 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 588 589 // Delay time in millisecs 590 static final int BROADCAST_DELAY = 10 * 1000; 591 592 static UserManagerService sUserManager; 593 594 // Stores a list of users whose package restrictions file needs to be updated 595 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 596 597 final private DefaultContainerConnection mDefContainerConn = 598 new DefaultContainerConnection(); 599 class DefaultContainerConnection implements ServiceConnection { 600 public void onServiceConnected(ComponentName name, IBinder service) { 601 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 602 IMediaContainerService imcs = 603 IMediaContainerService.Stub.asInterface(service); 604 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 605 } 606 607 public void onServiceDisconnected(ComponentName name) { 608 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 609 } 610 }; 611 612 // Recordkeeping of restore-after-install operations that are currently in flight 613 // between the Package Manager and the Backup Manager 614 class PostInstallData { 615 public InstallArgs args; 616 public PackageInstalledInfo res; 617 618 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 619 args = _a; 620 res = _r; 621 } 622 }; 623 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 624 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 625 626 private final String mRequiredVerifierPackage; 627 628 private final PackageUsage mPackageUsage = new PackageUsage(); 629 630 private class PackageUsage { 631 private static final int WRITE_INTERVAL 632 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 633 634 private final Object mFileLock = new Object(); 635 private final AtomicLong mLastWritten = new AtomicLong(0); 636 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 637 638 private boolean mIsHistoricalPackageUsageAvailable = true; 639 640 boolean isHistoricalPackageUsageAvailable() { 641 return mIsHistoricalPackageUsageAvailable; 642 } 643 644 void write(boolean force) { 645 if (force) { 646 writeInternal(); 647 return; 648 } 649 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 650 && !DEBUG_DEXOPT) { 651 return; 652 } 653 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 654 new Thread("PackageUsage_DiskWriter") { 655 @Override 656 public void run() { 657 try { 658 writeInternal(); 659 } finally { 660 mBackgroundWriteRunning.set(false); 661 } 662 } 663 }.start(); 664 } 665 } 666 667 private void writeInternal() { 668 synchronized (mPackages) { 669 synchronized (mFileLock) { 670 AtomicFile file = getFile(); 671 FileOutputStream f = null; 672 try { 673 f = file.startWrite(); 674 BufferedOutputStream out = new BufferedOutputStream(f); 675 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 676 StringBuilder sb = new StringBuilder(); 677 for (PackageParser.Package pkg : mPackages.values()) { 678 if (pkg.mLastPackageUsageTimeInMills == 0) { 679 continue; 680 } 681 sb.setLength(0); 682 sb.append(pkg.packageName); 683 sb.append(' '); 684 sb.append((long)pkg.mLastPackageUsageTimeInMills); 685 sb.append('\n'); 686 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 687 } 688 out.flush(); 689 file.finishWrite(f); 690 } catch (IOException e) { 691 if (f != null) { 692 file.failWrite(f); 693 } 694 Log.e(TAG, "Failed to write package usage times", e); 695 } 696 } 697 } 698 mLastWritten.set(SystemClock.elapsedRealtime()); 699 } 700 701 void readLP() { 702 synchronized (mFileLock) { 703 AtomicFile file = getFile(); 704 BufferedInputStream in = null; 705 try { 706 in = new BufferedInputStream(file.openRead()); 707 StringBuffer sb = new StringBuffer(); 708 while (true) { 709 String packageName = readToken(in, sb, ' '); 710 if (packageName == null) { 711 break; 712 } 713 String timeInMillisString = readToken(in, sb, '\n'); 714 if (timeInMillisString == null) { 715 throw new IOException("Failed to find last usage time for package " 716 + packageName); 717 } 718 PackageParser.Package pkg = mPackages.get(packageName); 719 if (pkg == null) { 720 continue; 721 } 722 long timeInMillis; 723 try { 724 timeInMillis = Long.parseLong(timeInMillisString.toString()); 725 } catch (NumberFormatException e) { 726 throw new IOException("Failed to parse " + timeInMillisString 727 + " as a long.", e); 728 } 729 pkg.mLastPackageUsageTimeInMills = timeInMillis; 730 } 731 } catch (FileNotFoundException expected) { 732 mIsHistoricalPackageUsageAvailable = false; 733 } catch (IOException e) { 734 Log.w(TAG, "Failed to read package usage times", e); 735 } finally { 736 IoUtils.closeQuietly(in); 737 } 738 } 739 mLastWritten.set(SystemClock.elapsedRealtime()); 740 } 741 742 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 743 throws IOException { 744 sb.setLength(0); 745 while (true) { 746 int ch = in.read(); 747 if (ch == -1) { 748 if (sb.length() == 0) { 749 return null; 750 } 751 throw new IOException("Unexpected EOF"); 752 } 753 if (ch == endOfToken) { 754 return sb.toString(); 755 } 756 sb.append((char)ch); 757 } 758 } 759 760 private AtomicFile getFile() { 761 File dataDir = Environment.getDataDirectory(); 762 File systemDir = new File(dataDir, "system"); 763 File fname = new File(systemDir, "package-usage.list"); 764 return new AtomicFile(fname); 765 } 766 } 767 768 class PackageHandler extends Handler { 769 private boolean mBound = false; 770 final ArrayList<HandlerParams> mPendingInstalls = 771 new ArrayList<HandlerParams>(); 772 773 private boolean connectToService() { 774 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 775 " DefaultContainerService"); 776 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 777 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 778 if (mContext.bindServiceAsUser(service, mDefContainerConn, 779 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 mBound = true; 782 return true; 783 } 784 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 785 return false; 786 } 787 788 private void disconnectService() { 789 mContainerService = null; 790 mBound = false; 791 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 792 mContext.unbindService(mDefContainerConn); 793 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 794 } 795 796 PackageHandler(Looper looper) { 797 super(looper); 798 } 799 800 public void handleMessage(Message msg) { 801 try { 802 doHandleMessage(msg); 803 } finally { 804 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 805 } 806 } 807 808 void doHandleMessage(Message msg) { 809 switch (msg.what) { 810 case INIT_COPY: { 811 HandlerParams params = (HandlerParams) msg.obj; 812 int idx = mPendingInstalls.size(); 813 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 814 // If a bind was already initiated we dont really 815 // need to do anything. The pending install 816 // will be processed later on. 817 if (!mBound) { 818 // If this is the only one pending we might 819 // have to bind to the service again. 820 if (!connectToService()) { 821 Slog.e(TAG, "Failed to bind to media container service"); 822 params.serviceError(); 823 return; 824 } else { 825 // Once we bind to the service, the first 826 // pending request will be processed. 827 mPendingInstalls.add(idx, params); 828 } 829 } else { 830 mPendingInstalls.add(idx, params); 831 // Already bound to the service. Just make 832 // sure we trigger off processing the first request. 833 if (idx == 0) { 834 mHandler.sendEmptyMessage(MCS_BOUND); 835 } 836 } 837 break; 838 } 839 case MCS_BOUND: { 840 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 841 if (msg.obj != null) { 842 mContainerService = (IMediaContainerService) msg.obj; 843 } 844 if (mContainerService == null) { 845 // Something seriously wrong. Bail out 846 Slog.e(TAG, "Cannot bind to media container service"); 847 for (HandlerParams params : mPendingInstalls) { 848 // Indicate service bind error 849 params.serviceError(); 850 } 851 mPendingInstalls.clear(); 852 } else if (mPendingInstalls.size() > 0) { 853 HandlerParams params = mPendingInstalls.get(0); 854 if (params != null) { 855 if (params.startCopy()) { 856 // We are done... look for more work or to 857 // go idle. 858 if (DEBUG_SD_INSTALL) Log.i(TAG, 859 "Checking for more work or unbind..."); 860 // Delete pending install 861 if (mPendingInstalls.size() > 0) { 862 mPendingInstalls.remove(0); 863 } 864 if (mPendingInstalls.size() == 0) { 865 if (mBound) { 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting delayed MCS_UNBIND"); 868 removeMessages(MCS_UNBIND); 869 Message ubmsg = obtainMessage(MCS_UNBIND); 870 // Unbind after a little delay, to avoid 871 // continual thrashing. 872 sendMessageDelayed(ubmsg, 10000); 873 } 874 } else { 875 // There are more pending requests in queue. 876 // Just post MCS_BOUND message to trigger processing 877 // of next pending install. 878 if (DEBUG_SD_INSTALL) Log.i(TAG, 879 "Posting MCS_BOUND for next work"); 880 mHandler.sendEmptyMessage(MCS_BOUND); 881 } 882 } 883 } 884 } else { 885 // Should never happen ideally. 886 Slog.w(TAG, "Empty queue"); 887 } 888 break; 889 } 890 case MCS_RECONNECT: { 891 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 892 if (mPendingInstalls.size() > 0) { 893 if (mBound) { 894 disconnectService(); 895 } 896 if (!connectToService()) { 897 Slog.e(TAG, "Failed to bind to media container service"); 898 for (HandlerParams params : mPendingInstalls) { 899 // Indicate service bind error 900 params.serviceError(); 901 } 902 mPendingInstalls.clear(); 903 } 904 } 905 break; 906 } 907 case MCS_UNBIND: { 908 // If there is no actual work left, then time to unbind. 909 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 910 911 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 912 if (mBound) { 913 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 914 915 disconnectService(); 916 } 917 } else if (mPendingInstalls.size() > 0) { 918 // There are more pending requests in queue. 919 // Just post MCS_BOUND message to trigger processing 920 // of next pending install. 921 mHandler.sendEmptyMessage(MCS_BOUND); 922 } 923 924 break; 925 } 926 case MCS_GIVE_UP: { 927 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 928 mPendingInstalls.remove(0); 929 break; 930 } 931 case SEND_PENDING_BROADCAST: { 932 String packages[]; 933 ArrayList<String> components[]; 934 int size = 0; 935 int uids[]; 936 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 937 synchronized (mPackages) { 938 if (mPendingBroadcasts == null) { 939 return; 940 } 941 size = mPendingBroadcasts.size(); 942 if (size <= 0) { 943 // Nothing to be done. Just return 944 return; 945 } 946 packages = new String[size]; 947 components = new ArrayList[size]; 948 uids = new int[size]; 949 int i = 0; // filling out the above arrays 950 951 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 952 int packageUserId = mPendingBroadcasts.userIdAt(n); 953 Iterator<Map.Entry<String, ArrayList<String>>> it 954 = mPendingBroadcasts.packagesForUserId(packageUserId) 955 .entrySet().iterator(); 956 while (it.hasNext() && i < size) { 957 Map.Entry<String, ArrayList<String>> ent = it.next(); 958 packages[i] = ent.getKey(); 959 components[i] = ent.getValue(); 960 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 961 uids[i] = (ps != null) 962 ? UserHandle.getUid(packageUserId, ps.appId) 963 : -1; 964 i++; 965 } 966 } 967 size = i; 968 mPendingBroadcasts.clear(); 969 } 970 // Send broadcasts 971 for (int i = 0; i < size; i++) { 972 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 973 } 974 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 975 break; 976 } 977 case START_CLEANING_PACKAGE: { 978 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 979 final String packageName = (String)msg.obj; 980 final int userId = msg.arg1; 981 final boolean andCode = msg.arg2 != 0; 982 synchronized (mPackages) { 983 if (userId == UserHandle.USER_ALL) { 984 int[] users = sUserManager.getUserIds(); 985 for (int user : users) { 986 mSettings.addPackageToCleanLPw( 987 new PackageCleanItem(user, packageName, andCode)); 988 } 989 } else { 990 mSettings.addPackageToCleanLPw( 991 new PackageCleanItem(userId, packageName, andCode)); 992 } 993 } 994 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 995 startCleaningPackages(); 996 } break; 997 case POST_INSTALL: { 998 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 999 PostInstallData data = mRunningInstalls.get(msg.arg1); 1000 mRunningInstalls.delete(msg.arg1); 1001 boolean deleteOld = false; 1002 1003 if (data != null) { 1004 InstallArgs args = data.args; 1005 PackageInstalledInfo res = data.res; 1006 1007 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1008 res.removedInfo.sendBroadcast(false, true, false); 1009 Bundle extras = new Bundle(1); 1010 extras.putInt(Intent.EXTRA_UID, res.uid); 1011 // Determine the set of users who are adding this 1012 // package for the first time vs. those who are seeing 1013 // an update. 1014 int[] firstUsers; 1015 int[] updateUsers = new int[0]; 1016 if (res.origUsers == null || res.origUsers.length == 0) { 1017 firstUsers = res.newUsers; 1018 } else { 1019 firstUsers = new int[0]; 1020 for (int i=0; i<res.newUsers.length; i++) { 1021 int user = res.newUsers[i]; 1022 boolean isNew = true; 1023 for (int j=0; j<res.origUsers.length; j++) { 1024 if (res.origUsers[j] == user) { 1025 isNew = false; 1026 break; 1027 } 1028 } 1029 if (isNew) { 1030 int[] newFirst = new int[firstUsers.length+1]; 1031 System.arraycopy(firstUsers, 0, newFirst, 0, 1032 firstUsers.length); 1033 newFirst[firstUsers.length] = user; 1034 firstUsers = newFirst; 1035 } else { 1036 int[] newUpdate = new int[updateUsers.length+1]; 1037 System.arraycopy(updateUsers, 0, newUpdate, 0, 1038 updateUsers.length); 1039 newUpdate[updateUsers.length] = user; 1040 updateUsers = newUpdate; 1041 } 1042 } 1043 } 1044 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1045 res.pkg.applicationInfo.packageName, 1046 extras, null, null, firstUsers); 1047 final boolean update = res.removedInfo.removedPackage != null; 1048 if (update) { 1049 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1050 } 1051 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1052 res.pkg.applicationInfo.packageName, 1053 extras, null, null, updateUsers); 1054 if (update) { 1055 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1056 res.pkg.applicationInfo.packageName, 1057 extras, null, null, updateUsers); 1058 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1059 null, null, 1060 res.pkg.applicationInfo.packageName, null, updateUsers); 1061 1062 // treat asec-hosted packages like removable media on upgrade 1063 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1064 if (DEBUG_INSTALL) { 1065 Slog.i(TAG, "upgrading pkg " + res.pkg 1066 + " is ASEC-hosted -> AVAILABLE"); 1067 } 1068 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1069 ArrayList<String> pkgList = new ArrayList<String>(1); 1070 pkgList.add(res.pkg.applicationInfo.packageName); 1071 sendResourcesChangedBroadcast(true, true, 1072 pkgList,uidArray, null); 1073 } 1074 } 1075 if (res.removedInfo.args != null) { 1076 // Remove the replaced package's older resources safely now 1077 deleteOld = true; 1078 } 1079 1080 // Log current value of "unknown sources" setting 1081 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1082 getUnknownSourcesSettings()); 1083 } 1084 // Force a gc to clear up things 1085 Runtime.getRuntime().gc(); 1086 // We delete after a gc for applications on sdcard. 1087 if (deleteOld) { 1088 synchronized (mInstallLock) { 1089 res.removedInfo.args.doPostDeleteLI(true); 1090 } 1091 } 1092 if (args.observer != null) { 1093 try { 1094 Bundle extras = extrasForInstallResult(res); 1095 args.observer.packageInstalled(res.name, extras, res.returnCode, 1096 res.returnMsg); 1097 } catch (RemoteException e) { 1098 Slog.i(TAG, "Observer no longer exists."); 1099 } 1100 } 1101 } else { 1102 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1103 } 1104 } break; 1105 case UPDATED_MEDIA_STATUS: { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1107 boolean reportStatus = msg.arg1 == 1; 1108 boolean doGc = msg.arg2 == 1; 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1110 if (doGc) { 1111 // Force a gc to clear up stale containers. 1112 Runtime.getRuntime().gc(); 1113 } 1114 if (msg.obj != null) { 1115 @SuppressWarnings("unchecked") 1116 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1118 // Unload containers 1119 unloadAllContainers(args); 1120 } 1121 if (reportStatus) { 1122 try { 1123 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1124 PackageHelper.getMountService().finishMediaUpdate(); 1125 } catch (RemoteException e) { 1126 Log.e(TAG, "MountService not running?"); 1127 } 1128 } 1129 } break; 1130 case WRITE_SETTINGS: { 1131 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1132 synchronized (mPackages) { 1133 removeMessages(WRITE_SETTINGS); 1134 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1135 mSettings.writeLPr(); 1136 mDirtyUsers.clear(); 1137 } 1138 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1139 } break; 1140 case WRITE_PACKAGE_RESTRICTIONS: { 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1142 synchronized (mPackages) { 1143 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1144 for (int userId : mDirtyUsers) { 1145 mSettings.writePackageRestrictionsLPr(userId); 1146 } 1147 mDirtyUsers.clear(); 1148 } 1149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1150 } break; 1151 case CHECK_PENDING_VERIFICATION: { 1152 final int verificationId = msg.arg1; 1153 final PackageVerificationState state = mPendingVerification.get(verificationId); 1154 1155 if ((state != null) && !state.timeoutExtended()) { 1156 final InstallArgs args = state.getInstallArgs(); 1157 final Uri originUri = Uri.fromFile(args.originFile); 1158 1159 Slog.i(TAG, "Verification timed out for " + originUri); 1160 mPendingVerification.remove(verificationId); 1161 1162 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1163 1164 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1165 Slog.i(TAG, "Continuing with installation of " + originUri); 1166 state.setVerifierResponse(Binder.getCallingUid(), 1167 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1168 broadcastPackageVerified(verificationId, originUri, 1169 PackageManager.VERIFICATION_ALLOW, 1170 state.getInstallArgs().getUser()); 1171 try { 1172 ret = args.copyApk(mContainerService, true); 1173 } catch (RemoteException e) { 1174 Slog.e(TAG, "Could not contact the ContainerService"); 1175 } 1176 } else { 1177 broadcastPackageVerified(verificationId, originUri, 1178 PackageManager.VERIFICATION_REJECT, 1179 state.getInstallArgs().getUser()); 1180 } 1181 1182 processPendingInstall(args, ret); 1183 mHandler.sendEmptyMessage(MCS_UNBIND); 1184 } 1185 break; 1186 } 1187 case PACKAGE_VERIFIED: { 1188 final int verificationId = msg.arg1; 1189 1190 final PackageVerificationState state = mPendingVerification.get(verificationId); 1191 if (state == null) { 1192 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1193 break; 1194 } 1195 1196 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1197 1198 state.setVerifierResponse(response.callerUid, response.code); 1199 1200 if (state.isVerificationComplete()) { 1201 mPendingVerification.remove(verificationId); 1202 1203 final InstallArgs args = state.getInstallArgs(); 1204 final Uri originUri = Uri.fromFile(args.originFile); 1205 1206 int ret; 1207 if (state.isInstallAllowed()) { 1208 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1209 broadcastPackageVerified(verificationId, originUri, 1210 response.code, state.getInstallArgs().getUser()); 1211 try { 1212 ret = args.copyApk(mContainerService, true); 1213 } catch (RemoteException e) { 1214 Slog.e(TAG, "Could not contact the ContainerService"); 1215 } 1216 } else { 1217 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1218 } 1219 1220 processPendingInstall(args, ret); 1221 1222 mHandler.sendEmptyMessage(MCS_UNBIND); 1223 } 1224 1225 break; 1226 } 1227 } 1228 } 1229 } 1230 1231 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1232 Bundle extras = null; 1233 switch (res.returnCode) { 1234 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1235 extras = new Bundle(); 1236 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1237 res.origPermission); 1238 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1239 res.origPackage); 1240 break; 1241 } 1242 } 1243 return extras; 1244 } 1245 1246 void scheduleWriteSettingsLocked() { 1247 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1248 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1249 } 1250 } 1251 1252 void scheduleWritePackageRestrictionsLocked(int userId) { 1253 if (!sUserManager.exists(userId)) return; 1254 mDirtyUsers.add(userId); 1255 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1256 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1257 } 1258 } 1259 1260 public static final PackageManagerService main(Context context, Installer installer, 1261 boolean factoryTest, boolean onlyCore) { 1262 PackageManagerService m = new PackageManagerService(context, installer, 1263 factoryTest, onlyCore); 1264 ServiceManager.addService("package", m); 1265 return m; 1266 } 1267 1268 static String[] splitString(String str, char sep) { 1269 int count = 1; 1270 int i = 0; 1271 while ((i=str.indexOf(sep, i)) >= 0) { 1272 count++; 1273 i++; 1274 } 1275 1276 String[] res = new String[count]; 1277 i=0; 1278 count = 0; 1279 int lastI=0; 1280 while ((i=str.indexOf(sep, i)) >= 0) { 1281 res[count] = str.substring(lastI, i); 1282 count++; 1283 i++; 1284 lastI = i; 1285 } 1286 res[count] = str.substring(lastI, str.length()); 1287 return res; 1288 } 1289 1290 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1291 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1292 Context.DISPLAY_SERVICE); 1293 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1294 } 1295 1296 public PackageManagerService(Context context, Installer installer, 1297 boolean factoryTest, boolean onlyCore) { 1298 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1299 SystemClock.uptimeMillis()); 1300 1301 if (mSdkVersion <= 0) { 1302 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1303 } 1304 1305 mContext = context; 1306 mFactoryTest = factoryTest; 1307 mOnlyCore = onlyCore; 1308 mMetrics = new DisplayMetrics(); 1309 mSettings = new Settings(context); 1310 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1311 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1312 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1313 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1314 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1315 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1316 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1317 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1318 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1319 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1320 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1321 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1322 1323 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1324 if (separateProcesses != null && separateProcesses.length() > 0) { 1325 if ("*".equals(separateProcesses)) { 1326 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1327 mSeparateProcesses = null; 1328 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1329 } else { 1330 mDefParseFlags = 0; 1331 mSeparateProcesses = separateProcesses.split(","); 1332 Slog.w(TAG, "Running with debug.separate_processes: " 1333 + separateProcesses); 1334 } 1335 } else { 1336 mDefParseFlags = 0; 1337 mSeparateProcesses = null; 1338 } 1339 1340 mInstaller = installer; 1341 1342 getDefaultDisplayMetrics(context, mMetrics); 1343 1344 SystemConfig systemConfig = SystemConfig.getInstance(); 1345 mGlobalGids = systemConfig.getGlobalGids(); 1346 mSystemPermissions = systemConfig.getSystemPermissions(); 1347 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1348 1349 synchronized (mInstallLock) { 1350 // writer 1351 synchronized (mPackages) { 1352 mHandlerThread = new ServiceThread(TAG, 1353 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1354 mHandlerThread.start(); 1355 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1356 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1357 1358 File dataDir = Environment.getDataDirectory(); 1359 mAppDataDir = new File(dataDir, "data"); 1360 mAppInstallDir = new File(dataDir, "app"); 1361 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1362 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1363 mUserAppDataDir = new File(dataDir, "user"); 1364 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1365 1366 sUserManager = new UserManagerService(context, this, 1367 mInstallLock, mPackages); 1368 1369 // Propagate permission configuration in to package manager. 1370 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1371 = systemConfig.getPermissions(); 1372 for (int i=0; i<permConfig.size(); i++) { 1373 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1374 BasePermission bp = mSettings.mPermissions.get(perm.name); 1375 if (bp == null) { 1376 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1377 mSettings.mPermissions.put(perm.name, bp); 1378 } 1379 if (perm.gids != null) { 1380 bp.gids = appendInts(bp.gids, perm.gids); 1381 } 1382 } 1383 1384 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1385 for (int i=0; i<libConfig.size(); i++) { 1386 mSharedLibraries.put(libConfig.keyAt(i), 1387 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1388 } 1389 1390 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1391 1392 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1393 mSdkVersion, mOnlyCore); 1394 1395 String customResolverActivity = Resources.getSystem().getString( 1396 R.string.config_customResolverActivity); 1397 if (TextUtils.isEmpty(customResolverActivity)) { 1398 customResolverActivity = null; 1399 } else { 1400 mCustomResolverComponentName = ComponentName.unflattenFromString( 1401 customResolverActivity); 1402 } 1403 1404 long startTime = SystemClock.uptimeMillis(); 1405 1406 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1407 startTime); 1408 1409 // Set flag to monitor and not change apk file paths when 1410 // scanning install directories. 1411 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1412 1413 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1414 1415 /** 1416 * Add everything in the in the boot class path to the 1417 * list of process files because dexopt will have been run 1418 * if necessary during zygote startup. 1419 */ 1420 String bootClassPath = System.getProperty("java.boot.class.path"); 1421 if (bootClassPath != null) { 1422 String[] paths = splitString(bootClassPath, ':'); 1423 for (int i=0; i<paths.length; i++) { 1424 alreadyDexOpted.add(paths[i]); 1425 } 1426 } else { 1427 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1428 } 1429 1430 boolean didDexOptLibraryOrTool = false; 1431 1432 final List<String> instructionSets = getAllInstructionSets(); 1433 1434 /** 1435 * Ensure all external libraries have had dexopt run on them. 1436 */ 1437 if (mSharedLibraries.size() > 0) { 1438 // NOTE: For now, we're compiling these system "shared libraries" 1439 // (and framework jars) into all available architectures. It's possible 1440 // to compile them only when we come across an app that uses them (there's 1441 // already logic for that in scanPackageLI) but that adds some complexity. 1442 for (String instructionSet : instructionSets) { 1443 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1444 final String lib = libEntry.path; 1445 if (lib == null) { 1446 continue; 1447 } 1448 1449 try { 1450 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1451 alreadyDexOpted.add(lib); 1452 1453 // The list of "shared libraries" we have at this point is 1454 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1455 didDexOptLibraryOrTool = true; 1456 } 1457 } catch (FileNotFoundException e) { 1458 Slog.w(TAG, "Library not found: " + lib); 1459 } catch (IOException e) { 1460 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1461 + e.getMessage()); 1462 } 1463 } 1464 } 1465 } 1466 1467 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1468 1469 // Gross hack for now: we know this file doesn't contain any 1470 // code, so don't dexopt it to avoid the resulting log spew. 1471 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1472 1473 // Gross hack for now: we know this file is only part of 1474 // the boot class path for art, so don't dexopt it to 1475 // avoid the resulting log spew. 1476 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1477 1478 /** 1479 * And there are a number of commands implemented in Java, which 1480 * we currently need to do the dexopt on so that they can be 1481 * run from a non-root shell. 1482 */ 1483 String[] frameworkFiles = frameworkDir.list(); 1484 if (frameworkFiles != null) { 1485 // TODO: We could compile these only for the most preferred ABI. We should 1486 // first double check that the dex files for these commands are not referenced 1487 // by other system apps. 1488 for (String instructionSet : instructionSets) { 1489 for (int i=0; i<frameworkFiles.length; i++) { 1490 File libPath = new File(frameworkDir, frameworkFiles[i]); 1491 String path = libPath.getPath(); 1492 // Skip the file if we already did it. 1493 if (alreadyDexOpted.contains(path)) { 1494 continue; 1495 } 1496 // Skip the file if it is not a type we want to dexopt. 1497 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1498 continue; 1499 } 1500 try { 1501 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1502 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1503 didDexOptLibraryOrTool = true; 1504 } 1505 } catch (FileNotFoundException e) { 1506 Slog.w(TAG, "Jar not found: " + path); 1507 } catch (IOException e) { 1508 Slog.w(TAG, "Exception reading jar: " + path, e); 1509 } 1510 } 1511 } 1512 } 1513 1514 if (didDexOptLibraryOrTool) { 1515 // If we dexopted a library or tool, then something on the system has 1516 // changed. Consider this significant, and wipe away all other 1517 // existing dexopt files to ensure we don't leave any dangling around. 1518 // 1519 // TODO: This should be revisited because it isn't as good an indicator 1520 // as it used to be. It used to include the boot classpath but at some point 1521 // DexFile.isDexOptNeeded started returning false for the boot 1522 // class path files in all cases. It is very possible in a 1523 // small maintenance release update that the library and tool 1524 // jars may be unchanged but APK could be removed resulting in 1525 // unused dalvik-cache files. 1526 for (String instructionSet : instructionSets) { 1527 mInstaller.pruneDexCache(instructionSet); 1528 } 1529 1530 // Additionally, delete all dex files from the root directory 1531 // since there shouldn't be any there anyway, unless we're upgrading 1532 // from an older OS version or a build that contained the "old" style 1533 // flat scheme. 1534 mInstaller.pruneDexCache("."); 1535 } 1536 1537 // Collect vendor overlay packages. 1538 // (Do this before scanning any apps.) 1539 // For security and version matching reason, only consider 1540 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1541 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1542 mVendorOverlayInstallObserver = new AppDirObserver( 1543 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1544 mVendorOverlayInstallObserver.startWatching(); 1545 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1547 1548 // Find base frameworks (resource packages without code). 1549 mFrameworkInstallObserver = new AppDirObserver( 1550 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1551 mFrameworkInstallObserver.startWatching(); 1552 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1553 | PackageParser.PARSE_IS_SYSTEM_DIR 1554 | PackageParser.PARSE_IS_PRIVILEGED, 1555 scanMode | SCAN_NO_DEX, 0); 1556 1557 // Collected privileged system packages. 1558 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1559 mPrivilegedInstallObserver = new AppDirObserver( 1560 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1561 mPrivilegedInstallObserver.startWatching(); 1562 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR 1564 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1565 1566 // Collect ordinary system packages. 1567 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1568 mSystemInstallObserver = new AppDirObserver( 1569 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1570 mSystemInstallObserver.startWatching(); 1571 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1572 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1573 1574 // Collect all vendor packages. 1575 File vendorAppDir = new File("/vendor/app"); 1576 try { 1577 vendorAppDir = vendorAppDir.getCanonicalFile(); 1578 } catch (IOException e) { 1579 // failed to look up canonical path, continue with original one 1580 } 1581 mVendorInstallObserver = new AppDirObserver( 1582 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1583 mVendorInstallObserver.startWatching(); 1584 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1585 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1586 1587 // Collect all OEM packages. 1588 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1589 mOemInstallObserver = new AppDirObserver( 1590 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1591 mOemInstallObserver.startWatching(); 1592 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1593 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1594 1595 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1596 mInstaller.moveFiles(); 1597 1598 // Prune any system packages that no longer exist. 1599 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1600 if (!mOnlyCore) { 1601 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1602 while (psit.hasNext()) { 1603 PackageSetting ps = psit.next(); 1604 1605 /* 1606 * If this is not a system app, it can't be a 1607 * disable system app. 1608 */ 1609 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1610 continue; 1611 } 1612 1613 /* 1614 * If the package is scanned, it's not erased. 1615 */ 1616 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1617 if (scannedPkg != null) { 1618 /* 1619 * If the system app is both scanned and in the 1620 * disabled packages list, then it must have been 1621 * added via OTA. Remove it from the currently 1622 * scanned package so the previously user-installed 1623 * application can be scanned. 1624 */ 1625 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1626 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1627 + "; removing system app"); 1628 removePackageLI(ps, true); 1629 } 1630 1631 continue; 1632 } 1633 1634 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1635 psit.remove(); 1636 String msg = "System package " + ps.name 1637 + " no longer exists; wiping its data"; 1638 reportSettingsProblem(Log.WARN, msg); 1639 removeDataDirsLI(ps.name); 1640 } else { 1641 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1642 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1643 possiblyDeletedUpdatedSystemApps.add(ps.name); 1644 } 1645 } 1646 } 1647 } 1648 1649 //look for any incomplete package installations 1650 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1651 //clean up list 1652 for(int i = 0; i < deletePkgsList.size(); i++) { 1653 //clean up here 1654 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1655 } 1656 //delete tmp files 1657 deleteTempPackageFiles(); 1658 1659 // Remove any shared userIDs that have no associated packages 1660 mSettings.pruneSharedUsersLPw(); 1661 1662 if (!mOnlyCore) { 1663 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1664 SystemClock.uptimeMillis()); 1665 mAppInstallObserver = new AppDirObserver( 1666 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1667 mAppInstallObserver.startWatching(); 1668 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1669 1670 mDrmAppInstallObserver = new AppDirObserver( 1671 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1672 mDrmAppInstallObserver.startWatching(); 1673 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1674 scanMode, 0); 1675 1676 /** 1677 * Remove disable package settings for any updated system 1678 * apps that were removed via an OTA. If they're not a 1679 * previously-updated app, remove them completely. 1680 * Otherwise, just revoke their system-level permissions. 1681 */ 1682 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1683 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1684 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1685 1686 String msg; 1687 if (deletedPkg == null) { 1688 msg = "Updated system package " + deletedAppName 1689 + " no longer exists; wiping its data"; 1690 removeDataDirsLI(deletedAppName); 1691 } else { 1692 msg = "Updated system app + " + deletedAppName 1693 + " no longer present; removing system privileges for " 1694 + deletedAppName; 1695 1696 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1697 1698 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1699 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1700 } 1701 reportSettingsProblem(Log.WARN, msg); 1702 } 1703 } else { 1704 mAppInstallObserver = null; 1705 mDrmAppInstallObserver = null; 1706 } 1707 1708 // Now that we know all of the shared libraries, update all clients to have 1709 // the correct library paths. 1710 updateAllSharedLibrariesLPw(); 1711 1712 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1713 // NOTE: We ignore potential failures here during a system scan (like 1714 // the rest of the commands above) because there's precious little we 1715 // can do about it. A settings error is reported, though. 1716 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1717 false /* force dexopt */, false /* defer dexopt */); 1718 } 1719 1720 // Now that we know all the packages we are keeping, 1721 // read and update their last usage times. 1722 mPackageUsage.readLP(); 1723 1724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1725 SystemClock.uptimeMillis()); 1726 Slog.i(TAG, "Time to scan packages: " 1727 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1728 + " seconds"); 1729 1730 // If the platform SDK has changed since the last time we booted, 1731 // we need to re-grant app permission to catch any new ones that 1732 // appear. This is really a hack, and means that apps can in some 1733 // cases get permissions that the user didn't initially explicitly 1734 // allow... it would be nice to have some better way to handle 1735 // this situation. 1736 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1737 != mSdkVersion; 1738 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1739 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1740 + "; regranting permissions for internal storage"); 1741 mSettings.mInternalSdkPlatform = mSdkVersion; 1742 1743 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1744 | (regrantPermissions 1745 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1746 : 0)); 1747 1748 // If this is the first boot, and it is a normal boot, then 1749 // we need to initialize the default preferred apps. 1750 if (!mRestoredSettings && !onlyCore) { 1751 mSettings.readDefaultPreferredAppsLPw(this, 0); 1752 } 1753 1754 // If this is first boot after an OTA, and a normal boot, then 1755 // we need to clear code cache directories. 1756 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1757 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1758 for (String pkgName : mSettings.mPackages.keySet()) { 1759 deleteCodeCacheDirsLI(pkgName); 1760 } 1761 mSettings.mFingerprint = Build.FINGERPRINT; 1762 } 1763 1764 // All the changes are done during package scanning. 1765 mSettings.updateInternalDatabaseVersion(); 1766 1767 // can downgrade to reader 1768 mSettings.writeLPr(); 1769 1770 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1771 SystemClock.uptimeMillis()); 1772 1773 1774 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1775 } // synchronized (mPackages) 1776 } // synchronized (mInstallLock) 1777 1778 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1779 1780 // Now after opening every single application zip, make sure they 1781 // are all flushed. Not really needed, but keeps things nice and 1782 // tidy. 1783 Runtime.getRuntime().gc(); 1784 } 1785 1786 @Override 1787 public boolean isFirstBoot() { 1788 return !mRestoredSettings; 1789 } 1790 1791 @Override 1792 public boolean isOnlyCoreApps() { 1793 return mOnlyCore; 1794 } 1795 1796 private String getRequiredVerifierLPr() { 1797 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1798 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1799 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1800 1801 String requiredVerifier = null; 1802 1803 final int N = receivers.size(); 1804 for (int i = 0; i < N; i++) { 1805 final ResolveInfo info = receivers.get(i); 1806 1807 if (info.activityInfo == null) { 1808 continue; 1809 } 1810 1811 final String packageName = info.activityInfo.packageName; 1812 1813 final PackageSetting ps = mSettings.mPackages.get(packageName); 1814 if (ps == null) { 1815 continue; 1816 } 1817 1818 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1819 if (!gp.grantedPermissions 1820 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1821 continue; 1822 } 1823 1824 if (requiredVerifier != null) { 1825 throw new RuntimeException("There can be only one required verifier"); 1826 } 1827 1828 requiredVerifier = packageName; 1829 } 1830 1831 return requiredVerifier; 1832 } 1833 1834 @Override 1835 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1836 throws RemoteException { 1837 try { 1838 return super.onTransact(code, data, reply, flags); 1839 } catch (RuntimeException e) { 1840 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1841 Slog.wtf(TAG, "Package Manager Crash", e); 1842 } 1843 throw e; 1844 } 1845 } 1846 1847 void cleanupInstallFailedPackage(PackageSetting ps) { 1848 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1849 removeDataDirsLI(ps.name); 1850 1851 // TODO: try cleaning up codePath directory contents first, since it 1852 // might be a cluster 1853 1854 if (ps.codePath != null) { 1855 if (!ps.codePath.delete()) { 1856 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1857 } 1858 } 1859 if (ps.resourcePath != null) { 1860 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1861 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1862 } 1863 } 1864 mSettings.removePackageLPw(ps.name); 1865 } 1866 1867 static int[] appendInts(int[] cur, int[] add) { 1868 if (add == null) return cur; 1869 if (cur == null) return add; 1870 final int N = add.length; 1871 for (int i=0; i<N; i++) { 1872 cur = appendInt(cur, add[i]); 1873 } 1874 return cur; 1875 } 1876 1877 static int[] removeInts(int[] cur, int[] rem) { 1878 if (rem == null) return cur; 1879 if (cur == null) return cur; 1880 final int N = rem.length; 1881 for (int i=0; i<N; i++) { 1882 cur = removeInt(cur, rem[i]); 1883 } 1884 return cur; 1885 } 1886 1887 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1888 if (!sUserManager.exists(userId)) return null; 1889 final PackageSetting ps = (PackageSetting) p.mExtras; 1890 if (ps == null) { 1891 return null; 1892 } 1893 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1894 final PackageUserState state = ps.readUserState(userId); 1895 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1896 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1897 state, userId); 1898 } 1899 1900 @Override 1901 public boolean isPackageAvailable(String packageName, int userId) { 1902 if (!sUserManager.exists(userId)) return false; 1903 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1904 synchronized (mPackages) { 1905 PackageParser.Package p = mPackages.get(packageName); 1906 if (p != null) { 1907 final PackageSetting ps = (PackageSetting) p.mExtras; 1908 if (ps != null) { 1909 final PackageUserState state = ps.readUserState(userId); 1910 if (state != null) { 1911 return PackageParser.isAvailable(state); 1912 } 1913 } 1914 } 1915 } 1916 return false; 1917 } 1918 1919 @Override 1920 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1921 if (!sUserManager.exists(userId)) return null; 1922 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1923 // reader 1924 synchronized (mPackages) { 1925 PackageParser.Package p = mPackages.get(packageName); 1926 if (DEBUG_PACKAGE_INFO) 1927 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1928 if (p != null) { 1929 return generatePackageInfo(p, flags, userId); 1930 } 1931 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1932 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1933 } 1934 } 1935 return null; 1936 } 1937 1938 @Override 1939 public String[] currentToCanonicalPackageNames(String[] names) { 1940 String[] out = new String[names.length]; 1941 // reader 1942 synchronized (mPackages) { 1943 for (int i=names.length-1; i>=0; i--) { 1944 PackageSetting ps = mSettings.mPackages.get(names[i]); 1945 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1946 } 1947 } 1948 return out; 1949 } 1950 1951 @Override 1952 public String[] canonicalToCurrentPackageNames(String[] names) { 1953 String[] out = new String[names.length]; 1954 // reader 1955 synchronized (mPackages) { 1956 for (int i=names.length-1; i>=0; i--) { 1957 String cur = mSettings.mRenamedPackages.get(names[i]); 1958 out[i] = cur != null ? cur : names[i]; 1959 } 1960 } 1961 return out; 1962 } 1963 1964 @Override 1965 public int getPackageUid(String packageName, int userId) { 1966 if (!sUserManager.exists(userId)) return -1; 1967 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1968 // reader 1969 synchronized (mPackages) { 1970 PackageParser.Package p = mPackages.get(packageName); 1971 if(p != null) { 1972 return UserHandle.getUid(userId, p.applicationInfo.uid); 1973 } 1974 PackageSetting ps = mSettings.mPackages.get(packageName); 1975 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1976 return -1; 1977 } 1978 p = ps.pkg; 1979 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1980 } 1981 } 1982 1983 @Override 1984 public int[] getPackageGids(String packageName) { 1985 // reader 1986 synchronized (mPackages) { 1987 PackageParser.Package p = mPackages.get(packageName); 1988 if (DEBUG_PACKAGE_INFO) 1989 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1990 if (p != null) { 1991 final PackageSetting ps = (PackageSetting)p.mExtras; 1992 return ps.getGids(); 1993 } 1994 } 1995 // stupid thing to indicate an error. 1996 return new int[0]; 1997 } 1998 1999 static final PermissionInfo generatePermissionInfo( 2000 BasePermission bp, int flags) { 2001 if (bp.perm != null) { 2002 return PackageParser.generatePermissionInfo(bp.perm, flags); 2003 } 2004 PermissionInfo pi = new PermissionInfo(); 2005 pi.name = bp.name; 2006 pi.packageName = bp.sourcePackage; 2007 pi.nonLocalizedLabel = bp.name; 2008 pi.protectionLevel = bp.protectionLevel; 2009 return pi; 2010 } 2011 2012 @Override 2013 public PermissionInfo getPermissionInfo(String name, int flags) { 2014 // reader 2015 synchronized (mPackages) { 2016 final BasePermission p = mSettings.mPermissions.get(name); 2017 if (p != null) { 2018 return generatePermissionInfo(p, flags); 2019 } 2020 return null; 2021 } 2022 } 2023 2024 @Override 2025 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2026 // reader 2027 synchronized (mPackages) { 2028 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2029 for (BasePermission p : mSettings.mPermissions.values()) { 2030 if (group == null) { 2031 if (p.perm == null || p.perm.info.group == null) { 2032 out.add(generatePermissionInfo(p, flags)); 2033 } 2034 } else { 2035 if (p.perm != null && group.equals(p.perm.info.group)) { 2036 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2037 } 2038 } 2039 } 2040 2041 if (out.size() > 0) { 2042 return out; 2043 } 2044 return mPermissionGroups.containsKey(group) ? out : null; 2045 } 2046 } 2047 2048 @Override 2049 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2050 // reader 2051 synchronized (mPackages) { 2052 return PackageParser.generatePermissionGroupInfo( 2053 mPermissionGroups.get(name), flags); 2054 } 2055 } 2056 2057 @Override 2058 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2059 // reader 2060 synchronized (mPackages) { 2061 final int N = mPermissionGroups.size(); 2062 ArrayList<PermissionGroupInfo> out 2063 = new ArrayList<PermissionGroupInfo>(N); 2064 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2065 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2066 } 2067 return out; 2068 } 2069 } 2070 2071 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2072 int userId) { 2073 if (!sUserManager.exists(userId)) return null; 2074 PackageSetting ps = mSettings.mPackages.get(packageName); 2075 if (ps != null) { 2076 if (ps.pkg == null) { 2077 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2078 flags, userId); 2079 if (pInfo != null) { 2080 return pInfo.applicationInfo; 2081 } 2082 return null; 2083 } 2084 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2085 ps.readUserState(userId), userId); 2086 } 2087 return null; 2088 } 2089 2090 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2091 int userId) { 2092 if (!sUserManager.exists(userId)) return null; 2093 PackageSetting ps = mSettings.mPackages.get(packageName); 2094 if (ps != null) { 2095 PackageParser.Package pkg = ps.pkg; 2096 if (pkg == null) { 2097 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2098 return null; 2099 } 2100 // Only data remains, so we aren't worried about code paths 2101 pkg = new PackageParser.Package(packageName); 2102 pkg.applicationInfo.packageName = packageName; 2103 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2104 pkg.applicationInfo.dataDir = 2105 getDataPathForPackage(packageName, 0).getPath(); 2106 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2107 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2108 } 2109 return generatePackageInfo(pkg, flags, userId); 2110 } 2111 return null; 2112 } 2113 2114 @Override 2115 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2116 if (!sUserManager.exists(userId)) return null; 2117 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2118 // writer 2119 synchronized (mPackages) { 2120 PackageParser.Package p = mPackages.get(packageName); 2121 if (DEBUG_PACKAGE_INFO) Log.v( 2122 TAG, "getApplicationInfo " + packageName 2123 + ": " + p); 2124 if (p != null) { 2125 PackageSetting ps = mSettings.mPackages.get(packageName); 2126 if (ps == null) return null; 2127 // Note: isEnabledLP() does not apply here - always return info 2128 return PackageParser.generateApplicationInfo( 2129 p, flags, ps.readUserState(userId), userId); 2130 } 2131 if ("android".equals(packageName)||"system".equals(packageName)) { 2132 return mAndroidApplication; 2133 } 2134 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2135 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2136 } 2137 } 2138 return null; 2139 } 2140 2141 2142 @Override 2143 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2144 mContext.enforceCallingOrSelfPermission( 2145 android.Manifest.permission.CLEAR_APP_CACHE, null); 2146 // Queue up an async operation since clearing cache may take a little while. 2147 mHandler.post(new Runnable() { 2148 public void run() { 2149 mHandler.removeCallbacks(this); 2150 int retCode = -1; 2151 synchronized (mInstallLock) { 2152 retCode = mInstaller.freeCache(freeStorageSize); 2153 if (retCode < 0) { 2154 Slog.w(TAG, "Couldn't clear application caches"); 2155 } 2156 } 2157 if (observer != null) { 2158 try { 2159 observer.onRemoveCompleted(null, (retCode >= 0)); 2160 } catch (RemoteException e) { 2161 Slog.w(TAG, "RemoveException when invoking call back"); 2162 } 2163 } 2164 } 2165 }); 2166 } 2167 2168 @Override 2169 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2170 mContext.enforceCallingOrSelfPermission( 2171 android.Manifest.permission.CLEAR_APP_CACHE, null); 2172 // Queue up an async operation since clearing cache may take a little while. 2173 mHandler.post(new Runnable() { 2174 public void run() { 2175 mHandler.removeCallbacks(this); 2176 int retCode = -1; 2177 synchronized (mInstallLock) { 2178 retCode = mInstaller.freeCache(freeStorageSize); 2179 if (retCode < 0) { 2180 Slog.w(TAG, "Couldn't clear application caches"); 2181 } 2182 } 2183 if(pi != null) { 2184 try { 2185 // Callback via pending intent 2186 int code = (retCode >= 0) ? 1 : 0; 2187 pi.sendIntent(null, code, null, 2188 null, null); 2189 } catch (SendIntentException e1) { 2190 Slog.i(TAG, "Failed to send pending intent"); 2191 } 2192 } 2193 } 2194 }); 2195 } 2196 2197 void freeStorage(long freeStorageSize) throws IOException { 2198 synchronized (mInstallLock) { 2199 if (mInstaller.freeCache(freeStorageSize) < 0) { 2200 throw new IOException("Failed to free enough space"); 2201 } 2202 } 2203 } 2204 2205 @Override 2206 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2207 if (!sUserManager.exists(userId)) return null; 2208 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2209 synchronized (mPackages) { 2210 PackageParser.Activity a = mActivities.mActivities.get(component); 2211 2212 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + 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 if (mResolveComponentName.equals(component)) { 2220 return mResolveActivity; 2221 } 2222 } 2223 return null; 2224 } 2225 2226 @Override 2227 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2228 String resolvedType) { 2229 synchronized (mPackages) { 2230 PackageParser.Activity a = mActivities.mActivities.get(component); 2231 if (a == null) { 2232 return false; 2233 } 2234 for (int i=0; i<a.intents.size(); i++) { 2235 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2236 intent.getData(), intent.getCategories(), TAG) >= 0) { 2237 return true; 2238 } 2239 } 2240 return false; 2241 } 2242 } 2243 2244 @Override 2245 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2246 if (!sUserManager.exists(userId)) return null; 2247 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2248 synchronized (mPackages) { 2249 PackageParser.Activity a = mReceivers.mActivities.get(component); 2250 if (DEBUG_PACKAGE_INFO) Log.v( 2251 TAG, "getReceiverInfo " + component + ": " + a); 2252 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2253 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2254 if (ps == null) return null; 2255 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2256 userId); 2257 } 2258 } 2259 return null; 2260 } 2261 2262 @Override 2263 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2264 if (!sUserManager.exists(userId)) return null; 2265 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2266 synchronized (mPackages) { 2267 PackageParser.Service s = mServices.mServices.get(component); 2268 if (DEBUG_PACKAGE_INFO) Log.v( 2269 TAG, "getServiceInfo " + component + ": " + s); 2270 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2271 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2272 if (ps == null) return null; 2273 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2274 userId); 2275 } 2276 } 2277 return null; 2278 } 2279 2280 @Override 2281 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2282 if (!sUserManager.exists(userId)) return null; 2283 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2284 synchronized (mPackages) { 2285 PackageParser.Provider p = mProviders.mProviders.get(component); 2286 if (DEBUG_PACKAGE_INFO) Log.v( 2287 TAG, "getProviderInfo " + component + ": " + p); 2288 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2289 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2290 if (ps == null) return null; 2291 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2292 userId); 2293 } 2294 } 2295 return null; 2296 } 2297 2298 @Override 2299 public String[] getSystemSharedLibraryNames() { 2300 Set<String> libSet; 2301 synchronized (mPackages) { 2302 libSet = mSharedLibraries.keySet(); 2303 int size = libSet.size(); 2304 if (size > 0) { 2305 String[] libs = new String[size]; 2306 libSet.toArray(libs); 2307 return libs; 2308 } 2309 } 2310 return null; 2311 } 2312 2313 @Override 2314 public FeatureInfo[] getSystemAvailableFeatures() { 2315 Collection<FeatureInfo> featSet; 2316 synchronized (mPackages) { 2317 featSet = mAvailableFeatures.values(); 2318 int size = featSet.size(); 2319 if (size > 0) { 2320 FeatureInfo[] features = new FeatureInfo[size+1]; 2321 featSet.toArray(features); 2322 FeatureInfo fi = new FeatureInfo(); 2323 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2324 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2325 features[size] = fi; 2326 return features; 2327 } 2328 } 2329 return null; 2330 } 2331 2332 @Override 2333 public boolean hasSystemFeature(String name) { 2334 synchronized (mPackages) { 2335 return mAvailableFeatures.containsKey(name); 2336 } 2337 } 2338 2339 private void checkValidCaller(int uid, int userId) { 2340 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2341 return; 2342 2343 throw new SecurityException("Caller uid=" + uid 2344 + " is not privileged to communicate with user=" + userId); 2345 } 2346 2347 @Override 2348 public int checkPermission(String permName, String pkgName) { 2349 synchronized (mPackages) { 2350 PackageParser.Package p = mPackages.get(pkgName); 2351 if (p != null && p.mExtras != null) { 2352 PackageSetting ps = (PackageSetting)p.mExtras; 2353 if (ps.sharedUser != null) { 2354 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2355 return PackageManager.PERMISSION_GRANTED; 2356 } 2357 } else if (ps.grantedPermissions.contains(permName)) { 2358 return PackageManager.PERMISSION_GRANTED; 2359 } 2360 } 2361 } 2362 return PackageManager.PERMISSION_DENIED; 2363 } 2364 2365 @Override 2366 public int checkUidPermission(String permName, int uid) { 2367 synchronized (mPackages) { 2368 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2369 if (obj != null) { 2370 GrantedPermissions gp = (GrantedPermissions)obj; 2371 if (gp.grantedPermissions.contains(permName)) { 2372 return PackageManager.PERMISSION_GRANTED; 2373 } 2374 } else { 2375 HashSet<String> perms = mSystemPermissions.get(uid); 2376 if (perms != null && perms.contains(permName)) { 2377 return PackageManager.PERMISSION_GRANTED; 2378 } 2379 } 2380 } 2381 return PackageManager.PERMISSION_DENIED; 2382 } 2383 2384 /** 2385 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2386 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2387 * @param message the message to log on security exception 2388 */ 2389 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2390 String message) { 2391 if (userId < 0) { 2392 throw new IllegalArgumentException("Invalid userId " + userId); 2393 } 2394 if (userId == UserHandle.getUserId(callingUid)) return; 2395 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2396 if (requireFullPermission) { 2397 mContext.enforceCallingOrSelfPermission( 2398 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2399 } else { 2400 try { 2401 mContext.enforceCallingOrSelfPermission( 2402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2403 } catch (SecurityException se) { 2404 mContext.enforceCallingOrSelfPermission( 2405 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2406 } 2407 } 2408 } 2409 } 2410 2411 private BasePermission findPermissionTreeLP(String permName) { 2412 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2413 if (permName.startsWith(bp.name) && 2414 permName.length() > bp.name.length() && 2415 permName.charAt(bp.name.length()) == '.') { 2416 return bp; 2417 } 2418 } 2419 return null; 2420 } 2421 2422 private BasePermission checkPermissionTreeLP(String permName) { 2423 if (permName != null) { 2424 BasePermission bp = findPermissionTreeLP(permName); 2425 if (bp != null) { 2426 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2427 return bp; 2428 } 2429 throw new SecurityException("Calling uid " 2430 + Binder.getCallingUid() 2431 + " is not allowed to add to permission tree " 2432 + bp.name + " owned by uid " + bp.uid); 2433 } 2434 } 2435 throw new SecurityException("No permission tree found for " + permName); 2436 } 2437 2438 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2439 if (s1 == null) { 2440 return s2 == null; 2441 } 2442 if (s2 == null) { 2443 return false; 2444 } 2445 if (s1.getClass() != s2.getClass()) { 2446 return false; 2447 } 2448 return s1.equals(s2); 2449 } 2450 2451 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2452 if (pi1.icon != pi2.icon) return false; 2453 if (pi1.logo != pi2.logo) return false; 2454 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2455 if (!compareStrings(pi1.name, pi2.name)) return false; 2456 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2457 // We'll take care of setting this one. 2458 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2459 // These are not currently stored in settings. 2460 //if (!compareStrings(pi1.group, pi2.group)) return false; 2461 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2462 //if (pi1.labelRes != pi2.labelRes) return false; 2463 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2464 return true; 2465 } 2466 2467 int permissionInfoFootprint(PermissionInfo info) { 2468 int size = info.name.length(); 2469 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2470 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2471 return size; 2472 } 2473 2474 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2475 int size = 0; 2476 for (BasePermission perm : mSettings.mPermissions.values()) { 2477 if (perm.uid == tree.uid) { 2478 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2479 } 2480 } 2481 return size; 2482 } 2483 2484 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2485 // We calculate the max size of permissions defined by this uid and throw 2486 // if that plus the size of 'info' would exceed our stated maximum. 2487 if (tree.uid != Process.SYSTEM_UID) { 2488 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2489 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2490 throw new SecurityException("Permission tree size cap exceeded"); 2491 } 2492 } 2493 } 2494 2495 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2496 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2497 throw new SecurityException("Label must be specified in permission"); 2498 } 2499 BasePermission tree = checkPermissionTreeLP(info.name); 2500 BasePermission bp = mSettings.mPermissions.get(info.name); 2501 boolean added = bp == null; 2502 boolean changed = true; 2503 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2504 if (added) { 2505 enforcePermissionCapLocked(info, tree); 2506 bp = new BasePermission(info.name, tree.sourcePackage, 2507 BasePermission.TYPE_DYNAMIC); 2508 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2509 throw new SecurityException( 2510 "Not allowed to modify non-dynamic permission " 2511 + info.name); 2512 } else { 2513 if (bp.protectionLevel == fixedLevel 2514 && bp.perm.owner.equals(tree.perm.owner) 2515 && bp.uid == tree.uid 2516 && comparePermissionInfos(bp.perm.info, info)) { 2517 changed = false; 2518 } 2519 } 2520 bp.protectionLevel = fixedLevel; 2521 info = new PermissionInfo(info); 2522 info.protectionLevel = fixedLevel; 2523 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2524 bp.perm.info.packageName = tree.perm.info.packageName; 2525 bp.uid = tree.uid; 2526 if (added) { 2527 mSettings.mPermissions.put(info.name, bp); 2528 } 2529 if (changed) { 2530 if (!async) { 2531 mSettings.writeLPr(); 2532 } else { 2533 scheduleWriteSettingsLocked(); 2534 } 2535 } 2536 return added; 2537 } 2538 2539 @Override 2540 public boolean addPermission(PermissionInfo info) { 2541 synchronized (mPackages) { 2542 return addPermissionLocked(info, false); 2543 } 2544 } 2545 2546 @Override 2547 public boolean addPermissionAsync(PermissionInfo info) { 2548 synchronized (mPackages) { 2549 return addPermissionLocked(info, true); 2550 } 2551 } 2552 2553 @Override 2554 public void removePermission(String name) { 2555 synchronized (mPackages) { 2556 checkPermissionTreeLP(name); 2557 BasePermission bp = mSettings.mPermissions.get(name); 2558 if (bp != null) { 2559 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2560 throw new SecurityException( 2561 "Not allowed to modify non-dynamic permission " 2562 + name); 2563 } 2564 mSettings.mPermissions.remove(name); 2565 mSettings.writeLPr(); 2566 } 2567 } 2568 } 2569 2570 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2571 int index = pkg.requestedPermissions.indexOf(bp.name); 2572 if (index == -1) { 2573 throw new SecurityException("Package " + pkg.packageName 2574 + " has not requested permission " + bp.name); 2575 } 2576 boolean isNormal = 2577 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2578 == PermissionInfo.PROTECTION_NORMAL); 2579 boolean isDangerous = 2580 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2581 == PermissionInfo.PROTECTION_DANGEROUS); 2582 boolean isDevelopment = 2583 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2584 2585 if (!isNormal && !isDangerous && !isDevelopment) { 2586 throw new SecurityException("Permission " + bp.name 2587 + " is not a changeable permission type"); 2588 } 2589 2590 if (isNormal || isDangerous) { 2591 if (pkg.requestedPermissionsRequired.get(index)) { 2592 throw new SecurityException("Can't change " + bp.name 2593 + ". It is required by the application"); 2594 } 2595 } 2596 } 2597 2598 @Override 2599 public void grantPermission(String packageName, String permissionName) { 2600 mContext.enforceCallingOrSelfPermission( 2601 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2602 synchronized (mPackages) { 2603 final PackageParser.Package pkg = mPackages.get(packageName); 2604 if (pkg == null) { 2605 throw new IllegalArgumentException("Unknown package: " + packageName); 2606 } 2607 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2608 if (bp == null) { 2609 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2610 } 2611 2612 checkGrantRevokePermissions(pkg, bp); 2613 2614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2615 if (ps == null) { 2616 return; 2617 } 2618 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2619 if (gp.grantedPermissions.add(permissionName)) { 2620 if (ps.haveGids) { 2621 gp.gids = appendInts(gp.gids, bp.gids); 2622 } 2623 mSettings.writeLPr(); 2624 } 2625 } 2626 } 2627 2628 @Override 2629 public void revokePermission(String packageName, String permissionName) { 2630 int changedAppId = -1; 2631 2632 synchronized (mPackages) { 2633 final PackageParser.Package pkg = mPackages.get(packageName); 2634 if (pkg == null) { 2635 throw new IllegalArgumentException("Unknown package: " + packageName); 2636 } 2637 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2638 mContext.enforceCallingOrSelfPermission( 2639 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2640 } 2641 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2642 if (bp == null) { 2643 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2644 } 2645 2646 checkGrantRevokePermissions(pkg, bp); 2647 2648 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2649 if (ps == null) { 2650 return; 2651 } 2652 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2653 if (gp.grantedPermissions.remove(permissionName)) { 2654 gp.grantedPermissions.remove(permissionName); 2655 if (ps.haveGids) { 2656 gp.gids = removeInts(gp.gids, bp.gids); 2657 } 2658 mSettings.writeLPr(); 2659 changedAppId = ps.appId; 2660 } 2661 } 2662 2663 if (changedAppId >= 0) { 2664 // We changed the perm on someone, kill its processes. 2665 IActivityManager am = ActivityManagerNative.getDefault(); 2666 if (am != null) { 2667 final int callingUserId = UserHandle.getCallingUserId(); 2668 final long ident = Binder.clearCallingIdentity(); 2669 try { 2670 //XXX we should only revoke for the calling user's app permissions, 2671 // but for now we impact all users. 2672 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2673 // "revoke " + permissionName); 2674 int[] users = sUserManager.getUserIds(); 2675 for (int user : users) { 2676 am.killUid(UserHandle.getUid(user, changedAppId), 2677 "revoke " + permissionName); 2678 } 2679 } catch (RemoteException e) { 2680 } finally { 2681 Binder.restoreCallingIdentity(ident); 2682 } 2683 } 2684 } 2685 } 2686 2687 @Override 2688 public boolean isProtectedBroadcast(String actionName) { 2689 synchronized (mPackages) { 2690 return mProtectedBroadcasts.contains(actionName); 2691 } 2692 } 2693 2694 @Override 2695 public int checkSignatures(String pkg1, String pkg2) { 2696 synchronized (mPackages) { 2697 final PackageParser.Package p1 = mPackages.get(pkg1); 2698 final PackageParser.Package p2 = mPackages.get(pkg2); 2699 if (p1 == null || p1.mExtras == null 2700 || p2 == null || p2.mExtras == null) { 2701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2702 } 2703 return compareSignatures(p1.mSignatures, p2.mSignatures); 2704 } 2705 } 2706 2707 @Override 2708 public int checkUidSignatures(int uid1, int uid2) { 2709 // Map to base uids. 2710 uid1 = UserHandle.getAppId(uid1); 2711 uid2 = UserHandle.getAppId(uid2); 2712 // reader 2713 synchronized (mPackages) { 2714 Signature[] s1; 2715 Signature[] s2; 2716 Object obj = mSettings.getUserIdLPr(uid1); 2717 if (obj != null) { 2718 if (obj instanceof SharedUserSetting) { 2719 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2720 } else if (obj instanceof PackageSetting) { 2721 s1 = ((PackageSetting)obj).signatures.mSignatures; 2722 } else { 2723 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2724 } 2725 } else { 2726 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2727 } 2728 obj = mSettings.getUserIdLPr(uid2); 2729 if (obj != null) { 2730 if (obj instanceof SharedUserSetting) { 2731 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2732 } else if (obj instanceof PackageSetting) { 2733 s2 = ((PackageSetting)obj).signatures.mSignatures; 2734 } else { 2735 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2736 } 2737 } else { 2738 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2739 } 2740 return compareSignatures(s1, s2); 2741 } 2742 } 2743 2744 /** 2745 * Compares two sets of signatures. Returns: 2746 * <br /> 2747 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2748 * <br /> 2749 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2750 * <br /> 2751 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2752 * <br /> 2753 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2754 * <br /> 2755 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2756 */ 2757 static int compareSignatures(Signature[] s1, Signature[] s2) { 2758 if (s1 == null) { 2759 return s2 == null 2760 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2761 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2762 } 2763 2764 if (s2 == null) { 2765 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2766 } 2767 2768 if (s1.length != s2.length) { 2769 return PackageManager.SIGNATURE_NO_MATCH; 2770 } 2771 2772 // Since both signature sets are of size 1, we can compare without HashSets. 2773 if (s1.length == 1) { 2774 return s1[0].equals(s2[0]) ? 2775 PackageManager.SIGNATURE_MATCH : 2776 PackageManager.SIGNATURE_NO_MATCH; 2777 } 2778 2779 HashSet<Signature> set1 = new HashSet<Signature>(); 2780 for (Signature sig : s1) { 2781 set1.add(sig); 2782 } 2783 HashSet<Signature> set2 = new HashSet<Signature>(); 2784 for (Signature sig : s2) { 2785 set2.add(sig); 2786 } 2787 // Make sure s2 contains all signatures in s1. 2788 if (set1.equals(set2)) { 2789 return PackageManager.SIGNATURE_MATCH; 2790 } 2791 return PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 /** 2795 * If the database version for this type of package (internal storage or 2796 * external storage) is less than the version where package signatures 2797 * were updated, return true. 2798 */ 2799 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2800 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2801 DatabaseVersion.SIGNATURE_END_ENTITY)) 2802 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2803 DatabaseVersion.SIGNATURE_END_ENTITY)); 2804 } 2805 2806 /** 2807 * Used for backward compatibility to make sure any packages with 2808 * certificate chains get upgraded to the new style. {@code existingSigs} 2809 * will be in the old format (since they were stored on disk from before the 2810 * system upgrade) and {@code scannedSigs} will be in the newer format. 2811 */ 2812 private int compareSignaturesCompat(PackageSignatures existingSigs, 2813 PackageParser.Package scannedPkg) { 2814 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2815 return PackageManager.SIGNATURE_NO_MATCH; 2816 } 2817 2818 HashSet<Signature> existingSet = new HashSet<Signature>(); 2819 for (Signature sig : existingSigs.mSignatures) { 2820 existingSet.add(sig); 2821 } 2822 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2823 for (Signature sig : scannedPkg.mSignatures) { 2824 try { 2825 Signature[] chainSignatures = sig.getChainSignatures(); 2826 for (Signature chainSig : chainSignatures) { 2827 scannedCompatSet.add(chainSig); 2828 } 2829 } catch (CertificateEncodingException e) { 2830 scannedCompatSet.add(sig); 2831 } 2832 } 2833 /* 2834 * Make sure the expanded scanned set contains all signatures in the 2835 * existing one. 2836 */ 2837 if (scannedCompatSet.equals(existingSet)) { 2838 // Migrate the old signatures to the new scheme. 2839 existingSigs.assignSignatures(scannedPkg.mSignatures); 2840 // The new KeySets will be re-added later in the scanning process. 2841 synchronized (mPackages) { 2842 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2843 } 2844 return PackageManager.SIGNATURE_MATCH; 2845 } 2846 return PackageManager.SIGNATURE_NO_MATCH; 2847 } 2848 2849 @Override 2850 public String[] getPackagesForUid(int uid) { 2851 uid = UserHandle.getAppId(uid); 2852 // reader 2853 synchronized (mPackages) { 2854 Object obj = mSettings.getUserIdLPr(uid); 2855 if (obj instanceof SharedUserSetting) { 2856 final SharedUserSetting sus = (SharedUserSetting) obj; 2857 final int N = sus.packages.size(); 2858 final String[] res = new String[N]; 2859 final Iterator<PackageSetting> it = sus.packages.iterator(); 2860 int i = 0; 2861 while (it.hasNext()) { 2862 res[i++] = it.next().name; 2863 } 2864 return res; 2865 } else if (obj instanceof PackageSetting) { 2866 final PackageSetting ps = (PackageSetting) obj; 2867 return new String[] { ps.name }; 2868 } 2869 } 2870 return null; 2871 } 2872 2873 @Override 2874 public String getNameForUid(int uid) { 2875 // reader 2876 synchronized (mPackages) { 2877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2878 if (obj instanceof SharedUserSetting) { 2879 final SharedUserSetting sus = (SharedUserSetting) obj; 2880 return sus.name + ":" + sus.userId; 2881 } else if (obj instanceof PackageSetting) { 2882 final PackageSetting ps = (PackageSetting) obj; 2883 return ps.name; 2884 } 2885 } 2886 return null; 2887 } 2888 2889 @Override 2890 public int getUidForSharedUser(String sharedUserName) { 2891 if(sharedUserName == null) { 2892 return -1; 2893 } 2894 // reader 2895 synchronized (mPackages) { 2896 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2897 if (suid == null) { 2898 return -1; 2899 } 2900 return suid.userId; 2901 } 2902 } 2903 2904 @Override 2905 public int getFlagsForUid(int uid) { 2906 synchronized (mPackages) { 2907 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2908 if (obj instanceof SharedUserSetting) { 2909 final SharedUserSetting sus = (SharedUserSetting) obj; 2910 return sus.pkgFlags; 2911 } else if (obj instanceof PackageSetting) { 2912 final PackageSetting ps = (PackageSetting) obj; 2913 return ps.pkgFlags; 2914 } 2915 } 2916 return 0; 2917 } 2918 2919 @Override 2920 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2921 int flags, int userId) { 2922 if (!sUserManager.exists(userId)) return null; 2923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2925 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2926 } 2927 2928 @Override 2929 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2930 IntentFilter filter, int match, ComponentName activity) { 2931 final int userId = UserHandle.getCallingUserId(); 2932 if (DEBUG_PREFERRED) { 2933 Log.v(TAG, "setLastChosenActivity intent=" + intent 2934 + " resolvedType=" + resolvedType 2935 + " flags=" + flags 2936 + " filter=" + filter 2937 + " match=" + match 2938 + " activity=" + activity); 2939 filter.dump(new PrintStreamPrinter(System.out), " "); 2940 } 2941 intent.setComponent(null); 2942 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2943 // Find any earlier preferred or last chosen entries and nuke them 2944 findPreferredActivity(intent, resolvedType, 2945 flags, query, 0, false, true, false, userId); 2946 // Add the new activity as the last chosen for this filter 2947 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2948 } 2949 2950 @Override 2951 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2952 final int userId = UserHandle.getCallingUserId(); 2953 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2954 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2955 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2956 false, false, false, userId); 2957 } 2958 2959 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2960 int flags, List<ResolveInfo> query, int userId) { 2961 if (query != null) { 2962 final int N = query.size(); 2963 if (N == 1) { 2964 return query.get(0); 2965 } else if (N > 1) { 2966 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2967 // If there is more than one activity with the same priority, 2968 // then let the user decide between them. 2969 ResolveInfo r0 = query.get(0); 2970 ResolveInfo r1 = query.get(1); 2971 if (DEBUG_INTENT_MATCHING || debug) { 2972 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2973 + r1.activityInfo.name + "=" + r1.priority); 2974 } 2975 // If the first activity has a higher priority, or a different 2976 // default, then it is always desireable to pick it. 2977 if (r0.priority != r1.priority 2978 || r0.preferredOrder != r1.preferredOrder 2979 || r0.isDefault != r1.isDefault) { 2980 return query.get(0); 2981 } 2982 // If we have saved a preference for a preferred activity for 2983 // this Intent, use that. 2984 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2985 flags, query, r0.priority, true, false, debug, userId); 2986 if (ri != null) { 2987 return ri; 2988 } 2989 if (userId != 0) { 2990 ri = new ResolveInfo(mResolveInfo); 2991 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2992 ri.activityInfo.applicationInfo = new ApplicationInfo( 2993 ri.activityInfo.applicationInfo); 2994 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2995 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2996 return ri; 2997 } 2998 return mResolveInfo; 2999 } 3000 } 3001 return null; 3002 } 3003 3004 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3005 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3006 final int N = query.size(); 3007 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3008 .get(userId); 3009 // Get the list of persistent preferred activities that handle the intent 3010 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3011 List<PersistentPreferredActivity> pprefs = ppir != null 3012 ? ppir.queryIntent(intent, resolvedType, 3013 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3014 : null; 3015 if (pprefs != null && pprefs.size() > 0) { 3016 final int M = pprefs.size(); 3017 for (int i=0; i<M; i++) { 3018 final PersistentPreferredActivity ppa = pprefs.get(i); 3019 if (DEBUG_PREFERRED || debug) { 3020 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3021 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3022 + "\n component=" + ppa.mComponent); 3023 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3024 } 3025 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3026 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3027 if (DEBUG_PREFERRED || debug) { 3028 Slog.v(TAG, "Found persistent preferred activity:"); 3029 if (ai != null) { 3030 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3031 } else { 3032 Slog.v(TAG, " null"); 3033 } 3034 } 3035 if (ai == null) { 3036 // This previously registered persistent preferred activity 3037 // component is no longer known. Ignore it and do NOT remove it. 3038 continue; 3039 } 3040 for (int j=0; j<N; j++) { 3041 final ResolveInfo ri = query.get(j); 3042 if (!ri.activityInfo.applicationInfo.packageName 3043 .equals(ai.applicationInfo.packageName)) { 3044 continue; 3045 } 3046 if (!ri.activityInfo.name.equals(ai.name)) { 3047 continue; 3048 } 3049 // Found a persistent preference that can handle the intent. 3050 if (DEBUG_PREFERRED || debug) { 3051 Slog.v(TAG, "Returning persistent preferred activity: " + 3052 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3053 } 3054 return ri; 3055 } 3056 } 3057 } 3058 return null; 3059 } 3060 3061 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3062 List<ResolveInfo> query, int priority, boolean always, 3063 boolean removeMatches, boolean debug, int userId) { 3064 if (!sUserManager.exists(userId)) return null; 3065 // writer 3066 synchronized (mPackages) { 3067 if (intent.getSelector() != null) { 3068 intent = intent.getSelector(); 3069 } 3070 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3071 3072 // Try to find a matching persistent preferred activity. 3073 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3074 debug, userId); 3075 3076 // If a persistent preferred activity matched, use it. 3077 if (pri != null) { 3078 return pri; 3079 } 3080 3081 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3082 // Get the list of preferred activities that handle the intent 3083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3084 List<PreferredActivity> prefs = pir != null 3085 ? pir.queryIntent(intent, resolvedType, 3086 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3087 : null; 3088 if (prefs != null && prefs.size() > 0) { 3089 // First figure out how good the original match set is. 3090 // We will only allow preferred activities that came 3091 // from the same match quality. 3092 int match = 0; 3093 3094 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3095 3096 final int N = query.size(); 3097 for (int j=0; j<N; j++) { 3098 final ResolveInfo ri = query.get(j); 3099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3100 + ": 0x" + Integer.toHexString(match)); 3101 if (ri.match > match) { 3102 match = ri.match; 3103 } 3104 } 3105 3106 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3107 + Integer.toHexString(match)); 3108 3109 match &= IntentFilter.MATCH_CATEGORY_MASK; 3110 final int M = prefs.size(); 3111 for (int i=0; i<M; i++) { 3112 final PreferredActivity pa = prefs.get(i); 3113 if (DEBUG_PREFERRED || debug) { 3114 Slog.v(TAG, "Checking PreferredActivity ds=" 3115 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3116 + "\n component=" + pa.mPref.mComponent); 3117 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3118 } 3119 if (pa.mPref.mMatch != match) { 3120 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3121 + Integer.toHexString(pa.mPref.mMatch)); 3122 continue; 3123 } 3124 // If it's not an "always" type preferred activity and that's what we're 3125 // looking for, skip it. 3126 if (always && !pa.mPref.mAlways) { 3127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3128 continue; 3129 } 3130 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3131 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3132 if (DEBUG_PREFERRED || debug) { 3133 Slog.v(TAG, "Found preferred activity:"); 3134 if (ai != null) { 3135 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3136 } else { 3137 Slog.v(TAG, " null"); 3138 } 3139 } 3140 if (ai == null) { 3141 // This previously registered preferred activity 3142 // component is no longer known. Most likely an update 3143 // to the app was installed and in the new version this 3144 // component no longer exists. Clean it up by removing 3145 // it from the preferred activities list, and skip it. 3146 Slog.w(TAG, "Removing dangling preferred activity: " 3147 + pa.mPref.mComponent); 3148 pir.removeFilter(pa); 3149 continue; 3150 } 3151 for (int j=0; j<N; j++) { 3152 final ResolveInfo ri = query.get(j); 3153 if (!ri.activityInfo.applicationInfo.packageName 3154 .equals(ai.applicationInfo.packageName)) { 3155 continue; 3156 } 3157 if (!ri.activityInfo.name.equals(ai.name)) { 3158 continue; 3159 } 3160 3161 if (removeMatches) { 3162 pir.removeFilter(pa); 3163 if (DEBUG_PREFERRED) { 3164 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3165 } 3166 break; 3167 } 3168 3169 // Okay we found a previously set preferred or last chosen app. 3170 // If the result set is different from when this 3171 // was created, we need to clear it and re-ask the 3172 // user their preference, if we're looking for an "always" type entry. 3173 if (always && !pa.mPref.sameSet(query, priority)) { 3174 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3175 + intent + " type " + resolvedType); 3176 if (DEBUG_PREFERRED) { 3177 Slog.v(TAG, "Removing preferred activity since set changed " 3178 + pa.mPref.mComponent); 3179 } 3180 pir.removeFilter(pa); 3181 // Re-add the filter as a "last chosen" entry (!always) 3182 PreferredActivity lastChosen = new PreferredActivity( 3183 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3184 pir.addFilter(lastChosen); 3185 mSettings.writePackageRestrictionsLPr(userId); 3186 return null; 3187 } 3188 3189 // Yay! Either the set matched or we're looking for the last chosen 3190 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3191 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3192 mSettings.writePackageRestrictionsLPr(userId); 3193 return ri; 3194 } 3195 } 3196 } 3197 mSettings.writePackageRestrictionsLPr(userId); 3198 } 3199 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3200 return null; 3201 } 3202 3203 /* 3204 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3205 */ 3206 @Override 3207 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3208 int targetUserId) { 3209 mContext.enforceCallingOrSelfPermission( 3210 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3211 List<CrossProfileIntentFilter> matches = 3212 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3213 if (matches != null) { 3214 int size = matches.size(); 3215 for (int i = 0; i < size; i++) { 3216 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3217 } 3218 } 3219 3220 ArrayList<String> packageNames = null; 3221 SparseArray<ArrayList<String>> fromSource = 3222 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3223 if (fromSource != null) { 3224 packageNames = fromSource.get(targetUserId); 3225 } 3226 if (packageNames.contains(intent.getPackage())) { 3227 return true; 3228 } 3229 // We need the package name, so we try to resolve with the loosest flags possible 3230 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3231 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3232 int count = resolveInfos.size(); 3233 for (int i = 0; i < count; i++) { 3234 ResolveInfo resolveInfo = resolveInfos.get(i); 3235 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3236 return true; 3237 } 3238 } 3239 return false; 3240 } 3241 3242 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3243 String resolvedType, int userId) { 3244 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3245 if (resolver != null) { 3246 return resolver.queryIntent(intent, resolvedType, false, userId); 3247 } 3248 return null; 3249 } 3250 3251 @Override 3252 public List<ResolveInfo> queryIntentActivities(Intent intent, 3253 String resolvedType, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3255 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3256 ComponentName comp = intent.getComponent(); 3257 if (comp == null) { 3258 if (intent.getSelector() != null) { 3259 intent = intent.getSelector(); 3260 comp = intent.getComponent(); 3261 } 3262 } 3263 3264 if (comp != null) { 3265 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3266 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3267 if (ai != null) { 3268 final ResolveInfo ri = new ResolveInfo(); 3269 ri.activityInfo = ai; 3270 list.add(ri); 3271 } 3272 return list; 3273 } 3274 3275 // reader 3276 synchronized (mPackages) { 3277 final String pkgName = intent.getPackage(); 3278 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3279 if (pkgName == null) { 3280 ResolveInfo resolveInfo = null; 3281 if (queryCrossProfile) { 3282 // Check if the intent needs to be forwarded to another user for this package 3283 ArrayList<ResolveInfo> crossProfileResult = 3284 queryIntentActivitiesCrossProfilePackage( 3285 intent, resolvedType, flags, userId); 3286 if (!crossProfileResult.isEmpty()) { 3287 // Skip the current profile 3288 return crossProfileResult; 3289 } 3290 List<CrossProfileIntentFilter> matchingFilters = 3291 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3292 // Check for results that need to skip the current profile. 3293 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3294 resolvedType, flags, userId); 3295 if (resolveInfo != null) { 3296 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3297 result.add(resolveInfo); 3298 return result; 3299 } 3300 // Check for cross profile results. 3301 resolveInfo = queryCrossProfileIntents( 3302 matchingFilters, intent, resolvedType, flags, userId); 3303 } 3304 // Check for results in the current profile. 3305 List<ResolveInfo> result = mActivities.queryIntent( 3306 intent, resolvedType, flags, userId); 3307 if (resolveInfo != null) { 3308 result.add(resolveInfo); 3309 } 3310 return result; 3311 } 3312 final PackageParser.Package pkg = mPackages.get(pkgName); 3313 if (pkg != null) { 3314 if (queryCrossProfile) { 3315 ArrayList<ResolveInfo> crossProfileResult = 3316 queryIntentActivitiesCrossProfilePackage( 3317 intent, resolvedType, flags, userId, pkg, pkgName); 3318 if (!crossProfileResult.isEmpty()) { 3319 // Skip the current profile 3320 return crossProfileResult; 3321 } 3322 } 3323 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3324 pkg.activities, userId); 3325 } 3326 return new ArrayList<ResolveInfo>(); 3327 } 3328 } 3329 3330 private ResolveInfo querySkipCurrentProfileIntents( 3331 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3332 int flags, int sourceUserId) { 3333 if (matchingFilters != null) { 3334 int size = matchingFilters.size(); 3335 for (int i = 0; i < size; i ++) { 3336 CrossProfileIntentFilter filter = matchingFilters.get(i); 3337 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3338 // Checking if there are activities in the target user that can handle the 3339 // intent. 3340 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3341 flags, sourceUserId); 3342 if (resolveInfo != null) { 3343 return resolveInfo; 3344 } 3345 } 3346 } 3347 } 3348 return null; 3349 } 3350 3351 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3352 Intent intent, String resolvedType, int flags, int userId) { 3353 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3354 SparseArray<ArrayList<String>> sourceForwardingInfo = 3355 mSettings.mCrossProfilePackageInfo.get(userId); 3356 if (sourceForwardingInfo != null) { 3357 int NI = sourceForwardingInfo.size(); 3358 for (int i = 0; i < NI; i++) { 3359 int targetUserId = sourceForwardingInfo.keyAt(i); 3360 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3361 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3362 intent, resolvedType, flags, targetUserId); 3363 int NJ = resolveInfos.size(); 3364 for (int j = 0; j < NJ; j++) { 3365 ResolveInfo resolveInfo = resolveInfos.get(j); 3366 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3367 matchingResolveInfos.add(createForwardingResolveInfo( 3368 resolveInfo.filter, userId, targetUserId)); 3369 } 3370 } 3371 } 3372 } 3373 return matchingResolveInfos; 3374 } 3375 3376 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3377 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3378 String packageName) { 3379 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3380 SparseArray<ArrayList<String>> sourceForwardingInfo = 3381 mSettings.mCrossProfilePackageInfo.get(userId); 3382 if (sourceForwardingInfo != null) { 3383 int NI = sourceForwardingInfo.size(); 3384 for (int i = 0; i < NI; i++) { 3385 int targetUserId = sourceForwardingInfo.keyAt(i); 3386 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3387 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3388 intent, resolvedType, flags, pkg.activities, targetUserId); 3389 int NJ = resolveInfos.size(); 3390 for (int j = 0; j < NJ; j++) { 3391 ResolveInfo resolveInfo = resolveInfos.get(j); 3392 matchingResolveInfos.add(createForwardingResolveInfo( 3393 resolveInfo.filter, userId, targetUserId)); 3394 } 3395 } 3396 } 3397 } 3398 return matchingResolveInfos; 3399 } 3400 3401 // Return matching ResolveInfo if any for skip current profile intent filters. 3402 private ResolveInfo queryCrossProfileIntents( 3403 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3404 int flags, int sourceUserId) { 3405 if (matchingFilters != null) { 3406 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3407 // match the same intent. For performance reasons, it is better not to 3408 // run queryIntent twice for the same userId 3409 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3410 int size = matchingFilters.size(); 3411 for (int i = 0; i < size; i++) { 3412 CrossProfileIntentFilter filter = matchingFilters.get(i); 3413 int targetUserId = filter.getTargetUserId(); 3414 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3415 && !alreadyTriedUserIds.get(targetUserId)) { 3416 // Checking if there are activities in the target user that can handle the 3417 // intent. 3418 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3419 flags, sourceUserId); 3420 if (resolveInfo != null) return resolveInfo; 3421 alreadyTriedUserIds.put(targetUserId, true); 3422 } 3423 } 3424 } 3425 return null; 3426 } 3427 3428 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3429 String resolvedType, int flags, int sourceUserId) { 3430 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3431 resolvedType, flags, filter.getTargetUserId()); 3432 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3433 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3434 } 3435 return null; 3436 } 3437 3438 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3439 int sourceUserId, int targetUserId) { 3440 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3441 String className; 3442 if (targetUserId == UserHandle.USER_OWNER) { 3443 className = FORWARD_INTENT_TO_USER_OWNER; 3444 } else { 3445 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3446 } 3447 ComponentName forwardingActivityComponentName = new ComponentName( 3448 mAndroidApplication.packageName, className); 3449 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3450 sourceUserId); 3451 if (targetUserId == UserHandle.USER_OWNER) { 3452 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3453 forwardingResolveInfo.noResourceId = true; 3454 } 3455 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3456 forwardingResolveInfo.priority = 0; 3457 forwardingResolveInfo.preferredOrder = 0; 3458 forwardingResolveInfo.match = 0; 3459 forwardingResolveInfo.isDefault = true; 3460 forwardingResolveInfo.filter = filter; 3461 forwardingResolveInfo.targetUserId = targetUserId; 3462 return forwardingResolveInfo; 3463 } 3464 3465 @Override 3466 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3467 Intent[] specifics, String[] specificTypes, Intent intent, 3468 String resolvedType, int flags, int userId) { 3469 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3471 "query intent activity options"); 3472 final String resultsAction = intent.getAction(); 3473 3474 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3475 | PackageManager.GET_RESOLVED_FILTER, userId); 3476 3477 if (DEBUG_INTENT_MATCHING) { 3478 Log.v(TAG, "Query " + intent + ": " + results); 3479 } 3480 3481 int specificsPos = 0; 3482 int N; 3483 3484 // todo: note that the algorithm used here is O(N^2). This 3485 // isn't a problem in our current environment, but if we start running 3486 // into situations where we have more than 5 or 10 matches then this 3487 // should probably be changed to something smarter... 3488 3489 // First we go through and resolve each of the specific items 3490 // that were supplied, taking care of removing any corresponding 3491 // duplicate items in the generic resolve list. 3492 if (specifics != null) { 3493 for (int i=0; i<specifics.length; i++) { 3494 final Intent sintent = specifics[i]; 3495 if (sintent == null) { 3496 continue; 3497 } 3498 3499 if (DEBUG_INTENT_MATCHING) { 3500 Log.v(TAG, "Specific #" + i + ": " + sintent); 3501 } 3502 3503 String action = sintent.getAction(); 3504 if (resultsAction != null && resultsAction.equals(action)) { 3505 // If this action was explicitly requested, then don't 3506 // remove things that have it. 3507 action = null; 3508 } 3509 3510 ResolveInfo ri = null; 3511 ActivityInfo ai = null; 3512 3513 ComponentName comp = sintent.getComponent(); 3514 if (comp == null) { 3515 ri = resolveIntent( 3516 sintent, 3517 specificTypes != null ? specificTypes[i] : null, 3518 flags, userId); 3519 if (ri == null) { 3520 continue; 3521 } 3522 if (ri == mResolveInfo) { 3523 // ACK! Must do something better with this. 3524 } 3525 ai = ri.activityInfo; 3526 comp = new ComponentName(ai.applicationInfo.packageName, 3527 ai.name); 3528 } else { 3529 ai = getActivityInfo(comp, flags, userId); 3530 if (ai == null) { 3531 continue; 3532 } 3533 } 3534 3535 // Look for any generic query activities that are duplicates 3536 // of this specific one, and remove them from the results. 3537 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3538 N = results.size(); 3539 int j; 3540 for (j=specificsPos; j<N; j++) { 3541 ResolveInfo sri = results.get(j); 3542 if ((sri.activityInfo.name.equals(comp.getClassName()) 3543 && sri.activityInfo.applicationInfo.packageName.equals( 3544 comp.getPackageName())) 3545 || (action != null && sri.filter.matchAction(action))) { 3546 results.remove(j); 3547 if (DEBUG_INTENT_MATCHING) Log.v( 3548 TAG, "Removing duplicate item from " + j 3549 + " due to specific " + specificsPos); 3550 if (ri == null) { 3551 ri = sri; 3552 } 3553 j--; 3554 N--; 3555 } 3556 } 3557 3558 // Add this specific item to its proper place. 3559 if (ri == null) { 3560 ri = new ResolveInfo(); 3561 ri.activityInfo = ai; 3562 } 3563 results.add(specificsPos, ri); 3564 ri.specificIndex = i; 3565 specificsPos++; 3566 } 3567 } 3568 3569 // Now we go through the remaining generic results and remove any 3570 // duplicate actions that are found here. 3571 N = results.size(); 3572 for (int i=specificsPos; i<N-1; i++) { 3573 final ResolveInfo rii = results.get(i); 3574 if (rii.filter == null) { 3575 continue; 3576 } 3577 3578 // Iterate over all of the actions of this result's intent 3579 // filter... typically this should be just one. 3580 final Iterator<String> it = rii.filter.actionsIterator(); 3581 if (it == null) { 3582 continue; 3583 } 3584 while (it.hasNext()) { 3585 final String action = it.next(); 3586 if (resultsAction != null && resultsAction.equals(action)) { 3587 // If this action was explicitly requested, then don't 3588 // remove things that have it. 3589 continue; 3590 } 3591 for (int j=i+1; j<N; j++) { 3592 final ResolveInfo rij = results.get(j); 3593 if (rij.filter != null && rij.filter.hasAction(action)) { 3594 results.remove(j); 3595 if (DEBUG_INTENT_MATCHING) Log.v( 3596 TAG, "Removing duplicate item from " + j 3597 + " due to action " + action + " at " + i); 3598 j--; 3599 N--; 3600 } 3601 } 3602 } 3603 3604 // If the caller didn't request filter information, drop it now 3605 // so we don't have to marshall/unmarshall it. 3606 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3607 rii.filter = null; 3608 } 3609 } 3610 3611 // Filter out the caller activity if so requested. 3612 if (caller != null) { 3613 N = results.size(); 3614 for (int i=0; i<N; i++) { 3615 ActivityInfo ainfo = results.get(i).activityInfo; 3616 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3617 && caller.getClassName().equals(ainfo.name)) { 3618 results.remove(i); 3619 break; 3620 } 3621 } 3622 } 3623 3624 // If the caller didn't request filter information, 3625 // drop them now so we don't have to 3626 // marshall/unmarshall it. 3627 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3628 N = results.size(); 3629 for (int i=0; i<N; i++) { 3630 results.get(i).filter = null; 3631 } 3632 } 3633 3634 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3635 return results; 3636 } 3637 3638 @Override 3639 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3640 int userId) { 3641 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3642 ComponentName comp = intent.getComponent(); 3643 if (comp == null) { 3644 if (intent.getSelector() != null) { 3645 intent = intent.getSelector(); 3646 comp = intent.getComponent(); 3647 } 3648 } 3649 if (comp != null) { 3650 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3651 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3652 if (ai != null) { 3653 ResolveInfo ri = new ResolveInfo(); 3654 ri.activityInfo = ai; 3655 list.add(ri); 3656 } 3657 return list; 3658 } 3659 3660 // reader 3661 synchronized (mPackages) { 3662 String pkgName = intent.getPackage(); 3663 if (pkgName == null) { 3664 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3665 } 3666 final PackageParser.Package pkg = mPackages.get(pkgName); 3667 if (pkg != null) { 3668 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3669 userId); 3670 } 3671 return null; 3672 } 3673 } 3674 3675 @Override 3676 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3677 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3678 if (!sUserManager.exists(userId)) return null; 3679 if (query != null) { 3680 if (query.size() >= 1) { 3681 // If there is more than one service with the same priority, 3682 // just arbitrarily pick the first one. 3683 return query.get(0); 3684 } 3685 } 3686 return null; 3687 } 3688 3689 @Override 3690 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3691 int userId) { 3692 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3693 ComponentName comp = intent.getComponent(); 3694 if (comp == null) { 3695 if (intent.getSelector() != null) { 3696 intent = intent.getSelector(); 3697 comp = intent.getComponent(); 3698 } 3699 } 3700 if (comp != null) { 3701 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3702 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3703 if (si != null) { 3704 final ResolveInfo ri = new ResolveInfo(); 3705 ri.serviceInfo = si; 3706 list.add(ri); 3707 } 3708 return list; 3709 } 3710 3711 // reader 3712 synchronized (mPackages) { 3713 String pkgName = intent.getPackage(); 3714 if (pkgName == null) { 3715 return mServices.queryIntent(intent, resolvedType, flags, userId); 3716 } 3717 final PackageParser.Package pkg = mPackages.get(pkgName); 3718 if (pkg != null) { 3719 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3720 userId); 3721 } 3722 return null; 3723 } 3724 } 3725 3726 @Override 3727 public List<ResolveInfo> queryIntentContentProviders( 3728 Intent intent, String resolvedType, int flags, int userId) { 3729 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3730 ComponentName comp = intent.getComponent(); 3731 if (comp == null) { 3732 if (intent.getSelector() != null) { 3733 intent = intent.getSelector(); 3734 comp = intent.getComponent(); 3735 } 3736 } 3737 if (comp != null) { 3738 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3739 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3740 if (pi != null) { 3741 final ResolveInfo ri = new ResolveInfo(); 3742 ri.providerInfo = pi; 3743 list.add(ri); 3744 } 3745 return list; 3746 } 3747 3748 // reader 3749 synchronized (mPackages) { 3750 String pkgName = intent.getPackage(); 3751 if (pkgName == null) { 3752 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3753 } 3754 final PackageParser.Package pkg = mPackages.get(pkgName); 3755 if (pkg != null) { 3756 return mProviders.queryIntentForPackage( 3757 intent, resolvedType, flags, pkg.providers, userId); 3758 } 3759 return null; 3760 } 3761 } 3762 3763 @Override 3764 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3765 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3766 3767 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3768 3769 // writer 3770 synchronized (mPackages) { 3771 ArrayList<PackageInfo> list; 3772 if (listUninstalled) { 3773 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3774 for (PackageSetting ps : mSettings.mPackages.values()) { 3775 PackageInfo pi; 3776 if (ps.pkg != null) { 3777 pi = generatePackageInfo(ps.pkg, flags, userId); 3778 } else { 3779 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3780 } 3781 if (pi != null) { 3782 list.add(pi); 3783 } 3784 } 3785 } else { 3786 list = new ArrayList<PackageInfo>(mPackages.size()); 3787 for (PackageParser.Package p : mPackages.values()) { 3788 PackageInfo pi = generatePackageInfo(p, flags, userId); 3789 if (pi != null) { 3790 list.add(pi); 3791 } 3792 } 3793 } 3794 3795 return new ParceledListSlice<PackageInfo>(list); 3796 } 3797 } 3798 3799 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3800 String[] permissions, boolean[] tmp, int flags, int userId) { 3801 int numMatch = 0; 3802 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3803 for (int i=0; i<permissions.length; i++) { 3804 if (gp.grantedPermissions.contains(permissions[i])) { 3805 tmp[i] = true; 3806 numMatch++; 3807 } else { 3808 tmp[i] = false; 3809 } 3810 } 3811 if (numMatch == 0) { 3812 return; 3813 } 3814 PackageInfo pi; 3815 if (ps.pkg != null) { 3816 pi = generatePackageInfo(ps.pkg, flags, userId); 3817 } else { 3818 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3819 } 3820 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3821 if (numMatch == permissions.length) { 3822 pi.requestedPermissions = permissions; 3823 } else { 3824 pi.requestedPermissions = new String[numMatch]; 3825 numMatch = 0; 3826 for (int i=0; i<permissions.length; i++) { 3827 if (tmp[i]) { 3828 pi.requestedPermissions[numMatch] = permissions[i]; 3829 numMatch++; 3830 } 3831 } 3832 } 3833 } 3834 list.add(pi); 3835 } 3836 3837 @Override 3838 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3839 String[] permissions, int flags, int userId) { 3840 if (!sUserManager.exists(userId)) return null; 3841 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3842 3843 // writer 3844 synchronized (mPackages) { 3845 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3846 boolean[] tmpBools = new boolean[permissions.length]; 3847 if (listUninstalled) { 3848 for (PackageSetting ps : mSettings.mPackages.values()) { 3849 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3850 } 3851 } else { 3852 for (PackageParser.Package pkg : mPackages.values()) { 3853 PackageSetting ps = (PackageSetting)pkg.mExtras; 3854 if (ps != null) { 3855 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3856 userId); 3857 } 3858 } 3859 } 3860 3861 return new ParceledListSlice<PackageInfo>(list); 3862 } 3863 } 3864 3865 @Override 3866 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3867 if (!sUserManager.exists(userId)) return null; 3868 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3869 3870 // writer 3871 synchronized (mPackages) { 3872 ArrayList<ApplicationInfo> list; 3873 if (listUninstalled) { 3874 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3875 for (PackageSetting ps : mSettings.mPackages.values()) { 3876 ApplicationInfo ai; 3877 if (ps.pkg != null) { 3878 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3879 ps.readUserState(userId), userId); 3880 } else { 3881 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3882 } 3883 if (ai != null) { 3884 list.add(ai); 3885 } 3886 } 3887 } else { 3888 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3889 for (PackageParser.Package p : mPackages.values()) { 3890 if (p.mExtras != null) { 3891 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3892 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3893 if (ai != null) { 3894 list.add(ai); 3895 } 3896 } 3897 } 3898 } 3899 3900 return new ParceledListSlice<ApplicationInfo>(list); 3901 } 3902 } 3903 3904 public List<ApplicationInfo> getPersistentApplications(int flags) { 3905 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3906 3907 // reader 3908 synchronized (mPackages) { 3909 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3910 final int userId = UserHandle.getCallingUserId(); 3911 while (i.hasNext()) { 3912 final PackageParser.Package p = i.next(); 3913 if (p.applicationInfo != null 3914 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3915 && (!mSafeMode || isSystemApp(p))) { 3916 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3917 if (ps != null) { 3918 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3919 ps.readUserState(userId), userId); 3920 if (ai != null) { 3921 finalList.add(ai); 3922 } 3923 } 3924 } 3925 } 3926 } 3927 3928 return finalList; 3929 } 3930 3931 @Override 3932 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3933 if (!sUserManager.exists(userId)) return null; 3934 // reader 3935 synchronized (mPackages) { 3936 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3937 PackageSetting ps = provider != null 3938 ? mSettings.mPackages.get(provider.owner.packageName) 3939 : null; 3940 return ps != null 3941 && mSettings.isEnabledLPr(provider.info, flags, userId) 3942 && (!mSafeMode || (provider.info.applicationInfo.flags 3943 &ApplicationInfo.FLAG_SYSTEM) != 0) 3944 ? PackageParser.generateProviderInfo(provider, flags, 3945 ps.readUserState(userId), userId) 3946 : null; 3947 } 3948 } 3949 3950 /** 3951 * @deprecated 3952 */ 3953 @Deprecated 3954 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3955 // reader 3956 synchronized (mPackages) { 3957 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3958 .entrySet().iterator(); 3959 final int userId = UserHandle.getCallingUserId(); 3960 while (i.hasNext()) { 3961 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3962 PackageParser.Provider p = entry.getValue(); 3963 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3964 3965 if (ps != null && p.syncable 3966 && (!mSafeMode || (p.info.applicationInfo.flags 3967 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3968 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3969 ps.readUserState(userId), userId); 3970 if (info != null) { 3971 outNames.add(entry.getKey()); 3972 outInfo.add(info); 3973 } 3974 } 3975 } 3976 } 3977 } 3978 3979 @Override 3980 public List<ProviderInfo> queryContentProviders(String processName, 3981 int uid, int flags) { 3982 ArrayList<ProviderInfo> finalList = null; 3983 // reader 3984 synchronized (mPackages) { 3985 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3986 final int userId = processName != null ? 3987 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3988 while (i.hasNext()) { 3989 final PackageParser.Provider p = i.next(); 3990 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3991 if (ps != null && p.info.authority != null 3992 && (processName == null 3993 || (p.info.processName.equals(processName) 3994 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3995 && mSettings.isEnabledLPr(p.info, flags, userId) 3996 && (!mSafeMode 3997 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3998 if (finalList == null) { 3999 finalList = new ArrayList<ProviderInfo>(3); 4000 } 4001 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4002 ps.readUserState(userId), userId); 4003 if (info != null) { 4004 finalList.add(info); 4005 } 4006 } 4007 } 4008 } 4009 4010 if (finalList != null) { 4011 Collections.sort(finalList, mProviderInitOrderSorter); 4012 } 4013 4014 return finalList; 4015 } 4016 4017 @Override 4018 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4019 int flags) { 4020 // reader 4021 synchronized (mPackages) { 4022 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4023 return PackageParser.generateInstrumentationInfo(i, flags); 4024 } 4025 } 4026 4027 @Override 4028 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4029 int flags) { 4030 ArrayList<InstrumentationInfo> finalList = 4031 new ArrayList<InstrumentationInfo>(); 4032 4033 // reader 4034 synchronized (mPackages) { 4035 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4036 while (i.hasNext()) { 4037 final PackageParser.Instrumentation p = i.next(); 4038 if (targetPackage == null 4039 || targetPackage.equals(p.info.targetPackage)) { 4040 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4041 flags); 4042 if (ii != null) { 4043 finalList.add(ii); 4044 } 4045 } 4046 } 4047 } 4048 4049 return finalList; 4050 } 4051 4052 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4053 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4054 if (overlays == null) { 4055 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4056 return; 4057 } 4058 for (PackageParser.Package opkg : overlays.values()) { 4059 // Not much to do if idmap fails: we already logged the error 4060 // and we certainly don't want to abort installation of pkg simply 4061 // because an overlay didn't fit properly. For these reasons, 4062 // ignore the return value of createIdmapForPackagePairLI. 4063 createIdmapForPackagePairLI(pkg, opkg); 4064 } 4065 } 4066 4067 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4068 PackageParser.Package opkg) { 4069 if (!opkg.mTrustedOverlay) { 4070 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4071 opkg.baseCodePath + ": overlay not trusted"); 4072 return false; 4073 } 4074 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4075 if (overlaySet == null) { 4076 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4077 opkg.baseCodePath + " but target package has no known overlays"); 4078 return false; 4079 } 4080 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4081 // TODO: generate idmap for split APKs 4082 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4083 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4084 + opkg.baseCodePath); 4085 return false; 4086 } 4087 PackageParser.Package[] overlayArray = 4088 overlaySet.values().toArray(new PackageParser.Package[0]); 4089 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4090 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4091 return p1.mOverlayPriority - p2.mOverlayPriority; 4092 } 4093 }; 4094 Arrays.sort(overlayArray, cmp); 4095 4096 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4097 int i = 0; 4098 for (PackageParser.Package p : overlayArray) { 4099 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4100 } 4101 return true; 4102 } 4103 4104 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4105 final File[] files = dir.listFiles(); 4106 if (ArrayUtils.isEmpty(files)) { 4107 Log.d(TAG, "No files in app dir " + dir); 4108 return; 4109 } 4110 4111 if (DEBUG_PACKAGE_SCANNING) { 4112 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4113 + " flags=0x" + Integer.toHexString(flags)); 4114 } 4115 4116 for (File file : files) { 4117 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4118 if (!isPackage) { 4119 // Ignore entries which are not apk's 4120 continue; 4121 } 4122 try { 4123 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4124 null, null); 4125 } catch (PackageManagerException e) { 4126 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4127 4128 // Don't mess around with apps in system partition. 4129 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4130 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4131 // Delete the apk 4132 Slog.w(TAG, "Cleaning up failed install of " + file); 4133 file.delete(); 4134 } 4135 } 4136 } 4137 } 4138 4139 private static File getSettingsProblemFile() { 4140 File dataDir = Environment.getDataDirectory(); 4141 File systemDir = new File(dataDir, "system"); 4142 File fname = new File(systemDir, "uiderrors.txt"); 4143 return fname; 4144 } 4145 4146 static void reportSettingsProblem(int priority, String msg) { 4147 try { 4148 File fname = getSettingsProblemFile(); 4149 FileOutputStream out = new FileOutputStream(fname, true); 4150 PrintWriter pw = new FastPrintWriter(out); 4151 SimpleDateFormat formatter = new SimpleDateFormat(); 4152 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4153 pw.println(dateString + ": " + msg); 4154 pw.close(); 4155 FileUtils.setPermissions( 4156 fname.toString(), 4157 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4158 -1, -1); 4159 } catch (java.io.IOException e) { 4160 } 4161 Slog.println(priority, TAG, msg); 4162 } 4163 4164 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4165 PackageParser.Package pkg, File srcFile, int parseFlags) 4166 throws PackageManagerException { 4167 if (ps != null 4168 && ps.codePath.equals(srcFile) 4169 && ps.timeStamp == srcFile.lastModified() 4170 && !isCompatSignatureUpdateNeeded(pkg)) { 4171 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4172 if (ps.signatures.mSignatures != null 4173 && ps.signatures.mSignatures.length != 0 4174 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4175 // Optimization: reuse the existing cached certificates 4176 // if the package appears to be unchanged. 4177 pkg.mSignatures = ps.signatures.mSignatures; 4178 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4179 synchronized (mPackages) { 4180 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4181 } 4182 return; 4183 } 4184 4185 Slog.w(TAG, "PackageSetting for " + ps.name 4186 + " is missing signatures. Collecting certs again to recover them."); 4187 } else { 4188 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4189 } 4190 4191 try { 4192 pp.collectCertificates(pkg, parseFlags); 4193 pp.collectManifestDigest(pkg); 4194 } catch (PackageParserException e) { 4195 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4196 + pkg.packageName + ": " + e.getMessage()); 4197 } 4198 } 4199 4200 /* 4201 * Scan a package and return the newly parsed package. 4202 * Returns null in case of errors and the error code is stored in mLastScanError 4203 */ 4204 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4205 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4206 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4207 parseFlags |= mDefParseFlags; 4208 PackageParser pp = new PackageParser(); 4209 pp.setSeparateProcesses(mSeparateProcesses); 4210 pp.setOnlyCoreApps(mOnlyCore); 4211 pp.setDisplayMetrics(mMetrics); 4212 4213 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4214 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4215 } 4216 4217 final PackageParser.Package pkg; 4218 try { 4219 pkg = pp.parsePackage(scanFile, parseFlags); 4220 } catch (PackageParserException e) { 4221 throw new PackageManagerException(e.error, 4222 "Failed to scan " + scanFile + ": " + e.getMessage()); 4223 } 4224 4225 PackageSetting ps = null; 4226 PackageSetting updatedPkg; 4227 // reader 4228 synchronized (mPackages) { 4229 // Look to see if we already know about this package. 4230 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4231 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4232 // This package has been renamed to its original name. Let's 4233 // use that. 4234 ps = mSettings.peekPackageLPr(oldName); 4235 } 4236 // If there was no original package, see one for the real package name. 4237 if (ps == null) { 4238 ps = mSettings.peekPackageLPr(pkg.packageName); 4239 } 4240 // Check to see if this package could be hiding/updating a system 4241 // package. Must look for it either under the original or real 4242 // package name depending on our state. 4243 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4244 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4245 } 4246 boolean updatedPkgBetter = false; 4247 // First check if this is a system package that may involve an update 4248 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4249 if (ps != null && !ps.codePath.equals(scanFile)) { 4250 // The path has changed from what was last scanned... check the 4251 // version of the new path against what we have stored to determine 4252 // what to do. 4253 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4254 if (pkg.mVersionCode < ps.versionCode) { 4255 // The system package has been updated and the code path does not match 4256 // Ignore entry. Skip it. 4257 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4258 + " ignored: updated version " + ps.versionCode 4259 + " better than this " + pkg.mVersionCode); 4260 if (!updatedPkg.codePath.equals(scanFile)) { 4261 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4262 + ps.name + " changing from " + updatedPkg.codePathString 4263 + " to " + scanFile); 4264 updatedPkg.codePath = scanFile; 4265 updatedPkg.codePathString = scanFile.toString(); 4266 // This is the point at which we know that the system-disk APK 4267 // for this package has moved during a reboot (e.g. due to an OTA), 4268 // so we need to reevaluate it for privilege policy. 4269 if (locationIsPrivileged(scanFile)) { 4270 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4271 } 4272 } 4273 updatedPkg.pkg = pkg; 4274 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4275 } else { 4276 // The current app on the system partition is better than 4277 // what we have updated to on the data partition; switch 4278 // back to the system partition version. 4279 // At this point, its safely assumed that package installation for 4280 // apps in system partition will go through. If not there won't be a working 4281 // version of the app 4282 // writer 4283 synchronized (mPackages) { 4284 // Just remove the loaded entries from package lists. 4285 mPackages.remove(ps.name); 4286 } 4287 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4288 + "reverting from " + ps.codePathString 4289 + ": new version " + pkg.mVersionCode 4290 + " better than installed " + ps.versionCode); 4291 4292 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4293 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4294 getAppDexInstructionSets(ps), isMultiArch(ps)); 4295 synchronized (mInstallLock) { 4296 args.cleanUpResourcesLI(); 4297 } 4298 synchronized (mPackages) { 4299 mSettings.enableSystemPackageLPw(ps.name); 4300 } 4301 updatedPkgBetter = true; 4302 } 4303 } 4304 } 4305 4306 if (updatedPkg != null) { 4307 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4308 // initially 4309 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4310 4311 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4312 // flag set initially 4313 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4314 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4315 } 4316 } 4317 4318 // Verify certificates against what was last scanned 4319 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4320 4321 /* 4322 * A new system app appeared, but we already had a non-system one of the 4323 * same name installed earlier. 4324 */ 4325 boolean shouldHideSystemApp = false; 4326 if (updatedPkg == null && ps != null 4327 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4328 /* 4329 * Check to make sure the signatures match first. If they don't, 4330 * wipe the installed application and its data. 4331 */ 4332 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4333 != PackageManager.SIGNATURE_MATCH) { 4334 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4335 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4336 ps = null; 4337 } else { 4338 /* 4339 * If the newly-added system app is an older version than the 4340 * already installed version, hide it. It will be scanned later 4341 * and re-added like an update. 4342 */ 4343 if (pkg.mVersionCode < ps.versionCode) { 4344 shouldHideSystemApp = true; 4345 } else { 4346 /* 4347 * The newly found system app is a newer version that the 4348 * one previously installed. Simply remove the 4349 * already-installed application and replace it with our own 4350 * while keeping the application data. 4351 */ 4352 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4353 + ps.codePathString + ": new version " + pkg.mVersionCode 4354 + " better than installed " + ps.versionCode); 4355 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4356 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4357 getAppDexInstructionSets(ps), isMultiArch(ps)); 4358 synchronized (mInstallLock) { 4359 args.cleanUpResourcesLI(); 4360 } 4361 } 4362 } 4363 } 4364 4365 // The apk is forward locked (not public) if its code and resources 4366 // are kept in different files. (except for app in either system or 4367 // vendor path). 4368 // TODO grab this value from PackageSettings 4369 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4370 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4371 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4372 } 4373 } 4374 4375 // TODO: extend to support forward-locked splits 4376 String resourcePath = null; 4377 String baseResourcePath = null; 4378 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4379 if (ps != null && ps.resourcePathString != null) { 4380 resourcePath = ps.resourcePathString; 4381 baseResourcePath = ps.resourcePathString; 4382 } else { 4383 // Should not happen at all. Just log an error. 4384 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4385 } 4386 } else { 4387 resourcePath = pkg.codePath; 4388 baseResourcePath = pkg.baseCodePath; 4389 } 4390 4391 // Set application objects path explicitly. 4392 pkg.applicationInfo.setCodePath(pkg.codePath); 4393 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4394 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4395 pkg.applicationInfo.setResourcePath(resourcePath); 4396 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4397 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4398 4399 // Note that we invoke the following method only if we are about to unpack an application 4400 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4401 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4402 4403 /* 4404 * If the system app should be overridden by a previously installed 4405 * data, hide the system app now and let the /data/app scan pick it up 4406 * again. 4407 */ 4408 if (shouldHideSystemApp) { 4409 synchronized (mPackages) { 4410 /* 4411 * We have to grant systems permissions before we hide, because 4412 * grantPermissions will assume the package update is trying to 4413 * expand its permissions. 4414 */ 4415 grantPermissionsLPw(pkg, true); 4416 mSettings.disableSystemPackageLPw(pkg.packageName); 4417 } 4418 } 4419 4420 return scannedPkg; 4421 } 4422 4423 private static String fixProcessName(String defProcessName, 4424 String processName, int uid) { 4425 if (processName == null) { 4426 return defProcessName; 4427 } 4428 return processName; 4429 } 4430 4431 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4432 throws PackageManagerException { 4433 if (pkgSetting.signatures.mSignatures != null) { 4434 // Already existing package. Make sure signatures match 4435 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4436 == PackageManager.SIGNATURE_MATCH; 4437 if (!match) { 4438 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4439 == PackageManager.SIGNATURE_MATCH; 4440 } 4441 if (!match) { 4442 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4443 + pkg.packageName + " signatures do not match the " 4444 + "previously installed version; ignoring!"); 4445 } 4446 } 4447 4448 // Check for shared user signatures 4449 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4450 // Already existing package. Make sure signatures match 4451 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4452 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4453 if (!match) { 4454 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4455 == PackageManager.SIGNATURE_MATCH; 4456 } 4457 if (!match) { 4458 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4459 "Package " + pkg.packageName 4460 + " has no signatures that match those in shared user " 4461 + pkgSetting.sharedUser.name + "; ignoring!"); 4462 } 4463 } 4464 } 4465 4466 /** 4467 * Enforces that only the system UID or root's UID can call a method exposed 4468 * via Binder. 4469 * 4470 * @param message used as message if SecurityException is thrown 4471 * @throws SecurityException if the caller is not system or root 4472 */ 4473 private static final void enforceSystemOrRoot(String message) { 4474 final int uid = Binder.getCallingUid(); 4475 if (uid != Process.SYSTEM_UID && uid != 0) { 4476 throw new SecurityException(message); 4477 } 4478 } 4479 4480 @Override 4481 public void performBootDexOpt() { 4482 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4483 4484 final HashSet<PackageParser.Package> pkgs; 4485 synchronized (mPackages) { 4486 pkgs = mDeferredDexOpt; 4487 mDeferredDexOpt = null; 4488 } 4489 4490 if (pkgs != null) { 4491 // Filter out packages that aren't recently used. 4492 // 4493 // The exception is first boot of a non-eng device, which 4494 // should do a full dexopt. 4495 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4496 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4497 // TODO: add a property to control this? 4498 long dexOptLRUThresholdInMinutes; 4499 if (eng) { 4500 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4501 } else { 4502 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4503 } 4504 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4505 4506 int total = pkgs.size(); 4507 int skipped = 0; 4508 long now = System.currentTimeMillis(); 4509 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4510 PackageParser.Package pkg = i.next(); 4511 long then = pkg.mLastPackageUsageTimeInMills; 4512 if (then + dexOptLRUThresholdInMills < now) { 4513 if (DEBUG_DEXOPT) { 4514 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4515 ((then == 0) ? "never" : new Date(then))); 4516 } 4517 i.remove(); 4518 skipped++; 4519 } 4520 } 4521 if (DEBUG_DEXOPT) { 4522 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4523 } 4524 } 4525 4526 int i = 0; 4527 for (PackageParser.Package pkg : pkgs) { 4528 i++; 4529 if (DEBUG_DEXOPT) { 4530 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4531 + ": " + pkg.packageName); 4532 } 4533 if (!isFirstBoot()) { 4534 try { 4535 ActivityManagerNative.getDefault().showBootMessage( 4536 mContext.getResources().getString( 4537 R.string.android_upgrading_apk, 4538 i, pkgs.size()), true); 4539 } catch (RemoteException e) { 4540 } 4541 } 4542 PackageParser.Package p = pkg; 4543 synchronized (mInstallLock) { 4544 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4545 true /* include dependencies */); 4546 } 4547 } 4548 } 4549 } 4550 4551 @Override 4552 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4553 return performDexOpt(packageName, instructionSet, true); 4554 } 4555 4556 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4557 if (info.primaryCpuAbi == null) { 4558 return getPreferredInstructionSet(); 4559 } 4560 4561 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4562 } 4563 4564 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4565 PackageParser.Package p; 4566 final String targetInstructionSet; 4567 synchronized (mPackages) { 4568 p = mPackages.get(packageName); 4569 if (p == null) { 4570 return false; 4571 } 4572 if (updateUsage) { 4573 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4574 } 4575 mPackageUsage.write(false); 4576 4577 targetInstructionSet = instructionSet != null ? instructionSet : 4578 getPrimaryInstructionSet(p.applicationInfo); 4579 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4580 return false; 4581 } 4582 } 4583 4584 synchronized (mInstallLock) { 4585 final String[] instructionSets = new String[] { targetInstructionSet }; 4586 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4587 true /* include dependencies */) == DEX_OPT_PERFORMED; 4588 } 4589 } 4590 4591 public HashSet<String> getPackagesThatNeedDexOpt() { 4592 HashSet<String> pkgs = null; 4593 synchronized (mPackages) { 4594 for (PackageParser.Package p : mPackages.values()) { 4595 if (DEBUG_DEXOPT) { 4596 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4597 } 4598 if (!p.mDexOptPerformed.isEmpty()) { 4599 continue; 4600 } 4601 if (pkgs == null) { 4602 pkgs = new HashSet<String>(); 4603 } 4604 pkgs.add(p.packageName); 4605 } 4606 } 4607 return pkgs; 4608 } 4609 4610 public void shutdown() { 4611 mPackageUsage.write(true); 4612 } 4613 4614 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4615 boolean forceDex, boolean defer, HashSet<String> done) { 4616 for (int i=0; i<libs.size(); i++) { 4617 PackageParser.Package libPkg; 4618 String libName; 4619 synchronized (mPackages) { 4620 libName = libs.get(i); 4621 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4622 if (lib != null && lib.apk != null) { 4623 libPkg = mPackages.get(lib.apk); 4624 } else { 4625 libPkg = null; 4626 } 4627 } 4628 if (libPkg != null && !done.contains(libName)) { 4629 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4630 } 4631 } 4632 } 4633 4634 static final int DEX_OPT_SKIPPED = 0; 4635 static final int DEX_OPT_PERFORMED = 1; 4636 static final int DEX_OPT_DEFERRED = 2; 4637 static final int DEX_OPT_FAILED = -1; 4638 4639 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4640 boolean forceDex, boolean defer, HashSet<String> done) { 4641 final String[] instructionSets = targetInstructionSets != null ? 4642 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4643 4644 if (done != null) { 4645 done.add(pkg.packageName); 4646 if (pkg.usesLibraries != null) { 4647 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4648 } 4649 if (pkg.usesOptionalLibraries != null) { 4650 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4651 } 4652 } 4653 4654 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4655 return DEX_OPT_SKIPPED; 4656 } 4657 4658 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4659 boolean performedDexOpt = false; 4660 // There are three basic cases here: 4661 // 1.) we need to dexopt, either because we are forced or it is needed 4662 // 2.) we are defering a needed dexopt 4663 // 3.) we are skipping an unneeded dexopt 4664 for (String path : paths) { 4665 for (String instructionSet : instructionSets) { 4666 if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) { 4667 continue; 4668 } 4669 4670 try { 4671 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4672 pkg.packageName, instructionSet, defer); 4673 if (forceDex || (!defer && isDexOptNeeded)) { 4674 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4675 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4676 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4677 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4678 pkg.packageName, instructionSet); 4679 4680 if (ret < 0) { 4681 // Don't bother running dexopt again if we failed, it will probably 4682 // just result in an error again. Also, don't bother dexopting for other 4683 // paths & ISAs. 4684 return DEX_OPT_FAILED; 4685 } else { 4686 performedDexOpt = true; 4687 pkg.mDexOptPerformed.add(instructionSet); 4688 } 4689 } 4690 4691 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4692 // paths and instruction sets. We'll deal with them all together when we process 4693 // our list of deferred dexopts. 4694 if (defer && isDexOptNeeded) { 4695 if (mDeferredDexOpt == null) { 4696 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4697 } 4698 mDeferredDexOpt.add(pkg); 4699 return DEX_OPT_DEFERRED; 4700 } 4701 } catch (FileNotFoundException e) { 4702 Slog.w(TAG, "Apk not found for dexopt: " + path); 4703 return DEX_OPT_FAILED; 4704 } catch (IOException e) { 4705 Slog.w(TAG, "IOException reading apk: " + path, e); 4706 return DEX_OPT_FAILED; 4707 } catch (StaleDexCacheError e) { 4708 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4709 return DEX_OPT_FAILED; 4710 } catch (Exception e) { 4711 Slog.w(TAG, "Exception when doing dexopt : ", e); 4712 return DEX_OPT_FAILED; 4713 } 4714 } 4715 } 4716 4717 // If we've gotten here, we're sure that no error occurred and that we haven't 4718 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4719 // we've skipped all of them because they are up to date. In both cases this 4720 // package doesn't need dexopt any longer. 4721 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4722 } 4723 4724 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4725 if (info.primaryCpuAbi != null) { 4726 if (info.secondaryCpuAbi != null) { 4727 return new String[] { 4728 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4729 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4730 } else { 4731 return new String[] { 4732 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4733 } 4734 } 4735 4736 return new String[] { getPreferredInstructionSet() }; 4737 } 4738 4739 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4740 if (ps.primaryCpuAbiString != null) { 4741 if (ps.secondaryCpuAbiString != null) { 4742 return new String[] { 4743 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4744 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4745 } else { 4746 return new String[] { 4747 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4748 } 4749 } 4750 4751 return new String[] { getPreferredInstructionSet() }; 4752 } 4753 4754 private static String getPreferredInstructionSet() { 4755 if (sPreferredInstructionSet == null) { 4756 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4757 } 4758 4759 return sPreferredInstructionSet; 4760 } 4761 4762 private static List<String> getAllInstructionSets() { 4763 final String[] allAbis = Build.SUPPORTED_ABIS; 4764 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4765 4766 for (String abi : allAbis) { 4767 final String instructionSet = VMRuntime.getInstructionSet(abi); 4768 if (!allInstructionSets.contains(instructionSet)) { 4769 allInstructionSets.add(instructionSet); 4770 } 4771 } 4772 4773 return allInstructionSets; 4774 } 4775 4776 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4777 boolean forceDex, boolean defer, boolean inclDependencies) { 4778 HashSet<String> done; 4779 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4780 done = new HashSet<String>(); 4781 done.add(pkg.packageName); 4782 } else { 4783 done = null; 4784 } 4785 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4786 } 4787 4788 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4789 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4790 Slog.w(TAG, "Unable to update from " + oldPkg.name 4791 + " to " + newPkg.packageName 4792 + ": old package not in system partition"); 4793 return false; 4794 } else if (mPackages.get(oldPkg.name) != null) { 4795 Slog.w(TAG, "Unable to update from " + oldPkg.name 4796 + " to " + newPkg.packageName 4797 + ": old package still exists"); 4798 return false; 4799 } 4800 return true; 4801 } 4802 4803 File getDataPathForUser(int userId) { 4804 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4805 } 4806 4807 private File getDataPathForPackage(String packageName, int userId) { 4808 /* 4809 * Until we fully support multiple users, return the directory we 4810 * previously would have. The PackageManagerTests will need to be 4811 * revised when this is changed back.. 4812 */ 4813 if (userId == 0) { 4814 return new File(mAppDataDir, packageName); 4815 } else { 4816 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4817 + File.separator + packageName); 4818 } 4819 } 4820 4821 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4822 int[] users = sUserManager.getUserIds(); 4823 int res = mInstaller.install(packageName, uid, uid, seinfo); 4824 if (res < 0) { 4825 return res; 4826 } 4827 for (int user : users) { 4828 if (user != 0) { 4829 res = mInstaller.createUserData(packageName, 4830 UserHandle.getUid(user, uid), user, seinfo); 4831 if (res < 0) { 4832 return res; 4833 } 4834 } 4835 } 4836 return res; 4837 } 4838 4839 private int removeDataDirsLI(String packageName) { 4840 int[] users = sUserManager.getUserIds(); 4841 int res = 0; 4842 for (int user : users) { 4843 int resInner = mInstaller.remove(packageName, user); 4844 if (resInner < 0) { 4845 res = resInner; 4846 } 4847 } 4848 4849 return res; 4850 } 4851 4852 private int deleteCodeCacheDirsLI(String packageName) { 4853 int[] users = sUserManager.getUserIds(); 4854 int res = 0; 4855 for (int user : users) { 4856 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4857 if (resInner < 0) { 4858 res = resInner; 4859 } 4860 } 4861 return res; 4862 } 4863 4864 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4865 PackageParser.Package changingLib) { 4866 if (file.path != null) { 4867 usesLibraryFiles.add(file.path); 4868 return; 4869 } 4870 PackageParser.Package p = mPackages.get(file.apk); 4871 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4872 // If we are doing this while in the middle of updating a library apk, 4873 // then we need to make sure to use that new apk for determining the 4874 // dependencies here. (We haven't yet finished committing the new apk 4875 // to the package manager state.) 4876 if (p == null || p.packageName.equals(changingLib.packageName)) { 4877 p = changingLib; 4878 } 4879 } 4880 if (p != null) { 4881 usesLibraryFiles.addAll(p.getAllCodePaths()); 4882 } 4883 } 4884 4885 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4886 PackageParser.Package changingLib) throws PackageManagerException { 4887 // We might be upgrading from a version of the platform that did not 4888 // provide per-package native library directories for system apps. 4889 // Fix that up here. 4890 if (isSystemApp(pkg)) { 4891 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4892 if (!isUpdatedSystemApp(pkg)) { 4893 setBundledAppAbisAndRoots(pkg, ps); 4894 } 4895 } 4896 4897 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4898 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4899 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4900 for (int i=0; i<N; i++) { 4901 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4902 if (file == null) { 4903 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4904 "Package " + pkg.packageName + " requires unavailable shared library " 4905 + pkg.usesLibraries.get(i) + "; failing!"); 4906 } 4907 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4908 } 4909 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4910 for (int i=0; i<N; i++) { 4911 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4912 if (file == null) { 4913 Slog.w(TAG, "Package " + pkg.packageName 4914 + " desires unavailable shared library " 4915 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4916 } else { 4917 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4918 } 4919 } 4920 N = usesLibraryFiles.size(); 4921 if (N > 0) { 4922 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4923 } else { 4924 pkg.usesLibraryFiles = null; 4925 } 4926 } 4927 } 4928 4929 private static boolean hasString(List<String> list, List<String> which) { 4930 if (list == null) { 4931 return false; 4932 } 4933 for (int i=list.size()-1; i>=0; i--) { 4934 for (int j=which.size()-1; j>=0; j--) { 4935 if (which.get(j).equals(list.get(i))) { 4936 return true; 4937 } 4938 } 4939 } 4940 return false; 4941 } 4942 4943 private void updateAllSharedLibrariesLPw() { 4944 for (PackageParser.Package pkg : mPackages.values()) { 4945 try { 4946 updateSharedLibrariesLPw(pkg, null); 4947 } catch (PackageManagerException e) { 4948 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4949 } 4950 } 4951 } 4952 4953 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4954 PackageParser.Package changingPkg) { 4955 ArrayList<PackageParser.Package> res = null; 4956 for (PackageParser.Package pkg : mPackages.values()) { 4957 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4958 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4959 if (res == null) { 4960 res = new ArrayList<PackageParser.Package>(); 4961 } 4962 res.add(pkg); 4963 try { 4964 updateSharedLibrariesLPw(pkg, changingPkg); 4965 } catch (PackageManagerException e) { 4966 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4967 } 4968 } 4969 } 4970 return res; 4971 } 4972 4973 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4974 int scanMode, long currentTime, UserHandle user, String abiOverride) 4975 throws PackageManagerException { 4976 final File scanFile = new File(pkg.codePath); 4977 if (pkg.applicationInfo.getCodePath() == null || 4978 pkg.applicationInfo.getResourcePath() == null) { 4979 // Bail out. The resource and code paths haven't been set. 4980 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4981 "Code and resource paths haven't been set correctly"); 4982 } 4983 4984 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4985 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4986 } 4987 4988 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4989 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4990 } 4991 4992 if (mCustomResolverComponentName != null && 4993 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4994 setUpCustomResolverActivity(pkg); 4995 } 4996 4997 if (pkg.packageName.equals("android")) { 4998 synchronized (mPackages) { 4999 if (mAndroidApplication != null) { 5000 Slog.w(TAG, "*************************************************"); 5001 Slog.w(TAG, "Core android package being redefined. Skipping."); 5002 Slog.w(TAG, " file=" + scanFile); 5003 Slog.w(TAG, "*************************************************"); 5004 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5005 "Core android package being redefined. Skipping."); 5006 } 5007 5008 // Set up information for our fall-back user intent resolution activity. 5009 mPlatformPackage = pkg; 5010 pkg.mVersionCode = mSdkVersion; 5011 mAndroidApplication = pkg.applicationInfo; 5012 5013 if (!mResolverReplaced) { 5014 mResolveActivity.applicationInfo = mAndroidApplication; 5015 mResolveActivity.name = ResolverActivity.class.getName(); 5016 mResolveActivity.packageName = mAndroidApplication.packageName; 5017 mResolveActivity.processName = "system:ui"; 5018 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5019 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5020 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5021 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5022 mResolveActivity.exported = true; 5023 mResolveActivity.enabled = true; 5024 mResolveInfo.activityInfo = mResolveActivity; 5025 mResolveInfo.priority = 0; 5026 mResolveInfo.preferredOrder = 0; 5027 mResolveInfo.match = 0; 5028 mResolveComponentName = new ComponentName( 5029 mAndroidApplication.packageName, mResolveActivity.name); 5030 } 5031 } 5032 } 5033 5034 if (DEBUG_PACKAGE_SCANNING) { 5035 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5036 Log.d(TAG, "Scanning package " + pkg.packageName); 5037 } 5038 5039 if (mPackages.containsKey(pkg.packageName) 5040 || mSharedLibraries.containsKey(pkg.packageName)) { 5041 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5042 "Application package " + pkg.packageName 5043 + " already installed. Skipping duplicate."); 5044 } 5045 5046 // Initialize package source and resource directories 5047 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5048 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5049 5050 SharedUserSetting suid = null; 5051 PackageSetting pkgSetting = null; 5052 5053 if (!isSystemApp(pkg)) { 5054 // Only system apps can use these features. 5055 pkg.mOriginalPackages = null; 5056 pkg.mRealPackage = null; 5057 pkg.mAdoptPermissions = null; 5058 } 5059 5060 // writer 5061 synchronized (mPackages) { 5062 if (pkg.mSharedUserId != null) { 5063 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5064 if (suid == null) { 5065 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5066 "Creating application package " + pkg.packageName 5067 + " for shared user failed"); 5068 } 5069 if (DEBUG_PACKAGE_SCANNING) { 5070 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5071 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5072 + "): packages=" + suid.packages); 5073 } 5074 } 5075 5076 // Check if we are renaming from an original package name. 5077 PackageSetting origPackage = null; 5078 String realName = null; 5079 if (pkg.mOriginalPackages != null) { 5080 // This package may need to be renamed to a previously 5081 // installed name. Let's check on that... 5082 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5083 if (pkg.mOriginalPackages.contains(renamed)) { 5084 // This package had originally been installed as the 5085 // original name, and we have already taken care of 5086 // transitioning to the new one. Just update the new 5087 // one to continue using the old name. 5088 realName = pkg.mRealPackage; 5089 if (!pkg.packageName.equals(renamed)) { 5090 // Callers into this function may have already taken 5091 // care of renaming the package; only do it here if 5092 // it is not already done. 5093 pkg.setPackageName(renamed); 5094 } 5095 5096 } else { 5097 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5098 if ((origPackage = mSettings.peekPackageLPr( 5099 pkg.mOriginalPackages.get(i))) != null) { 5100 // We do have the package already installed under its 5101 // original name... should we use it? 5102 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5103 // New package is not compatible with original. 5104 origPackage = null; 5105 continue; 5106 } else if (origPackage.sharedUser != null) { 5107 // Make sure uid is compatible between packages. 5108 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5109 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5110 + " to " + pkg.packageName + ": old uid " 5111 + origPackage.sharedUser.name 5112 + " differs from " + pkg.mSharedUserId); 5113 origPackage = null; 5114 continue; 5115 } 5116 } else { 5117 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5118 + pkg.packageName + " to old name " + origPackage.name); 5119 } 5120 break; 5121 } 5122 } 5123 } 5124 } 5125 5126 if (mTransferedPackages.contains(pkg.packageName)) { 5127 Slog.w(TAG, "Package " + pkg.packageName 5128 + " was transferred to another, but its .apk remains"); 5129 } 5130 5131 // Just create the setting, don't add it yet. For already existing packages 5132 // the PkgSetting exists already and doesn't have to be created. 5133 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5134 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5135 pkg.applicationInfo.primaryCpuAbi, 5136 pkg.applicationInfo.secondaryCpuAbi, 5137 pkg.applicationInfo.flags, user, false); 5138 if (pkgSetting == null) { 5139 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5140 "Creating application package " + pkg.packageName + " failed"); 5141 } 5142 5143 if (pkgSetting.origPackage != null) { 5144 // If we are first transitioning from an original package, 5145 // fix up the new package's name now. We need to do this after 5146 // looking up the package under its new name, so getPackageLP 5147 // can take care of fiddling things correctly. 5148 pkg.setPackageName(origPackage.name); 5149 5150 // File a report about this. 5151 String msg = "New package " + pkgSetting.realName 5152 + " renamed to replace old package " + pkgSetting.name; 5153 reportSettingsProblem(Log.WARN, msg); 5154 5155 // Make a note of it. 5156 mTransferedPackages.add(origPackage.name); 5157 5158 // No longer need to retain this. 5159 pkgSetting.origPackage = null; 5160 } 5161 5162 if (realName != null) { 5163 // Make a note of it. 5164 mTransferedPackages.add(pkg.packageName); 5165 } 5166 5167 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5168 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5169 } 5170 5171 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5172 // Check all shared libraries and map to their actual file path. 5173 // We only do this here for apps not on a system dir, because those 5174 // are the only ones that can fail an install due to this. We 5175 // will take care of the system apps by updating all of their 5176 // library paths after the scan is done. 5177 updateSharedLibrariesLPw(pkg, null); 5178 } 5179 5180 if (mFoundPolicyFile) { 5181 SELinuxMMAC.assignSeinfoValue(pkg); 5182 } 5183 5184 pkg.applicationInfo.uid = pkgSetting.appId; 5185 pkg.mExtras = pkgSetting; 5186 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5187 try { 5188 verifySignaturesLP(pkgSetting, pkg); 5189 } catch (PackageManagerException e) { 5190 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5191 throw e; 5192 } 5193 // The signature has changed, but this package is in the system 5194 // image... let's recover! 5195 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5196 // However... if this package is part of a shared user, but it 5197 // doesn't match the signature of the shared user, let's fail. 5198 // What this means is that you can't change the signatures 5199 // associated with an overall shared user, which doesn't seem all 5200 // that unreasonable. 5201 if (pkgSetting.sharedUser != null) { 5202 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5203 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5204 throw new PackageManagerException( 5205 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5206 "Signature mismatch for shared user : " 5207 + pkgSetting.sharedUser); 5208 } 5209 } 5210 // File a report about this. 5211 String msg = "System package " + pkg.packageName 5212 + " signature changed; retaining data."; 5213 reportSettingsProblem(Log.WARN, msg); 5214 } 5215 } else { 5216 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5217 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5218 + pkg.packageName + " upgrade keys do not match the " 5219 + "previously installed version"); 5220 } else { 5221 // signatures may have changed as result of upgrade 5222 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5223 } 5224 } 5225 // Verify that this new package doesn't have any content providers 5226 // that conflict with existing packages. Only do this if the 5227 // package isn't already installed, since we don't want to break 5228 // things that are installed. 5229 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5230 final int N = pkg.providers.size(); 5231 int i; 5232 for (i=0; i<N; i++) { 5233 PackageParser.Provider p = pkg.providers.get(i); 5234 if (p.info.authority != null) { 5235 String names[] = p.info.authority.split(";"); 5236 for (int j = 0; j < names.length; j++) { 5237 if (mProvidersByAuthority.containsKey(names[j])) { 5238 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5239 final String otherPackageName = 5240 ((other != null && other.getComponentName() != null) ? 5241 other.getComponentName().getPackageName() : "?"); 5242 throw new PackageManagerException( 5243 INSTALL_FAILED_CONFLICTING_PROVIDER, 5244 "Can't install because provider name " + names[j] 5245 + " (in package " + pkg.applicationInfo.packageName 5246 + ") is already used by " + otherPackageName); 5247 } 5248 } 5249 } 5250 } 5251 } 5252 5253 if (pkg.mAdoptPermissions != null) { 5254 // This package wants to adopt ownership of permissions from 5255 // another package. 5256 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5257 final String origName = pkg.mAdoptPermissions.get(i); 5258 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5259 if (orig != null) { 5260 if (verifyPackageUpdateLPr(orig, pkg)) { 5261 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5262 + pkg.packageName); 5263 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5264 } 5265 } 5266 } 5267 } 5268 } 5269 5270 final String pkgName = pkg.packageName; 5271 5272 final long scanFileTime = scanFile.lastModified(); 5273 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5274 pkg.applicationInfo.processName = fixProcessName( 5275 pkg.applicationInfo.packageName, 5276 pkg.applicationInfo.processName, 5277 pkg.applicationInfo.uid); 5278 5279 File dataPath; 5280 if (mPlatformPackage == pkg) { 5281 // The system package is special. 5282 dataPath = new File (Environment.getDataDirectory(), "system"); 5283 pkg.applicationInfo.dataDir = dataPath.getPath(); 5284 } else { 5285 // This is a normal package, need to make its data directory. 5286 dataPath = getDataPathForPackage(pkg.packageName, 0); 5287 5288 boolean uidError = false; 5289 5290 if (dataPath.exists()) { 5291 int currentUid = 0; 5292 try { 5293 StructStat stat = Os.stat(dataPath.getPath()); 5294 currentUid = stat.st_uid; 5295 } catch (ErrnoException e) { 5296 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5297 } 5298 5299 // If we have mismatched owners for the data path, we have a problem. 5300 if (currentUid != pkg.applicationInfo.uid) { 5301 boolean recovered = false; 5302 if (currentUid == 0) { 5303 // The directory somehow became owned by root. Wow. 5304 // This is probably because the system was stopped while 5305 // installd was in the middle of messing with its libs 5306 // directory. Ask installd to fix that. 5307 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5308 pkg.applicationInfo.uid); 5309 if (ret >= 0) { 5310 recovered = true; 5311 String msg = "Package " + pkg.packageName 5312 + " unexpectedly changed to uid 0; recovered to " + 5313 + pkg.applicationInfo.uid; 5314 reportSettingsProblem(Log.WARN, msg); 5315 } 5316 } 5317 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5318 || (scanMode&SCAN_BOOTING) != 0)) { 5319 // If this is a system app, we can at least delete its 5320 // current data so the application will still work. 5321 int ret = removeDataDirsLI(pkgName); 5322 if (ret >= 0) { 5323 // TODO: Kill the processes first 5324 // Old data gone! 5325 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5326 ? "System package " : "Third party package "; 5327 String msg = prefix + pkg.packageName 5328 + " has changed from uid: " 5329 + currentUid + " to " 5330 + pkg.applicationInfo.uid + "; old data erased"; 5331 reportSettingsProblem(Log.WARN, msg); 5332 recovered = true; 5333 5334 // And now re-install the app. 5335 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5336 pkg.applicationInfo.seinfo); 5337 if (ret == -1) { 5338 // Ack should not happen! 5339 msg = prefix + pkg.packageName 5340 + " could not have data directory re-created after delete."; 5341 reportSettingsProblem(Log.WARN, msg); 5342 throw new PackageManagerException( 5343 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5344 } 5345 } 5346 if (!recovered) { 5347 mHasSystemUidErrors = true; 5348 } 5349 } else if (!recovered) { 5350 // If we allow this install to proceed, we will be broken. 5351 // Abort, abort! 5352 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5353 "scanPackageLI"); 5354 } 5355 if (!recovered) { 5356 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5357 + pkg.applicationInfo.uid + "/fs_" 5358 + currentUid; 5359 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5360 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5361 String msg = "Package " + pkg.packageName 5362 + " has mismatched uid: " 5363 + currentUid + " on disk, " 5364 + pkg.applicationInfo.uid + " in settings"; 5365 // writer 5366 synchronized (mPackages) { 5367 mSettings.mReadMessages.append(msg); 5368 mSettings.mReadMessages.append('\n'); 5369 uidError = true; 5370 if (!pkgSetting.uidError) { 5371 reportSettingsProblem(Log.ERROR, msg); 5372 } 5373 } 5374 } 5375 } 5376 pkg.applicationInfo.dataDir = dataPath.getPath(); 5377 if (mShouldRestoreconData) { 5378 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5379 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5380 pkg.applicationInfo.uid); 5381 } 5382 } else { 5383 if (DEBUG_PACKAGE_SCANNING) { 5384 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5385 Log.v(TAG, "Want this data dir: " + dataPath); 5386 } 5387 //invoke installer to do the actual installation 5388 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5389 pkg.applicationInfo.seinfo); 5390 if (ret < 0) { 5391 // Error from installer 5392 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5393 "Unable to create data dirs [errorCode=" + ret + "]"); 5394 } 5395 5396 if (dataPath.exists()) { 5397 pkg.applicationInfo.dataDir = dataPath.getPath(); 5398 } else { 5399 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5400 pkg.applicationInfo.dataDir = null; 5401 } 5402 } 5403 5404 pkgSetting.uidError = uidError; 5405 } 5406 5407 final String path = scanFile.getPath(); 5408 final String codePath = pkg.applicationInfo.getCodePath(); 5409 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5410 // For the case where we had previously uninstalled an update, get rid 5411 // of any native binaries we might have unpackaged. Note that this assumes 5412 // that system app updates were not installed via ASEC. 5413 // 5414 // TODO(multiArch): Is this cleanup really necessary ? 5415 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5416 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5417 setBundledAppAbisAndRoots(pkg, pkgSetting); 5418 setNativeLibraryPaths(pkg); 5419 } else { 5420 // TODO: We can probably be smarter about this stuff. For installed apps, 5421 // we can calculate this information at install time once and for all. For 5422 // system apps, we can probably assume that this information doesn't change 5423 // after the first boot scan. As things stand, we do lots of unnecessary work. 5424 5425 // Give ourselves some initial paths; we'll come back for another 5426 // pass once we've determined ABI below. 5427 setNativeLibraryPaths(pkg); 5428 5429 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5430 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5431 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5432 5433 NativeLibraryHelper.Handle handle = null; 5434 try { 5435 handle = NativeLibraryHelper.Handle.create(scanFile); 5436 // TODO(multiArch): This can be null for apps that didn't go through the 5437 // usual installation process. We can calculate it again, like we 5438 // do during install time. 5439 // 5440 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5441 // unnecessary. 5442 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5443 5444 // Null out the abis so that they can be recalculated. 5445 pkg.applicationInfo.primaryCpuAbi = null; 5446 pkg.applicationInfo.secondaryCpuAbi = null; 5447 if (isMultiArch(pkg.applicationInfo)) { 5448 // Warn if we've set an abiOverride for multi-lib packages.. 5449 // By definition, we need to copy both 32 and 64 bit libraries for 5450 // such packages. 5451 if (abiOverride != null) { 5452 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5453 } 5454 5455 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5456 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5457 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5458 if (isAsec) { 5459 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5460 } else { 5461 abi32 = copyNativeLibrariesForInternalApp(handle, 5462 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5463 } 5464 } 5465 5466 maybeThrowExceptionForMultiArchCopy( 5467 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5468 5469 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5470 if (isAsec) { 5471 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5472 } else { 5473 abi64 = copyNativeLibrariesForInternalApp(handle, 5474 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5475 } 5476 } 5477 5478 maybeThrowExceptionForMultiArchCopy( 5479 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5480 5481 if (abi64 >= 0) { 5482 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5483 } 5484 5485 if (abi32 >= 0) { 5486 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5487 if (abi64 >= 0) { 5488 pkg.applicationInfo.secondaryCpuAbi = abi; 5489 } else { 5490 pkg.applicationInfo.primaryCpuAbi = abi; 5491 } 5492 } 5493 } else { 5494 String[] abiList = (abiOverride != null) ? 5495 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5496 5497 // Enable gross and lame hacks for apps that are built with old 5498 // SDK tools. We must scan their APKs for renderscript bitcode and 5499 // not launch them if it's present. Don't bother checking on devices 5500 // that don't have 64 bit support. 5501 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5502 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5503 abiList = Build.SUPPORTED_32_BIT_ABIS; 5504 } 5505 5506 final int copyRet; 5507 if (isAsec) { 5508 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5509 } else { 5510 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5511 useIsaSpecificSubdirs); 5512 } 5513 5514 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5515 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5516 "Error unpackaging native libs for app, errorCode=" + copyRet); 5517 } 5518 5519 if (copyRet >= 0) { 5520 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5521 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5522 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5523 } 5524 } 5525 } catch (IOException ioe) { 5526 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5527 } finally { 5528 IoUtils.closeQuietly(handle); 5529 } 5530 5531 // Now that we've calculated the ABIs and determined if it's an internal app, 5532 // we will go ahead and populate the nativeLibraryPath. 5533 setNativeLibraryPaths(pkg); 5534 5535 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5536 final int[] userIds = sUserManager.getUserIds(); 5537 synchronized (mInstallLock) { 5538 // Create a native library symlink only if we have native libraries 5539 // and if the native libraries are 32 bit libraries. We do not provide 5540 // this symlink for 64 bit libraries. 5541 if (pkg.applicationInfo.primaryCpuAbi != null && 5542 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5543 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5544 for (int userId : userIds) { 5545 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5546 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5547 "Failed linking native library dir (user=" + userId + ")"); 5548 } 5549 } 5550 } 5551 } 5552 5553 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5554 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5555 } 5556 5557 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5558 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5559 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5560 5561 // Push the derived path down into PackageSettings so we know what to 5562 // clean up at uninstall time. 5563 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5564 5565 if (DEBUG_ABI_SELECTION) { 5566 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5567 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5568 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5569 } 5570 5571 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5572 // We don't do this here during boot because we can do it all 5573 // at once after scanning all existing packages. 5574 // 5575 // We also do this *before* we perform dexopt on this package, so that 5576 // we can avoid redundant dexopts, and also to make sure we've got the 5577 // code and package path correct. 5578 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5579 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5580 } 5581 5582 if ((scanMode&SCAN_NO_DEX) == 0) { 5583 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5584 == DEX_OPT_FAILED) { 5585 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5586 removeDataDirsLI(pkg.packageName); 5587 } 5588 5589 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5590 } 5591 } 5592 5593 if (mFactoryTest && pkg.requestedPermissions.contains( 5594 android.Manifest.permission.FACTORY_TEST)) { 5595 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5596 } 5597 5598 ArrayList<PackageParser.Package> clientLibPkgs = null; 5599 5600 // writer 5601 synchronized (mPackages) { 5602 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5603 // Only system apps can add new shared libraries. 5604 if (pkg.libraryNames != null) { 5605 for (int i=0; i<pkg.libraryNames.size(); i++) { 5606 String name = pkg.libraryNames.get(i); 5607 boolean allowed = false; 5608 if (isUpdatedSystemApp(pkg)) { 5609 // New library entries can only be added through the 5610 // system image. This is important to get rid of a lot 5611 // of nasty edge cases: for example if we allowed a non- 5612 // system update of the app to add a library, then uninstalling 5613 // the update would make the library go away, and assumptions 5614 // we made such as through app install filtering would now 5615 // have allowed apps on the device which aren't compatible 5616 // with it. Better to just have the restriction here, be 5617 // conservative, and create many fewer cases that can negatively 5618 // impact the user experience. 5619 final PackageSetting sysPs = mSettings 5620 .getDisabledSystemPkgLPr(pkg.packageName); 5621 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5622 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5623 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5624 allowed = true; 5625 allowed = true; 5626 break; 5627 } 5628 } 5629 } 5630 } else { 5631 allowed = true; 5632 } 5633 if (allowed) { 5634 if (!mSharedLibraries.containsKey(name)) { 5635 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5636 } else if (!name.equals(pkg.packageName)) { 5637 Slog.w(TAG, "Package " + pkg.packageName + " library " 5638 + name + " already exists; skipping"); 5639 } 5640 } else { 5641 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5642 + name + " that is not declared on system image; skipping"); 5643 } 5644 } 5645 if ((scanMode&SCAN_BOOTING) == 0) { 5646 // If we are not booting, we need to update any applications 5647 // that are clients of our shared library. If we are booting, 5648 // this will all be done once the scan is complete. 5649 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5650 } 5651 } 5652 } 5653 } 5654 5655 // We also need to dexopt any apps that are dependent on this library. Note that 5656 // if these fail, we should abort the install since installing the library will 5657 // result in some apps being broken. 5658 if (clientLibPkgs != null) { 5659 if ((scanMode&SCAN_NO_DEX) == 0) { 5660 for (int i=0; i<clientLibPkgs.size(); i++) { 5661 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5662 if (performDexOptLI(clientPkg, null /* instruction sets */, 5663 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5664 == DEX_OPT_FAILED) { 5665 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5666 removeDataDirsLI(pkg.packageName); 5667 } 5668 5669 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5670 "scanPackageLI failed to dexopt clientLibPkgs"); 5671 } 5672 } 5673 } 5674 } 5675 5676 // Request the ActivityManager to kill the process(only for existing packages) 5677 // so that we do not end up in a confused state while the user is still using the older 5678 // version of the application while the new one gets installed. 5679 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5680 // If the package lives in an asec, tell everyone that the container is going 5681 // away so they can clean up any references to its resources (which would prevent 5682 // vold from being able to unmount the asec) 5683 if (isForwardLocked(pkg) || isExternal(pkg)) { 5684 if (DEBUG_INSTALL) { 5685 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5686 } 5687 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5688 final ArrayList<String> pkgList = new ArrayList<String>(1); 5689 pkgList.add(pkg.applicationInfo.packageName); 5690 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5691 } 5692 5693 // Post the request that it be killed now that the going-away broadcast is en route 5694 killApplication(pkg.applicationInfo.packageName, 5695 pkg.applicationInfo.uid, "update pkg"); 5696 } 5697 5698 // Also need to kill any apps that are dependent on the library. 5699 if (clientLibPkgs != null) { 5700 for (int i=0; i<clientLibPkgs.size(); i++) { 5701 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5702 killApplication(clientPkg.applicationInfo.packageName, 5703 clientPkg.applicationInfo.uid, "update lib"); 5704 } 5705 } 5706 5707 // writer 5708 synchronized (mPackages) { 5709 // We don't expect installation to fail beyond this point, 5710 if ((scanMode&SCAN_MONITOR) != 0) { 5711 mAppDirs.put(pkg.codePath, pkg); 5712 } 5713 // Add the new setting to mSettings 5714 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5715 // Add the new setting to mPackages 5716 mPackages.put(pkg.applicationInfo.packageName, pkg); 5717 // Make sure we don't accidentally delete its data. 5718 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5719 while (iter.hasNext()) { 5720 PackageCleanItem item = iter.next(); 5721 if (pkgName.equals(item.packageName)) { 5722 iter.remove(); 5723 } 5724 } 5725 5726 // Take care of first install / last update times. 5727 if (currentTime != 0) { 5728 if (pkgSetting.firstInstallTime == 0) { 5729 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5730 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5731 pkgSetting.lastUpdateTime = currentTime; 5732 } 5733 } else if (pkgSetting.firstInstallTime == 0) { 5734 // We need *something*. Take time time stamp of the file. 5735 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5736 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5737 if (scanFileTime != pkgSetting.timeStamp) { 5738 // A package on the system image has changed; consider this 5739 // to be an update. 5740 pkgSetting.lastUpdateTime = scanFileTime; 5741 } 5742 } 5743 5744 // Add the package's KeySets to the global KeySetManagerService 5745 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5746 try { 5747 // Old KeySetData no longer valid. 5748 ksms.removeAppKeySetDataLPw(pkg.packageName); 5749 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5750 if (pkg.mKeySetMapping != null) { 5751 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5752 pkg.mKeySetMapping.entrySet()) { 5753 if (entry.getValue() != null) { 5754 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5755 entry.getValue(), entry.getKey()); 5756 } 5757 } 5758 if (pkg.mUpgradeKeySets != null) { 5759 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5760 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5761 } 5762 } 5763 } 5764 } catch (NullPointerException e) { 5765 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5766 } catch (IllegalArgumentException e) { 5767 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5768 } 5769 5770 int N = pkg.providers.size(); 5771 StringBuilder r = null; 5772 int i; 5773 for (i=0; i<N; i++) { 5774 PackageParser.Provider p = pkg.providers.get(i); 5775 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5776 p.info.processName, pkg.applicationInfo.uid); 5777 mProviders.addProvider(p); 5778 p.syncable = p.info.isSyncable; 5779 if (p.info.authority != null) { 5780 String names[] = p.info.authority.split(";"); 5781 p.info.authority = null; 5782 for (int j = 0; j < names.length; j++) { 5783 if (j == 1 && p.syncable) { 5784 // We only want the first authority for a provider to possibly be 5785 // syncable, so if we already added this provider using a different 5786 // authority clear the syncable flag. We copy the provider before 5787 // changing it because the mProviders object contains a reference 5788 // to a provider that we don't want to change. 5789 // Only do this for the second authority since the resulting provider 5790 // object can be the same for all future authorities for this provider. 5791 p = new PackageParser.Provider(p); 5792 p.syncable = false; 5793 } 5794 if (!mProvidersByAuthority.containsKey(names[j])) { 5795 mProvidersByAuthority.put(names[j], p); 5796 if (p.info.authority == null) { 5797 p.info.authority = names[j]; 5798 } else { 5799 p.info.authority = p.info.authority + ";" + names[j]; 5800 } 5801 if (DEBUG_PACKAGE_SCANNING) { 5802 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5803 Log.d(TAG, "Registered content provider: " + names[j] 5804 + ", className = " + p.info.name + ", isSyncable = " 5805 + p.info.isSyncable); 5806 } 5807 } else { 5808 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5809 Slog.w(TAG, "Skipping provider name " + names[j] + 5810 " (in package " + pkg.applicationInfo.packageName + 5811 "): name already used by " 5812 + ((other != null && other.getComponentName() != null) 5813 ? other.getComponentName().getPackageName() : "?")); 5814 } 5815 } 5816 } 5817 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5818 if (r == null) { 5819 r = new StringBuilder(256); 5820 } else { 5821 r.append(' '); 5822 } 5823 r.append(p.info.name); 5824 } 5825 } 5826 if (r != null) { 5827 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5828 } 5829 5830 N = pkg.services.size(); 5831 r = null; 5832 for (i=0; i<N; i++) { 5833 PackageParser.Service s = pkg.services.get(i); 5834 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5835 s.info.processName, pkg.applicationInfo.uid); 5836 mServices.addService(s); 5837 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5838 if (r == null) { 5839 r = new StringBuilder(256); 5840 } else { 5841 r.append(' '); 5842 } 5843 r.append(s.info.name); 5844 } 5845 } 5846 if (r != null) { 5847 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5848 } 5849 5850 N = pkg.receivers.size(); 5851 r = null; 5852 for (i=0; i<N; i++) { 5853 PackageParser.Activity a = pkg.receivers.get(i); 5854 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5855 a.info.processName, pkg.applicationInfo.uid); 5856 mReceivers.addActivity(a, "receiver"); 5857 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5858 if (r == null) { 5859 r = new StringBuilder(256); 5860 } else { 5861 r.append(' '); 5862 } 5863 r.append(a.info.name); 5864 } 5865 } 5866 if (r != null) { 5867 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5868 } 5869 5870 N = pkg.activities.size(); 5871 r = null; 5872 for (i=0; i<N; i++) { 5873 PackageParser.Activity a = pkg.activities.get(i); 5874 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5875 a.info.processName, pkg.applicationInfo.uid); 5876 mActivities.addActivity(a, "activity"); 5877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5878 if (r == null) { 5879 r = new StringBuilder(256); 5880 } else { 5881 r.append(' '); 5882 } 5883 r.append(a.info.name); 5884 } 5885 } 5886 if (r != null) { 5887 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5888 } 5889 5890 N = pkg.permissionGroups.size(); 5891 r = null; 5892 for (i=0; i<N; i++) { 5893 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5894 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5895 if (cur == null) { 5896 mPermissionGroups.put(pg.info.name, pg); 5897 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5898 if (r == null) { 5899 r = new StringBuilder(256); 5900 } else { 5901 r.append(' '); 5902 } 5903 r.append(pg.info.name); 5904 } 5905 } else { 5906 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5907 + pg.info.packageName + " ignored: original from " 5908 + cur.info.packageName); 5909 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5910 if (r == null) { 5911 r = new StringBuilder(256); 5912 } else { 5913 r.append(' '); 5914 } 5915 r.append("DUP:"); 5916 r.append(pg.info.name); 5917 } 5918 } 5919 } 5920 if (r != null) { 5921 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5922 } 5923 5924 N = pkg.permissions.size(); 5925 r = null; 5926 for (i=0; i<N; i++) { 5927 PackageParser.Permission p = pkg.permissions.get(i); 5928 HashMap<String, BasePermission> permissionMap = 5929 p.tree ? mSettings.mPermissionTrees 5930 : mSettings.mPermissions; 5931 p.group = mPermissionGroups.get(p.info.group); 5932 if (p.info.group == null || p.group != null) { 5933 BasePermission bp = permissionMap.get(p.info.name); 5934 if (bp == null) { 5935 bp = new BasePermission(p.info.name, p.info.packageName, 5936 BasePermission.TYPE_NORMAL); 5937 permissionMap.put(p.info.name, bp); 5938 } 5939 if (bp.perm == null) { 5940 if (bp.sourcePackage != null 5941 && !bp.sourcePackage.equals(p.info.packageName)) { 5942 // If this is a permission that was formerly defined by a non-system 5943 // app, but is now defined by a system app (following an upgrade), 5944 // discard the previous declaration and consider the system's to be 5945 // canonical. 5946 if (isSystemApp(p.owner)) { 5947 String msg = "New decl " + p.owner + " of permission " 5948 + p.info.name + " is system"; 5949 reportSettingsProblem(Log.WARN, msg); 5950 bp.sourcePackage = null; 5951 } 5952 } 5953 if (bp.sourcePackage == null 5954 || bp.sourcePackage.equals(p.info.packageName)) { 5955 BasePermission tree = findPermissionTreeLP(p.info.name); 5956 if (tree == null 5957 || tree.sourcePackage.equals(p.info.packageName)) { 5958 bp.packageSetting = pkgSetting; 5959 bp.perm = p; 5960 bp.uid = pkg.applicationInfo.uid; 5961 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5962 if (r == null) { 5963 r = new StringBuilder(256); 5964 } else { 5965 r.append(' '); 5966 } 5967 r.append(p.info.name); 5968 } 5969 } else { 5970 Slog.w(TAG, "Permission " + p.info.name + " from package " 5971 + p.info.packageName + " ignored: base tree " 5972 + tree.name + " is from package " 5973 + tree.sourcePackage); 5974 } 5975 } else { 5976 Slog.w(TAG, "Permission " + p.info.name + " from package " 5977 + p.info.packageName + " ignored: original from " 5978 + bp.sourcePackage); 5979 } 5980 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5981 if (r == null) { 5982 r = new StringBuilder(256); 5983 } else { 5984 r.append(' '); 5985 } 5986 r.append("DUP:"); 5987 r.append(p.info.name); 5988 } 5989 if (bp.perm == p) { 5990 bp.protectionLevel = p.info.protectionLevel; 5991 } 5992 } else { 5993 Slog.w(TAG, "Permission " + p.info.name + " from package " 5994 + p.info.packageName + " ignored: no group " 5995 + p.group); 5996 } 5997 } 5998 if (r != null) { 5999 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6000 } 6001 6002 N = pkg.instrumentation.size(); 6003 r = null; 6004 for (i=0; i<N; i++) { 6005 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6006 a.info.packageName = pkg.applicationInfo.packageName; 6007 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6008 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6009 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6010 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6011 a.info.dataDir = pkg.applicationInfo.dataDir; 6012 6013 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6014 // need other information about the application, like the ABI and what not ? 6015 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6016 mInstrumentation.put(a.getComponentName(), a); 6017 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6018 if (r == null) { 6019 r = new StringBuilder(256); 6020 } else { 6021 r.append(' '); 6022 } 6023 r.append(a.info.name); 6024 } 6025 } 6026 if (r != null) { 6027 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6028 } 6029 6030 if (pkg.protectedBroadcasts != null) { 6031 N = pkg.protectedBroadcasts.size(); 6032 for (i=0; i<N; i++) { 6033 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6034 } 6035 } 6036 6037 pkgSetting.setTimeStamp(scanFileTime); 6038 6039 // Create idmap files for pairs of (packages, overlay packages). 6040 // Note: "android", ie framework-res.apk, is handled by native layers. 6041 if (pkg.mOverlayTarget != null) { 6042 // This is an overlay package. 6043 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6044 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6045 mOverlays.put(pkg.mOverlayTarget, 6046 new HashMap<String, PackageParser.Package>()); 6047 } 6048 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6049 map.put(pkg.packageName, pkg); 6050 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6051 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6052 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6053 "scanPackageLI failed to createIdmap"); 6054 } 6055 } 6056 } else if (mOverlays.containsKey(pkg.packageName) && 6057 !pkg.packageName.equals("android")) { 6058 // This is a regular package, with one or more known overlay packages. 6059 createIdmapsForPackageLI(pkg); 6060 } 6061 } 6062 6063 return pkg; 6064 } 6065 6066 /** 6067 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6068 * i.e, so that all packages can be run inside a single process if required. 6069 * 6070 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6071 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6072 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6073 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6074 * updating a package that belongs to a shared user. 6075 * 6076 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6077 * adds unnecessary complexity. 6078 */ 6079 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6080 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6081 String requiredInstructionSet = null; 6082 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6083 requiredInstructionSet = VMRuntime.getInstructionSet( 6084 scannedPackage.applicationInfo.primaryCpuAbi); 6085 } 6086 6087 PackageSetting requirer = null; 6088 for (PackageSetting ps : packagesForUser) { 6089 // If packagesForUser contains scannedPackage, we skip it. This will happen 6090 // when scannedPackage is an update of an existing package. Without this check, 6091 // we will never be able to change the ABI of any package belonging to a shared 6092 // user, even if it's compatible with other packages. 6093 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6094 if (ps.primaryCpuAbiString == null) { 6095 continue; 6096 } 6097 6098 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6099 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6100 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6101 // this but there's not much we can do. 6102 String errorMessage = "Instruction set mismatch, " 6103 + ((requirer == null) ? "[caller]" : requirer) 6104 + " requires " + requiredInstructionSet + " whereas " + ps 6105 + " requires " + instructionSet; 6106 Slog.w(TAG, errorMessage); 6107 } 6108 6109 if (requiredInstructionSet == null) { 6110 requiredInstructionSet = instructionSet; 6111 requirer = ps; 6112 } 6113 } 6114 } 6115 6116 if (requiredInstructionSet != null) { 6117 String adjustedAbi; 6118 if (requirer != null) { 6119 // requirer != null implies that either scannedPackage was null or that scannedPackage 6120 // did not require an ABI, in which case we have to adjust scannedPackage to match 6121 // the ABI of the set (which is the same as requirer's ABI) 6122 adjustedAbi = requirer.primaryCpuAbiString; 6123 if (scannedPackage != null) { 6124 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6125 } 6126 } else { 6127 // requirer == null implies that we're updating all ABIs in the set to 6128 // match scannedPackage. 6129 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6130 } 6131 6132 for (PackageSetting ps : packagesForUser) { 6133 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6134 if (ps.primaryCpuAbiString != null) { 6135 continue; 6136 } 6137 6138 ps.primaryCpuAbiString = adjustedAbi; 6139 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6140 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6141 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6142 6143 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6144 deferDexOpt, true) == DEX_OPT_FAILED) { 6145 ps.primaryCpuAbiString = null; 6146 ps.pkg.applicationInfo.primaryCpuAbi = null; 6147 return; 6148 } else { 6149 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6150 } 6151 } 6152 } 6153 } 6154 } 6155 } 6156 6157 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6158 synchronized (mPackages) { 6159 mResolverReplaced = true; 6160 // Set up information for custom user intent resolution activity. 6161 mResolveActivity.applicationInfo = pkg.applicationInfo; 6162 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6163 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6164 mResolveActivity.processName = null; 6165 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6166 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6167 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6168 mResolveActivity.theme = 0; 6169 mResolveActivity.exported = true; 6170 mResolveActivity.enabled = true; 6171 mResolveInfo.activityInfo = mResolveActivity; 6172 mResolveInfo.priority = 0; 6173 mResolveInfo.preferredOrder = 0; 6174 mResolveInfo.match = 0; 6175 mResolveComponentName = mCustomResolverComponentName; 6176 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6177 mResolveComponentName); 6178 } 6179 } 6180 6181 private static String calculateApkRoot(final String codePathString) { 6182 final File codePath = new File(codePathString); 6183 final File codeRoot; 6184 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6185 codeRoot = Environment.getRootDirectory(); 6186 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6187 codeRoot = Environment.getOemDirectory(); 6188 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6189 codeRoot = Environment.getVendorDirectory(); 6190 } else { 6191 // Unrecognized code path; take its top real segment as the apk root: 6192 // e.g. /something/app/blah.apk => /something 6193 try { 6194 File f = codePath.getCanonicalFile(); 6195 File parent = f.getParentFile(); // non-null because codePath is a file 6196 File tmp; 6197 while ((tmp = parent.getParentFile()) != null) { 6198 f = parent; 6199 parent = tmp; 6200 } 6201 codeRoot = f; 6202 Slog.w(TAG, "Unrecognized code path " 6203 + codePath + " - using " + codeRoot); 6204 } catch (IOException e) { 6205 // Can't canonicalize the code path -- shenanigans? 6206 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6207 return Environment.getRootDirectory().getPath(); 6208 } 6209 } 6210 return codeRoot.getPath(); 6211 } 6212 6213 /** 6214 * Derive and set the location of native libraries for the given package, 6215 * which varies depending on where and how the package was installed. 6216 */ 6217 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6218 final ApplicationInfo info = pkg.applicationInfo; 6219 final String codePath = pkg.codePath; 6220 final File codeFile = new File(codePath); 6221 // If "/system/lib64/apkname" exists, assume that is the per-package 6222 // native library directory to use; otherwise use "/system/lib/apkname". 6223 final String apkRoot = calculateApkRoot(info.sourceDir); 6224 6225 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6226 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6227 6228 6229 info.nativeLibraryRootDir = null; 6230 info.nativeLibraryRootRequiresIsa = false; 6231 info.nativeLibraryDir = null; 6232 info.secondaryNativeLibraryDir = null; 6233 6234 if (isApkFile(codeFile)) { 6235 // Monolithic install 6236 if (bundledApp) { 6237 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6238 getPrimaryInstructionSet(info)); 6239 6240 // This is a bundled system app so choose the path based on the ABI. 6241 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6242 // is just the default path. 6243 final String apkName = deriveCodePathName(codePath); 6244 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6245 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6246 apkName).getAbsolutePath(); 6247 6248 if (info.secondaryCpuAbi != null) { 6249 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6250 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6251 secondaryLibDir, apkName).getAbsolutePath(); 6252 } 6253 } else if (asecApp) { 6254 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6255 .getAbsolutePath(); 6256 } else { 6257 final String apkName = deriveCodePathName(codePath); 6258 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6259 .getAbsolutePath(); 6260 } 6261 6262 info.nativeLibraryRootRequiresIsa = false; 6263 info.nativeLibraryDir = info.nativeLibraryRootDir; 6264 } else { 6265 // Cluster install 6266 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6267 info.nativeLibraryRootRequiresIsa = true; 6268 6269 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6270 getPrimaryInstructionSet(info)).getAbsolutePath(); 6271 6272 if (info.secondaryCpuAbi != null) { 6273 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6274 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6275 } 6276 } 6277 } 6278 6279 /** 6280 * Calculate the abis and roots for a bundled app. These can uniquely 6281 * be determined from the contents of the system partition, i.e whether 6282 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6283 * of this information, and instead assume that the system was built 6284 * sensibly. 6285 */ 6286 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6287 PackageSetting pkgSetting) { 6288 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6289 6290 // If "/system/lib64/apkname" exists, assume that is the per-package 6291 // native library directory to use; otherwise use "/system/lib/apkname". 6292 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6293 setBundledAppAbi(pkg, apkRoot, apkName); 6294 // pkgSetting might be null during rescan following uninstall of updates 6295 // to a bundled app, so accommodate that possibility. The settings in 6296 // that case will be established later from the parsed package. 6297 // 6298 // If the settings aren't null, sync them up with what we've just derived. 6299 // note that apkRoot isn't stored in the package settings. 6300 if (pkgSetting != null) { 6301 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6302 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6303 } 6304 } 6305 6306 /** 6307 * Deduces the ABI of a bundled app and sets the relevant fields on the 6308 * parsed pkg object. 6309 * 6310 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6311 * under which system libraries are installed. 6312 * @param apkName the name of the installed package. 6313 */ 6314 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6315 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6316 // or similar. 6317 final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6318 final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6319 6320 if (has64BitLibs && !has32BitLibs) { 6321 // The package has 64 bit libs, but not 32 bit libs. Its primary 6322 // ABI should be 64 bit. We can safely assume here that the bundled 6323 // native libraries correspond to the most preferred ABI in the list. 6324 6325 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6326 pkg.applicationInfo.secondaryCpuAbi = null; 6327 } else if (has32BitLibs && !has64BitLibs) { 6328 // The package has 32 bit libs but not 64 bit libs. Its primary 6329 // ABI should be 32 bit. 6330 6331 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6332 pkg.applicationInfo.secondaryCpuAbi = null; 6333 } else if (has32BitLibs && has64BitLibs) { 6334 // The application has both 64 and 32 bit bundled libraries. We check 6335 // here that the app declares multiArch support, and warn if it doesn't. 6336 // 6337 // We will be lenient here and record both ABIs. The primary will be the 6338 // ABI that's higher on the list, i.e, a device that's configured to prefer 6339 // 64 bit apps will see a 64 bit primary ABI, 6340 6341 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6342 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6343 } 6344 6345 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6346 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6347 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6348 } else { 6349 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6350 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6351 } 6352 } else { 6353 pkg.applicationInfo.primaryCpuAbi = null; 6354 pkg.applicationInfo.secondaryCpuAbi = null; 6355 } 6356 } 6357 6358 private static void createNativeLibrarySubdir(File path) throws IOException { 6359 if (!path.isDirectory()) { 6360 path.delete(); 6361 6362 if (!path.mkdir()) { 6363 throw new IOException("Cannot create " + path.getPath()); 6364 } 6365 6366 try { 6367 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6368 } catch (ErrnoException e) { 6369 throw new IOException("Cannot chmod native library directory " 6370 + path.getPath(), e); 6371 } 6372 } else if (!SELinux.restorecon(path)) { 6373 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6374 } 6375 } 6376 6377 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6378 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6379 createNativeLibrarySubdir(nativeLibraryRoot); 6380 6381 /* 6382 * If this is an internal application or our nativeLibraryPath points to 6383 * the app-lib directory, unpack the libraries if necessary. 6384 */ 6385 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6386 if (abi >= 0) { 6387 /* 6388 * If we have a matching instruction set, construct a subdir under the native 6389 * library root that corresponds to this instruction set. 6390 */ 6391 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6392 final File subDir; 6393 if (useIsaSubdir) { 6394 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6395 createNativeLibrarySubdir(isaSubdir); 6396 subDir = isaSubdir; 6397 } else { 6398 subDir = nativeLibraryRoot; 6399 } 6400 6401 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6402 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6403 return copyRet; 6404 } 6405 } 6406 6407 return abi; 6408 } 6409 6410 private void killApplication(String pkgName, int appId, String reason) { 6411 // Request the ActivityManager to kill the process(only for existing packages) 6412 // so that we do not end up in a confused state while the user is still using the older 6413 // version of the application while the new one gets installed. 6414 IActivityManager am = ActivityManagerNative.getDefault(); 6415 if (am != null) { 6416 try { 6417 am.killApplicationWithAppId(pkgName, appId, reason); 6418 } catch (RemoteException e) { 6419 } 6420 } 6421 } 6422 6423 void removePackageLI(PackageSetting ps, boolean chatty) { 6424 if (DEBUG_INSTALL) { 6425 if (chatty) 6426 Log.d(TAG, "Removing package " + ps.name); 6427 } 6428 6429 // writer 6430 synchronized (mPackages) { 6431 mPackages.remove(ps.name); 6432 if (ps.codePathString != null) { 6433 mAppDirs.remove(ps.codePathString); 6434 } 6435 6436 final PackageParser.Package pkg = ps.pkg; 6437 if (pkg != null) { 6438 cleanPackageDataStructuresLILPw(pkg, chatty); 6439 } 6440 } 6441 } 6442 6443 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6444 if (DEBUG_INSTALL) { 6445 if (chatty) 6446 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6447 } 6448 6449 // writer 6450 synchronized (mPackages) { 6451 mPackages.remove(pkg.applicationInfo.packageName); 6452 if (pkg.codePath != null) { 6453 mAppDirs.remove(pkg.codePath); 6454 } 6455 cleanPackageDataStructuresLILPw(pkg, chatty); 6456 } 6457 } 6458 6459 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6460 int N = pkg.providers.size(); 6461 StringBuilder r = null; 6462 int i; 6463 for (i=0; i<N; i++) { 6464 PackageParser.Provider p = pkg.providers.get(i); 6465 mProviders.removeProvider(p); 6466 if (p.info.authority == null) { 6467 6468 /* There was another ContentProvider with this authority when 6469 * this app was installed so this authority is null, 6470 * Ignore it as we don't have to unregister the provider. 6471 */ 6472 continue; 6473 } 6474 String names[] = p.info.authority.split(";"); 6475 for (int j = 0; j < names.length; j++) { 6476 if (mProvidersByAuthority.get(names[j]) == p) { 6477 mProvidersByAuthority.remove(names[j]); 6478 if (DEBUG_REMOVE) { 6479 if (chatty) 6480 Log.d(TAG, "Unregistered content provider: " + names[j] 6481 + ", className = " + p.info.name + ", isSyncable = " 6482 + p.info.isSyncable); 6483 } 6484 } 6485 } 6486 if (DEBUG_REMOVE && chatty) { 6487 if (r == null) { 6488 r = new StringBuilder(256); 6489 } else { 6490 r.append(' '); 6491 } 6492 r.append(p.info.name); 6493 } 6494 } 6495 if (r != null) { 6496 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6497 } 6498 6499 N = pkg.services.size(); 6500 r = null; 6501 for (i=0; i<N; i++) { 6502 PackageParser.Service s = pkg.services.get(i); 6503 mServices.removeService(s); 6504 if (chatty) { 6505 if (r == null) { 6506 r = new StringBuilder(256); 6507 } else { 6508 r.append(' '); 6509 } 6510 r.append(s.info.name); 6511 } 6512 } 6513 if (r != null) { 6514 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6515 } 6516 6517 N = pkg.receivers.size(); 6518 r = null; 6519 for (i=0; i<N; i++) { 6520 PackageParser.Activity a = pkg.receivers.get(i); 6521 mReceivers.removeActivity(a, "receiver"); 6522 if (DEBUG_REMOVE && chatty) { 6523 if (r == null) { 6524 r = new StringBuilder(256); 6525 } else { 6526 r.append(' '); 6527 } 6528 r.append(a.info.name); 6529 } 6530 } 6531 if (r != null) { 6532 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6533 } 6534 6535 N = pkg.activities.size(); 6536 r = null; 6537 for (i=0; i<N; i++) { 6538 PackageParser.Activity a = pkg.activities.get(i); 6539 mActivities.removeActivity(a, "activity"); 6540 if (DEBUG_REMOVE && chatty) { 6541 if (r == null) { 6542 r = new StringBuilder(256); 6543 } else { 6544 r.append(' '); 6545 } 6546 r.append(a.info.name); 6547 } 6548 } 6549 if (r != null) { 6550 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6551 } 6552 6553 N = pkg.permissions.size(); 6554 r = null; 6555 for (i=0; i<N; i++) { 6556 PackageParser.Permission p = pkg.permissions.get(i); 6557 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6558 if (bp == null) { 6559 bp = mSettings.mPermissionTrees.get(p.info.name); 6560 } 6561 if (bp != null && bp.perm == p) { 6562 bp.perm = null; 6563 if (DEBUG_REMOVE && chatty) { 6564 if (r == null) { 6565 r = new StringBuilder(256); 6566 } else { 6567 r.append(' '); 6568 } 6569 r.append(p.info.name); 6570 } 6571 } 6572 } 6573 if (r != null) { 6574 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6575 } 6576 6577 N = pkg.instrumentation.size(); 6578 r = null; 6579 for (i=0; i<N; i++) { 6580 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6581 mInstrumentation.remove(a.getComponentName()); 6582 if (DEBUG_REMOVE && chatty) { 6583 if (r == null) { 6584 r = new StringBuilder(256); 6585 } else { 6586 r.append(' '); 6587 } 6588 r.append(a.info.name); 6589 } 6590 } 6591 if (r != null) { 6592 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6593 } 6594 6595 r = null; 6596 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6597 // Only system apps can hold shared libraries. 6598 if (pkg.libraryNames != null) { 6599 for (i=0; i<pkg.libraryNames.size(); i++) { 6600 String name = pkg.libraryNames.get(i); 6601 SharedLibraryEntry cur = mSharedLibraries.get(name); 6602 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6603 mSharedLibraries.remove(name); 6604 if (DEBUG_REMOVE && chatty) { 6605 if (r == null) { 6606 r = new StringBuilder(256); 6607 } else { 6608 r.append(' '); 6609 } 6610 r.append(name); 6611 } 6612 } 6613 } 6614 } 6615 } 6616 if (r != null) { 6617 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6618 } 6619 } 6620 6621 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6622 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6623 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6624 return true; 6625 } 6626 } 6627 return false; 6628 } 6629 6630 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6631 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6632 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6633 6634 private void updatePermissionsLPw(String changingPkg, 6635 PackageParser.Package pkgInfo, int flags) { 6636 // Make sure there are no dangling permission trees. 6637 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6638 while (it.hasNext()) { 6639 final BasePermission bp = it.next(); 6640 if (bp.packageSetting == null) { 6641 // We may not yet have parsed the package, so just see if 6642 // we still know about its settings. 6643 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6644 } 6645 if (bp.packageSetting == null) { 6646 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6647 + " from package " + bp.sourcePackage); 6648 it.remove(); 6649 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6650 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6651 Slog.i(TAG, "Removing old permission tree: " + bp.name 6652 + " from package " + bp.sourcePackage); 6653 flags |= UPDATE_PERMISSIONS_ALL; 6654 it.remove(); 6655 } 6656 } 6657 } 6658 6659 // Make sure all dynamic permissions have been assigned to a package, 6660 // and make sure there are no dangling permissions. 6661 it = mSettings.mPermissions.values().iterator(); 6662 while (it.hasNext()) { 6663 final BasePermission bp = it.next(); 6664 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6665 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6666 + bp.name + " pkg=" + bp.sourcePackage 6667 + " info=" + bp.pendingInfo); 6668 if (bp.packageSetting == null && bp.pendingInfo != null) { 6669 final BasePermission tree = findPermissionTreeLP(bp.name); 6670 if (tree != null && tree.perm != null) { 6671 bp.packageSetting = tree.packageSetting; 6672 bp.perm = new PackageParser.Permission(tree.perm.owner, 6673 new PermissionInfo(bp.pendingInfo)); 6674 bp.perm.info.packageName = tree.perm.info.packageName; 6675 bp.perm.info.name = bp.name; 6676 bp.uid = tree.uid; 6677 } 6678 } 6679 } 6680 if (bp.packageSetting == null) { 6681 // We may not yet have parsed the package, so just see if 6682 // we still know about its settings. 6683 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6684 } 6685 if (bp.packageSetting == null) { 6686 Slog.w(TAG, "Removing dangling permission: " + bp.name 6687 + " from package " + bp.sourcePackage); 6688 it.remove(); 6689 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6690 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6691 Slog.i(TAG, "Removing old permission: " + bp.name 6692 + " from package " + bp.sourcePackage); 6693 flags |= UPDATE_PERMISSIONS_ALL; 6694 it.remove(); 6695 } 6696 } 6697 } 6698 6699 // Now update the permissions for all packages, in particular 6700 // replace the granted permissions of the system packages. 6701 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6702 for (PackageParser.Package pkg : mPackages.values()) { 6703 if (pkg != pkgInfo) { 6704 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6705 } 6706 } 6707 } 6708 6709 if (pkgInfo != null) { 6710 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6711 } 6712 } 6713 6714 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6715 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6716 if (ps == null) { 6717 return; 6718 } 6719 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6720 HashSet<String> origPermissions = gp.grantedPermissions; 6721 boolean changedPermission = false; 6722 6723 if (replace) { 6724 ps.permissionsFixed = false; 6725 if (gp == ps) { 6726 origPermissions = new HashSet<String>(gp.grantedPermissions); 6727 gp.grantedPermissions.clear(); 6728 gp.gids = mGlobalGids; 6729 } 6730 } 6731 6732 if (gp.gids == null) { 6733 gp.gids = mGlobalGids; 6734 } 6735 6736 final int N = pkg.requestedPermissions.size(); 6737 for (int i=0; i<N; i++) { 6738 final String name = pkg.requestedPermissions.get(i); 6739 final boolean required = pkg.requestedPermissionsRequired.get(i); 6740 final BasePermission bp = mSettings.mPermissions.get(name); 6741 if (DEBUG_INSTALL) { 6742 if (gp != ps) { 6743 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6744 } 6745 } 6746 6747 if (bp == null || bp.packageSetting == null) { 6748 Slog.w(TAG, "Unknown permission " + name 6749 + " in package " + pkg.packageName); 6750 continue; 6751 } 6752 6753 final String perm = bp.name; 6754 boolean allowed; 6755 boolean allowedSig = false; 6756 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6757 if (level == PermissionInfo.PROTECTION_NORMAL 6758 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6759 // We grant a normal or dangerous permission if any of the following 6760 // are true: 6761 // 1) The permission is required 6762 // 2) The permission is optional, but was granted in the past 6763 // 3) The permission is optional, but was requested by an 6764 // app in /system (not /data) 6765 // 6766 // Otherwise, reject the permission. 6767 allowed = (required || origPermissions.contains(perm) 6768 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6769 } else if (bp.packageSetting == null) { 6770 // This permission is invalid; skip it. 6771 allowed = false; 6772 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6773 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6774 if (allowed) { 6775 allowedSig = true; 6776 } 6777 } else { 6778 allowed = false; 6779 } 6780 if (DEBUG_INSTALL) { 6781 if (gp != ps) { 6782 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6783 } 6784 } 6785 if (allowed) { 6786 if (!isSystemApp(ps) && ps.permissionsFixed) { 6787 // If this is an existing, non-system package, then 6788 // we can't add any new permissions to it. 6789 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6790 // Except... if this is a permission that was added 6791 // to the platform (note: need to only do this when 6792 // updating the platform). 6793 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6794 } 6795 } 6796 if (allowed) { 6797 if (!gp.grantedPermissions.contains(perm)) { 6798 changedPermission = true; 6799 gp.grantedPermissions.add(perm); 6800 gp.gids = appendInts(gp.gids, bp.gids); 6801 } else if (!ps.haveGids) { 6802 gp.gids = appendInts(gp.gids, bp.gids); 6803 } 6804 } else { 6805 Slog.w(TAG, "Not granting permission " + perm 6806 + " to package " + pkg.packageName 6807 + " because it was previously installed without"); 6808 } 6809 } else { 6810 if (gp.grantedPermissions.remove(perm)) { 6811 changedPermission = true; 6812 gp.gids = removeInts(gp.gids, bp.gids); 6813 Slog.i(TAG, "Un-granting permission " + perm 6814 + " from package " + pkg.packageName 6815 + " (protectionLevel=" + bp.protectionLevel 6816 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6817 + ")"); 6818 } else { 6819 Slog.w(TAG, "Not granting permission " + perm 6820 + " to package " + pkg.packageName 6821 + " (protectionLevel=" + bp.protectionLevel 6822 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6823 + ")"); 6824 } 6825 } 6826 } 6827 6828 if ((changedPermission || replace) && !ps.permissionsFixed && 6829 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6830 // This is the first that we have heard about this package, so the 6831 // permissions we have now selected are fixed until explicitly 6832 // changed. 6833 ps.permissionsFixed = true; 6834 } 6835 ps.haveGids = true; 6836 } 6837 6838 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6839 boolean allowed = false; 6840 final int NP = PackageParser.NEW_PERMISSIONS.length; 6841 for (int ip=0; ip<NP; ip++) { 6842 final PackageParser.NewPermissionInfo npi 6843 = PackageParser.NEW_PERMISSIONS[ip]; 6844 if (npi.name.equals(perm) 6845 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6846 allowed = true; 6847 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6848 + pkg.packageName); 6849 break; 6850 } 6851 } 6852 return allowed; 6853 } 6854 6855 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6856 BasePermission bp, HashSet<String> origPermissions) { 6857 boolean allowed; 6858 allowed = (compareSignatures( 6859 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6860 == PackageManager.SIGNATURE_MATCH) 6861 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6862 == PackageManager.SIGNATURE_MATCH); 6863 if (!allowed && (bp.protectionLevel 6864 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6865 if (isSystemApp(pkg)) { 6866 // For updated system applications, a system permission 6867 // is granted only if it had been defined by the original application. 6868 if (isUpdatedSystemApp(pkg)) { 6869 final PackageSetting sysPs = mSettings 6870 .getDisabledSystemPkgLPr(pkg.packageName); 6871 final GrantedPermissions origGp = sysPs.sharedUser != null 6872 ? sysPs.sharedUser : sysPs; 6873 6874 if (origGp.grantedPermissions.contains(perm)) { 6875 // If the original was granted this permission, we take 6876 // that grant decision as read and propagate it to the 6877 // update. 6878 allowed = true; 6879 } else { 6880 // The system apk may have been updated with an older 6881 // version of the one on the data partition, but which 6882 // granted a new system permission that it didn't have 6883 // before. In this case we do want to allow the app to 6884 // now get the new permission if the ancestral apk is 6885 // privileged to get it. 6886 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6887 for (int j=0; 6888 j<sysPs.pkg.requestedPermissions.size(); j++) { 6889 if (perm.equals( 6890 sysPs.pkg.requestedPermissions.get(j))) { 6891 allowed = true; 6892 break; 6893 } 6894 } 6895 } 6896 } 6897 } else { 6898 allowed = isPrivilegedApp(pkg); 6899 } 6900 } 6901 } 6902 if (!allowed && (bp.protectionLevel 6903 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6904 // For development permissions, a development permission 6905 // is granted only if it was already granted. 6906 allowed = origPermissions.contains(perm); 6907 } 6908 return allowed; 6909 } 6910 6911 final class ActivityIntentResolver 6912 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6913 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6914 boolean defaultOnly, int userId) { 6915 if (!sUserManager.exists(userId)) return null; 6916 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6917 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6918 } 6919 6920 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6921 int userId) { 6922 if (!sUserManager.exists(userId)) return null; 6923 mFlags = flags; 6924 return super.queryIntent(intent, resolvedType, 6925 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6926 } 6927 6928 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6929 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6930 if (!sUserManager.exists(userId)) return null; 6931 if (packageActivities == null) { 6932 return null; 6933 } 6934 mFlags = flags; 6935 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6936 final int N = packageActivities.size(); 6937 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6938 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6939 6940 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6941 for (int i = 0; i < N; ++i) { 6942 intentFilters = packageActivities.get(i).intents; 6943 if (intentFilters != null && intentFilters.size() > 0) { 6944 PackageParser.ActivityIntentInfo[] array = 6945 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6946 intentFilters.toArray(array); 6947 listCut.add(array); 6948 } 6949 } 6950 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6951 } 6952 6953 public final void addActivity(PackageParser.Activity a, String type) { 6954 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6955 mActivities.put(a.getComponentName(), a); 6956 if (DEBUG_SHOW_INFO) 6957 Log.v( 6958 TAG, " " + type + " " + 6959 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6960 if (DEBUG_SHOW_INFO) 6961 Log.v(TAG, " Class=" + a.info.name); 6962 final int NI = a.intents.size(); 6963 for (int j=0; j<NI; j++) { 6964 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6965 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6966 intent.setPriority(0); 6967 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6968 + a.className + " with priority > 0, forcing to 0"); 6969 } 6970 if (DEBUG_SHOW_INFO) { 6971 Log.v(TAG, " IntentFilter:"); 6972 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6973 } 6974 if (!intent.debugCheck()) { 6975 Log.w(TAG, "==> For Activity " + a.info.name); 6976 } 6977 addFilter(intent); 6978 } 6979 } 6980 6981 public final void removeActivity(PackageParser.Activity a, String type) { 6982 mActivities.remove(a.getComponentName()); 6983 if (DEBUG_SHOW_INFO) { 6984 Log.v(TAG, " " + type + " " 6985 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6986 : a.info.name) + ":"); 6987 Log.v(TAG, " Class=" + a.info.name); 6988 } 6989 final int NI = a.intents.size(); 6990 for (int j=0; j<NI; j++) { 6991 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6992 if (DEBUG_SHOW_INFO) { 6993 Log.v(TAG, " IntentFilter:"); 6994 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6995 } 6996 removeFilter(intent); 6997 } 6998 } 6999 7000 @Override 7001 protected boolean allowFilterResult( 7002 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7003 ActivityInfo filterAi = filter.activity.info; 7004 for (int i=dest.size()-1; i>=0; i--) { 7005 ActivityInfo destAi = dest.get(i).activityInfo; 7006 if (destAi.name == filterAi.name 7007 && destAi.packageName == filterAi.packageName) { 7008 return false; 7009 } 7010 } 7011 return true; 7012 } 7013 7014 @Override 7015 protected ActivityIntentInfo[] newArray(int size) { 7016 return new ActivityIntentInfo[size]; 7017 } 7018 7019 @Override 7020 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7021 if (!sUserManager.exists(userId)) return true; 7022 PackageParser.Package p = filter.activity.owner; 7023 if (p != null) { 7024 PackageSetting ps = (PackageSetting)p.mExtras; 7025 if (ps != null) { 7026 // System apps are never considered stopped for purposes of 7027 // filtering, because there may be no way for the user to 7028 // actually re-launch them. 7029 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7030 && ps.getStopped(userId); 7031 } 7032 } 7033 return false; 7034 } 7035 7036 @Override 7037 protected boolean isPackageForFilter(String packageName, 7038 PackageParser.ActivityIntentInfo info) { 7039 return packageName.equals(info.activity.owner.packageName); 7040 } 7041 7042 @Override 7043 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7044 int match, int userId) { 7045 if (!sUserManager.exists(userId)) return null; 7046 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7047 return null; 7048 } 7049 final PackageParser.Activity activity = info.activity; 7050 if (mSafeMode && (activity.info.applicationInfo.flags 7051 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7052 return null; 7053 } 7054 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7055 if (ps == null) { 7056 return null; 7057 } 7058 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7059 ps.readUserState(userId), userId); 7060 if (ai == null) { 7061 return null; 7062 } 7063 final ResolveInfo res = new ResolveInfo(); 7064 res.activityInfo = ai; 7065 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7066 res.filter = info; 7067 } 7068 res.priority = info.getPriority(); 7069 res.preferredOrder = activity.owner.mPreferredOrder; 7070 //System.out.println("Result: " + res.activityInfo.className + 7071 // " = " + res.priority); 7072 res.match = match; 7073 res.isDefault = info.hasDefault; 7074 res.labelRes = info.labelRes; 7075 res.nonLocalizedLabel = info.nonLocalizedLabel; 7076 if (userNeedsBadging(userId)) { 7077 res.noResourceId = true; 7078 } else { 7079 res.icon = info.icon; 7080 } 7081 res.system = isSystemApp(res.activityInfo.applicationInfo); 7082 return res; 7083 } 7084 7085 @Override 7086 protected void sortResults(List<ResolveInfo> results) { 7087 Collections.sort(results, mResolvePrioritySorter); 7088 } 7089 7090 @Override 7091 protected void dumpFilter(PrintWriter out, String prefix, 7092 PackageParser.ActivityIntentInfo filter) { 7093 out.print(prefix); out.print( 7094 Integer.toHexString(System.identityHashCode(filter.activity))); 7095 out.print(' '); 7096 filter.activity.printComponentShortName(out); 7097 out.print(" filter "); 7098 out.println(Integer.toHexString(System.identityHashCode(filter))); 7099 } 7100 7101// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7102// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7103// final List<ResolveInfo> retList = Lists.newArrayList(); 7104// while (i.hasNext()) { 7105// final ResolveInfo resolveInfo = i.next(); 7106// if (isEnabledLP(resolveInfo.activityInfo)) { 7107// retList.add(resolveInfo); 7108// } 7109// } 7110// return retList; 7111// } 7112 7113 // Keys are String (activity class name), values are Activity. 7114 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7115 = new HashMap<ComponentName, PackageParser.Activity>(); 7116 private int mFlags; 7117 } 7118 7119 private final class ServiceIntentResolver 7120 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7121 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7122 boolean defaultOnly, int userId) { 7123 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7124 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7125 } 7126 7127 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7128 int userId) { 7129 if (!sUserManager.exists(userId)) return null; 7130 mFlags = flags; 7131 return super.queryIntent(intent, resolvedType, 7132 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7133 } 7134 7135 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7136 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7137 if (!sUserManager.exists(userId)) return null; 7138 if (packageServices == null) { 7139 return null; 7140 } 7141 mFlags = flags; 7142 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7143 final int N = packageServices.size(); 7144 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7145 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7146 7147 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7148 for (int i = 0; i < N; ++i) { 7149 intentFilters = packageServices.get(i).intents; 7150 if (intentFilters != null && intentFilters.size() > 0) { 7151 PackageParser.ServiceIntentInfo[] array = 7152 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7153 intentFilters.toArray(array); 7154 listCut.add(array); 7155 } 7156 } 7157 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7158 } 7159 7160 public final void addService(PackageParser.Service s) { 7161 mServices.put(s.getComponentName(), s); 7162 if (DEBUG_SHOW_INFO) { 7163 Log.v(TAG, " " 7164 + (s.info.nonLocalizedLabel != null 7165 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7166 Log.v(TAG, " Class=" + s.info.name); 7167 } 7168 final int NI = s.intents.size(); 7169 int j; 7170 for (j=0; j<NI; j++) { 7171 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7172 if (DEBUG_SHOW_INFO) { 7173 Log.v(TAG, " IntentFilter:"); 7174 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7175 } 7176 if (!intent.debugCheck()) { 7177 Log.w(TAG, "==> For Service " + s.info.name); 7178 } 7179 addFilter(intent); 7180 } 7181 } 7182 7183 public final void removeService(PackageParser.Service s) { 7184 mServices.remove(s.getComponentName()); 7185 if (DEBUG_SHOW_INFO) { 7186 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7187 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7188 Log.v(TAG, " Class=" + s.info.name); 7189 } 7190 final int NI = s.intents.size(); 7191 int j; 7192 for (j=0; j<NI; j++) { 7193 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7194 if (DEBUG_SHOW_INFO) { 7195 Log.v(TAG, " IntentFilter:"); 7196 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7197 } 7198 removeFilter(intent); 7199 } 7200 } 7201 7202 @Override 7203 protected boolean allowFilterResult( 7204 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7205 ServiceInfo filterSi = filter.service.info; 7206 for (int i=dest.size()-1; i>=0; i--) { 7207 ServiceInfo destAi = dest.get(i).serviceInfo; 7208 if (destAi.name == filterSi.name 7209 && destAi.packageName == filterSi.packageName) { 7210 return false; 7211 } 7212 } 7213 return true; 7214 } 7215 7216 @Override 7217 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7218 return new PackageParser.ServiceIntentInfo[size]; 7219 } 7220 7221 @Override 7222 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7223 if (!sUserManager.exists(userId)) return true; 7224 PackageParser.Package p = filter.service.owner; 7225 if (p != null) { 7226 PackageSetting ps = (PackageSetting)p.mExtras; 7227 if (ps != null) { 7228 // System apps are never considered stopped for purposes of 7229 // filtering, because there may be no way for the user to 7230 // actually re-launch them. 7231 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7232 && ps.getStopped(userId); 7233 } 7234 } 7235 return false; 7236 } 7237 7238 @Override 7239 protected boolean isPackageForFilter(String packageName, 7240 PackageParser.ServiceIntentInfo info) { 7241 return packageName.equals(info.service.owner.packageName); 7242 } 7243 7244 @Override 7245 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7246 int match, int userId) { 7247 if (!sUserManager.exists(userId)) return null; 7248 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7249 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7250 return null; 7251 } 7252 final PackageParser.Service service = info.service; 7253 if (mSafeMode && (service.info.applicationInfo.flags 7254 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7255 return null; 7256 } 7257 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7258 if (ps == null) { 7259 return null; 7260 } 7261 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7262 ps.readUserState(userId), userId); 7263 if (si == null) { 7264 return null; 7265 } 7266 final ResolveInfo res = new ResolveInfo(); 7267 res.serviceInfo = si; 7268 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7269 res.filter = filter; 7270 } 7271 res.priority = info.getPriority(); 7272 res.preferredOrder = service.owner.mPreferredOrder; 7273 //System.out.println("Result: " + res.activityInfo.className + 7274 // " = " + res.priority); 7275 res.match = match; 7276 res.isDefault = info.hasDefault; 7277 res.labelRes = info.labelRes; 7278 res.nonLocalizedLabel = info.nonLocalizedLabel; 7279 res.icon = info.icon; 7280 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7281 return res; 7282 } 7283 7284 @Override 7285 protected void sortResults(List<ResolveInfo> results) { 7286 Collections.sort(results, mResolvePrioritySorter); 7287 } 7288 7289 @Override 7290 protected void dumpFilter(PrintWriter out, String prefix, 7291 PackageParser.ServiceIntentInfo filter) { 7292 out.print(prefix); out.print( 7293 Integer.toHexString(System.identityHashCode(filter.service))); 7294 out.print(' '); 7295 filter.service.printComponentShortName(out); 7296 out.print(" filter "); 7297 out.println(Integer.toHexString(System.identityHashCode(filter))); 7298 } 7299 7300// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7301// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7302// final List<ResolveInfo> retList = Lists.newArrayList(); 7303// while (i.hasNext()) { 7304// final ResolveInfo resolveInfo = (ResolveInfo) i; 7305// if (isEnabledLP(resolveInfo.serviceInfo)) { 7306// retList.add(resolveInfo); 7307// } 7308// } 7309// return retList; 7310// } 7311 7312 // Keys are String (activity class name), values are Activity. 7313 private final HashMap<ComponentName, PackageParser.Service> mServices 7314 = new HashMap<ComponentName, PackageParser.Service>(); 7315 private int mFlags; 7316 }; 7317 7318 private final class ProviderIntentResolver 7319 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7320 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7321 boolean defaultOnly, int userId) { 7322 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7323 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7324 } 7325 7326 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7327 int userId) { 7328 if (!sUserManager.exists(userId)) 7329 return null; 7330 mFlags = flags; 7331 return super.queryIntent(intent, resolvedType, 7332 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7333 } 7334 7335 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7336 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7337 if (!sUserManager.exists(userId)) 7338 return null; 7339 if (packageProviders == null) { 7340 return null; 7341 } 7342 mFlags = flags; 7343 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7344 final int N = packageProviders.size(); 7345 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7346 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7347 7348 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7349 for (int i = 0; i < N; ++i) { 7350 intentFilters = packageProviders.get(i).intents; 7351 if (intentFilters != null && intentFilters.size() > 0) { 7352 PackageParser.ProviderIntentInfo[] array = 7353 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7354 intentFilters.toArray(array); 7355 listCut.add(array); 7356 } 7357 } 7358 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7359 } 7360 7361 public final void addProvider(PackageParser.Provider p) { 7362 if (mProviders.containsKey(p.getComponentName())) { 7363 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7364 return; 7365 } 7366 7367 mProviders.put(p.getComponentName(), p); 7368 if (DEBUG_SHOW_INFO) { 7369 Log.v(TAG, " " 7370 + (p.info.nonLocalizedLabel != null 7371 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7372 Log.v(TAG, " Class=" + p.info.name); 7373 } 7374 final int NI = p.intents.size(); 7375 int j; 7376 for (j = 0; j < NI; j++) { 7377 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7378 if (DEBUG_SHOW_INFO) { 7379 Log.v(TAG, " IntentFilter:"); 7380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7381 } 7382 if (!intent.debugCheck()) { 7383 Log.w(TAG, "==> For Provider " + p.info.name); 7384 } 7385 addFilter(intent); 7386 } 7387 } 7388 7389 public final void removeProvider(PackageParser.Provider p) { 7390 mProviders.remove(p.getComponentName()); 7391 if (DEBUG_SHOW_INFO) { 7392 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7393 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7394 Log.v(TAG, " Class=" + p.info.name); 7395 } 7396 final int NI = p.intents.size(); 7397 int j; 7398 for (j = 0; j < NI; j++) { 7399 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7400 if (DEBUG_SHOW_INFO) { 7401 Log.v(TAG, " IntentFilter:"); 7402 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7403 } 7404 removeFilter(intent); 7405 } 7406 } 7407 7408 @Override 7409 protected boolean allowFilterResult( 7410 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7411 ProviderInfo filterPi = filter.provider.info; 7412 for (int i = dest.size() - 1; i >= 0; i--) { 7413 ProviderInfo destPi = dest.get(i).providerInfo; 7414 if (destPi.name == filterPi.name 7415 && destPi.packageName == filterPi.packageName) { 7416 return false; 7417 } 7418 } 7419 return true; 7420 } 7421 7422 @Override 7423 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7424 return new PackageParser.ProviderIntentInfo[size]; 7425 } 7426 7427 @Override 7428 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7429 if (!sUserManager.exists(userId)) 7430 return true; 7431 PackageParser.Package p = filter.provider.owner; 7432 if (p != null) { 7433 PackageSetting ps = (PackageSetting) p.mExtras; 7434 if (ps != null) { 7435 // System apps are never considered stopped for purposes of 7436 // filtering, because there may be no way for the user to 7437 // actually re-launch them. 7438 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7439 && ps.getStopped(userId); 7440 } 7441 } 7442 return false; 7443 } 7444 7445 @Override 7446 protected boolean isPackageForFilter(String packageName, 7447 PackageParser.ProviderIntentInfo info) { 7448 return packageName.equals(info.provider.owner.packageName); 7449 } 7450 7451 @Override 7452 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7453 int match, int userId) { 7454 if (!sUserManager.exists(userId)) 7455 return null; 7456 final PackageParser.ProviderIntentInfo info = filter; 7457 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7458 return null; 7459 } 7460 final PackageParser.Provider provider = info.provider; 7461 if (mSafeMode && (provider.info.applicationInfo.flags 7462 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7463 return null; 7464 } 7465 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7466 if (ps == null) { 7467 return null; 7468 } 7469 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7470 ps.readUserState(userId), userId); 7471 if (pi == null) { 7472 return null; 7473 } 7474 final ResolveInfo res = new ResolveInfo(); 7475 res.providerInfo = pi; 7476 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7477 res.filter = filter; 7478 } 7479 res.priority = info.getPriority(); 7480 res.preferredOrder = provider.owner.mPreferredOrder; 7481 res.match = match; 7482 res.isDefault = info.hasDefault; 7483 res.labelRes = info.labelRes; 7484 res.nonLocalizedLabel = info.nonLocalizedLabel; 7485 res.icon = info.icon; 7486 res.system = isSystemApp(res.providerInfo.applicationInfo); 7487 return res; 7488 } 7489 7490 @Override 7491 protected void sortResults(List<ResolveInfo> results) { 7492 Collections.sort(results, mResolvePrioritySorter); 7493 } 7494 7495 @Override 7496 protected void dumpFilter(PrintWriter out, String prefix, 7497 PackageParser.ProviderIntentInfo filter) { 7498 out.print(prefix); 7499 out.print( 7500 Integer.toHexString(System.identityHashCode(filter.provider))); 7501 out.print(' '); 7502 filter.provider.printComponentShortName(out); 7503 out.print(" filter "); 7504 out.println(Integer.toHexString(System.identityHashCode(filter))); 7505 } 7506 7507 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7508 = new HashMap<ComponentName, PackageParser.Provider>(); 7509 private int mFlags; 7510 }; 7511 7512 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7513 new Comparator<ResolveInfo>() { 7514 public int compare(ResolveInfo r1, ResolveInfo r2) { 7515 int v1 = r1.priority; 7516 int v2 = r2.priority; 7517 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7518 if (v1 != v2) { 7519 return (v1 > v2) ? -1 : 1; 7520 } 7521 v1 = r1.preferredOrder; 7522 v2 = r2.preferredOrder; 7523 if (v1 != v2) { 7524 return (v1 > v2) ? -1 : 1; 7525 } 7526 if (r1.isDefault != r2.isDefault) { 7527 return r1.isDefault ? -1 : 1; 7528 } 7529 v1 = r1.match; 7530 v2 = r2.match; 7531 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7532 if (v1 != v2) { 7533 return (v1 > v2) ? -1 : 1; 7534 } 7535 if (r1.system != r2.system) { 7536 return r1.system ? -1 : 1; 7537 } 7538 return 0; 7539 } 7540 }; 7541 7542 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7543 new Comparator<ProviderInfo>() { 7544 public int compare(ProviderInfo p1, ProviderInfo p2) { 7545 final int v1 = p1.initOrder; 7546 final int v2 = p2.initOrder; 7547 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7548 } 7549 }; 7550 7551 static final void sendPackageBroadcast(String action, String pkg, 7552 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7553 int[] userIds) { 7554 IActivityManager am = ActivityManagerNative.getDefault(); 7555 if (am != null) { 7556 try { 7557 if (userIds == null) { 7558 userIds = am.getRunningUserIds(); 7559 } 7560 for (int id : userIds) { 7561 final Intent intent = new Intent(action, 7562 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7563 if (extras != null) { 7564 intent.putExtras(extras); 7565 } 7566 if (targetPkg != null) { 7567 intent.setPackage(targetPkg); 7568 } 7569 // Modify the UID when posting to other users 7570 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7571 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7572 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7573 intent.putExtra(Intent.EXTRA_UID, uid); 7574 } 7575 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7576 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7577 if (DEBUG_BROADCASTS) { 7578 RuntimeException here = new RuntimeException("here"); 7579 here.fillInStackTrace(); 7580 Slog.d(TAG, "Sending to user " + id + ": " 7581 + intent.toShortString(false, true, false, false) 7582 + " " + intent.getExtras(), here); 7583 } 7584 am.broadcastIntent(null, intent, null, finishedReceiver, 7585 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7586 finishedReceiver != null, false, id); 7587 } 7588 } catch (RemoteException ex) { 7589 } 7590 } 7591 } 7592 7593 /** 7594 * Check if the external storage media is available. This is true if there 7595 * is a mounted external storage medium or if the external storage is 7596 * emulated. 7597 */ 7598 private boolean isExternalMediaAvailable() { 7599 return mMediaMounted || Environment.isExternalStorageEmulated(); 7600 } 7601 7602 @Override 7603 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7604 // writer 7605 synchronized (mPackages) { 7606 if (!isExternalMediaAvailable()) { 7607 // If the external storage is no longer mounted at this point, 7608 // the caller may not have been able to delete all of this 7609 // packages files and can not delete any more. Bail. 7610 return null; 7611 } 7612 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7613 if (lastPackage != null) { 7614 pkgs.remove(lastPackage); 7615 } 7616 if (pkgs.size() > 0) { 7617 return pkgs.get(0); 7618 } 7619 } 7620 return null; 7621 } 7622 7623 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7624 if (false) { 7625 RuntimeException here = new RuntimeException("here"); 7626 here.fillInStackTrace(); 7627 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7628 + " andCode=" + andCode, here); 7629 } 7630 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7631 userId, andCode ? 1 : 0, packageName)); 7632 } 7633 7634 void startCleaningPackages() { 7635 // reader 7636 synchronized (mPackages) { 7637 if (!isExternalMediaAvailable()) { 7638 return; 7639 } 7640 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7641 return; 7642 } 7643 } 7644 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7645 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7646 IActivityManager am = ActivityManagerNative.getDefault(); 7647 if (am != null) { 7648 try { 7649 am.startService(null, intent, null, UserHandle.USER_OWNER); 7650 } catch (RemoteException e) { 7651 } 7652 } 7653 } 7654 7655 private final class AppDirObserver extends FileObserver { 7656 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7657 super(path, mask); 7658 mRootDir = path; 7659 mIsRom = isrom; 7660 mIsPrivileged = isPrivileged; 7661 } 7662 7663 public void onEvent(int event, String path) { 7664 String removedPackage = null; 7665 int removedAppId = -1; 7666 int[] removedUsers = null; 7667 String addedPackage = null; 7668 int addedAppId = -1; 7669 int[] addedUsers = null; 7670 7671 // TODO post a message to the handler to obtain serial ordering 7672 synchronized (mInstallLock) { 7673 String fullPathStr = null; 7674 File fullPath = null; 7675 if (path != null) { 7676 fullPath = new File(mRootDir, path); 7677 fullPathStr = fullPath.getPath(); 7678 } 7679 7680 if (DEBUG_APP_DIR_OBSERVER) 7681 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7682 7683 if (!isApkFile(fullPath)) { 7684 if (DEBUG_APP_DIR_OBSERVER) 7685 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7686 return; 7687 } 7688 7689 // Ignore packages that are being installed or 7690 // have just been installed. 7691 if (ignoreCodePath(fullPathStr)) { 7692 return; 7693 } 7694 PackageParser.Package p = null; 7695 PackageSetting ps = null; 7696 // reader 7697 synchronized (mPackages) { 7698 p = mAppDirs.get(fullPathStr); 7699 if (p != null) { 7700 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7701 if (ps != null) { 7702 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7703 } else { 7704 removedUsers = sUserManager.getUserIds(); 7705 } 7706 } 7707 addedUsers = sUserManager.getUserIds(); 7708 } 7709 if ((event&REMOVE_EVENTS) != 0) { 7710 if (ps != null) { 7711 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7712 removePackageLI(ps, true); 7713 removedPackage = ps.name; 7714 removedAppId = ps.appId; 7715 } 7716 } 7717 7718 if ((event&ADD_EVENTS) != 0) { 7719 if (p == null) { 7720 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7721 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7722 if (mIsRom) { 7723 flags |= PackageParser.PARSE_IS_SYSTEM 7724 | PackageParser.PARSE_IS_SYSTEM_DIR; 7725 if (mIsPrivileged) { 7726 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7727 } 7728 } 7729 try { 7730 p = scanPackageLI(fullPath, flags, 7731 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7732 System.currentTimeMillis(), UserHandle.ALL, null); 7733 } catch (PackageManagerException e) { 7734 Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage()); 7735 p = null; 7736 } 7737 if (p != null) { 7738 /* 7739 * TODO this seems dangerous as the package may have 7740 * changed since we last acquired the mPackages 7741 * lock. 7742 */ 7743 // writer 7744 synchronized (mPackages) { 7745 updatePermissionsLPw(p.packageName, p, 7746 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7747 } 7748 addedPackage = p.applicationInfo.packageName; 7749 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7750 } 7751 } 7752 } 7753 7754 // reader 7755 synchronized (mPackages) { 7756 mSettings.writeLPr(); 7757 } 7758 } 7759 7760 if (removedPackage != null) { 7761 Bundle extras = new Bundle(1); 7762 extras.putInt(Intent.EXTRA_UID, removedAppId); 7763 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7764 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7765 extras, null, null, removedUsers); 7766 } 7767 if (addedPackage != null) { 7768 Bundle extras = new Bundle(1); 7769 extras.putInt(Intent.EXTRA_UID, addedAppId); 7770 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7771 extras, null, null, addedUsers); 7772 } 7773 } 7774 7775 private final String mRootDir; 7776 private final boolean mIsRom; 7777 private final boolean mIsPrivileged; 7778 } 7779 7780 @Override 7781 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7782 String installerPackageName, VerificationParams verificationParams, 7783 String packageAbiOverride) { 7784 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7785 null); 7786 7787 final File originFile = new File(originPath); 7788 final int uid = Binder.getCallingUid(); 7789 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7790 try { 7791 if (observer != null) { 7792 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7793 } 7794 } catch (RemoteException re) { 7795 } 7796 return; 7797 } 7798 7799 UserHandle user; 7800 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7801 user = UserHandle.ALL; 7802 } else { 7803 user = new UserHandle(UserHandle.getUserId(uid)); 7804 } 7805 7806 final int filteredFlags; 7807 if (uid == Process.SHELL_UID || uid == 0) { 7808 if (DEBUG_INSTALL) { 7809 Slog.v(TAG, "Install from ADB"); 7810 } 7811 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7812 } else { 7813 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7814 } 7815 7816 verificationParams.setInstallerUid(uid); 7817 7818 final Message msg = mHandler.obtainMessage(INIT_COPY); 7819 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7820 installerPackageName, verificationParams, user, packageAbiOverride); 7821 mHandler.sendMessage(msg); 7822 } 7823 7824 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7825 InstallSessionParams params, String installerPackageName, int installerUid, 7826 UserHandle user) { 7827 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7828 params.referrerUri, installerUid, null); 7829 7830 final Message msg = mHandler.obtainMessage(INIT_COPY); 7831 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7832 installerPackageName, verifParams, user, params.abiOverride); 7833 mHandler.sendMessage(msg); 7834 } 7835 7836 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7837 Bundle extras = new Bundle(1); 7838 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7839 7840 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7841 packageName, extras, null, null, new int[] {userId}); 7842 try { 7843 IActivityManager am = ActivityManagerNative.getDefault(); 7844 final boolean isSystem = 7845 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7846 if (isSystem && am.isUserRunning(userId, false)) { 7847 // The just-installed/enabled app is bundled on the system, so presumed 7848 // to be able to run automatically without needing an explicit launch. 7849 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7850 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7851 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7852 .setPackage(packageName); 7853 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7854 android.app.AppOpsManager.OP_NONE, false, false, userId); 7855 } 7856 } catch (RemoteException e) { 7857 // shouldn't happen 7858 Slog.w(TAG, "Unable to bootstrap installed package", e); 7859 } 7860 } 7861 7862 @Override 7863 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7864 int userId) { 7865 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7866 PackageSetting pkgSetting; 7867 final int uid = Binder.getCallingUid(); 7868 if (UserHandle.getUserId(uid) != userId) { 7869 mContext.enforceCallingOrSelfPermission( 7870 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7871 "setApplicationBlockedSetting for user " + userId); 7872 } 7873 7874 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7875 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7876 return false; 7877 } 7878 7879 long callingId = Binder.clearCallingIdentity(); 7880 try { 7881 boolean sendAdded = false; 7882 boolean sendRemoved = false; 7883 // writer 7884 synchronized (mPackages) { 7885 pkgSetting = mSettings.mPackages.get(packageName); 7886 if (pkgSetting == null) { 7887 return false; 7888 } 7889 if (pkgSetting.getBlocked(userId) != blocked) { 7890 pkgSetting.setBlocked(blocked, userId); 7891 mSettings.writePackageRestrictionsLPr(userId); 7892 if (blocked) { 7893 sendRemoved = true; 7894 } else { 7895 sendAdded = true; 7896 } 7897 } 7898 } 7899 if (sendAdded) { 7900 sendPackageAddedForUser(packageName, pkgSetting, userId); 7901 return true; 7902 } 7903 if (sendRemoved) { 7904 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7905 "blocking pkg"); 7906 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7907 } 7908 } finally { 7909 Binder.restoreCallingIdentity(callingId); 7910 } 7911 return false; 7912 } 7913 7914 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7915 int userId) { 7916 final PackageRemovedInfo info = new PackageRemovedInfo(); 7917 info.removedPackage = packageName; 7918 info.removedUsers = new int[] {userId}; 7919 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7920 info.sendBroadcast(false, false, false); 7921 } 7922 7923 /** 7924 * Returns true if application is not found or there was an error. Otherwise it returns 7925 * the blocked state of the package for the given user. 7926 */ 7927 @Override 7928 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7929 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7930 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7931 "getApplicationBlocked for user " + userId); 7932 PackageSetting pkgSetting; 7933 long callingId = Binder.clearCallingIdentity(); 7934 try { 7935 // writer 7936 synchronized (mPackages) { 7937 pkgSetting = mSettings.mPackages.get(packageName); 7938 if (pkgSetting == null) { 7939 return true; 7940 } 7941 return pkgSetting.getBlocked(userId); 7942 } 7943 } finally { 7944 Binder.restoreCallingIdentity(callingId); 7945 } 7946 } 7947 7948 /** 7949 * @hide 7950 */ 7951 @Override 7952 public int installExistingPackageAsUser(String packageName, int userId) { 7953 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7954 null); 7955 PackageSetting pkgSetting; 7956 final int uid = Binder.getCallingUid(); 7957 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7958 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7959 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7960 } 7961 7962 long callingId = Binder.clearCallingIdentity(); 7963 try { 7964 boolean sendAdded = false; 7965 Bundle extras = new Bundle(1); 7966 7967 // writer 7968 synchronized (mPackages) { 7969 pkgSetting = mSettings.mPackages.get(packageName); 7970 if (pkgSetting == null) { 7971 return PackageManager.INSTALL_FAILED_INVALID_URI; 7972 } 7973 if (!pkgSetting.getInstalled(userId)) { 7974 pkgSetting.setInstalled(true, userId); 7975 pkgSetting.setBlocked(false, userId); 7976 mSettings.writePackageRestrictionsLPr(userId); 7977 sendAdded = true; 7978 } 7979 } 7980 7981 if (sendAdded) { 7982 sendPackageAddedForUser(packageName, pkgSetting, userId); 7983 } 7984 } finally { 7985 Binder.restoreCallingIdentity(callingId); 7986 } 7987 7988 return PackageManager.INSTALL_SUCCEEDED; 7989 } 7990 7991 boolean isUserRestricted(int userId, String restrictionKey) { 7992 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7993 if (restrictions.getBoolean(restrictionKey, false)) { 7994 Log.w(TAG, "User is restricted: " + restrictionKey); 7995 return true; 7996 } 7997 return false; 7998 } 7999 8000 @Override 8001 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8002 mContext.enforceCallingOrSelfPermission( 8003 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8004 "Only package verification agents can verify applications"); 8005 8006 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8007 final PackageVerificationResponse response = new PackageVerificationResponse( 8008 verificationCode, Binder.getCallingUid()); 8009 msg.arg1 = id; 8010 msg.obj = response; 8011 mHandler.sendMessage(msg); 8012 } 8013 8014 @Override 8015 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8016 long millisecondsToDelay) { 8017 mContext.enforceCallingOrSelfPermission( 8018 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8019 "Only package verification agents can extend verification timeouts"); 8020 8021 final PackageVerificationState state = mPendingVerification.get(id); 8022 final PackageVerificationResponse response = new PackageVerificationResponse( 8023 verificationCodeAtTimeout, Binder.getCallingUid()); 8024 8025 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8026 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8027 } 8028 if (millisecondsToDelay < 0) { 8029 millisecondsToDelay = 0; 8030 } 8031 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8032 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8033 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8034 } 8035 8036 if ((state != null) && !state.timeoutExtended()) { 8037 state.extendTimeout(); 8038 8039 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8040 msg.arg1 = id; 8041 msg.obj = response; 8042 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8043 } 8044 } 8045 8046 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8047 int verificationCode, UserHandle user) { 8048 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8049 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8050 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8051 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8052 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8053 8054 mContext.sendBroadcastAsUser(intent, user, 8055 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8056 } 8057 8058 private ComponentName matchComponentForVerifier(String packageName, 8059 List<ResolveInfo> receivers) { 8060 ActivityInfo targetReceiver = null; 8061 8062 final int NR = receivers.size(); 8063 for (int i = 0; i < NR; i++) { 8064 final ResolveInfo info = receivers.get(i); 8065 if (info.activityInfo == null) { 8066 continue; 8067 } 8068 8069 if (packageName.equals(info.activityInfo.packageName)) { 8070 targetReceiver = info.activityInfo; 8071 break; 8072 } 8073 } 8074 8075 if (targetReceiver == null) { 8076 return null; 8077 } 8078 8079 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8080 } 8081 8082 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8083 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8084 if (pkgInfo.verifiers.length == 0) { 8085 return null; 8086 } 8087 8088 final int N = pkgInfo.verifiers.length; 8089 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8090 for (int i = 0; i < N; i++) { 8091 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8092 8093 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8094 receivers); 8095 if (comp == null) { 8096 continue; 8097 } 8098 8099 final int verifierUid = getUidForVerifier(verifierInfo); 8100 if (verifierUid == -1) { 8101 continue; 8102 } 8103 8104 if (DEBUG_VERIFY) { 8105 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8106 + " with the correct signature"); 8107 } 8108 sufficientVerifiers.add(comp); 8109 verificationState.addSufficientVerifier(verifierUid); 8110 } 8111 8112 return sufficientVerifiers; 8113 } 8114 8115 private int getUidForVerifier(VerifierInfo verifierInfo) { 8116 synchronized (mPackages) { 8117 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8118 if (pkg == null) { 8119 return -1; 8120 } else if (pkg.mSignatures.length != 1) { 8121 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8122 + " has more than one signature; ignoring"); 8123 return -1; 8124 } 8125 8126 /* 8127 * If the public key of the package's signature does not match 8128 * our expected public key, then this is a different package and 8129 * we should skip. 8130 */ 8131 8132 final byte[] expectedPublicKey; 8133 try { 8134 final Signature verifierSig = pkg.mSignatures[0]; 8135 final PublicKey publicKey = verifierSig.getPublicKey(); 8136 expectedPublicKey = publicKey.getEncoded(); 8137 } catch (CertificateException e) { 8138 return -1; 8139 } 8140 8141 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8142 8143 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8144 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8145 + " does not have the expected public key; ignoring"); 8146 return -1; 8147 } 8148 8149 return pkg.applicationInfo.uid; 8150 } 8151 } 8152 8153 @Override 8154 public void finishPackageInstall(int token) { 8155 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8156 8157 if (DEBUG_INSTALL) { 8158 Slog.v(TAG, "BM finishing package install for " + token); 8159 } 8160 8161 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8162 mHandler.sendMessage(msg); 8163 } 8164 8165 /** 8166 * Get the verification agent timeout. 8167 * 8168 * @return verification timeout in milliseconds 8169 */ 8170 private long getVerificationTimeout() { 8171 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8172 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8173 DEFAULT_VERIFICATION_TIMEOUT); 8174 } 8175 8176 /** 8177 * Get the default verification agent response code. 8178 * 8179 * @return default verification response code 8180 */ 8181 private int getDefaultVerificationResponse() { 8182 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8183 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8184 DEFAULT_VERIFICATION_RESPONSE); 8185 } 8186 8187 /** 8188 * Check whether or not package verification has been enabled. 8189 * 8190 * @return true if verification should be performed 8191 */ 8192 private boolean isVerificationEnabled(int userId, int flags) { 8193 if (!DEFAULT_VERIFY_ENABLE) { 8194 return false; 8195 } 8196 8197 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8198 8199 // Check if installing from ADB 8200 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8201 // Do not run verification in a test harness environment 8202 if (ActivityManager.isRunningInTestHarness()) { 8203 return false; 8204 } 8205 if (ensureVerifyAppsEnabled) { 8206 return true; 8207 } 8208 // Check if the developer does not want package verification for ADB installs 8209 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8210 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8211 return false; 8212 } 8213 } 8214 8215 if (ensureVerifyAppsEnabled) { 8216 return true; 8217 } 8218 8219 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8220 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8221 } 8222 8223 /** 8224 * Get the "allow unknown sources" setting. 8225 * 8226 * @return the current "allow unknown sources" setting 8227 */ 8228 private int getUnknownSourcesSettings() { 8229 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8230 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8231 -1); 8232 } 8233 8234 @Override 8235 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8236 final int uid = Binder.getCallingUid(); 8237 // writer 8238 synchronized (mPackages) { 8239 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8240 if (targetPackageSetting == null) { 8241 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8242 } 8243 8244 PackageSetting installerPackageSetting; 8245 if (installerPackageName != null) { 8246 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8247 if (installerPackageSetting == null) { 8248 throw new IllegalArgumentException("Unknown installer package: " 8249 + installerPackageName); 8250 } 8251 } else { 8252 installerPackageSetting = null; 8253 } 8254 8255 Signature[] callerSignature; 8256 Object obj = mSettings.getUserIdLPr(uid); 8257 if (obj != null) { 8258 if (obj instanceof SharedUserSetting) { 8259 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8260 } else if (obj instanceof PackageSetting) { 8261 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8262 } else { 8263 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8264 } 8265 } else { 8266 throw new SecurityException("Unknown calling uid " + uid); 8267 } 8268 8269 // Verify: can't set installerPackageName to a package that is 8270 // not signed with the same cert as the caller. 8271 if (installerPackageSetting != null) { 8272 if (compareSignatures(callerSignature, 8273 installerPackageSetting.signatures.mSignatures) 8274 != PackageManager.SIGNATURE_MATCH) { 8275 throw new SecurityException( 8276 "Caller does not have same cert as new installer package " 8277 + installerPackageName); 8278 } 8279 } 8280 8281 // Verify: if target already has an installer package, it must 8282 // be signed with the same cert as the caller. 8283 if (targetPackageSetting.installerPackageName != null) { 8284 PackageSetting setting = mSettings.mPackages.get( 8285 targetPackageSetting.installerPackageName); 8286 // If the currently set package isn't valid, then it's always 8287 // okay to change it. 8288 if (setting != null) { 8289 if (compareSignatures(callerSignature, 8290 setting.signatures.mSignatures) 8291 != PackageManager.SIGNATURE_MATCH) { 8292 throw new SecurityException( 8293 "Caller does not have same cert as old installer package " 8294 + targetPackageSetting.installerPackageName); 8295 } 8296 } 8297 } 8298 8299 // Okay! 8300 targetPackageSetting.installerPackageName = installerPackageName; 8301 scheduleWriteSettingsLocked(); 8302 } 8303 } 8304 8305 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8306 // Queue up an async operation since the package installation may take a little while. 8307 mHandler.post(new Runnable() { 8308 public void run() { 8309 mHandler.removeCallbacks(this); 8310 // Result object to be returned 8311 PackageInstalledInfo res = new PackageInstalledInfo(); 8312 res.returnCode = currentStatus; 8313 res.uid = -1; 8314 res.pkg = null; 8315 res.removedInfo = new PackageRemovedInfo(); 8316 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8317 args.doPreInstall(res.returnCode); 8318 synchronized (mInstallLock) { 8319 installPackageLI(args, true, res); 8320 } 8321 args.doPostInstall(res.returnCode, res.uid); 8322 } 8323 8324 // A restore should be performed at this point if (a) the install 8325 // succeeded, (b) the operation is not an update, and (c) the new 8326 // package has a backupAgent defined. 8327 final boolean update = res.removedInfo.removedPackage != null; 8328 boolean doRestore = (!update 8329 && res.pkg != null 8330 && res.pkg.applicationInfo.backupAgentName != null); 8331 8332 // Set up the post-install work request bookkeeping. This will be used 8333 // and cleaned up by the post-install event handling regardless of whether 8334 // there's a restore pass performed. Token values are >= 1. 8335 int token; 8336 if (mNextInstallToken < 0) mNextInstallToken = 1; 8337 token = mNextInstallToken++; 8338 8339 PostInstallData data = new PostInstallData(args, res); 8340 mRunningInstalls.put(token, data); 8341 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8342 8343 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8344 // Pass responsibility to the Backup Manager. It will perform a 8345 // restore if appropriate, then pass responsibility back to the 8346 // Package Manager to run the post-install observer callbacks 8347 // and broadcasts. 8348 IBackupManager bm = IBackupManager.Stub.asInterface( 8349 ServiceManager.getService(Context.BACKUP_SERVICE)); 8350 if (bm != null) { 8351 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8352 + " to BM for possible restore"); 8353 try { 8354 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8355 } catch (RemoteException e) { 8356 // can't happen; the backup manager is local 8357 } catch (Exception e) { 8358 Slog.e(TAG, "Exception trying to enqueue restore", e); 8359 doRestore = false; 8360 } 8361 } else { 8362 Slog.e(TAG, "Backup Manager not found!"); 8363 doRestore = false; 8364 } 8365 } 8366 8367 if (!doRestore) { 8368 // No restore possible, or the Backup Manager was mysteriously not 8369 // available -- just fire the post-install work request directly. 8370 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8371 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8372 mHandler.sendMessage(msg); 8373 } 8374 } 8375 }); 8376 } 8377 8378 private abstract class HandlerParams { 8379 private static final int MAX_RETRIES = 4; 8380 8381 /** 8382 * Number of times startCopy() has been attempted and had a non-fatal 8383 * error. 8384 */ 8385 private int mRetries = 0; 8386 8387 /** User handle for the user requesting the information or installation. */ 8388 private final UserHandle mUser; 8389 8390 HandlerParams(UserHandle user) { 8391 mUser = user; 8392 } 8393 8394 UserHandle getUser() { 8395 return mUser; 8396 } 8397 8398 final boolean startCopy() { 8399 boolean res; 8400 try { 8401 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8402 8403 if (++mRetries > MAX_RETRIES) { 8404 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8405 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8406 handleServiceError(); 8407 return false; 8408 } else { 8409 handleStartCopy(); 8410 res = true; 8411 } 8412 } catch (RemoteException e) { 8413 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8414 mHandler.sendEmptyMessage(MCS_RECONNECT); 8415 res = false; 8416 } 8417 handleReturnCode(); 8418 return res; 8419 } 8420 8421 final void serviceError() { 8422 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8423 handleServiceError(); 8424 handleReturnCode(); 8425 } 8426 8427 abstract void handleStartCopy() throws RemoteException; 8428 abstract void handleServiceError(); 8429 abstract void handleReturnCode(); 8430 } 8431 8432 class MeasureParams extends HandlerParams { 8433 private final PackageStats mStats; 8434 private boolean mSuccess; 8435 8436 private final IPackageStatsObserver mObserver; 8437 8438 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8439 super(new UserHandle(stats.userHandle)); 8440 mObserver = observer; 8441 mStats = stats; 8442 } 8443 8444 @Override 8445 public String toString() { 8446 return "MeasureParams{" 8447 + Integer.toHexString(System.identityHashCode(this)) 8448 + " " + mStats.packageName + "}"; 8449 } 8450 8451 @Override 8452 void handleStartCopy() throws RemoteException { 8453 synchronized (mInstallLock) { 8454 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8455 } 8456 8457 if (mSuccess) { 8458 final boolean mounted; 8459 if (Environment.isExternalStorageEmulated()) { 8460 mounted = true; 8461 } else { 8462 final String status = Environment.getExternalStorageState(); 8463 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8464 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8465 } 8466 8467 if (mounted) { 8468 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8469 8470 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8471 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8472 8473 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8474 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8475 8476 // Always subtract cache size, since it's a subdirectory 8477 mStats.externalDataSize -= mStats.externalCacheSize; 8478 8479 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8480 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8481 8482 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8483 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8484 } 8485 } 8486 } 8487 8488 @Override 8489 void handleReturnCode() { 8490 if (mObserver != null) { 8491 try { 8492 mObserver.onGetStatsCompleted(mStats, mSuccess); 8493 } catch (RemoteException e) { 8494 Slog.i(TAG, "Observer no longer exists."); 8495 } 8496 } 8497 } 8498 8499 @Override 8500 void handleServiceError() { 8501 Slog.e(TAG, "Could not measure application " + mStats.packageName 8502 + " external storage"); 8503 } 8504 } 8505 8506 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8507 throws RemoteException { 8508 long result = 0; 8509 for (File path : paths) { 8510 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8511 } 8512 return result; 8513 } 8514 8515 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8516 for (File path : paths) { 8517 try { 8518 mcs.clearDirectory(path.getAbsolutePath()); 8519 } catch (RemoteException e) { 8520 } 8521 } 8522 } 8523 8524 class InstallParams extends HandlerParams { 8525 /** 8526 * Location where install is coming from, before it has been 8527 * copied/renamed into place. This could be a single monolithic APK 8528 * file, or a cluster directory. This location may be untrusted. 8529 */ 8530 final File originFile; 8531 8532 /** 8533 * Flag indicating that {@link #originFile} has already been staged, 8534 * meaning downstream users don't need to defensively copy the contents. 8535 */ 8536 boolean originStaged; 8537 8538 final IPackageInstallObserver2 observer; 8539 int flags; 8540 final String installerPackageName; 8541 final VerificationParams verificationParams; 8542 private InstallArgs mArgs; 8543 private int mRet; 8544 final String packageAbiOverride; 8545 boolean multiArch; 8546 8547 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8548 int flags, String installerPackageName, VerificationParams verificationParams, 8549 UserHandle user, String packageAbiOverride) { 8550 super(user); 8551 this.originFile = Preconditions.checkNotNull(originFile); 8552 this.originStaged = originStaged; 8553 this.observer = observer; 8554 this.flags = flags; 8555 this.installerPackageName = installerPackageName; 8556 this.verificationParams = verificationParams; 8557 this.packageAbiOverride = packageAbiOverride; 8558 } 8559 8560 @Override 8561 public String toString() { 8562 return "InstallParams{" 8563 + Integer.toHexString(System.identityHashCode(this)) 8564 + " " + originFile + "}"; 8565 } 8566 8567 public ManifestDigest getManifestDigest() { 8568 if (verificationParams == null) { 8569 return null; 8570 } 8571 return verificationParams.getManifestDigest(); 8572 } 8573 8574 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8575 String packageName = pkgLite.packageName; 8576 int installLocation = pkgLite.installLocation; 8577 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8578 // reader 8579 synchronized (mPackages) { 8580 PackageParser.Package pkg = mPackages.get(packageName); 8581 if (pkg != null) { 8582 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8583 // Check for downgrading. 8584 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8585 if (pkgLite.versionCode < pkg.mVersionCode) { 8586 Slog.w(TAG, "Can't install update of " + packageName 8587 + " update version " + pkgLite.versionCode 8588 + " is older than installed version " 8589 + pkg.mVersionCode); 8590 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8591 } 8592 } 8593 // Check for updated system application. 8594 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8595 if (onSd) { 8596 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8597 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8598 } 8599 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8600 } else { 8601 if (onSd) { 8602 // Install flag overrides everything. 8603 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8604 } 8605 // If current upgrade specifies particular preference 8606 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8607 // Application explicitly specified internal. 8608 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8609 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8610 // App explictly prefers external. Let policy decide 8611 } else { 8612 // Prefer previous location 8613 if (isExternal(pkg)) { 8614 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8615 } 8616 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8617 } 8618 } 8619 } else { 8620 // Invalid install. Return error code 8621 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8622 } 8623 } 8624 } 8625 // All the special cases have been taken care of. 8626 // Return result based on recommended install location. 8627 if (onSd) { 8628 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8629 } 8630 return pkgLite.recommendedInstallLocation; 8631 } 8632 8633 private long getMemoryLowThreshold() { 8634 final DeviceStorageMonitorInternal 8635 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8636 if (dsm == null) { 8637 return 0L; 8638 } 8639 return dsm.getMemoryLowThreshold(); 8640 } 8641 8642 /* 8643 * Invoke remote method to get package information and install 8644 * location values. Override install location based on default 8645 * policy if needed and then create install arguments based 8646 * on the install location. 8647 */ 8648 public void handleStartCopy() throws RemoteException { 8649 int ret = PackageManager.INSTALL_SUCCEEDED; 8650 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8651 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8652 PackageInfoLite pkgLite = null; 8653 8654 if (onInt && onSd) { 8655 // Check if both bits are set. 8656 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8657 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8658 } else { 8659 final long lowThreshold = getMemoryLowThreshold(); 8660 if (lowThreshold == 0L) { 8661 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8662 } 8663 8664 // Remote call to find out default install location 8665 final String originPath = originFile.getAbsolutePath(); 8666 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8667 packageAbiOverride); 8668 // Keep track of whether this package is a multiArch package until 8669 // we perform a full scan of it. We need to do this because we might 8670 // end up extracting the package shared libraries before we perform 8671 // a full scan. 8672 multiArch = pkgLite.multiArch; 8673 8674 /* 8675 * If we have too little free space, try to free cache 8676 * before giving up. 8677 */ 8678 if (pkgLite.recommendedInstallLocation 8679 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8680 final long size = mContainerService.calculateInstalledSize( 8681 originPath, isForwardLocked(), packageAbiOverride); 8682 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8683 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8684 lowThreshold, packageAbiOverride); 8685 } 8686 /* 8687 * The cache free must have deleted the file we 8688 * downloaded to install. 8689 * 8690 * TODO: fix the "freeCache" call to not delete 8691 * the file we care about. 8692 */ 8693 if (pkgLite.recommendedInstallLocation 8694 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8695 pkgLite.recommendedInstallLocation 8696 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8697 } 8698 } 8699 } 8700 8701 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8702 int loc = pkgLite.recommendedInstallLocation; 8703 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8704 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8705 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8706 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8707 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8708 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8709 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8710 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8711 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8712 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8713 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8714 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8715 } else { 8716 // Override with defaults if needed. 8717 loc = installLocationPolicy(pkgLite, flags); 8718 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8719 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8720 } else if (!onSd && !onInt) { 8721 // Override install location with flags 8722 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8723 // Set the flag to install on external media. 8724 flags |= PackageManager.INSTALL_EXTERNAL; 8725 flags &= ~PackageManager.INSTALL_INTERNAL; 8726 } else { 8727 // Make sure the flag for installing on external 8728 // media is unset 8729 flags |= PackageManager.INSTALL_INTERNAL; 8730 flags &= ~PackageManager.INSTALL_EXTERNAL; 8731 } 8732 } 8733 } 8734 } 8735 8736 final InstallArgs args = createInstallArgs(this); 8737 mArgs = args; 8738 8739 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8740 /* 8741 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8742 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8743 */ 8744 int userIdentifier = getUser().getIdentifier(); 8745 if (userIdentifier == UserHandle.USER_ALL 8746 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8747 userIdentifier = UserHandle.USER_OWNER; 8748 } 8749 8750 /* 8751 * Determine if we have any installed package verifiers. If we 8752 * do, then we'll defer to them to verify the packages. 8753 */ 8754 final int requiredUid = mRequiredVerifierPackage == null ? -1 8755 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8756 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8757 // TODO: send verifier the install session instead of uri 8758 final Intent verification = new Intent( 8759 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8760 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8761 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8762 8763 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8764 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8765 0 /* TODO: Which userId? */); 8766 8767 if (DEBUG_VERIFY) { 8768 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8769 + verification.toString() + " with " + pkgLite.verifiers.length 8770 + " optional verifiers"); 8771 } 8772 8773 final int verificationId = mPendingVerificationToken++; 8774 8775 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8776 8777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8778 installerPackageName); 8779 8780 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8781 8782 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8783 pkgLite.packageName); 8784 8785 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8786 pkgLite.versionCode); 8787 8788 if (verificationParams != null) { 8789 if (verificationParams.getVerificationURI() != null) { 8790 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8791 verificationParams.getVerificationURI()); 8792 } 8793 if (verificationParams.getOriginatingURI() != null) { 8794 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8795 verificationParams.getOriginatingURI()); 8796 } 8797 if (verificationParams.getReferrer() != null) { 8798 verification.putExtra(Intent.EXTRA_REFERRER, 8799 verificationParams.getReferrer()); 8800 } 8801 if (verificationParams.getOriginatingUid() >= 0) { 8802 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8803 verificationParams.getOriginatingUid()); 8804 } 8805 if (verificationParams.getInstallerUid() >= 0) { 8806 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8807 verificationParams.getInstallerUid()); 8808 } 8809 } 8810 8811 final PackageVerificationState verificationState = new PackageVerificationState( 8812 requiredUid, args); 8813 8814 mPendingVerification.append(verificationId, verificationState); 8815 8816 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8817 receivers, verificationState); 8818 8819 /* 8820 * If any sufficient verifiers were listed in the package 8821 * manifest, attempt to ask them. 8822 */ 8823 if (sufficientVerifiers != null) { 8824 final int N = sufficientVerifiers.size(); 8825 if (N == 0) { 8826 Slog.i(TAG, "Additional verifiers required, but none installed."); 8827 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8828 } else { 8829 for (int i = 0; i < N; i++) { 8830 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8831 8832 final Intent sufficientIntent = new Intent(verification); 8833 sufficientIntent.setComponent(verifierComponent); 8834 8835 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8836 } 8837 } 8838 } 8839 8840 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8841 mRequiredVerifierPackage, receivers); 8842 if (ret == PackageManager.INSTALL_SUCCEEDED 8843 && mRequiredVerifierPackage != null) { 8844 /* 8845 * Send the intent to the required verification agent, 8846 * but only start the verification timeout after the 8847 * target BroadcastReceivers have run. 8848 */ 8849 verification.setComponent(requiredVerifierComponent); 8850 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8852 new BroadcastReceiver() { 8853 @Override 8854 public void onReceive(Context context, Intent intent) { 8855 final Message msg = mHandler 8856 .obtainMessage(CHECK_PENDING_VERIFICATION); 8857 msg.arg1 = verificationId; 8858 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8859 } 8860 }, null, 0, null, null); 8861 8862 /* 8863 * We don't want the copy to proceed until verification 8864 * succeeds, so null out this field. 8865 */ 8866 mArgs = null; 8867 } 8868 } else { 8869 /* 8870 * No package verification is enabled, so immediately start 8871 * the remote call to initiate copy using temporary file. 8872 */ 8873 ret = args.copyApk(mContainerService, true); 8874 } 8875 } 8876 8877 mRet = ret; 8878 } 8879 8880 @Override 8881 void handleReturnCode() { 8882 // If mArgs is null, then MCS couldn't be reached. When it 8883 // reconnects, it will try again to install. At that point, this 8884 // will succeed. 8885 if (mArgs != null) { 8886 processPendingInstall(mArgs, mRet); 8887 } 8888 } 8889 8890 @Override 8891 void handleServiceError() { 8892 mArgs = createInstallArgs(this); 8893 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8894 } 8895 8896 public boolean isForwardLocked() { 8897 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8898 } 8899 } 8900 8901 /* 8902 * Utility class used in movePackage api. 8903 * srcArgs and targetArgs are not set for invalid flags and make 8904 * sure to do null checks when invoking methods on them. 8905 * We probably want to return ErrorPrams for both failed installs 8906 * and moves. 8907 */ 8908 class MoveParams extends HandlerParams { 8909 final IPackageMoveObserver observer; 8910 final int flags; 8911 final String packageName; 8912 final InstallArgs srcArgs; 8913 final InstallArgs targetArgs; 8914 int uid; 8915 int mRet; 8916 8917 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8918 String packageName, String[] instructionSets, int uid, UserHandle user, 8919 boolean isMultiArch) { 8920 super(user); 8921 this.srcArgs = srcArgs; 8922 this.observer = observer; 8923 this.flags = flags; 8924 this.packageName = packageName; 8925 this.uid = uid; 8926 if (srcArgs != null) { 8927 final String codePath = srcArgs.getCodePath(); 8928 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8929 instructionSets, isMultiArch); 8930 } else { 8931 targetArgs = null; 8932 } 8933 } 8934 8935 @Override 8936 public String toString() { 8937 return "MoveParams{" 8938 + Integer.toHexString(System.identityHashCode(this)) 8939 + " " + packageName + "}"; 8940 } 8941 8942 public void handleStartCopy() throws RemoteException { 8943 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8944 // Check for storage space on target medium 8945 if (!targetArgs.checkFreeStorage(mContainerService)) { 8946 Log.w(TAG, "Insufficient storage to install"); 8947 return; 8948 } 8949 8950 mRet = srcArgs.doPreCopy(); 8951 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8952 return; 8953 } 8954 8955 mRet = targetArgs.copyApk(mContainerService, false); 8956 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8957 srcArgs.doPostCopy(uid); 8958 return; 8959 } 8960 8961 mRet = srcArgs.doPostCopy(uid); 8962 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8963 return; 8964 } 8965 8966 mRet = targetArgs.doPreInstall(mRet); 8967 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8968 return; 8969 } 8970 8971 if (DEBUG_SD_INSTALL) { 8972 StringBuilder builder = new StringBuilder(); 8973 if (srcArgs != null) { 8974 builder.append("src: "); 8975 builder.append(srcArgs.getCodePath()); 8976 } 8977 if (targetArgs != null) { 8978 builder.append(" target : "); 8979 builder.append(targetArgs.getCodePath()); 8980 } 8981 Log.i(TAG, builder.toString()); 8982 } 8983 } 8984 8985 @Override 8986 void handleReturnCode() { 8987 targetArgs.doPostInstall(mRet, uid); 8988 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8989 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8990 currentStatus = PackageManager.MOVE_SUCCEEDED; 8991 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8992 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8993 } 8994 processPendingMove(this, currentStatus); 8995 } 8996 8997 @Override 8998 void handleServiceError() { 8999 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9000 } 9001 } 9002 9003 /** 9004 * Used during creation of InstallArgs 9005 * 9006 * @param flags package installation flags 9007 * @return true if should be installed on external storage 9008 */ 9009 private static boolean installOnSd(int flags) { 9010 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9011 return false; 9012 } 9013 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9014 return true; 9015 } 9016 return false; 9017 } 9018 9019 /** 9020 * Used during creation of InstallArgs 9021 * 9022 * @param flags package installation flags 9023 * @return true if should be installed as forward locked 9024 */ 9025 private static boolean installForwardLocked(int flags) { 9026 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9027 } 9028 9029 private InstallArgs createInstallArgs(InstallParams params) { 9030 // TODO: extend to support incoming zero-copy locations 9031 9032 if (installOnSd(params.flags) || params.isForwardLocked()) { 9033 return new AsecInstallArgs(params); 9034 } else { 9035 return new FileInstallArgs(params); 9036 } 9037 } 9038 9039 /** 9040 * Create args that describe an existing installed package. Typically used 9041 * when cleaning up old installs, or used as a move source. 9042 */ 9043 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9044 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9045 boolean isMultiArch) { 9046 final boolean isInAsec; 9047 if (installOnSd(flags)) { 9048 /* Apps on SD card are always in ASEC containers. */ 9049 isInAsec = true; 9050 } else if (installForwardLocked(flags) 9051 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9052 /* 9053 * Forward-locked apps are only in ASEC containers if they're the 9054 * new style 9055 */ 9056 isInAsec = true; 9057 } else { 9058 isInAsec = false; 9059 } 9060 9061 if (isInAsec) { 9062 return new AsecInstallArgs(codePath, instructionSets, 9063 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9064 } else { 9065 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9066 instructionSets, isMultiArch); 9067 } 9068 } 9069 9070 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9071 String[] instructionSets, boolean isMultiArch) { 9072 final File codeFile = new File(codePath); 9073 if (installOnSd(flags) || installForwardLocked(flags)) { 9074 String cid = getNextCodePath(codePath, pkgName, "/" 9075 + AsecInstallArgs.RES_FILE_NAME); 9076 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9077 installForwardLocked(flags), isMultiArch); 9078 } else { 9079 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9080 } 9081 } 9082 9083 static abstract class InstallArgs { 9084 /** @see InstallParams#originFile */ 9085 final File originFile; 9086 /** @see InstallParams#originStaged */ 9087 final boolean originStaged; 9088 9089 // TODO: define inherit location 9090 9091 final IPackageInstallObserver2 observer; 9092 // Always refers to PackageManager flags only 9093 final int flags; 9094 final String installerPackageName; 9095 final ManifestDigest manifestDigest; 9096 final UserHandle user; 9097 final String abiOverride; 9098 final boolean multiArch; 9099 9100 // The list of instruction sets supported by this app. This is currently 9101 // only used during the rmdex() phase to clean up resources. We can get rid of this 9102 // if we move dex files under the common app path. 9103 /* nullable */ String[] instructionSets; 9104 9105 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9106 int flags, String installerPackageName, ManifestDigest manifestDigest, 9107 UserHandle user, String[] instructionSets, 9108 String abiOverride, boolean multiArch) { 9109 this.originFile = originFile; 9110 this.originStaged = originStaged; 9111 this.flags = flags; 9112 this.observer = observer; 9113 this.installerPackageName = installerPackageName; 9114 this.manifestDigest = manifestDigest; 9115 this.user = user; 9116 this.instructionSets = instructionSets; 9117 this.abiOverride = abiOverride; 9118 this.multiArch = multiArch; 9119 } 9120 9121 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9122 abstract int doPreInstall(int status); 9123 9124 /** 9125 * Rename package into final resting place. All paths on the given 9126 * scanned package should be updated to reflect the rename. 9127 */ 9128 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9129 abstract int doPostInstall(int status, int uid); 9130 9131 /** @see PackageSettingBase#codePathString */ 9132 abstract String getCodePath(); 9133 /** @see PackageSettingBase#resourcePathString */ 9134 abstract String getResourcePath(); 9135 abstract String getLegacyNativeLibraryPath(); 9136 9137 // Need installer lock especially for dex file removal. 9138 abstract void cleanUpResourcesLI(); 9139 abstract boolean doPostDeleteLI(boolean delete); 9140 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9141 9142 /** 9143 * Called before the source arguments are copied. This is used mostly 9144 * for MoveParams when it needs to read the source file to put it in the 9145 * destination. 9146 */ 9147 int doPreCopy() { 9148 return PackageManager.INSTALL_SUCCEEDED; 9149 } 9150 9151 /** 9152 * Called after the source arguments are copied. This is used mostly for 9153 * MoveParams when it needs to read the source file to put it in the 9154 * destination. 9155 * 9156 * @return 9157 */ 9158 int doPostCopy(int uid) { 9159 return PackageManager.INSTALL_SUCCEEDED; 9160 } 9161 9162 protected boolean isFwdLocked() { 9163 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9164 } 9165 9166 UserHandle getUser() { 9167 return user; 9168 } 9169 } 9170 9171 /** 9172 * Logic to handle installation of non-ASEC applications, including copying 9173 * and renaming logic. 9174 */ 9175 class FileInstallArgs extends InstallArgs { 9176 private File codeFile; 9177 private File resourceFile; 9178 private File legacyNativeLibraryPath; 9179 9180 // Example topology: 9181 // /data/app/com.example/base.apk 9182 // /data/app/com.example/split_foo.apk 9183 // /data/app/com.example/lib/arm/libfoo.so 9184 // /data/app/com.example/lib/arm64/libfoo.so 9185 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9186 9187 /** New install */ 9188 FileInstallArgs(InstallParams params) { 9189 super(params.originFile, params.originStaged, params.observer, params.flags, 9190 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9191 null /* instruction sets */, params.packageAbiOverride, 9192 params.multiArch); 9193 if (isFwdLocked()) { 9194 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9195 } 9196 } 9197 9198 /** Existing install */ 9199 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9200 String[] instructionSets, boolean isMultiArch) { 9201 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9202 this.codeFile = (codePath != null) ? new File(codePath) : null; 9203 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9204 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9205 new File(legacyNativeLibraryPath) : null; 9206 } 9207 9208 /** New install from existing */ 9209 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9210 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9211 isMultiArch); 9212 } 9213 9214 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9215 final long lowThreshold; 9216 9217 final DeviceStorageMonitorInternal 9218 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9219 if (dsm == null) { 9220 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9221 lowThreshold = 0L; 9222 } else { 9223 if (dsm.isMemoryLow()) { 9224 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9225 return false; 9226 } 9227 9228 lowThreshold = dsm.getMemoryLowThreshold(); 9229 } 9230 9231 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9232 lowThreshold); 9233 } 9234 9235 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9236 int ret = PackageManager.INSTALL_SUCCEEDED; 9237 9238 if (originStaged) { 9239 Slog.d(TAG, originFile + " already staged; skipping copy"); 9240 codeFile = originFile; 9241 resourceFile = originFile; 9242 } else { 9243 try { 9244 final File tempDir = mInstallerService.allocateSessionDir(); 9245 codeFile = tempDir; 9246 resourceFile = tempDir; 9247 } catch (IOException e) { 9248 Slog.w(TAG, "Failed to create copy file: " + e); 9249 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9250 } 9251 9252 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9253 @Override 9254 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9255 if (!FileUtils.isValidExtFilename(name)) { 9256 throw new IllegalArgumentException("Invalid filename: " + name); 9257 } 9258 try { 9259 final File file = new File(codeFile, name); 9260 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9261 O_RDWR | O_CREAT, 0644); 9262 Os.chmod(file.getAbsolutePath(), 0644); 9263 return new ParcelFileDescriptor(fd); 9264 } catch (ErrnoException e) { 9265 throw new RemoteException("Failed to open: " + e.getMessage()); 9266 } 9267 } 9268 }; 9269 9270 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9271 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9272 Slog.e(TAG, "Failed to copy package"); 9273 return ret; 9274 } 9275 } 9276 9277 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9278 NativeLibraryHelper.Handle handle = null; 9279 try { 9280 handle = NativeLibraryHelper.Handle.create(codeFile); 9281 if (multiArch) { 9282 // Warn if we've set an abiOverride for multi-lib packages.. 9283 // By definition, we need to copy both 32 and 64 bit libraries for 9284 // such packages. 9285 if (abiOverride != null) { 9286 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9287 } 9288 9289 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9290 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9291 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9292 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9293 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9294 } 9295 9296 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9297 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9298 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9299 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9300 } 9301 } else { 9302 String[] abiList = (abiOverride != null) ? 9303 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9304 9305 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9306 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9307 abiList = Build.SUPPORTED_32_BIT_ABIS; 9308 } 9309 9310 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9311 true /* use isa specific subdirs */); 9312 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9313 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9314 return copyRet; 9315 } 9316 } 9317 } catch (IOException e) { 9318 Slog.e(TAG, "Copying native libraries failed", e); 9319 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9320 } catch (PackageManagerException pme) { 9321 Slog.e(TAG, "Copying native libraries failed", pme); 9322 ret = pme.error; 9323 } finally { 9324 IoUtils.closeQuietly(handle); 9325 } 9326 9327 return ret; 9328 } 9329 9330 int doPreInstall(int status) { 9331 if (status != PackageManager.INSTALL_SUCCEEDED) { 9332 cleanUp(); 9333 } 9334 return status; 9335 } 9336 9337 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9338 if (status != PackageManager.INSTALL_SUCCEEDED) { 9339 cleanUp(); 9340 return false; 9341 } else { 9342 final File beforeCodeFile = codeFile; 9343 final File afterCodeFile = getNextCodePath(pkg.packageName); 9344 9345 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9346 try { 9347 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9348 } catch (ErrnoException e) { 9349 Slog.d(TAG, "Failed to rename", e); 9350 return false; 9351 } 9352 9353 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9354 Slog.d(TAG, "Failed to restorecon"); 9355 return false; 9356 } 9357 9358 // Reflect the rename internally 9359 codeFile = afterCodeFile; 9360 resourceFile = afterCodeFile; 9361 9362 // Reflect the rename in scanned details 9363 pkg.codePath = afterCodeFile.getAbsolutePath(); 9364 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9365 pkg.baseCodePath); 9366 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9367 pkg.splitCodePaths); 9368 9369 // Reflect the rename in app info 9370 pkg.applicationInfo.setCodePath(pkg.codePath); 9371 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9372 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9373 pkg.applicationInfo.setResourcePath(pkg.codePath); 9374 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9375 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9376 9377 return true; 9378 } 9379 } 9380 9381 int doPostInstall(int status, int uid) { 9382 if (status != PackageManager.INSTALL_SUCCEEDED) { 9383 cleanUp(); 9384 } 9385 return status; 9386 } 9387 9388 @Override 9389 String getCodePath() { 9390 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9391 } 9392 9393 @Override 9394 String getResourcePath() { 9395 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9396 } 9397 9398 @Override 9399 String getLegacyNativeLibraryPath() { 9400 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9401 } 9402 9403 private boolean cleanUp() { 9404 if (codeFile == null || !codeFile.exists()) { 9405 return false; 9406 } 9407 9408 if (codeFile.isDirectory()) { 9409 FileUtils.deleteContents(codeFile); 9410 } 9411 codeFile.delete(); 9412 9413 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9414 resourceFile.delete(); 9415 } 9416 9417 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9418 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9419 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9420 } 9421 legacyNativeLibraryPath.delete(); 9422 } 9423 9424 return true; 9425 } 9426 9427 void cleanUpResourcesLI() { 9428 // Try enumerating all code paths before deleting 9429 List<String> allCodePaths = Collections.EMPTY_LIST; 9430 if (codeFile != null && codeFile.exists()) { 9431 try { 9432 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9433 allCodePaths = pkg.getAllCodePaths(); 9434 } catch (PackageParserException e) { 9435 // Ignored; we tried our best 9436 } 9437 } 9438 9439 cleanUp(); 9440 9441 if (!allCodePaths.isEmpty()) { 9442 if (instructionSets == null) { 9443 throw new IllegalStateException("instructionSet == null"); 9444 } 9445 9446 for (String codePath : allCodePaths) { 9447 for (String instructionSet : instructionSets) { 9448 int retCode = mInstaller.rmdex(codePath, instructionSet); 9449 if (retCode < 0) { 9450 Slog.w(TAG, "Couldn't remove dex file for package: " 9451 + " at location " + codePath + ", retcode=" + retCode); 9452 // we don't consider this to be a failure of the core package deletion 9453 } 9454 } 9455 } 9456 } 9457 } 9458 9459 boolean doPostDeleteLI(boolean delete) { 9460 // XXX err, shouldn't we respect the delete flag? 9461 cleanUpResourcesLI(); 9462 return true; 9463 } 9464 } 9465 9466 private boolean isAsecExternal(String cid) { 9467 final String asecPath = PackageHelper.getSdFilesystem(cid); 9468 return !asecPath.startsWith(mAsecInternalPath); 9469 } 9470 9471 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9472 PackageManagerException { 9473 if (copyRet < 0) { 9474 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9475 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9476 throw new PackageManagerException(copyRet, message); 9477 } 9478 } 9479 } 9480 9481 /** 9482 * Extract the MountService "container ID" from the full code path of an 9483 * .apk. 9484 */ 9485 static String cidFromCodePath(String fullCodePath) { 9486 int eidx = fullCodePath.lastIndexOf("/"); 9487 String subStr1 = fullCodePath.substring(0, eidx); 9488 int sidx = subStr1.lastIndexOf("/"); 9489 return subStr1.substring(sidx+1, eidx); 9490 } 9491 9492 /** 9493 * Logic to handle installation of ASEC applications, including copying and 9494 * renaming logic. 9495 */ 9496 class AsecInstallArgs extends InstallArgs { 9497 // TODO: teach about handling cluster directories 9498 9499 static final String RES_FILE_NAME = "pkg.apk"; 9500 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9501 9502 String cid; 9503 String packagePath; 9504 String resourcePath; 9505 String legacyNativeLibraryDir; 9506 9507 /** New install */ 9508 AsecInstallArgs(InstallParams params) { 9509 super(params.originFile, params.originStaged, params.observer, params.flags, 9510 params.installerPackageName, params.getManifestDigest(), 9511 params.getUser(), null /* instruction sets */, 9512 params.packageAbiOverride, params.multiArch); 9513 } 9514 9515 /** Existing install */ 9516 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9517 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9518 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9519 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9520 instructionSets, null, isMultiArch); 9521 // Extract cid from fullCodePath 9522 int eidx = fullCodePath.lastIndexOf("/"); 9523 String subStr1 = fullCodePath.substring(0, eidx); 9524 int sidx = subStr1.lastIndexOf("/"); 9525 cid = subStr1.substring(sidx+1, eidx); 9526 setCachePath(subStr1); 9527 } 9528 9529 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9530 boolean isMultiArch) { 9531 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9532 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9533 instructionSets, null, isMultiArch); 9534 this.cid = cid; 9535 setCachePath(PackageHelper.getSdDir(cid)); 9536 } 9537 9538 /** New install from existing */ 9539 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9540 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9541 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9542 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9543 instructionSets, null, isMultiArch); 9544 this.cid = cid; 9545 } 9546 9547 void createCopyFile() { 9548 cid = getTempContainerId(); 9549 } 9550 9551 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9552 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9553 abiOverride); 9554 } 9555 9556 private final boolean isExternal() { 9557 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9558 } 9559 9560 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9561 if (temp) { 9562 createCopyFile(); 9563 } else { 9564 /* 9565 * Pre-emptively destroy the container since it's destroyed if 9566 * copying fails due to it existing anyway. 9567 */ 9568 PackageHelper.destroySdDir(cid); 9569 } 9570 9571 final String newCachePath = imcs.copyPackageToContainer( 9572 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9573 isFwdLocked(), abiOverride); 9574 9575 if (newCachePath != null) { 9576 setCachePath(newCachePath); 9577 return PackageManager.INSTALL_SUCCEEDED; 9578 } else { 9579 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9580 } 9581 } 9582 9583 @Override 9584 String getCodePath() { 9585 return packagePath; 9586 } 9587 9588 @Override 9589 String getResourcePath() { 9590 return resourcePath; 9591 } 9592 9593 @Override 9594 String getLegacyNativeLibraryPath() { 9595 return legacyNativeLibraryDir; 9596 } 9597 9598 int doPreInstall(int status) { 9599 if (status != PackageManager.INSTALL_SUCCEEDED) { 9600 // Destroy container 9601 PackageHelper.destroySdDir(cid); 9602 } else { 9603 boolean mounted = PackageHelper.isContainerMounted(cid); 9604 if (!mounted) { 9605 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9606 Process.SYSTEM_UID); 9607 if (newCachePath != null) { 9608 setCachePath(newCachePath); 9609 } else { 9610 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9611 } 9612 } 9613 } 9614 return status; 9615 } 9616 9617 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9618 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9619 String newCachePath = null; 9620 if (PackageHelper.isContainerMounted(cid)) { 9621 // Unmount the container 9622 if (!PackageHelper.unMountSdDir(cid)) { 9623 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9624 return false; 9625 } 9626 } 9627 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9628 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9629 " which might be stale. Will try to clean up."); 9630 // Clean up the stale container and proceed to recreate. 9631 if (!PackageHelper.destroySdDir(newCacheId)) { 9632 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9633 return false; 9634 } 9635 // Successfully cleaned up stale container. Try to rename again. 9636 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9637 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9638 + " inspite of cleaning it up."); 9639 return false; 9640 } 9641 } 9642 if (!PackageHelper.isContainerMounted(newCacheId)) { 9643 Slog.w(TAG, "Mounting container " + newCacheId); 9644 newCachePath = PackageHelper.mountSdDir(newCacheId, 9645 getEncryptKey(), Process.SYSTEM_UID); 9646 } else { 9647 newCachePath = PackageHelper.getSdDir(newCacheId); 9648 } 9649 if (newCachePath == null) { 9650 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9651 return false; 9652 } 9653 Log.i(TAG, "Succesfully renamed " + cid + 9654 " to " + newCacheId + 9655 " at new path: " + newCachePath); 9656 cid = newCacheId; 9657 setCachePath(newCachePath); 9658 9659 // TODO: extend to support split APKs 9660 pkg.codePath = getCodePath(); 9661 pkg.baseCodePath = getCodePath(); 9662 pkg.splitCodePaths = null; 9663 9664 pkg.applicationInfo.setCodePath(getCodePath()); 9665 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9666 pkg.applicationInfo.setSplitCodePaths(null); 9667 pkg.applicationInfo.setResourcePath(getResourcePath()); 9668 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9669 pkg.applicationInfo.setSplitResourcePaths(null); 9670 9671 return true; 9672 } 9673 9674 private void setCachePath(String newCachePath) { 9675 File cachePath = new File(newCachePath); 9676 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9677 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9678 9679 if (isFwdLocked()) { 9680 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9681 } else { 9682 resourcePath = packagePath; 9683 } 9684 } 9685 9686 int doPostInstall(int status, int uid) { 9687 if (status != PackageManager.INSTALL_SUCCEEDED) { 9688 cleanUp(); 9689 } else { 9690 final int groupOwner; 9691 final String protectedFile; 9692 if (isFwdLocked()) { 9693 groupOwner = UserHandle.getSharedAppGid(uid); 9694 protectedFile = RES_FILE_NAME; 9695 } else { 9696 groupOwner = -1; 9697 protectedFile = null; 9698 } 9699 9700 if (uid < Process.FIRST_APPLICATION_UID 9701 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9702 Slog.e(TAG, "Failed to finalize " + cid); 9703 PackageHelper.destroySdDir(cid); 9704 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9705 } 9706 9707 boolean mounted = PackageHelper.isContainerMounted(cid); 9708 if (!mounted) { 9709 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9710 } 9711 } 9712 return status; 9713 } 9714 9715 private void cleanUp() { 9716 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9717 9718 // Destroy secure container 9719 PackageHelper.destroySdDir(cid); 9720 } 9721 9722 void cleanUpResourcesLI() { 9723 String sourceFile = getCodePath(); 9724 // Remove dex file 9725 if (instructionSets == null) { 9726 throw new IllegalStateException("instructionSet == null"); 9727 } 9728 for (String instructionSet : instructionSets) { 9729 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9730 if (retCode < 0) { 9731 Slog.w(TAG, "Couldn't remove dex file for package: " 9732 + " at location " 9733 + sourceFile.toString() + ", retcode=" + retCode); 9734 // we don't consider this to be a failure of the core package deletion 9735 } 9736 } 9737 cleanUp(); 9738 } 9739 9740 boolean matchContainer(String app) { 9741 if (cid.startsWith(app)) { 9742 return true; 9743 } 9744 return false; 9745 } 9746 9747 String getPackageName() { 9748 return getAsecPackageName(cid); 9749 } 9750 9751 boolean doPostDeleteLI(boolean delete) { 9752 boolean ret = false; 9753 boolean mounted = PackageHelper.isContainerMounted(cid); 9754 if (mounted) { 9755 // Unmount first 9756 ret = PackageHelper.unMountSdDir(cid); 9757 } 9758 if (ret && delete) { 9759 cleanUpResourcesLI(); 9760 } 9761 return ret; 9762 } 9763 9764 @Override 9765 int doPreCopy() { 9766 if (isFwdLocked()) { 9767 if (!PackageHelper.fixSdPermissions(cid, 9768 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9769 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9770 } 9771 } 9772 9773 return PackageManager.INSTALL_SUCCEEDED; 9774 } 9775 9776 @Override 9777 int doPostCopy(int uid) { 9778 if (isFwdLocked()) { 9779 if (uid < Process.FIRST_APPLICATION_UID 9780 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9781 RES_FILE_NAME)) { 9782 Slog.e(TAG, "Failed to finalize " + cid); 9783 PackageHelper.destroySdDir(cid); 9784 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9785 } 9786 } 9787 9788 return PackageManager.INSTALL_SUCCEEDED; 9789 } 9790 } 9791 9792 static String getAsecPackageName(String packageCid) { 9793 int idx = packageCid.lastIndexOf("-"); 9794 if (idx == -1) { 9795 return packageCid; 9796 } 9797 return packageCid.substring(0, idx); 9798 } 9799 9800 // Utility method used to create code paths based on package name and available index. 9801 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9802 String idxStr = ""; 9803 int idx = 1; 9804 // Fall back to default value of idx=1 if prefix is not 9805 // part of oldCodePath 9806 if (oldCodePath != null) { 9807 String subStr = oldCodePath; 9808 // Drop the suffix right away 9809 if (suffix != null && subStr.endsWith(suffix)) { 9810 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9811 } 9812 // If oldCodePath already contains prefix find out the 9813 // ending index to either increment or decrement. 9814 int sidx = subStr.lastIndexOf(prefix); 9815 if (sidx != -1) { 9816 subStr = subStr.substring(sidx + prefix.length()); 9817 if (subStr != null) { 9818 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9819 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9820 } 9821 try { 9822 idx = Integer.parseInt(subStr); 9823 if (idx <= 1) { 9824 idx++; 9825 } else { 9826 idx--; 9827 } 9828 } catch(NumberFormatException e) { 9829 } 9830 } 9831 } 9832 } 9833 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9834 return prefix + idxStr; 9835 } 9836 9837 private File getNextCodePath(String packageName) { 9838 int suffix = 1; 9839 File result; 9840 do { 9841 result = new File(mAppInstallDir, packageName + "-" + suffix); 9842 suffix++; 9843 } while (result.exists()); 9844 return result; 9845 } 9846 9847 // Utility method used to ignore ADD/REMOVE events 9848 // by directory observer. 9849 private static boolean ignoreCodePath(String fullPathStr) { 9850 String apkName = deriveCodePathName(fullPathStr); 9851 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9852 if (idx != -1 && ((idx+1) < apkName.length())) { 9853 // Make sure the package ends with a numeral 9854 String version = apkName.substring(idx+1); 9855 try { 9856 Integer.parseInt(version); 9857 return true; 9858 } catch (NumberFormatException e) {} 9859 } 9860 return false; 9861 } 9862 9863 // Utility method that returns the relative package path with respect 9864 // to the installation directory. Like say for /data/data/com.test-1.apk 9865 // string com.test-1 is returned. 9866 static String deriveCodePathName(String codePath) { 9867 if (codePath == null) { 9868 return null; 9869 } 9870 final File codeFile = new File(codePath); 9871 final String name = codeFile.getName(); 9872 if (codeFile.isDirectory()) { 9873 return name; 9874 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9875 final int lastDot = name.lastIndexOf('.'); 9876 return name.substring(0, lastDot); 9877 } else { 9878 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9879 return null; 9880 } 9881 } 9882 9883 class PackageInstalledInfo { 9884 String name; 9885 int uid; 9886 // The set of users that originally had this package installed. 9887 int[] origUsers; 9888 // The set of users that now have this package installed. 9889 int[] newUsers; 9890 PackageParser.Package pkg; 9891 int returnCode; 9892 String returnMsg; 9893 PackageRemovedInfo removedInfo; 9894 9895 public void setError(int code, String msg) { 9896 returnCode = code; 9897 returnMsg = msg; 9898 Slog.w(TAG, msg); 9899 } 9900 9901 public void setError(String msg, PackageParserException e) { 9902 returnCode = e.error; 9903 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9904 Slog.w(TAG, msg, e); 9905 } 9906 9907 public void setError(String msg, PackageManagerException e) { 9908 returnCode = e.error; 9909 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9910 Slog.w(TAG, msg, e); 9911 } 9912 9913 // In some error cases we want to convey more info back to the observer 9914 String origPackage; 9915 String origPermission; 9916 } 9917 9918 /* 9919 * Install a non-existing package. 9920 */ 9921 private void installNewPackageLI(PackageParser.Package pkg, 9922 int parseFlags, int scanMode, UserHandle user, 9923 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9924 // Remember this for later, in case we need to rollback this install 9925 String pkgName = pkg.packageName; 9926 9927 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9928 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9929 synchronized(mPackages) { 9930 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9931 // A package with the same name is already installed, though 9932 // it has been renamed to an older name. The package we 9933 // are trying to install should be installed as an update to 9934 // the existing one, but that has not been requested, so bail. 9935 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9936 + " without first uninstalling package running as " 9937 + mSettings.mRenamedPackages.get(pkgName)); 9938 return; 9939 } 9940 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9941 // Don't allow installation over an existing package with the same name. 9942 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9943 + " without first uninstalling."); 9944 return; 9945 } 9946 } 9947 9948 try { 9949 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9950 System.currentTimeMillis(), user, abiOverride); 9951 9952 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9953 // delete the partially installed application. the data directory will have to be 9954 // restored if it was already existing 9955 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9956 // remove package from internal structures. Note that we want deletePackageX to 9957 // delete the package data and cache directories that it created in 9958 // scanPackageLocked, unless those directories existed before we even tried to 9959 // install. 9960 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9961 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9962 res.removedInfo, true); 9963 } 9964 9965 } catch (PackageManagerException e) { 9966 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9967 } 9968 } 9969 9970 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9971 // Upgrade keysets are being used. Determine if new package has a superset of the 9972 // required keys. 9973 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9974 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9975 for (int i = 0; i < upgradeKeySets.length; i++) { 9976 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9977 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9978 return true; 9979 } 9980 } 9981 return false; 9982 } 9983 9984 private void replacePackageLI(PackageParser.Package pkg, 9985 int parseFlags, int scanMode, UserHandle user, 9986 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9987 PackageParser.Package oldPackage; 9988 String pkgName = pkg.packageName; 9989 int[] allUsers; 9990 boolean[] perUserInstalled; 9991 9992 // First find the old package info and check signatures 9993 synchronized(mPackages) { 9994 oldPackage = mPackages.get(pkgName); 9995 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9996 PackageSetting ps = mSettings.mPackages.get(pkgName); 9997 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9998 // default to original signature matching 9999 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10000 != PackageManager.SIGNATURE_MATCH) { 10001 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10002 "New package has a different signature: " + pkgName); 10003 return; 10004 } 10005 } else { 10006 if(!checkUpgradeKeySetLP(ps, pkg)) { 10007 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10008 "New package not signed by keys specified by upgrade-keysets: " 10009 + pkgName); 10010 return; 10011 } 10012 } 10013 10014 // In case of rollback, remember per-user/profile install state 10015 allUsers = sUserManager.getUserIds(); 10016 perUserInstalled = new boolean[allUsers.length]; 10017 for (int i = 0; i < allUsers.length; i++) { 10018 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10019 } 10020 } 10021 10022 boolean sysPkg = (isSystemApp(oldPackage)); 10023 if (sysPkg) { 10024 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10025 user, allUsers, perUserInstalled, installerPackageName, res, 10026 abiOverride); 10027 } else { 10028 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10029 user, allUsers, perUserInstalled, installerPackageName, res, 10030 abiOverride); 10031 } 10032 } 10033 10034 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10035 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10036 int[] allUsers, boolean[] perUserInstalled, 10037 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10038 String pkgName = deletedPackage.packageName; 10039 boolean deletedPkg = true; 10040 boolean updatedSettings = false; 10041 10042 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10043 + deletedPackage); 10044 long origUpdateTime; 10045 if (pkg.mExtras != null) { 10046 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10047 } else { 10048 origUpdateTime = 0; 10049 } 10050 10051 // First delete the existing package while retaining the data directory 10052 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10053 res.removedInfo, true)) { 10054 // If the existing package wasn't successfully deleted 10055 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10056 deletedPkg = false; 10057 } else { 10058 // Successfully deleted the old package. Now proceed with re-installation 10059 deleteCodeCacheDirsLI(pkgName); 10060 try { 10061 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10062 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 10063 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10064 updatedSettings = true; 10065 } catch (PackageManagerException e) { 10066 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10067 } 10068 } 10069 10070 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10071 // remove package from internal structures. Note that we want deletePackageX to 10072 // delete the package data and cache directories that it created in 10073 // scanPackageLocked, unless those directories existed before we even tried to 10074 // install. 10075 if(updatedSettings) { 10076 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10077 deletePackageLI( 10078 pkgName, null, true, allUsers, perUserInstalled, 10079 PackageManager.DELETE_KEEP_DATA, 10080 res.removedInfo, true); 10081 } 10082 // Since we failed to install the new package we need to restore the old 10083 // package that we deleted. 10084 if (deletedPkg) { 10085 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10086 File restoreFile = new File(deletedPackage.codePath); 10087 // Parse old package 10088 boolean oldOnSd = isExternal(deletedPackage); 10089 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10090 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10091 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10092 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10093 | SCAN_UPDATE_TIME; 10094 try { 10095 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10096 null); 10097 } catch (PackageManagerException e) { 10098 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10099 + e.getMessage()); 10100 return; 10101 } 10102 // Restore of old package succeeded. Update permissions. 10103 // writer 10104 synchronized (mPackages) { 10105 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10106 UPDATE_PERMISSIONS_ALL); 10107 // can downgrade to reader 10108 mSettings.writeLPr(); 10109 } 10110 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10111 } 10112 } 10113 } 10114 10115 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10116 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10117 int[] allUsers, boolean[] perUserInstalled, 10118 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10119 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10120 + ", old=" + deletedPackage); 10121 boolean updatedSettings = false; 10122 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10123 PackageParser.PARSE_IS_SYSTEM; 10124 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10125 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10126 } 10127 String packageName = deletedPackage.packageName; 10128 if (packageName == null) { 10129 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10130 "Attempt to delete null packageName."); 10131 return; 10132 } 10133 PackageParser.Package oldPkg; 10134 PackageSetting oldPkgSetting; 10135 // reader 10136 synchronized (mPackages) { 10137 oldPkg = mPackages.get(packageName); 10138 oldPkgSetting = mSettings.mPackages.get(packageName); 10139 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10140 (oldPkgSetting == null)) { 10141 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10142 "Couldn't find package:" + packageName + " information"); 10143 return; 10144 } 10145 } 10146 10147 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10148 10149 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10150 res.removedInfo.removedPackage = packageName; 10151 // Remove existing system package 10152 removePackageLI(oldPkgSetting, true); 10153 // writer 10154 synchronized (mPackages) { 10155 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10156 // We didn't need to disable the .apk as a current system package, 10157 // which means we are replacing another update that is already 10158 // installed. We need to make sure to delete the older one's .apk. 10159 res.removedInfo.args = createInstallArgsForExisting(0, 10160 deletedPackage.applicationInfo.getCodePath(), 10161 deletedPackage.applicationInfo.getResourcePath(), 10162 deletedPackage.applicationInfo.nativeLibraryRootDir, 10163 getAppDexInstructionSets(deletedPackage.applicationInfo), 10164 isMultiArch(deletedPackage.applicationInfo)); 10165 } else { 10166 res.removedInfo.args = null; 10167 } 10168 } 10169 10170 // Successfully disabled the old package. Now proceed with re-installation 10171 deleteCodeCacheDirsLI(packageName); 10172 10173 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10174 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10175 10176 PackageParser.Package newPackage = null; 10177 try { 10178 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10179 if (newPackage.mExtras != null) { 10180 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10181 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10182 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10183 10184 // is the update attempting to change shared user? that isn't going to work... 10185 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10186 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10187 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10188 + " to " + newPkgSetting.sharedUser); 10189 updatedSettings = true; 10190 } 10191 } 10192 10193 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10194 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10195 updatedSettings = true; 10196 } 10197 10198 } catch (PackageManagerException e) { 10199 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10200 } 10201 10202 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10203 // Re installation failed. Restore old information 10204 // Remove new pkg information 10205 if (newPackage != null) { 10206 removeInstalledPackageLI(newPackage, true); 10207 } 10208 // Add back the old system package 10209 try { 10210 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10211 null); 10212 } catch (PackageManagerException e) { 10213 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10214 } 10215 // Restore the old system information in Settings 10216 synchronized(mPackages) { 10217 if (updatedSettings) { 10218 mSettings.enableSystemPackageLPw(packageName); 10219 mSettings.setInstallerPackageName(packageName, 10220 oldPkgSetting.installerPackageName); 10221 } 10222 mSettings.writeLPr(); 10223 } 10224 } 10225 } 10226 10227 // Utility method used to move dex files during install. 10228 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10229 // TODO: extend to move split APK dex files 10230 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10231 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10232 for (String instructionSet : instructionSets) { 10233 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10234 instructionSet); 10235 if (retCode != 0) { 10236 /* 10237 * Programs may be lazily run through dexopt, so the 10238 * source may not exist. However, something seems to 10239 * have gone wrong, so note that dexopt needs to be 10240 * run again and remove the source file. In addition, 10241 * remove the target to make sure there isn't a stale 10242 * file from a previous version of the package. 10243 */ 10244 newPackage.mDexOptPerformed.clear(); 10245 mInstaller.rmdex(oldCodePath, instructionSet); 10246 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10247 } 10248 } 10249 } 10250 return PackageManager.INSTALL_SUCCEEDED; 10251 } 10252 10253 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10254 int[] allUsers, boolean[] perUserInstalled, 10255 PackageInstalledInfo res) { 10256 String pkgName = newPackage.packageName; 10257 synchronized (mPackages) { 10258 //write settings. the installStatus will be incomplete at this stage. 10259 //note that the new package setting would have already been 10260 //added to mPackages. It hasn't been persisted yet. 10261 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10262 mSettings.writeLPr(); 10263 } 10264 10265 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10266 10267 synchronized (mPackages) { 10268 updatePermissionsLPw(newPackage.packageName, newPackage, 10269 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10270 ? UPDATE_PERMISSIONS_ALL : 0)); 10271 // For system-bundled packages, we assume that installing an upgraded version 10272 // of the package implies that the user actually wants to run that new code, 10273 // so we enable the package. 10274 if (isSystemApp(newPackage)) { 10275 // NB: implicit assumption that system package upgrades apply to all users 10276 if (DEBUG_INSTALL) { 10277 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10278 } 10279 PackageSetting ps = mSettings.mPackages.get(pkgName); 10280 if (ps != null) { 10281 if (res.origUsers != null) { 10282 for (int userHandle : res.origUsers) { 10283 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10284 userHandle, installerPackageName); 10285 } 10286 } 10287 // Also convey the prior install/uninstall state 10288 if (allUsers != null && perUserInstalled != null) { 10289 for (int i = 0; i < allUsers.length; i++) { 10290 if (DEBUG_INSTALL) { 10291 Slog.d(TAG, " user " + allUsers[i] 10292 + " => " + perUserInstalled[i]); 10293 } 10294 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10295 } 10296 // these install state changes will be persisted in the 10297 // upcoming call to mSettings.writeLPr(). 10298 } 10299 } 10300 } 10301 res.name = pkgName; 10302 res.uid = newPackage.applicationInfo.uid; 10303 res.pkg = newPackage; 10304 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10305 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10306 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10307 //to update install status 10308 mSettings.writeLPr(); 10309 } 10310 } 10311 10312 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10313 int pFlags = args.flags; 10314 String installerPackageName = args.installerPackageName; 10315 File tmpPackageFile = new File(args.getCodePath()); 10316 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10317 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10318 boolean replace = false; 10319 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10320 | (newInstall ? SCAN_NEW_INSTALL : 0); 10321 // Result object to be returned 10322 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10323 10324 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10325 // Retrieve PackageSettings and parse package 10326 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10327 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10328 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10329 PackageParser pp = new PackageParser(); 10330 pp.setSeparateProcesses(mSeparateProcesses); 10331 pp.setDisplayMetrics(mMetrics); 10332 10333 final PackageParser.Package pkg; 10334 try { 10335 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10336 } catch (PackageParserException e) { 10337 res.setError("Failed parse during installPackageLI", e); 10338 return; 10339 } 10340 10341 String pkgName = res.name = pkg.packageName; 10342 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10343 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10344 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10345 return; 10346 } 10347 } 10348 10349 try { 10350 pp.collectCertificates(pkg, parseFlags); 10351 pp.collectManifestDigest(pkg); 10352 } catch (PackageParserException e) { 10353 res.setError("Failed collect during installPackageLI", e); 10354 return; 10355 } 10356 10357 /* If the installer passed in a manifest digest, compare it now. */ 10358 if (args.manifestDigest != null) { 10359 if (DEBUG_INSTALL) { 10360 final String parsedManifest = pkg.manifestDigest == null ? "null" 10361 : pkg.manifestDigest.toString(); 10362 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10363 + parsedManifest); 10364 } 10365 10366 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10367 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10368 return; 10369 } 10370 } else if (DEBUG_INSTALL) { 10371 final String parsedManifest = pkg.manifestDigest == null 10372 ? "null" : pkg.manifestDigest.toString(); 10373 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10374 } 10375 10376 // Get rid of all references to package scan path via parser. 10377 pp = null; 10378 String oldCodePath = null; 10379 boolean systemApp = false; 10380 synchronized (mPackages) { 10381 // Check whether the newly-scanned package wants to define an already-defined perm 10382 int N = pkg.permissions.size(); 10383 for (int i = N-1; i >= 0; i--) { 10384 PackageParser.Permission perm = pkg.permissions.get(i); 10385 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10386 if (bp != null) { 10387 // If the defining package is signed with our cert, it's okay. This 10388 // also includes the "updating the same package" case, of course. 10389 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10390 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10391 // If the owning package is the system itself, we log but allow 10392 // install to proceed; we fail the install on all other permission 10393 // redefinitions. 10394 if (!bp.sourcePackage.equals("android")) { 10395 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10396 + pkg.packageName + " attempting to redeclare permission " 10397 + perm.info.name + " already owned by " + bp.sourcePackage); 10398 res.origPermission = perm.info.name; 10399 res.origPackage = bp.sourcePackage; 10400 return; 10401 } else { 10402 Slog.w(TAG, "Package " + pkg.packageName 10403 + " attempting to redeclare system permission " 10404 + perm.info.name + "; ignoring new declaration"); 10405 pkg.permissions.remove(i); 10406 } 10407 } 10408 } 10409 } 10410 10411 // Check if installing already existing package 10412 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10413 String oldName = mSettings.mRenamedPackages.get(pkgName); 10414 if (pkg.mOriginalPackages != null 10415 && pkg.mOriginalPackages.contains(oldName) 10416 && mPackages.containsKey(oldName)) { 10417 // This package is derived from an original package, 10418 // and this device has been updating from that original 10419 // name. We must continue using the original name, so 10420 // rename the new package here. 10421 pkg.setPackageName(oldName); 10422 pkgName = pkg.packageName; 10423 replace = true; 10424 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10425 + oldName + " pkgName=" + pkgName); 10426 } else if (mPackages.containsKey(pkgName)) { 10427 // This package, under its official name, already exists 10428 // on the device; we should replace it. 10429 replace = true; 10430 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10431 } 10432 } 10433 PackageSetting ps = mSettings.mPackages.get(pkgName); 10434 if (ps != null) { 10435 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10436 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10437 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10438 systemApp = (ps.pkg.applicationInfo.flags & 10439 ApplicationInfo.FLAG_SYSTEM) != 0; 10440 } 10441 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10442 } 10443 } 10444 10445 if (systemApp && onSd) { 10446 // Disable updates to system apps on sdcard 10447 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10448 "Cannot install updates to system apps on sdcard"); 10449 return; 10450 } 10451 10452 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10453 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10454 return; 10455 } 10456 10457 if (replace) { 10458 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10459 installerPackageName, res, args.abiOverride); 10460 } else { 10461 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10462 installerPackageName, res, args.abiOverride); 10463 } 10464 synchronized (mPackages) { 10465 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10466 if (ps != null) { 10467 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10468 } 10469 } 10470 } 10471 10472 private static boolean isForwardLocked(PackageParser.Package pkg) { 10473 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10474 } 10475 10476 private static boolean isForwardLocked(ApplicationInfo info) { 10477 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10478 } 10479 10480 private boolean isForwardLocked(PackageSetting ps) { 10481 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10482 } 10483 10484 private static boolean isMultiArch(PackageSetting ps) { 10485 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10486 } 10487 10488 private static boolean isMultiArch(ApplicationInfo info) { 10489 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10490 } 10491 10492 private static boolean isExternal(PackageParser.Package pkg) { 10493 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10494 } 10495 10496 private static boolean isExternal(PackageSetting ps) { 10497 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10498 } 10499 10500 private static boolean isExternal(ApplicationInfo info) { 10501 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10502 } 10503 10504 private static boolean isSystemApp(PackageParser.Package pkg) { 10505 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10506 } 10507 10508 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10509 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10510 } 10511 10512 private static boolean isSystemApp(ApplicationInfo info) { 10513 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10514 } 10515 10516 private static boolean isSystemApp(PackageSetting ps) { 10517 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10518 } 10519 10520 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10521 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10522 } 10523 10524 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10525 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10526 } 10527 10528 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10529 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10530 } 10531 10532 private int packageFlagsToInstallFlags(PackageSetting ps) { 10533 int installFlags = 0; 10534 if (isExternal(ps)) { 10535 installFlags |= PackageManager.INSTALL_EXTERNAL; 10536 } 10537 if (isForwardLocked(ps)) { 10538 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10539 } 10540 return installFlags; 10541 } 10542 10543 private void deleteTempPackageFiles() { 10544 final FilenameFilter filter = new FilenameFilter() { 10545 public boolean accept(File dir, String name) { 10546 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10547 } 10548 }; 10549 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10550 file.delete(); 10551 } 10552 } 10553 10554 @Override 10555 public void deletePackageAsUser(final String packageName, 10556 final IPackageDeleteObserver observer, 10557 final int userId, final int flags) { 10558 mContext.enforceCallingOrSelfPermission( 10559 android.Manifest.permission.DELETE_PACKAGES, null); 10560 final int uid = Binder.getCallingUid(); 10561 if (UserHandle.getUserId(uid) != userId) { 10562 mContext.enforceCallingPermission( 10563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10564 "deletePackage for user " + userId); 10565 } 10566 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10567 try { 10568 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10569 } catch (RemoteException re) { 10570 } 10571 return; 10572 } 10573 10574 boolean blocked = 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 blocked = true; 10580 break; 10581 } 10582 } 10583 } else { 10584 blocked = getBlockUninstallForUser(packageName, userId); 10585 } 10586 if (blocked) { 10587 try { 10588 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10589 } catch (RemoteException re) { 10590 } 10591 return; 10592 } 10593 10594 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10595 // Queue up an async operation since the package deletion may take a little while. 10596 mHandler.post(new Runnable() { 10597 public void run() { 10598 mHandler.removeCallbacks(this); 10599 final int returnCode = deletePackageX(packageName, userId, flags); 10600 if (observer != null) { 10601 try { 10602 observer.packageDeleted(packageName, returnCode); 10603 } catch (RemoteException e) { 10604 Log.i(TAG, "Observer no longer exists."); 10605 } //end catch 10606 } //end if 10607 } //end run 10608 }); 10609 } 10610 10611 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10612 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10613 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10614 try { 10615 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10616 || dpm.isDeviceOwner(packageName))) { 10617 return true; 10618 } 10619 } catch (RemoteException e) { 10620 } 10621 return false; 10622 } 10623 10624 /** 10625 * This method is an internal method that could be get invoked either 10626 * to delete an installed package or to clean up a failed installation. 10627 * After deleting an installed package, a broadcast is sent to notify any 10628 * listeners that the package has been installed. For cleaning up a failed 10629 * installation, the broadcast is not necessary since the package's 10630 * installation wouldn't have sent the initial broadcast either 10631 * The key steps in deleting a package are 10632 * deleting the package information in internal structures like mPackages, 10633 * deleting the packages base directories through installd 10634 * updating mSettings to reflect current status 10635 * persisting settings for later use 10636 * sending a broadcast if necessary 10637 */ 10638 private int deletePackageX(String packageName, int userId, int flags) { 10639 final PackageRemovedInfo info = new PackageRemovedInfo(); 10640 final boolean res; 10641 10642 if (isPackageDeviceAdmin(packageName, userId)) { 10643 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10644 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10645 } 10646 10647 boolean removedForAllUsers = false; 10648 boolean systemUpdate = false; 10649 10650 // for the uninstall-updates case and restricted profiles, remember the per- 10651 // userhandle installed state 10652 int[] allUsers; 10653 boolean[] perUserInstalled; 10654 synchronized (mPackages) { 10655 PackageSetting ps = mSettings.mPackages.get(packageName); 10656 allUsers = sUserManager.getUserIds(); 10657 perUserInstalled = new boolean[allUsers.length]; 10658 for (int i = 0; i < allUsers.length; i++) { 10659 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10660 } 10661 } 10662 10663 synchronized (mInstallLock) { 10664 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10665 res = deletePackageLI(packageName, 10666 (flags & PackageManager.DELETE_ALL_USERS) != 0 10667 ? UserHandle.ALL : new UserHandle(userId), 10668 true, allUsers, perUserInstalled, 10669 flags | REMOVE_CHATTY, info, true); 10670 systemUpdate = info.isRemovedPackageSystemUpdate; 10671 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10672 removedForAllUsers = true; 10673 } 10674 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10675 + " removedForAllUsers=" + removedForAllUsers); 10676 } 10677 10678 if (res) { 10679 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10680 10681 // If the removed package was a system update, the old system package 10682 // was re-enabled; we need to broadcast this information 10683 if (systemUpdate) { 10684 Bundle extras = new Bundle(1); 10685 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10686 ? info.removedAppId : info.uid); 10687 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10688 10689 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10690 extras, null, null, null); 10691 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10692 extras, null, null, null); 10693 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10694 null, packageName, null, null); 10695 } 10696 } 10697 // Force a gc here. 10698 Runtime.getRuntime().gc(); 10699 // Delete the resources here after sending the broadcast to let 10700 // other processes clean up before deleting resources. 10701 if (info.args != null) { 10702 synchronized (mInstallLock) { 10703 info.args.doPostDeleteLI(true); 10704 } 10705 } 10706 10707 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10708 } 10709 10710 static class PackageRemovedInfo { 10711 String removedPackage; 10712 int uid = -1; 10713 int removedAppId = -1; 10714 int[] removedUsers = null; 10715 boolean isRemovedPackageSystemUpdate = false; 10716 // Clean up resources deleted packages. 10717 InstallArgs args = null; 10718 10719 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10720 Bundle extras = new Bundle(1); 10721 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10722 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10723 if (replacing) { 10724 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10725 } 10726 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10727 if (removedPackage != null) { 10728 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10729 extras, null, null, removedUsers); 10730 if (fullRemove && !replacing) { 10731 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10732 extras, null, null, removedUsers); 10733 } 10734 } 10735 if (removedAppId >= 0) { 10736 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10737 removedUsers); 10738 } 10739 } 10740 } 10741 10742 /* 10743 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10744 * flag is not set, the data directory is removed as well. 10745 * make sure this flag is set for partially installed apps. If not its meaningless to 10746 * delete a partially installed application. 10747 */ 10748 private void removePackageDataLI(PackageSetting ps, 10749 int[] allUserHandles, boolean[] perUserInstalled, 10750 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10751 String packageName = ps.name; 10752 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10753 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10754 // Retrieve object to delete permissions for shared user later on 10755 final PackageSetting deletedPs; 10756 // reader 10757 synchronized (mPackages) { 10758 deletedPs = mSettings.mPackages.get(packageName); 10759 if (outInfo != null) { 10760 outInfo.removedPackage = packageName; 10761 outInfo.removedUsers = deletedPs != null 10762 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10763 : null; 10764 } 10765 } 10766 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10767 removeDataDirsLI(packageName); 10768 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10769 } 10770 // writer 10771 synchronized (mPackages) { 10772 if (deletedPs != null) { 10773 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10774 if (outInfo != null) { 10775 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10776 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10777 } 10778 if (deletedPs != null) { 10779 updatePermissionsLPw(deletedPs.name, null, 0); 10780 if (deletedPs.sharedUser != null) { 10781 // remove permissions associated with package 10782 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10783 } 10784 } 10785 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10786 } 10787 // make sure to preserve per-user disabled state if this removal was just 10788 // a downgrade of a system app to the factory package 10789 if (allUserHandles != null && perUserInstalled != null) { 10790 if (DEBUG_REMOVE) { 10791 Slog.d(TAG, "Propagating install state across downgrade"); 10792 } 10793 for (int i = 0; i < allUserHandles.length; i++) { 10794 if (DEBUG_REMOVE) { 10795 Slog.d(TAG, " user " + allUserHandles[i] 10796 + " => " + perUserInstalled[i]); 10797 } 10798 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10799 } 10800 } 10801 } 10802 // can downgrade to reader 10803 if (writeSettings) { 10804 // Save settings now 10805 mSettings.writeLPr(); 10806 } 10807 } 10808 if (outInfo != null) { 10809 // A user ID was deleted here. Go through all users and remove it 10810 // from KeyStore. 10811 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10812 } 10813 } 10814 10815 static boolean locationIsPrivileged(File path) { 10816 try { 10817 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10818 .getCanonicalPath(); 10819 return path.getCanonicalPath().startsWith(privilegedAppDir); 10820 } catch (IOException e) { 10821 Slog.e(TAG, "Unable to access code path " + path); 10822 } 10823 return false; 10824 } 10825 10826 /* 10827 * Tries to delete system package. 10828 */ 10829 private boolean deleteSystemPackageLI(PackageSetting newPs, 10830 int[] allUserHandles, boolean[] perUserInstalled, 10831 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10832 final boolean applyUserRestrictions 10833 = (allUserHandles != null) && (perUserInstalled != null); 10834 PackageSetting disabledPs = null; 10835 // Confirm if the system package has been updated 10836 // An updated system app can be deleted. This will also have to restore 10837 // the system pkg from system partition 10838 // reader 10839 synchronized (mPackages) { 10840 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10841 } 10842 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10843 + " disabledPs=" + disabledPs); 10844 if (disabledPs == null) { 10845 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10846 return false; 10847 } else if (DEBUG_REMOVE) { 10848 Slog.d(TAG, "Deleting system pkg from data partition"); 10849 } 10850 if (DEBUG_REMOVE) { 10851 if (applyUserRestrictions) { 10852 Slog.d(TAG, "Remembering install states:"); 10853 for (int i = 0; i < allUserHandles.length; i++) { 10854 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10855 } 10856 } 10857 } 10858 // Delete the updated package 10859 outInfo.isRemovedPackageSystemUpdate = true; 10860 if (disabledPs.versionCode < newPs.versionCode) { 10861 // Delete data for downgrades 10862 flags &= ~PackageManager.DELETE_KEEP_DATA; 10863 } else { 10864 // Preserve data by setting flag 10865 flags |= PackageManager.DELETE_KEEP_DATA; 10866 } 10867 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10868 allUserHandles, perUserInstalled, outInfo, writeSettings); 10869 if (!ret) { 10870 return false; 10871 } 10872 // writer 10873 synchronized (mPackages) { 10874 // Reinstate the old system package 10875 mSettings.enableSystemPackageLPw(newPs.name); 10876 // Remove any native libraries from the upgraded package. 10877 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10878 } 10879 // Install the system package 10880 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10881 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10882 if (locationIsPrivileged(disabledPs.codePath)) { 10883 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10884 } 10885 10886 final PackageParser.Package newPkg; 10887 try { 10888 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10889 null, null); 10890 } catch (PackageManagerException e) { 10891 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10892 return false; 10893 } 10894 10895 // writer 10896 synchronized (mPackages) { 10897 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10898 setBundledAppAbisAndRoots(newPkg, ps); 10899 updatePermissionsLPw(newPkg.packageName, newPkg, 10900 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10901 if (applyUserRestrictions) { 10902 if (DEBUG_REMOVE) { 10903 Slog.d(TAG, "Propagating install state across reinstall"); 10904 } 10905 for (int i = 0; i < allUserHandles.length; i++) { 10906 if (DEBUG_REMOVE) { 10907 Slog.d(TAG, " user " + allUserHandles[i] 10908 + " => " + perUserInstalled[i]); 10909 } 10910 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10911 } 10912 // Regardless of writeSettings we need to ensure that this restriction 10913 // state propagation is persisted 10914 mSettings.writeAllUsersPackageRestrictionsLPr(); 10915 } 10916 // can downgrade to reader here 10917 if (writeSettings) { 10918 mSettings.writeLPr(); 10919 } 10920 } 10921 return true; 10922 } 10923 10924 private boolean deleteInstalledPackageLI(PackageSetting ps, 10925 boolean deleteCodeAndResources, int flags, 10926 int[] allUserHandles, boolean[] perUserInstalled, 10927 PackageRemovedInfo outInfo, boolean writeSettings) { 10928 if (outInfo != null) { 10929 outInfo.uid = ps.appId; 10930 } 10931 10932 // Delete package data from internal structures and also remove data if flag is set 10933 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10934 10935 // Delete application code and resources 10936 if (deleteCodeAndResources && (outInfo != null)) { 10937 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10938 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10939 getAppDexInstructionSets(ps), isMultiArch(ps)); 10940 } 10941 return true; 10942 } 10943 10944 @Override 10945 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10946 int userId) { 10947 mContext.enforceCallingOrSelfPermission( 10948 android.Manifest.permission.DELETE_PACKAGES, null); 10949 synchronized (mPackages) { 10950 PackageSetting ps = mSettings.mPackages.get(packageName); 10951 if (ps == null) { 10952 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10953 return false; 10954 } 10955 if (!ps.getInstalled(userId)) { 10956 // Can't block uninstall for an app that is not installed or enabled. 10957 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10958 return false; 10959 } 10960 ps.setBlockUninstall(blockUninstall, userId); 10961 mSettings.writePackageRestrictionsLPr(userId); 10962 } 10963 return true; 10964 } 10965 10966 @Override 10967 public boolean getBlockUninstallForUser(String packageName, int userId) { 10968 synchronized (mPackages) { 10969 PackageSetting ps = mSettings.mPackages.get(packageName); 10970 if (ps == null) { 10971 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10972 return false; 10973 } 10974 return ps.getBlockUninstall(userId); 10975 } 10976 } 10977 10978 /* 10979 * This method handles package deletion in general 10980 */ 10981 private boolean deletePackageLI(String packageName, UserHandle user, 10982 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10983 int flags, PackageRemovedInfo outInfo, 10984 boolean writeSettings) { 10985 if (packageName == null) { 10986 Slog.w(TAG, "Attempt to delete null packageName."); 10987 return false; 10988 } 10989 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10990 PackageSetting ps; 10991 boolean dataOnly = false; 10992 int removeUser = -1; 10993 int appId = -1; 10994 synchronized (mPackages) { 10995 ps = mSettings.mPackages.get(packageName); 10996 if (ps == null) { 10997 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10998 return false; 10999 } 11000 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11001 && user.getIdentifier() != UserHandle.USER_ALL) { 11002 // The caller is asking that the package only be deleted for a single 11003 // user. To do this, we just mark its uninstalled state and delete 11004 // its data. If this is a system app, we only allow this to happen if 11005 // they have set the special DELETE_SYSTEM_APP which requests different 11006 // semantics than normal for uninstalling system apps. 11007 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11008 ps.setUserState(user.getIdentifier(), 11009 COMPONENT_ENABLED_STATE_DEFAULT, 11010 false, //installed 11011 true, //stopped 11012 true, //notLaunched 11013 false, //blocked 11014 null, null, null, 11015 false // blockUninstall 11016 ); 11017 if (!isSystemApp(ps)) { 11018 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11019 // Other user still have this package installed, so all 11020 // we need to do is clear this user's data and save that 11021 // it is uninstalled. 11022 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11023 removeUser = user.getIdentifier(); 11024 appId = ps.appId; 11025 mSettings.writePackageRestrictionsLPr(removeUser); 11026 } else { 11027 // We need to set it back to 'installed' so the uninstall 11028 // broadcasts will be sent correctly. 11029 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11030 ps.setInstalled(true, user.getIdentifier()); 11031 } 11032 } else { 11033 // This is a system app, so we assume that the 11034 // other users still have this package installed, so all 11035 // we need to do is clear this user's data and save that 11036 // it is uninstalled. 11037 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11038 removeUser = user.getIdentifier(); 11039 appId = ps.appId; 11040 mSettings.writePackageRestrictionsLPr(removeUser); 11041 } 11042 } 11043 } 11044 11045 if (removeUser >= 0) { 11046 // From above, we determined that we are deleting this only 11047 // for a single user. Continue the work here. 11048 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11049 if (outInfo != null) { 11050 outInfo.removedPackage = packageName; 11051 outInfo.removedAppId = appId; 11052 outInfo.removedUsers = new int[] {removeUser}; 11053 } 11054 mInstaller.clearUserData(packageName, removeUser); 11055 removeKeystoreDataIfNeeded(removeUser, appId); 11056 schedulePackageCleaning(packageName, removeUser, false); 11057 return true; 11058 } 11059 11060 if (dataOnly) { 11061 // Delete application data first 11062 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11063 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11064 return true; 11065 } 11066 11067 boolean ret = false; 11068 if (isSystemApp(ps)) { 11069 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11070 // When an updated system application is deleted we delete the existing resources as well and 11071 // fall back to existing code in system partition 11072 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11073 flags, outInfo, writeSettings); 11074 } else { 11075 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11076 // Kill application pre-emptively especially for apps on sd. 11077 killApplication(packageName, ps.appId, "uninstall pkg"); 11078 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11079 allUserHandles, perUserInstalled, 11080 outInfo, writeSettings); 11081 } 11082 11083 return ret; 11084 } 11085 11086 private final class ClearStorageConnection implements ServiceConnection { 11087 IMediaContainerService mContainerService; 11088 11089 @Override 11090 public void onServiceConnected(ComponentName name, IBinder service) { 11091 synchronized (this) { 11092 mContainerService = IMediaContainerService.Stub.asInterface(service); 11093 notifyAll(); 11094 } 11095 } 11096 11097 @Override 11098 public void onServiceDisconnected(ComponentName name) { 11099 } 11100 } 11101 11102 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11103 final boolean mounted; 11104 if (Environment.isExternalStorageEmulated()) { 11105 mounted = true; 11106 } else { 11107 final String status = Environment.getExternalStorageState(); 11108 11109 mounted = status.equals(Environment.MEDIA_MOUNTED) 11110 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11111 } 11112 11113 if (!mounted) { 11114 return; 11115 } 11116 11117 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11118 int[] users; 11119 if (userId == UserHandle.USER_ALL) { 11120 users = sUserManager.getUserIds(); 11121 } else { 11122 users = new int[] { userId }; 11123 } 11124 final ClearStorageConnection conn = new ClearStorageConnection(); 11125 if (mContext.bindServiceAsUser( 11126 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11127 try { 11128 for (int curUser : users) { 11129 long timeout = SystemClock.uptimeMillis() + 5000; 11130 synchronized (conn) { 11131 long now = SystemClock.uptimeMillis(); 11132 while (conn.mContainerService == null && now < timeout) { 11133 try { 11134 conn.wait(timeout - now); 11135 } catch (InterruptedException e) { 11136 } 11137 } 11138 } 11139 if (conn.mContainerService == null) { 11140 return; 11141 } 11142 11143 final UserEnvironment userEnv = new UserEnvironment(curUser); 11144 clearDirectory(conn.mContainerService, 11145 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11146 if (allData) { 11147 clearDirectory(conn.mContainerService, 11148 userEnv.buildExternalStorageAppDataDirs(packageName)); 11149 clearDirectory(conn.mContainerService, 11150 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11151 } 11152 } 11153 } finally { 11154 mContext.unbindService(conn); 11155 } 11156 } 11157 } 11158 11159 @Override 11160 public void clearApplicationUserData(final String packageName, 11161 final IPackageDataObserver observer, final int userId) { 11162 mContext.enforceCallingOrSelfPermission( 11163 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11164 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11165 // Queue up an async operation since the package deletion may take a little while. 11166 mHandler.post(new Runnable() { 11167 public void run() { 11168 mHandler.removeCallbacks(this); 11169 final boolean succeeded; 11170 synchronized (mInstallLock) { 11171 succeeded = clearApplicationUserDataLI(packageName, userId); 11172 } 11173 clearExternalStorageDataSync(packageName, userId, true); 11174 if (succeeded) { 11175 // invoke DeviceStorageMonitor's update method to clear any notifications 11176 DeviceStorageMonitorInternal 11177 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11178 if (dsm != null) { 11179 dsm.checkMemory(); 11180 } 11181 } 11182 if(observer != null) { 11183 try { 11184 observer.onRemoveCompleted(packageName, succeeded); 11185 } catch (RemoteException e) { 11186 Log.i(TAG, "Observer no longer exists."); 11187 } 11188 } //end if observer 11189 } //end run 11190 }); 11191 } 11192 11193 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11194 if (packageName == null) { 11195 Slog.w(TAG, "Attempt to delete null packageName."); 11196 return false; 11197 } 11198 PackageParser.Package p; 11199 boolean dataOnly = false; 11200 final int appId; 11201 synchronized (mPackages) { 11202 p = mPackages.get(packageName); 11203 if (p == null) { 11204 dataOnly = true; 11205 PackageSetting ps = mSettings.mPackages.get(packageName); 11206 if ((ps == null) || (ps.pkg == null)) { 11207 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11208 return false; 11209 } 11210 p = ps.pkg; 11211 } 11212 if (!dataOnly) { 11213 // need to check this only for fully installed applications 11214 if (p == null) { 11215 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11216 return false; 11217 } 11218 final ApplicationInfo applicationInfo = p.applicationInfo; 11219 if (applicationInfo == null) { 11220 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11221 return false; 11222 } 11223 } 11224 if (p != null && p.applicationInfo != null) { 11225 appId = p.applicationInfo.uid; 11226 } else { 11227 appId = -1; 11228 } 11229 } 11230 int retCode = mInstaller.clearUserData(packageName, userId); 11231 if (retCode < 0) { 11232 Slog.w(TAG, "Couldn't remove cache files for package: " 11233 + packageName); 11234 return false; 11235 } 11236 removeKeystoreDataIfNeeded(userId, appId); 11237 return true; 11238 } 11239 11240 /** 11241 * Remove entries from the keystore daemon. Will only remove it if the 11242 * {@code appId} is valid. 11243 */ 11244 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11245 if (appId < 0) { 11246 return; 11247 } 11248 11249 final KeyStore keyStore = KeyStore.getInstance(); 11250 if (keyStore != null) { 11251 if (userId == UserHandle.USER_ALL) { 11252 for (final int individual : sUserManager.getUserIds()) { 11253 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11254 } 11255 } else { 11256 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11257 } 11258 } else { 11259 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11260 } 11261 } 11262 11263 @Override 11264 public void deleteApplicationCacheFiles(final String packageName, 11265 final IPackageDataObserver observer) { 11266 mContext.enforceCallingOrSelfPermission( 11267 android.Manifest.permission.DELETE_CACHE_FILES, null); 11268 // Queue up an async operation since the package deletion may take a little while. 11269 final int userId = UserHandle.getCallingUserId(); 11270 mHandler.post(new Runnable() { 11271 public void run() { 11272 mHandler.removeCallbacks(this); 11273 final boolean succeded; 11274 synchronized (mInstallLock) { 11275 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11276 } 11277 clearExternalStorageDataSync(packageName, userId, false); 11278 if(observer != null) { 11279 try { 11280 observer.onRemoveCompleted(packageName, succeded); 11281 } catch (RemoteException e) { 11282 Log.i(TAG, "Observer no longer exists."); 11283 } 11284 } //end if observer 11285 } //end run 11286 }); 11287 } 11288 11289 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11290 if (packageName == null) { 11291 Slog.w(TAG, "Attempt to delete null packageName."); 11292 return false; 11293 } 11294 PackageParser.Package p; 11295 synchronized (mPackages) { 11296 p = mPackages.get(packageName); 11297 } 11298 if (p == null) { 11299 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11300 return false; 11301 } 11302 final ApplicationInfo applicationInfo = p.applicationInfo; 11303 if (applicationInfo == null) { 11304 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11305 return false; 11306 } 11307 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11308 if (retCode < 0) { 11309 Slog.w(TAG, "Couldn't remove cache files for package: " 11310 + packageName + " u" + userId); 11311 return false; 11312 } 11313 return true; 11314 } 11315 11316 @Override 11317 public void getPackageSizeInfo(final String packageName, int userHandle, 11318 final IPackageStatsObserver observer) { 11319 mContext.enforceCallingOrSelfPermission( 11320 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11321 if (packageName == null) { 11322 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11323 } 11324 11325 PackageStats stats = new PackageStats(packageName, userHandle); 11326 11327 /* 11328 * Queue up an async operation since the package measurement may take a 11329 * little while. 11330 */ 11331 Message msg = mHandler.obtainMessage(INIT_COPY); 11332 msg.obj = new MeasureParams(stats, observer); 11333 mHandler.sendMessage(msg); 11334 } 11335 11336 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11337 PackageStats pStats) { 11338 if (packageName == null) { 11339 Slog.w(TAG, "Attempt to get size of null packageName."); 11340 return false; 11341 } 11342 PackageParser.Package p; 11343 boolean dataOnly = false; 11344 String libDirRoot = null; 11345 String asecPath = null; 11346 PackageSetting ps = null; 11347 synchronized (mPackages) { 11348 p = mPackages.get(packageName); 11349 ps = mSettings.mPackages.get(packageName); 11350 if(p == null) { 11351 dataOnly = true; 11352 if((ps == null) || (ps.pkg == null)) { 11353 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11354 return false; 11355 } 11356 p = ps.pkg; 11357 } 11358 if (ps != null) { 11359 libDirRoot = ps.legacyNativeLibraryPathString; 11360 } 11361 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11362 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11363 if (secureContainerId != null) { 11364 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11365 } 11366 } 11367 } 11368 String publicSrcDir = null; 11369 if(!dataOnly) { 11370 final ApplicationInfo applicationInfo = p.applicationInfo; 11371 if (applicationInfo == null) { 11372 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11373 return false; 11374 } 11375 if (isForwardLocked(p)) { 11376 publicSrcDir = applicationInfo.getBaseResourcePath(); 11377 } 11378 } 11379 // TODO: extend to measure size of split APKs 11380 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11381 // not just the first level. 11382 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11383 // just the primary. 11384 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11385 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11386 pStats); 11387 if (res < 0) { 11388 return false; 11389 } 11390 11391 // Fix-up for forward-locked applications in ASEC containers. 11392 if (!isExternal(p)) { 11393 pStats.codeSize += pStats.externalCodeSize; 11394 pStats.externalCodeSize = 0L; 11395 } 11396 11397 return true; 11398 } 11399 11400 11401 @Override 11402 public void addPackageToPreferred(String packageName) { 11403 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11404 } 11405 11406 @Override 11407 public void removePackageFromPreferred(String packageName) { 11408 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11409 } 11410 11411 @Override 11412 public List<PackageInfo> getPreferredPackages(int flags) { 11413 return new ArrayList<PackageInfo>(); 11414 } 11415 11416 private int getUidTargetSdkVersionLockedLPr(int uid) { 11417 Object obj = mSettings.getUserIdLPr(uid); 11418 if (obj instanceof SharedUserSetting) { 11419 final SharedUserSetting sus = (SharedUserSetting) obj; 11420 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11421 final Iterator<PackageSetting> it = sus.packages.iterator(); 11422 while (it.hasNext()) { 11423 final PackageSetting ps = it.next(); 11424 if (ps.pkg != null) { 11425 int v = ps.pkg.applicationInfo.targetSdkVersion; 11426 if (v < vers) vers = v; 11427 } 11428 } 11429 return vers; 11430 } else if (obj instanceof PackageSetting) { 11431 final PackageSetting ps = (PackageSetting) obj; 11432 if (ps.pkg != null) { 11433 return ps.pkg.applicationInfo.targetSdkVersion; 11434 } 11435 } 11436 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11437 } 11438 11439 @Override 11440 public void addPreferredActivity(IntentFilter filter, int match, 11441 ComponentName[] set, ComponentName activity, int userId) { 11442 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11443 } 11444 11445 private void addPreferredActivityInternal(IntentFilter filter, int match, 11446 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11447 // writer 11448 int callingUid = Binder.getCallingUid(); 11449 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11450 if (filter.countActions() == 0) { 11451 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11452 return; 11453 } 11454 synchronized (mPackages) { 11455 if (mContext.checkCallingOrSelfPermission( 11456 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11457 != PackageManager.PERMISSION_GRANTED) { 11458 if (getUidTargetSdkVersionLockedLPr(callingUid) 11459 < Build.VERSION_CODES.FROYO) { 11460 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11461 + callingUid); 11462 return; 11463 } 11464 mContext.enforceCallingOrSelfPermission( 11465 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11466 } 11467 11468 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11469 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11470 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11471 new PreferredActivity(filter, match, set, activity, always)); 11472 mSettings.writePackageRestrictionsLPr(userId); 11473 } 11474 } 11475 11476 @Override 11477 public void replacePreferredActivity(IntentFilter filter, int match, 11478 ComponentName[] set, ComponentName activity) { 11479 if (filter.countActions() != 1) { 11480 throw new IllegalArgumentException( 11481 "replacePreferredActivity expects filter to have only 1 action."); 11482 } 11483 if (filter.countDataAuthorities() != 0 11484 || filter.countDataPaths() != 0 11485 || filter.countDataSchemes() > 1 11486 || filter.countDataTypes() != 0) { 11487 throw new IllegalArgumentException( 11488 "replacePreferredActivity expects filter to have no data authorities, " + 11489 "paths, or types; and at most one scheme."); 11490 } 11491 synchronized (mPackages) { 11492 if (mContext.checkCallingOrSelfPermission( 11493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11494 != PackageManager.PERMISSION_GRANTED) { 11495 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11496 < Build.VERSION_CODES.FROYO) { 11497 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11498 + Binder.getCallingUid()); 11499 return; 11500 } 11501 mContext.enforceCallingOrSelfPermission( 11502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11503 } 11504 11505 final int callingUserId = UserHandle.getCallingUserId(); 11506 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11507 if (pir != null) { 11508 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11509 if (filter.countDataSchemes() == 1) { 11510 Uri.Builder builder = new Uri.Builder(); 11511 builder.scheme(filter.getDataScheme(0)); 11512 intent.setData(builder.build()); 11513 } 11514 List<PreferredActivity> matches = pir.queryIntent( 11515 intent, null, true, callingUserId); 11516 if (DEBUG_PREFERRED) { 11517 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11518 } 11519 for (int i = 0; i < matches.size(); i++) { 11520 PreferredActivity pa = matches.get(i); 11521 if (DEBUG_PREFERRED) { 11522 Slog.i(TAG, "Removing preferred activity " 11523 + pa.mPref.mComponent + ":"); 11524 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11525 } 11526 pir.removeFilter(pa); 11527 } 11528 } 11529 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11530 } 11531 } 11532 11533 @Override 11534 public void clearPackagePreferredActivities(String packageName) { 11535 final int uid = Binder.getCallingUid(); 11536 // writer 11537 synchronized (mPackages) { 11538 PackageParser.Package pkg = mPackages.get(packageName); 11539 if (pkg == null || pkg.applicationInfo.uid != uid) { 11540 if (mContext.checkCallingOrSelfPermission( 11541 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11542 != PackageManager.PERMISSION_GRANTED) { 11543 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11544 < Build.VERSION_CODES.FROYO) { 11545 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11546 + Binder.getCallingUid()); 11547 return; 11548 } 11549 mContext.enforceCallingOrSelfPermission( 11550 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11551 } 11552 } 11553 11554 int user = UserHandle.getCallingUserId(); 11555 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11556 mSettings.writePackageRestrictionsLPr(user); 11557 scheduleWriteSettingsLocked(); 11558 } 11559 } 11560 } 11561 11562 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11563 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11564 ArrayList<PreferredActivity> removed = null; 11565 boolean changed = false; 11566 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11567 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11568 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11569 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11570 continue; 11571 } 11572 Iterator<PreferredActivity> it = pir.filterIterator(); 11573 while (it.hasNext()) { 11574 PreferredActivity pa = it.next(); 11575 // Mark entry for removal only if it matches the package name 11576 // and the entry is of type "always". 11577 if (packageName == null || 11578 (pa.mPref.mComponent.getPackageName().equals(packageName) 11579 && pa.mPref.mAlways)) { 11580 if (removed == null) { 11581 removed = new ArrayList<PreferredActivity>(); 11582 } 11583 removed.add(pa); 11584 } 11585 } 11586 if (removed != null) { 11587 for (int j=0; j<removed.size(); j++) { 11588 PreferredActivity pa = removed.get(j); 11589 pir.removeFilter(pa); 11590 } 11591 changed = true; 11592 } 11593 } 11594 return changed; 11595 } 11596 11597 @Override 11598 public void resetPreferredActivities(int userId) { 11599 mContext.enforceCallingOrSelfPermission( 11600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11601 // writer 11602 synchronized (mPackages) { 11603 int user = UserHandle.getCallingUserId(); 11604 clearPackagePreferredActivitiesLPw(null, user); 11605 mSettings.readDefaultPreferredAppsLPw(this, user); 11606 mSettings.writePackageRestrictionsLPr(user); 11607 scheduleWriteSettingsLocked(); 11608 } 11609 } 11610 11611 @Override 11612 public int getPreferredActivities(List<IntentFilter> outFilters, 11613 List<ComponentName> outActivities, String packageName) { 11614 11615 int num = 0; 11616 final int userId = UserHandle.getCallingUserId(); 11617 // reader 11618 synchronized (mPackages) { 11619 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11620 if (pir != null) { 11621 final Iterator<PreferredActivity> it = pir.filterIterator(); 11622 while (it.hasNext()) { 11623 final PreferredActivity pa = it.next(); 11624 if (packageName == null 11625 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11626 && pa.mPref.mAlways)) { 11627 if (outFilters != null) { 11628 outFilters.add(new IntentFilter(pa)); 11629 } 11630 if (outActivities != null) { 11631 outActivities.add(pa.mPref.mComponent); 11632 } 11633 } 11634 } 11635 } 11636 } 11637 11638 return num; 11639 } 11640 11641 @Override 11642 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11643 int userId) { 11644 int callingUid = Binder.getCallingUid(); 11645 if (callingUid != Process.SYSTEM_UID) { 11646 throw new SecurityException( 11647 "addPersistentPreferredActivity can only be run by the system"); 11648 } 11649 if (filter.countActions() == 0) { 11650 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11651 return; 11652 } 11653 synchronized (mPackages) { 11654 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11655 " :"); 11656 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11657 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11658 new PersistentPreferredActivity(filter, activity)); 11659 mSettings.writePackageRestrictionsLPr(userId); 11660 } 11661 } 11662 11663 @Override 11664 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11665 int callingUid = Binder.getCallingUid(); 11666 if (callingUid != Process.SYSTEM_UID) { 11667 throw new SecurityException( 11668 "clearPackagePersistentPreferredActivities can only be run by the system"); 11669 } 11670 ArrayList<PersistentPreferredActivity> removed = null; 11671 boolean changed = false; 11672 synchronized (mPackages) { 11673 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11674 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11675 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11676 .valueAt(i); 11677 if (userId != thisUserId) { 11678 continue; 11679 } 11680 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11681 while (it.hasNext()) { 11682 PersistentPreferredActivity ppa = it.next(); 11683 // Mark entry for removal only if it matches the package name. 11684 if (ppa.mComponent.getPackageName().equals(packageName)) { 11685 if (removed == null) { 11686 removed = new ArrayList<PersistentPreferredActivity>(); 11687 } 11688 removed.add(ppa); 11689 } 11690 } 11691 if (removed != null) { 11692 for (int j=0; j<removed.size(); j++) { 11693 PersistentPreferredActivity ppa = removed.get(j); 11694 ppir.removeFilter(ppa); 11695 } 11696 changed = true; 11697 } 11698 } 11699 11700 if (changed) { 11701 mSettings.writePackageRestrictionsLPr(userId); 11702 } 11703 } 11704 } 11705 11706 @Override 11707 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11708 int targetUserId, int flags) { 11709 mContext.enforceCallingOrSelfPermission( 11710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11711 if (intentFilter.countActions() == 0) { 11712 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11713 return; 11714 } 11715 synchronized (mPackages) { 11716 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11717 targetUserId, flags); 11718 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11719 mSettings.writePackageRestrictionsLPr(sourceUserId); 11720 } 11721 } 11722 11723 public void addCrossProfileIntentsForPackage(String packageName, 11724 int sourceUserId, int targetUserId) { 11725 mContext.enforceCallingOrSelfPermission( 11726 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11727 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11728 mSettings.writePackageRestrictionsLPr(sourceUserId); 11729 } 11730 11731 public void removeCrossProfileIntentsForPackage(String packageName, 11732 int sourceUserId, int targetUserId) { 11733 mContext.enforceCallingOrSelfPermission( 11734 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11735 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11736 mSettings.writePackageRestrictionsLPr(sourceUserId); 11737 } 11738 11739 @Override 11740 public void clearCrossProfileIntentFilters(int sourceUserId) { 11741 mContext.enforceCallingOrSelfPermission( 11742 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11743 synchronized (mPackages) { 11744 CrossProfileIntentResolver resolver = 11745 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11746 HashSet<CrossProfileIntentFilter> set = 11747 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11748 for (CrossProfileIntentFilter filter : set) { 11749 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11750 resolver.removeFilter(filter); 11751 } 11752 } 11753 mSettings.writePackageRestrictionsLPr(sourceUserId); 11754 } 11755 } 11756 11757 @Override 11758 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11759 Intent intent = new Intent(Intent.ACTION_MAIN); 11760 intent.addCategory(Intent.CATEGORY_HOME); 11761 11762 final int callingUserId = UserHandle.getCallingUserId(); 11763 List<ResolveInfo> list = queryIntentActivities(intent, null, 11764 PackageManager.GET_META_DATA, callingUserId); 11765 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11766 true, false, false, callingUserId); 11767 11768 allHomeCandidates.clear(); 11769 if (list != null) { 11770 for (ResolveInfo ri : list) { 11771 allHomeCandidates.add(ri); 11772 } 11773 } 11774 return (preferred == null || preferred.activityInfo == null) 11775 ? null 11776 : new ComponentName(preferred.activityInfo.packageName, 11777 preferred.activityInfo.name); 11778 } 11779 11780 @Override 11781 public void setApplicationEnabledSetting(String appPackageName, 11782 int newState, int flags, int userId, String callingPackage) { 11783 if (!sUserManager.exists(userId)) return; 11784 if (callingPackage == null) { 11785 callingPackage = Integer.toString(Binder.getCallingUid()); 11786 } 11787 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11788 } 11789 11790 @Override 11791 public void setComponentEnabledSetting(ComponentName componentName, 11792 int newState, int flags, int userId) { 11793 if (!sUserManager.exists(userId)) return; 11794 setEnabledSetting(componentName.getPackageName(), 11795 componentName.getClassName(), newState, flags, userId, null); 11796 } 11797 11798 private void setEnabledSetting(final String packageName, String className, int newState, 11799 final int flags, int userId, String callingPackage) { 11800 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11801 || newState == COMPONENT_ENABLED_STATE_ENABLED 11802 || newState == COMPONENT_ENABLED_STATE_DISABLED 11803 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11804 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11805 throw new IllegalArgumentException("Invalid new component state: " 11806 + newState); 11807 } 11808 PackageSetting pkgSetting; 11809 final int uid = Binder.getCallingUid(); 11810 final int permission = mContext.checkCallingOrSelfPermission( 11811 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11812 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11813 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11814 boolean sendNow = false; 11815 boolean isApp = (className == null); 11816 String componentName = isApp ? packageName : className; 11817 int packageUid = -1; 11818 ArrayList<String> components; 11819 11820 // writer 11821 synchronized (mPackages) { 11822 pkgSetting = mSettings.mPackages.get(packageName); 11823 if (pkgSetting == null) { 11824 if (className == null) { 11825 throw new IllegalArgumentException( 11826 "Unknown package: " + packageName); 11827 } 11828 throw new IllegalArgumentException( 11829 "Unknown component: " + packageName 11830 + "/" + className); 11831 } 11832 // Allow root and verify that userId is not being specified by a different user 11833 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11834 throw new SecurityException( 11835 "Permission Denial: attempt to change component state from pid=" 11836 + Binder.getCallingPid() 11837 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11838 } 11839 if (className == null) { 11840 // We're dealing with an application/package level state change 11841 if (pkgSetting.getEnabled(userId) == newState) { 11842 // Nothing to do 11843 return; 11844 } 11845 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11846 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11847 // Don't care about who enables an app. 11848 callingPackage = null; 11849 } 11850 pkgSetting.setEnabled(newState, userId, callingPackage); 11851 // pkgSetting.pkg.mSetEnabled = newState; 11852 } else { 11853 // We're dealing with a component level state change 11854 // First, verify that this is a valid class name. 11855 PackageParser.Package pkg = pkgSetting.pkg; 11856 if (pkg == null || !pkg.hasComponentClassName(className)) { 11857 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11858 throw new IllegalArgumentException("Component class " + className 11859 + " does not exist in " + packageName); 11860 } else { 11861 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11862 + className + " does not exist in " + packageName); 11863 } 11864 } 11865 switch (newState) { 11866 case COMPONENT_ENABLED_STATE_ENABLED: 11867 if (!pkgSetting.enableComponentLPw(className, userId)) { 11868 return; 11869 } 11870 break; 11871 case COMPONENT_ENABLED_STATE_DISABLED: 11872 if (!pkgSetting.disableComponentLPw(className, userId)) { 11873 return; 11874 } 11875 break; 11876 case COMPONENT_ENABLED_STATE_DEFAULT: 11877 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11878 return; 11879 } 11880 break; 11881 default: 11882 Slog.e(TAG, "Invalid new component state: " + newState); 11883 return; 11884 } 11885 } 11886 mSettings.writePackageRestrictionsLPr(userId); 11887 components = mPendingBroadcasts.get(userId, packageName); 11888 final boolean newPackage = components == null; 11889 if (newPackage) { 11890 components = new ArrayList<String>(); 11891 } 11892 if (!components.contains(componentName)) { 11893 components.add(componentName); 11894 } 11895 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11896 sendNow = true; 11897 // Purge entry from pending broadcast list if another one exists already 11898 // since we are sending one right away. 11899 mPendingBroadcasts.remove(userId, packageName); 11900 } else { 11901 if (newPackage) { 11902 mPendingBroadcasts.put(userId, packageName, components); 11903 } 11904 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11905 // Schedule a message 11906 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11907 } 11908 } 11909 } 11910 11911 long callingId = Binder.clearCallingIdentity(); 11912 try { 11913 if (sendNow) { 11914 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11915 sendPackageChangedBroadcast(packageName, 11916 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11917 } 11918 } finally { 11919 Binder.restoreCallingIdentity(callingId); 11920 } 11921 } 11922 11923 private void sendPackageChangedBroadcast(String packageName, 11924 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11925 if (DEBUG_INSTALL) 11926 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11927 + componentNames); 11928 Bundle extras = new Bundle(4); 11929 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11930 String nameList[] = new String[componentNames.size()]; 11931 componentNames.toArray(nameList); 11932 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11933 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11934 extras.putInt(Intent.EXTRA_UID, packageUid); 11935 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11936 new int[] {UserHandle.getUserId(packageUid)}); 11937 } 11938 11939 @Override 11940 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11941 if (!sUserManager.exists(userId)) return; 11942 final int uid = Binder.getCallingUid(); 11943 final int permission = mContext.checkCallingOrSelfPermission( 11944 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11945 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11946 enforceCrossUserPermission(uid, userId, true, "stop package"); 11947 // writer 11948 synchronized (mPackages) { 11949 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11950 uid, userId)) { 11951 scheduleWritePackageRestrictionsLocked(userId); 11952 } 11953 } 11954 } 11955 11956 @Override 11957 public String getInstallerPackageName(String packageName) { 11958 // reader 11959 synchronized (mPackages) { 11960 return mSettings.getInstallerPackageNameLPr(packageName); 11961 } 11962 } 11963 11964 @Override 11965 public int getApplicationEnabledSetting(String packageName, int userId) { 11966 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11967 int uid = Binder.getCallingUid(); 11968 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11969 // reader 11970 synchronized (mPackages) { 11971 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11972 } 11973 } 11974 11975 @Override 11976 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11977 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11978 int uid = Binder.getCallingUid(); 11979 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11980 // reader 11981 synchronized (mPackages) { 11982 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11983 } 11984 } 11985 11986 @Override 11987 public void enterSafeMode() { 11988 enforceSystemOrRoot("Only the system can request entering safe mode"); 11989 11990 if (!mSystemReady) { 11991 mSafeMode = true; 11992 } 11993 } 11994 11995 @Override 11996 public void systemReady() { 11997 mSystemReady = true; 11998 11999 // Read the compatibilty setting when the system is ready. 12000 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12001 mContext.getContentResolver(), 12002 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12003 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12004 if (DEBUG_SETTINGS) { 12005 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12006 } 12007 12008 synchronized (mPackages) { 12009 // Verify that all of the preferred activity components actually 12010 // exist. It is possible for applications to be updated and at 12011 // that point remove a previously declared activity component that 12012 // had been set as a preferred activity. We try to clean this up 12013 // the next time we encounter that preferred activity, but it is 12014 // possible for the user flow to never be able to return to that 12015 // situation so here we do a sanity check to make sure we haven't 12016 // left any junk around. 12017 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12018 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12019 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12020 removed.clear(); 12021 for (PreferredActivity pa : pir.filterSet()) { 12022 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12023 removed.add(pa); 12024 } 12025 } 12026 if (removed.size() > 0) { 12027 for (int r=0; r<removed.size(); r++) { 12028 PreferredActivity pa = removed.get(r); 12029 Slog.w(TAG, "Removing dangling preferred activity: " 12030 + pa.mPref.mComponent); 12031 pir.removeFilter(pa); 12032 } 12033 mSettings.writePackageRestrictionsLPr( 12034 mSettings.mPreferredActivities.keyAt(i)); 12035 } 12036 } 12037 } 12038 sUserManager.systemReady(); 12039 } 12040 12041 @Override 12042 public boolean isSafeMode() { 12043 return mSafeMode; 12044 } 12045 12046 @Override 12047 public boolean hasSystemUidErrors() { 12048 return mHasSystemUidErrors; 12049 } 12050 12051 static String arrayToString(int[] array) { 12052 StringBuffer buf = new StringBuffer(128); 12053 buf.append('['); 12054 if (array != null) { 12055 for (int i=0; i<array.length; i++) { 12056 if (i > 0) buf.append(", "); 12057 buf.append(array[i]); 12058 } 12059 } 12060 buf.append(']'); 12061 return buf.toString(); 12062 } 12063 12064 static class DumpState { 12065 public static final int DUMP_LIBS = 1 << 0; 12066 public static final int DUMP_FEATURES = 1 << 1; 12067 public static final int DUMP_RESOLVERS = 1 << 2; 12068 public static final int DUMP_PERMISSIONS = 1 << 3; 12069 public static final int DUMP_PACKAGES = 1 << 4; 12070 public static final int DUMP_SHARED_USERS = 1 << 5; 12071 public static final int DUMP_MESSAGES = 1 << 6; 12072 public static final int DUMP_PROVIDERS = 1 << 7; 12073 public static final int DUMP_VERIFIERS = 1 << 8; 12074 public static final int DUMP_PREFERRED = 1 << 9; 12075 public static final int DUMP_PREFERRED_XML = 1 << 10; 12076 public static final int DUMP_KEYSETS = 1 << 11; 12077 public static final int DUMP_VERSION = 1 << 12; 12078 public static final int DUMP_INSTALLS = 1 << 13; 12079 12080 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12081 12082 private int mTypes; 12083 12084 private int mOptions; 12085 12086 private boolean mTitlePrinted; 12087 12088 private SharedUserSetting mSharedUser; 12089 12090 public boolean isDumping(int type) { 12091 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12092 return true; 12093 } 12094 12095 return (mTypes & type) != 0; 12096 } 12097 12098 public void setDump(int type) { 12099 mTypes |= type; 12100 } 12101 12102 public boolean isOptionEnabled(int option) { 12103 return (mOptions & option) != 0; 12104 } 12105 12106 public void setOptionEnabled(int option) { 12107 mOptions |= option; 12108 } 12109 12110 public boolean onTitlePrinted() { 12111 final boolean printed = mTitlePrinted; 12112 mTitlePrinted = true; 12113 return printed; 12114 } 12115 12116 public boolean getTitlePrinted() { 12117 return mTitlePrinted; 12118 } 12119 12120 public void setTitlePrinted(boolean enabled) { 12121 mTitlePrinted = enabled; 12122 } 12123 12124 public SharedUserSetting getSharedUser() { 12125 return mSharedUser; 12126 } 12127 12128 public void setSharedUser(SharedUserSetting user) { 12129 mSharedUser = user; 12130 } 12131 } 12132 12133 @Override 12134 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12135 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12136 != PackageManager.PERMISSION_GRANTED) { 12137 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12138 + Binder.getCallingPid() 12139 + ", uid=" + Binder.getCallingUid() 12140 + " without permission " 12141 + android.Manifest.permission.DUMP); 12142 return; 12143 } 12144 12145 DumpState dumpState = new DumpState(); 12146 boolean fullPreferred = false; 12147 boolean checkin = false; 12148 12149 String packageName = null; 12150 12151 int opti = 0; 12152 while (opti < args.length) { 12153 String opt = args[opti]; 12154 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12155 break; 12156 } 12157 opti++; 12158 if ("-a".equals(opt)) { 12159 // Right now we only know how to print all. 12160 } else if ("-h".equals(opt)) { 12161 pw.println("Package manager dump options:"); 12162 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12163 pw.println(" --checkin: dump for a checkin"); 12164 pw.println(" -f: print details of intent filters"); 12165 pw.println(" -h: print this help"); 12166 pw.println(" cmd may be one of:"); 12167 pw.println(" l[ibraries]: list known shared libraries"); 12168 pw.println(" f[ibraries]: list device features"); 12169 pw.println(" k[eysets]: print known keysets"); 12170 pw.println(" r[esolvers]: dump intent resolvers"); 12171 pw.println(" perm[issions]: dump permissions"); 12172 pw.println(" pref[erred]: print preferred package settings"); 12173 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12174 pw.println(" prov[iders]: dump content providers"); 12175 pw.println(" p[ackages]: dump installed packages"); 12176 pw.println(" s[hared-users]: dump shared user IDs"); 12177 pw.println(" m[essages]: print collected runtime messages"); 12178 pw.println(" v[erifiers]: print package verifier info"); 12179 pw.println(" version: print database version info"); 12180 pw.println(" write: write current settings now"); 12181 pw.println(" <package.name>: info about given package"); 12182 pw.println(" installs: details about install sessions"); 12183 return; 12184 } else if ("--checkin".equals(opt)) { 12185 checkin = true; 12186 } else if ("-f".equals(opt)) { 12187 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12188 } else { 12189 pw.println("Unknown argument: " + opt + "; use -h for help"); 12190 } 12191 } 12192 12193 // Is the caller requesting to dump a particular piece of data? 12194 if (opti < args.length) { 12195 String cmd = args[opti]; 12196 opti++; 12197 // Is this a package name? 12198 if ("android".equals(cmd) || cmd.contains(".")) { 12199 packageName = cmd; 12200 // When dumping a single package, we always dump all of its 12201 // filter information since the amount of data will be reasonable. 12202 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12203 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12204 dumpState.setDump(DumpState.DUMP_LIBS); 12205 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12206 dumpState.setDump(DumpState.DUMP_FEATURES); 12207 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12208 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12209 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12210 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12211 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_PREFERRED); 12213 } else if ("preferred-xml".equals(cmd)) { 12214 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12215 if (opti < args.length && "--full".equals(args[opti])) { 12216 fullPreferred = true; 12217 opti++; 12218 } 12219 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12220 dumpState.setDump(DumpState.DUMP_PACKAGES); 12221 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12222 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12223 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12224 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12225 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12226 dumpState.setDump(DumpState.DUMP_MESSAGES); 12227 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12228 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12229 } else if ("version".equals(cmd)) { 12230 dumpState.setDump(DumpState.DUMP_VERSION); 12231 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12232 dumpState.setDump(DumpState.DUMP_KEYSETS); 12233 } else if ("write".equals(cmd)) { 12234 synchronized (mPackages) { 12235 mSettings.writeLPr(); 12236 pw.println("Settings written."); 12237 return; 12238 } 12239 } else if ("installs".equals(cmd)) { 12240 dumpState.setDump(DumpState.DUMP_INSTALLS); 12241 } 12242 } 12243 12244 if (checkin) { 12245 pw.println("vers,1"); 12246 } 12247 12248 // reader 12249 synchronized (mPackages) { 12250 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12251 if (!checkin) { 12252 if (dumpState.onTitlePrinted()) 12253 pw.println(); 12254 pw.println("Database versions:"); 12255 pw.print(" SDK Version:"); 12256 pw.print(" internal="); 12257 pw.print(mSettings.mInternalSdkPlatform); 12258 pw.print(" external="); 12259 pw.println(mSettings.mExternalSdkPlatform); 12260 pw.print(" DB Version:"); 12261 pw.print(" internal="); 12262 pw.print(mSettings.mInternalDatabaseVersion); 12263 pw.print(" external="); 12264 pw.println(mSettings.mExternalDatabaseVersion); 12265 } 12266 } 12267 12268 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12269 if (!checkin) { 12270 if (dumpState.onTitlePrinted()) 12271 pw.println(); 12272 pw.println("Verifiers:"); 12273 pw.print(" Required: "); 12274 pw.print(mRequiredVerifierPackage); 12275 pw.print(" (uid="); 12276 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12277 pw.println(")"); 12278 } else if (mRequiredVerifierPackage != null) { 12279 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12280 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12281 } 12282 } 12283 12284 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12285 boolean printedHeader = false; 12286 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12287 while (it.hasNext()) { 12288 String name = it.next(); 12289 SharedLibraryEntry ent = mSharedLibraries.get(name); 12290 if (!checkin) { 12291 if (!printedHeader) { 12292 if (dumpState.onTitlePrinted()) 12293 pw.println(); 12294 pw.println("Libraries:"); 12295 printedHeader = true; 12296 } 12297 pw.print(" "); 12298 } else { 12299 pw.print("lib,"); 12300 } 12301 pw.print(name); 12302 if (!checkin) { 12303 pw.print(" -> "); 12304 } 12305 if (ent.path != null) { 12306 if (!checkin) { 12307 pw.print("(jar) "); 12308 pw.print(ent.path); 12309 } else { 12310 pw.print(",jar,"); 12311 pw.print(ent.path); 12312 } 12313 } else { 12314 if (!checkin) { 12315 pw.print("(apk) "); 12316 pw.print(ent.apk); 12317 } else { 12318 pw.print(",apk,"); 12319 pw.print(ent.apk); 12320 } 12321 } 12322 pw.println(); 12323 } 12324 } 12325 12326 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12327 if (dumpState.onTitlePrinted()) 12328 pw.println(); 12329 if (!checkin) { 12330 pw.println("Features:"); 12331 } 12332 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12333 while (it.hasNext()) { 12334 String name = it.next(); 12335 if (!checkin) { 12336 pw.print(" "); 12337 } else { 12338 pw.print("feat,"); 12339 } 12340 pw.println(name); 12341 } 12342 } 12343 12344 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12345 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12346 : "Activity Resolver Table:", " ", packageName, 12347 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12348 dumpState.setTitlePrinted(true); 12349 } 12350 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12351 : "Receiver Resolver Table:", " ", packageName, 12352 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12353 dumpState.setTitlePrinted(true); 12354 } 12355 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12356 : "Service Resolver Table:", " ", packageName, 12357 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12358 dumpState.setTitlePrinted(true); 12359 } 12360 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12361 : "Provider Resolver Table:", " ", packageName, 12362 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12363 dumpState.setTitlePrinted(true); 12364 } 12365 } 12366 12367 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12368 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12369 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12370 int user = mSettings.mPreferredActivities.keyAt(i); 12371 if (pir.dump(pw, 12372 dumpState.getTitlePrinted() 12373 ? "\nPreferred Activities User " + user + ":" 12374 : "Preferred Activities User " + user + ":", " ", 12375 packageName, true)) { 12376 dumpState.setTitlePrinted(true); 12377 } 12378 } 12379 } 12380 12381 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12382 pw.flush(); 12383 FileOutputStream fout = new FileOutputStream(fd); 12384 BufferedOutputStream str = new BufferedOutputStream(fout); 12385 XmlSerializer serializer = new FastXmlSerializer(); 12386 try { 12387 serializer.setOutput(str, "utf-8"); 12388 serializer.startDocument(null, true); 12389 serializer.setFeature( 12390 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12391 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12392 serializer.endDocument(); 12393 serializer.flush(); 12394 } catch (IllegalArgumentException e) { 12395 pw.println("Failed writing: " + e); 12396 } catch (IllegalStateException e) { 12397 pw.println("Failed writing: " + e); 12398 } catch (IOException e) { 12399 pw.println("Failed writing: " + e); 12400 } 12401 } 12402 12403 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12404 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12405 } 12406 12407 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12408 boolean printedSomething = false; 12409 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12410 if (packageName != null && !packageName.equals(p.info.packageName)) { 12411 continue; 12412 } 12413 if (!printedSomething) { 12414 if (dumpState.onTitlePrinted()) 12415 pw.println(); 12416 pw.println("Registered ContentProviders:"); 12417 printedSomething = true; 12418 } 12419 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12420 pw.print(" "); pw.println(p.toString()); 12421 } 12422 printedSomething = false; 12423 for (Map.Entry<String, PackageParser.Provider> entry : 12424 mProvidersByAuthority.entrySet()) { 12425 PackageParser.Provider p = entry.getValue(); 12426 if (packageName != null && !packageName.equals(p.info.packageName)) { 12427 continue; 12428 } 12429 if (!printedSomething) { 12430 if (dumpState.onTitlePrinted()) 12431 pw.println(); 12432 pw.println("ContentProvider Authorities:"); 12433 printedSomething = true; 12434 } 12435 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12436 pw.print(" "); pw.println(p.toString()); 12437 if (p.info != null && p.info.applicationInfo != null) { 12438 final String appInfo = p.info.applicationInfo.toString(); 12439 pw.print(" applicationInfo="); pw.println(appInfo); 12440 } 12441 } 12442 } 12443 12444 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12445 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12446 } 12447 12448 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12449 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12450 } 12451 12452 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12453 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12454 } 12455 12456 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12457 if (dumpState.onTitlePrinted()) pw.println(); 12458 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12459 } 12460 12461 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12462 if (dumpState.onTitlePrinted()) pw.println(); 12463 mSettings.dumpReadMessagesLPr(pw, dumpState); 12464 12465 pw.println(); 12466 pw.println("Package warning messages:"); 12467 final File fname = getSettingsProblemFile(); 12468 FileInputStream in = null; 12469 try { 12470 in = new FileInputStream(fname); 12471 final int avail = in.available(); 12472 final byte[] data = new byte[avail]; 12473 in.read(data); 12474 pw.print(new String(data)); 12475 } catch (FileNotFoundException e) { 12476 } catch (IOException e) { 12477 } finally { 12478 if (in != null) { 12479 try { 12480 in.close(); 12481 } catch (IOException e) { 12482 } 12483 } 12484 } 12485 } 12486 } 12487 } 12488 12489 // ------- apps on sdcard specific code ------- 12490 static final boolean DEBUG_SD_INSTALL = false; 12491 12492 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12493 12494 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12495 12496 private boolean mMediaMounted = false; 12497 12498 private String getEncryptKey() { 12499 try { 12500 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12501 SD_ENCRYPTION_KEYSTORE_NAME); 12502 if (sdEncKey == null) { 12503 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12504 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12505 if (sdEncKey == null) { 12506 Slog.e(TAG, "Failed to create encryption keys"); 12507 return null; 12508 } 12509 } 12510 return sdEncKey; 12511 } catch (NoSuchAlgorithmException nsae) { 12512 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12513 return null; 12514 } catch (IOException ioe) { 12515 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12516 return null; 12517 } 12518 12519 } 12520 12521 /* package */static String getTempContainerId() { 12522 int tmpIdx = 1; 12523 String list[] = PackageHelper.getSecureContainerList(); 12524 if (list != null) { 12525 for (final String name : list) { 12526 // Ignore null and non-temporary container entries 12527 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12528 continue; 12529 } 12530 12531 String subStr = name.substring(mTempContainerPrefix.length()); 12532 try { 12533 int cid = Integer.parseInt(subStr); 12534 if (cid >= tmpIdx) { 12535 tmpIdx = cid + 1; 12536 } 12537 } catch (NumberFormatException e) { 12538 } 12539 } 12540 } 12541 return mTempContainerPrefix + tmpIdx; 12542 } 12543 12544 /* 12545 * Update media status on PackageManager. 12546 */ 12547 @Override 12548 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12549 int callingUid = Binder.getCallingUid(); 12550 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12551 throw new SecurityException("Media status can only be updated by the system"); 12552 } 12553 // reader; this apparently protects mMediaMounted, but should probably 12554 // be a different lock in that case. 12555 synchronized (mPackages) { 12556 Log.i(TAG, "Updating external media status from " 12557 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12558 + (mediaStatus ? "mounted" : "unmounted")); 12559 if (DEBUG_SD_INSTALL) 12560 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12561 + ", mMediaMounted=" + mMediaMounted); 12562 if (mediaStatus == mMediaMounted) { 12563 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12564 : 0, -1); 12565 mHandler.sendMessage(msg); 12566 return; 12567 } 12568 mMediaMounted = mediaStatus; 12569 } 12570 // Queue up an async operation since the package installation may take a 12571 // little while. 12572 mHandler.post(new Runnable() { 12573 public void run() { 12574 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12575 } 12576 }); 12577 } 12578 12579 /** 12580 * Called by MountService when the initial ASECs to scan are available. 12581 * Should block until all the ASEC containers are finished being scanned. 12582 */ 12583 public void scanAvailableAsecs() { 12584 updateExternalMediaStatusInner(true, false, false); 12585 if (mShouldRestoreconData) { 12586 SELinuxMMAC.setRestoreconDone(); 12587 mShouldRestoreconData = false; 12588 } 12589 } 12590 12591 /* 12592 * Collect information of applications on external media, map them against 12593 * existing containers and update information based on current mount status. 12594 * Please note that we always have to report status if reportStatus has been 12595 * set to true especially when unloading packages. 12596 */ 12597 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12598 boolean externalStorage) { 12599 // Collection of uids 12600 int uidArr[] = null; 12601 // Collection of stale containers 12602 HashSet<String> removeCids = new HashSet<String>(); 12603 // Collection of packages on external media with valid containers. 12604 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12605 // Get list of secure containers. 12606 final String list[] = PackageHelper.getSecureContainerList(); 12607 if (list == null || list.length == 0) { 12608 Log.i(TAG, "No secure containers on sdcard"); 12609 } else { 12610 // Process list of secure containers and categorize them 12611 // as active or stale based on their package internal state. 12612 int uidList[] = new int[list.length]; 12613 int num = 0; 12614 // reader 12615 synchronized (mPackages) { 12616 for (String cid : list) { 12617 if (DEBUG_SD_INSTALL) 12618 Log.i(TAG, "Processing container " + cid); 12619 String pkgName = getAsecPackageName(cid); 12620 if (pkgName == null) { 12621 if (DEBUG_SD_INSTALL) 12622 Log.i(TAG, "Container : " + cid + " stale"); 12623 removeCids.add(cid); 12624 continue; 12625 } 12626 if (DEBUG_SD_INSTALL) 12627 Log.i(TAG, "Looking for pkg : " + pkgName); 12628 12629 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12630 if (ps == null) { 12631 Log.i(TAG, "Deleting container with no matching settings " + cid); 12632 removeCids.add(cid); 12633 continue; 12634 } 12635 12636 /* 12637 * Skip packages that are not external if we're unmounting 12638 * external storage. 12639 */ 12640 if (externalStorage && !isMounted && !isExternal(ps)) { 12641 continue; 12642 } 12643 12644 final AsecInstallArgs args = new AsecInstallArgs(cid, 12645 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12646 // The package status is changed only if the code path 12647 // matches between settings and the container id. 12648 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12649 if (DEBUG_SD_INSTALL) { 12650 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12651 + " at code path: " + ps.codePathString); 12652 } 12653 12654 // We do have a valid package installed on sdcard 12655 processCids.put(args, ps.codePathString); 12656 final int uid = ps.appId; 12657 if (uid != -1) { 12658 uidList[num++] = uid; 12659 } 12660 } else { 12661 Log.i(TAG, "Deleting stale container for " + cid); 12662 removeCids.add(cid); 12663 } 12664 } 12665 } 12666 12667 if (num > 0) { 12668 // Sort uid list 12669 Arrays.sort(uidList, 0, num); 12670 // Throw away duplicates 12671 uidArr = new int[num]; 12672 uidArr[0] = uidList[0]; 12673 int di = 0; 12674 for (int i = 1; i < num; i++) { 12675 if (uidList[i - 1] != uidList[i]) { 12676 uidArr[di++] = uidList[i]; 12677 } 12678 } 12679 } 12680 } 12681 // Process packages with valid entries. 12682 if (isMounted) { 12683 if (DEBUG_SD_INSTALL) 12684 Log.i(TAG, "Loading packages"); 12685 loadMediaPackages(processCids, uidArr, removeCids); 12686 startCleaningPackages(); 12687 } else { 12688 if (DEBUG_SD_INSTALL) 12689 Log.i(TAG, "Unloading packages"); 12690 unloadMediaPackages(processCids, uidArr, reportStatus); 12691 } 12692 } 12693 12694 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12695 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12696 int size = pkgList.size(); 12697 if (size > 0) { 12698 // Send broadcasts here 12699 Bundle extras = new Bundle(); 12700 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12701 .toArray(new String[size])); 12702 if (uidArr != null) { 12703 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12704 } 12705 if (replacing) { 12706 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12707 } 12708 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12709 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12710 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12711 } 12712 } 12713 12714 /* 12715 * Look at potentially valid container ids from processCids If package 12716 * information doesn't match the one on record or package scanning fails, 12717 * the cid is added to list of removeCids. We currently don't delete stale 12718 * containers. 12719 */ 12720 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12721 HashSet<String> removeCids) { 12722 ArrayList<String> pkgList = new ArrayList<String>(); 12723 Set<AsecInstallArgs> keys = processCids.keySet(); 12724 boolean doGc = false; 12725 for (AsecInstallArgs args : keys) { 12726 String codePath = processCids.get(args); 12727 if (DEBUG_SD_INSTALL) 12728 Log.i(TAG, "Loading container : " + args.cid); 12729 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12730 try { 12731 // Make sure there are no container errors first. 12732 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12733 Slog.e(TAG, "Failed to mount cid : " + args.cid 12734 + " when installing from sdcard"); 12735 continue; 12736 } 12737 // Check code path here. 12738 if (codePath == null || !codePath.equals(args.getCodePath())) { 12739 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12740 + " does not match one in settings " + codePath); 12741 continue; 12742 } 12743 // Parse package 12744 int parseFlags = mDefParseFlags; 12745 if (args.isExternal()) { 12746 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12747 } 12748 if (args.isFwdLocked()) { 12749 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12750 } 12751 12752 doGc = true; 12753 synchronized (mInstallLock) { 12754 PackageParser.Package pkg = null; 12755 try { 12756 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12757 } catch (PackageManagerException e) { 12758 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12759 } 12760 // Scan the package 12761 if (pkg != null) { 12762 /* 12763 * TODO why is the lock being held? doPostInstall is 12764 * called in other places without the lock. This needs 12765 * to be straightened out. 12766 */ 12767 // writer 12768 synchronized (mPackages) { 12769 retCode = PackageManager.INSTALL_SUCCEEDED; 12770 pkgList.add(pkg.packageName); 12771 // Post process args 12772 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12773 pkg.applicationInfo.uid); 12774 } 12775 } else { 12776 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12777 } 12778 } 12779 12780 } finally { 12781 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12782 // Don't destroy container here. Wait till gc clears things 12783 // up. 12784 removeCids.add(args.cid); 12785 } 12786 } 12787 } 12788 // writer 12789 synchronized (mPackages) { 12790 // If the platform SDK has changed since the last time we booted, 12791 // we need to re-grant app permission to catch any new ones that 12792 // appear. This is really a hack, and means that apps can in some 12793 // cases get permissions that the user didn't initially explicitly 12794 // allow... it would be nice to have some better way to handle 12795 // this situation. 12796 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12797 if (regrantPermissions) 12798 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12799 + mSdkVersion + "; regranting permissions for external storage"); 12800 mSettings.mExternalSdkPlatform = mSdkVersion; 12801 12802 // Make sure group IDs have been assigned, and any permission 12803 // changes in other apps are accounted for 12804 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12805 | (regrantPermissions 12806 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12807 : 0)); 12808 12809 mSettings.updateExternalDatabaseVersion(); 12810 12811 // can downgrade to reader 12812 // Persist settings 12813 mSettings.writeLPr(); 12814 } 12815 // Send a broadcast to let everyone know we are done processing 12816 if (pkgList.size() > 0) { 12817 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12818 } 12819 // Force gc to avoid any stale parser references that we might have. 12820 if (doGc) { 12821 Runtime.getRuntime().gc(); 12822 } 12823 // List stale containers and destroy stale temporary containers. 12824 if (removeCids != null) { 12825 for (String cid : removeCids) { 12826 if (cid.startsWith(mTempContainerPrefix)) { 12827 Log.i(TAG, "Destroying stale temporary container " + cid); 12828 PackageHelper.destroySdDir(cid); 12829 } else { 12830 Log.w(TAG, "Container " + cid + " is stale"); 12831 } 12832 } 12833 } 12834 } 12835 12836 /* 12837 * Utility method to unload a list of specified containers 12838 */ 12839 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12840 // Just unmount all valid containers. 12841 for (AsecInstallArgs arg : cidArgs) { 12842 synchronized (mInstallLock) { 12843 arg.doPostDeleteLI(false); 12844 } 12845 } 12846 } 12847 12848 /* 12849 * Unload packages mounted on external media. This involves deleting package 12850 * data from internal structures, sending broadcasts about diabled packages, 12851 * gc'ing to free up references, unmounting all secure containers 12852 * corresponding to packages on external media, and posting a 12853 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12854 * that we always have to post this message if status has been requested no 12855 * matter what. 12856 */ 12857 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12858 final boolean reportStatus) { 12859 if (DEBUG_SD_INSTALL) 12860 Log.i(TAG, "unloading media packages"); 12861 ArrayList<String> pkgList = new ArrayList<String>(); 12862 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12863 final Set<AsecInstallArgs> keys = processCids.keySet(); 12864 for (AsecInstallArgs args : keys) { 12865 String pkgName = args.getPackageName(); 12866 if (DEBUG_SD_INSTALL) 12867 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12868 // Delete package internally 12869 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12870 synchronized (mInstallLock) { 12871 boolean res = deletePackageLI(pkgName, null, false, null, null, 12872 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12873 if (res) { 12874 pkgList.add(pkgName); 12875 } else { 12876 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12877 failedList.add(args); 12878 } 12879 } 12880 } 12881 12882 // reader 12883 synchronized (mPackages) { 12884 // We didn't update the settings after removing each package; 12885 // write them now for all packages. 12886 mSettings.writeLPr(); 12887 } 12888 12889 // We have to absolutely send UPDATED_MEDIA_STATUS only 12890 // after confirming that all the receivers processed the ordered 12891 // broadcast when packages get disabled, force a gc to clean things up. 12892 // and unload all the containers. 12893 if (pkgList.size() > 0) { 12894 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12895 new IIntentReceiver.Stub() { 12896 public void performReceive(Intent intent, int resultCode, String data, 12897 Bundle extras, boolean ordered, boolean sticky, 12898 int sendingUser) throws RemoteException { 12899 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12900 reportStatus ? 1 : 0, 1, keys); 12901 mHandler.sendMessage(msg); 12902 } 12903 }); 12904 } else { 12905 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12906 keys); 12907 mHandler.sendMessage(msg); 12908 } 12909 } 12910 12911 /** Binder call */ 12912 @Override 12913 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12914 final int flags) { 12915 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12916 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12917 int returnCode = PackageManager.MOVE_SUCCEEDED; 12918 int currFlags = 0; 12919 int newFlags = 0; 12920 // reader 12921 synchronized (mPackages) { 12922 PackageParser.Package pkg = mPackages.get(packageName); 12923 if (pkg == null) { 12924 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12925 } else { 12926 // Disable moving fwd locked apps and system packages 12927 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12928 Slog.w(TAG, "Cannot move system application"); 12929 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12930 } else if (pkg.mOperationPending) { 12931 Slog.w(TAG, "Attempt to move package which has pending operations"); 12932 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12933 } else { 12934 // Find install location first 12935 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12936 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12937 Slog.w(TAG, "Ambigous flags specified for move location."); 12938 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12939 } else { 12940 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12941 : PackageManager.INSTALL_INTERNAL; 12942 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12943 : PackageManager.INSTALL_INTERNAL; 12944 12945 if (newFlags == currFlags) { 12946 Slog.w(TAG, "No move required. Trying to move to same location"); 12947 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12948 } else { 12949 if (isForwardLocked(pkg)) { 12950 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12951 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12952 } 12953 } 12954 } 12955 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12956 pkg.mOperationPending = true; 12957 } 12958 } 12959 } 12960 12961 /* 12962 * TODO this next block probably shouldn't be inside the lock. We 12963 * can't guarantee these won't change after this is fired off 12964 * anyway. 12965 */ 12966 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12967 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12968 returnCode); 12969 } else { 12970 Message msg = mHandler.obtainMessage(INIT_COPY); 12971 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12972 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12973 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12974 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12975 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12976 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12977 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12978 msg.obj = mp; 12979 mHandler.sendMessage(msg); 12980 } 12981 } 12982 } 12983 12984 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12985 // Queue up an async operation since the package deletion may take a 12986 // little while. 12987 mHandler.post(new Runnable() { 12988 public void run() { 12989 // TODO fix this; this does nothing. 12990 mHandler.removeCallbacks(this); 12991 int returnCode = currentStatus; 12992 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12993 int uidArr[] = null; 12994 ArrayList<String> pkgList = null; 12995 synchronized (mPackages) { 12996 PackageParser.Package pkg = mPackages.get(mp.packageName); 12997 if (pkg == null) { 12998 Slog.w(TAG, " Package " + mp.packageName 12999 + " doesn't exist. Aborting move"); 13000 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13001 } else if (!mp.srcArgs.getCodePath().equals( 13002 pkg.applicationInfo.getCodePath())) { 13003 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13004 + mp.srcArgs.getCodePath() + " to " 13005 + pkg.applicationInfo.getCodePath() 13006 + " Aborting move and returning error"); 13007 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13008 } else { 13009 uidArr = new int[] { 13010 pkg.applicationInfo.uid 13011 }; 13012 pkgList = new ArrayList<String>(); 13013 pkgList.add(mp.packageName); 13014 } 13015 } 13016 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13017 // Send resources unavailable broadcast 13018 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13019 // Update package code and resource paths 13020 synchronized (mInstallLock) { 13021 synchronized (mPackages) { 13022 PackageParser.Package pkg = mPackages.get(mp.packageName); 13023 // Recheck for package again. 13024 if (pkg == null) { 13025 Slog.w(TAG, " Package " + mp.packageName 13026 + " doesn't exist. Aborting move"); 13027 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13028 } else if (!mp.srcArgs.getCodePath().equals( 13029 pkg.applicationInfo.getCodePath())) { 13030 Slog.w(TAG, "Package " + mp.packageName 13031 + " code path changed from " + mp.srcArgs.getCodePath() 13032 + " to " + pkg.applicationInfo.getCodePath() 13033 + " Aborting move and returning error"); 13034 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13035 } else { 13036 final String oldCodePath = pkg.codePath; 13037 final String newCodePath = mp.targetArgs.getCodePath(); 13038 final String newResPath = mp.targetArgs.getResourcePath(); 13039 // TODO: This assumes the new style of installation. 13040 // should we look at legacyNativeLibraryPath ? 13041 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13042 final File newNativeDir = new File(newNativeRoot); 13043 13044 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13045 // TODO(multiArch): Fix this so that it looks at the existing 13046 // recorded CPU abis from the package. There's no need for a separate 13047 // round of ABI scanning here. 13048 NativeLibraryHelper.Handle handle = null; 13049 try { 13050 handle = NativeLibraryHelper.Handle.create( 13051 new File(newCodePath)); 13052 final int abi = NativeLibraryHelper.findSupportedAbi( 13053 handle, Build.SUPPORTED_ABIS); 13054 if (abi >= 0) { 13055 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13056 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13057 } 13058 } catch (IOException ioe) { 13059 Slog.w(TAG, "Unable to extract native libs for package :" 13060 + mp.packageName, ioe); 13061 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13062 } finally { 13063 IoUtils.closeQuietly(handle); 13064 } 13065 } 13066 13067 final int[] users = sUserManager.getUserIds(); 13068 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13069 for (int user : users) { 13070 // TODO(multiArch): Fix this so that it links to the 13071 // correct directory. We're currently pointing to root. but we 13072 // must point to the arch specific subdirectory (if applicable). 13073 // 13074 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13075 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13076 newNativeRoot, user) < 0) { 13077 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13078 } 13079 } 13080 } 13081 13082 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13083 pkg.codePath = newCodePath; 13084 pkg.baseCodePath = newCodePath; 13085 // Move dex files around 13086 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13087 // Moving of dex files failed. Set 13088 // error code and abort move. 13089 pkg.codePath = oldCodePath; 13090 pkg.baseCodePath = oldCodePath; 13091 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13092 } 13093 } 13094 13095 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13096 pkg.applicationInfo.setCodePath(newCodePath); 13097 pkg.applicationInfo.setBaseCodePath(newCodePath); 13098 pkg.applicationInfo.setSplitCodePaths(null); 13099 pkg.applicationInfo.setResourcePath(newResPath); 13100 pkg.applicationInfo.setBaseResourcePath(newResPath); 13101 pkg.applicationInfo.setSplitResourcePaths(null); 13102 13103 PackageSetting ps = (PackageSetting) pkg.mExtras; 13104 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13105 ps.codePathString = ps.codePath.getPath(); 13106 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13107 ps.resourcePathString = ps.resourcePath.getPath(); 13108 13109 // Note that we don't have to recalculate the primary and secondary 13110 // CPU ABIs because they must already have been calculated during the 13111 // initial install of the app. 13112 ps.legacyNativeLibraryPathString = null; 13113 13114 // Set the application info flag 13115 // correctly. 13116 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13117 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13118 } else { 13119 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13120 } 13121 ps.setFlags(pkg.applicationInfo.flags); 13122 mAppDirs.remove(oldCodePath); 13123 mAppDirs.put(newCodePath, pkg); 13124 // Persist settings 13125 mSettings.writeLPr(); 13126 } 13127 } 13128 } 13129 } 13130 // Send resources available broadcast 13131 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13132 } 13133 } 13134 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13135 // Clean up failed installation 13136 if (mp.targetArgs != null) { 13137 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13138 -1); 13139 } 13140 } else { 13141 // Force a gc to clear things up. 13142 Runtime.getRuntime().gc(); 13143 // Delete older code 13144 synchronized (mInstallLock) { 13145 mp.srcArgs.doPostDeleteLI(true); 13146 } 13147 } 13148 13149 // Allow more operations on this file if we didn't fail because 13150 // an operation was already pending for this package. 13151 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13152 synchronized (mPackages) { 13153 PackageParser.Package pkg = mPackages.get(mp.packageName); 13154 if (pkg != null) { 13155 pkg.mOperationPending = false; 13156 } 13157 } 13158 } 13159 13160 IPackageMoveObserver observer = mp.observer; 13161 if (observer != null) { 13162 try { 13163 observer.packageMoved(mp.packageName, returnCode); 13164 } catch (RemoteException e) { 13165 Log.i(TAG, "Observer no longer exists."); 13166 } 13167 } 13168 } 13169 }); 13170 } 13171 13172 @Override 13173 public boolean setInstallLocation(int loc) { 13174 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13175 null); 13176 if (getInstallLocation() == loc) { 13177 return true; 13178 } 13179 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13180 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13181 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13182 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13183 return true; 13184 } 13185 return false; 13186 } 13187 13188 @Override 13189 public int getInstallLocation() { 13190 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13191 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13192 PackageHelper.APP_INSTALL_AUTO); 13193 } 13194 13195 /** Called by UserManagerService */ 13196 void cleanUpUserLILPw(int userHandle) { 13197 mDirtyUsers.remove(userHandle); 13198 mSettings.removeUserLPw(userHandle); 13199 mPendingBroadcasts.remove(userHandle); 13200 if (mInstaller != null) { 13201 // Technically, we shouldn't be doing this with the package lock 13202 // held. However, this is very rare, and there is already so much 13203 // other disk I/O going on, that we'll let it slide for now. 13204 mInstaller.removeUserDataDirs(userHandle); 13205 } 13206 mUserNeedsBadging.delete(userHandle); 13207 } 13208 13209 /** Called by UserManagerService */ 13210 void createNewUserLILPw(int userHandle, File path) { 13211 if (mInstaller != null) { 13212 mInstaller.createUserConfig(userHandle); 13213 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13214 } 13215 } 13216 13217 @Override 13218 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13219 mContext.enforceCallingOrSelfPermission( 13220 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13221 "Only package verification agents can read the verifier device identity"); 13222 13223 synchronized (mPackages) { 13224 return mSettings.getVerifierDeviceIdentityLPw(); 13225 } 13226 } 13227 13228 @Override 13229 public void setPermissionEnforced(String permission, boolean enforced) { 13230 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13231 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13232 synchronized (mPackages) { 13233 if (mSettings.mReadExternalStorageEnforced == null 13234 || mSettings.mReadExternalStorageEnforced != enforced) { 13235 mSettings.mReadExternalStorageEnforced = enforced; 13236 mSettings.writeLPr(); 13237 } 13238 } 13239 // kill any non-foreground processes so we restart them and 13240 // grant/revoke the GID. 13241 final IActivityManager am = ActivityManagerNative.getDefault(); 13242 if (am != null) { 13243 final long token = Binder.clearCallingIdentity(); 13244 try { 13245 am.killProcessesBelowForeground("setPermissionEnforcement"); 13246 } catch (RemoteException e) { 13247 } finally { 13248 Binder.restoreCallingIdentity(token); 13249 } 13250 } 13251 } else { 13252 throw new IllegalArgumentException("No selective enforcement for " + permission); 13253 } 13254 } 13255 13256 @Override 13257 @Deprecated 13258 public boolean isPermissionEnforced(String permission) { 13259 return true; 13260 } 13261 13262 @Override 13263 public boolean isStorageLow() { 13264 final long token = Binder.clearCallingIdentity(); 13265 try { 13266 final DeviceStorageMonitorInternal 13267 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13268 if (dsm != null) { 13269 return dsm.isMemoryLow(); 13270 } else { 13271 return false; 13272 } 13273 } finally { 13274 Binder.restoreCallingIdentity(token); 13275 } 13276 } 13277 13278 @Override 13279 public IPackageInstaller getPackageInstaller() { 13280 return mInstallerService; 13281 } 13282 13283 private boolean userNeedsBadging(int userId) { 13284 int index = mUserNeedsBadging.indexOfKey(userId); 13285 if (index < 0) { 13286 final UserInfo userInfo; 13287 final long token = Binder.clearCallingIdentity(); 13288 try { 13289 userInfo = sUserManager.getUserInfo(userId); 13290 } finally { 13291 Binder.restoreCallingIdentity(token); 13292 } 13293 final boolean b; 13294 if (userInfo != null && userInfo.isManagedProfile()) { 13295 b = true; 13296 } else { 13297 b = false; 13298 } 13299 mUserNeedsBadging.put(userId, b); 13300 return b; 13301 } 13302 return mUserNeedsBadging.valueAt(index); 13303 } 13304 13305 @Override 13306 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13307 if (packageName == null || alias == null) { 13308 return null; 13309 } 13310 synchronized(mPackages) { 13311 final PackageParser.Package pkg = mPackages.get(packageName); 13312 if (pkg == null) { 13313 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13314 throw new IllegalArgumentException("Unknown package: " + packageName); 13315 } 13316 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13317 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13318 throw new SecurityException("May not access KeySets defined by" 13319 + " aliases in other applications."); 13320 } 13321 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13322 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13323 } 13324 } 13325 13326 @Override 13327 public KeySetHandle getSigningKeySet(String packageName) { 13328 if (packageName == null) { 13329 return null; 13330 } 13331 synchronized(mPackages) { 13332 final PackageParser.Package pkg = mPackages.get(packageName); 13333 if (pkg == null) { 13334 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13335 throw new IllegalArgumentException("Unknown package: " + packageName); 13336 } 13337 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13338 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13339 throw new SecurityException("May not access signing KeySet of other apps."); 13340 } 13341 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13342 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13343 } 13344 } 13345 13346 @Override 13347 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13348 if (packageName == null || ks == null) { 13349 return false; 13350 } 13351 synchronized(mPackages) { 13352 final PackageParser.Package pkg = mPackages.get(packageName); 13353 if (pkg == null) { 13354 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13355 throw new IllegalArgumentException("Unknown package: " + packageName); 13356 } 13357 if (ks instanceof KeySetHandle) { 13358 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13359 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13360 } 13361 return false; 13362 } 13363 } 13364 13365 @Override 13366 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13367 if (packageName == null || ks == null) { 13368 return false; 13369 } 13370 synchronized(mPackages) { 13371 final PackageParser.Package pkg = mPackages.get(packageName); 13372 if (pkg == null) { 13373 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13374 throw new IllegalArgumentException("Unknown package: " + packageName); 13375 } 13376 if (ks instanceof KeySetHandle) { 13377 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13378 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13379 } 13380 return false; 13381 } 13382 } 13383} 13384